1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2011 The Bitcoin developers
3 // Distributed under the MIT/X11 software license, see the accompanying
4 // file license.txt 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>
21 class CRequestTracker;
24 extern int nBestHeight;
28 inline unsigned int ReceiveBufferSize() { return 1000*GetArg("-maxreceivebuffer", 10*1000); }
29 inline unsigned int SendBufferSize() { return 1000*GetArg("-maxsendbuffer", 10*1000); }
30 static const unsigned int PUBLISH_HOPS = 5;
32 bool GetMyExternalIP(CNetAddr& ipRet);
33 bool AddAddress(CAddress addr, int64 nTimePenalty=0, CAddrDB *pAddrDB=NULL);
34 void AddressCurrentlyConnected(const CService& addr);
35 CNode* FindNode(const CNetAddr& ip);
36 CNode* FindNode(const CService& ip);
37 CNode* ConnectNode(CAddress addrConnect, int64 nTimeout=0);
38 void AbandonRequests(void (*fn)(void*, CDataStream&), void* param1);
39 bool AnySubscribed(unsigned int nChannel);
40 void MapPort(bool fMapPort);
41 bool BindListenPort(std::string& strError=REF(std::string()));
42 void StartNode(void* parg);
54 void (*fn)(void*, CDataStream&);
57 explicit CRequestTracker(void (*fnIn)(void*, CDataStream&)=NULL, void* param1In=NULL)
74 extern bool fAllowDNS;
75 extern uint64 nLocalServices;
76 extern CAddress addrLocalHost;
77 extern uint64 nLocalHostNonce;
78 extern boost::array<int, 10> vnThreadsRunning;
80 extern std::vector<CNode*> vNodes;
81 extern CCriticalSection cs_vNodes;
82 extern std::map<std::vector<unsigned char>, CAddress> mapAddresses;
83 extern CCriticalSection cs_mapAddresses;
84 extern std::map<CInv, CDataStream> mapRelay;
85 extern std::deque<std::pair<int64, CInv> > vRelayExpiration;
86 extern CCriticalSection cs_mapRelay;
87 extern std::map<CInv, int64> mapAlreadyAskedFor;
103 CCriticalSection cs_vSend;
104 CCriticalSection cs_vRecv;
107 int64 nLastSendEmpty;
108 int64 nTimeConnected;
109 unsigned int nHeaderStart;
110 unsigned int nMessageStart;
113 std::string strSubVer;
117 bool fSuccessfullyConnected;
122 // Denial-of-service detection/prevention
123 // Key is ip address, value is banned-until-time
124 static std::map<CNetAddr, int64> setBanned;
125 static CCriticalSection cs_setBanned;
130 std::map<uint256, CRequestTracker> mapRequests;
131 CCriticalSection cs_mapRequests;
132 uint256 hashContinue;
133 CBlockIndex* pindexLastGetBlocksBegin;
134 uint256 hashLastGetBlocksEnd;
138 std::vector<CAddress> vAddrToSend;
139 std::set<CAddress> setAddrKnown;
141 std::set<uint256> setKnown;
143 // inventory based relay
144 std::set<CInv> setInventoryKnown;
145 std::vector<CInv> vInventoryToSend;
146 CCriticalSection cs_inventory;
147 std::multimap<int64, CInv> mapAskFor;
149 // publish and subscription
150 std::vector<char> vfSubscribe;
152 CNode(SOCKET hSocketIn, CAddress addrIn, bool fInboundIn=false)
156 vSend.SetType(SER_NETWORK);
158 vRecv.SetType(SER_NETWORK);
160 // Version 0.2 obsoletes 20 Feb 2012
161 if (GetTime() > 1329696000)
163 vSend.SetVersion(209);
164 vRecv.SetVersion(209);
168 nLastSendEmpty = GetTime();
169 nTimeConnected = GetTime();
175 fClient = false; // set by version message
176 fInbound = fInboundIn;
177 fNetworkNode = false;
178 fSuccessfullyConnected = false;
183 pindexLastGetBlocksBegin = 0;
184 hashLastGetBlocksEnd = 0;
185 nStartingHeight = -1;
187 vfSubscribe.assign(256, false);
190 // Be shy and don't send version until we hear
197 if (hSocket != INVALID_SOCKET)
199 closesocket(hSocket);
200 hSocket = INVALID_SOCKET;
206 void operator=(const CNode&);
212 return std::max(nRefCount, 0) + (GetTime() < nReleaseTime ? 1 : 0);
215 CNode* AddRef(int64 nTimeout=0)
218 nReleaseTime = std::max(nReleaseTime, GetTime() + nTimeout);
231 void AddAddressKnown(const CAddress& addr)
233 setAddrKnown.insert(addr);
236 void PushAddress(const CAddress& addr)
238 // Known checking here is only to save space from duplicates.
239 // SendMessages will filter it again for knowns that were added
240 // after addresses were pushed.
241 if (addr.IsValid() && !setAddrKnown.count(addr))
242 vAddrToSend.push_back(addr);
246 void AddInventoryKnown(const CInv& inv)
248 CRITICAL_BLOCK(cs_inventory)
249 setInventoryKnown.insert(inv);
252 void PushInventory(const CInv& inv)
254 CRITICAL_BLOCK(cs_inventory)
255 if (!setInventoryKnown.count(inv))
256 vInventoryToSend.push_back(inv);
259 void AskFor(const CInv& inv)
261 // We're using mapAskFor as a priority queue,
262 // the key is the earliest time the request can be sent
263 int64& nRequestTime = mapAlreadyAskedFor[inv];
264 printf("askfor %s %"PRI64d"\n", inv.ToString().c_str(), nRequestTime);
266 // Make sure not to reuse time indexes to keep things in the same order
267 int64 nNow = (GetTime() - 1) * 1000000;
268 static int64 nLastTime;
270 nNow = std::max(nNow, nLastTime);
273 // Each retry is 2 minutes after the last
274 nRequestTime = std::max(nRequestTime + 2 * 60 * 1000000, nNow);
275 mapAskFor.insert(std::make_pair(nRequestTime, inv));
280 void BeginMessage(const char* pszCommand)
282 cs_vSend.Enter("cs_vSend", __FILE__, __LINE__);
283 if (nHeaderStart != -1)
285 nHeaderStart = vSend.size();
286 vSend << CMessageHeader(pszCommand, 0);
287 nMessageStart = vSend.size();
289 printf("%s ", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());
290 printf("sending: %s ", pszCommand);
296 if (nHeaderStart == -1)
298 vSend.resize(nHeaderStart);
304 printf("(aborted)\n");
309 if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
311 printf("dropmessages DROPPING SEND MESSAGE\n");
316 if (nHeaderStart == -1)
320 unsigned int nSize = vSend.size() - nMessageStart;
321 memcpy((char*)&vSend[nHeaderStart] + offsetof(CMessageHeader, nMessageSize), &nSize, sizeof(nSize));
324 if (vSend.GetVersion() >= 209)
326 uint256 hash = Hash(vSend.begin() + nMessageStart, vSend.end());
327 unsigned int nChecksum = 0;
328 memcpy(&nChecksum, &hash, sizeof(nChecksum));
329 assert(nMessageStart - nHeaderStart >= offsetof(CMessageHeader, nChecksum) + sizeof(nChecksum));
330 memcpy((char*)&vSend[nHeaderStart] + offsetof(CMessageHeader, nChecksum), &nChecksum, sizeof(nChecksum));
334 printf("(%d bytes)\n", nSize);
342 void EndMessageAbortIfEmpty()
344 if (nHeaderStart == -1)
346 int nSize = vSend.size() - nMessageStart;
358 void PushMessage(const char* pszCommand)
362 BeginMessage(pszCommand);
372 template<typename T1>
373 void PushMessage(const char* pszCommand, const T1& a1)
377 BeginMessage(pszCommand);
388 template<typename T1, typename T2>
389 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2)
393 BeginMessage(pszCommand);
404 template<typename T1, typename T2, typename T3>
405 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3)
409 BeginMessage(pszCommand);
410 vSend << a1 << a2 << a3;
420 template<typename T1, typename T2, typename T3, typename T4>
421 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4)
425 BeginMessage(pszCommand);
426 vSend << a1 << a2 << a3 << a4;
436 template<typename T1, typename T2, typename T3, typename T4, typename T5>
437 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4, const T5& a5)
441 BeginMessage(pszCommand);
442 vSend << a1 << a2 << a3 << a4 << a5;
452 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6>
453 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4, const T5& a5, const T6& a6)
457 BeginMessage(pszCommand);
458 vSend << a1 << a2 << a3 << a4 << a5 << a6;
468 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7>
469 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)
473 BeginMessage(pszCommand);
474 vSend << a1 << a2 << a3 << a4 << a5 << a6 << a7;
484 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8>
485 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)
489 BeginMessage(pszCommand);
490 vSend << a1 << a2 << a3 << a4 << a5 << a6 << a7 << a8;
500 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9>
501 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)
505 BeginMessage(pszCommand);
506 vSend << a1 << a2 << a3 << a4 << a5 << a6 << a7 << a8 << a9;
517 void PushRequest(const char* pszCommand,
518 void (*fn)(void*, CDataStream&), void* param1)
521 RAND_bytes((unsigned char*)&hashReply, sizeof(hashReply));
523 CRITICAL_BLOCK(cs_mapRequests)
524 mapRequests[hashReply] = CRequestTracker(fn, param1);
526 PushMessage(pszCommand, hashReply);
529 template<typename T1>
530 void PushRequest(const char* pszCommand, const T1& a1,
531 void (*fn)(void*, CDataStream&), void* param1)
534 RAND_bytes((unsigned char*)&hashReply, sizeof(hashReply));
536 CRITICAL_BLOCK(cs_mapRequests)
537 mapRequests[hashReply] = CRequestTracker(fn, param1);
539 PushMessage(pszCommand, hashReply, a1);
542 template<typename T1, typename T2>
543 void PushRequest(const char* pszCommand, const T1& a1, const T2& a2,
544 void (*fn)(void*, CDataStream&), void* param1)
547 RAND_bytes((unsigned char*)&hashReply, sizeof(hashReply));
549 CRITICAL_BLOCK(cs_mapRequests)
550 mapRequests[hashReply] = CRequestTracker(fn, param1);
552 PushMessage(pszCommand, hashReply, a1, a2);
557 void PushGetBlocks(CBlockIndex* pindexBegin, uint256 hashEnd);
558 bool IsSubscribed(unsigned int nChannel);
559 void Subscribe(unsigned int nChannel, unsigned int nHops=0);
560 void CancelSubscribe(unsigned int nChannel);
561 void CloseSocketDisconnect();
565 // Denial-of-service detection/prevention
566 // The idea is to detect peers that are behaving
567 // badly and disconnect/ban them, but do it in a
568 // one-coding-mistake-won't-shatter-the-entire-network
570 // IMPORTANT: There should be nothing I can give a
571 // node that it will forward on that will make that
572 // node's peers drop it. If there is, an attacker
573 // can isolate a node and/or try to split the network.
574 // Dropping a node for sending stuff that is invalid
575 // now but might be valid in a later version is also
576 // dangerous, because it can cause a network split
577 // between nodes running old code and nodes running
579 static void ClearBanned(); // needed for unit testing
580 static bool IsBanned(CNetAddr ip);
581 bool Misbehaving(int howmuch); // 1 == a little, 100 == a lot
593 inline void RelayInventory(const CInv& inv)
595 // Put on lists to offer to the other nodes
596 CRITICAL_BLOCK(cs_vNodes)
597 BOOST_FOREACH(CNode* pnode, vNodes)
598 pnode->PushInventory(inv);
602 void RelayMessage(const CInv& inv, const T& a)
604 CDataStream ss(SER_NETWORK);
607 RelayMessage(inv, ss);
611 inline void RelayMessage<>(const CInv& inv, const CDataStream& ss)
613 CRITICAL_BLOCK(cs_mapRelay)
615 // Expire old relay messages
616 while (!vRelayExpiration.empty() && vRelayExpiration.front().first < GetTime())
618 mapRelay.erase(vRelayExpiration.front().second);
619 vRelayExpiration.pop_front();
622 // Save original serialized message so newer versions are preserved
624 vRelayExpiration.push_back(std::make_pair(GetTime() + 15 * 60, inv));
638 // Templates for the publish and subscription system.
639 // The object being published as T& obj needs to have:
640 // a set<unsigned int> setSources member
641 // specializations of AdvertInsert and AdvertErase
642 // Currently implemented for CTable and CProduct.
646 void AdvertStartPublish(CNode* pfrom, unsigned int nChannel, unsigned int nHops, T& obj)
649 obj.setSources.insert(pfrom->addr.ip);
651 if (!AdvertInsert(obj))
655 CRITICAL_BLOCK(cs_vNodes)
656 BOOST_FOREACH(CNode* pnode, vNodes)
657 if (pnode != pfrom && (nHops < PUBLISH_HOPS || pnode->IsSubscribed(nChannel)))
658 pnode->PushMessage("publish", nChannel, nHops, obj);
662 void AdvertStopPublish(CNode* pfrom, unsigned int nChannel, unsigned int nHops, T& obj)
664 uint256 hash = obj.GetHash();
666 CRITICAL_BLOCK(cs_vNodes)
667 BOOST_FOREACH(CNode* pnode, vNodes)
668 if (pnode != pfrom && (nHops < PUBLISH_HOPS || pnode->IsSubscribed(nChannel)))
669 pnode->PushMessage("pub-cancel", nChannel, nHops, hash);
675 void AdvertRemoveSource(CNode* pfrom, unsigned int nChannel, unsigned int nHops, T& obj)
678 obj.setSources.erase(pfrom->addr.ip);
680 // If no longer supported by any sources, cancel it
681 if (obj.setSources.empty())
682 AdvertStopPublish(pfrom, nChannel, nHops, obj);