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>
20 class CRequestTracker;
23 extern int nBestHeight;
24 extern int nConnectTimeout;
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 ConnectSocket(const CAddress& addrConnect, SOCKET& hSocketRet, int nTimeout=nConnectTimeout);
33 bool Lookup(const char *pszName, std::vector<CAddress>& vaddr, int nServices, int nMaxSolutions, bool fAllowLookup = false, int portDefault = 0, bool fAllowPort = false);
34 bool Lookup(const char *pszName, CAddress& addr, int nServices, bool fAllowLookup = false, int portDefault = 0, bool fAllowPort = false);
35 bool GetMyExternalIP(unsigned int& ipRet);
36 bool AddAddress(CAddress addr, int64 nTimePenalty=0, CAddrDB *pAddrDB=NULL);
37 void AddressCurrentlyConnected(const CAddress& addr);
38 CNode* FindNode(unsigned int 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 extern bool fAllowDNS;
77 extern uint64 nLocalServices;
78 extern CAddress addrLocalHost;
79 extern uint64 nLocalHostNonce;
80 extern boost::array<int, 10> vnThreadsRunning;
82 extern std::vector<CNode*> vNodes;
83 extern CCriticalSection cs_vNodes;
84 extern std::map<std::vector<unsigned char>, CAddress> mapAddresses;
85 extern CCriticalSection cs_mapAddresses;
86 extern std::map<CInv, CDataStream> mapRelay;
87 extern std::deque<std::pair<int64, CInv> > vRelayExpiration;
88 extern CCriticalSection cs_mapRelay;
89 extern std::map<CInv, int64> mapAlreadyAskedFor;
93 extern CAddress addrProxy;
108 CCriticalSection cs_vSend;
109 CCriticalSection cs_vRecv;
112 int64 nLastSendEmpty;
113 int64 nTimeConnected;
114 signed int nHeaderStart;
115 unsigned int nMessageStart;
118 std::string strSubVer;
122 bool fSuccessfullyConnected;
127 // Denial-of-service detection/prevention
128 // Key is ip address, value is banned-until-time
129 static std::map<unsigned int, int64> setBanned;
130 static CCriticalSection cs_setBanned;
135 std::map<uint256, CRequestTracker> mapRequests;
136 CCriticalSection cs_mapRequests;
137 uint256 hashContinue;
138 CBlockIndex* pindexLastGetBlocksBegin;
139 uint256 hashLastGetBlocksEnd;
143 std::vector<CAddress> vAddrToSend;
144 std::set<CAddress> setAddrKnown;
146 std::set<uint256> setKnown;
148 // inventory based relay
149 std::set<CInv> setInventoryKnown;
150 std::vector<CInv> vInventoryToSend;
151 CCriticalSection cs_inventory;
152 std::multimap<int64, CInv> mapAskFor;
154 // publish and subscription
155 std::vector<char> vfSubscribe;
157 CNode(SOCKET hSocketIn, CAddress addrIn, bool fInboundIn=false)
161 vSend.SetType(SER_NETWORK);
163 vRecv.SetType(SER_NETWORK);
165 // Version 0.2 obsoletes 20 Feb 2012
166 if (GetTime() > 1329696000)
168 vSend.SetVersion(209);
169 vRecv.SetVersion(209);
173 nLastSendEmpty = GetTime();
174 nTimeConnected = GetTime();
180 fClient = false; // set by version message
181 fInbound = fInboundIn;
182 fNetworkNode = false;
183 fSuccessfullyConnected = false;
188 pindexLastGetBlocksBegin = 0;
189 hashLastGetBlocksEnd = 0;
190 nStartingHeight = -1;
192 vfSubscribe.assign(256, false);
195 // Be shy and don't send version until we hear
202 if (hSocket != INVALID_SOCKET)
204 closesocket(hSocket);
205 hSocket = INVALID_SOCKET;
211 void operator=(const CNode&);
217 return std::max(nRefCount, 0) + (GetTime() < nReleaseTime ? 1 : 0);
220 CNode* AddRef(int64 nTimeout=0)
223 nReleaseTime = std::max(nReleaseTime, GetTime() + nTimeout);
236 void AddAddressKnown(const CAddress& addr)
238 setAddrKnown.insert(addr);
241 void PushAddress(const CAddress& addr)
243 // Known checking here is only to save space from duplicates.
244 // SendMessages will filter it again for knowns that were added
245 // after addresses were pushed.
246 if (addr.IsValid() && !setAddrKnown.count(addr))
247 vAddrToSend.push_back(addr);
251 void AddInventoryKnown(const CInv& inv)
253 CRITICAL_BLOCK(cs_inventory)
254 setInventoryKnown.insert(inv);
257 void PushInventory(const CInv& inv)
259 CRITICAL_BLOCK(cs_inventory)
260 if (!setInventoryKnown.count(inv))
261 vInventoryToSend.push_back(inv);
264 void AskFor(const CInv& inv)
266 // We're using mapAskFor as a priority queue,
267 // the key is the earliest time the request can be sent
268 int64& nRequestTime = mapAlreadyAskedFor[inv];
269 printf("askfor %s %"PRI64d"\n", inv.ToString().c_str(), nRequestTime);
271 // Make sure not to reuse time indexes to keep things in the same order
272 int64 nNow = (GetTime() - 1) * 1000000;
273 static int64 nLastTime;
275 nNow = std::max(nNow, nLastTime);
278 // Each retry is 2 minutes after the last
279 nRequestTime = std::max(nRequestTime + 2 * 60 * 1000000, nNow);
280 mapAskFor.insert(std::make_pair(nRequestTime, inv));
285 void BeginMessage(const char* pszCommand)
287 ENTER_CRITICAL_SECTION(cs_vSend);
288 if (nHeaderStart != -1)
290 nHeaderStart = vSend.size();
291 vSend << CMessageHeader(pszCommand, 0);
292 nMessageStart = vSend.size();
294 printf("%s ", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());
295 printf("sending: %s ", pszCommand);
301 if (nHeaderStart == -1)
303 vSend.resize(nHeaderStart);
306 LEAVE_CRITICAL_SECTION(cs_vSend);
309 printf("(aborted)\n");
314 if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
316 printf("dropmessages DROPPING SEND MESSAGE\n");
321 if (nHeaderStart == -1)
325 unsigned int nSize = vSend.size() - nMessageStart;
326 memcpy((char*)&vSend[nHeaderStart] + offsetof(CMessageHeader, nMessageSize), &nSize, sizeof(nSize));
329 if (vSend.GetVersion() >= 209)
331 uint256 hash = Hash(vSend.begin() + nMessageStart, vSend.end());
332 unsigned int nChecksum = 0;
333 memcpy(&nChecksum, &hash, sizeof(nChecksum));
334 assert(nMessageStart - nHeaderStart >= offsetof(CMessageHeader, nChecksum) + sizeof(nChecksum));
335 memcpy((char*)&vSend[nHeaderStart] + offsetof(CMessageHeader, nChecksum), &nChecksum, sizeof(nChecksum));
339 printf("(%d bytes)\n", nSize);
344 LEAVE_CRITICAL_SECTION(cs_vSend);
347 void EndMessageAbortIfEmpty()
349 if (nHeaderStart == -1)
351 int nSize = vSend.size() - nMessageStart;
362 /// when NTP implemented, change to just nTime = GetAdjustedTime()
363 int64 nTime = (fInbound ? GetAdjustedTime() : GetTime());
364 CAddress addrYou = (fUseProxy ? CAddress("0.0.0.0") : addr);
365 CAddress addrMe = (fUseProxy || !addrLocalHost.IsRoutable() ? CAddress("0.0.0.0") : addrLocalHost);
366 RAND_bytes((unsigned char*)&nLocalHostNonce, sizeof(nLocalHostNonce));
367 PushMessage("version", VERSION, nLocalServices, nTime, addrYou, addrMe,
368 nLocalHostNonce, std::string(pszSubVer), nBestHeight);
374 void PushMessage(const char* pszCommand)
378 BeginMessage(pszCommand);
388 template<typename T1>
389 void PushMessage(const char* pszCommand, const T1& a1)
393 BeginMessage(pszCommand);
404 template<typename T1, typename T2>
405 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2)
409 BeginMessage(pszCommand);
420 template<typename T1, typename T2, typename T3>
421 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3)
425 BeginMessage(pszCommand);
426 vSend << a1 << a2 << a3;
436 template<typename T1, typename T2, typename T3, typename T4>
437 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4)
441 BeginMessage(pszCommand);
442 vSend << a1 << a2 << a3 << a4;
452 template<typename T1, typename T2, typename T3, typename T4, typename T5>
453 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4, const T5& a5)
457 BeginMessage(pszCommand);
458 vSend << a1 << a2 << a3 << a4 << a5;
468 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6>
469 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4, const T5& a5, const T6& a6)
473 BeginMessage(pszCommand);
474 vSend << a1 << a2 << a3 << a4 << a5 << a6;
484 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7>
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)
489 BeginMessage(pszCommand);
490 vSend << a1 << a2 << a3 << a4 << a5 << a6 << a7;
500 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8>
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)
505 BeginMessage(pszCommand);
506 vSend << a1 << a2 << a3 << a4 << a5 << a6 << a7 << a8;
516 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9>
517 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)
521 BeginMessage(pszCommand);
522 vSend << a1 << a2 << a3 << a4 << a5 << a6 << a7 << a8 << a9;
533 void PushRequest(const char* pszCommand,
534 void (*fn)(void*, CDataStream&), void* param1)
537 RAND_bytes((unsigned char*)&hashReply, sizeof(hashReply));
539 CRITICAL_BLOCK(cs_mapRequests)
540 mapRequests[hashReply] = CRequestTracker(fn, param1);
542 PushMessage(pszCommand, hashReply);
545 template<typename T1>
546 void PushRequest(const char* pszCommand, const T1& a1,
547 void (*fn)(void*, CDataStream&), void* param1)
550 RAND_bytes((unsigned char*)&hashReply, sizeof(hashReply));
552 CRITICAL_BLOCK(cs_mapRequests)
553 mapRequests[hashReply] = CRequestTracker(fn, param1);
555 PushMessage(pszCommand, hashReply, a1);
558 template<typename T1, typename T2>
559 void PushRequest(const char* pszCommand, const T1& a1, const T2& a2,
560 void (*fn)(void*, CDataStream&), void* param1)
563 RAND_bytes((unsigned char*)&hashReply, sizeof(hashReply));
565 CRITICAL_BLOCK(cs_mapRequests)
566 mapRequests[hashReply] = CRequestTracker(fn, param1);
568 PushMessage(pszCommand, hashReply, a1, a2);
573 void PushGetBlocks(CBlockIndex* pindexBegin, uint256 hashEnd);
574 bool IsSubscribed(unsigned int nChannel);
575 void Subscribe(unsigned int nChannel, unsigned int nHops=0);
576 void CancelSubscribe(unsigned int nChannel);
577 void CloseSocketDisconnect();
581 // Denial-of-service detection/prevention
582 // The idea is to detect peers that are behaving
583 // badly and disconnect/ban them, but do it in a
584 // one-coding-mistake-won't-shatter-the-entire-network
586 // IMPORTANT: There should be nothing I can give a
587 // node that it will forward on that will make that
588 // node's peers drop it. If there is, an attacker
589 // can isolate a node and/or try to split the network.
590 // Dropping a node for sending stuff that is invalid
591 // now but might be valid in a later version is also
592 // dangerous, because it can cause a network split
593 // between nodes running old code and nodes running
595 static void ClearBanned(); // needed for unit testing
596 static bool IsBanned(unsigned int ip);
597 bool Misbehaving(int howmuch); // 1 == a little, 100 == a lot
609 inline void RelayInventory(const CInv& inv)
611 // Put on lists to offer to the other nodes
612 CRITICAL_BLOCK(cs_vNodes)
613 BOOST_FOREACH(CNode* pnode, vNodes)
614 pnode->PushInventory(inv);
618 void RelayMessage(const CInv& inv, const T& a)
620 CDataStream ss(SER_NETWORK);
623 RelayMessage(inv, ss);
627 inline void RelayMessage<>(const CInv& inv, const CDataStream& ss)
629 CRITICAL_BLOCK(cs_mapRelay)
631 // Expire old relay messages
632 while (!vRelayExpiration.empty() && vRelayExpiration.front().first < GetTime())
634 mapRelay.erase(vRelayExpiration.front().second);
635 vRelayExpiration.pop_front();
638 // Save original serialized message so newer versions are preserved
640 vRelayExpiration.push_back(std::make_pair(GetTime() + 15 * 60, inv));
654 // Templates for the publish and subscription system.
655 // The object being published as T& obj needs to have:
656 // a set<unsigned int> setSources member
657 // specializations of AdvertInsert and AdvertErase
658 // Currently implemented for CTable and CProduct.
662 void AdvertStartPublish(CNode* pfrom, unsigned int nChannel, unsigned int nHops, T& obj)
665 obj.setSources.insert(pfrom->addr.ip);
667 if (!AdvertInsert(obj))
671 CRITICAL_BLOCK(cs_vNodes)
672 BOOST_FOREACH(CNode* pnode, vNodes)
673 if (pnode != pfrom && (nHops < PUBLISH_HOPS || pnode->IsSubscribed(nChannel)))
674 pnode->PushMessage("publish", nChannel, nHops, obj);
678 void AdvertStopPublish(CNode* pfrom, unsigned int nChannel, unsigned int nHops, T& obj)
680 uint256 hash = obj.GetHash();
682 CRITICAL_BLOCK(cs_vNodes)
683 BOOST_FOREACH(CNode* pnode, vNodes)
684 if (pnode != pfrom && (nHops < PUBLISH_HOPS || pnode->IsSubscribed(nChannel)))
685 pnode->PushMessage("pub-cancel", nChannel, nHops, hash);
691 void AdvertRemoveSource(CNode* pfrom, unsigned int nChannel, unsigned int nHops, T& obj)
694 obj.setSources.erase(pfrom->addr.ip);
696 // If no longer supported by any sources, cancel it
697 if (obj.setSources.empty())
698 AdvertStopPublish(pfrom, nChannel, nHops, obj);