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);
42 bool OpenNetworkConnection(const CAddress& addrConnect, CSemaphoreGrant *grantOutbound = NULL, const char *strDest = NULL, bool fOneShot = false);
44 unsigned short GetListenPort();
45 bool BindListenPort(const CService &bindAddr, std::string& strError=REF(std::string()));
46 void StartNode(void* parg);
51 LOCAL_NONE, // unknown
52 LOCAL_IF, // address a local interface listens on
53 LOCAL_BIND, // address explicit bound to
54 LOCAL_UPNP, // address reported by UPnP
55 LOCAL_IRC, // address reported by IRC (deprecated)
56 LOCAL_HTTP, // address reported by whatismyip.com and similar
57 LOCAL_MANUAL, // address explicitly specified (-externalip=)
62 void SetLimited(enum Network net, bool fLimited = true);
63 bool IsLimited(enum Network net);
64 bool IsLimited(const CNetAddr& addr);
65 bool AddLocal(const CService& addr, int nScore = LOCAL_NONE);
66 bool AddLocal(const CNetAddr& addr, int nScore = LOCAL_NONE);
67 bool SeenLocal(const CService& addr);
68 bool IsLocal(const CService& addr);
69 bool GetLocal(CService &addr, const CNetAddr *paddrPeer = NULL);
70 bool IsReachable(const CNetAddr &addr);
71 void SetReachable(enum Network net, bool fFlag = true);
72 CAddress GetLocalAddress(const CNetAddr *paddrPeer = NULL);
84 void (*fn)(void*, CDataStream&);
87 explicit CRequestTracker(void (*fnIn)(void*, CDataStream&)=NULL, void* param1In=NULL)
103 THREAD_SOCKETHANDLER,
104 THREAD_OPENCONNECTIONS,
105 THREAD_MESSAGEHANDLER,
109 THREAD_ADDEDCONNECTIONS,
119 extern bool fDiscover;
120 extern bool fUseUPnP;
121 extern uint64_t nLocalServices;
122 extern uint64_t nLocalHostNonce;
123 extern CAddress addrSeenByPeer;
124 extern boost::array<int, THREAD_MAX> vnThreadsRunning;
125 extern CAddrMan addrman;
127 extern std::vector<CNode*> vNodes;
128 extern CCriticalSection cs_vNodes;
129 extern std::vector<std::string> vAddedNodes;
130 extern CCriticalSection cs_vAddedNodes;
131 extern std::map<CInv, CDataStream> mapRelay;
132 extern std::deque<std::pair<int64_t, CInv> > vRelayExpiration;
133 extern CCriticalSection cs_mapRelay;
134 extern std::map<CInv, int64_t> mapAlreadyAskedFor;
145 int64_t nTimeConnected;
146 std::string addrName;
148 std::string strSubVer;
150 int64_t nReleaseTime;
151 int32_t nStartingHeight;
152 int32_t nMisbehavior;
162 /** Information about a peer */
173 CCriticalSection cs_vSend;
174 CCriticalSection cs_vRecv;
177 int64_t nLastSendEmpty;
178 int64_t nTimeConnected;
179 int32_t nHeaderStart;
180 uint32_t nMessageStart;
182 std::string addrName;
185 std::string strSubVer;
190 bool fSuccessfullyConnected;
192 CSemaphoreGrant grantOutbound;
196 // Denial-of-service detection/prevention
197 // Key is IP address, value is banned-until-time
198 static std::map<CNetAddr, int64_t> setBanned;
199 static CCriticalSection cs_setBanned;
203 int64_t nReleaseTime;
204 std::map<uint256, CRequestTracker> mapRequests;
205 CCriticalSection cs_mapRequests;
206 uint256 hashContinue;
207 CBlockIndex* pindexLastGetBlocksBegin;
208 uint256 hashLastGetBlocksEnd;
209 int32_t nStartingHeight;
213 std::vector<CAddress> vAddrToSend;
214 std::set<CAddress> setAddrKnown;
216 std::set<uint256> setKnown;
217 uint256 hashCheckpointKnown; // ppcoin: known sent sync-checkpoint
219 // inventory based relay
220 mruset<CInv> setInventoryKnown;
221 std::vector<CInv> vInventoryToSend;
222 CCriticalSection cs_inventory;
223 std::multimap<int64_t, CInv> mapAskFor;
225 CNode(SOCKET hSocketIn, CAddress addrIn, std::string addrNameIn = "", bool fInboundIn=false) : vSend(SER_NETWORK, MIN_PROTO_VERSION), vRecv(SER_NETWORK, MIN_PROTO_VERSION)
233 nLastSendEmpty = GetTime();
234 nTimeConnected = GetTime();
238 addrName = addrNameIn == "" ? addr.ToStringIPPort() : addrNameIn;
242 fClient = false; // set by version message
243 fInbound = fInboundIn;
244 fNetworkNode = false;
245 fSuccessfullyConnected = false;
250 pindexLastGetBlocksBegin = 0;
251 hashLastGetBlocksEnd = 0;
252 nStartingHeight = -1;
256 hashCheckpointKnown = 0;
257 setInventoryKnown.max_size((size_t)SendBufferSize() / 1000);
259 // Be shy and don't send version until we hear
260 if (hSocket != INVALID_SOCKET && !fInbound)
266 if (hSocket != INVALID_SOCKET)
268 closesocket(hSocket);
269 hSocket = INVALID_SOCKET;
275 // Network usage totals
276 static CCriticalSection cs_totalBytesRecv;
277 static CCriticalSection cs_totalBytesSent;
278 static uint64_t nTotalBytesRecv;
279 static uint64_t nTotalBytesSent;
281 void operator=(const CNode&);
287 return std::max(nRefCount, 0) + (GetTime() < nReleaseTime ? 1 : 0);
290 CNode* AddRef(int64_t nTimeout=0)
293 nReleaseTime = std::max(nReleaseTime, GetTime() + nTimeout);
306 void AddAddressKnown(const CAddress& addr)
308 setAddrKnown.insert(addr);
311 void PushAddress(const CAddress& addr)
313 // Known checking here is only to save space from duplicates.
314 // SendMessages will filter it again for knowns that were added
315 // after addresses were pushed.
316 if (addr.IsValid() && !setAddrKnown.count(addr))
317 vAddrToSend.push_back(addr);
321 void AddInventoryKnown(const CInv& inv)
325 setInventoryKnown.insert(inv);
329 void PushInventory(const CInv& inv)
333 if (!setInventoryKnown.count(inv))
334 vInventoryToSend.push_back(inv);
338 void AskFor(const CInv& inv)
340 // We're using mapAskFor as a priority queue,
341 // the key is the earliest time the request can be sent
342 int64_t& nRequestTime = mapAlreadyAskedFor[inv];
344 printf("askfor %s %" PRId64 " (%s)\n", inv.ToString().c_str(), nRequestTime, DateTimeStrFormat("%H:%M:%S", nRequestTime/1000000).c_str());
346 // Make sure not to reuse time indexes to keep things in the same order
347 int64_t nNow = (GetTime() - 1) * 1000000;
348 static int64_t nLastTime;
350 nNow = std::max(nNow, nLastTime);
353 // Each retry is 2 minutes after the last
354 nRequestTime = std::max(nRequestTime + 2 * 60 * 1000000, nNow);
355 mapAskFor.insert(std::make_pair(nRequestTime, inv));
360 void BeginMessage(const char* pszCommand)
362 ENTER_CRITICAL_SECTION(cs_vSend);
363 if (nHeaderStart != -1)
365 nHeaderStart = (int32_t)vSend.size();
366 vSend << CMessageHeader(pszCommand, 0);
367 nMessageStart = (uint32_t)vSend.size();
369 printf("sending: %s ", pszCommand);
374 if (nHeaderStart < 0)
376 vSend.resize(nHeaderStart);
379 LEAVE_CRITICAL_SECTION(cs_vSend);
382 printf("(aborted)\n");
387 if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
389 printf("dropmessages DROPPING SEND MESSAGE\n");
394 if (nHeaderStart < 0)
398 uint32_t nSize = (uint32_t) vSend.size() - nMessageStart;
399 memcpy((char*)&vSend[nHeaderStart] + CMessageHeader::MESSAGE_SIZE_OFFSET, &nSize, sizeof(nSize));
402 uint256 hash = Hash(vSend.begin() + nMessageStart, vSend.end());
403 uint32_t nChecksum = 0;
404 memcpy(&nChecksum, &hash, sizeof(nChecksum));
405 assert(nMessageStart - nHeaderStart >= CMessageHeader::CHECKSUM_OFFSET + sizeof(nChecksum));
406 memcpy((char*)&vSend[nHeaderStart] + CMessageHeader::CHECKSUM_OFFSET, &nChecksum, sizeof(nChecksum));
409 printf("(%d bytes)\n", nSize);
414 LEAVE_CRITICAL_SECTION(cs_vSend);
417 void EndMessageAbortIfEmpty()
419 if (nHeaderStart < 0)
421 int nSize = (int) vSend.size() - nMessageStart;
433 void PushMessage(const char* pszCommand)
437 BeginMessage(pszCommand);
447 template<typename T1>
448 void PushMessage(const char* pszCommand, const T1& a1)
452 BeginMessage(pszCommand);
463 template<typename T1, typename T2>
464 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2)
468 BeginMessage(pszCommand);
479 template<typename T1, typename T2, typename T3>
480 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3)
484 BeginMessage(pszCommand);
485 vSend << a1 << a2 << a3;
495 template<typename T1, typename T2, typename T3, typename T4>
496 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4)
500 BeginMessage(pszCommand);
501 vSend << a1 << a2 << a3 << a4;
511 template<typename T1, typename T2, typename T3, typename T4, typename T5>
512 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4, const T5& a5)
516 BeginMessage(pszCommand);
517 vSend << a1 << a2 << a3 << a4 << a5;
527 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6>
528 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4, const T5& a5, const T6& a6)
532 BeginMessage(pszCommand);
533 vSend << a1 << a2 << a3 << a4 << a5 << a6;
543 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7>
544 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)
548 BeginMessage(pszCommand);
549 vSend << a1 << a2 << a3 << a4 << a5 << a6 << a7;
559 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8>
560 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)
564 BeginMessage(pszCommand);
565 vSend << a1 << a2 << a3 << a4 << a5 << a6 << a7 << a8;
575 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9>
576 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)
580 BeginMessage(pszCommand);
581 vSend << a1 << a2 << a3 << a4 << a5 << a6 << a7 << a8 << a9;
592 void PushRequest(const char* pszCommand,
593 void (*fn)(void*, CDataStream&), void* param1)
596 RAND_bytes((unsigned char*)&hashReply, sizeof(hashReply));
599 LOCK(cs_mapRequests);
600 mapRequests[hashReply] = CRequestTracker(fn, param1);
603 PushMessage(pszCommand, hashReply);
606 template<typename T1>
607 void PushRequest(const char* pszCommand, const T1& a1,
608 void (*fn)(void*, CDataStream&), void* param1)
611 RAND_bytes((unsigned char*)&hashReply, sizeof(hashReply));
614 LOCK(cs_mapRequests);
615 mapRequests[hashReply] = CRequestTracker(fn, param1);
618 PushMessage(pszCommand, hashReply, a1);
621 template<typename T1, typename T2>
622 void PushRequest(const char* pszCommand, const T1& a1, const T2& a2,
623 void (*fn)(void*, CDataStream&), void* param1)
626 RAND_bytes((unsigned char*)&hashReply, sizeof(hashReply));
629 LOCK(cs_mapRequests);
630 mapRequests[hashReply] = CRequestTracker(fn, param1);
633 PushMessage(pszCommand, hashReply, a1, a2);
638 void PushGetBlocks(CBlockIndex* pindexBegin, uint256 hashEnd);
639 bool IsSubscribed(unsigned int nChannel);
640 void Subscribe(unsigned int nChannel, unsigned int nHops=0);
641 void CancelSubscribe(unsigned int nChannel);
642 void CloseSocketDisconnect();
646 // Denial-of-service detection/prevention
647 // The idea is to detect peers that are behaving
648 // badly and disconnect/ban them, but do it in a
649 // one-coding-mistake-won't-shatter-the-entire-network
651 // IMPORTANT: There should be nothing I can give a
652 // node that it will forward on that will make that
653 // node's peers drop it. If there is, an attacker
654 // can isolate a node and/or try to split the network.
655 // Dropping a node for sending stuff that is invalid
656 // now but might be valid in a later version is also
657 // dangerous, because it can cause a network split
658 // between nodes running old code and nodes running
660 static void ClearBanned(); // needed for unit testing
661 static bool IsBanned(CNetAddr ip);
662 bool Misbehaving(int howmuch); // 1 == a little, 100 == a lot
663 void copyStats(CNodeStats &stats);
665 static void RecordBytesRecv(uint64_t bytes);
666 static void RecordBytesSent(uint64_t bytes);
668 static uint64_t GetTotalBytesRecv();
669 static uint64_t GetTotalBytesSent();
672 inline void RelayInventory(const CInv& inv)
674 // Put on lists to offer to the other nodes
677 BOOST_FOREACH(CNode* pnode, vNodes)
678 pnode->PushInventory(inv);
683 void RelayTransaction(const CTransaction& tx, const uint256& hash);
684 void RelayTransaction(const CTransaction& tx, const uint256& hash, const CDataStream& ss);