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 unsigned int nHeaderStart;
115 unsigned int nMessageStart;
118 std::string strSubVer;
122 bool fSuccessfullyConnected;
128 std::map<uint256, CRequestTracker> mapRequests;
129 CCriticalSection cs_mapRequests;
130 uint256 hashContinue;
131 CBlockIndex* pindexLastGetBlocksBegin;
132 uint256 hashLastGetBlocksEnd;
136 std::vector<CAddress> vAddrToSend;
137 std::set<CAddress> setAddrKnown;
139 std::set<uint256> setKnown;
141 // inventory based relay
142 std::set<CInv> setInventoryKnown;
143 std::vector<CInv> vInventoryToSend;
144 CCriticalSection cs_inventory;
145 std::multimap<int64, CInv> mapAskFor;
147 // publish and subscription
148 std::vector<char> vfSubscribe;
151 CNode(SOCKET hSocketIn, CAddress addrIn, bool fInboundIn=false)
155 vSend.SetType(SER_NETWORK);
157 vRecv.SetType(SER_NETWORK);
159 // Version 0.2 obsoletes 20 Feb 2012
160 if (GetTime() > 1329696000)
162 vSend.SetVersion(209);
163 vRecv.SetVersion(209);
167 nLastSendEmpty = GetTime();
168 nTimeConnected = GetTime();
174 fClient = false; // set by version message
175 fInbound = fInboundIn;
176 fNetworkNode = false;
177 fSuccessfullyConnected = false;
182 pindexLastGetBlocksBegin = 0;
183 hashLastGetBlocksEnd = 0;
184 nStartingHeight = -1;
186 vfSubscribe.assign(256, false);
188 // Be shy and don't send version until we hear
195 if (hSocket != INVALID_SOCKET)
197 closesocket(hSocket);
198 hSocket = INVALID_SOCKET;
204 void operator=(const CNode&);
210 return std::max(nRefCount, 0) + (GetTime() < nReleaseTime ? 1 : 0);
213 CNode* AddRef(int64 nTimeout=0)
216 nReleaseTime = std::max(nReleaseTime, GetTime() + nTimeout);
229 void AddAddressKnown(const CAddress& addr)
231 setAddrKnown.insert(addr);
234 void PushAddress(const CAddress& addr)
236 // Known checking here is only to save space from duplicates.
237 // SendMessages will filter it again for knowns that were added
238 // after addresses were pushed.
239 if (addr.IsValid() && !setAddrKnown.count(addr))
240 vAddrToSend.push_back(addr);
244 void AddInventoryKnown(const CInv& inv)
246 CRITICAL_BLOCK(cs_inventory)
247 setInventoryKnown.insert(inv);
250 void PushInventory(const CInv& inv)
252 CRITICAL_BLOCK(cs_inventory)
253 if (!setInventoryKnown.count(inv))
254 vInventoryToSend.push_back(inv);
257 void AskFor(const CInv& inv)
259 // We're using mapAskFor as a priority queue,
260 // the key is the earliest time the request can be sent
261 int64& nRequestTime = mapAlreadyAskedFor[inv];
262 printf("askfor %s %"PRI64d"\n", inv.ToString().c_str(), nRequestTime);
264 // Make sure not to reuse time indexes to keep things in the same order
265 int64 nNow = (GetTime() - 1) * 1000000;
266 static int64 nLastTime;
268 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 ENTER_CRITICAL_SECTION(cs_vSend);
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);
299 LEAVE_CRITICAL_SECTION(cs_vSend);
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);
337 LEAVE_CRITICAL_SECTION(cs_vSend);
340 void EndMessageAbortIfEmpty()
342 if (nHeaderStart == -1)
344 int nSize = vSend.size() - nMessageStart;
355 /// when NTP implemented, change to just nTime = GetAdjustedTime()
356 int64 nTime = (fInbound ? GetAdjustedTime() : GetTime());
357 CAddress addrYou = (fUseProxy ? CAddress("0.0.0.0") : addr);
358 CAddress addrMe = (fUseProxy || !addrLocalHost.IsRoutable() ? CAddress("0.0.0.0") : addrLocalHost);
359 RAND_bytes((unsigned char*)&nLocalHostNonce, sizeof(nLocalHostNonce));
360 PushMessage("version", VERSION, nLocalServices, nTime, addrYou, addrMe,
361 nLocalHostNonce, std::string(pszSubVer), nBestHeight);
367 void PushMessage(const char* pszCommand)
371 BeginMessage(pszCommand);
381 template<typename T1>
382 void PushMessage(const char* pszCommand, const T1& a1)
386 BeginMessage(pszCommand);
397 template<typename T1, typename T2>
398 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2)
402 BeginMessage(pszCommand);
413 template<typename T1, typename T2, typename T3>
414 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3)
418 BeginMessage(pszCommand);
419 vSend << a1 << a2 << a3;
429 template<typename T1, typename T2, typename T3, typename T4>
430 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4)
434 BeginMessage(pszCommand);
435 vSend << a1 << a2 << a3 << a4;
445 template<typename T1, typename T2, typename T3, typename T4, typename T5>
446 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4, const T5& a5)
450 BeginMessage(pszCommand);
451 vSend << a1 << a2 << a3 << a4 << a5;
461 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6>
462 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4, const T5& a5, const T6& a6)
466 BeginMessage(pszCommand);
467 vSend << a1 << a2 << a3 << a4 << a5 << a6;
477 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7>
478 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)
482 BeginMessage(pszCommand);
483 vSend << a1 << a2 << a3 << a4 << a5 << a6 << a7;
493 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8>
494 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)
498 BeginMessage(pszCommand);
499 vSend << a1 << a2 << a3 << a4 << a5 << a6 << a7 << a8;
509 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9>
510 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)
514 BeginMessage(pszCommand);
515 vSend << a1 << a2 << a3 << a4 << a5 << a6 << a7 << a8 << a9;
526 void PushRequest(const char* pszCommand,
527 void (*fn)(void*, CDataStream&), void* param1)
530 RAND_bytes((unsigned char*)&hashReply, sizeof(hashReply));
532 CRITICAL_BLOCK(cs_mapRequests)
533 mapRequests[hashReply] = CRequestTracker(fn, param1);
535 PushMessage(pszCommand, hashReply);
538 template<typename T1>
539 void PushRequest(const char* pszCommand, const T1& a1,
540 void (*fn)(void*, CDataStream&), void* param1)
543 RAND_bytes((unsigned char*)&hashReply, sizeof(hashReply));
545 CRITICAL_BLOCK(cs_mapRequests)
546 mapRequests[hashReply] = CRequestTracker(fn, param1);
548 PushMessage(pszCommand, hashReply, a1);
551 template<typename T1, typename T2>
552 void PushRequest(const char* pszCommand, const T1& a1, const T2& a2,
553 void (*fn)(void*, CDataStream&), void* param1)
556 RAND_bytes((unsigned char*)&hashReply, sizeof(hashReply));
558 CRITICAL_BLOCK(cs_mapRequests)
559 mapRequests[hashReply] = CRequestTracker(fn, param1);
561 PushMessage(pszCommand, hashReply, a1, a2);
566 void PushGetBlocks(CBlockIndex* pindexBegin, uint256 hashEnd);
567 bool IsSubscribed(unsigned int nChannel);
568 void Subscribe(unsigned int nChannel, unsigned int nHops=0);
569 void CancelSubscribe(unsigned int nChannel);
570 void CloseSocketDisconnect();
583 inline void RelayInventory(const CInv& inv)
585 // Put on lists to offer to the other nodes
586 CRITICAL_BLOCK(cs_vNodes)
587 BOOST_FOREACH(CNode* pnode, vNodes)
588 pnode->PushInventory(inv);
592 void RelayMessage(const CInv& inv, const T& a)
594 CDataStream ss(SER_NETWORK);
597 RelayMessage(inv, ss);
601 inline void RelayMessage<>(const CInv& inv, const CDataStream& ss)
603 CRITICAL_BLOCK(cs_mapRelay)
605 // Expire old relay messages
606 while (!vRelayExpiration.empty() && vRelayExpiration.front().first < GetTime())
608 mapRelay.erase(vRelayExpiration.front().second);
609 vRelayExpiration.pop_front();
612 // Save original serialized message so newer versions are preserved
614 vRelayExpiration.push_back(std::make_pair(GetTime() + 15 * 60, inv));
628 // Templates for the publish and subscription system.
629 // The object being published as T& obj needs to have:
630 // a set<unsigned int> setSources member
631 // specializations of AdvertInsert and AdvertErase
632 // Currently implemented for CTable and CProduct.
636 void AdvertStartPublish(CNode* pfrom, unsigned int nChannel, unsigned int nHops, T& obj)
639 obj.setSources.insert(pfrom->addr.ip);
641 if (!AdvertInsert(obj))
645 CRITICAL_BLOCK(cs_vNodes)
646 BOOST_FOREACH(CNode* pnode, vNodes)
647 if (pnode != pfrom && (nHops < PUBLISH_HOPS || pnode->IsSubscribed(nChannel)))
648 pnode->PushMessage("publish", nChannel, nHops, obj);
652 void AdvertStopPublish(CNode* pfrom, unsigned int nChannel, unsigned int nHops, T& obj)
654 uint256 hash = obj.GetHash();
656 CRITICAL_BLOCK(cs_vNodes)
657 BOOST_FOREACH(CNode* pnode, vNodes)
658 if (pnode != pfrom && (nHops < PUBLISH_HOPS || pnode->IsSubscribed(nChannel)))
659 pnode->PushMessage("pub-cancel", nChannel, nHops, hash);
665 void AdvertRemoveSource(CNode* pfrom, unsigned int nChannel, unsigned int nHops, T& obj)
668 obj.setSources.erase(pfrom->addr.ip);
670 // If no longer supported by any sources, cancel it
671 if (obj.setSources.empty())
672 AdvertStopPublish(pfrom, nChannel, nHops, obj);