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,
87 extern bool fAllowDNS;
88 extern uint64 nLocalServices;
89 extern CAddress addrLocalHost;
90 extern CAddress addrSeenByPeer;
91 extern uint64 nLocalHostNonce;
92 extern boost::array<int, THREAD_MAX> vnThreadsRunning;
93 extern CAddrMan addrman;
95 extern std::vector<CNode*> vNodes;
96 extern CCriticalSection cs_vNodes;
97 extern std::map<CInv, CDataStream> mapRelay;
98 extern std::deque<std::pair<int64, CInv> > vRelayExpiration;
99 extern CCriticalSection cs_mapRelay;
100 extern std::map<CInv, int64> mapAlreadyAskedFor;
107 /** Information about a peer */
116 CCriticalSection cs_vSend;
117 CCriticalSection cs_vRecv;
120 int64 nLastSendEmpty;
121 int64 nTimeConnected;
123 unsigned int nMessageStart;
126 std::string strSubVer;
130 bool fSuccessfullyConnected;
132 bool fHasGrant; // whether to call semOutbound.post() at disconnect
136 // Denial-of-service detection/prevention
137 // Key is ip address, value is banned-until-time
138 static std::map<CNetAddr, int64> setBanned;
139 static CCriticalSection cs_setBanned;
144 std::map<uint256, CRequestTracker> mapRequests;
145 CCriticalSection cs_mapRequests;
146 uint256 hashContinue;
147 CBlockIndex* pindexLastGetBlocksBegin;
148 uint256 hashLastGetBlocksEnd;
152 std::vector<CAddress> vAddrToSend;
153 std::set<CAddress> setAddrKnown;
155 std::set<uint256> setKnown;
156 uint256 hashCheckpointKnown; // ppcoin: known sent sync-checkpoint
158 // inventory based relay
159 mruset<CInv> setInventoryKnown;
160 std::vector<CInv> vInventoryToSend;
161 CCriticalSection cs_inventory;
162 std::multimap<int64, CInv> mapAskFor;
164 CNode(SOCKET hSocketIn, CAddress addrIn, bool fInboundIn=false) : vSend(SER_NETWORK, MIN_PROTO_VERSION), vRecv(SER_NETWORK, MIN_PROTO_VERSION)
170 nLastSendEmpty = GetTime();
171 nTimeConnected = GetTime();
177 fClient = false; // set by version message
179 fInbound = fInboundIn;
180 fNetworkNode = false;
181 fSuccessfullyConnected = false;
186 pindexLastGetBlocksBegin = 0;
187 hashLastGetBlocksEnd = 0;
188 nStartingHeight = -1;
191 hashCheckpointKnown = 0;
192 setInventoryKnown.max_size(SendBufferSize() / 1000);
194 // Be shy and don't send version until we hear
201 if (hSocket != INVALID_SOCKET)
203 closesocket(hSocket);
204 hSocket = INVALID_SOCKET;
210 void operator=(const CNode&);
216 return std::max(nRefCount, 0) + (GetTime() < nReleaseTime ? 1 : 0);
219 CNode* AddRef(int64 nTimeout=0)
222 nReleaseTime = std::max(nReleaseTime, GetTime() + nTimeout);
235 void AddAddressKnown(const CAddress& addr)
237 setAddrKnown.insert(addr);
240 void PushAddress(const CAddress& addr)
242 // Known checking here is only to save space from duplicates.
243 // SendMessages will filter it again for knowns that were added
244 // after addresses were pushed.
245 if (addr.IsValid() && !setAddrKnown.count(addr))
246 vAddrToSend.push_back(addr);
250 void AddInventoryKnown(const CInv& inv)
254 setInventoryKnown.insert(inv);
258 void PushInventory(const CInv& inv)
262 if (!setInventoryKnown.count(inv))
263 vInventoryToSend.push_back(inv);
267 void AskFor(const CInv& inv)
269 // We're using mapAskFor as a priority queue,
270 // the key is the earliest time the request can be sent
271 int64& nRequestTime = mapAlreadyAskedFor[inv];
272 printf("askfor %s %"PRI64d"\n", inv.ToString().c_str(), nRequestTime);
274 // Make sure not to reuse time indexes to keep things in the same order
275 int64 nNow = (GetTime() - 1) * 1000000;
276 static int64 nLastTime;
278 nNow = std::max(nNow, nLastTime);
281 // Each retry is 2 minutes after the last
282 nRequestTime = std::max(nRequestTime + 2 * 60 * 1000000, nNow);
283 mapAskFor.insert(std::make_pair(nRequestTime, inv));
288 void BeginMessage(const char* pszCommand)
290 ENTER_CRITICAL_SECTION(cs_vSend);
291 if (nHeaderStart != -1)
293 nHeaderStart = vSend.size();
294 vSend << CMessageHeader(pszCommand, 0);
295 nMessageStart = vSend.size();
297 printf("%s ", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());
298 printf("sending: %s ", pszCommand);
304 if (nHeaderStart < 0)
306 vSend.resize(nHeaderStart);
309 LEAVE_CRITICAL_SECTION(cs_vSend);
312 printf("(aborted)\n");
317 if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
319 printf("dropmessages DROPPING SEND MESSAGE\n");
324 if (nHeaderStart < 0)
328 unsigned int nSize = vSend.size() - nMessageStart;
329 memcpy((char*)&vSend[nHeaderStart] + offsetof(CMessageHeader, nMessageSize), &nSize, sizeof(nSize));
332 uint256 hash = Hash(vSend.begin() + nMessageStart, vSend.end());
333 unsigned int nChecksum = 0;
334 memcpy(&nChecksum, &hash, sizeof(nChecksum));
335 assert(nMessageStart - nHeaderStart >= offsetof(CMessageHeader, nChecksum) + sizeof(nChecksum));
336 memcpy((char*)&vSend[nHeaderStart] + offsetof(CMessageHeader, nChecksum), &nChecksum, sizeof(nChecksum));
339 printf("(%d bytes)\n", nSize);
344 LEAVE_CRITICAL_SECTION(cs_vSend);
347 void EndMessageAbortIfEmpty()
349 if (nHeaderStart < 0)
351 int nSize = vSend.size() - nMessageStart;
363 void PushMessage(const char* pszCommand)
367 BeginMessage(pszCommand);
377 template<typename T1>
378 void PushMessage(const char* pszCommand, const T1& a1)
382 BeginMessage(pszCommand);
393 template<typename T1, typename T2>
394 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2)
398 BeginMessage(pszCommand);
409 template<typename T1, typename T2, typename T3>
410 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3)
414 BeginMessage(pszCommand);
415 vSend << a1 << a2 << a3;
425 template<typename T1, typename T2, typename T3, typename T4>
426 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4)
430 BeginMessage(pszCommand);
431 vSend << a1 << a2 << a3 << a4;
441 template<typename T1, typename T2, typename T3, typename T4, typename T5>
442 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4, const T5& a5)
446 BeginMessage(pszCommand);
447 vSend << a1 << a2 << a3 << a4 << a5;
457 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6>
458 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4, const T5& a5, const T6& a6)
462 BeginMessage(pszCommand);
463 vSend << a1 << a2 << a3 << a4 << a5 << a6;
473 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7>
474 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)
478 BeginMessage(pszCommand);
479 vSend << a1 << a2 << a3 << a4 << a5 << a6 << a7;
489 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8>
490 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)
494 BeginMessage(pszCommand);
495 vSend << a1 << a2 << a3 << a4 << a5 << a6 << a7 << a8;
505 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9>
506 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)
510 BeginMessage(pszCommand);
511 vSend << a1 << a2 << a3 << a4 << a5 << a6 << a7 << a8 << a9;
522 void PushRequest(const char* pszCommand,
523 void (*fn)(void*, CDataStream&), void* param1)
526 RAND_bytes((unsigned char*)&hashReply, sizeof(hashReply));
529 LOCK(cs_mapRequests);
530 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));
544 LOCK(cs_mapRequests);
545 mapRequests[hashReply] = CRequestTracker(fn, param1);
548 PushMessage(pszCommand, hashReply, a1);
551 template<typename T1, typename T2>
552 void PushRequest(const char* pszCommand, const T1& a1, const T2& a2,
553 void (*fn)(void*, CDataStream&), void* param1)
556 RAND_bytes((unsigned char*)&hashReply, sizeof(hashReply));
559 LOCK(cs_mapRequests);
560 mapRequests[hashReply] = CRequestTracker(fn, param1);
563 PushMessage(pszCommand, hashReply, a1, a2);
568 void PushGetBlocks(CBlockIndex* pindexBegin, uint256 hashEnd);
569 bool IsSubscribed(unsigned int nChannel);
570 void Subscribe(unsigned int nChannel, unsigned int nHops=0);
571 void CancelSubscribe(unsigned int nChannel);
572 void CloseSocketDisconnect();
576 // Denial-of-service detection/prevention
577 // The idea is to detect peers that are behaving
578 // badly and disconnect/ban them, but do it in a
579 // one-coding-mistake-won't-shatter-the-entire-network
581 // IMPORTANT: There should be nothing I can give a
582 // node that it will forward on that will make that
583 // node's peers drop it. If there is, an attacker
584 // can isolate a node and/or try to split the network.
585 // Dropping a node for sending stuff that is invalid
586 // now but might be valid in a later version is also
587 // dangerous, because it can cause a network split
588 // between nodes running old code and nodes running
590 static void ClearBanned(); // needed for unit testing
591 static bool IsBanned(CNetAddr ip);
592 bool Misbehaving(int howmuch); // 1 == a little, 100 == a lot
604 inline void RelayInventory(const CInv& inv)
606 // Put on lists to offer to the other nodes
609 BOOST_FOREACH(CNode* pnode, vNodes)
610 pnode->PushInventory(inv);
615 void RelayMessage(const CInv& inv, const T& a)
617 CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
620 RelayMessage(inv, ss);
624 inline void RelayMessage<>(const CInv& inv, const CDataStream& ss)
628 // Expire old relay messages
629 while (!vRelayExpiration.empty() && vRelayExpiration.front().first < GetTime())
631 mapRelay.erase(vRelayExpiration.front().second);
632 vRelayExpiration.pop_front();
635 // Save original serialized message so newer versions are preserved
636 mapRelay.insert(std::make_pair(inv, ss));
637 vRelayExpiration.push_back(std::make_pair(GetTime() + 15 * 60, inv));