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.
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;
25 extern int nConnectTimeout;
29 inline unsigned int ReceiveBufferSize() { return 1000*GetArg("-maxreceivebuffer", 10*1000); }
30 inline unsigned int SendBufferSize() { return 1000*GetArg("-maxsendbuffer", 10*1000); }
31 static const unsigned int PUBLISH_HOPS = 5;
33 bool ConnectSocket(const CAddress& addrConnect, SOCKET& hSocketRet, int nTimeout=nConnectTimeout);
34 bool Lookup(const char *pszName, std::vector<CAddress>& vaddr, int nServices, int nMaxSolutions, bool fAllowLookup = false, int portDefault = 0, bool fAllowPort = false);
35 bool Lookup(const char *pszName, CAddress& addr, int nServices, bool fAllowLookup = false, int portDefault = 0, bool fAllowPort = false);
36 bool GetMyExternalIP(unsigned int& ipRet);
37 bool AddAddress(CAddress addr, int64 nTimePenalty=0, CAddrDB *pAddrDB=NULL);
38 void AddressCurrentlyConnected(const CAddress& addr);
39 CNode* FindNode(unsigned int ip);
40 CNode* ConnectNode(CAddress addrConnect, int64 nTimeout=0);
41 void AbandonRequests(void (*fn)(void*, CDataStream&), void* param1);
42 bool AnySubscribed(unsigned int nChannel);
43 void MapPort(bool fMapPort);
44 void DNSAddressSeed();
45 bool BindListenPort(std::string& strError=REF(std::string()));
46 void StartNode(void* parg);
55 static const char* ppszTypeName[] =
74 CInv(int typeIn, const uint256& hashIn)
80 CInv(const std::string& strType, const uint256& hashIn)
83 for (i = 1; i < ARRAYLEN(ppszTypeName); i++)
85 if (strType == ppszTypeName[i])
91 if (i == ARRAYLEN(ppszTypeName))
92 throw std::out_of_range(strprintf("CInv::CInv(string, uint256) : unknown type '%s'", strType.c_str()));
102 friend inline bool operator<(const CInv& a, const CInv& b)
104 return (a.type < b.type || (a.type == b.type && a.hash < b.hash));
107 bool IsKnownType() const
109 return (type >= 1 && type < ARRAYLEN(ppszTypeName));
112 const char* GetCommand() const
115 throw std::out_of_range(strprintf("CInv::GetCommand() : type=%d unknown type", type));
116 return ppszTypeName[type];
119 std::string ToString() const
121 return strprintf("%s %s", GetCommand(), hash.ToString().substr(0,20).c_str());
126 printf("CInv(%s)\n", ToString().c_str());
134 class CRequestTracker
137 void (*fn)(void*, CDataStream&);
140 explicit CRequestTracker(void (*fnIn)(void*, CDataStream&)=NULL, void* param1In=NULL)
157 extern bool fAllowDNS;
158 extern uint64 nLocalServices;
159 extern CAddress addrLocalHost;
160 extern uint64 nLocalHostNonce;
161 extern boost::array<int, 10> vnThreadsRunning;
163 extern std::vector<CNode*> vNodes;
164 extern CCriticalSection cs_vNodes;
165 extern std::map<std::vector<unsigned char>, CAddress> mapAddresses;
166 extern CCriticalSection cs_mapAddresses;
167 extern std::map<CInv, CDataStream> mapRelay;
168 extern std::deque<std::pair<int64, CInv> > vRelayExpiration;
169 extern CCriticalSection cs_mapRelay;
170 extern std::map<CInv, int64> mapAlreadyAskedFor;
173 extern int fUseProxy;
174 extern CAddress addrProxy;
189 CCriticalSection cs_vSend;
190 CCriticalSection cs_vRecv;
193 int64 nLastSendEmpty;
194 int64 nTimeConnected;
195 unsigned int nHeaderStart;
196 unsigned int nMessageStart;
199 std::string strSubVer;
203 bool fSuccessfullyConnected;
209 std::map<uint256, CRequestTracker> mapRequests;
210 CCriticalSection cs_mapRequests;
211 uint256 hashContinue;
212 CBlockIndex* pindexLastGetBlocksBegin;
213 uint256 hashLastGetBlocksEnd;
217 std::vector<CAddress> vAddrToSend;
218 std::set<CAddress> setAddrKnown;
220 std::set<uint256> setKnown;
222 // inventory based relay
223 std::set<CInv> setInventoryKnown;
224 std::vector<CInv> vInventoryToSend;
225 CCriticalSection cs_inventory;
226 std::multimap<int64, CInv> mapAskFor;
228 // publish and subscription
229 std::vector<char> vfSubscribe;
232 CNode(SOCKET hSocketIn, CAddress addrIn, bool fInboundIn=false)
236 vSend.SetType(SER_NETWORK);
238 vRecv.SetType(SER_NETWORK);
240 // Version 0.2 obsoletes 20 Feb 2012
241 if (GetTime() > 1329696000)
243 vSend.SetVersion(209);
244 vRecv.SetVersion(209);
248 nLastSendEmpty = GetTime();
249 nTimeConnected = GetTime();
255 fClient = false; // set by version message
256 fInbound = fInboundIn;
257 fNetworkNode = false;
258 fSuccessfullyConnected = false;
263 pindexLastGetBlocksBegin = 0;
264 hashLastGetBlocksEnd = 0;
265 nStartingHeight = -1;
267 vfSubscribe.assign(256, false);
269 // Be shy and don't send version until we hear
276 if (hSocket != INVALID_SOCKET)
278 closesocket(hSocket);
279 hSocket = INVALID_SOCKET;
285 void operator=(const CNode&);
291 return std::max(nRefCount, 0) + (GetTime() < nReleaseTime ? 1 : 0);
294 CNode* AddRef(int64 nTimeout=0)
297 nReleaseTime = std::max(nReleaseTime, GetTime() + nTimeout);
310 void AddAddressKnown(const CAddress& addr)
312 setAddrKnown.insert(addr);
315 void PushAddress(const CAddress& addr)
317 // Known checking here is only to save space from duplicates.
318 // SendMessages will filter it again for knowns that were added
319 // after addresses were pushed.
320 if (addr.IsValid() && !setAddrKnown.count(addr))
321 vAddrToSend.push_back(addr);
325 void AddInventoryKnown(const CInv& inv)
327 CRITICAL_BLOCK(cs_inventory)
328 setInventoryKnown.insert(inv);
331 void PushInventory(const CInv& inv)
333 CRITICAL_BLOCK(cs_inventory)
334 if (!setInventoryKnown.count(inv))
335 vInventoryToSend.push_back(inv);
338 void AskFor(const CInv& inv)
340 // We're using mapAskFor as a priority queue,
341 // the key is the earliest time the request can be sent
342 int64& nRequestTime = mapAlreadyAskedFor[inv];
343 printf("askfor %s %"PRI64d"\n", inv.ToString().c_str(), nRequestTime);
345 // Make sure not to reuse time indexes to keep things in the same order
346 int64 nNow = (GetTime() - 1) * 1000000;
347 static int64 nLastTime;
348 nLastTime = nNow = std::max(nNow, ++nLastTime);
350 // Each retry is 2 minutes after the last
351 nRequestTime = std::max(nRequestTime + 2 * 60 * 1000000, nNow);
352 mapAskFor.insert(std::make_pair(nRequestTime, inv));
357 void BeginMessage(const char* pszCommand)
359 cs_vSend.Enter("cs_vSend", __FILE__, __LINE__);
360 if (nHeaderStart != -1)
362 nHeaderStart = vSend.size();
363 vSend << CMessageHeader(pszCommand, 0);
364 nMessageStart = vSend.size();
366 printf("%s ", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());
367 printf("sending: %s ", pszCommand);
372 if (nHeaderStart == -1)
374 vSend.resize(nHeaderStart);
378 printf("(aborted)\n");
383 if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
385 printf("dropmessages DROPPING SEND MESSAGE\n");
390 if (nHeaderStart == -1)
394 unsigned int nSize = vSend.size() - nMessageStart;
395 memcpy((char*)&vSend[nHeaderStart] + offsetof(CMessageHeader, nMessageSize), &nSize, sizeof(nSize));
398 if (vSend.GetVersion() >= 209)
400 uint256 hash = Hash(vSend.begin() + nMessageStart, vSend.end());
401 unsigned int nChecksum = 0;
402 memcpy(&nChecksum, &hash, sizeof(nChecksum));
403 assert(nMessageStart - nHeaderStart >= offsetof(CMessageHeader, nChecksum) + sizeof(nChecksum));
404 memcpy((char*)&vSend[nHeaderStart] + offsetof(CMessageHeader, nChecksum), &nChecksum, sizeof(nChecksum));
407 printf("(%d bytes) ", nSize);
415 void EndMessageAbortIfEmpty()
417 if (nHeaderStart == -1)
419 int nSize = vSend.size() - nMessageStart;
430 /// when NTP implemented, change to just nTime = GetAdjustedTime()
431 int64 nTime = (fInbound ? GetAdjustedTime() : GetTime());
432 CAddress addrYou = (fUseProxy ? CAddress("0.0.0.0") : addr);
433 CAddress addrMe = (fUseProxy ? CAddress("0.0.0.0") : addrLocalHost);
434 RAND_bytes((unsigned char*)&nLocalHostNonce, sizeof(nLocalHostNonce));
435 PushMessage("version", VERSION, nLocalServices, nTime, addrYou, addrMe,
436 nLocalHostNonce, std::string(pszSubVer), nBestHeight);
442 void PushMessage(const char* pszCommand)
446 BeginMessage(pszCommand);
456 template<typename T1>
457 void PushMessage(const char* pszCommand, const T1& a1)
461 BeginMessage(pszCommand);
472 template<typename T1, typename T2>
473 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2)
477 BeginMessage(pszCommand);
488 template<typename T1, typename T2, typename T3>
489 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3)
493 BeginMessage(pszCommand);
494 vSend << a1 << a2 << a3;
504 template<typename T1, typename T2, typename T3, typename T4>
505 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4)
509 BeginMessage(pszCommand);
510 vSend << a1 << a2 << a3 << a4;
520 template<typename T1, typename T2, typename T3, typename T4, typename T5>
521 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4, const T5& a5)
525 BeginMessage(pszCommand);
526 vSend << a1 << a2 << a3 << a4 << a5;
536 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6>
537 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4, const T5& a5, const T6& a6)
541 BeginMessage(pszCommand);
542 vSend << a1 << a2 << a3 << a4 << a5 << a6;
552 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7>
553 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)
557 BeginMessage(pszCommand);
558 vSend << a1 << a2 << a3 << a4 << a5 << a6 << a7;
568 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8>
569 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)
573 BeginMessage(pszCommand);
574 vSend << a1 << a2 << a3 << a4 << a5 << a6 << a7 << a8;
584 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9>
585 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)
589 BeginMessage(pszCommand);
590 vSend << a1 << a2 << a3 << a4 << a5 << a6 << a7 << a8 << a9;
601 void PushRequest(const char* pszCommand,
602 void (*fn)(void*, CDataStream&), void* param1)
605 RAND_bytes((unsigned char*)&hashReply, sizeof(hashReply));
607 CRITICAL_BLOCK(cs_mapRequests)
608 mapRequests[hashReply] = CRequestTracker(fn, param1);
610 PushMessage(pszCommand, hashReply);
613 template<typename T1>
614 void PushRequest(const char* pszCommand, const T1& a1,
615 void (*fn)(void*, CDataStream&), void* param1)
618 RAND_bytes((unsigned char*)&hashReply, sizeof(hashReply));
620 CRITICAL_BLOCK(cs_mapRequests)
621 mapRequests[hashReply] = CRequestTracker(fn, param1);
623 PushMessage(pszCommand, hashReply, a1);
626 template<typename T1, typename T2>
627 void PushRequest(const char* pszCommand, const T1& a1, const T2& a2,
628 void (*fn)(void*, CDataStream&), void* param1)
631 RAND_bytes((unsigned char*)&hashReply, sizeof(hashReply));
633 CRITICAL_BLOCK(cs_mapRequests)
634 mapRequests[hashReply] = CRequestTracker(fn, param1);
636 PushMessage(pszCommand, hashReply, a1, a2);
641 void PushGetBlocks(CBlockIndex* pindexBegin, uint256 hashEnd);
642 bool IsSubscribed(unsigned int nChannel);
643 void Subscribe(unsigned int nChannel, unsigned int nHops=0);
644 void CancelSubscribe(unsigned int nChannel);
645 void CloseSocketDisconnect();
658 inline void RelayInventory(const CInv& inv)
660 // Put on lists to offer to the other nodes
661 CRITICAL_BLOCK(cs_vNodes)
662 BOOST_FOREACH(CNode* pnode, vNodes)
663 pnode->PushInventory(inv);
667 void RelayMessage(const CInv& inv, const T& a)
669 CDataStream ss(SER_NETWORK);
672 RelayMessage(inv, ss);
676 inline void RelayMessage<>(const CInv& inv, const CDataStream& ss)
678 CRITICAL_BLOCK(cs_mapRelay)
680 // Expire old relay messages
681 while (!vRelayExpiration.empty() && vRelayExpiration.front().first < GetTime())
683 mapRelay.erase(vRelayExpiration.front().second);
684 vRelayExpiration.pop_front();
687 // Save original serialized message so newer versions are preserved
689 vRelayExpiration.push_back(std::make_pair(GetTime() + 15 * 60, inv));
703 // Templates for the publish and subscription system.
704 // The object being published as T& obj needs to have:
705 // a set<unsigned int> setSources member
706 // specializations of AdvertInsert and AdvertErase
707 // Currently implemented for CTable and CProduct.
711 void AdvertStartPublish(CNode* pfrom, unsigned int nChannel, unsigned int nHops, T& obj)
714 obj.setSources.insert(pfrom->addr.ip);
716 if (!AdvertInsert(obj))
720 CRITICAL_BLOCK(cs_vNodes)
721 BOOST_FOREACH(CNode* pnode, vNodes)
722 if (pnode != pfrom && (nHops < PUBLISH_HOPS || pnode->IsSubscribed(nChannel)))
723 pnode->PushMessage("publish", nChannel, nHops, obj);
727 void AdvertStopPublish(CNode* pfrom, unsigned int nChannel, unsigned int nHops, T& obj)
729 uint256 hash = obj.GetHash();
731 CRITICAL_BLOCK(cs_vNodes)
732 BOOST_FOREACH(CNode* pnode, vNodes)
733 if (pnode != pfrom && (nHops < PUBLISH_HOPS || pnode->IsSubscribed(nChannel)))
734 pnode->PushMessage("pub-cancel", nChannel, nHops, hash);
740 void AdvertRemoveSource(CNode* pfrom, unsigned int nChannel, unsigned int nHops, T& obj)
743 obj.setSources.erase(pfrom->addr.ip);
745 // If no longer supported by any sources, cancel it
746 if (obj.setSources.empty())
747 AdvertStopPublish(pfrom, nChannel, nHops, obj);