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.
9 #include <boost/array.hpp>
10 #include <boost/foreach.hpp>
11 #include <openssl/rand.h>
14 #include <arpa/inet.h>
22 class CRequestTracker;
25 extern int nBestHeight;
29 inline unsigned int ReceiveBufferSize() { return 1000*GetArg("-maxreceivebuffer", 5*1000); }
30 inline unsigned int SendBufferSize() { return 1000*GetArg("-maxsendbuffer", 1*1000); }
32 void AddOneShot(std::string strDest);
33 bool RecvLine(SOCKET hSocket, std::string& strLine);
34 bool GetMyExternalIP(CNetAddr& ipRet);
35 void AddressCurrentlyConnected(const CService& addr);
36 CNode* FindNode(const CNetAddr& ip);
37 CNode* FindNode(const CService& ip);
38 CNode* ConnectNode(CAddress addrConnect, const char *strDest = NULL, int64 nTimeout=0);
40 unsigned short GetListenPort();
41 bool BindListenPort(const CService &bindAddr, std::string& strError=REF(std::string()));
42 void StartNode(void* parg);
47 LOCAL_NONE, // unknown
48 LOCAL_IF, // address a local interface listens on
49 LOCAL_BIND, // address explicit bound to
50 LOCAL_UPNP, // address reported by UPnP
51 LOCAL_IRC, // address reported by IRC (deprecated)
52 LOCAL_HTTP, // address reported by whatismyip.com and similar
53 LOCAL_MANUAL, // address explicitly specified (-externalip=)
58 void SetLimited(enum Network net, bool fLimited = true);
59 bool IsLimited(enum Network net);
60 bool IsLimited(const CNetAddr& addr);
61 bool AddLocal(const CService& addr, int nScore = LOCAL_NONE);
62 bool AddLocal(const CNetAddr& addr, int nScore = LOCAL_NONE);
63 bool SeenLocal(const CService& addr);
64 bool IsLocal(const CService& addr);
65 bool GetLocal(CService &addr, const CNetAddr *paddrPeer = NULL);
66 bool IsReachable(const CNetAddr &addr);
67 void SetReachable(enum Network net, bool fFlag = true);
68 CAddress GetLocalAddress(const CNetAddr *paddrPeer = NULL);
80 void (*fn)(void*, CDataStream&);
83 explicit CRequestTracker(void (*fnIn)(void*, CDataStream&)=NULL, void* param1In=NULL)
100 THREAD_OPENCONNECTIONS,
101 THREAD_MESSAGEHANDLER,
105 THREAD_ADDEDCONNECTIONS,
114 extern bool fDiscover;
115 extern bool fUseUPnP;
116 extern uint64 nLocalServices;
117 extern uint64 nLocalHostNonce;
118 extern CAddress addrSeenByPeer;
119 extern boost::array<int, THREAD_MAX> vnThreadsRunning;
120 extern CAddrMan addrman;
122 extern std::vector<CNode*> vNodes;
123 extern CCriticalSection cs_vNodes;
124 extern std::map<CInv, CDataStream> mapRelay;
125 extern std::deque<std::pair<int64, CInv> > vRelayExpiration;
126 extern CCriticalSection cs_mapRelay;
127 extern std::map<CInv, int64> mapAlreadyAskedFor;
138 int64 nTimeConnected;
139 std::string addrName;
141 std::string strSubVer;
152 /** Information about a peer */
161 CCriticalSection cs_vSend;
162 CCriticalSection cs_vRecv;
165 int64 nLastSendEmpty;
166 int64 nTimeConnected;
168 unsigned int nMessageStart;
170 std::string addrName;
173 std::string strSubVer;
178 bool fSuccessfullyConnected;
180 CSemaphoreGrant grantOutbound;
184 // Denial-of-service detection/prevention
185 // Key is IP address, value is banned-until-time
186 static std::map<CNetAddr, int64> setBanned;
187 static CCriticalSection cs_setBanned;
192 std::map<uint256, CRequestTracker> mapRequests;
193 CCriticalSection cs_mapRequests;
194 uint256 hashContinue;
195 CBlockIndex* pindexLastGetBlocksBegin;
196 uint256 hashLastGetBlocksEnd;
200 std::vector<CAddress> vAddrToSend;
201 std::set<CAddress> setAddrKnown;
203 std::set<uint256> setKnown;
204 uint256 hashCheckpointKnown; // ppcoin: known sent sync-checkpoint
206 // inventory based relay
207 mruset<CInv> setInventoryKnown;
208 std::vector<CInv> vInventoryToSend;
209 CCriticalSection cs_inventory;
210 std::multimap<int64, CInv> mapAskFor;
212 CNode(SOCKET hSocketIn, CAddress addrIn, std::string addrNameIn = "", bool fInboundIn=false) : vSend(SER_NETWORK, MIN_PROTO_VERSION), vRecv(SER_NETWORK, MIN_PROTO_VERSION)
218 nLastSendEmpty = GetTime();
219 nTimeConnected = GetTime();
223 addrName = addrNameIn == "" ? addr.ToStringIPPort() : addrNameIn;
227 fClient = false; // set by version message
228 fInbound = fInboundIn;
229 fNetworkNode = false;
230 fSuccessfullyConnected = false;
235 pindexLastGetBlocksBegin = 0;
236 hashLastGetBlocksEnd = 0;
237 nStartingHeight = -1;
240 hashCheckpointKnown = 0;
241 setInventoryKnown.max_size(SendBufferSize() / 1000);
243 // Be shy and don't send version until we hear
244 if (hSocket != INVALID_SOCKET && !fInbound)
250 if (hSocket != INVALID_SOCKET)
252 closesocket(hSocket);
253 hSocket = INVALID_SOCKET;
259 void operator=(const CNode&);
265 return std::max(nRefCount, 0) + (GetTime() < nReleaseTime ? 1 : 0);
268 CNode* AddRef(int64 nTimeout=0)
271 nReleaseTime = std::max(nReleaseTime, GetTime() + nTimeout);
284 void AddAddressKnown(const CAddress& addr)
286 setAddrKnown.insert(addr);
289 void PushAddress(const CAddress& addr)
291 // Known checking here is only to save space from duplicates.
292 // SendMessages will filter it again for knowns that were added
293 // after addresses were pushed.
294 if (addr.IsValid() && !setAddrKnown.count(addr))
295 vAddrToSend.push_back(addr);
299 void AddInventoryKnown(const CInv& inv)
303 setInventoryKnown.insert(inv);
307 void PushInventory(const CInv& inv)
311 if (!setInventoryKnown.count(inv))
312 vInventoryToSend.push_back(inv);
316 void AskFor(const CInv& inv)
318 // We're using mapAskFor as a priority queue,
319 // the key is the earliest time the request can be sent
320 int64& nRequestTime = mapAlreadyAskedFor[inv];
322 printf("askfor %s %"PRI64d" (%s)\n", inv.ToString().c_str(), nRequestTime, DateTimeStrFormat("%H:%M:%S", nRequestTime/1000000).c_str());
324 // Make sure not to reuse time indexes to keep things in the same order
325 int64 nNow = (GetTime() - 1) * 1000000;
326 static int64 nLastTime;
328 nNow = std::max(nNow, nLastTime);
331 // Each retry is 2 minutes after the last
332 nRequestTime = std::max(nRequestTime + 2 * 60 * 1000000, nNow);
333 mapAskFor.insert(std::make_pair(nRequestTime, inv));
338 void BeginMessage(const char* pszCommand)
340 ENTER_CRITICAL_SECTION(cs_vSend);
341 if (nHeaderStart != -1)
343 nHeaderStart = vSend.size();
344 vSend << CMessageHeader(pszCommand, 0);
345 nMessageStart = vSend.size();
347 printf("sending: %s ", pszCommand);
352 if (nHeaderStart < 0)
354 vSend.resize(nHeaderStart);
357 LEAVE_CRITICAL_SECTION(cs_vSend);
360 printf("(aborted)\n");
365 if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
367 printf("dropmessages DROPPING SEND MESSAGE\n");
372 if (nHeaderStart < 0)
376 unsigned int nSize = vSend.size() - nMessageStart;
377 memcpy((char*)&vSend[nHeaderStart] + CMessageHeader::MESSAGE_SIZE_OFFSET, &nSize, sizeof(nSize));
380 uint256 hash = Hash(vSend.begin() + nMessageStart, vSend.end());
381 unsigned int nChecksum = 0;
382 memcpy(&nChecksum, &hash, sizeof(nChecksum));
383 assert(nMessageStart - nHeaderStart >= CMessageHeader::CHECKSUM_OFFSET + sizeof(nChecksum));
384 memcpy((char*)&vSend[nHeaderStart] + CMessageHeader::CHECKSUM_OFFSET, &nChecksum, sizeof(nChecksum));
387 printf("(%d bytes)\n", nSize);
392 LEAVE_CRITICAL_SECTION(cs_vSend);
395 void EndMessageAbortIfEmpty()
397 if (nHeaderStart < 0)
399 int nSize = vSend.size() - nMessageStart;
411 void PushMessage(const char* pszCommand)
415 BeginMessage(pszCommand);
425 template<typename T1>
426 void PushMessage(const char* pszCommand, const T1& a1)
430 BeginMessage(pszCommand);
441 template<typename T1, typename T2>
442 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2)
446 BeginMessage(pszCommand);
457 template<typename T1, typename T2, typename T3>
458 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3)
462 BeginMessage(pszCommand);
463 vSend << a1 << a2 << a3;
473 template<typename T1, typename T2, typename T3, typename T4>
474 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4)
478 BeginMessage(pszCommand);
479 vSend << a1 << a2 << a3 << a4;
489 template<typename T1, typename T2, typename T3, typename T4, typename T5>
490 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4, const T5& a5)
494 BeginMessage(pszCommand);
495 vSend << a1 << a2 << a3 << a4 << a5;
505 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6>
506 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4, const T5& a5, const T6& a6)
510 BeginMessage(pszCommand);
511 vSend << a1 << a2 << a3 << a4 << a5 << a6;
521 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7>
522 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)
526 BeginMessage(pszCommand);
527 vSend << a1 << a2 << a3 << a4 << a5 << a6 << a7;
537 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8>
538 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)
542 BeginMessage(pszCommand);
543 vSend << a1 << a2 << a3 << a4 << a5 << a6 << a7 << a8;
553 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9>
554 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)
558 BeginMessage(pszCommand);
559 vSend << a1 << a2 << a3 << a4 << a5 << a6 << a7 << a8 << a9;
570 void PushRequest(const char* pszCommand,
571 void (*fn)(void*, CDataStream&), void* param1)
574 RAND_bytes((unsigned char*)&hashReply, sizeof(hashReply));
577 LOCK(cs_mapRequests);
578 mapRequests[hashReply] = CRequestTracker(fn, param1);
581 PushMessage(pszCommand, hashReply);
584 template<typename T1>
585 void PushRequest(const char* pszCommand, const T1& a1,
586 void (*fn)(void*, CDataStream&), void* param1)
589 RAND_bytes((unsigned char*)&hashReply, sizeof(hashReply));
592 LOCK(cs_mapRequests);
593 mapRequests[hashReply] = CRequestTracker(fn, param1);
596 PushMessage(pszCommand, hashReply, a1);
599 template<typename T1, typename T2>
600 void PushRequest(const char* pszCommand, const T1& a1, const T2& a2,
601 void (*fn)(void*, CDataStream&), void* param1)
604 RAND_bytes((unsigned char*)&hashReply, sizeof(hashReply));
607 LOCK(cs_mapRequests);
608 mapRequests[hashReply] = CRequestTracker(fn, param1);
611 PushMessage(pszCommand, hashReply, a1, a2);
616 void PushGetBlocks(CBlockIndex* pindexBegin, uint256 hashEnd);
617 bool IsSubscribed(unsigned int nChannel);
618 void Subscribe(unsigned int nChannel, unsigned int nHops=0);
619 void CancelSubscribe(unsigned int nChannel);
620 void CloseSocketDisconnect();
624 // Denial-of-service detection/prevention
625 // The idea is to detect peers that are behaving
626 // badly and disconnect/ban them, but do it in a
627 // one-coding-mistake-won't-shatter-the-entire-network
629 // IMPORTANT: There should be nothing I can give a
630 // node that it will forward on that will make that
631 // node's peers drop it. If there is, an attacker
632 // can isolate a node and/or try to split the network.
633 // Dropping a node for sending stuff that is invalid
634 // now but might be valid in a later version is also
635 // dangerous, because it can cause a network split
636 // between nodes running old code and nodes running
638 static void ClearBanned(); // needed for unit testing
639 static bool IsBanned(CNetAddr ip);
640 bool Misbehaving(int howmuch); // 1 == a little, 100 == a lot
641 void copyStats(CNodeStats &stats);
653 inline void RelayInventory(const CInv& inv)
655 // Put on lists to offer to the other nodes
658 BOOST_FOREACH(CNode* pnode, vNodes)
659 pnode->PushInventory(inv);
664 void RelayMessage(const CInv& inv, const T& a)
666 CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
669 RelayMessage(inv, ss);
673 inline void RelayMessage<>(const CInv& inv, const CDataStream& ss)
677 // Expire old relay messages
678 while (!vRelayExpiration.empty() && vRelayExpiration.front().first < GetTime())
680 mapRelay.erase(vRelayExpiration.front().second);
681 vRelayExpiration.pop_front();
684 // Save original serialized message so newer versions are preserved
685 mapRelay.insert(std::make_pair(inv, ss));
686 vRelayExpiration.push_back(std::make_pair(GetTime() + 15 * 60, inv));