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.
14 #include <openssl/rand.h>
17 #include <arpa/inet.h>
24 class CRequestTracker;
27 extern int nBestHeight;
29 const uint16_t nSocksDefault = 9050;
30 const uint16_t nPortZero = 0;
33 inline uint64_t ReceiveBufferSize() { return 1000*GetArg("-maxreceivebuffer", 5*1000); }
34 inline uint64_t SendBufferSize() { return 1000*GetArg("-maxsendbuffer", 1*1000); }
36 void AddOneShot(std::string strDest);
37 bool RecvLine(SOCKET hSocket, std::string& strLine);
38 bool GetMyExternalIP(CNetAddr& ipRet);
39 void AddressCurrentlyConnected(const CService& addr);
40 CNode* FindNode(const CNetAddr& ip);
41 CNode* FindNode(const CService& ip);
42 CNode* ConnectNode(CAddress addrConnect, const char *strDest = NULL, int64_t nTimeout=0);
43 bool OpenNetworkConnection(const CAddress& addrConnect, CSemaphoreGrant *grantOutbound = NULL, const char *strDest = NULL, bool fOneShot = false);
45 unsigned short GetListenPort();
46 bool BindListenPort(const CService &bindAddr, std::string& strError=REF(std::string()));
47 void StartNode(void* parg);
52 LOCAL_NONE, // unknown
53 LOCAL_IF, // address a local interface listens on
54 LOCAL_BIND, // address explicit bound to
55 LOCAL_IRC, // address reported by IRC (deprecated)
56 LOCAL_HTTP, // address reported by whatismyip.com and similar
57 LOCAL_MANUAL, // address explicitly specified (-externalip=)
63 bool IsPeerAddrLocalGood(CNode *pnode);
64 void AdvertiseLocal(CNode *pnode);
65 void SetLimited(enum Network net, bool fLimited = true);
66 bool IsLimited(enum Network net);
67 bool IsLimited(const CNetAddr& addr);
68 bool AddLocal(const CService& addr, int nScore = LOCAL_NONE);
69 bool AddLocal(const CNetAddr& addr, int nScore = LOCAL_NONE);
70 bool SeenLocal(const CService& addr);
71 bool IsLocal(const CService& addr);
72 bool GetLocal(CService &addr, const CNetAddr *paddrPeer = NULL);
73 bool IsReachable(const CNetAddr &addr);
74 void SetReachable(enum Network net, bool fFlag = true);
75 CAddress GetLocalAddress(const CNetAddr *paddrPeer = NULL);
87 void (*fn)(void*, CDataStream&);
90 explicit CRequestTracker(void (*fnIn)(void*, CDataStream&)=NULL, void* param1In=NULL)
106 THREAD_SOCKETHANDLER,
107 THREAD_OPENCONNECTIONS,
108 THREAD_MESSAGEHANDLER,
111 THREAD_ADDEDCONNECTIONS,
123 extern bool fDiscover;
124 extern bool fNoListen;
126 extern bool fDiscover;
127 extern uint64_t nLocalServices;
128 extern uint64_t nLocalHostNonce;
129 extern CAddress addrSeenByPeer;
130 extern std::array<int, THREAD_MAX> vnThreadsRunning;
131 extern CAddrMan addrman;
133 extern std::vector<CNode*> vNodes;
134 extern CCriticalSection cs_vNodes;
135 extern std::vector<std::string> vAddedNodes;
136 extern CCriticalSection cs_vAddedNodes;
137 extern std::map<CInv, CDataStream> mapRelay;
138 extern std::deque<std::pair<int64_t, CInv> > vRelayExpiration;
139 extern CCriticalSection cs_mapRelay;
140 extern std::map<CInv, int64_t> mapAlreadyAskedFor;
151 int64_t nTimeConnected;
152 std::string addrName;
154 std::string strSubVer;
156 int64_t nReleaseTime;
157 int32_t nStartingHeight;
158 int32_t nMisbehavior;
168 /** Information about a peer */
179 CCriticalSection cs_vSend;
180 CCriticalSection cs_vRecv;
183 int64_t nLastSendEmpty;
184 int64_t nTimeConnected;
185 int32_t nHeaderStart;
186 uint32_t nMessageStart;
188 std::string addrName;
191 std::string strSubVer;
196 bool fSuccessfullyConnected;
198 CSemaphoreGrant grantOutbound;
202 // Denial-of-service detection/prevention
203 // Key is IP address, value is banned-until-time
204 static std::map<CNetAddr, int64_t> setBanned;
205 static CCriticalSection cs_setBanned;
209 int64_t nReleaseTime;
210 std::map<uint256, CRequestTracker> mapRequests;
211 CCriticalSection cs_mapRequests;
212 uint256 hashContinue;
213 CBlockIndex* pindexLastGetBlocksBegin;
214 uint256 hashLastGetBlocksEnd;
215 int32_t nStartingHeight;
219 std::vector<CAddress> vAddrToSend;
220 std::set<CAddress> setAddrKnown;
222 std::set<uint256> setKnown;
223 uint256 hashCheckpointKnown; // ppcoin: known sent sync-checkpoint
224 int64_t nNextAddrSend;
225 int64_t nNextLocalAddrSend;
226 int64_t nNextInvSend;
228 // inventory based relay
229 mruset<CInv> setInventoryKnown;
230 std::vector<CInv> vInventoryToSend;
231 CCriticalSection cs_inventory;
232 std::multimap<int64_t, CInv> mapAskFor;
234 CNode(SOCKET hSocketIn, CAddress addrIn, std::string addrNameIn = "", bool fInboundIn=false) : vSend(SER_NETWORK, MIN_PROTO_VERSION), vRecv(SER_NETWORK, MIN_PROTO_VERSION)
242 nLastSendEmpty = GetTime();
243 nTimeConnected = GetTime();
245 nMessageStart = std::numeric_limits<uint32_t>::max();
247 addrName = addrNameIn.empty() ? addr.ToStringIPPort() : addrNameIn;
251 fClient = false; // set by version message
252 fInbound = fInboundIn;
253 fNetworkNode = false;
254 fSuccessfullyConnected = false;
259 pindexLastGetBlocksBegin = 0;
260 hashLastGetBlocksEnd = 0;
261 nStartingHeight = -1;
262 nNextLocalAddrSend = 0;
268 hashCheckpointKnown = 0;
269 setInventoryKnown.max_size((size_t)SendBufferSize() / 1000);
271 // Be shy and don't send version until we hear
272 if (hSocket != INVALID_SOCKET && !fInbound)
278 if (hSocket != INVALID_SOCKET)
280 CloseSocket(hSocket);
286 // Network usage totals
287 static CCriticalSection cs_totalBytesRecv;
288 static CCriticalSection cs_totalBytesSent;
289 static uint64_t nTotalBytesRecv;
290 static uint64_t nTotalBytesSent;
292 void operator=(const CNode&);
298 return std::max(nRefCount, 0) + (GetTime() < nReleaseTime ? 1 : 0);
301 CNode* AddRef(int64_t nTimeout=0)
304 nReleaseTime = std::max(nReleaseTime, GetTime() + nTimeout);
317 void AddAddressKnown(const CAddress& addr)
319 setAddrKnown.insert(addr);
322 void PushAddress(const CAddress& addr)
324 // Known checking here is only to save space from duplicates.
325 // SendMessages will filter it again for knowns that were added
326 // after addresses were pushed.
327 if (addr.IsValid() && !setAddrKnown.count(addr))
328 vAddrToSend.push_back(addr);
332 void AddInventoryKnown(const CInv& inv)
336 setInventoryKnown.insert(inv);
340 void PushInventory(const CInv& inv)
344 if (!setInventoryKnown.count(inv))
345 vInventoryToSend.push_back(inv);
349 void AskFor(const CInv& inv)
351 // We're using mapAskFor as a priority queue,
352 // the key is the earliest time the request can be sent
353 int64_t& nRequestTime = mapAlreadyAskedFor[inv];
355 printf("askfor %s %" PRId64 " (%s)\n", inv.ToString().c_str(), nRequestTime, DateTimeStrFormat("%H:%M:%S", nRequestTime/1000000).c_str());
357 // Make sure not to reuse time indexes to keep things in the same order
358 int64_t nNow = (GetTime() - 1) * 1000000;
359 static int64_t nLastTime;
361 nNow = std::max(nNow, nLastTime);
364 // Each retry is 2 minutes after the last
365 nRequestTime = std::max(nRequestTime + 2 * 60 * 1000000, nNow);
366 mapAskFor.insert(std::make_pair(nRequestTime, inv));
371 void BeginMessage(const char* pszCommand)
373 ENTER_CRITICAL_SECTION(cs_vSend);
374 if (nHeaderStart != -1)
376 nHeaderStart = (int32_t)vSend.size();
377 vSend << CMessageHeader(pszCommand, 0);
378 nMessageStart = (uint32_t)vSend.size();
380 printf("sending: %s ", pszCommand);
385 if (nHeaderStart < 0)
387 vSend.resize(nHeaderStart);
389 nMessageStart = std::numeric_limits<uint32_t>::max();
390 LEAVE_CRITICAL_SECTION(cs_vSend);
393 printf("(aborted)\n");
398 if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
400 printf("dropmessages DROPPING SEND MESSAGE\n");
405 if (nHeaderStart < 0) {
406 LEAVE_CRITICAL_SECTION(cs_vSend);
411 uint32_t nSize = (uint32_t) vSend.size() - nMessageStart;
412 memcpy((char*)&vSend[nHeaderStart] + CMessageHeader::MESSAGE_SIZE_OFFSET, &nSize, sizeof(nSize));
415 uint256 hash = Hash(vSend.begin() + nMessageStart, vSend.end());
416 uint32_t nChecksum = 0;
417 memcpy(&nChecksum, &hash, sizeof(nChecksum));
418 assert(nMessageStart - nHeaderStart >= CMessageHeader::CHECKSUM_OFFSET + sizeof(nChecksum));
419 memcpy((char*)&vSend[nHeaderStart] + CMessageHeader::CHECKSUM_OFFSET, &nChecksum, sizeof(nChecksum));
422 printf("(%d bytes)\n", nSize);
426 nMessageStart = std::numeric_limits<uint32_t>::max();
427 LEAVE_CRITICAL_SECTION(cs_vSend);
430 void EndMessageAbortIfEmpty()
432 if (nHeaderStart < 0)
434 int nSize = (int) vSend.size() - nMessageStart;
446 void PushMessage(const char* pszCommand)
450 BeginMessage(pszCommand);
460 template<typename ...Args>
461 void PushMessage(const char* pszCommand, const Args&... args)
465 BeginMessage(pszCommand);
466 (vSend << ... << args);
476 void PushRequest(const char* pszCommand,
477 void (*fn)(void*, CDataStream&), void* param1)
480 RAND_bytes((unsigned char*)&hashReply, sizeof(hashReply));
483 LOCK(cs_mapRequests);
484 mapRequests[hashReply] = CRequestTracker(fn, param1);
487 PushMessage(pszCommand, hashReply);
490 template<typename T1>
491 void PushRequest(const char* pszCommand, const T1& a1,
492 void (*fn)(void*, CDataStream&), void* param1)
495 RAND_bytes((unsigned char*)&hashReply, sizeof(hashReply));
498 LOCK(cs_mapRequests);
499 mapRequests[hashReply] = CRequestTracker(fn, param1);
502 PushMessage(pszCommand, hashReply, a1);
505 template<typename T1, typename T2>
506 void PushRequest(const char* pszCommand, const T1& a1, const T2& a2,
507 void (*fn)(void*, CDataStream&), void* param1)
510 RAND_bytes((unsigned char*)&hashReply, sizeof(hashReply));
513 LOCK(cs_mapRequests);
514 mapRequests[hashReply] = CRequestTracker(fn, param1);
517 PushMessage(pszCommand, hashReply, a1, a2);
522 void PushGetBlocks(CBlockIndex* pindexBegin, uint256 hashEnd);
523 bool IsSubscribed(unsigned int nChannel);
524 void Subscribe(unsigned int nChannel, unsigned int nHops=0);
525 void CancelSubscribe(unsigned int nChannel);
526 void CloseSocketDisconnect();
530 // Denial-of-service detection/prevention
531 // The idea is to detect peers that are behaving
532 // badly and disconnect/ban them, but do it in a
533 // one-coding-mistake-won't-shatter-the-entire-network
535 // IMPORTANT: There should be nothing I can give a
536 // node that it will forward on that will make that
537 // node's peers drop it. If there is, an attacker
538 // can isolate a node and/or try to split the network.
539 // Dropping a node for sending stuff that is invalid
540 // now but might be valid in a later version is also
541 // dangerous, because it can cause a network split
542 // between nodes running old code and nodes running
544 static void ClearBanned(); // needed for unit testing
545 static bool IsBanned(CNetAddr ip);
546 bool Misbehaving(int howmuch); // 1 == a little, 100 == a lot
547 void copyStats(CNodeStats &stats);
549 static void RecordBytesRecv(uint64_t bytes);
550 static void RecordBytesSent(uint64_t bytes);
552 static uint64_t GetTotalBytesRecv();
553 static uint64_t GetTotalBytesSent();
556 inline void RelayInventory(const CInv& inv)
558 // Put on lists to offer to the other nodes
561 for (CNode* pnode : vNodes)
562 pnode->PushInventory(inv);
567 void RelayTransaction(const CTransaction& tx, const uint256& hash);
568 void RelayTransaction(const CTransaction& tx, const uint256& hash, const CDataStream& ss);
571 /** Return a timestamp in the future (in microseconds) for exponentially distributed events. */
572 int64_t PoissonNextSend(int64_t nNow, int average_interval_seconds);