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;
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_UPNP, // address reported by UPnP
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=)
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,
111 THREAD_ADDEDCONNECTIONS,
121 extern bool fDiscover;
122 extern bool fUseUPnP;
123 extern uint64_t nLocalServices;
124 extern uint64_t nLocalHostNonce;
125 extern CAddress addrSeenByPeer;
126 extern boost::array<int, THREAD_MAX> vnThreadsRunning;
127 extern CAddrMan addrman;
129 extern std::vector<CNode*> vNodes;
130 extern CCriticalSection cs_vNodes;
131 extern std::vector<std::string> vAddedNodes;
132 extern CCriticalSection cs_vAddedNodes;
133 extern std::map<CInv, CDataStream> mapRelay;
134 extern std::deque<std::pair<int64_t, CInv> > vRelayExpiration;
135 extern CCriticalSection cs_mapRelay;
136 extern std::map<CInv, int64_t> mapAlreadyAskedFor;
147 int64_t nTimeConnected;
148 std::string addrName;
150 std::string strSubVer;
152 int64_t nReleaseTime;
153 int32_t nStartingHeight;
154 int32_t nMisbehavior;
164 /** Information about a peer */
175 CCriticalSection cs_vSend;
176 CCriticalSection cs_vRecv;
179 int64_t nLastSendEmpty;
180 int64_t nTimeConnected;
181 int32_t nHeaderStart;
182 uint32_t nMessageStart;
184 std::string addrName;
187 std::string strSubVer;
192 bool fSuccessfullyConnected;
194 CSemaphoreGrant grantOutbound;
198 // Denial-of-service detection/prevention
199 // Key is IP address, value is banned-until-time
200 static std::map<CNetAddr, int64_t> setBanned;
201 static CCriticalSection cs_setBanned;
205 int64_t nReleaseTime;
206 std::map<uint256, CRequestTracker> mapRequests;
207 CCriticalSection cs_mapRequests;
208 uint256 hashContinue;
209 CBlockIndex* pindexLastGetBlocksBegin;
210 uint256 hashLastGetBlocksEnd;
211 int32_t nStartingHeight;
215 std::vector<CAddress> vAddrToSend;
216 std::set<CAddress> setAddrKnown;
218 std::set<uint256> setKnown;
219 uint256 hashCheckpointKnown; // ppcoin: known sent sync-checkpoint
221 // inventory based relay
222 mruset<CInv> setInventoryKnown;
223 std::vector<CInv> vInventoryToSend;
224 CCriticalSection cs_inventory;
225 std::multimap<int64_t, CInv> mapAskFor;
227 CNode(SOCKET hSocketIn, CAddress addrIn, std::string addrNameIn = "", bool fInboundIn=false) : vSend(SER_NETWORK, MIN_PROTO_VERSION), vRecv(SER_NETWORK, MIN_PROTO_VERSION)
235 nLastSendEmpty = GetTime();
236 nTimeConnected = GetTime();
238 nMessageStart = std::numeric_limits<uint32_t>::max();
240 addrName = addrNameIn == "" ? addr.ToStringIPPort() : addrNameIn;
244 fClient = false; // set by version message
245 fInbound = fInboundIn;
246 fNetworkNode = false;
247 fSuccessfullyConnected = false;
252 pindexLastGetBlocksBegin = 0;
253 hashLastGetBlocksEnd = 0;
254 nStartingHeight = -1;
258 hashCheckpointKnown = 0;
259 setInventoryKnown.max_size((size_t)SendBufferSize() / 1000);
261 // Be shy and don't send version until we hear
262 if (hSocket != INVALID_SOCKET && !fInbound)
268 if (hSocket != INVALID_SOCKET)
270 closesocket(hSocket);
271 hSocket = INVALID_SOCKET;
277 // Network usage totals
278 static CCriticalSection cs_totalBytesRecv;
279 static CCriticalSection cs_totalBytesSent;
280 static uint64_t nTotalBytesRecv;
281 static uint64_t nTotalBytesSent;
283 void operator=(const CNode&);
289 return std::max(nRefCount, 0) + (GetTime() < nReleaseTime ? 1 : 0);
292 CNode* AddRef(int64_t nTimeout=0)
295 nReleaseTime = std::max(nReleaseTime, GetTime() + nTimeout);
308 void AddAddressKnown(const CAddress& addr)
310 setAddrKnown.insert(addr);
313 void PushAddress(const CAddress& addr)
315 // Known checking here is only to save space from duplicates.
316 // SendMessages will filter it again for knowns that were added
317 // after addresses were pushed.
318 if (addr.IsValid() && !setAddrKnown.count(addr))
319 vAddrToSend.push_back(addr);
323 void AddInventoryKnown(const CInv& inv)
327 setInventoryKnown.insert(inv);
331 void PushInventory(const CInv& inv)
335 if (!setInventoryKnown.count(inv))
336 vInventoryToSend.push_back(inv);
340 void AskFor(const CInv& inv)
342 // We're using mapAskFor as a priority queue,
343 // the key is the earliest time the request can be sent
344 int64_t& nRequestTime = mapAlreadyAskedFor[inv];
346 printf("askfor %s %" PRId64 " (%s)\n", inv.ToString().c_str(), nRequestTime, DateTimeStrFormat("%H:%M:%S", nRequestTime/1000000).c_str());
348 // Make sure not to reuse time indexes to keep things in the same order
349 int64_t nNow = (GetTime() - 1) * 1000000;
350 static int64_t nLastTime;
352 nNow = std::max(nNow, nLastTime);
355 // Each retry is 2 minutes after the last
356 nRequestTime = std::max(nRequestTime + 2 * 60 * 1000000, nNow);
357 mapAskFor.insert(std::make_pair(nRequestTime, inv));
362 void BeginMessage(const char* pszCommand)
364 ENTER_CRITICAL_SECTION(cs_vSend);
365 if (nHeaderStart != -1)
367 nHeaderStart = (int32_t)vSend.size();
368 vSend << CMessageHeader(pszCommand, 0);
369 nMessageStart = (uint32_t)vSend.size();
371 printf("sending: %s ", pszCommand);
376 if (nHeaderStart < 0)
378 vSend.resize(nHeaderStart);
380 nMessageStart = std::numeric_limits<uint32_t>::max();
381 LEAVE_CRITICAL_SECTION(cs_vSend);
384 printf("(aborted)\n");
389 if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
391 printf("dropmessages DROPPING SEND MESSAGE\n");
396 if (nHeaderStart < 0)
400 uint32_t nSize = (uint32_t) vSend.size() - nMessageStart;
401 memcpy((char*)&vSend[nHeaderStart] + CMessageHeader::MESSAGE_SIZE_OFFSET, &nSize, sizeof(nSize));
404 uint256 hash = Hash(vSend.begin() + nMessageStart, vSend.end());
405 uint32_t nChecksum = 0;
406 memcpy(&nChecksum, &hash, sizeof(nChecksum));
407 assert(nMessageStart - nHeaderStart >= CMessageHeader::CHECKSUM_OFFSET + sizeof(nChecksum));
408 memcpy((char*)&vSend[nHeaderStart] + CMessageHeader::CHECKSUM_OFFSET, &nChecksum, sizeof(nChecksum));
411 printf("(%d bytes)\n", nSize);
415 nMessageStart = std::numeric_limits<uint32_t>::max();
416 LEAVE_CRITICAL_SECTION(cs_vSend);
419 void EndMessageAbortIfEmpty()
421 if (nHeaderStart < 0)
423 int nSize = (int) vSend.size() - nMessageStart;
435 void PushMessage(const char* pszCommand)
439 BeginMessage(pszCommand);
449 template<typename T1>
450 void PushMessage(const char* pszCommand, const T1& a1)
454 BeginMessage(pszCommand);
465 template<typename T1, typename T2>
466 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2)
470 BeginMessage(pszCommand);
481 template<typename T1, typename T2, typename T3>
482 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3)
486 BeginMessage(pszCommand);
487 vSend << a1 << a2 << a3;
497 template<typename T1, typename T2, typename T3, typename T4>
498 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4)
502 BeginMessage(pszCommand);
503 vSend << a1 << a2 << a3 << a4;
513 template<typename T1, typename T2, typename T3, typename T4, typename T5>
514 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4, const T5& a5)
518 BeginMessage(pszCommand);
519 vSend << a1 << a2 << a3 << a4 << a5;
529 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6>
530 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4, const T5& a5, const T6& a6)
534 BeginMessage(pszCommand);
535 vSend << a1 << a2 << a3 << a4 << a5 << a6;
545 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7>
546 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)
550 BeginMessage(pszCommand);
551 vSend << a1 << a2 << a3 << a4 << a5 << a6 << a7;
561 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8>
562 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)
566 BeginMessage(pszCommand);
567 vSend << a1 << a2 << a3 << a4 << a5 << a6 << a7 << a8;
577 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9>
578 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)
582 BeginMessage(pszCommand);
583 vSend << a1 << a2 << a3 << a4 << a5 << a6 << a7 << a8 << a9;
594 void PushRequest(const char* pszCommand,
595 void (*fn)(void*, CDataStream&), void* param1)
598 RAND_bytes((unsigned char*)&hashReply, sizeof(hashReply));
601 LOCK(cs_mapRequests);
602 mapRequests[hashReply] = CRequestTracker(fn, param1);
605 PushMessage(pszCommand, hashReply);
608 template<typename T1>
609 void PushRequest(const char* pszCommand, const T1& a1,
610 void (*fn)(void*, CDataStream&), void* param1)
613 RAND_bytes((unsigned char*)&hashReply, sizeof(hashReply));
616 LOCK(cs_mapRequests);
617 mapRequests[hashReply] = CRequestTracker(fn, param1);
620 PushMessage(pszCommand, hashReply, a1);
623 template<typename T1, typename T2>
624 void PushRequest(const char* pszCommand, const T1& a1, const T2& a2,
625 void (*fn)(void*, CDataStream&), void* param1)
628 RAND_bytes((unsigned char*)&hashReply, sizeof(hashReply));
631 LOCK(cs_mapRequests);
632 mapRequests[hashReply] = CRequestTracker(fn, param1);
635 PushMessage(pszCommand, hashReply, a1, a2);
640 void PushGetBlocks(CBlockIndex* pindexBegin, uint256 hashEnd);
641 bool IsSubscribed(unsigned int nChannel);
642 void Subscribe(unsigned int nChannel, unsigned int nHops=0);
643 void CancelSubscribe(unsigned int nChannel);
644 void CloseSocketDisconnect();
648 // Denial-of-service detection/prevention
649 // The idea is to detect peers that are behaving
650 // badly and disconnect/ban them, but do it in a
651 // one-coding-mistake-won't-shatter-the-entire-network
653 // IMPORTANT: There should be nothing I can give a
654 // node that it will forward on that will make that
655 // node's peers drop it. If there is, an attacker
656 // can isolate a node and/or try to split the network.
657 // Dropping a node for sending stuff that is invalid
658 // now but might be valid in a later version is also
659 // dangerous, because it can cause a network split
660 // between nodes running old code and nodes running
662 static void ClearBanned(); // needed for unit testing
663 static bool IsBanned(CNetAddr ip);
664 bool Misbehaving(int howmuch); // 1 == a little, 100 == a lot
665 void copyStats(CNodeStats &stats);
667 static void RecordBytesRecv(uint64_t bytes);
668 static void RecordBytesSent(uint64_t bytes);
670 static uint64_t GetTotalBytesRecv();
671 static uint64_t GetTotalBytesSent();
674 inline void RelayInventory(const CInv& inv)
676 // Put on lists to offer to the other nodes
679 BOOST_FOREACH(CNode* pnode, vNodes)
680 pnode->PushInventory(inv);
685 void RelayTransaction(const CTransaction& tx, const uint256& hash);
686 void RelayTransaction(const CTransaction& tx, const uint256& hash, const CDataStream& ss);