1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2012 The Bitcoin developers
3 // Distributed under the MIT/X11 software license, see the accompanying
4 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
15 #include <arpa/inet.h>
24 extern int nBestHeight;
26 const uint16_t nSocksDefault = 9050;
27 const uint16_t nPortZero = 0;
30 inline uint64_t ReceiveBufferSize() { return 1000*GetArg("-maxreceivebuffer", 5*1000); }
31 inline uint64_t SendBufferSize() { return 1000*GetArg("-maxsendbuffer", 1*1000); }
33 void AddOneShot(std::string strDest);
34 bool RecvLine(SOCKET hSocket, std::string& strLine);
35 bool GetMyExternalIP(CNetAddr& ipRet);
36 void AddressCurrentlyConnected(const CService& addr);
37 CNode* FindNode(const CNetAddr& ip);
38 CNode* FindNode(const CService& ip);
39 CNode* ConnectNode(CAddress addrConnect, const char *strDest = NULL, int64_t nTimeout=0);
40 bool OpenNetworkConnection(const CAddress& addrConnect, CSemaphoreGrant *grantOutbound = NULL, const char *strDest = NULL, bool fOneShot = false);
42 unsigned short GetListenPort();
43 bool BindListenPort(const CService &bindAddr, std::string& strError=REF(std::string()));
44 void StartNode(void* parg);
49 LOCAL_NONE, // unknown
50 LOCAL_IF, // address a local interface listens on
51 LOCAL_BIND, // address explicit bound to
52 LOCAL_IRC, // address reported by IRC (deprecated)
53 LOCAL_HTTP, // address reported by whatismyip.com and similar
54 LOCAL_MANUAL, // address explicitly specified (-externalip=)
60 bool IsPeerAddrLocalGood(CNode *pnode);
61 void AdvertiseLocal(CNode *pnode);
62 void SetLimited(enum Network net, bool fLimited = true);
63 bool IsLimited(enum Network net);
64 bool IsLimited(const CNetAddr& addr);
65 bool AddLocal(const CService& addr, int nScore = LOCAL_NONE);
66 bool AddLocal(const CNetAddr& addr, int nScore = LOCAL_NONE);
67 bool SeenLocal(const CService& addr);
68 bool IsLocal(const CService& addr);
69 bool GetLocal(CService &addr, const CNetAddr *paddrPeer = NULL);
70 bool IsReachable(const CNetAddr &addr);
71 void SetReachable(enum Network net, bool fFlag = true);
72 CAddress GetLocalAddress(const CNetAddr *paddrPeer = NULL);
86 THREAD_OPENCONNECTIONS,
87 THREAD_MESSAGEHANDLER,
90 THREAD_ADDEDCONNECTIONS,
102 extern bool fDiscover;
103 extern bool fNoListen;
105 extern bool fDiscover;
106 extern uint64_t nLocalServices;
107 extern uint64_t nLocalHostNonce;
108 extern CAddress addrSeenByPeer;
109 extern std::array<int, THREAD_MAX> vnThreadsRunning;
110 extern CAddrMan addrman;
112 extern std::vector<CNode*> vNodes;
113 extern CCriticalSection cs_vNodes;
114 extern std::vector<std::string> vAddedNodes;
115 extern CCriticalSection cs_vAddedNodes;
116 extern std::map<CInv, CDataStream> mapRelay;
117 extern std::deque<std::pair<int64_t, CInv> > vRelayExpiration;
118 extern CCriticalSection cs_mapRelay;
119 extern std::map<CInv, int64_t> mapAlreadyAskedFor;
130 int64_t nTimeConnected;
131 std::string addrName;
133 std::string strSubVer;
135 int64_t nReleaseTime;
136 int32_t nStartingHeight;
137 int32_t nMisbehavior;
147 /** Information about a peer */
158 CCriticalSection cs_vSend;
159 CCriticalSection cs_vRecv;
162 int64_t nLastSendEmpty;
163 int64_t nTimeConnected;
164 int32_t nHeaderStart;
165 uint32_t nMessageStart;
167 std::string addrName;
170 std::string strSubVer;
175 bool fSuccessfullyConnected;
177 CSemaphoreGrant grantOutbound;
181 // Denial-of-service detection/prevention
182 // Key is IP address, value is banned-until-time
183 static std::map<CNetAddr, int64_t> setBanned;
184 static CCriticalSection cs_setBanned;
188 int64_t nReleaseTime;
189 uint256 hashContinue;
190 CBlockIndex* pindexLastGetBlocksBegin;
191 uint256 hashLastGetBlocksEnd;
192 int32_t nStartingHeight;
196 std::vector<CAddress> vAddrToSend;
197 std::set<CAddress> setAddrKnown;
199 std::set<uint256> setKnown;
200 uint256 hashCheckpointKnown; // ppcoin: known sent sync-checkpoint
201 int64_t nNextAddrSend;
202 int64_t nNextLocalAddrSend;
203 int64_t nNextInvSend;
205 // inventory based relay
206 mruset<CInv> setInventoryKnown;
207 std::vector<CInv> vInventoryToSend;
208 CCriticalSection cs_inventory;
209 std::multimap<int64_t, CInv> mapAskFor;
211 CNode(SOCKET hSocketIn, CAddress addrIn, std::string addrNameIn = "", bool fInboundIn=false) : vSend(SER_NETWORK, MIN_PROTO_VERSION), vRecv(SER_NETWORK, MIN_PROTO_VERSION)
219 nLastSendEmpty = GetTime();
220 nTimeConnected = GetTime();
222 nMessageStart = std::numeric_limits<uint32_t>::max();
224 addrName = addrNameIn.empty() ? addr.ToStringIPPort() : addrNameIn;
228 fClient = false; // set by version message
229 fInbound = fInboundIn;
230 fNetworkNode = false;
231 fSuccessfullyConnected = false;
236 pindexLastGetBlocksBegin = 0;
237 hashLastGetBlocksEnd = 0;
238 nStartingHeight = -1;
239 nNextLocalAddrSend = 0;
245 hashCheckpointKnown = 0;
246 setInventoryKnown.max_size((size_t)SendBufferSize() / 1000);
248 // Be shy and don't send version until we hear
249 if (hSocket != INVALID_SOCKET && !fInbound)
255 if (hSocket != INVALID_SOCKET)
257 CloseSocket(hSocket);
263 // Network usage totals
264 static CCriticalSection cs_totalBytesRecv;
265 static CCriticalSection cs_totalBytesSent;
266 static uint64_t nTotalBytesRecv;
267 static uint64_t nTotalBytesSent;
269 void operator=(const CNode&);
275 return std::max(nRefCount, 0) + (GetTime() < nReleaseTime ? 1 : 0);
278 CNode* AddRef(int64_t nTimeout=0)
281 nReleaseTime = std::max(nReleaseTime, GetTime() + nTimeout);
294 void AddAddressKnown(const CAddress& addr)
296 setAddrKnown.insert(addr);
299 void PushAddress(const CAddress& addr)
301 // Known checking here is only to save space from duplicates.
302 // SendMessages will filter it again for knowns that were added
303 // after addresses were pushed.
304 if (addr.IsValid() && !setAddrKnown.count(addr))
305 vAddrToSend.push_back(addr);
309 void AddInventoryKnown(const CInv& inv)
313 setInventoryKnown.insert(inv);
317 void PushInventory(const CInv& inv)
321 if (!setInventoryKnown.count(inv))
322 vInventoryToSend.push_back(inv);
326 void AskFor(const CInv& inv)
328 // We're using mapAskFor as a priority queue,
329 // the key is the earliest time the request can be sent
330 int64_t& nRequestTime = mapAlreadyAskedFor[inv];
332 printf("askfor %s %" PRId64 " (%s)\n", inv.ToString().c_str(), nRequestTime, DateTimeStrFormat("%H:%M:%S", nRequestTime/1000000).c_str());
334 // Make sure not to reuse time indexes to keep things in the same order
335 int64_t nNow = (GetTime() - 1) * 1000000;
336 static int64_t nLastTime;
338 nNow = std::max(nNow, nLastTime);
341 // Each retry is 2 minutes after the last
342 nRequestTime = std::max(nRequestTime + 2 * 60 * 1000000, nNow);
343 mapAskFor.insert(std::make_pair(nRequestTime, inv));
346 void BeginMessage(const char* pszCommand)
348 ENTER_CRITICAL_SECTION(cs_vSend);
349 if (nHeaderStart != -1)
351 nHeaderStart = (int32_t)vSend.size();
352 vSend << CMessageHeader(pszCommand, 0);
353 nMessageStart = (uint32_t)vSend.size();
355 printf("sending: %s ", pszCommand);
360 if (nHeaderStart < 0)
362 vSend.resize(nHeaderStart);
364 nMessageStart = std::numeric_limits<uint32_t>::max();
365 LEAVE_CRITICAL_SECTION(cs_vSend);
368 printf("(aborted)\n");
373 void EndMessageAbortIfEmpty()
375 if (nHeaderStart < 0)
377 int nSize = (int) vSend.size() - nMessageStart;
386 template<typename ...Args>
387 void PushMessage(const char* pszCommand, const Args&... args)
391 BeginMessage(pszCommand);
392 if constexpr (sizeof...(Args) > 0)
393 (vSend << ... << args);
403 void PushGetBlocks(CBlockIndex* pindexBegin, uint256 hashEnd);
404 bool IsSubscribed(unsigned int nChannel);
405 void Subscribe(unsigned int nChannel, unsigned int nHops=0);
406 void CancelSubscribe(unsigned int nChannel);
407 void CloseSocketDisconnect();
411 // Denial-of-service detection/prevention
412 // The idea is to detect peers that are behaving
413 // badly and disconnect/ban them, but do it in a
414 // one-coding-mistake-won't-shatter-the-entire-network
416 // IMPORTANT: There should be nothing I can give a
417 // node that it will forward on that will make that
418 // node's peers drop it. If there is, an attacker
419 // can isolate a node and/or try to split the network.
420 // Dropping a node for sending stuff that is invalid
421 // now but might be valid in a later version is also
422 // dangerous, because it can cause a network split
423 // between nodes running old code and nodes running
425 static void ClearBanned(); // needed for unit testing
426 static bool IsBanned(CNetAddr ip);
427 bool Misbehaving(int howmuch); // 1 == a little, 100 == a lot
428 void copyStats(CNodeStats &stats);
430 static void RecordBytesRecv(uint64_t bytes);
431 static void RecordBytesSent(uint64_t bytes);
433 static uint64_t GetTotalBytesRecv();
434 static uint64_t GetTotalBytesSent();
438 void RelayTransaction(const CTransaction& tx, const uint256& hash);
439 void RelayTransaction(const CTransaction& tx, const uint256& hash, const CDataStream& ss);
442 /** Return a timestamp in the future (in microseconds) for exponentially distributed events. */
443 int64_t PoissonNextSend(int64_t nNow, int average_interval_seconds);