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>
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 void DNSAddressSeed();
44 bool BindListenPort(std::string& strError=REF(std::string()));
45 void StartNode(void* parg);
57 void (*fn)(void*, CDataStream&);
60 explicit CRequestTracker(void (*fnIn)(void*, CDataStream&)=NULL, void* param1In=NULL)
77 extern bool fAllowDNS;
78 extern uint64 nLocalServices;
79 extern CAddress addrLocalHost;
80 extern uint64 nLocalHostNonce;
81 extern boost::array<int, 10> vnThreadsRunning;
83 extern std::vector<CNode*> vNodes;
84 extern CCriticalSection cs_vNodes;
85 extern std::map<std::vector<unsigned char>, CAddress> mapAddresses;
86 extern CCriticalSection cs_mapAddresses;
87 extern std::map<CInv, CDataStream> mapRelay;
88 extern std::deque<std::pair<int64, CInv> > vRelayExpiration;
89 extern CCriticalSection cs_mapRelay;
90 extern std::map<CInv, int64> mapAlreadyAskedFor;
94 extern CAddress addrProxy;
109 CCriticalSection cs_vSend;
110 CCriticalSection cs_vRecv;
113 int64 nLastSendEmpty;
114 int64 nTimeConnected;
115 unsigned int nHeaderStart;
116 unsigned int nMessageStart;
119 std::string strSubVer;
123 bool fSuccessfullyConnected;
129 std::map<uint256, CRequestTracker> mapRequests;
130 CCriticalSection cs_mapRequests;
131 uint256 hashContinue;
132 CBlockIndex* pindexLastGetBlocksBegin;
133 uint256 hashLastGetBlocksEnd;
137 std::vector<CAddress> vAddrToSend;
138 std::set<CAddress> setAddrKnown;
140 std::set<uint256> setKnown;
142 // inventory based relay
143 std::set<CInv> setInventoryKnown;
144 std::vector<CInv> vInventoryToSend;
145 CCriticalSection cs_inventory;
146 std::multimap<int64, CInv> mapAskFor;
148 // publish and subscription
149 std::vector<char> vfSubscribe;
152 CNode(SOCKET hSocketIn, CAddress addrIn, bool fInboundIn=false)
156 vSend.SetType(SER_NETWORK);
158 vRecv.SetType(SER_NETWORK);
160 // Version 0.2 obsoletes 20 Feb 2012
161 if (GetTime() > 1329696000)
163 vSend.SetVersion(209);
164 vRecv.SetVersion(209);
168 nLastSendEmpty = GetTime();
169 nTimeConnected = GetTime();
175 fClient = false; // set by version message
176 fInbound = fInboundIn;
177 fNetworkNode = false;
178 fSuccessfullyConnected = false;
183 pindexLastGetBlocksBegin = 0;
184 hashLastGetBlocksEnd = 0;
185 nStartingHeight = -1;
187 vfSubscribe.assign(256, false);
189 // Be shy and don't send version until we hear
196 if (hSocket != INVALID_SOCKET)
198 closesocket(hSocket);
199 hSocket = INVALID_SOCKET;
205 void operator=(const CNode&);
211 return std::max(nRefCount, 0) + (GetTime() < nReleaseTime ? 1 : 0);
214 CNode* AddRef(int64 nTimeout=0)
217 nReleaseTime = std::max(nReleaseTime, GetTime() + nTimeout);
230 void AddAddressKnown(const CAddress& addr)
232 setAddrKnown.insert(addr);
235 void PushAddress(const CAddress& addr)
237 // Known checking here is only to save space from duplicates.
238 // SendMessages will filter it again for knowns that were added
239 // after addresses were pushed.
240 if (addr.IsValid() && !setAddrKnown.count(addr))
241 vAddrToSend.push_back(addr);
245 void AddInventoryKnown(const CInv& inv)
247 CRITICAL_BLOCK(cs_inventory)
248 setInventoryKnown.insert(inv);
251 void PushInventory(const CInv& inv)
253 CRITICAL_BLOCK(cs_inventory)
254 if (!setInventoryKnown.count(inv))
255 vInventoryToSend.push_back(inv);
258 void AskFor(const CInv& inv)
260 // We're using mapAskFor as a priority queue,
261 // the key is the earliest time the request can be sent
262 int64& nRequestTime = mapAlreadyAskedFor[inv];
263 printf("askfor %s %"PRI64d"\n", inv.ToString().c_str(), nRequestTime);
265 // Make sure not to reuse time indexes to keep things in the same order
266 int64 nNow = (GetTime() - 1) * 1000000;
267 static int64 nLastTime;
268 nLastTime = nNow = std::max(nNow, ++nLastTime);
270 // Each retry is 2 minutes after the last
271 nRequestTime = std::max(nRequestTime + 2 * 60 * 1000000, nNow);
272 mapAskFor.insert(std::make_pair(nRequestTime, inv));
277 void BeginMessage(const char* pszCommand)
279 cs_vSend.Enter("cs_vSend", __FILE__, __LINE__);
280 if (nHeaderStart != -1)
282 nHeaderStart = vSend.size();
283 vSend << CMessageHeader(pszCommand, 0);
284 nMessageStart = vSend.size();
286 printf("%s ", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());
287 printf("sending: %s ", pszCommand);
293 if (nHeaderStart == -1)
295 vSend.resize(nHeaderStart);
299 printf("(aborted)\n");
304 if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
306 printf("dropmessages DROPPING SEND MESSAGE\n");
311 if (nHeaderStart == -1)
315 unsigned int nSize = vSend.size() - nMessageStart;
316 memcpy((char*)&vSend[nHeaderStart] + offsetof(CMessageHeader, nMessageSize), &nSize, sizeof(nSize));
319 if (vSend.GetVersion() >= 209)
321 uint256 hash = Hash(vSend.begin() + nMessageStart, vSend.end());
322 unsigned int nChecksum = 0;
323 memcpy(&nChecksum, &hash, sizeof(nChecksum));
324 assert(nMessageStart - nHeaderStart >= offsetof(CMessageHeader, nChecksum) + sizeof(nChecksum));
325 memcpy((char*)&vSend[nHeaderStart] + offsetof(CMessageHeader, nChecksum), &nChecksum, sizeof(nChecksum));
329 printf("(%d bytes) ", nSize);
338 void EndMessageAbortIfEmpty()
340 if (nHeaderStart == -1)
342 int nSize = vSend.size() - nMessageStart;
353 /// when NTP implemented, change to just nTime = GetAdjustedTime()
354 int64 nTime = (fInbound ? GetAdjustedTime() : GetTime());
355 CAddress addrYou = (fUseProxy ? CAddress("0.0.0.0") : addr);
356 CAddress addrMe = (fUseProxy ? CAddress("0.0.0.0") : addrLocalHost);
357 RAND_bytes((unsigned char*)&nLocalHostNonce, sizeof(nLocalHostNonce));
358 PushMessage("version", VERSION, nLocalServices, nTime, addrYou, addrMe,
359 nLocalHostNonce, std::string(pszSubVer), nBestHeight);
365 void PushMessage(const char* pszCommand)
369 BeginMessage(pszCommand);
379 template<typename T1>
380 void PushMessage(const char* pszCommand, const T1& a1)
384 BeginMessage(pszCommand);
395 template<typename T1, typename T2>
396 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2)
400 BeginMessage(pszCommand);
411 template<typename T1, typename T2, typename T3>
412 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3)
416 BeginMessage(pszCommand);
417 vSend << a1 << a2 << a3;
427 template<typename T1, typename T2, typename T3, typename T4>
428 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4)
432 BeginMessage(pszCommand);
433 vSend << a1 << a2 << a3 << a4;
443 template<typename T1, typename T2, typename T3, typename T4, typename T5>
444 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4, const T5& a5)
448 BeginMessage(pszCommand);
449 vSend << a1 << a2 << a3 << a4 << a5;
459 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6>
460 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4, const T5& a5, const T6& a6)
464 BeginMessage(pszCommand);
465 vSend << a1 << a2 << a3 << a4 << a5 << a6;
475 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7>
476 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)
480 BeginMessage(pszCommand);
481 vSend << a1 << a2 << a3 << a4 << a5 << a6 << a7;
491 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8>
492 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)
496 BeginMessage(pszCommand);
497 vSend << a1 << a2 << a3 << a4 << a5 << a6 << a7 << a8;
507 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9>
508 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)
512 BeginMessage(pszCommand);
513 vSend << a1 << a2 << a3 << a4 << a5 << a6 << a7 << a8 << a9;
524 void PushRequest(const char* pszCommand,
525 void (*fn)(void*, CDataStream&), void* param1)
528 RAND_bytes((unsigned char*)&hashReply, sizeof(hashReply));
530 CRITICAL_BLOCK(cs_mapRequests)
531 mapRequests[hashReply] = CRequestTracker(fn, param1);
533 PushMessage(pszCommand, hashReply);
536 template<typename T1>
537 void PushRequest(const char* pszCommand, const T1& a1,
538 void (*fn)(void*, CDataStream&), void* param1)
541 RAND_bytes((unsigned char*)&hashReply, sizeof(hashReply));
543 CRITICAL_BLOCK(cs_mapRequests)
544 mapRequests[hashReply] = CRequestTracker(fn, param1);
546 PushMessage(pszCommand, hashReply, a1);
549 template<typename T1, typename T2>
550 void PushRequest(const char* pszCommand, const T1& a1, const T2& a2,
551 void (*fn)(void*, CDataStream&), void* param1)
554 RAND_bytes((unsigned char*)&hashReply, sizeof(hashReply));
556 CRITICAL_BLOCK(cs_mapRequests)
557 mapRequests[hashReply] = CRequestTracker(fn, param1);
559 PushMessage(pszCommand, hashReply, a1, a2);
564 void PushGetBlocks(CBlockIndex* pindexBegin, uint256 hashEnd);
565 bool IsSubscribed(unsigned int nChannel);
566 void Subscribe(unsigned int nChannel, unsigned int nHops=0);
567 void CancelSubscribe(unsigned int nChannel);
568 void CloseSocketDisconnect();
581 inline void RelayInventory(const CInv& inv)
583 // Put on lists to offer to the other nodes
584 CRITICAL_BLOCK(cs_vNodes)
585 BOOST_FOREACH(CNode* pnode, vNodes)
586 pnode->PushInventory(inv);
590 void RelayMessage(const CInv& inv, const T& a)
592 CDataStream ss(SER_NETWORK);
595 RelayMessage(inv, ss);
599 inline void RelayMessage<>(const CInv& inv, const CDataStream& ss)
601 CRITICAL_BLOCK(cs_mapRelay)
603 // Expire old relay messages
604 while (!vRelayExpiration.empty() && vRelayExpiration.front().first < GetTime())
606 mapRelay.erase(vRelayExpiration.front().second);
607 vRelayExpiration.pop_front();
610 // Save original serialized message so newer versions are preserved
612 vRelayExpiration.push_back(std::make_pair(GetTime() + 15 * 60, inv));
626 // Templates for the publish and subscription system.
627 // The object being published as T& obj needs to have:
628 // a set<unsigned int> setSources member
629 // specializations of AdvertInsert and AdvertErase
630 // Currently implemented for CTable and CProduct.
634 void AdvertStartPublish(CNode* pfrom, unsigned int nChannel, unsigned int nHops, T& obj)
637 obj.setSources.insert(pfrom->addr.ip);
639 if (!AdvertInsert(obj))
643 CRITICAL_BLOCK(cs_vNodes)
644 BOOST_FOREACH(CNode* pnode, vNodes)
645 if (pnode != pfrom && (nHops < PUBLISH_HOPS || pnode->IsSubscribed(nChannel)))
646 pnode->PushMessage("publish", nChannel, nHops, obj);
650 void AdvertStopPublish(CNode* pfrom, unsigned int nChannel, unsigned int nHops, T& obj)
652 uint256 hash = obj.GetHash();
654 CRITICAL_BLOCK(cs_vNodes)
655 BOOST_FOREACH(CNode* pnode, vNodes)
656 if (pnode != pfrom && (nHops < PUBLISH_HOPS || pnode->IsSubscribed(nChannel)))
657 pnode->PushMessage("pub-cancel", nChannel, nHops, hash);
663 void AdvertRemoveSource(CNode* pfrom, unsigned int nChannel, unsigned int nHops, T& obj)
666 obj.setSources.erase(pfrom->addr.ip);
668 // If no longer supported by any sources, cancel it
669 if (obj.setSources.empty())
670 AdvertStopPublish(pfrom, nChannel, nHops, obj);