1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2012 The Bitcoin developers
3 // Copyright (c) 2012 The PPCoin developers
4 // Copyright (c) 2012-2013 The NovaCoin developers
5 // Distributed under the MIT/X11 software license, see the accompanying
6 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
11 #include <boost/array.hpp>
12 #include <boost/foreach.hpp>
13 #include <openssl/rand.h>
16 #include <arpa/inet.h>
25 class CRequestTracker;
28 extern int nBestHeight;
32 inline unsigned int ReceiveBufferSize() { return 1000*GetArg("-maxreceivebuffer", 10*1000); }
33 inline unsigned int SendBufferSize() { return 1000*GetArg("-maxsendbuffer", 10*1000); }
35 bool RecvLine(SOCKET hSocket, std::string& strLine);
36 bool GetMyExternalIP(CNetAddr& ipRet);
37 void AddressCurrentlyConnected(const CService& addr);
38 CNode* FindNode(const CNetAddr& ip);
39 CNode* FindNode(const CService& ip);
40 CNode* ConnectNode(CAddress addrConnect, int64 nTimeout=0);
41 void MapPort(bool fMapPort);
42 bool BindListenPort(std::string& strError=REF(std::string()));
43 void StartNode(void* parg);
55 void (*fn)(void*, CDataStream&);
58 explicit CRequestTracker(void (*fnIn)(void*, CDataStream&)=NULL, void* param1In=NULL)
75 THREAD_OPENCONNECTIONS,
76 THREAD_MESSAGEHANDLER,
81 THREAD_ADDEDCONNECTIONS,
89 extern bool fAllowDNS;
90 extern uint64 nLocalServices;
91 extern CAddress addrLocalHost;
92 extern CAddress addrSeenByPeer;
93 extern uint64 nLocalHostNonce;
94 extern boost::array<int, THREAD_MAX> vnThreadsRunning;
95 extern CAddrMan addrman;
97 extern std::vector<CNode*> vNodes;
98 extern CCriticalSection cs_vNodes;
99 extern std::map<CInv, CDataStream> mapRelay;
100 extern std::deque<std::pair<int64, CInv> > vRelayExpiration;
101 extern CCriticalSection cs_mapRelay;
102 extern std::map<CInv, int64> mapAlreadyAskedFor;
109 /** Information about a peer */
118 CCriticalSection cs_vSend;
119 CCriticalSection cs_vRecv;
122 int64 nLastSendEmpty;
123 int64 nTimeConnected;
125 unsigned int nMessageStart;
128 std::string strSubVer;
132 bool fSuccessfullyConnected;
134 bool fHasGrant; // whether to call semOutbound.post() at disconnect
138 // Denial-of-service detection/prevention
139 // Key is ip address, value is banned-until-time
140 static std::map<CNetAddr, int64> setBanned;
141 static CCriticalSection cs_setBanned;
146 std::map<uint256, CRequestTracker> mapRequests;
147 CCriticalSection cs_mapRequests;
148 uint256 hashContinue;
149 CBlockIndex* pindexLastGetBlocksBegin;
150 uint256 hashLastGetBlocksEnd;
154 std::vector<CAddress> vAddrToSend;
155 std::set<CAddress> setAddrKnown;
157 std::set<uint256> setKnown;
158 uint256 hashCheckpointKnown; // ppcoin: known sent sync-checkpoint
160 // inventory based relay
161 mruset<CInv> setInventoryKnown;
162 std::vector<CInv> vInventoryToSend;
163 CCriticalSection cs_inventory;
164 std::multimap<int64, CInv> mapAskFor;
166 CNode(SOCKET hSocketIn, CAddress addrIn, bool fInboundIn=false) : vSend(SER_NETWORK, MIN_PROTO_VERSION), vRecv(SER_NETWORK, MIN_PROTO_VERSION)
172 nLastSendEmpty = GetTime();
173 nTimeConnected = GetTime();
179 fClient = false; // set by version message
181 fInbound = fInboundIn;
182 fNetworkNode = false;
183 fSuccessfullyConnected = false;
188 pindexLastGetBlocksBegin = 0;
189 hashLastGetBlocksEnd = 0;
190 nStartingHeight = -1;
193 hashCheckpointKnown = 0;
194 setInventoryKnown.max_size(SendBufferSize() / 1000);
196 // Be shy and don't send version until we hear
203 if (hSocket != INVALID_SOCKET)
205 closesocket(hSocket);
206 hSocket = INVALID_SOCKET;
212 void operator=(const CNode&);
218 return std::max(nRefCount, 0) + (GetTime() < nReleaseTime ? 1 : 0);
221 CNode* AddRef(int64 nTimeout=0)
224 nReleaseTime = std::max(nReleaseTime, GetTime() + nTimeout);
237 void AddAddressKnown(const CAddress& addr)
239 setAddrKnown.insert(addr);
242 void PushAddress(const CAddress& addr)
244 // Known checking here is only to save space from duplicates.
245 // SendMessages will filter it again for knowns that were added
246 // after addresses were pushed.
247 if (addr.IsValid() && !setAddrKnown.count(addr))
248 vAddrToSend.push_back(addr);
252 void AddInventoryKnown(const CInv& inv)
256 setInventoryKnown.insert(inv);
260 void PushInventory(const CInv& inv)
264 if (!setInventoryKnown.count(inv))
265 vInventoryToSend.push_back(inv);
269 void AskFor(const CInv& inv)
271 // We're using mapAskFor as a priority queue,
272 // the key is the earliest time the request can be sent
273 int64& nRequestTime = mapAlreadyAskedFor[inv];
274 printf("askfor %s %"PRI64d"\n", inv.ToString().c_str(), nRequestTime);
276 // Make sure not to reuse time indexes to keep things in the same order
277 int64 nNow = (GetTime() - 1) * 1000000;
278 static int64 nLastTime;
280 nNow = std::max(nNow, nLastTime);
283 // Each retry is 2 minutes after the last
284 nRequestTime = std::max(nRequestTime + 2 * 60 * 1000000, nNow);
285 mapAskFor.insert(std::make_pair(nRequestTime, inv));
290 void BeginMessage(const char* pszCommand)
292 ENTER_CRITICAL_SECTION(cs_vSend);
293 if (nHeaderStart != -1)
295 nHeaderStart = vSend.size();
296 vSend << CMessageHeader(pszCommand, 0);
297 nMessageStart = vSend.size();
299 printf("%s ", DateTimeStrFormat(GetTime()).c_str());
300 printf("sending: %s ", pszCommand);
306 if (nHeaderStart < 0)
308 vSend.resize(nHeaderStart);
311 LEAVE_CRITICAL_SECTION(cs_vSend);
314 printf("(aborted)\n");
319 if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
321 printf("dropmessages DROPPING SEND MESSAGE\n");
326 if (nHeaderStart < 0)
330 unsigned int nSize = vSend.size() - nMessageStart;
331 memcpy((char*)&vSend[nHeaderStart] + offsetof(CMessageHeader, nMessageSize), &nSize, sizeof(nSize));
334 uint256 hash = Hash(vSend.begin() + nMessageStart, vSend.end());
335 unsigned int nChecksum = 0;
336 memcpy(&nChecksum, &hash, sizeof(nChecksum));
337 assert(nMessageStart - nHeaderStart >= offsetof(CMessageHeader, nChecksum) + sizeof(nChecksum));
338 memcpy((char*)&vSend[nHeaderStart] + offsetof(CMessageHeader, nChecksum), &nChecksum, sizeof(nChecksum));
341 printf("(%d bytes)\n", nSize);
346 LEAVE_CRITICAL_SECTION(cs_vSend);
349 void EndMessageAbortIfEmpty()
351 if (nHeaderStart < 0)
353 int nSize = vSend.size() - nMessageStart;
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));
531 LOCK(cs_mapRequests);
532 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));
546 LOCK(cs_mapRequests);
547 mapRequests[hashReply] = CRequestTracker(fn, param1);
550 PushMessage(pszCommand, hashReply, a1);
553 template<typename T1, typename T2>
554 void PushRequest(const char* pszCommand, const T1& a1, const T2& a2,
555 void (*fn)(void*, CDataStream&), void* param1)
558 RAND_bytes((unsigned char*)&hashReply, sizeof(hashReply));
561 LOCK(cs_mapRequests);
562 mapRequests[hashReply] = CRequestTracker(fn, param1);
565 PushMessage(pszCommand, hashReply, a1, a2);
570 void PushGetBlocks(CBlockIndex* pindexBegin, uint256 hashEnd);
571 bool IsSubscribed(unsigned int nChannel);
572 void Subscribe(unsigned int nChannel, unsigned int nHops=0);
573 void CancelSubscribe(unsigned int nChannel);
574 void CloseSocketDisconnect();
578 // Denial-of-service detection/prevention
579 // The idea is to detect peers that are behaving
580 // badly and disconnect/ban them, but do it in a
581 // one-coding-mistake-won't-shatter-the-entire-network
583 // IMPORTANT: There should be nothing I can give a
584 // node that it will forward on that will make that
585 // node's peers drop it. If there is, an attacker
586 // can isolate a node and/or try to split the network.
587 // Dropping a node for sending stuff that is invalid
588 // now but might be valid in a later version is also
589 // dangerous, because it can cause a network split
590 // between nodes running old code and nodes running
592 static void ClearBanned(); // needed for unit testing
593 static bool IsBanned(CNetAddr ip);
594 bool Misbehaving(int howmuch); // 1 == a little, 100 == a lot
606 inline void RelayInventory(const CInv& inv)
608 // Put on lists to offer to the other nodes
611 BOOST_FOREACH(CNode* pnode, vNodes)
612 pnode->PushInventory(inv);
617 void RelayMessage(const CInv& inv, const T& a)
619 CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
622 RelayMessage(inv, ss);
626 inline void RelayMessage<>(const CInv& inv, const CDataStream& ss)
630 // Expire old relay messages
631 while (!vRelayExpiration.empty() && vRelayExpiration.front().first < GetTime())
633 mapRelay.erase(vRelayExpiration.front().second);
634 vRelayExpiration.pop_front();
637 // Save original serialized message so newer versions are preserved
638 mapRelay.insert(std::make_pair(inv, ss));
639 vRelayExpiration.push_back(std::make_pair(GetTime() + 15 * 60, inv));