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.
10 #include <boost/array.hpp>
11 #include <boost/foreach.hpp>
13 #include <openssl/rand.h>
16 #include <arpa/inet.h>
25 class CRequestTracker;
28 extern int nBestHeight;
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);
43 unsigned short GetListenPort();
44 bool BindListenPort(const CService &bindAddr, std::string& strError=REF(std::string()));
45 void StartNode(void* parg);
50 LOCAL_NONE, // unknown
51 LOCAL_IF, // address a local interface listens on
52 LOCAL_BIND, // address explicit bound to
53 LOCAL_UPNP, // address reported by UPnP
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=)
61 void SetLimited(enum Network net, bool fLimited = true);
62 bool IsLimited(enum Network net);
63 bool IsLimited(const CNetAddr& addr);
64 bool AddLocal(const CService& addr, int nScore = LOCAL_NONE);
65 bool AddLocal(const CNetAddr& addr, int nScore = LOCAL_NONE);
66 bool SeenLocal(const CService& addr);
67 bool IsLocal(const CService& addr);
68 bool GetLocal(CService &addr, const CNetAddr *paddrPeer = NULL);
69 bool IsReachable(const CNetAddr &addr);
70 void SetReachable(enum Network net, bool fFlag = true);
71 CAddress GetLocalAddress(const CNetAddr *paddrPeer = NULL);
83 void (*fn)(void*, CDataStream&);
86 explicit CRequestTracker(void (*fnIn)(void*, CDataStream&)=NULL, void* param1In=NULL)
102 THREAD_SOCKETHANDLER,
103 THREAD_OPENCONNECTIONS,
104 THREAD_MESSAGEHANDLER,
108 THREAD_ADDEDCONNECTIONS,
118 extern bool fDiscover;
119 extern bool fUseUPnP;
120 extern uint64_t nLocalServices;
121 extern uint64_t nLocalHostNonce;
122 extern CAddress addrSeenByPeer;
123 extern boost::array<int, THREAD_MAX> vnThreadsRunning;
124 extern CAddrMan addrman;
126 extern std::vector<CNode*> vNodes;
127 extern CCriticalSection cs_vNodes;
128 extern std::vector<std::string> vAddedNodes;
129 extern CCriticalSection cs_vAddedNodes;
130 extern std::map<CInv, CDataStream> mapRelay;
131 extern std::deque<std::pair<int64_t, CInv> > vRelayExpiration;
132 extern CCriticalSection cs_mapRelay;
133 extern std::map<CInv, int64_t> mapAlreadyAskedFor;
144 int64_t nTimeConnected;
145 std::string addrName;
147 std::string strSubVer;
149 int64_t nReleaseTime;
150 int32_t nStartingHeight;
151 int32_t nMisbehavior;
161 /** Information about a peer */
172 CCriticalSection cs_vSend;
173 CCriticalSection cs_vRecv;
176 int64_t nLastSendEmpty;
177 int64_t nTimeConnected;
178 int32_t nHeaderStart;
179 uint32_t nMessageStart;
181 std::string addrName;
184 std::string strSubVer;
189 bool fSuccessfullyConnected;
191 CSemaphoreGrant grantOutbound;
195 // Denial-of-service detection/prevention
196 // Key is IP address, value is banned-until-time
197 static std::map<CNetAddr, int64_t> setBanned;
198 static CCriticalSection cs_setBanned;
202 int64_t nReleaseTime;
203 std::map<uint256, CRequestTracker> mapRequests;
204 CCriticalSection cs_mapRequests;
205 uint256 hashContinue;
206 CBlockIndex* pindexLastGetBlocksBegin;
207 uint256 hashLastGetBlocksEnd;
208 int32_t nStartingHeight;
212 std::vector<CAddress> vAddrToSend;
213 std::set<CAddress> setAddrKnown;
215 std::set<uint256> setKnown;
216 uint256 hashCheckpointKnown; // ppcoin: known sent sync-checkpoint
218 // inventory based relay
219 mruset<CInv> setInventoryKnown;
220 std::vector<CInv> vInventoryToSend;
221 CCriticalSection cs_inventory;
222 std::multimap<int64_t, CInv> mapAskFor;
224 CNode(SOCKET hSocketIn, CAddress addrIn, std::string addrNameIn = "", bool fInboundIn=false) : vSend(SER_NETWORK, MIN_PROTO_VERSION), vRecv(SER_NETWORK, MIN_PROTO_VERSION)
232 nLastSendEmpty = GetTime();
233 nTimeConnected = GetTime();
237 addrName = addrNameIn == "" ? addr.ToStringIPPort() : addrNameIn;
241 fClient = false; // set by version message
242 fInbound = fInboundIn;
243 fNetworkNode = false;
244 fSuccessfullyConnected = false;
249 pindexLastGetBlocksBegin = 0;
250 hashLastGetBlocksEnd = 0;
251 nStartingHeight = -1;
255 hashCheckpointKnown = 0;
256 setInventoryKnown.max_size((size_t)SendBufferSize() / 1000);
258 // Be shy and don't send version until we hear
259 if (hSocket != INVALID_SOCKET && !fInbound)
265 if (hSocket != INVALID_SOCKET)
267 closesocket(hSocket);
268 hSocket = INVALID_SOCKET;
274 // Network usage totals
275 static CCriticalSection cs_totalBytesRecv;
276 static CCriticalSection cs_totalBytesSent;
277 static uint64_t nTotalBytesRecv;
278 static uint64_t nTotalBytesSent;
280 void operator=(const CNode&);
286 return std::max(nRefCount, 0) + (GetTime() < nReleaseTime ? 1 : 0);
289 CNode* AddRef(int64_t nTimeout=0)
292 nReleaseTime = std::max(nReleaseTime, GetTime() + nTimeout);
305 void AddAddressKnown(const CAddress& addr)
307 setAddrKnown.insert(addr);
310 void PushAddress(const CAddress& addr)
312 // Known checking here is only to save space from duplicates.
313 // SendMessages will filter it again for knowns that were added
314 // after addresses were pushed.
315 if (addr.IsValid() && !setAddrKnown.count(addr))
316 vAddrToSend.push_back(addr);
320 void AddInventoryKnown(const CInv& inv)
324 setInventoryKnown.insert(inv);
328 void PushInventory(const CInv& inv)
332 if (!setInventoryKnown.count(inv))
333 vInventoryToSend.push_back(inv);
337 void AskFor(const CInv& inv)
339 // We're using mapAskFor as a priority queue,
340 // the key is the earliest time the request can be sent
341 int64_t& nRequestTime = mapAlreadyAskedFor[inv];
343 printf("askfor %s %" PRId64 " (%s)\n", inv.ToString().c_str(), nRequestTime, DateTimeStrFormat("%H:%M:%S", nRequestTime/1000000).c_str());
345 // Make sure not to reuse time indexes to keep things in the same order
346 int64_t nNow = (GetTime() - 1) * 1000000;
347 static int64_t nLastTime;
349 nNow = std::max(nNow, nLastTime);
352 // Each retry is 2 minutes after the last
353 nRequestTime = std::max(nRequestTime + 2 * 60 * 1000000, nNow);
354 mapAskFor.insert(std::make_pair(nRequestTime, inv));
359 void BeginMessage(const char* pszCommand)
361 ENTER_CRITICAL_SECTION(cs_vSend);
362 if (nHeaderStart != -1)
364 nHeaderStart = (int32_t)vSend.size();
365 vSend << CMessageHeader(pszCommand, 0);
366 nMessageStart = (uint32_t)vSend.size();
368 printf("sending: %s ", pszCommand);
373 if (nHeaderStart < 0)
375 vSend.resize(nHeaderStart);
378 LEAVE_CRITICAL_SECTION(cs_vSend);
381 printf("(aborted)\n");
386 if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
388 printf("dropmessages DROPPING SEND MESSAGE\n");
393 if (nHeaderStart < 0)
397 uint32_t nSize = (uint32_t) vSend.size() - nMessageStart;
398 memcpy((char*)&vSend[nHeaderStart] + CMessageHeader::MESSAGE_SIZE_OFFSET, &nSize, sizeof(nSize));
401 uint256 hash = Hash(vSend.begin() + nMessageStart, vSend.end());
402 uint32_t nChecksum = 0;
403 memcpy(&nChecksum, &hash, sizeof(nChecksum));
404 assert(nMessageStart - nHeaderStart >= CMessageHeader::CHECKSUM_OFFSET + sizeof(nChecksum));
405 memcpy((char*)&vSend[nHeaderStart] + CMessageHeader::CHECKSUM_OFFSET, &nChecksum, sizeof(nChecksum));
408 printf("(%d bytes)\n", nSize);
413 LEAVE_CRITICAL_SECTION(cs_vSend);
416 void EndMessageAbortIfEmpty()
418 if (nHeaderStart < 0)
420 int nSize = (int) vSend.size() - nMessageStart;
432 void PushMessage(const char* pszCommand)
436 BeginMessage(pszCommand);
446 template<typename T1>
447 void PushMessage(const char* pszCommand, const T1& a1)
451 BeginMessage(pszCommand);
462 template<typename T1, typename T2>
463 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2)
467 BeginMessage(pszCommand);
478 template<typename T1, typename T2, typename T3>
479 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3)
483 BeginMessage(pszCommand);
484 vSend << a1 << a2 << a3;
494 template<typename T1, typename T2, typename T3, typename T4>
495 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4)
499 BeginMessage(pszCommand);
500 vSend << a1 << a2 << a3 << a4;
510 template<typename T1, typename T2, typename T3, typename T4, typename T5>
511 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4, const T5& a5)
515 BeginMessage(pszCommand);
516 vSend << a1 << a2 << a3 << a4 << a5;
526 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6>
527 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4, const T5& a5, const T6& a6)
531 BeginMessage(pszCommand);
532 vSend << a1 << a2 << a3 << a4 << a5 << a6;
542 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7>
543 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)
547 BeginMessage(pszCommand);
548 vSend << a1 << a2 << a3 << a4 << a5 << a6 << a7;
558 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8>
559 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)
563 BeginMessage(pszCommand);
564 vSend << a1 << a2 << a3 << a4 << a5 << a6 << a7 << a8;
574 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9>
575 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)
579 BeginMessage(pszCommand);
580 vSend << a1 << a2 << a3 << a4 << a5 << a6 << a7 << a8 << a9;
591 void PushRequest(const char* pszCommand,
592 void (*fn)(void*, CDataStream&), void* param1)
595 RAND_bytes((unsigned char*)&hashReply, sizeof(hashReply));
598 LOCK(cs_mapRequests);
599 mapRequests[hashReply] = CRequestTracker(fn, param1);
602 PushMessage(pszCommand, hashReply);
605 template<typename T1>
606 void PushRequest(const char* pszCommand, const T1& a1,
607 void (*fn)(void*, CDataStream&), void* param1)
610 RAND_bytes((unsigned char*)&hashReply, sizeof(hashReply));
613 LOCK(cs_mapRequests);
614 mapRequests[hashReply] = CRequestTracker(fn, param1);
617 PushMessage(pszCommand, hashReply, a1);
620 template<typename T1, typename T2>
621 void PushRequest(const char* pszCommand, const T1& a1, const T2& a2,
622 void (*fn)(void*, CDataStream&), void* param1)
625 RAND_bytes((unsigned char*)&hashReply, sizeof(hashReply));
628 LOCK(cs_mapRequests);
629 mapRequests[hashReply] = CRequestTracker(fn, param1);
632 PushMessage(pszCommand, hashReply, a1, a2);
637 void PushGetBlocks(CBlockIndex* pindexBegin, uint256 hashEnd);
638 bool IsSubscribed(unsigned int nChannel);
639 void Subscribe(unsigned int nChannel, unsigned int nHops=0);
640 void CancelSubscribe(unsigned int nChannel);
641 void CloseSocketDisconnect();
645 // Denial-of-service detection/prevention
646 // The idea is to detect peers that are behaving
647 // badly and disconnect/ban them, but do it in a
648 // one-coding-mistake-won't-shatter-the-entire-network
650 // IMPORTANT: There should be nothing I can give a
651 // node that it will forward on that will make that
652 // node's peers drop it. If there is, an attacker
653 // can isolate a node and/or try to split the network.
654 // Dropping a node for sending stuff that is invalid
655 // now but might be valid in a later version is also
656 // dangerous, because it can cause a network split
657 // between nodes running old code and nodes running
659 static void ClearBanned(); // needed for unit testing
660 static bool IsBanned(CNetAddr ip);
661 bool Misbehaving(int howmuch); // 1 == a little, 100 == a lot
662 void copyStats(CNodeStats &stats);
664 static void RecordBytesRecv(uint64_t bytes);
665 static void RecordBytesSent(uint64_t bytes);
667 static uint64_t GetTotalBytesRecv();
668 static uint64_t GetTotalBytesSent();
671 inline void RelayInventory(const CInv& inv)
673 // Put on lists to offer to the other nodes
676 BOOST_FOREACH(CNode* pnode, vNodes)
677 pnode->PushInventory(inv);
682 void RelayTransaction(const CTransaction& tx, const uint256& hash);
683 void RelayTransaction(const CTransaction& tx, const uint256& hash, const CDataStream& ss);