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.
11 #include <boost/array.hpp>
13 #include <openssl/rand.h>
16 #include <arpa/inet.h>
26 class CRequestTracker;
29 extern int nBestHeight;
31 const uint16_t nSocksDefault = 9050;
32 const uint16_t nPortZero = 0;
35 inline uint64_t ReceiveBufferSize() { return 1000*GetArg("-maxreceivebuffer", 5*1000); }
36 inline uint64_t SendBufferSize() { return 1000*GetArg("-maxsendbuffer", 1*1000); }
38 void AddOneShot(string strDest);
39 bool RecvLine(SOCKET hSocket, string& strLine);
40 bool GetMyExternalIP(CNetAddr& ipRet);
41 void AddressCurrentlyConnected(const CService& addr);
42 CNode* FindNode(const CNetAddr& ip);
43 CNode* FindNode(const CService& ip);
44 CNode* ConnectNode(CAddress addrConnect, const char *strDest = NULL, int64_t nTimeout=0);
45 bool OpenNetworkConnection(const CAddress& addrConnect, CSemaphoreGrant *grantOutbound = NULL, const char *strDest = NULL, bool fOneShot = false);
47 uint16_t GetListenPort();
48 bool BindListenPort(const CService &bindAddr, string& strError=REF(string()));
49 void StartNode(void* parg);
54 LOCAL_NONE, // unknown
55 LOCAL_IF, // address a local interface listens on
56 LOCAL_BIND, // address explicit bound to
57 LOCAL_IRC, // address reported by IRC (deprecated)
58 LOCAL_HTTP, // address reported by whatismyip.com and similar
59 LOCAL_MANUAL, // address explicitly specified (-externalip=)
65 bool IsPeerAddrLocalGood(CNode *pnode);
66 void AdvertiseLocal(CNode *pnode);
67 void SetLimited(enum Network net, bool fLimited = true);
68 bool IsLimited(enum Network net);
69 bool IsLimited(const CNetAddr& addr);
70 bool AddLocal(const CService& addr, int nScore = LOCAL_NONE);
71 bool AddLocal(const CNetAddr& addr, int nScore = LOCAL_NONE);
72 bool SeenLocal(const CService& addr);
73 bool IsLocal(const CService& addr);
74 bool GetLocal(CService &addr, const CNetAddr *paddrPeer = NULL);
75 bool IsReachable(const CNetAddr &addr);
76 void SetReachable(enum Network net, bool fFlag = true);
77 CAddress GetLocalAddress(const CNetAddr *paddrPeer = NULL);
89 void (*fn)(void*, CDataStream&);
92 explicit CRequestTracker(void (*fnIn)(void*, CDataStream&)=NULL, void* param1In=NULL)
108 THREAD_SOCKETHANDLER,
109 THREAD_OPENCONNECTIONS,
110 THREAD_MESSAGEHANDLER,
113 THREAD_ADDEDCONNECTIONS,
125 extern bool fDiscover;
126 extern bool fNoListen;
128 extern bool fDiscover;
129 extern uint64_t nLocalServices;
130 extern uint64_t nLocalHostNonce;
131 extern CAddress addrSeenByPeer;
132 extern boost::array<int, THREAD_MAX> vnThreadsRunning;
133 extern CAddrMan addrman;
135 extern vector<CNode*> vNodes;
136 extern CCriticalSection cs_vNodes;
137 extern vector<string> vAddedNodes;
138 extern CCriticalSection cs_vAddedNodes;
139 extern map<CInv, CDataStream> mapRelay;
140 extern deque<pair<int64_t, CInv> > vRelayExpiration;
141 extern CCriticalSection cs_mapRelay;
142 extern map<CInv, int64_t> mapAlreadyAskedFor;
153 int64_t nTimeConnected;
158 int64_t nReleaseTime;
159 int32_t nStartingHeight;
160 int32_t nMisbehavior;
170 /** Information about a peer */
181 CCriticalSection cs_vSend;
182 CCriticalSection cs_vRecv;
185 int64_t nLastSendEmpty;
186 int64_t nTimeConnected;
187 int32_t nHeaderStart;
188 uint32_t nMessageStart;
198 bool fSuccessfullyConnected;
200 CSemaphoreGrant grantOutbound;
204 // Denial-of-service detection/prevention
205 // Key is IP address, value is banned-until-time
206 static map<CNetAddr, int64_t> setBanned;
207 static CCriticalSection cs_setBanned;
211 int64_t nReleaseTime;
212 map<uint256, CRequestTracker> mapRequests;
213 CCriticalSection cs_mapRequests;
214 uint256 hashContinue;
215 CBlockIndex* pindexLastGetBlocksBegin;
216 uint256 hashLastGetBlocksEnd;
217 int32_t nStartingHeight;
221 vector<CAddress> vAddrToSend;
222 set<CAddress> setAddrKnown;
224 set<uint256> setKnown;
225 uint256 hashCheckpointKnown; // ppcoin: known sent sync-checkpoint
226 int64_t nNextAddrSend;
227 int64_t nNextLocalAddrSend;
228 int64_t nNextInvSend;
230 // inventory based relay
231 mruset<CInv> setInventoryKnown;
232 vector<CInv> vInventoryToSend;
233 CCriticalSection cs_inventory;
234 multimap<int64_t, CInv> mapAskFor;
236 CNode(SOCKET hSocketIn, CAddress addrIn, string addrNameIn = "", bool fInboundIn=false) : vSend(SER_NETWORK, MIN_PROTO_VERSION), vRecv(SER_NETWORK, MIN_PROTO_VERSION)
244 nLastSendEmpty = GetTime();
245 nTimeConnected = GetTime();
247 nMessageStart = numeric_limits<uint32_t>::max();
249 addrName = addrNameIn.empty() ? addr.ToStringIPPort() : addrNameIn;
253 fClient = false; // set by version message
254 fInbound = fInboundIn;
255 fNetworkNode = false;
256 fSuccessfullyConnected = false;
261 pindexLastGetBlocksBegin = 0;
262 hashLastGetBlocksEnd = 0;
263 nStartingHeight = -1;
264 nNextLocalAddrSend = 0;
270 hashCheckpointKnown = 0;
271 setInventoryKnown.max_size((size_t)SendBufferSize() / 1000);
273 // Be shy and don't send version until we hear
274 if (hSocket != INVALID_SOCKET && !fInbound)
280 if (hSocket != INVALID_SOCKET)
282 CloseSocket(hSocket);
288 // Network usage totals
289 static CCriticalSection cs_totalBytesRecv;
290 static CCriticalSection cs_totalBytesSent;
291 static uint64_t nTotalBytesRecv;
292 static uint64_t nTotalBytesSent;
294 void operator=(const CNode&);
300 return max(nRefCount, 0) + (GetTime() < nReleaseTime ? 1 : 0);
303 CNode* AddRef(int64_t nTimeout=0)
306 nReleaseTime = max(nReleaseTime, GetTime() + nTimeout);
319 void AddAddressKnown(const CAddress& addr)
321 setAddrKnown.insert(addr);
324 void PushAddress(const CAddress& addr)
326 // Known checking here is only to save space from duplicates.
327 // SendMessages will filter it again for knowns that were added
328 // after addresses were pushed.
329 if (addr.IsValid() && !setAddrKnown.count(addr))
330 vAddrToSend.push_back(addr);
334 void AddInventoryKnown(const CInv& inv)
338 setInventoryKnown.insert(inv);
342 void PushInventory(const CInv& inv)
346 if (!setInventoryKnown.count(inv))
347 vInventoryToSend.push_back(inv);
351 void AskFor(const CInv& inv)
353 // We're using mapAskFor as a priority queue,
354 // the key is the earliest time the request can be sent
355 int64_t& nRequestTime = mapAlreadyAskedFor[inv];
357 printf("askfor %s %" PRId64 " (%s)\n", inv.ToString().c_str(), nRequestTime, DateTimeStrFormat("%H:%M:%S", nRequestTime/1000000).c_str());
359 // Make sure not to reuse time indexes to keep things in the same order
360 int64_t nNow = (GetTime() - 1) * 1000000;
361 static int64_t nLastTime;
363 nNow = max(nNow, nLastTime);
366 // Each retry is 2 minutes after the last
367 nRequestTime = max(nRequestTime + 2 * 60 * 1000000, nNow);
368 mapAskFor.insert({ nRequestTime, inv });
373 void BeginMessage(const char* pszCommand)
375 ENTER_CRITICAL_SECTION(cs_vSend);
376 if (nHeaderStart != -1)
378 nHeaderStart = (int32_t)vSend.size();
379 vSend << CMessageHeader(pszCommand, 0);
380 nMessageStart = (uint32_t)vSend.size();
382 printf("sending: %s ", pszCommand);
387 if (nHeaderStart < 0)
389 vSend.resize(nHeaderStart);
391 nMessageStart = numeric_limits<uint32_t>::max();
392 LEAVE_CRITICAL_SECTION(cs_vSend);
395 printf("(aborted)\n");
400 if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
402 printf("dropmessages DROPPING SEND MESSAGE\n");
407 if (nHeaderStart < 0)
411 uint32_t nSize = (uint32_t) vSend.size() - nMessageStart;
412 memcpy((char*)&vSend[nHeaderStart] + CMessageHeader::MESSAGE_SIZE_OFFSET, &nSize, sizeof(nSize));
415 auto 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 = 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 T1>
461 void PushMessage(const char* pszCommand, const T1& a1)
465 BeginMessage(pszCommand);
476 template<typename T1, typename T2>
477 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2)
481 BeginMessage(pszCommand);
492 template<typename T1, typename T2, typename T3>
493 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3)
497 BeginMessage(pszCommand);
498 vSend << a1 << a2 << a3;
508 template<typename T1, typename T2, typename T3, typename T4>
509 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4)
513 BeginMessage(pszCommand);
514 vSend << a1 << a2 << a3 << a4;
524 template<typename T1, typename T2, typename T3, typename T4, typename T5>
525 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4, const T5& a5)
529 BeginMessage(pszCommand);
530 vSend << a1 << a2 << a3 << a4 << a5;
540 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6>
541 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4, const T5& a5, const T6& a6)
545 BeginMessage(pszCommand);
546 vSend << a1 << a2 << a3 << a4 << a5 << a6;
556 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7>
557 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4, const T5& a5, const T6& a6, const T7& a7)
561 BeginMessage(pszCommand);
562 vSend << a1 << a2 << a3 << a4 << a5 << a6 << a7;
572 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8>
573 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4, const T5& a5, const T6& a6, const T7& a7, const T8& a8)
577 BeginMessage(pszCommand);
578 vSend << a1 << a2 << a3 << a4 << a5 << a6 << a7 << a8;
588 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9>
589 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4, const T5& a5, const T6& a6, const T7& a7, const T8& a8, const T9& a9)
593 BeginMessage(pszCommand);
594 vSend << a1 << a2 << a3 << a4 << a5 << a6 << a7 << a8 << a9;
605 void PushRequest(const char* pszCommand,
606 void (*fn)(void*, CDataStream&), void* param1)
609 RAND_bytes((unsigned char*)&hashReply, sizeof(hashReply));
612 LOCK(cs_mapRequests);
613 mapRequests[hashReply] = CRequestTracker(fn, param1);
616 PushMessage(pszCommand, hashReply);
619 template<typename T1>
620 void PushRequest(const char* pszCommand, const T1& a1,
621 void (*fn)(void*, CDataStream&), void* param1)
624 RAND_bytes((unsigned char*)&hashReply, sizeof(hashReply));
627 LOCK(cs_mapRequests);
628 mapRequests[hashReply] = CRequestTracker(fn, param1);
631 PushMessage(pszCommand, hashReply, a1);
634 template<typename T1, typename T2>
635 void PushRequest(const char* pszCommand, const T1& a1, const T2& a2,
636 void (*fn)(void*, CDataStream&), void* param1)
639 RAND_bytes((unsigned char*)&hashReply, sizeof(hashReply));
642 LOCK(cs_mapRequests);
643 mapRequests[hashReply] = CRequestTracker(fn, param1);
646 PushMessage(pszCommand, hashReply, a1, a2);
651 void PushGetBlocks(CBlockIndex* pindexBegin, uint256 hashEnd);
652 bool IsSubscribed(unsigned int nChannel);
653 void Subscribe(unsigned int nChannel, unsigned int nHops=0);
654 void CancelSubscribe(unsigned int nChannel);
655 void CloseSocketDisconnect();
659 // Denial-of-service detection/prevention
660 // The idea is to detect peers that are behaving
661 // badly and disconnect/ban them, but do it in a
662 // one-coding-mistake-won't-shatter-the-entire-network
664 // IMPORTANT: There should be nothing I can give a
665 // node that it will forward on that will make that
666 // node's peers drop it. If there is, an attacker
667 // can isolate a node and/or try to split the network.
668 // Dropping a node for sending stuff that is invalid
669 // now but might be valid in a later version is also
670 // dangerous, because it can cause a network split
671 // between nodes running old code and nodes running
673 static void ClearBanned(); // needed for unit testing
674 static bool IsBanned(CNetAddr ip);
675 bool Misbehaving(int howmuch); // 1 == a little, 100 == a lot
676 void copyStats(CNodeStats &stats);
678 static void RecordBytesRecv(uint64_t bytes);
679 static void RecordBytesSent(uint64_t bytes);
681 static uint64_t GetTotalBytesRecv();
682 static uint64_t GetTotalBytesSent();
685 inline void RelayInventory(const CInv& inv)
687 // Put on lists to offer to the other nodes
690 for(CNode* pnode : vNodes)
691 pnode->PushInventory(inv);
696 void RelayTransaction(const CTransaction& tx, const uint256& hash);
697 void RelayTransaction(const CTransaction& tx, const uint256& hash, const CDataStream& ss);
700 /** Return a timestamp in the future (in microseconds) for exponentially distributed events. */
701 int64_t PoissonNextSend(int64_t nNow, int average_interval_seconds);