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);
292 if (nHeaderStart == -1)
294 vSend.resize(nHeaderStart);
298 printf("(aborted)\n");
303 if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
305 printf("dropmessages DROPPING SEND MESSAGE\n");
310 if (nHeaderStart == -1)
314 unsigned int nSize = vSend.size() - nMessageStart;
315 memcpy((char*)&vSend[nHeaderStart] + offsetof(CMessageHeader, nMessageSize), &nSize, sizeof(nSize));
318 if (vSend.GetVersion() >= 209)
320 uint256 hash = Hash(vSend.begin() + nMessageStart, vSend.end());
321 unsigned int nChecksum = 0;
322 memcpy(&nChecksum, &hash, sizeof(nChecksum));
323 assert(nMessageStart - nHeaderStart >= offsetof(CMessageHeader, nChecksum) + sizeof(nChecksum));
324 memcpy((char*)&vSend[nHeaderStart] + offsetof(CMessageHeader, nChecksum), &nChecksum, sizeof(nChecksum));
327 printf("(%d bytes) ", nSize);
335 void EndMessageAbortIfEmpty()
337 if (nHeaderStart == -1)
339 int nSize = vSend.size() - nMessageStart;
350 /// when NTP implemented, change to just nTime = GetAdjustedTime()
351 int64 nTime = (fInbound ? GetAdjustedTime() : GetTime());
352 CAddress addrYou = (fUseProxy ? CAddress("0.0.0.0") : addr);
353 CAddress addrMe = (fUseProxy ? CAddress("0.0.0.0") : addrLocalHost);
354 RAND_bytes((unsigned char*)&nLocalHostNonce, sizeof(nLocalHostNonce));
355 PushMessage("version", VERSION, nLocalServices, nTime, addrYou, addrMe,
356 nLocalHostNonce, std::string(pszSubVer), nBestHeight);
362 void PushMessage(const char* pszCommand)
366 BeginMessage(pszCommand);
376 template<typename T1>
377 void PushMessage(const char* pszCommand, const T1& a1)
381 BeginMessage(pszCommand);
392 template<typename T1, typename T2>
393 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2)
397 BeginMessage(pszCommand);
408 template<typename T1, typename T2, typename T3>
409 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3)
413 BeginMessage(pszCommand);
414 vSend << a1 << a2 << a3;
424 template<typename T1, typename T2, typename T3, typename T4>
425 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4)
429 BeginMessage(pszCommand);
430 vSend << a1 << a2 << a3 << a4;
440 template<typename T1, typename T2, typename T3, typename T4, typename T5>
441 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4, const T5& a5)
445 BeginMessage(pszCommand);
446 vSend << a1 << a2 << a3 << a4 << a5;
456 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6>
457 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4, const T5& a5, const T6& a6)
461 BeginMessage(pszCommand);
462 vSend << a1 << a2 << a3 << a4 << a5 << a6;
472 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7>
473 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)
477 BeginMessage(pszCommand);
478 vSend << a1 << a2 << a3 << a4 << a5 << a6 << a7;
488 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8>
489 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)
493 BeginMessage(pszCommand);
494 vSend << a1 << a2 << a3 << a4 << a5 << a6 << a7 << a8;
504 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9>
505 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)
509 BeginMessage(pszCommand);
510 vSend << a1 << a2 << a3 << a4 << a5 << a6 << a7 << a8 << a9;
521 void PushRequest(const char* pszCommand,
522 void (*fn)(void*, CDataStream&), void* param1)
525 RAND_bytes((unsigned char*)&hashReply, sizeof(hashReply));
527 CRITICAL_BLOCK(cs_mapRequests)
528 mapRequests[hashReply] = CRequestTracker(fn, param1);
530 PushMessage(pszCommand, hashReply);
533 template<typename T1>
534 void PushRequest(const char* pszCommand, const T1& a1,
535 void (*fn)(void*, CDataStream&), void* param1)
538 RAND_bytes((unsigned char*)&hashReply, sizeof(hashReply));
540 CRITICAL_BLOCK(cs_mapRequests)
541 mapRequests[hashReply] = CRequestTracker(fn, param1);
543 PushMessage(pszCommand, hashReply, a1);
546 template<typename T1, typename T2>
547 void PushRequest(const char* pszCommand, const T1& a1, const T2& a2,
548 void (*fn)(void*, CDataStream&), void* param1)
551 RAND_bytes((unsigned char*)&hashReply, sizeof(hashReply));
553 CRITICAL_BLOCK(cs_mapRequests)
554 mapRequests[hashReply] = CRequestTracker(fn, param1);
556 PushMessage(pszCommand, hashReply, a1, a2);
561 void PushGetBlocks(CBlockIndex* pindexBegin, uint256 hashEnd);
562 bool IsSubscribed(unsigned int nChannel);
563 void Subscribe(unsigned int nChannel, unsigned int nHops=0);
564 void CancelSubscribe(unsigned int nChannel);
565 void CloseSocketDisconnect();
578 inline void RelayInventory(const CInv& inv)
580 // Put on lists to offer to the other nodes
581 CRITICAL_BLOCK(cs_vNodes)
582 BOOST_FOREACH(CNode* pnode, vNodes)
583 pnode->PushInventory(inv);
587 void RelayMessage(const CInv& inv, const T& a)
589 CDataStream ss(SER_NETWORK);
592 RelayMessage(inv, ss);
596 inline void RelayMessage<>(const CInv& inv, const CDataStream& ss)
598 CRITICAL_BLOCK(cs_mapRelay)
600 // Expire old relay messages
601 while (!vRelayExpiration.empty() && vRelayExpiration.front().first < GetTime())
603 mapRelay.erase(vRelayExpiration.front().second);
604 vRelayExpiration.pop_front();
607 // Save original serialized message so newer versions are preserved
609 vRelayExpiration.push_back(std::make_pair(GetTime() + 15 * 60, inv));
623 // Templates for the publish and subscription system.
624 // The object being published as T& obj needs to have:
625 // a set<unsigned int> setSources member
626 // specializations of AdvertInsert and AdvertErase
627 // Currently implemented for CTable and CProduct.
631 void AdvertStartPublish(CNode* pfrom, unsigned int nChannel, unsigned int nHops, T& obj)
634 obj.setSources.insert(pfrom->addr.ip);
636 if (!AdvertInsert(obj))
640 CRITICAL_BLOCK(cs_vNodes)
641 BOOST_FOREACH(CNode* pnode, vNodes)
642 if (pnode != pfrom && (nHops < PUBLISH_HOPS || pnode->IsSubscribed(nChannel)))
643 pnode->PushMessage("publish", nChannel, nHops, obj);
647 void AdvertStopPublish(CNode* pfrom, unsigned int nChannel, unsigned int nHops, T& obj)
649 uint256 hash = obj.GetHash();
651 CRITICAL_BLOCK(cs_vNodes)
652 BOOST_FOREACH(CNode* pnode, vNodes)
653 if (pnode != pfrom && (nHops < PUBLISH_HOPS || pnode->IsSubscribed(nChannel)))
654 pnode->PushMessage("pub-cancel", nChannel, nHops, hash);
660 void AdvertRemoveSource(CNode* pfrom, unsigned int nChannel, unsigned int nHops, T& obj)
663 obj.setSources.erase(pfrom->addr.ip);
665 // If no longer supported by any sources, cancel it
666 if (obj.setSources.empty())
667 AdvertStopPublish(pfrom, nChannel, nHops, obj);