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;
269 nLastTime = nNow = std::max(nNow, ++nLastTime);
271 // Each retry is 2 minutes after the last
272 nRequestTime = std::max(nRequestTime + 2 * 60 * 1000000, nNow);
273 mapAskFor.insert(std::make_pair(nRequestTime, inv));
278 void BeginMessage(const char* pszCommand)
280 cs_vSend.Enter("cs_vSend", __FILE__, __LINE__);
281 if (nHeaderStart != -1)
283 nHeaderStart = vSend.size();
284 vSend << CMessageHeader(pszCommand, 0);
285 nMessageStart = vSend.size();
287 printf("%s ", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());
288 printf("sending: %s ", pszCommand);
294 if (nHeaderStart == -1)
296 vSend.resize(nHeaderStart);
302 printf("(aborted)\n");
307 if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
309 printf("dropmessages DROPPING SEND MESSAGE\n");
314 if (nHeaderStart == -1)
318 unsigned int nSize = vSend.size() - nMessageStart;
319 memcpy((char*)&vSend[nHeaderStart] + offsetof(CMessageHeader, nMessageSize), &nSize, sizeof(nSize));
322 if (vSend.GetVersion() >= 209)
324 uint256 hash = Hash(vSend.begin() + nMessageStart, vSend.end());
325 unsigned int nChecksum = 0;
326 memcpy(&nChecksum, &hash, sizeof(nChecksum));
327 assert(nMessageStart - nHeaderStart >= offsetof(CMessageHeader, nChecksum) + sizeof(nChecksum));
328 memcpy((char*)&vSend[nHeaderStart] + offsetof(CMessageHeader, nChecksum), &nChecksum, sizeof(nChecksum));
332 printf("(%d bytes)\n", nSize);
340 void EndMessageAbortIfEmpty()
342 if (nHeaderStart == -1)
344 int nSize = vSend.size() - nMessageStart;
356 void PushMessage(const char* pszCommand)
360 BeginMessage(pszCommand);
370 template<typename T1>
371 void PushMessage(const char* pszCommand, const T1& a1)
375 BeginMessage(pszCommand);
386 template<typename T1, typename T2>
387 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2)
391 BeginMessage(pszCommand);
402 template<typename T1, typename T2, typename T3>
403 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3)
407 BeginMessage(pszCommand);
408 vSend << a1 << a2 << a3;
418 template<typename T1, typename T2, typename T3, typename T4>
419 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4)
423 BeginMessage(pszCommand);
424 vSend << a1 << a2 << a3 << a4;
434 template<typename T1, typename T2, typename T3, typename T4, typename T5>
435 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4, const T5& a5)
439 BeginMessage(pszCommand);
440 vSend << a1 << a2 << a3 << a4 << a5;
450 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6>
451 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4, const T5& a5, const T6& a6)
455 BeginMessage(pszCommand);
456 vSend << a1 << a2 << a3 << a4 << a5 << a6;
466 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7>
467 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)
471 BeginMessage(pszCommand);
472 vSend << a1 << a2 << a3 << a4 << a5 << a6 << a7;
482 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8>
483 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)
487 BeginMessage(pszCommand);
488 vSend << a1 << a2 << a3 << a4 << a5 << a6 << a7 << a8;
498 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9>
499 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)
503 BeginMessage(pszCommand);
504 vSend << a1 << a2 << a3 << a4 << a5 << a6 << a7 << a8 << a9;
515 void PushRequest(const char* pszCommand,
516 void (*fn)(void*, CDataStream&), void* param1)
519 RAND_bytes((unsigned char*)&hashReply, sizeof(hashReply));
521 CRITICAL_BLOCK(cs_mapRequests)
522 mapRequests[hashReply] = CRequestTracker(fn, param1);
524 PushMessage(pszCommand, hashReply);
527 template<typename T1>
528 void PushRequest(const char* pszCommand, const T1& a1,
529 void (*fn)(void*, CDataStream&), void* param1)
532 RAND_bytes((unsigned char*)&hashReply, sizeof(hashReply));
534 CRITICAL_BLOCK(cs_mapRequests)
535 mapRequests[hashReply] = CRequestTracker(fn, param1);
537 PushMessage(pszCommand, hashReply, a1);
540 template<typename T1, typename T2>
541 void PushRequest(const char* pszCommand, const T1& a1, const T2& a2,
542 void (*fn)(void*, CDataStream&), void* param1)
545 RAND_bytes((unsigned char*)&hashReply, sizeof(hashReply));
547 CRITICAL_BLOCK(cs_mapRequests)
548 mapRequests[hashReply] = CRequestTracker(fn, param1);
550 PushMessage(pszCommand, hashReply, a1, a2);
555 void PushGetBlocks(CBlockIndex* pindexBegin, uint256 hashEnd);
556 bool IsSubscribed(unsigned int nChannel);
557 void Subscribe(unsigned int nChannel, unsigned int nHops=0);
558 void CancelSubscribe(unsigned int nChannel);
559 void CloseSocketDisconnect();
563 // Denial-of-service detection/prevention
564 // The idea is to detect peers that are behaving
565 // badly and disconnect/ban them, but do it in a
566 // one-coding-mistake-won't-shatter-the-entire-network
568 // IMPORTANT: There should be nothing I can give a
569 // node that it will forward on that will make that
570 // node's peers drop it. If there is, an attacker
571 // can isolate a node and/or try to split the network.
572 // Dropping a node for sending stuff that is invalid
573 // now but might be valid in a later version is also
574 // dangerous, because it can cause a network split
575 // between nodes running old code and nodes running
577 static void ClearBanned(); // needed for unit testing
578 static bool IsBanned(CNetAddr ip);
579 bool Misbehaving(int howmuch); // 1 == a little, 100 == a lot
591 inline void RelayInventory(const CInv& inv)
593 // Put on lists to offer to the other nodes
594 CRITICAL_BLOCK(cs_vNodes)
595 BOOST_FOREACH(CNode* pnode, vNodes)
596 pnode->PushInventory(inv);
600 void RelayMessage(const CInv& inv, const T& a)
602 CDataStream ss(SER_NETWORK);
605 RelayMessage(inv, ss);
609 inline void RelayMessage<>(const CInv& inv, const CDataStream& ss)
611 CRITICAL_BLOCK(cs_mapRelay)
613 // Expire old relay messages
614 while (!vRelayExpiration.empty() && vRelayExpiration.front().first < GetTime())
616 mapRelay.erase(vRelayExpiration.front().second);
617 vRelayExpiration.pop_front();
620 // Save original serialized message so newer versions are preserved
622 vRelayExpiration.push_back(std::make_pair(GetTime() + 15 * 60, inv));
636 // Templates for the publish and subscription system.
637 // The object being published as T& obj needs to have:
638 // a set<unsigned int> setSources member
639 // specializations of AdvertInsert and AdvertErase
640 // Currently implemented for CTable and CProduct.
644 void AdvertStartPublish(CNode* pfrom, unsigned int nChannel, unsigned int nHops, T& obj)
647 obj.setSources.insert(pfrom->addr.ip);
649 if (!AdvertInsert(obj))
653 CRITICAL_BLOCK(cs_vNodes)
654 BOOST_FOREACH(CNode* pnode, vNodes)
655 if (pnode != pfrom && (nHops < PUBLISH_HOPS || pnode->IsSubscribed(nChannel)))
656 pnode->PushMessage("publish", nChannel, nHops, obj);
660 void AdvertStopPublish(CNode* pfrom, unsigned int nChannel, unsigned int nHops, T& obj)
662 uint256 hash = obj.GetHash();
664 CRITICAL_BLOCK(cs_vNodes)
665 BOOST_FOREACH(CNode* pnode, vNodes)
666 if (pnode != pfrom && (nHops < PUBLISH_HOPS || pnode->IsSubscribed(nChannel)))
667 pnode->PushMessage("pub-cancel", nChannel, nHops, hash);
673 void AdvertRemoveSource(CNode* pfrom, unsigned int nChannel, unsigned int nHops, T& obj)
676 obj.setSources.erase(pfrom->addr.ip);
678 // If no longer supported by any sources, cancel it
679 if (obj.setSources.empty())
680 AdvertStopPublish(pfrom, nChannel, nHops, obj);