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>
25 class CRequestTracker;
28 extern int nBestHeight;
30 const uint16_t nSocksDefault = 9050;
31 const uint16_t nPortZero = 0;
34 inline uint64_t ReceiveBufferSize() { return 1000*GetArg("-maxreceivebuffer", 5*1000); }
35 inline uint64_t SendBufferSize() { return 1000*GetArg("-maxsendbuffer", 1*1000); }
37 void AddOneShot(std::string strDest);
38 bool RecvLine(SOCKET hSocket, std::string& strLine);
39 bool GetMyExternalIP(CNetAddr& ipRet);
40 void AddressCurrentlyConnected(const CService& addr);
41 CNode* FindNode(const CNetAddr& ip);
42 CNode* FindNode(const CService& ip);
43 CNode* ConnectNode(CAddress addrConnect, const char *strDest = NULL, int64_t nTimeout=0);
44 bool OpenNetworkConnection(const CAddress& addrConnect, CSemaphoreGrant *grantOutbound = NULL, const char *strDest = NULL, bool fOneShot = false);
46 unsigned short GetListenPort();
47 bool BindListenPort(const CService &bindAddr, std::string& strError=REF(std::string()));
48 void StartNode(void* parg);
53 LOCAL_NONE, // unknown
54 LOCAL_IF, // address a local interface listens on
55 LOCAL_BIND, // address explicit bound to
56 LOCAL_IRC, // address reported by IRC (deprecated)
57 LOCAL_HTTP, // address reported by whatismyip.com and similar
58 LOCAL_MANUAL, // address explicitly specified (-externalip=)
64 bool IsPeerAddrLocalGood(CNode *pnode);
65 void AdvertiseLocal(CNode *pnode);
66 void SetLimited(enum Network net, bool fLimited = true);
67 bool IsLimited(enum Network net);
68 bool IsLimited(const CNetAddr& addr);
69 bool AddLocal(const CService& addr, int nScore = LOCAL_NONE);
70 bool AddLocal(const CNetAddr& addr, int nScore = LOCAL_NONE);
71 bool SeenLocal(const CService& addr);
72 bool IsLocal(const CService& addr);
73 bool GetLocal(CService &addr, const CNetAddr *paddrPeer = NULL);
74 bool IsReachable(const CNetAddr &addr);
75 void SetReachable(enum Network net, bool fFlag = true);
76 CAddress GetLocalAddress(const CNetAddr *paddrPeer = NULL);
88 void (*fn)(void*, CDataStream&);
91 explicit CRequestTracker(void (*fnIn)(void*, CDataStream&)=NULL, void* param1In=NULL)
107 THREAD_SOCKETHANDLER,
108 THREAD_OPENCONNECTIONS,
109 THREAD_MESSAGEHANDLER,
112 THREAD_ADDEDCONNECTIONS,
124 extern bool fDiscover;
125 extern bool fNoListen;
127 extern bool fDiscover;
128 extern uint64_t nLocalServices;
129 extern uint64_t nLocalHostNonce;
130 extern CAddress addrSeenByPeer;
131 extern boost::array<int, THREAD_MAX> vnThreadsRunning;
132 extern CAddrMan addrman;
134 extern std::vector<CNode*> vNodes;
135 extern CCriticalSection cs_vNodes;
136 extern std::vector<std::string> vAddedNodes;
137 extern CCriticalSection cs_vAddedNodes;
138 extern std::map<CInv, CDataStream> mapRelay;
139 extern std::deque<std::pair<int64_t, CInv> > vRelayExpiration;
140 extern CCriticalSection cs_mapRelay;
141 extern std::map<CInv, int64_t> mapAlreadyAskedFor;
152 int64_t nTimeConnected;
153 std::string addrName;
155 std::string strSubVer;
157 int64_t nReleaseTime;
158 int32_t nStartingHeight;
159 int32_t nMisbehavior;
169 /** Information about a peer */
180 CCriticalSection cs_vSend;
181 CCriticalSection cs_vRecv;
184 int64_t nLastSendEmpty;
185 int64_t nTimeConnected;
186 int32_t nHeaderStart;
187 uint32_t nMessageStart;
189 std::string addrName;
192 std::string strSubVer;
197 bool fSuccessfullyConnected;
199 CSemaphoreGrant grantOutbound;
203 // Denial-of-service detection/prevention
204 // Key is IP address, value is banned-until-time
205 static std::map<CNetAddr, int64_t> setBanned;
206 static CCriticalSection cs_setBanned;
210 int64_t nReleaseTime;
211 std::map<uint256, CRequestTracker> mapRequests;
212 CCriticalSection cs_mapRequests;
213 uint256 hashContinue;
214 CBlockIndex* pindexLastGetBlocksBegin;
215 uint256 hashLastGetBlocksEnd;
216 int32_t nStartingHeight;
220 std::vector<CAddress> vAddrToSend;
221 std::set<CAddress> setAddrKnown;
223 std::set<uint256> setKnown;
224 uint256 hashCheckpointKnown; // ppcoin: known sent sync-checkpoint
225 int64_t nNextAddrSend;
226 int64_t nNextLocalAddrSend;
227 int64_t nNextInvSend;
229 // inventory based relay
230 mruset<CInv> setInventoryKnown;
231 std::vector<CInv> vInventoryToSend;
232 CCriticalSection cs_inventory;
233 std::multimap<int64_t, CInv> mapAskFor;
235 CNode(SOCKET hSocketIn, CAddress addrIn, std::string addrNameIn = "", bool fInboundIn=false) : vSend(SER_NETWORK, MIN_PROTO_VERSION), vRecv(SER_NETWORK, MIN_PROTO_VERSION)
243 nLastSendEmpty = GetTime();
244 nTimeConnected = GetTime();
246 nMessageStart = std::numeric_limits<uint32_t>::max();
248 addrName = addrNameIn.empty() ? addr.ToStringIPPort() : addrNameIn;
252 fClient = false; // set by version message
253 fInbound = fInboundIn;
254 fNetworkNode = false;
255 fSuccessfullyConnected = false;
260 pindexLastGetBlocksBegin = 0;
261 hashLastGetBlocksEnd = 0;
262 nStartingHeight = -1;
263 nNextLocalAddrSend = 0;
269 hashCheckpointKnown = 0;
270 setInventoryKnown.max_size((size_t)SendBufferSize() / 1000);
272 // Be shy and don't send version until we hear
273 if (hSocket != INVALID_SOCKET && !fInbound)
279 if (hSocket != INVALID_SOCKET)
281 CloseSocket(hSocket);
287 // Network usage totals
288 static CCriticalSection cs_totalBytesRecv;
289 static CCriticalSection cs_totalBytesSent;
290 static uint64_t nTotalBytesRecv;
291 static uint64_t nTotalBytesSent;
293 void operator=(const CNode&);
299 return std::max(nRefCount, 0) + (GetTime() < nReleaseTime ? 1 : 0);
302 CNode* AddRef(int64_t nTimeout=0)
305 nReleaseTime = std::max(nReleaseTime, GetTime() + nTimeout);
318 void AddAddressKnown(const CAddress& addr)
320 setAddrKnown.insert(addr);
323 void PushAddress(const CAddress& addr)
325 // Known checking here is only to save space from duplicates.
326 // SendMessages will filter it again for knowns that were added
327 // after addresses were pushed.
328 if (addr.IsValid() && !setAddrKnown.count(addr))
329 vAddrToSend.push_back(addr);
333 void AddInventoryKnown(const CInv& inv)
337 setInventoryKnown.insert(inv);
341 void PushInventory(const CInv& inv)
345 if (!setInventoryKnown.count(inv))
346 vInventoryToSend.push_back(inv);
350 void AskFor(const CInv& inv)
352 // We're using mapAskFor as a priority queue,
353 // the key is the earliest time the request can be sent
354 int64_t& nRequestTime = mapAlreadyAskedFor[inv];
356 printf("askfor %s %" PRId64 " (%s)\n", inv.ToString().c_str(), nRequestTime, DateTimeStrFormat("%H:%M:%S", nRequestTime/1000000).c_str());
358 // Make sure not to reuse time indexes to keep things in the same order
359 int64_t nNow = (GetTime() - 1) * 1000000;
360 static int64_t nLastTime;
362 nNow = std::max(nNow, nLastTime);
365 // Each retry is 2 minutes after the last
366 nRequestTime = std::max(nRequestTime + 2 * 60 * 1000000, nNow);
367 mapAskFor.insert(std::make_pair(nRequestTime, inv));
372 void BeginMessage(const char* pszCommand)
374 ENTER_CRITICAL_SECTION(cs_vSend);
375 if (nHeaderStart != -1)
377 nHeaderStart = (int32_t)vSend.size();
378 vSend << CMessageHeader(pszCommand, 0);
379 nMessageStart = (uint32_t)vSend.size();
381 printf("sending: %s ", pszCommand);
386 if (nHeaderStart < 0)
388 vSend.resize(nHeaderStart);
390 nMessageStart = std::numeric_limits<uint32_t>::max();
391 LEAVE_CRITICAL_SECTION(cs_vSend);
394 printf("(aborted)\n");
399 if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
401 printf("dropmessages DROPPING SEND MESSAGE\n");
406 if (nHeaderStart < 0) {
407 LEAVE_CRITICAL_SECTION(cs_vSend);
412 uint32_t nSize = (uint32_t) vSend.size() - nMessageStart;
413 memcpy((char*)&vSend[nHeaderStart] + CMessageHeader::MESSAGE_SIZE_OFFSET, &nSize, sizeof(nSize));
416 uint256 hash = Hash(vSend.begin() + nMessageStart, vSend.end());
417 uint32_t nChecksum = 0;
418 memcpy(&nChecksum, &hash, sizeof(nChecksum));
419 assert(nMessageStart - nHeaderStart >= CMessageHeader::CHECKSUM_OFFSET + sizeof(nChecksum));
420 memcpy((char*)&vSend[nHeaderStart] + CMessageHeader::CHECKSUM_OFFSET, &nChecksum, sizeof(nChecksum));
423 printf("(%d bytes)\n", nSize);
427 nMessageStart = std::numeric_limits<uint32_t>::max();
428 LEAVE_CRITICAL_SECTION(cs_vSend);
431 void EndMessageAbortIfEmpty()
433 if (nHeaderStart < 0)
435 int nSize = (int) vSend.size() - nMessageStart;
447 void PushMessage(const char* pszCommand)
451 BeginMessage(pszCommand);
461 template<typename T1>
462 void PushMessage(const char* pszCommand, const T1& a1)
466 BeginMessage(pszCommand);
477 template<typename T1, typename T2>
478 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2)
482 BeginMessage(pszCommand);
493 template<typename T1, typename T2, typename T3>
494 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3)
498 BeginMessage(pszCommand);
499 vSend << a1 << a2 << a3;
509 template<typename T1, typename T2, typename T3, typename T4>
510 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4)
514 BeginMessage(pszCommand);
515 vSend << a1 << a2 << a3 << a4;
525 template<typename T1, typename T2, typename T3, typename T4, typename T5>
526 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4, const T5& a5)
530 BeginMessage(pszCommand);
531 vSend << a1 << a2 << a3 << a4 << a5;
541 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6>
542 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4, const T5& a5, const T6& a6)
546 BeginMessage(pszCommand);
547 vSend << a1 << a2 << a3 << a4 << a5 << a6;
557 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7>
558 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)
562 BeginMessage(pszCommand);
563 vSend << a1 << a2 << a3 << a4 << a5 << a6 << a7;
573 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8>
574 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)
578 BeginMessage(pszCommand);
579 vSend << a1 << a2 << a3 << a4 << a5 << a6 << a7 << a8;
589 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9>
590 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)
594 BeginMessage(pszCommand);
595 vSend << a1 << a2 << a3 << a4 << a5 << a6 << a7 << a8 << a9;
606 void PushRequest(const char* pszCommand,
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);
620 template<typename T1>
621 void PushRequest(const char* pszCommand, const T1& a1,
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);
635 template<typename T1, typename T2>
636 void PushRequest(const char* pszCommand, const T1& a1, const T2& a2,
637 void (*fn)(void*, CDataStream&), void* param1)
640 RAND_bytes((unsigned char*)&hashReply, sizeof(hashReply));
643 LOCK(cs_mapRequests);
644 mapRequests[hashReply] = CRequestTracker(fn, param1);
647 PushMessage(pszCommand, hashReply, a1, a2);
652 void PushGetBlocks(CBlockIndex* pindexBegin, uint256 hashEnd);
653 bool IsSubscribed(unsigned int nChannel);
654 void Subscribe(unsigned int nChannel, unsigned int nHops=0);
655 void CancelSubscribe(unsigned int nChannel);
656 void CloseSocketDisconnect();
660 // Denial-of-service detection/prevention
661 // The idea is to detect peers that are behaving
662 // badly and disconnect/ban them, but do it in a
663 // one-coding-mistake-won't-shatter-the-entire-network
665 // IMPORTANT: There should be nothing I can give a
666 // node that it will forward on that will make that
667 // node's peers drop it. If there is, an attacker
668 // can isolate a node and/or try to split the network.
669 // Dropping a node for sending stuff that is invalid
670 // now but might be valid in a later version is also
671 // dangerous, because it can cause a network split
672 // between nodes running old code and nodes running
674 static void ClearBanned(); // needed for unit testing
675 static bool IsBanned(CNetAddr ip);
676 bool Misbehaving(int howmuch); // 1 == a little, 100 == a lot
677 void copyStats(CNodeStats &stats);
679 static void RecordBytesRecv(uint64_t bytes);
680 static void RecordBytesSent(uint64_t bytes);
682 static uint64_t GetTotalBytesRecv();
683 static uint64_t GetTotalBytesSent();
686 inline void RelayInventory(const CInv& inv)
688 // Put on lists to offer to the other nodes
691 BOOST_FOREACH(CNode* pnode, vNodes)
692 pnode->PushInventory(inv);
697 void RelayTransaction(const CTransaction& tx, const uint256& hash);
698 void RelayTransaction(const CTransaction& tx, const uint256& hash, const CDataStream& ss);
701 /** Return a timestamp in the future (in microseconds) for exponentially distributed events. */
702 int64_t PoissonNextSend(int64_t nNow, int average_interval_seconds);