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.
11 #include <boost/array.hpp>
12 #include <boost/foreach.hpp>
13 #include <openssl/rand.h>
16 #include <arpa/inet.h>
22 class CRequestTracker;
25 extern int nBestHeight;
26 extern int nConnectTimeout;
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 ConnectSocket(const CAddress& addrConnect, SOCKET& hSocketRet, int nTimeout=nConnectTimeout);
35 bool Lookup(const char *pszName, std::vector<CAddress>& vaddr, int nServices, int nMaxSolutions, bool fAllowLookup = false, int portDefault = 0, bool fAllowPort = false);
36 bool Lookup(const char *pszName, CAddress& addr, int nServices, bool fAllowLookup = false, int portDefault = 0, bool fAllowPort = false);
37 bool GetMyExternalIP(unsigned int& ipRet);
38 bool AddAddress(CAddress addr, int64_t nTimePenalty=0, CAddrDB *pAddrDB=NULL);
39 void AddressCurrentlyConnected(const CAddress& addr);
40 CNode* FindNode(unsigned int ip);
41 CNode* ConnectNode(CAddress addrConnect, int64_t nTimeout=0);
42 void AbandonRequests(void (*fn)(void*, CDataStream&), void* param1);
43 bool AnySubscribed(unsigned int nChannel);
44 void MapPort(bool fMapPort);
45 bool BindListenPort(std::string& strError=REF(std::string()));
46 void StartNode(void* parg);
58 void (*fn)(void*, CDataStream&);
61 explicit CRequestTracker(void (*fnIn)(void*, CDataStream&)=NULL, void* param1In=NULL)
78 extern bool fAllowDNS;
79 extern uint64_t nLocalServices;
80 extern CAddress addrLocalHost;
81 extern uint64_t nLocalHostNonce;
82 extern boost::array<int, 10> vnThreadsRunning;
84 extern std::vector<CNode*> vNodes;
85 extern CCriticalSection cs_vNodes;
86 extern std::map<std::vector<unsigned char>, CAddress> mapAddresses;
87 extern CCriticalSection cs_mapAddresses;
88 extern std::map<CInv, CDataStream> mapRelay;
89 extern std::deque<std::pair<int64_t, CInv> > vRelayExpiration;
90 extern CCriticalSection cs_mapRelay;
91 extern std::map<CInv, int64_t> mapAlreadyAskedFor;
95 extern CAddress addrProxy;
110 CCriticalSection cs_vSend;
111 CCriticalSection cs_vRecv;
114 int64_t nLastSendEmpty;
115 int64_t nTimeConnected;
116 unsigned int nHeaderStart;
117 unsigned int nMessageStart;
120 std::string strSubVer;
124 bool fSuccessfullyConnected;
129 // Denial-of-service detection/prevention
130 // Key is ip address, value is banned-until-time
131 static std::map<unsigned int, int64_t> setBanned;
132 static CCriticalSection cs_setBanned;
136 int64_t nReleaseTime;
137 std::map<uint256, CRequestTracker> mapRequests;
138 CCriticalSection cs_mapRequests;
139 uint256 hashContinue;
140 CBlockIndex* pindexLastGetBlocksBegin;
141 uint256 hashLastGetBlocksEnd;
145 std::vector<CAddress> vAddrToSend;
146 std::set<CAddress> setAddrKnown;
148 std::set<uint256> setKnown;
150 // inventory based relay
151 std::set<CInv> setInventoryKnown;
152 std::vector<CInv> vInventoryToSend;
153 CCriticalSection cs_inventory;
154 std::multimap<int64_t, CInv> mapAskFor;
156 // publish and subscription
157 std::vector<char> vfSubscribe;
159 CNode(SOCKET hSocketIn, CAddress addrIn, bool fInboundIn=false)
163 vSend.SetType(SER_NETWORK);
165 vRecv.SetType(SER_NETWORK);
167 // Version 0.2 obsoletes 20 Feb 2012
168 if (GetTime() > 1329696000)
170 vSend.SetVersion(209);
171 vRecv.SetVersion(209);
175 nLastSendEmpty = GetTime();
176 nTimeConnected = GetTime();
182 fClient = false; // set by version message
183 fInbound = fInboundIn;
184 fNetworkNode = false;
185 fSuccessfullyConnected = false;
190 pindexLastGetBlocksBegin = 0;
191 hashLastGetBlocksEnd = 0;
192 nStartingHeight = -1;
194 vfSubscribe.assign(256, false);
197 // Be shy and don't send version until we hear
204 if (hSocket != INVALID_SOCKET)
206 closesocket(hSocket);
207 hSocket = INVALID_SOCKET;
213 void operator=(const CNode&);
219 return std::max(nRefCount, 0) + (GetTime() < nReleaseTime ? 1 : 0);
222 CNode* AddRef(int64_t nTimeout=0)
225 nReleaseTime = std::max(nReleaseTime, GetTime() + nTimeout);
238 void AddAddressKnown(const CAddress& addr)
240 setAddrKnown.insert(addr);
243 void PushAddress(const CAddress& addr)
245 // Known checking here is only to save space from duplicates.
246 // SendMessages will filter it again for knowns that were added
247 // after addresses were pushed.
248 if (addr.IsValid() && !setAddrKnown.count(addr))
249 vAddrToSend.push_back(addr);
253 void AddInventoryKnown(const CInv& inv)
255 CRITICAL_BLOCK(cs_inventory)
256 setInventoryKnown.insert(inv);
259 void PushInventory(const CInv& inv)
261 CRITICAL_BLOCK(cs_inventory)
262 if (!setInventoryKnown.count(inv))
263 vInventoryToSend.push_back(inv);
266 void AskFor(const CInv& inv)
268 // We're using mapAskFor as a priority queue,
269 // the key is the earliest time the request can be sent
270 int64_t& nRequestTime = mapAlreadyAskedFor[inv];
271 printf("askfor %s %"PRI64d"\n", inv.ToString().c_str(), nRequestTime);
273 // Make sure not to reuse time indexes to keep things in the same order
274 int64_t nNow = (GetTime() - 1) * 1000000;
275 static int64_t nLastTime;
276 nLastTime = 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 cs_vSend.Enter("cs_vSend", __FILE__, __LINE__);
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);
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);
347 void EndMessageAbortIfEmpty()
349 if (nHeaderStart == -1)
351 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(unsigned int 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);