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>
12 #include <boost/foreach.hpp>
14 #include <openssl/rand.h>
17 #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(std::string strDest);
39 bool RecvLine(SOCKET hSocket, std::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 unsigned short GetListenPort();
48 bool BindListenPort(const CService &bindAddr, std::string& strError=REF(std::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_UPNP, // address reported by UPnP
58 LOCAL_IRC, // address reported by IRC (deprecated)
59 LOCAL_HTTP, // address reported by whatismyip.com and similar
60 LOCAL_MANUAL, // address explicitly specified (-externalip=)
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,
112 THREAD_ADDEDCONNECTIONS,
123 extern bool fDiscover;
124 extern bool fUseUPnP;
125 extern uint64_t nLocalServices;
126 extern uint64_t nLocalHostNonce;
127 extern CAddress addrSeenByPeer;
128 extern boost::array<int, THREAD_MAX> vnThreadsRunning;
129 extern CAddrMan addrman;
131 extern std::vector<CNode*> vNodes;
132 extern CCriticalSection cs_vNodes;
133 extern std::vector<std::string> vAddedNodes;
134 extern CCriticalSection cs_vAddedNodes;
135 extern std::map<CInv, CDataStream> mapRelay;
136 extern std::deque<std::pair<int64_t, CInv> > vRelayExpiration;
137 extern CCriticalSection cs_mapRelay;
138 extern std::map<CInv, int64_t> mapAlreadyAskedFor;
149 int64_t nTimeConnected;
150 std::string addrName;
152 std::string strSubVer;
154 int64_t nReleaseTime;
155 int32_t nStartingHeight;
156 int32_t nMisbehavior;
166 /** Information about a peer */
177 CCriticalSection cs_vSend;
178 CCriticalSection cs_vRecv;
181 int64_t nLastSendEmpty;
182 int64_t nTimeConnected;
183 int32_t nHeaderStart;
184 uint32_t nMessageStart;
186 std::string addrName;
189 std::string strSubVer;
194 bool fSuccessfullyConnected;
196 CSemaphoreGrant grantOutbound;
200 // Denial-of-service detection/prevention
201 // Key is IP address, value is banned-until-time
202 static std::map<CNetAddr, int64_t> setBanned;
203 static CCriticalSection cs_setBanned;
207 int64_t nReleaseTime;
208 std::map<uint256, CRequestTracker> mapRequests;
209 CCriticalSection cs_mapRequests;
210 uint256 hashContinue;
211 CBlockIndex* pindexLastGetBlocksBegin;
212 uint256 hashLastGetBlocksEnd;
213 int32_t nStartingHeight;
217 std::vector<CAddress> vAddrToSend;
218 std::set<CAddress> setAddrKnown;
220 std::set<uint256> setKnown;
221 uint256 hashCheckpointKnown; // ppcoin: known sent sync-checkpoint
223 // inventory based relay
224 mruset<CInv> setInventoryKnown;
225 std::vector<CInv> vInventoryToSend;
226 CCriticalSection cs_inventory;
227 std::multimap<int64_t, CInv> mapAskFor;
229 CNode(SOCKET hSocketIn, CAddress addrIn, std::string addrNameIn = "", bool fInboundIn=false) : vSend(SER_NETWORK, MIN_PROTO_VERSION), vRecv(SER_NETWORK, MIN_PROTO_VERSION)
237 nLastSendEmpty = GetTime();
238 nTimeConnected = GetTime();
240 nMessageStart = std::numeric_limits<uint32_t>::max();
242 addrName = addrNameIn == "" ? addr.ToStringIPPort() : addrNameIn;
246 fClient = false; // set by version message
247 fInbound = fInboundIn;
248 fNetworkNode = false;
249 fSuccessfullyConnected = false;
254 pindexLastGetBlocksBegin = 0;
255 hashLastGetBlocksEnd = 0;
256 nStartingHeight = -1;
260 hashCheckpointKnown = 0;
261 setInventoryKnown.max_size((size_t)SendBufferSize() / 1000);
263 // Be shy and don't send version until we hear
264 if (hSocket != INVALID_SOCKET && !fInbound)
270 if (hSocket != INVALID_SOCKET)
272 closesocket(hSocket);
273 hSocket = INVALID_SOCKET;
279 // Network usage totals
280 static CCriticalSection cs_totalBytesRecv;
281 static CCriticalSection cs_totalBytesSent;
282 static uint64_t nTotalBytesRecv;
283 static uint64_t nTotalBytesSent;
285 void operator=(const CNode&);
291 return std::max(nRefCount, 0) + (GetTime() < nReleaseTime ? 1 : 0);
294 CNode* AddRef(int64_t nTimeout=0)
297 nReleaseTime = std::max(nReleaseTime, GetTime() + nTimeout);
310 void AddAddressKnown(const CAddress& addr)
312 setAddrKnown.insert(addr);
315 void PushAddress(const CAddress& addr)
317 // Known checking here is only to save space from duplicates.
318 // SendMessages will filter it again for knowns that were added
319 // after addresses were pushed.
320 if (addr.IsValid() && !setAddrKnown.count(addr))
321 vAddrToSend.push_back(addr);
325 void AddInventoryKnown(const CInv& inv)
329 setInventoryKnown.insert(inv);
333 void PushInventory(const CInv& inv)
337 if (!setInventoryKnown.count(inv))
338 vInventoryToSend.push_back(inv);
342 void AskFor(const CInv& inv)
344 // We're using mapAskFor as a priority queue,
345 // the key is the earliest time the request can be sent
346 int64_t& nRequestTime = mapAlreadyAskedFor[inv];
348 printf("askfor %s %" PRId64 " (%s)\n", inv.ToString().c_str(), nRequestTime, DateTimeStrFormat("%H:%M:%S", nRequestTime/1000000).c_str());
350 // Make sure not to reuse time indexes to keep things in the same order
351 int64_t nNow = (GetTime() - 1) * 1000000;
352 static int64_t nLastTime;
354 nNow = std::max(nNow, nLastTime);
357 // Each retry is 2 minutes after the last
358 nRequestTime = std::max(nRequestTime + 2 * 60 * 1000000, nNow);
359 mapAskFor.insert(std::make_pair(nRequestTime, inv));
364 void BeginMessage(const char* pszCommand)
366 ENTER_CRITICAL_SECTION(cs_vSend);
367 if (nHeaderStart != -1)
369 nHeaderStart = (int32_t)vSend.size();
370 vSend << CMessageHeader(pszCommand, 0);
371 nMessageStart = (uint32_t)vSend.size();
373 printf("sending: %s ", pszCommand);
378 if (nHeaderStart < 0)
380 vSend.resize(nHeaderStart);
382 nMessageStart = std::numeric_limits<uint32_t>::max();
383 LEAVE_CRITICAL_SECTION(cs_vSend);
386 printf("(aborted)\n");
391 if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
393 printf("dropmessages DROPPING SEND MESSAGE\n");
398 if (nHeaderStart < 0)
402 uint32_t nSize = (uint32_t) vSend.size() - nMessageStart;
403 memcpy((char*)&vSend[nHeaderStart] + CMessageHeader::MESSAGE_SIZE_OFFSET, &nSize, sizeof(nSize));
406 uint256 hash = Hash(vSend.begin() + nMessageStart, vSend.end());
407 uint32_t nChecksum = 0;
408 memcpy(&nChecksum, &hash, sizeof(nChecksum));
409 assert(nMessageStart - nHeaderStart >= CMessageHeader::CHECKSUM_OFFSET + sizeof(nChecksum));
410 memcpy((char*)&vSend[nHeaderStart] + CMessageHeader::CHECKSUM_OFFSET, &nChecksum, sizeof(nChecksum));
413 printf("(%d bytes)\n", nSize);
417 nMessageStart = std::numeric_limits<uint32_t>::max();
418 LEAVE_CRITICAL_SECTION(cs_vSend);
421 void EndMessageAbortIfEmpty()
423 if (nHeaderStart < 0)
425 int nSize = (int) vSend.size() - nMessageStart;
437 void PushMessage(const char* pszCommand)
441 BeginMessage(pszCommand);
451 template<typename T1>
452 void PushMessage(const char* pszCommand, const T1& a1)
456 BeginMessage(pszCommand);
467 template<typename T1, typename T2>
468 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2)
472 BeginMessage(pszCommand);
483 template<typename T1, typename T2, typename T3>
484 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3)
488 BeginMessage(pszCommand);
489 vSend << a1 << a2 << a3;
499 template<typename T1, typename T2, typename T3, typename T4>
500 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4)
504 BeginMessage(pszCommand);
505 vSend << a1 << a2 << a3 << a4;
515 template<typename T1, typename T2, typename T3, typename T4, typename T5>
516 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4, const T5& a5)
520 BeginMessage(pszCommand);
521 vSend << a1 << a2 << a3 << a4 << a5;
531 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6>
532 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4, const T5& a5, const T6& a6)
536 BeginMessage(pszCommand);
537 vSend << a1 << a2 << a3 << a4 << a5 << a6;
547 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7>
548 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)
552 BeginMessage(pszCommand);
553 vSend << a1 << a2 << a3 << a4 << a5 << a6 << a7;
563 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8>
564 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)
568 BeginMessage(pszCommand);
569 vSend << a1 << a2 << a3 << a4 << a5 << a6 << a7 << a8;
579 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9>
580 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)
584 BeginMessage(pszCommand);
585 vSend << a1 << a2 << a3 << a4 << a5 << a6 << a7 << a8 << a9;
596 void PushRequest(const char* pszCommand,
597 void (*fn)(void*, CDataStream&), void* param1)
600 RAND_bytes((unsigned char*)&hashReply, sizeof(hashReply));
603 LOCK(cs_mapRequests);
604 mapRequests[hashReply] = CRequestTracker(fn, param1);
607 PushMessage(pszCommand, hashReply);
610 template<typename T1>
611 void PushRequest(const char* pszCommand, const T1& a1,
612 void (*fn)(void*, CDataStream&), void* param1)
615 RAND_bytes((unsigned char*)&hashReply, sizeof(hashReply));
618 LOCK(cs_mapRequests);
619 mapRequests[hashReply] = CRequestTracker(fn, param1);
622 PushMessage(pszCommand, hashReply, a1);
625 template<typename T1, typename T2>
626 void PushRequest(const char* pszCommand, const T1& a1, const T2& a2,
627 void (*fn)(void*, CDataStream&), void* param1)
630 RAND_bytes((unsigned char*)&hashReply, sizeof(hashReply));
633 LOCK(cs_mapRequests);
634 mapRequests[hashReply] = CRequestTracker(fn, param1);
637 PushMessage(pszCommand, hashReply, a1, a2);
642 void PushGetBlocks(CBlockIndex* pindexBegin, uint256 hashEnd);
643 bool IsSubscribed(unsigned int nChannel);
644 void Subscribe(unsigned int nChannel, unsigned int nHops=0);
645 void CancelSubscribe(unsigned int nChannel);
646 void CloseSocketDisconnect();
650 // Denial-of-service detection/prevention
651 // The idea is to detect peers that are behaving
652 // badly and disconnect/ban them, but do it in a
653 // one-coding-mistake-won't-shatter-the-entire-network
655 // IMPORTANT: There should be nothing I can give a
656 // node that it will forward on that will make that
657 // node's peers drop it. If there is, an attacker
658 // can isolate a node and/or try to split the network.
659 // Dropping a node for sending stuff that is invalid
660 // now but might be valid in a later version is also
661 // dangerous, because it can cause a network split
662 // between nodes running old code and nodes running
664 static void ClearBanned(); // needed for unit testing
665 static bool IsBanned(CNetAddr ip);
666 bool Misbehaving(int howmuch); // 1 == a little, 100 == a lot
667 void copyStats(CNodeStats &stats);
669 static void RecordBytesRecv(uint64_t bytes);
670 static void RecordBytesSent(uint64_t bytes);
672 static uint64_t GetTotalBytesRecv();
673 static uint64_t GetTotalBytesSent();
676 inline void RelayInventory(const CInv& inv)
678 // Put on lists to offer to the other nodes
681 BOOST_FOREACH(CNode* pnode, vNodes)
682 pnode->PushInventory(inv);
687 void RelayTransaction(const CTransaction& tx, const uint256& hash);
688 void RelayTransaction(const CTransaction& tx, const uint256& hash, const CDataStream& ss);