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 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>
23 class CRequestTracker;
26 extern int nBestHeight;
30 inline unsigned int ReceiveBufferSize() { return 1000*GetArg("-maxreceivebuffer", 10*1000); }
31 inline unsigned int SendBufferSize() { return 1000*GetArg("-maxsendbuffer", 10*1000); }
32 static const unsigned int PUBLISH_HOPS = 5;
34 bool RecvLine(SOCKET hSocket, std::string& strLine);
35 bool GetMyExternalIP(CNetAddr& ipRet);
36 void AddressCurrentlyConnected(const CService& addr);
37 CNode* FindNode(const CNetAddr& ip);
38 CNode* FindNode(const CService& ip);
39 CNode* ConnectNode(CAddress addrConnect, int64 nTimeout=0);
40 void AbandonRequests(void (*fn)(void*, CDataStream&), void* param1);
41 bool AnySubscribed(unsigned int nChannel);
42 void MapPort(bool fMapPort);
43 bool BindListenPort(std::string& strError=REF(std::string()));
44 void StartNode(void* parg);
56 void (*fn)(void*, CDataStream&);
59 explicit CRequestTracker(void (*fnIn)(void*, CDataStream&)=NULL, void* param1In=NULL)
76 THREAD_OPENCONNECTIONS,
77 THREAD_MESSAGEHANDLER,
82 THREAD_ADDEDCONNECTIONS,
89 extern bool fAllowDNS;
90 extern uint64 nLocalServices;
91 extern CAddress addrLocalHost;
92 extern uint64 nLocalHostNonce;
93 extern boost::array<int, THREAD_MAX> vnThreadsRunning;
94 extern CAddrMan addrman;
96 extern std::vector<CNode*> vNodes;
97 extern CCriticalSection cs_vNodes;
98 extern std::map<CInv, CDataStream> mapRelay;
99 extern std::deque<std::pair<int64, CInv> > vRelayExpiration;
100 extern CCriticalSection cs_mapRelay;
101 extern std::map<CInv, int64> mapAlreadyAskedFor;
108 /** Information about a peer */
117 CCriticalSection cs_vSend;
118 CCriticalSection cs_vRecv;
121 int64 nLastSendEmpty;
122 int64 nTimeConnected;
123 unsigned int nHeaderStart;
124 unsigned int nMessageStart;
127 std::string strSubVer;
131 bool fSuccessfullyConnected;
136 // Denial-of-service detection/prevention
137 // Key is ip address, value is banned-until-time
138 static std::map<CNetAddr, int64> setBanned;
139 static CCriticalSection cs_setBanned;
144 std::map<uint256, CRequestTracker> mapRequests;
145 CCriticalSection cs_mapRequests;
146 uint256 hashContinue;
147 CBlockIndex* pindexLastGetBlocksBegin;
148 uint256 hashLastGetBlocksEnd;
152 std::vector<CAddress> vAddrToSend;
153 std::set<CAddress> setAddrKnown;
155 std::set<uint256> setKnown;
157 // inventory based relay
158 mruset<CInv> setInventoryKnown;
159 std::vector<CInv> vInventoryToSend;
160 CCriticalSection cs_inventory;
161 std::multimap<int64, CInv> mapAskFor;
163 // publish and subscription
164 std::vector<char> vfSubscribe;
166 CNode(SOCKET hSocketIn, CAddress addrIn, bool fInboundIn=false)
170 vSend.SetType(SER_NETWORK);
171 vRecv.SetType(SER_NETWORK);
172 vSend.SetVersion(209);
173 vRecv.SetVersion(209);
176 nLastSendEmpty = GetTime();
177 nTimeConnected = GetTime();
183 fClient = false; // set by version message
184 fInbound = fInboundIn;
185 fNetworkNode = false;
186 fSuccessfullyConnected = false;
191 pindexLastGetBlocksBegin = 0;
192 hashLastGetBlocksEnd = 0;
193 nStartingHeight = -1;
195 vfSubscribe.assign(256, false);
197 setInventoryKnown.max_size(SendBufferSize() / 1000);
199 // Be shy and don't send version until we hear
206 if (hSocket != INVALID_SOCKET)
208 closesocket(hSocket);
209 hSocket = INVALID_SOCKET;
215 void operator=(const CNode&);
221 return std::max(nRefCount, 0) + (GetTime() < nReleaseTime ? 1 : 0);
224 CNode* AddRef(int64 nTimeout=0)
227 nReleaseTime = std::max(nReleaseTime, GetTime() + nTimeout);
240 void AddAddressKnown(const CAddress& addr)
242 setAddrKnown.insert(addr);
245 void PushAddress(const CAddress& addr)
247 // Known checking here is only to save space from duplicates.
248 // SendMessages will filter it again for knowns that were added
249 // after addresses were pushed.
250 if (addr.IsValid() && !setAddrKnown.count(addr))
251 vAddrToSend.push_back(addr);
255 void AddInventoryKnown(const CInv& inv)
257 CRITICAL_BLOCK(cs_inventory)
258 setInventoryKnown.insert(inv);
261 void PushInventory(const CInv& inv)
263 CRITICAL_BLOCK(cs_inventory)
264 if (!setInventoryKnown.count(inv))
265 vInventoryToSend.push_back(inv);
268 void AskFor(const CInv& inv)
270 // We're using mapAskFor as a priority queue,
271 // the key is the earliest time the request can be sent
272 int64& nRequestTime = mapAlreadyAskedFor[inv];
273 printf("askfor %s %"PRI64d"\n", inv.ToString().c_str(), nRequestTime);
275 // Make sure not to reuse time indexes to keep things in the same order
276 int64 nNow = (GetTime() - 1) * 1000000;
277 static int64 nLastTime;
279 nNow = std::max(nNow, nLastTime);
282 // Each retry is 2 minutes after the last
283 nRequestTime = std::max(nRequestTime + 2 * 60 * 1000000, nNow);
284 mapAskFor.insert(std::make_pair(nRequestTime, inv));
289 void BeginMessage(const char* pszCommand)
291 ENTER_CRITICAL_SECTION(cs_vSend);
292 if (nHeaderStart != -1)
294 nHeaderStart = vSend.size();
295 vSend << CMessageHeader(pszCommand, 0);
296 nMessageStart = vSend.size();
298 printf("%s ", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());
299 printf("sending: %s ", pszCommand);
305 if (nHeaderStart == -1)
307 vSend.resize(nHeaderStart);
310 LEAVE_CRITICAL_SECTION(cs_vSend);
313 printf("(aborted)\n");
318 if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
320 printf("dropmessages DROPPING SEND MESSAGE\n");
325 if (nHeaderStart == -1)
329 unsigned int nSize = vSend.size() - nMessageStart;
330 memcpy((char*)&vSend[nHeaderStart] + offsetof(CMessageHeader, nMessageSize), &nSize, sizeof(nSize));
333 uint256 hash = Hash(vSend.begin() + nMessageStart, vSend.end());
334 unsigned int nChecksum = 0;
335 memcpy(&nChecksum, &hash, sizeof(nChecksum));
336 assert(nMessageStart - nHeaderStart >= offsetof(CMessageHeader, nChecksum) + sizeof(nChecksum));
337 memcpy((char*)&vSend[nHeaderStart] + offsetof(CMessageHeader, nChecksum), &nChecksum, sizeof(nChecksum));
340 printf("(%d bytes)\n", nSize);
345 LEAVE_CRITICAL_SECTION(cs_vSend);
348 void EndMessageAbortIfEmpty()
350 if (nHeaderStart == -1)
352 int nSize = vSend.size() - nMessageStart;
364 void PushMessage(const char* pszCommand)
368 BeginMessage(pszCommand);
378 template<typename T1>
379 void PushMessage(const char* pszCommand, const T1& a1)
383 BeginMessage(pszCommand);
394 template<typename T1, typename T2>
395 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2)
399 BeginMessage(pszCommand);
410 template<typename T1, typename T2, typename T3>
411 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3)
415 BeginMessage(pszCommand);
416 vSend << a1 << a2 << a3;
426 template<typename T1, typename T2, typename T3, typename T4>
427 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4)
431 BeginMessage(pszCommand);
432 vSend << a1 << a2 << a3 << a4;
442 template<typename T1, typename T2, typename T3, typename T4, typename T5>
443 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4, const T5& a5)
447 BeginMessage(pszCommand);
448 vSend << a1 << a2 << a3 << a4 << a5;
458 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6>
459 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4, const T5& a5, const T6& a6)
463 BeginMessage(pszCommand);
464 vSend << a1 << a2 << a3 << a4 << a5 << a6;
474 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7>
475 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)
479 BeginMessage(pszCommand);
480 vSend << a1 << a2 << a3 << a4 << a5 << a6 << a7;
490 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8>
491 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)
495 BeginMessage(pszCommand);
496 vSend << a1 << a2 << a3 << a4 << a5 << a6 << a7 << a8;
506 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9>
507 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)
511 BeginMessage(pszCommand);
512 vSend << a1 << a2 << a3 << a4 << a5 << a6 << a7 << a8 << a9;
523 void PushRequest(const char* pszCommand,
524 void (*fn)(void*, CDataStream&), void* param1)
527 RAND_bytes((unsigned char*)&hashReply, sizeof(hashReply));
529 CRITICAL_BLOCK(cs_mapRequests)
530 mapRequests[hashReply] = CRequestTracker(fn, param1);
532 PushMessage(pszCommand, hashReply);
535 template<typename T1>
536 void PushRequest(const char* pszCommand, const T1& a1,
537 void (*fn)(void*, CDataStream&), void* param1)
540 RAND_bytes((unsigned char*)&hashReply, sizeof(hashReply));
542 CRITICAL_BLOCK(cs_mapRequests)
543 mapRequests[hashReply] = CRequestTracker(fn, param1);
545 PushMessage(pszCommand, hashReply, a1);
548 template<typename T1, typename T2>
549 void PushRequest(const char* pszCommand, const T1& a1, const T2& a2,
550 void (*fn)(void*, CDataStream&), void* param1)
553 RAND_bytes((unsigned char*)&hashReply, sizeof(hashReply));
555 CRITICAL_BLOCK(cs_mapRequests)
556 mapRequests[hashReply] = CRequestTracker(fn, param1);
558 PushMessage(pszCommand, hashReply, a1, a2);
563 void PushGetBlocks(CBlockIndex* pindexBegin, uint256 hashEnd);
564 bool IsSubscribed(unsigned int nChannel);
565 void Subscribe(unsigned int nChannel, unsigned int nHops=0);
566 void CancelSubscribe(unsigned int nChannel);
567 void CloseSocketDisconnect();
571 // Denial-of-service detection/prevention
572 // The idea is to detect peers that are behaving
573 // badly and disconnect/ban them, but do it in a
574 // one-coding-mistake-won't-shatter-the-entire-network
576 // IMPORTANT: There should be nothing I can give a
577 // node that it will forward on that will make that
578 // node's peers drop it. If there is, an attacker
579 // can isolate a node and/or try to split the network.
580 // Dropping a node for sending stuff that is invalid
581 // now but might be valid in a later version is also
582 // dangerous, because it can cause a network split
583 // between nodes running old code and nodes running
585 static void ClearBanned(); // needed for unit testing
586 static bool IsBanned(CNetAddr ip);
587 bool Misbehaving(int howmuch); // 1 == a little, 100 == a lot
599 inline void RelayInventory(const CInv& inv)
601 // Put on lists to offer to the other nodes
602 CRITICAL_BLOCK(cs_vNodes)
603 BOOST_FOREACH(CNode* pnode, vNodes)
604 pnode->PushInventory(inv);
608 void RelayMessage(const CInv& inv, const T& a)
610 CDataStream ss(SER_NETWORK);
613 RelayMessage(inv, ss);
617 inline void RelayMessage<>(const CInv& inv, const CDataStream& ss)
619 CRITICAL_BLOCK(cs_mapRelay)
621 // Expire old relay messages
622 while (!vRelayExpiration.empty() && vRelayExpiration.front().first < GetTime())
624 mapRelay.erase(vRelayExpiration.front().second);
625 vRelayExpiration.pop_front();
628 // Save original serialized message so newer versions are preserved
630 vRelayExpiration.push_back(std::make_pair(GetTime() + 15 * 60, inv));
644 // Templates for the publish and subscription system.
645 // The object being published as T& obj needs to have:
646 // a set<unsigned int> setSources member
647 // specializations of AdvertInsert and AdvertErase
648 // Currently implemented for CTable and CProduct.
652 void AdvertStartPublish(CNode* pfrom, unsigned int nChannel, unsigned int nHops, T& obj)
655 obj.setSources.insert(pfrom->addr.ip);
657 if (!AdvertInsert(obj))
661 CRITICAL_BLOCK(cs_vNodes)
662 BOOST_FOREACH(CNode* pnode, vNodes)
663 if (pnode != pfrom && (nHops < PUBLISH_HOPS || pnode->IsSubscribed(nChannel)))
664 pnode->PushMessage("publish", nChannel, nHops, obj);
668 void AdvertStopPublish(CNode* pfrom, unsigned int nChannel, unsigned int nHops, T& obj)
670 uint256 hash = obj.GetHash();
672 CRITICAL_BLOCK(cs_vNodes)
673 BOOST_FOREACH(CNode* pnode, vNodes)
674 if (pnode != pfrom && (nHops < PUBLISH_HOPS || pnode->IsSubscribed(nChannel)))
675 pnode->PushMessage("pub-cancel", nChannel, nHops, hash);
681 void AdvertRemoveSource(CNode* pfrom, unsigned int nChannel, unsigned int nHops, T& obj)
684 obj.setSources.erase(pfrom->addr.ip);
686 // If no longer supported by any sources, cancel it
687 if (obj.setSources.empty())
688 AdvertStopPublish(pfrom, nChannel, nHops, obj);