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;
120 unsigned int nHeaderStart;
121 unsigned int nMessageStart;
124 std::string strSubVer;
128 bool fSuccessfullyConnected;
133 // Denial-of-service detection/prevention
134 // Key is ip address, value is banned-until-time
135 static std::map<CNetAddr, int64> setBanned;
136 static CCriticalSection cs_setBanned;
141 std::map<uint256, CRequestTracker> mapRequests;
142 CCriticalSection cs_mapRequests;
143 uint256 hashContinue;
144 CBlockIndex* pindexLastGetBlocksBegin;
145 uint256 hashLastGetBlocksEnd;
149 std::vector<CAddress> vAddrToSend;
150 std::set<CAddress> setAddrKnown;
152 std::set<uint256> setKnown;
154 // inventory based relay
155 mruset<CInv> setInventoryKnown;
156 std::vector<CInv> vInventoryToSend;
157 CCriticalSection cs_inventory;
158 std::multimap<int64, CInv> mapAskFor;
160 CNode(SOCKET hSocketIn, CAddress addrIn, bool fInboundIn=false)
164 vSend.SetType(SER_NETWORK);
165 vRecv.SetType(SER_NETWORK);
166 vSend.SetVersion(209);
167 vRecv.SetVersion(209);
170 nLastSendEmpty = GetTime();
171 nTimeConnected = GetTime();
177 fClient = false; // set by version message
178 fInbound = fInboundIn;
179 fNetworkNode = false;
180 fSuccessfullyConnected = false;
185 pindexLastGetBlocksBegin = 0;
186 hashLastGetBlocksEnd = 0;
187 nStartingHeight = -1;
190 setInventoryKnown.max_size(SendBufferSize() / 1000);
192 // Be shy and don't send version until we hear
199 if (hSocket != INVALID_SOCKET)
201 closesocket(hSocket);
202 hSocket = INVALID_SOCKET;
208 void operator=(const CNode&);
214 return std::max(nRefCount, 0) + (GetTime() < nReleaseTime ? 1 : 0);
217 CNode* AddRef(int64 nTimeout=0)
220 nReleaseTime = std::max(nReleaseTime, GetTime() + nTimeout);
233 void AddAddressKnown(const CAddress& addr)
235 setAddrKnown.insert(addr);
238 void PushAddress(const CAddress& addr)
240 // Known checking here is only to save space from duplicates.
241 // SendMessages will filter it again for knowns that were added
242 // after addresses were pushed.
243 if (addr.IsValid() && !setAddrKnown.count(addr))
244 vAddrToSend.push_back(addr);
248 void AddInventoryKnown(const CInv& inv)
250 CRITICAL_BLOCK(cs_inventory)
251 setInventoryKnown.insert(inv);
254 void PushInventory(const CInv& inv)
256 CRITICAL_BLOCK(cs_inventory)
257 if (!setInventoryKnown.count(inv))
258 vInventoryToSend.push_back(inv);
261 void AskFor(const CInv& inv)
263 // We're using mapAskFor as a priority queue,
264 // the key is the earliest time the request can be sent
265 int64& nRequestTime = mapAlreadyAskedFor[inv];
266 printf("askfor %s %"PRI64d"\n", inv.ToString().c_str(), nRequestTime);
268 // Make sure not to reuse time indexes to keep things in the same order
269 int64 nNow = (GetTime() - 1) * 1000000;
270 static int64 nLastTime;
272 nNow = std::max(nNow, nLastTime);
275 // Each retry is 2 minutes after the last
276 nRequestTime = std::max(nRequestTime + 2 * 60 * 1000000, nNow);
277 mapAskFor.insert(std::make_pair(nRequestTime, inv));
282 void BeginMessage(const char* pszCommand)
284 ENTER_CRITICAL_SECTION(cs_vSend);
285 if (nHeaderStart != -1)
287 nHeaderStart = vSend.size();
288 vSend << CMessageHeader(pszCommand, 0);
289 nMessageStart = vSend.size();
291 printf("%s ", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());
292 printf("sending: %s ", pszCommand);
298 if (nHeaderStart == -1)
300 vSend.resize(nHeaderStart);
303 LEAVE_CRITICAL_SECTION(cs_vSend);
306 printf("(aborted)\n");
311 if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
313 printf("dropmessages DROPPING SEND MESSAGE\n");
318 if (nHeaderStart == -1)
322 unsigned int nSize = vSend.size() - nMessageStart;
323 memcpy((char*)&vSend[nHeaderStart] + offsetof(CMessageHeader, nMessageSize), &nSize, sizeof(nSize));
326 uint256 hash = Hash(vSend.begin() + nMessageStart, vSend.end());
327 unsigned int nChecksum = 0;
328 memcpy(&nChecksum, &hash, sizeof(nChecksum));
329 assert(nMessageStart - nHeaderStart >= offsetof(CMessageHeader, nChecksum) + sizeof(nChecksum));
330 memcpy((char*)&vSend[nHeaderStart] + offsetof(CMessageHeader, nChecksum), &nChecksum, sizeof(nChecksum));
333 printf("(%d bytes)\n", nSize);
338 LEAVE_CRITICAL_SECTION(cs_vSend);
341 void EndMessageAbortIfEmpty()
343 if (nHeaderStart == -1)
345 int nSize = vSend.size() - nMessageStart;
357 void PushMessage(const char* pszCommand)
361 BeginMessage(pszCommand);
371 template<typename T1>
372 void PushMessage(const char* pszCommand, const T1& a1)
376 BeginMessage(pszCommand);
387 template<typename T1, typename T2>
388 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2)
392 BeginMessage(pszCommand);
403 template<typename T1, typename T2, typename T3>
404 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3)
408 BeginMessage(pszCommand);
409 vSend << a1 << a2 << a3;
419 template<typename T1, typename T2, typename T3, typename T4>
420 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4)
424 BeginMessage(pszCommand);
425 vSend << a1 << a2 << a3 << a4;
435 template<typename T1, typename T2, typename T3, typename T4, typename T5>
436 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4, const T5& a5)
440 BeginMessage(pszCommand);
441 vSend << a1 << a2 << a3 << a4 << a5;
451 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6>
452 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4, const T5& a5, const T6& a6)
456 BeginMessage(pszCommand);
457 vSend << a1 << a2 << a3 << a4 << a5 << a6;
467 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7>
468 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)
472 BeginMessage(pszCommand);
473 vSend << a1 << a2 << a3 << a4 << a5 << a6 << a7;
483 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8>
484 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)
488 BeginMessage(pszCommand);
489 vSend << a1 << a2 << a3 << a4 << a5 << a6 << a7 << a8;
499 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9>
500 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)
504 BeginMessage(pszCommand);
505 vSend << a1 << a2 << a3 << a4 << a5 << a6 << a7 << a8 << a9;
516 void PushRequest(const char* pszCommand,
517 void (*fn)(void*, CDataStream&), void* param1)
520 RAND_bytes((unsigned char*)&hashReply, sizeof(hashReply));
522 CRITICAL_BLOCK(cs_mapRequests)
523 mapRequests[hashReply] = CRequestTracker(fn, param1);
525 PushMessage(pszCommand, hashReply);
528 template<typename T1>
529 void PushRequest(const char* pszCommand, const T1& a1,
530 void (*fn)(void*, CDataStream&), void* param1)
533 RAND_bytes((unsigned char*)&hashReply, sizeof(hashReply));
535 CRITICAL_BLOCK(cs_mapRequests)
536 mapRequests[hashReply] = CRequestTracker(fn, param1);
538 PushMessage(pszCommand, hashReply, a1);
541 template<typename T1, typename T2>
542 void PushRequest(const char* pszCommand, const T1& a1, const T2& a2,
543 void (*fn)(void*, CDataStream&), void* param1)
546 RAND_bytes((unsigned char*)&hashReply, sizeof(hashReply));
548 CRITICAL_BLOCK(cs_mapRequests)
549 mapRequests[hashReply] = CRequestTracker(fn, param1);
551 PushMessage(pszCommand, hashReply, a1, a2);
556 void PushGetBlocks(CBlockIndex* pindexBegin, uint256 hashEnd);
557 bool IsSubscribed(unsigned int nChannel);
558 void Subscribe(unsigned int nChannel, unsigned int nHops=0);
559 void CancelSubscribe(unsigned int nChannel);
560 void CloseSocketDisconnect();
564 // Denial-of-service detection/prevention
565 // The idea is to detect peers that are behaving
566 // badly and disconnect/ban them, but do it in a
567 // one-coding-mistake-won't-shatter-the-entire-network
569 // IMPORTANT: There should be nothing I can give a
570 // node that it will forward on that will make that
571 // node's peers drop it. If there is, an attacker
572 // can isolate a node and/or try to split the network.
573 // Dropping a node for sending stuff that is invalid
574 // now but might be valid in a later version is also
575 // dangerous, because it can cause a network split
576 // between nodes running old code and nodes running
578 static void ClearBanned(); // needed for unit testing
579 static bool IsBanned(CNetAddr ip);
580 bool Misbehaving(int howmuch); // 1 == a little, 100 == a lot
592 inline void RelayInventory(const CInv& inv)
594 // Put on lists to offer to the other nodes
595 CRITICAL_BLOCK(cs_vNodes)
596 BOOST_FOREACH(CNode* pnode, vNodes)
597 pnode->PushInventory(inv);
601 void RelayMessage(const CInv& inv, const T& a)
603 CDataStream ss(SER_NETWORK);
606 RelayMessage(inv, ss);
610 inline void RelayMessage<>(const CInv& inv, const CDataStream& ss)
612 CRITICAL_BLOCK(cs_mapRelay)
614 // Expire old relay messages
615 while (!vRelayExpiration.empty() && vRelayExpiration.front().first < GetTime())
617 mapRelay.erase(vRelayExpiration.front().second);
618 vRelayExpiration.pop_front();
621 // Save original serialized message so newer versions are preserved
623 vRelayExpiration.push_back(std::make_pair(GetTime() + 15 * 60, inv));