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>
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 RecvLine(SOCKET hSocket, std::string& strLine);
33 bool GetMyExternalIP(CNetAddr& ipRet);
34 bool AddAddress(CAddress addr, int64 nTimePenalty=0, CAddrDB *pAddrDB=NULL);
35 void AddressCurrentlyConnected(const CService& addr);
36 CNode* FindNode(const CNetAddr& ip);
37 CNode* FindNode(const CService& ip);
38 CNode* ConnectNode(CAddress addrConnect, int64 nTimeout=0);
39 void AbandonRequests(void (*fn)(void*, CDataStream&), void* param1);
40 bool AnySubscribed(unsigned int nChannel);
41 void MapPort(bool fMapPort);
42 bool BindListenPort(std::string& strError=REF(std::string()));
43 void StartNode(void* parg);
55 void (*fn)(void*, CDataStream&);
58 explicit CRequestTracker(void (*fnIn)(void*, CDataStream&)=NULL, void* param1In=NULL)
75 THREAD_OPENCONNECTIONS,
76 THREAD_MESSAGEHANDLER,
81 THREAD_ADDEDCONNECTIONS,
87 extern bool fAllowDNS;
88 extern uint64 nLocalServices;
89 extern CAddress addrLocalHost;
90 extern uint64 nLocalHostNonce;
91 extern boost::array<int, THREAD_MAX> vnThreadsRunning;
93 extern std::vector<CNode*> vNodes;
94 extern CCriticalSection cs_vNodes;
95 extern std::map<std::vector<unsigned char>, CAddress> mapAddresses;
96 extern CCriticalSection cs_mapAddresses;
97 extern std::map<CInv, CDataStream> mapRelay;
98 extern std::deque<std::pair<int64, CInv> > vRelayExpiration;
99 extern CCriticalSection cs_mapRelay;
100 extern std::map<CInv, int64> mapAlreadyAskedFor;
116 CCriticalSection cs_vSend;
117 CCriticalSection cs_vRecv;
120 int64 nLastSendEmpty;
121 int64 nTimeConnected;
122 unsigned int nHeaderStart;
123 unsigned int nMessageStart;
126 std::string strSubVer;
130 bool fSuccessfullyConnected;
135 // Denial-of-service detection/prevention
136 // Key is ip address, value is banned-until-time
137 static std::map<CNetAddr, int64> setBanned;
138 static CCriticalSection cs_setBanned;
143 std::map<uint256, CRequestTracker> mapRequests;
144 CCriticalSection cs_mapRequests;
145 uint256 hashContinue;
146 CBlockIndex* pindexLastGetBlocksBegin;
147 uint256 hashLastGetBlocksEnd;
151 std::vector<CAddress> vAddrToSend;
152 std::set<CAddress> setAddrKnown;
154 std::set<uint256> setKnown;
156 // inventory based relay
157 std::set<CInv> setInventoryKnown;
158 std::vector<CInv> vInventoryToSend;
159 CCriticalSection cs_inventory;
160 std::multimap<int64, CInv> mapAskFor;
162 // publish and subscription
163 std::vector<char> vfSubscribe;
165 CNode(SOCKET hSocketIn, CAddress addrIn, bool fInboundIn=false)
169 vSend.SetType(SER_NETWORK);
171 vRecv.SetType(SER_NETWORK);
173 // Version 0.2 obsoletes 20 Feb 2012
174 if (GetTime() > 1329696000)
176 vSend.SetVersion(209);
177 vRecv.SetVersion(209);
181 nLastSendEmpty = GetTime();
182 nTimeConnected = GetTime();
188 fClient = false; // set by version message
189 fInbound = fInboundIn;
190 fNetworkNode = false;
191 fSuccessfullyConnected = false;
196 pindexLastGetBlocksBegin = 0;
197 hashLastGetBlocksEnd = 0;
198 nStartingHeight = -1;
200 vfSubscribe.assign(256, false);
203 // Be shy and don't send version until we hear
210 if (hSocket != INVALID_SOCKET)
212 closesocket(hSocket);
213 hSocket = INVALID_SOCKET;
219 void operator=(const CNode&);
225 return std::max(nRefCount, 0) + (GetTime() < nReleaseTime ? 1 : 0);
228 CNode* AddRef(int64 nTimeout=0)
231 nReleaseTime = std::max(nReleaseTime, GetTime() + nTimeout);
244 void AddAddressKnown(const CAddress& addr)
246 setAddrKnown.insert(addr);
249 void PushAddress(const CAddress& addr)
251 // Known checking here is only to save space from duplicates.
252 // SendMessages will filter it again for knowns that were added
253 // after addresses were pushed.
254 if (addr.IsValid() && !setAddrKnown.count(addr))
255 vAddrToSend.push_back(addr);
259 void AddInventoryKnown(const CInv& inv)
261 CRITICAL_BLOCK(cs_inventory)
262 setInventoryKnown.insert(inv);
265 void PushInventory(const CInv& inv)
267 CRITICAL_BLOCK(cs_inventory)
268 if (!setInventoryKnown.count(inv))
269 vInventoryToSend.push_back(inv);
272 void AskFor(const CInv& inv)
274 // We're using mapAskFor as a priority queue,
275 // the key is the earliest time the request can be sent
276 int64& nRequestTime = mapAlreadyAskedFor[inv];
277 printf("askfor %s %"PRI64d"\n", inv.ToString().c_str(), nRequestTime);
279 // Make sure not to reuse time indexes to keep things in the same order
280 int64 nNow = (GetTime() - 1) * 1000000;
281 static int64 nLastTime;
283 nNow = std::max(nNow, nLastTime);
286 // Each retry is 2 minutes after the last
287 nRequestTime = std::max(nRequestTime + 2 * 60 * 1000000, nNow);
288 mapAskFor.insert(std::make_pair(nRequestTime, inv));
293 void BeginMessage(const char* pszCommand)
295 ENTER_CRITICAL_SECTION(cs_vSend);
296 if (nHeaderStart != -1)
298 nHeaderStart = vSend.size();
299 vSend << CMessageHeader(pszCommand, 0);
300 nMessageStart = vSend.size();
302 printf("%s ", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());
303 printf("sending: %s ", pszCommand);
309 if (nHeaderStart == -1)
311 vSend.resize(nHeaderStart);
314 LEAVE_CRITICAL_SECTION(cs_vSend);
317 printf("(aborted)\n");
322 if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
324 printf("dropmessages DROPPING SEND MESSAGE\n");
329 if (nHeaderStart == -1)
333 unsigned int nSize = vSend.size() - nMessageStart;
334 memcpy((char*)&vSend[nHeaderStart] + offsetof(CMessageHeader, nMessageSize), &nSize, sizeof(nSize));
337 if (vSend.GetVersion() >= 209)
339 uint256 hash = Hash(vSend.begin() + nMessageStart, vSend.end());
340 unsigned int nChecksum = 0;
341 memcpy(&nChecksum, &hash, sizeof(nChecksum));
342 assert(nMessageStart - nHeaderStart >= offsetof(CMessageHeader, nChecksum) + sizeof(nChecksum));
343 memcpy((char*)&vSend[nHeaderStart] + offsetof(CMessageHeader, nChecksum), &nChecksum, sizeof(nChecksum));
347 printf("(%d bytes)\n", nSize);
352 LEAVE_CRITICAL_SECTION(cs_vSend);
355 void EndMessageAbortIfEmpty()
357 if (nHeaderStart == -1)
359 int nSize = vSend.size() - nMessageStart;
371 void PushMessage(const char* pszCommand)
375 BeginMessage(pszCommand);
385 template<typename T1>
386 void PushMessage(const char* pszCommand, const T1& a1)
390 BeginMessage(pszCommand);
401 template<typename T1, typename T2>
402 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2)
406 BeginMessage(pszCommand);
417 template<typename T1, typename T2, typename T3>
418 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3)
422 BeginMessage(pszCommand);
423 vSend << a1 << a2 << a3;
433 template<typename T1, typename T2, typename T3, typename T4>
434 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4)
438 BeginMessage(pszCommand);
439 vSend << a1 << a2 << a3 << a4;
449 template<typename T1, typename T2, typename T3, typename T4, typename T5>
450 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4, const T5& a5)
454 BeginMessage(pszCommand);
455 vSend << a1 << a2 << a3 << a4 << a5;
465 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6>
466 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4, const T5& a5, const T6& a6)
470 BeginMessage(pszCommand);
471 vSend << a1 << a2 << a3 << a4 << a5 << a6;
481 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7>
482 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)
486 BeginMessage(pszCommand);
487 vSend << a1 << a2 << a3 << a4 << a5 << a6 << a7;
497 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8>
498 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)
502 BeginMessage(pszCommand);
503 vSend << a1 << a2 << a3 << a4 << a5 << a6 << a7 << a8;
513 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9>
514 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)
518 BeginMessage(pszCommand);
519 vSend << a1 << a2 << a3 << a4 << a5 << a6 << a7 << a8 << a9;
530 void PushRequest(const char* pszCommand,
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);
542 template<typename T1>
543 void PushRequest(const char* pszCommand, const T1& a1,
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);
555 template<typename T1, typename T2>
556 void PushRequest(const char* pszCommand, const T1& a1, const T2& a2,
557 void (*fn)(void*, CDataStream&), void* param1)
560 RAND_bytes((unsigned char*)&hashReply, sizeof(hashReply));
562 CRITICAL_BLOCK(cs_mapRequests)
563 mapRequests[hashReply] = CRequestTracker(fn, param1);
565 PushMessage(pszCommand, hashReply, a1, a2);
570 void PushGetBlocks(CBlockIndex* pindexBegin, uint256 hashEnd);
571 bool IsSubscribed(unsigned int nChannel);
572 void Subscribe(unsigned int nChannel, unsigned int nHops=0);
573 void CancelSubscribe(unsigned int nChannel);
574 void CloseSocketDisconnect();
578 // Denial-of-service detection/prevention
579 // The idea is to detect peers that are behaving
580 // badly and disconnect/ban them, but do it in a
581 // one-coding-mistake-won't-shatter-the-entire-network
583 // IMPORTANT: There should be nothing I can give a
584 // node that it will forward on that will make that
585 // node's peers drop it. If there is, an attacker
586 // can isolate a node and/or try to split the network.
587 // Dropping a node for sending stuff that is invalid
588 // now but might be valid in a later version is also
589 // dangerous, because it can cause a network split
590 // between nodes running old code and nodes running
592 static void ClearBanned(); // needed for unit testing
593 static bool IsBanned(CNetAddr ip);
594 bool Misbehaving(int howmuch); // 1 == a little, 100 == a lot
606 inline void RelayInventory(const CInv& inv)
608 // Put on lists to offer to the other nodes
609 CRITICAL_BLOCK(cs_vNodes)
610 BOOST_FOREACH(CNode* pnode, vNodes)
611 pnode->PushInventory(inv);
615 void RelayMessage(const CInv& inv, const T& a)
617 CDataStream ss(SER_NETWORK);
620 RelayMessage(inv, ss);
624 inline void RelayMessage<>(const CInv& inv, const CDataStream& ss)
626 CRITICAL_BLOCK(cs_mapRelay)
628 // Expire old relay messages
629 while (!vRelayExpiration.empty() && vRelayExpiration.front().first < GetTime())
631 mapRelay.erase(vRelayExpiration.front().second);
632 vRelayExpiration.pop_front();
635 // Save original serialized message so newer versions are preserved
637 vRelayExpiration.push_back(std::make_pair(GetTime() + 15 * 60, inv));
651 // Templates for the publish and subscription system.
652 // The object being published as T& obj needs to have:
653 // a set<unsigned int> setSources member
654 // specializations of AdvertInsert and AdvertErase
655 // Currently implemented for CTable and CProduct.
659 void AdvertStartPublish(CNode* pfrom, unsigned int nChannel, unsigned int nHops, T& obj)
662 obj.setSources.insert(pfrom->addr.ip);
664 if (!AdvertInsert(obj))
668 CRITICAL_BLOCK(cs_vNodes)
669 BOOST_FOREACH(CNode* pnode, vNodes)
670 if (pnode != pfrom && (nHops < PUBLISH_HOPS || pnode->IsSubscribed(nChannel)))
671 pnode->PushMessage("publish", nChannel, nHops, obj);
675 void AdvertStopPublish(CNode* pfrom, unsigned int nChannel, unsigned int nHops, T& obj)
677 uint256 hash = obj.GetHash();
679 CRITICAL_BLOCK(cs_vNodes)
680 BOOST_FOREACH(CNode* pnode, vNodes)
681 if (pnode != pfrom && (nHops < PUBLISH_HOPS || pnode->IsSubscribed(nChannel)))
682 pnode->PushMessage("pub-cancel", nChannel, nHops, hash);
688 void AdvertRemoveSource(CNode* pfrom, unsigned int nChannel, unsigned int nHops, T& obj)
691 obj.setSources.erase(pfrom->addr.ip);
693 // If no longer supported by any sources, cancel it
694 if (obj.setSources.empty())
695 AdvertStopPublish(pfrom, nChannel, nHops, obj);