1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2011 The Bitcoin developers
3 // Copyright (c) 2012 The PPCoin developers
4 // Distributed under the MIT/X11 software license, see the accompanying
5 // file license.txt or http://www.opensource.org/licenses/mit-license.php.
10 #include <boost/array.hpp>
11 #include <boost/foreach.hpp>
12 #include <openssl/rand.h>
15 #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 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 CAddress addrSeenByPeer;
81 extern uint64 nLocalHostNonce;
82 extern boost::array<int, 10> vnThreadsRunning;
84 extern std::vector<CNode*> vNodes;
85 extern CCriticalSection cs_vNodes;
86 extern std::map<std::vector<unsigned char>, CAddress> mapAddresses;
87 extern CCriticalSection cs_mapAddresses;
88 extern std::map<CInv, CDataStream> mapRelay;
89 extern std::deque<std::pair<int64, CInv> > vRelayExpiration;
90 extern CCriticalSection cs_mapRelay;
91 extern std::map<CInv, int64> mapAlreadyAskedFor;
95 extern CAddress addrProxy;
110 CCriticalSection cs_vSend;
111 CCriticalSection cs_vRecv;
114 int64 nLastSendEmpty;
115 int64 nTimeConnected;
116 unsigned int nHeaderStart;
117 unsigned int nMessageStart;
120 std::string strSubVer;
124 bool fSuccessfullyConnected;
129 // Denial-of-service detection/prevention
130 // Key is ip address, value is banned-until-time
131 static std::map<unsigned int, int64> setBanned;
132 static CCriticalSection cs_setBanned;
137 std::map<uint256, CRequestTracker> mapRequests;
138 CCriticalSection cs_mapRequests;
139 uint256 hashContinue;
140 CBlockIndex* pindexLastGetBlocksBegin;
141 uint256 hashLastGetBlocksEnd;
145 std::vector<CAddress> vAddrToSend;
146 std::set<CAddress> setAddrKnown;
148 std::set<uint256> setKnown;
149 uint256 hashCheckpointKnown; // ppcoin: known sent sync-checkpoint
151 // inventory based relay
152 std::set<CInv> setInventoryKnown;
153 std::vector<CInv> vInventoryToSend;
154 CCriticalSection cs_inventory;
155 std::multimap<int64, CInv> mapAskFor;
157 // publish and subscription
158 std::vector<char> vfSubscribe;
160 CNode(SOCKET hSocketIn, CAddress addrIn, bool fInboundIn=false)
164 vSend.SetType(SER_NETWORK);
166 vRecv.SetType(SER_NETWORK);
168 // Version 0.2 obsoletes 20 Feb 2012
169 if (GetTime() > 1329696000)
171 vSend.SetVersion(209);
172 vRecv.SetVersion(209);
176 nLastSendEmpty = GetTime();
177 nTimeConnected = GetTime();
183 fClient = false; // set by version message
184 fInbound = fInboundIn;
185 fNetworkNode = false;
186 fSuccessfullyConnected = false;
191 pindexLastGetBlocksBegin = 0;
192 hashLastGetBlocksEnd = 0;
193 nStartingHeight = -1;
195 vfSubscribe.assign(256, false);
197 hashCheckpointKnown = 0;
199 // Be shy and don't send version until we hear
206 if (hSocket != INVALID_SOCKET)
208 closesocket(hSocket);
209 hSocket = INVALID_SOCKET;
215 void operator=(const CNode&);
221 return std::max(nRefCount, 0) + (GetTime() < nReleaseTime ? 1 : 0);
224 CNode* AddRef(int64 nTimeout=0)
227 nReleaseTime = std::max(nReleaseTime, GetTime() + nTimeout);
240 void AddAddressKnown(const CAddress& addr)
242 setAddrKnown.insert(addr);
245 void PushAddress(const CAddress& addr)
247 // Known checking here is only to save space from duplicates.
248 // SendMessages will filter it again for knowns that were added
249 // after addresses were pushed.
250 if (addr.IsValid() && !setAddrKnown.count(addr))
251 vAddrToSend.push_back(addr);
255 void AddInventoryKnown(const CInv& inv)
257 CRITICAL_BLOCK(cs_inventory)
258 setInventoryKnown.insert(inv);
261 void PushInventory(const CInv& inv)
263 CRITICAL_BLOCK(cs_inventory)
264 if (!setInventoryKnown.count(inv))
265 vInventoryToSend.push_back(inv);
268 void AskFor(const CInv& inv)
270 // We're using mapAskFor as a priority queue,
271 // the key is the earliest time the request can be sent
272 int64& nRequestTime = mapAlreadyAskedFor[inv];
273 printf("askfor %s %"PRI64d"\n", inv.ToString().c_str(), nRequestTime);
275 // Make sure not to reuse time indexes to keep things in the same order
276 int64 nNow = (GetTime() - 1) * 1000000;
277 static int64 nLastTime;
278 nLastTime = nNow = std::max(nNow, ++nLastTime);
280 // Each retry is 2 minutes after the last
281 nRequestTime = std::max(nRequestTime + 2 * 60 * 1000000, nNow);
282 mapAskFor.insert(std::make_pair(nRequestTime, inv));
287 void BeginMessage(const char* pszCommand)
289 cs_vSend.Enter("cs_vSend", __FILE__, __LINE__);
290 if (nHeaderStart != -1)
292 nHeaderStart = vSend.size();
293 vSend << CMessageHeader(pszCommand, 0);
294 nMessageStart = vSend.size();
296 printf("%s ", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());
297 printf("sending: %s ", pszCommand);
303 if (nHeaderStart == -1)
305 vSend.resize(nHeaderStart);
311 printf("(aborted)\n");
316 if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
318 printf("dropmessages DROPPING SEND MESSAGE\n");
323 if (nHeaderStart == -1)
327 unsigned int nSize = vSend.size() - nMessageStart;
328 memcpy((char*)&vSend[nHeaderStart] + offsetof(CMessageHeader, nMessageSize), &nSize, sizeof(nSize));
331 if (vSend.GetVersion() >= 209)
333 uint256 hash = Hash(vSend.begin() + nMessageStart, vSend.end());
334 unsigned int nChecksum = 0;
335 memcpy(&nChecksum, &hash, sizeof(nChecksum));
336 assert(nMessageStart - nHeaderStart >= offsetof(CMessageHeader, nChecksum) + sizeof(nChecksum));
337 memcpy((char*)&vSend[nHeaderStart] + offsetof(CMessageHeader, nChecksum), &nChecksum, sizeof(nChecksum));
341 printf("(%d bytes)\n", nSize);
349 void EndMessageAbortIfEmpty()
351 if (nHeaderStart == -1)
353 int nSize = vSend.size() - nMessageStart;
364 /// when NTP implemented, change to just nTime = GetAdjustedTime()
365 int64 nTime = (fInbound ? GetAdjustedTime() : GetTime());
366 CAddress addrYou = (fUseProxy ? CAddress("0.0.0.0") : addr);
367 CAddress addrMe = (fUseProxy ? CAddress("0.0.0.0") : addrLocalHost);
368 RAND_bytes((unsigned char*)&nLocalHostNonce, sizeof(nLocalHostNonce));
369 PushMessage("version", VERSION, nLocalServices, nTime, addrYou, addrMe,
370 nLocalHostNonce, std::string(pszSubVer), nBestHeight);
376 void PushMessage(const char* pszCommand)
380 BeginMessage(pszCommand);
390 template<typename T1>
391 void PushMessage(const char* pszCommand, const T1& a1)
395 BeginMessage(pszCommand);
406 template<typename T1, typename T2>
407 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2)
411 BeginMessage(pszCommand);
422 template<typename T1, typename T2, typename T3>
423 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3)
427 BeginMessage(pszCommand);
428 vSend << a1 << a2 << a3;
438 template<typename T1, typename T2, typename T3, typename T4>
439 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4)
443 BeginMessage(pszCommand);
444 vSend << a1 << a2 << a3 << a4;
454 template<typename T1, typename T2, typename T3, typename T4, typename T5>
455 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4, const T5& a5)
459 BeginMessage(pszCommand);
460 vSend << a1 << a2 << a3 << a4 << a5;
470 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6>
471 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4, const T5& a5, const T6& a6)
475 BeginMessage(pszCommand);
476 vSend << a1 << a2 << a3 << a4 << a5 << a6;
486 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7>
487 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)
491 BeginMessage(pszCommand);
492 vSend << a1 << a2 << a3 << a4 << a5 << a6 << a7;
502 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8>
503 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)
507 BeginMessage(pszCommand);
508 vSend << a1 << a2 << a3 << a4 << a5 << a6 << a7 << a8;
518 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9>
519 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)
523 BeginMessage(pszCommand);
524 vSend << a1 << a2 << a3 << a4 << a5 << a6 << a7 << a8 << a9;
535 void PushRequest(const char* pszCommand,
536 void (*fn)(void*, CDataStream&), void* param1)
539 RAND_bytes((unsigned char*)&hashReply, sizeof(hashReply));
541 CRITICAL_BLOCK(cs_mapRequests)
542 mapRequests[hashReply] = CRequestTracker(fn, param1);
544 PushMessage(pszCommand, hashReply);
547 template<typename T1>
548 void PushRequest(const char* pszCommand, const T1& a1,
549 void (*fn)(void*, CDataStream&), void* param1)
552 RAND_bytes((unsigned char*)&hashReply, sizeof(hashReply));
554 CRITICAL_BLOCK(cs_mapRequests)
555 mapRequests[hashReply] = CRequestTracker(fn, param1);
557 PushMessage(pszCommand, hashReply, a1);
560 template<typename T1, typename T2>
561 void PushRequest(const char* pszCommand, const T1& a1, const T2& a2,
562 void (*fn)(void*, CDataStream&), void* param1)
565 RAND_bytes((unsigned char*)&hashReply, sizeof(hashReply));
567 CRITICAL_BLOCK(cs_mapRequests)
568 mapRequests[hashReply] = CRequestTracker(fn, param1);
570 PushMessage(pszCommand, hashReply, a1, a2);
575 void PushGetBlocks(CBlockIndex* pindexBegin, uint256 hashEnd);
576 bool IsSubscribed(unsigned int nChannel);
577 void Subscribe(unsigned int nChannel, unsigned int nHops=0);
578 void CancelSubscribe(unsigned int nChannel);
579 void CloseSocketDisconnect();
583 // Denial-of-service detection/prevention
584 // The idea is to detect peers that are behaving
585 // badly and disconnect/ban them, but do it in a
586 // one-coding-mistake-won't-shatter-the-entire-network
588 // IMPORTANT: There should be nothing I can give a
589 // node that it will forward on that will make that
590 // node's peers drop it. If there is, an attacker
591 // can isolate a node and/or try to split the network.
592 // Dropping a node for sending stuff that is invalid
593 // now but might be valid in a later version is also
594 // dangerous, because it can cause a network split
595 // between nodes running old code and nodes running
597 static void ClearBanned(); // needed for unit testing
598 static bool IsBanned(unsigned int ip);
599 bool Misbehaving(int howmuch); // 1 == a little, 100 == a lot
611 inline void RelayInventory(const CInv& inv)
613 // Put on lists to offer to the other nodes
614 CRITICAL_BLOCK(cs_vNodes)
615 BOOST_FOREACH(CNode* pnode, vNodes)
616 pnode->PushInventory(inv);
620 void RelayMessage(const CInv& inv, const T& a)
622 CDataStream ss(SER_NETWORK);
625 RelayMessage(inv, ss);
629 inline void RelayMessage<>(const CInv& inv, const CDataStream& ss)
631 CRITICAL_BLOCK(cs_mapRelay)
633 // Expire old relay messages
634 while (!vRelayExpiration.empty() && vRelayExpiration.front().first < GetTime())
636 mapRelay.erase(vRelayExpiration.front().second);
637 vRelayExpiration.pop_front();
640 // Save original serialized message so newer versions are preserved
642 vRelayExpiration.push_back(std::make_pair(GetTime() + 15 * 60, inv));
656 // Templates for the publish and subscription system.
657 // The object being published as T& obj needs to have:
658 // a set<unsigned int> setSources member
659 // specializations of AdvertInsert and AdvertErase
660 // Currently implemented for CTable and CProduct.
664 void AdvertStartPublish(CNode* pfrom, unsigned int nChannel, unsigned int nHops, T& obj)
667 obj.setSources.insert(pfrom->addr.ip);
669 if (!AdvertInsert(obj))
673 CRITICAL_BLOCK(cs_vNodes)
674 BOOST_FOREACH(CNode* pnode, vNodes)
675 if (pnode != pfrom && (nHops < PUBLISH_HOPS || pnode->IsSubscribed(nChannel)))
676 pnode->PushMessage("publish", nChannel, nHops, obj);
680 void AdvertStopPublish(CNode* pfrom, unsigned int nChannel, unsigned int nHops, T& obj)
682 uint256 hash = obj.GetHash();
684 CRITICAL_BLOCK(cs_vNodes)
685 BOOST_FOREACH(CNode* pnode, vNodes)
686 if (pnode != pfrom && (nHops < PUBLISH_HOPS || pnode->IsSubscribed(nChannel)))
687 pnode->PushMessage("pub-cancel", nChannel, nHops, hash);
693 void AdvertRemoveSource(CNode* pfrom, unsigned int nChannel, unsigned int nHops, T& obj)
696 obj.setSources.erase(pfrom->addr.ip);
698 // If no longer supported by any sources, cancel it
699 if (obj.setSources.empty())
700 AdvertStopPublish(pfrom, nChannel, nHops, obj);