1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2012 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>
23 class CRequestTracker;
26 extern int nBestHeight;
30 inline unsigned int ReceiveBufferSize() { return 1000*GetArg("-maxreceivebuffer", 10*1000); }
31 inline unsigned int SendBufferSize() { return 1000*GetArg("-maxsendbuffer", 10*1000); }
33 bool RecvLine(SOCKET hSocket, std::string& strLine);
34 bool GetMyExternalIP(CNetAddr& ipRet);
35 void AddressCurrentlyConnected(const CService& addr);
36 CNode* FindNode(const CNetAddr& ip);
37 CNode* FindNode(const CService& ip);
38 CNode* ConnectNode(CAddress addrConnect, int64 nTimeout=0);
39 void MapPort(bool fMapPort);
40 bool BindListenPort(std::string& strError=REF(std::string()));
41 void StartNode(void* parg);
53 void (*fn)(void*, CDataStream&);
56 explicit CRequestTracker(void (*fnIn)(void*, CDataStream&)=NULL, void* param1In=NULL)
73 THREAD_OPENCONNECTIONS,
74 THREAD_MESSAGEHANDLER,
79 THREAD_ADDEDCONNECTIONS,
86 extern bool fAllowDNS;
87 extern uint64 nLocalServices;
88 extern CAddress addrLocalHost;
89 extern uint64 nLocalHostNonce;
90 extern boost::array<int, THREAD_MAX> vnThreadsRunning;
91 extern CAddrMan addrman;
93 extern std::vector<CNode*> vNodes;
94 extern CCriticalSection cs_vNodes;
95 extern std::map<CInv, CDataStream> mapRelay;
96 extern std::deque<std::pair<int64, CInv> > vRelayExpiration;
97 extern CCriticalSection cs_mapRelay;
98 extern std::map<CInv, int64> mapAlreadyAskedFor;
105 /** Information about a peer */
114 CCriticalSection cs_vSend;
115 CCriticalSection cs_vRecv;
118 int64 nLastSendEmpty;
119 int64 nTimeConnected;
121 unsigned int nMessageStart;
124 std::string strSubVer;
128 bool fSuccessfullyConnected;
130 bool fHasGrant; // whether to call semOutbound.post() at disconnect
134 // Denial-of-service detection/prevention
135 // Key is ip address, value is banned-until-time
136 static std::map<CNetAddr, int64> setBanned;
137 static CCriticalSection cs_setBanned;
142 std::map<uint256, CRequestTracker> mapRequests;
143 CCriticalSection cs_mapRequests;
144 uint256 hashContinue;
145 CBlockIndex* pindexLastGetBlocksBegin;
146 uint256 hashLastGetBlocksEnd;
150 std::vector<CAddress> vAddrToSend;
151 std::set<CAddress> setAddrKnown;
153 std::set<uint256> setKnown;
155 // inventory based relay
156 mruset<CInv> setInventoryKnown;
157 std::vector<CInv> vInventoryToSend;
158 CCriticalSection cs_inventory;
159 std::multimap<int64, CInv> mapAskFor;
161 CNode(SOCKET hSocketIn, CAddress addrIn, bool fInboundIn=false) : vSend(SER_NETWORK, MIN_PROTO_VERSION), vRecv(SER_NETWORK, MIN_PROTO_VERSION)
167 nLastSendEmpty = GetTime();
168 nTimeConnected = GetTime();
174 fClient = false; // set by version message
176 fInbound = fInboundIn;
177 fNetworkNode = false;
178 fSuccessfullyConnected = false;
183 pindexLastGetBlocksBegin = 0;
184 hashLastGetBlocksEnd = 0;
185 nStartingHeight = -1;
188 setInventoryKnown.max_size(SendBufferSize() / 1000);
190 // Be shy and don't send version until we hear
197 if (hSocket != INVALID_SOCKET)
199 closesocket(hSocket);
200 hSocket = INVALID_SOCKET;
206 void operator=(const CNode&);
212 return std::max(nRefCount, 0) + (GetTime() < nReleaseTime ? 1 : 0);
215 CNode* AddRef(int64 nTimeout=0)
218 nReleaseTime = std::max(nReleaseTime, GetTime() + nTimeout);
231 void AddAddressKnown(const CAddress& addr)
233 setAddrKnown.insert(addr);
236 void PushAddress(const CAddress& addr)
238 // Known checking here is only to save space from duplicates.
239 // SendMessages will filter it again for knowns that were added
240 // after addresses were pushed.
241 if (addr.IsValid() && !setAddrKnown.count(addr))
242 vAddrToSend.push_back(addr);
246 void AddInventoryKnown(const CInv& inv)
250 setInventoryKnown.insert(inv);
254 void PushInventory(const CInv& inv)
258 if (!setInventoryKnown.count(inv))
259 vInventoryToSend.push_back(inv);
263 void AskFor(const CInv& inv)
265 // We're using mapAskFor as a priority queue,
266 // the key is the earliest time the request can be sent
267 int64& nRequestTime = mapAlreadyAskedFor[inv];
268 printf("askfor %s %"PRI64d"\n", inv.ToString().c_str(), nRequestTime);
270 // Make sure not to reuse time indexes to keep things in the same order
271 int64 nNow = (GetTime() - 1) * 1000000;
272 static int64 nLastTime;
274 nNow = std::max(nNow, nLastTime);
277 // Each retry is 2 minutes after the last
278 nRequestTime = std::max(nRequestTime + 2 * 60 * 1000000, nNow);
279 mapAskFor.insert(std::make_pair(nRequestTime, inv));
284 void BeginMessage(const char* pszCommand)
286 ENTER_CRITICAL_SECTION(cs_vSend);
287 if (nHeaderStart != -1)
289 nHeaderStart = vSend.size();
290 vSend << CMessageHeader(pszCommand, 0);
291 nMessageStart = vSend.size();
293 printf("%s ", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());
294 printf("sending: %s ", pszCommand);
300 if (nHeaderStart < 0)
302 vSend.resize(nHeaderStart);
305 LEAVE_CRITICAL_SECTION(cs_vSend);
308 printf("(aborted)\n");
313 if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
315 printf("dropmessages DROPPING SEND MESSAGE\n");
320 if (nHeaderStart < 0)
324 unsigned int nSize = vSend.size() - nMessageStart;
325 memcpy((char*)&vSend[nHeaderStart] + offsetof(CMessageHeader, nMessageSize), &nSize, sizeof(nSize));
328 uint256 hash = Hash(vSend.begin() + nMessageStart, vSend.end());
329 unsigned int nChecksum = 0;
330 memcpy(&nChecksum, &hash, sizeof(nChecksum));
331 assert(nMessageStart - nHeaderStart >= offsetof(CMessageHeader, nChecksum) + sizeof(nChecksum));
332 memcpy((char*)&vSend[nHeaderStart] + offsetof(CMessageHeader, nChecksum), &nChecksum, sizeof(nChecksum));
335 printf("(%d bytes)\n", nSize);
340 LEAVE_CRITICAL_SECTION(cs_vSend);
343 void EndMessageAbortIfEmpty()
345 if (nHeaderStart < 0)
347 int nSize = vSend.size() - nMessageStart;
359 void PushMessage(const char* pszCommand)
363 BeginMessage(pszCommand);
373 template<typename T1>
374 void PushMessage(const char* pszCommand, const T1& a1)
378 BeginMessage(pszCommand);
389 template<typename T1, typename T2>
390 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2)
394 BeginMessage(pszCommand);
405 template<typename T1, typename T2, typename T3>
406 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3)
410 BeginMessage(pszCommand);
411 vSend << a1 << a2 << a3;
421 template<typename T1, typename T2, typename T3, typename T4>
422 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4)
426 BeginMessage(pszCommand);
427 vSend << a1 << a2 << a3 << a4;
437 template<typename T1, typename T2, typename T3, typename T4, typename T5>
438 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4, const T5& a5)
442 BeginMessage(pszCommand);
443 vSend << a1 << a2 << a3 << a4 << a5;
453 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6>
454 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4, const T5& a5, const T6& a6)
458 BeginMessage(pszCommand);
459 vSend << a1 << a2 << a3 << a4 << a5 << a6;
469 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7>
470 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)
474 BeginMessage(pszCommand);
475 vSend << a1 << a2 << a3 << a4 << a5 << a6 << a7;
485 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8>
486 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)
490 BeginMessage(pszCommand);
491 vSend << a1 << a2 << a3 << a4 << a5 << a6 << a7 << a8;
501 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9>
502 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)
506 BeginMessage(pszCommand);
507 vSend << a1 << a2 << a3 << a4 << a5 << a6 << a7 << a8 << a9;
518 void PushRequest(const char* pszCommand,
519 void (*fn)(void*, CDataStream&), void* param1)
522 RAND_bytes((unsigned char*)&hashReply, sizeof(hashReply));
525 LOCK(cs_mapRequests);
526 mapRequests[hashReply] = CRequestTracker(fn, param1);
529 PushMessage(pszCommand, hashReply);
532 template<typename T1>
533 void PushRequest(const char* pszCommand, const T1& a1,
534 void (*fn)(void*, CDataStream&), void* param1)
537 RAND_bytes((unsigned char*)&hashReply, sizeof(hashReply));
540 LOCK(cs_mapRequests);
541 mapRequests[hashReply] = CRequestTracker(fn, param1);
544 PushMessage(pszCommand, hashReply, a1);
547 template<typename T1, typename T2>
548 void PushRequest(const char* pszCommand, const T1& a1, const T2& a2,
549 void (*fn)(void*, CDataStream&), void* param1)
552 RAND_bytes((unsigned char*)&hashReply, sizeof(hashReply));
555 LOCK(cs_mapRequests);
556 mapRequests[hashReply] = CRequestTracker(fn, param1);
559 PushMessage(pszCommand, hashReply, a1, a2);
564 void PushGetBlocks(CBlockIndex* pindexBegin, uint256 hashEnd);
565 bool IsSubscribed(unsigned int nChannel);
566 void Subscribe(unsigned int nChannel, unsigned int nHops=0);
567 void CancelSubscribe(unsigned int nChannel);
568 void CloseSocketDisconnect();
572 // Denial-of-service detection/prevention
573 // The idea is to detect peers that are behaving
574 // badly and disconnect/ban them, but do it in a
575 // one-coding-mistake-won't-shatter-the-entire-network
577 // IMPORTANT: There should be nothing I can give a
578 // node that it will forward on that will make that
579 // node's peers drop it. If there is, an attacker
580 // can isolate a node and/or try to split the network.
581 // Dropping a node for sending stuff that is invalid
582 // now but might be valid in a later version is also
583 // dangerous, because it can cause a network split
584 // between nodes running old code and nodes running
586 static void ClearBanned(); // needed for unit testing
587 static bool IsBanned(CNetAddr ip);
588 bool Misbehaving(int howmuch); // 1 == a little, 100 == a lot
600 inline void RelayInventory(const CInv& inv)
602 // Put on lists to offer to the other nodes
605 BOOST_FOREACH(CNode* pnode, vNodes)
606 pnode->PushInventory(inv);
611 void RelayMessage(const CInv& inv, const T& a)
613 CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
616 RelayMessage(inv, ss);
620 inline void RelayMessage<>(const CInv& inv, const CDataStream& ss)
624 // Expire old relay messages
625 while (!vRelayExpiration.empty() && vRelayExpiration.front().first < GetTime())
627 mapRelay.erase(vRelayExpiration.front().second);
628 vRelayExpiration.pop_front();
631 // Save original serialized message so newer versions are preserved
632 mapRelay.insert(std::make_pair(inv, ss));
633 vRelayExpiration.push_back(std::make_pair(GetTime() + 15 * 60, inv));