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.
13 #include <openssl/rand.h>
16 #include <arpa/inet.h>
23 class CRequestTracker;
26 extern int nBestHeight;
28 const uint16_t nSocksDefault = 9050;
29 const uint16_t nPortZero = 0;
32 inline uint64_t ReceiveBufferSize() { return 1000*GetArg("-maxreceivebuffer", 5*1000); }
33 inline uint64_t SendBufferSize() { return 1000*GetArg("-maxsendbuffer", 1*1000); }
35 void AddOneShot(std::string strDest);
36 bool RecvLine(SOCKET hSocket, std::string& strLine);
37 bool GetMyExternalIP(CNetAddr& ipRet);
38 void AddressCurrentlyConnected(const CService& addr);
39 CNode* FindNode(const CNetAddr& ip);
40 CNode* FindNode(const CService& ip);
41 CNode* ConnectNode(CAddress addrConnect, const char *strDest = NULL, int64_t nTimeout=0);
42 bool OpenNetworkConnection(const CAddress& addrConnect, CSemaphoreGrant *grantOutbound = NULL, const char *strDest = NULL, bool fOneShot = false);
44 unsigned short GetListenPort();
45 bool BindListenPort(const CService &bindAddr, std::string& strError=REF(std::string()));
46 void StartNode(void* parg);
51 LOCAL_NONE, // unknown
52 LOCAL_IF, // address a local interface listens on
53 LOCAL_BIND, // address explicit bound to
54 LOCAL_IRC, // address reported by IRC (deprecated)
55 LOCAL_HTTP, // address reported by whatismyip.com and similar
56 LOCAL_MANUAL, // address explicitly specified (-externalip=)
62 bool IsPeerAddrLocalGood(CNode *pnode);
63 void AdvertiseLocal(CNode *pnode);
64 void SetLimited(enum Network net, bool fLimited = true);
65 bool IsLimited(enum Network net);
66 bool IsLimited(const CNetAddr& addr);
67 bool AddLocal(const CService& addr, int nScore = LOCAL_NONE);
68 bool AddLocal(const CNetAddr& addr, int nScore = LOCAL_NONE);
69 bool SeenLocal(const CService& addr);
70 bool IsLocal(const CService& addr);
71 bool GetLocal(CService &addr, const CNetAddr *paddrPeer = NULL);
72 bool IsReachable(const CNetAddr &addr);
73 void SetReachable(enum Network net, bool fFlag = true);
74 CAddress GetLocalAddress(const CNetAddr *paddrPeer = NULL);
86 void (*fn)(void*, CDataStream&);
89 explicit CRequestTracker(void (*fnIn)(void*, CDataStream&)=NULL, void* param1In=NULL)
105 THREAD_SOCKETHANDLER,
106 THREAD_OPENCONNECTIONS,
107 THREAD_MESSAGEHANDLER,
110 THREAD_ADDEDCONNECTIONS,
122 extern bool fDiscover;
123 extern bool fNoListen;
125 extern bool fDiscover;
126 extern uint64_t nLocalServices;
127 extern uint64_t nLocalHostNonce;
128 extern CAddress addrSeenByPeer;
129 extern std::array<int, THREAD_MAX> vnThreadsRunning;
130 extern CAddrMan addrman;
132 extern std::vector<CNode*> vNodes;
133 extern CCriticalSection cs_vNodes;
134 extern std::vector<std::string> vAddedNodes;
135 extern CCriticalSection cs_vAddedNodes;
136 extern std::map<CInv, CDataStream> mapRelay;
137 extern std::deque<std::pair<int64_t, CInv> > vRelayExpiration;
138 extern CCriticalSection cs_mapRelay;
139 extern std::map<CInv, int64_t> mapAlreadyAskedFor;
150 int64_t nTimeConnected;
151 std::string addrName;
153 std::string strSubVer;
155 int64_t nReleaseTime;
156 int32_t nStartingHeight;
157 int32_t nMisbehavior;
167 /** Information about a peer */
178 CCriticalSection cs_vSend;
179 CCriticalSection cs_vRecv;
182 int64_t nLastSendEmpty;
183 int64_t nTimeConnected;
184 int32_t nHeaderStart;
185 uint32_t nMessageStart;
187 std::string addrName;
190 std::string strSubVer;
195 bool fSuccessfullyConnected;
197 CSemaphoreGrant grantOutbound;
201 // Denial-of-service detection/prevention
202 // Key is IP address, value is banned-until-time
203 static std::map<CNetAddr, int64_t> setBanned;
204 static CCriticalSection cs_setBanned;
208 int64_t nReleaseTime;
209 std::map<uint256, CRequestTracker> mapRequests;
210 CCriticalSection cs_mapRequests;
211 uint256 hashContinue;
212 CBlockIndex* pindexLastGetBlocksBegin;
213 uint256 hashLastGetBlocksEnd;
214 int32_t nStartingHeight;
218 std::vector<CAddress> vAddrToSend;
219 std::set<CAddress> setAddrKnown;
221 std::set<uint256> setKnown;
222 uint256 hashCheckpointKnown; // ppcoin: known sent sync-checkpoint
223 int64_t nNextAddrSend;
224 int64_t nNextLocalAddrSend;
225 int64_t nNextInvSend;
227 // inventory based relay
228 mruset<CInv> setInventoryKnown;
229 std::vector<CInv> vInventoryToSend;
230 CCriticalSection cs_inventory;
231 std::multimap<int64_t, CInv> mapAskFor;
233 CNode(SOCKET hSocketIn, CAddress addrIn, std::string addrNameIn = "", bool fInboundIn=false) : vSend(SER_NETWORK, MIN_PROTO_VERSION), vRecv(SER_NETWORK, MIN_PROTO_VERSION)
241 nLastSendEmpty = GetTime();
242 nTimeConnected = GetTime();
244 nMessageStart = std::numeric_limits<uint32_t>::max();
246 addrName = addrNameIn.empty() ? addr.ToStringIPPort() : addrNameIn;
250 fClient = false; // set by version message
251 fInbound = fInboundIn;
252 fNetworkNode = false;
253 fSuccessfullyConnected = false;
258 pindexLastGetBlocksBegin = 0;
259 hashLastGetBlocksEnd = 0;
260 nStartingHeight = -1;
261 nNextLocalAddrSend = 0;
267 hashCheckpointKnown = 0;
268 setInventoryKnown.max_size((size_t)SendBufferSize() / 1000);
270 // Be shy and don't send version until we hear
271 if (hSocket != INVALID_SOCKET && !fInbound)
277 if (hSocket != INVALID_SOCKET)
279 CloseSocket(hSocket);
285 // Network usage totals
286 static CCriticalSection cs_totalBytesRecv;
287 static CCriticalSection cs_totalBytesSent;
288 static uint64_t nTotalBytesRecv;
289 static uint64_t nTotalBytesSent;
291 void operator=(const CNode&);
297 return std::max(nRefCount, 0) + (GetTime() < nReleaseTime ? 1 : 0);
300 CNode* AddRef(int64_t nTimeout=0)
303 nReleaseTime = std::max(nReleaseTime, GetTime() + nTimeout);
316 void AddAddressKnown(const CAddress& addr)
318 setAddrKnown.insert(addr);
321 void PushAddress(const CAddress& addr)
323 // Known checking here is only to save space from duplicates.
324 // SendMessages will filter it again for knowns that were added
325 // after addresses were pushed.
326 if (addr.IsValid() && !setAddrKnown.count(addr))
327 vAddrToSend.push_back(addr);
331 void AddInventoryKnown(const CInv& inv)
335 setInventoryKnown.insert(inv);
339 void PushInventory(const CInv& inv)
343 if (!setInventoryKnown.count(inv))
344 vInventoryToSend.push_back(inv);
348 void AskFor(const CInv& inv)
350 // We're using mapAskFor as a priority queue,
351 // the key is the earliest time the request can be sent
352 int64_t& nRequestTime = mapAlreadyAskedFor[inv];
354 printf("askfor %s %" PRId64 " (%s)\n", inv.ToString().c_str(), nRequestTime, DateTimeStrFormat("%H:%M:%S", nRequestTime/1000000).c_str());
356 // Make sure not to reuse time indexes to keep things in the same order
357 int64_t nNow = (GetTime() - 1) * 1000000;
358 static int64_t nLastTime;
360 nNow = std::max(nNow, nLastTime);
363 // Each retry is 2 minutes after the last
364 nRequestTime = std::max(nRequestTime + 2 * 60 * 1000000, nNow);
365 mapAskFor.insert(std::make_pair(nRequestTime, inv));
370 void BeginMessage(const char* pszCommand)
372 ENTER_CRITICAL_SECTION(cs_vSend);
373 if (nHeaderStart != -1)
375 nHeaderStart = (int32_t)vSend.size();
376 vSend << CMessageHeader(pszCommand, 0);
377 nMessageStart = (uint32_t)vSend.size();
379 printf("sending: %s ", pszCommand);
384 if (nHeaderStart < 0)
386 vSend.resize(nHeaderStart);
388 nMessageStart = std::numeric_limits<uint32_t>::max();
389 LEAVE_CRITICAL_SECTION(cs_vSend);
392 printf("(aborted)\n");
397 if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
399 printf("dropmessages DROPPING SEND MESSAGE\n");
404 if (nHeaderStart < 0) {
405 LEAVE_CRITICAL_SECTION(cs_vSend);
410 uint32_t nSize = (uint32_t) vSend.size() - nMessageStart;
411 memcpy((char*)&vSend[nHeaderStart] + CMessageHeader::MESSAGE_SIZE_OFFSET, &nSize, sizeof(nSize));
414 uint256 hash = Hash(vSend.begin() + nMessageStart, vSend.end());
415 uint32_t nChecksum = 0;
416 memcpy(&nChecksum, &hash, sizeof(nChecksum));
417 assert(nMessageStart - nHeaderStart >= CMessageHeader::CHECKSUM_OFFSET + sizeof(nChecksum));
418 memcpy((char*)&vSend[nHeaderStart] + CMessageHeader::CHECKSUM_OFFSET, &nChecksum, sizeof(nChecksum));
421 printf("(%d bytes)\n", nSize);
425 nMessageStart = std::numeric_limits<uint32_t>::max();
426 LEAVE_CRITICAL_SECTION(cs_vSend);
429 void EndMessageAbortIfEmpty()
431 if (nHeaderStart < 0)
433 int nSize = (int) vSend.size() - nMessageStart;
445 void PushMessage(const char* pszCommand)
449 BeginMessage(pszCommand);
459 template<typename ...Args>
460 void PushMessage(const char* pszCommand, const Args&... args)
464 BeginMessage(pszCommand);
465 (vSend << ... << args);
475 void PushRequest(const char* pszCommand,
476 void (*fn)(void*, CDataStream&), void* param1)
479 RAND_bytes((unsigned char*)&hashReply, sizeof(hashReply));
482 LOCK(cs_mapRequests);
483 mapRequests[hashReply] = CRequestTracker(fn, param1);
486 PushMessage(pszCommand, hashReply);
489 template<typename T1>
490 void PushRequest(const char* pszCommand, const T1& a1,
491 void (*fn)(void*, CDataStream&), void* param1)
494 RAND_bytes((unsigned char*)&hashReply, sizeof(hashReply));
497 LOCK(cs_mapRequests);
498 mapRequests[hashReply] = CRequestTracker(fn, param1);
501 PushMessage(pszCommand, hashReply, a1);
504 template<typename T1, typename T2>
505 void PushRequest(const char* pszCommand, const T1& a1, const T2& a2,
506 void (*fn)(void*, CDataStream&), void* param1)
509 RAND_bytes((unsigned char*)&hashReply, sizeof(hashReply));
512 LOCK(cs_mapRequests);
513 mapRequests[hashReply] = CRequestTracker(fn, param1);
516 PushMessage(pszCommand, hashReply, a1, a2);
521 void PushGetBlocks(CBlockIndex* pindexBegin, uint256 hashEnd);
522 bool IsSubscribed(unsigned int nChannel);
523 void Subscribe(unsigned int nChannel, unsigned int nHops=0);
524 void CancelSubscribe(unsigned int nChannel);
525 void CloseSocketDisconnect();
529 // Denial-of-service detection/prevention
530 // The idea is to detect peers that are behaving
531 // badly and disconnect/ban them, but do it in a
532 // one-coding-mistake-won't-shatter-the-entire-network
534 // IMPORTANT: There should be nothing I can give a
535 // node that it will forward on that will make that
536 // node's peers drop it. If there is, an attacker
537 // can isolate a node and/or try to split the network.
538 // Dropping a node for sending stuff that is invalid
539 // now but might be valid in a later version is also
540 // dangerous, because it can cause a network split
541 // between nodes running old code and nodes running
543 static void ClearBanned(); // needed for unit testing
544 static bool IsBanned(CNetAddr ip);
545 bool Misbehaving(int howmuch); // 1 == a little, 100 == a lot
546 void copyStats(CNodeStats &stats);
548 static void RecordBytesRecv(uint64_t bytes);
549 static void RecordBytesSent(uint64_t bytes);
551 static uint64_t GetTotalBytesRecv();
552 static uint64_t GetTotalBytesSent();
555 inline void RelayInventory(const CInv& inv)
557 // Put on lists to offer to the other nodes
560 for (CNode* pnode : vNodes)
561 pnode->PushInventory(inv);
566 void RelayTransaction(const CTransaction& tx, const uint256& hash);
567 void RelayTransaction(const CTransaction& tx, const uint256& hash, const CDataStream& ss);
570 /** Return a timestamp in the future (in microseconds) for exponentially distributed events. */
571 int64_t PoissonNextSend(int64_t nNow, int average_interval_seconds);