1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2012 The Bitcoin developers
3 // Copyright (c) 2012 The PPCoin developers
4 // Distributed under the MIT/X11 software license, see the accompanying
5 // file COPYING 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>
24 class CRequestTracker;
27 extern int nBestHeight;
31 inline unsigned int ReceiveBufferSize() { return 1000*GetArg("-maxreceivebuffer", 10*1000); }
32 inline unsigned int SendBufferSize() { return 1000*GetArg("-maxsendbuffer", 10*1000); }
34 bool RecvLine(SOCKET hSocket, std::string& strLine);
35 bool GetMyExternalIP(CNetAddr& ipRet);
36 void AddressCurrentlyConnected(const CService& addr);
37 CNode* FindNode(const CNetAddr& ip);
38 CNode* FindNode(const CService& ip);
39 CNode* ConnectNode(CAddress addrConnect, int64 nTimeout=0);
40 void MapPort(bool fMapPort);
41 bool BindListenPort(std::string& strError=REF(std::string()));
42 void StartNode(void* parg);
54 void (*fn)(void*, CDataStream&);
57 explicit CRequestTracker(void (*fnIn)(void*, CDataStream&)=NULL, void* param1In=NULL)
74 THREAD_OPENCONNECTIONS,
75 THREAD_MESSAGEHANDLER,
80 THREAD_ADDEDCONNECTIONS,
88 extern bool fAllowDNS;
89 extern uint64 nLocalServices;
90 extern CAddress addrLocalHost;
91 extern CAddress addrSeenByPeer;
92 extern uint64 nLocalHostNonce;
93 extern boost::array<int, THREAD_MAX> vnThreadsRunning;
94 extern CAddrMan addrman;
96 extern std::vector<CNode*> vNodes;
97 extern CCriticalSection cs_vNodes;
98 extern std::map<CInv, CDataStream> mapRelay;
99 extern std::deque<std::pair<int64, CInv> > vRelayExpiration;
100 extern CCriticalSection cs_mapRelay;
101 extern std::map<CInv, int64> mapAlreadyAskedFor;
108 /** Information about a peer */
117 CCriticalSection cs_vSend;
118 CCriticalSection cs_vRecv;
121 int64 nLastSendEmpty;
122 int64 nTimeConnected;
124 unsigned int nMessageStart;
127 std::string strSubVer;
131 bool fSuccessfullyConnected;
133 bool fHasGrant; // whether to call semOutbound.post() at disconnect
137 // Denial-of-service detection/prevention
138 // Key is ip address, value is banned-until-time
139 static std::map<CNetAddr, int64> setBanned;
140 static CCriticalSection cs_setBanned;
145 std::map<uint256, CRequestTracker> mapRequests;
146 CCriticalSection cs_mapRequests;
147 uint256 hashContinue;
148 CBlockIndex* pindexLastGetBlocksBegin;
149 uint256 hashLastGetBlocksEnd;
153 std::vector<CAddress> vAddrToSend;
154 std::set<CAddress> setAddrKnown;
156 std::set<uint256> setKnown;
157 uint256 hashCheckpointKnown; // ppcoin: known sent sync-checkpoint
159 // inventory based relay
160 mruset<CInv> setInventoryKnown;
161 std::vector<CInv> vInventoryToSend;
162 CCriticalSection cs_inventory;
163 std::multimap<int64, CInv> mapAskFor;
165 CNode(SOCKET hSocketIn, CAddress addrIn, bool fInboundIn=false) : vSend(SER_NETWORK, MIN_PROTO_VERSION), vRecv(SER_NETWORK, MIN_PROTO_VERSION)
171 nLastSendEmpty = GetTime();
172 nTimeConnected = GetTime();
178 fClient = false; // set by version message
180 fInbound = fInboundIn;
181 fNetworkNode = false;
182 fSuccessfullyConnected = false;
187 pindexLastGetBlocksBegin = 0;
188 hashLastGetBlocksEnd = 0;
189 nStartingHeight = -1;
192 hashCheckpointKnown = 0;
193 setInventoryKnown.max_size(SendBufferSize() / 1000);
195 // Be shy and don't send version until we hear
202 if (hSocket != INVALID_SOCKET)
204 closesocket(hSocket);
205 hSocket = INVALID_SOCKET;
211 void operator=(const CNode&);
217 return std::max(nRefCount, 0) + (GetTime() < nReleaseTime ? 1 : 0);
220 CNode* AddRef(int64 nTimeout=0)
223 nReleaseTime = std::max(nReleaseTime, GetTime() + nTimeout);
236 void AddAddressKnown(const CAddress& addr)
238 setAddrKnown.insert(addr);
241 void PushAddress(const CAddress& addr)
243 // Known checking here is only to save space from duplicates.
244 // SendMessages will filter it again for knowns that were added
245 // after addresses were pushed.
246 if (addr.IsValid() && !setAddrKnown.count(addr))
247 vAddrToSend.push_back(addr);
251 void AddInventoryKnown(const CInv& inv)
255 setInventoryKnown.insert(inv);
259 void PushInventory(const CInv& inv)
263 if (!setInventoryKnown.count(inv))
264 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;
279 nNow = std::max(nNow, nLastTime);
282 // Each retry is 2 minutes after the last
283 nRequestTime = std::max(nRequestTime + 2 * 60 * 1000000, nNow);
284 mapAskFor.insert(std::make_pair(nRequestTime, inv));
289 void BeginMessage(const char* pszCommand)
291 ENTER_CRITICAL_SECTION(cs_vSend);
292 if (nHeaderStart != -1)
294 nHeaderStart = vSend.size();
295 vSend << CMessageHeader(pszCommand, 0);
296 nMessageStart = vSend.size();
298 printf("%s ", DateTimeStrFormat(GetTime()).c_str());
299 printf("sending: %s ", pszCommand);
305 if (nHeaderStart < 0)
307 vSend.resize(nHeaderStart);
310 LEAVE_CRITICAL_SECTION(cs_vSend);
313 printf("(aborted)\n");
318 if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
320 printf("dropmessages DROPPING SEND MESSAGE\n");
325 if (nHeaderStart < 0)
329 unsigned int nSize = vSend.size() - nMessageStart;
330 memcpy((char*)&vSend[nHeaderStart] + offsetof(CMessageHeader, nMessageSize), &nSize, sizeof(nSize));
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));
340 printf("(%d bytes)\n", nSize);
345 LEAVE_CRITICAL_SECTION(cs_vSend);
348 void EndMessageAbortIfEmpty()
350 if (nHeaderStart < 0)
352 int nSize = vSend.size() - nMessageStart;
364 void PushMessage(const char* pszCommand)
368 BeginMessage(pszCommand);
378 template<typename T1>
379 void PushMessage(const char* pszCommand, const T1& a1)
383 BeginMessage(pszCommand);
394 template<typename T1, typename T2>
395 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2)
399 BeginMessage(pszCommand);
410 template<typename T1, typename T2, typename T3>
411 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3)
415 BeginMessage(pszCommand);
416 vSend << a1 << a2 << a3;
426 template<typename T1, typename T2, typename T3, typename T4>
427 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4)
431 BeginMessage(pszCommand);
432 vSend << a1 << a2 << a3 << a4;
442 template<typename T1, typename T2, typename T3, typename T4, typename T5>
443 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4, const T5& a5)
447 BeginMessage(pszCommand);
448 vSend << a1 << a2 << a3 << a4 << a5;
458 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6>
459 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4, const T5& a5, const T6& a6)
463 BeginMessage(pszCommand);
464 vSend << a1 << a2 << a3 << a4 << a5 << a6;
474 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7>
475 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)
479 BeginMessage(pszCommand);
480 vSend << a1 << a2 << a3 << a4 << a5 << a6 << a7;
490 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8>
491 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)
495 BeginMessage(pszCommand);
496 vSend << a1 << a2 << a3 << a4 << a5 << a6 << a7 << a8;
506 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9>
507 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)
511 BeginMessage(pszCommand);
512 vSend << a1 << a2 << a3 << a4 << a5 << a6 << a7 << a8 << a9;
523 void PushRequest(const char* pszCommand,
524 void (*fn)(void*, CDataStream&), void* param1)
527 RAND_bytes((unsigned char*)&hashReply, sizeof(hashReply));
530 LOCK(cs_mapRequests);
531 mapRequests[hashReply] = CRequestTracker(fn, param1);
534 PushMessage(pszCommand, hashReply);
537 template<typename T1>
538 void PushRequest(const char* pszCommand, const T1& a1,
539 void (*fn)(void*, CDataStream&), void* param1)
542 RAND_bytes((unsigned char*)&hashReply, sizeof(hashReply));
545 LOCK(cs_mapRequests);
546 mapRequests[hashReply] = CRequestTracker(fn, param1);
549 PushMessage(pszCommand, hashReply, a1);
552 template<typename T1, typename T2>
553 void PushRequest(const char* pszCommand, const T1& a1, const T2& a2,
554 void (*fn)(void*, CDataStream&), void* param1)
557 RAND_bytes((unsigned char*)&hashReply, sizeof(hashReply));
560 LOCK(cs_mapRequests);
561 mapRequests[hashReply] = CRequestTracker(fn, param1);
564 PushMessage(pszCommand, hashReply, a1, a2);
569 void PushGetBlocks(CBlockIndex* pindexBegin, uint256 hashEnd);
570 bool IsSubscribed(unsigned int nChannel);
571 void Subscribe(unsigned int nChannel, unsigned int nHops=0);
572 void CancelSubscribe(unsigned int nChannel);
573 void CloseSocketDisconnect();
577 // Denial-of-service detection/prevention
578 // The idea is to detect peers that are behaving
579 // badly and disconnect/ban them, but do it in a
580 // one-coding-mistake-won't-shatter-the-entire-network
582 // IMPORTANT: There should be nothing I can give a
583 // node that it will forward on that will make that
584 // node's peers drop it. If there is, an attacker
585 // can isolate a node and/or try to split the network.
586 // Dropping a node for sending stuff that is invalid
587 // now but might be valid in a later version is also
588 // dangerous, because it can cause a network split
589 // between nodes running old code and nodes running
591 static void ClearBanned(); // needed for unit testing
592 static bool IsBanned(CNetAddr ip);
593 bool Misbehaving(int howmuch); // 1 == a little, 100 == a lot
605 inline void RelayInventory(const CInv& inv)
607 // Put on lists to offer to the other nodes
610 BOOST_FOREACH(CNode* pnode, vNodes)
611 pnode->PushInventory(inv);
616 void RelayMessage(const CInv& inv, const T& a)
618 CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
621 RelayMessage(inv, ss);
625 inline void RelayMessage<>(const CInv& inv, const CDataStream& ss)
629 // Expire old relay messages
630 while (!vRelayExpiration.empty() && vRelayExpiration.front().first < GetTime())
632 mapRelay.erase(vRelayExpiration.front().second);
633 vRelayExpiration.pop_front();
636 // Save original serialized message so newer versions are preserved
637 mapRelay.insert(std::make_pair(inv, ss));
638 vRelayExpiration.push_back(std::make_pair(GetTime() + 15 * 60, inv));