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,
122 extern bool fDiscover;
123 extern bool fUseUPnP;
124 extern uint64_t nLocalServices;
125 extern uint64_t nLocalHostNonce;
126 extern CAddress addrSeenByPeer;
127 extern boost::array<int, THREAD_MAX> vnThreadsRunning;
128 extern CAddrMan addrman;
130 extern std::vector<CNode*> vNodes;
131 extern CCriticalSection cs_vNodes;
132 extern std::vector<std::string> vAddedNodes;
133 extern CCriticalSection cs_vAddedNodes;
134 extern std::map<CInv, CDataStream> mapRelay;
135 extern std::deque<std::pair<int64_t, CInv> > vRelayExpiration;
136 extern CCriticalSection cs_mapRelay;
137 extern std::map<CInv, int64_t> mapAlreadyAskedFor;
148 int64_t nTimeConnected;
149 std::string addrName;
151 std::string strSubVer;
153 int64_t nReleaseTime;
154 int32_t nStartingHeight;
155 int32_t nMisbehavior;
165 /** Information about a peer */
176 CCriticalSection cs_vSend;
177 CCriticalSection cs_vRecv;
180 int64_t nLastSendEmpty;
181 int64_t nTimeConnected;
182 int32_t nHeaderStart;
183 uint32_t nMessageStart;
185 std::string addrName;
188 std::string strSubVer;
193 bool fSuccessfullyConnected;
195 CSemaphoreGrant grantOutbound;
199 // Denial-of-service detection/prevention
200 // Key is IP address, value is banned-until-time
201 static std::map<CNetAddr, int64_t> setBanned;
202 static CCriticalSection cs_setBanned;
206 int64_t nReleaseTime;
207 std::map<uint256, CRequestTracker> mapRequests;
208 CCriticalSection cs_mapRequests;
209 uint256 hashContinue;
210 CBlockIndex* pindexLastGetBlocksBegin;
211 uint256 hashLastGetBlocksEnd;
212 int32_t nStartingHeight;
216 std::vector<CAddress> vAddrToSend;
217 std::set<CAddress> setAddrKnown;
219 std::set<uint256> setKnown;
220 uint256 hashCheckpointKnown; // ppcoin: known sent sync-checkpoint
222 // inventory based relay
223 mruset<CInv> setInventoryKnown;
224 std::vector<CInv> vInventoryToSend;
225 CCriticalSection cs_inventory;
226 std::multimap<int64_t, CInv> mapAskFor;
228 CNode(SOCKET hSocketIn, CAddress addrIn, std::string addrNameIn = "", bool fInboundIn=false) : vSend(SER_NETWORK, MIN_PROTO_VERSION), vRecv(SER_NETWORK, MIN_PROTO_VERSION)
236 nLastSendEmpty = GetTime();
237 nTimeConnected = GetTime();
239 nMessageStart = std::numeric_limits<uint32_t>::max();
241 addrName = addrNameIn == "" ? addr.ToStringIPPort() : addrNameIn;
245 fClient = false; // set by version message
246 fInbound = fInboundIn;
247 fNetworkNode = false;
248 fSuccessfullyConnected = false;
253 pindexLastGetBlocksBegin = 0;
254 hashLastGetBlocksEnd = 0;
255 nStartingHeight = -1;
259 hashCheckpointKnown = 0;
260 setInventoryKnown.max_size((size_t)SendBufferSize() / 1000);
262 // Be shy and don't send version until we hear
263 if (hSocket != INVALID_SOCKET && !fInbound)
269 if (hSocket != INVALID_SOCKET)
271 closesocket(hSocket);
272 hSocket = INVALID_SOCKET;
278 // Network usage totals
279 static CCriticalSection cs_totalBytesRecv;
280 static CCriticalSection cs_totalBytesSent;
281 static uint64_t nTotalBytesRecv;
282 static uint64_t nTotalBytesSent;
284 void operator=(const CNode&);
290 return std::max(nRefCount, 0) + (GetTime() < nReleaseTime ? 1 : 0);
293 CNode* AddRef(int64_t nTimeout=0)
296 nReleaseTime = std::max(nReleaseTime, GetTime() + nTimeout);
309 void AddAddressKnown(const CAddress& addr)
311 setAddrKnown.insert(addr);
314 void PushAddress(const CAddress& addr)
316 // Known checking here is only to save space from duplicates.
317 // SendMessages will filter it again for knowns that were added
318 // after addresses were pushed.
319 if (addr.IsValid() && !setAddrKnown.count(addr))
320 vAddrToSend.push_back(addr);
324 void AddInventoryKnown(const CInv& inv)
328 setInventoryKnown.insert(inv);
332 void PushInventory(const CInv& inv)
336 if (!setInventoryKnown.count(inv))
337 vInventoryToSend.push_back(inv);
341 void AskFor(const CInv& inv)
343 // We're using mapAskFor as a priority queue,
344 // the key is the earliest time the request can be sent
345 int64_t& nRequestTime = mapAlreadyAskedFor[inv];
347 printf("askfor %s %" PRId64 " (%s)\n", inv.ToString().c_str(), nRequestTime, DateTimeStrFormat("%H:%M:%S", nRequestTime/1000000).c_str());
349 // Make sure not to reuse time indexes to keep things in the same order
350 int64_t nNow = (GetTime() - 1) * 1000000;
351 static int64_t nLastTime;
353 nNow = std::max(nNow, nLastTime);
356 // Each retry is 2 minutes after the last
357 nRequestTime = std::max(nRequestTime + 2 * 60 * 1000000, nNow);
358 mapAskFor.insert(std::make_pair(nRequestTime, inv));
363 void BeginMessage(const char* pszCommand)
365 ENTER_CRITICAL_SECTION(cs_vSend);
366 if (nHeaderStart != -1)
368 nHeaderStart = (int32_t)vSend.size();
369 vSend << CMessageHeader(pszCommand, 0);
370 nMessageStart = (uint32_t)vSend.size();
372 printf("sending: %s ", pszCommand);
377 if (nHeaderStart < 0)
379 vSend.resize(nHeaderStart);
381 nMessageStart = std::numeric_limits<uint32_t>::max();
382 LEAVE_CRITICAL_SECTION(cs_vSend);
385 printf("(aborted)\n");
390 if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
392 printf("dropmessages DROPPING SEND MESSAGE\n");
397 if (nHeaderStart < 0)
401 uint32_t nSize = (uint32_t) vSend.size() - nMessageStart;
402 memcpy((char*)&vSend[nHeaderStart] + CMessageHeader::MESSAGE_SIZE_OFFSET, &nSize, sizeof(nSize));
405 uint256 hash = Hash(vSend.begin() + nMessageStart, vSend.end());
406 uint32_t nChecksum = 0;
407 memcpy(&nChecksum, &hash, sizeof(nChecksum));
408 assert(nMessageStart - nHeaderStart >= CMessageHeader::CHECKSUM_OFFSET + sizeof(nChecksum));
409 memcpy((char*)&vSend[nHeaderStart] + CMessageHeader::CHECKSUM_OFFSET, &nChecksum, sizeof(nChecksum));
412 printf("(%d bytes)\n", nSize);
416 nMessageStart = std::numeric_limits<uint32_t>::max();
417 LEAVE_CRITICAL_SECTION(cs_vSend);
420 void EndMessageAbortIfEmpty()
422 if (nHeaderStart < 0)
424 int nSize = (int) vSend.size() - nMessageStart;
436 void PushMessage(const char* pszCommand)
440 BeginMessage(pszCommand);
450 template<typename T1>
451 void PushMessage(const char* pszCommand, const T1& a1)
455 BeginMessage(pszCommand);
466 template<typename T1, typename T2>
467 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2)
471 BeginMessage(pszCommand);
482 template<typename T1, typename T2, typename T3>
483 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3)
487 BeginMessage(pszCommand);
488 vSend << a1 << a2 << a3;
498 template<typename T1, typename T2, typename T3, typename T4>
499 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4)
503 BeginMessage(pszCommand);
504 vSend << a1 << a2 << a3 << a4;
514 template<typename T1, typename T2, typename T3, typename T4, typename T5>
515 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4, const T5& a5)
519 BeginMessage(pszCommand);
520 vSend << a1 << a2 << a3 << a4 << a5;
530 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6>
531 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4, const T5& a5, const T6& a6)
535 BeginMessage(pszCommand);
536 vSend << a1 << a2 << a3 << a4 << a5 << a6;
546 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7>
547 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)
551 BeginMessage(pszCommand);
552 vSend << a1 << a2 << a3 << a4 << a5 << a6 << a7;
562 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8>
563 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)
567 BeginMessage(pszCommand);
568 vSend << a1 << a2 << a3 << a4 << a5 << a6 << a7 << a8;
578 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9>
579 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)
583 BeginMessage(pszCommand);
584 vSend << a1 << a2 << a3 << a4 << a5 << a6 << a7 << a8 << a9;
595 void PushRequest(const char* pszCommand,
596 void (*fn)(void*, CDataStream&), void* param1)
599 RAND_bytes((unsigned char*)&hashReply, sizeof(hashReply));
602 LOCK(cs_mapRequests);
603 mapRequests[hashReply] = CRequestTracker(fn, param1);
606 PushMessage(pszCommand, hashReply);
609 template<typename T1>
610 void PushRequest(const char* pszCommand, const T1& a1,
611 void (*fn)(void*, CDataStream&), void* param1)
614 RAND_bytes((unsigned char*)&hashReply, sizeof(hashReply));
617 LOCK(cs_mapRequests);
618 mapRequests[hashReply] = CRequestTracker(fn, param1);
621 PushMessage(pszCommand, hashReply, a1);
624 template<typename T1, typename T2>
625 void PushRequest(const char* pszCommand, const T1& a1, const T2& a2,
626 void (*fn)(void*, CDataStream&), void* param1)
629 RAND_bytes((unsigned char*)&hashReply, sizeof(hashReply));
632 LOCK(cs_mapRequests);
633 mapRequests[hashReply] = CRequestTracker(fn, param1);
636 PushMessage(pszCommand, hashReply, a1, a2);
641 void PushGetBlocks(CBlockIndex* pindexBegin, uint256 hashEnd);
642 bool IsSubscribed(unsigned int nChannel);
643 void Subscribe(unsigned int nChannel, unsigned int nHops=0);
644 void CancelSubscribe(unsigned int nChannel);
645 void CloseSocketDisconnect();
649 // Denial-of-service detection/prevention
650 // The idea is to detect peers that are behaving
651 // badly and disconnect/ban them, but do it in a
652 // one-coding-mistake-won't-shatter-the-entire-network
654 // IMPORTANT: There should be nothing I can give a
655 // node that it will forward on that will make that
656 // node's peers drop it. If there is, an attacker
657 // can isolate a node and/or try to split the network.
658 // Dropping a node for sending stuff that is invalid
659 // now but might be valid in a later version is also
660 // dangerous, because it can cause a network split
661 // between nodes running old code and nodes running
663 static void ClearBanned(); // needed for unit testing
664 static bool IsBanned(CNetAddr ip);
665 bool Misbehaving(int howmuch); // 1 == a little, 100 == a lot
666 void copyStats(CNodeStats &stats);
668 static void RecordBytesRecv(uint64_t bytes);
669 static void RecordBytesSent(uint64_t bytes);
671 static uint64_t GetTotalBytesRecv();
672 static uint64_t GetTotalBytesSent();
675 inline void RelayInventory(const CInv& inv)
677 // Put on lists to offer to the other nodes
680 BOOST_FOREACH(CNode* pnode, vNodes)
681 pnode->PushInventory(inv);
686 void RelayTransaction(const CTransaction& tx, const uint256& hash);
687 void RelayTransaction(const CTransaction& tx, const uint256& hash, const CDataStream& ss);