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 COPYING or http://www.opensource.org/licenses/mit-license.php.
10 #include <boost/array.hpp>
11 #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", 5*1000); }
33 inline unsigned int SendBufferSize() { return 1000*GetArg("-maxsendbuffer", 1*1000); }
35 void AddOneShot(std::string strDest);
36 bool RecvLine(SOCKET hSocket, std::string& strLine);
37 bool GetMyExternalIP(CNetAddr& ipRet);
38 void AddressCurrentlyConnected(const CService& addr);
39 CNode* FindNode(const CNetAddr& ip);
40 CNode* FindNode(const CService& ip);
41 CNode* ConnectNode(CAddress addrConnect, const char *strDest = NULL, int64_t nTimeout=0);
43 unsigned short GetListenPort();
44 bool BindListenPort(const CService &bindAddr, std::string& strError=REF(std::string()));
45 void StartNode(void* parg);
50 LOCAL_NONE, // unknown
51 LOCAL_IF, // address a local interface listens on
52 LOCAL_BIND, // address explicit bound to
53 LOCAL_UPNP, // address reported by UPnP
54 LOCAL_IRC, // address reported by IRC (deprecated)
55 LOCAL_HTTP, // address reported by whatismyip.com and similar
56 LOCAL_MANUAL, // address explicitly specified (-externalip=)
61 void SetLimited(enum Network net, bool fLimited = true);
62 bool IsLimited(enum Network net);
63 bool IsLimited(const CNetAddr& addr);
64 bool AddLocal(const CService& addr, int nScore = LOCAL_NONE);
65 bool AddLocal(const CNetAddr& addr, int nScore = LOCAL_NONE);
66 bool SeenLocal(const CService& addr);
67 bool IsLocal(const CService& addr);
68 bool GetLocal(CService &addr, const CNetAddr *paddrPeer = NULL);
69 bool IsReachable(const CNetAddr &addr);
70 void SetReachable(enum Network net, bool fFlag = true);
71 CAddress GetLocalAddress(const CNetAddr *paddrPeer = NULL);
83 void (*fn)(void*, CDataStream&);
86 explicit CRequestTracker(void (*fnIn)(void*, CDataStream&)=NULL, void* param1In=NULL)
102 THREAD_SOCKETHANDLER,
103 THREAD_OPENCONNECTIONS,
104 THREAD_MESSAGEHANDLER,
108 THREAD_ADDEDCONNECTIONS,
118 extern bool fDiscover;
119 extern bool fUseUPnP;
120 extern uint64_t nLocalServices;
121 extern uint64_t nLocalHostNonce;
122 extern CAddress addrSeenByPeer;
123 extern boost::array<int, THREAD_MAX> vnThreadsRunning;
124 extern CAddrMan addrman;
126 extern std::vector<CNode*> vNodes;
127 extern CCriticalSection cs_vNodes;
128 extern std::map<CInv, CDataStream> mapRelay;
129 extern std::deque<std::pair<int64_t, CInv> > vRelayExpiration;
130 extern CCriticalSection cs_mapRelay;
131 extern std::map<CInv, int64_t> mapAlreadyAskedFor;
142 int64_t nTimeConnected;
143 std::string addrName;
145 std::string strSubVer;
147 int64_t nReleaseTime;
159 /** Information about a peer */
170 CCriticalSection cs_vSend;
171 CCriticalSection cs_vRecv;
174 int64_t nLastSendEmpty;
175 int64_t nTimeConnected;
177 unsigned int nMessageStart;
179 std::string addrName;
182 std::string strSubVer;
187 bool fSuccessfullyConnected;
189 CSemaphoreGrant grantOutbound;
193 // Denial-of-service detection/prevention
194 // Key is IP address, value is banned-until-time
195 static std::map<CNetAddr, int64_t> setBanned;
196 static CCriticalSection cs_setBanned;
200 int64_t nReleaseTime;
201 std::map<uint256, CRequestTracker> mapRequests;
202 CCriticalSection cs_mapRequests;
203 uint256 hashContinue;
204 CBlockIndex* pindexLastGetBlocksBegin;
205 uint256 hashLastGetBlocksEnd;
210 std::vector<CAddress> vAddrToSend;
211 std::set<CAddress> setAddrKnown;
213 std::set<uint256> setKnown;
214 uint256 hashCheckpointKnown; // ppcoin: known sent sync-checkpoint
216 // inventory based relay
217 mruset<CInv> setInventoryKnown;
218 std::vector<CInv> vInventoryToSend;
219 CCriticalSection cs_inventory;
220 std::multimap<int64_t, CInv> mapAskFor;
222 CNode(SOCKET hSocketIn, CAddress addrIn, std::string addrNameIn = "", bool fInboundIn=false) : vSend(SER_NETWORK, MIN_PROTO_VERSION), vRecv(SER_NETWORK, MIN_PROTO_VERSION)
230 nLastSendEmpty = GetTime();
231 nTimeConnected = GetTime();
235 addrName = addrNameIn == "" ? addr.ToStringIPPort() : addrNameIn;
239 fClient = false; // set by version message
240 fInbound = fInboundIn;
241 fNetworkNode = false;
242 fSuccessfullyConnected = false;
247 pindexLastGetBlocksBegin = 0;
248 hashLastGetBlocksEnd = 0;
249 nStartingHeight = -1;
253 hashCheckpointKnown = 0;
254 setInventoryKnown.max_size(SendBufferSize() / 1000);
256 // Be shy and don't send version until we hear
257 if (hSocket != INVALID_SOCKET && !fInbound)
263 if (hSocket != INVALID_SOCKET)
265 closesocket(hSocket);
266 hSocket = INVALID_SOCKET;
272 // Network usage totals
273 static CCriticalSection cs_totalBytesRecv;
274 static CCriticalSection cs_totalBytesSent;
275 static uint64_t nTotalBytesRecv;
276 static uint64_t nTotalBytesSent;
278 void operator=(const CNode&);
284 return std::max(nRefCount, 0) + (GetTime() < nReleaseTime ? 1 : 0);
287 CNode* AddRef(int64_t nTimeout=0)
290 nReleaseTime = std::max(nReleaseTime, GetTime() + nTimeout);
303 void AddAddressKnown(const CAddress& addr)
305 setAddrKnown.insert(addr);
308 void PushAddress(const CAddress& addr)
310 // Known checking here is only to save space from duplicates.
311 // SendMessages will filter it again for knowns that were added
312 // after addresses were pushed.
313 if (addr.IsValid() && !setAddrKnown.count(addr))
314 vAddrToSend.push_back(addr);
318 void AddInventoryKnown(const CInv& inv)
322 setInventoryKnown.insert(inv);
326 void PushInventory(const CInv& inv)
330 if (!setInventoryKnown.count(inv))
331 vInventoryToSend.push_back(inv);
335 void AskFor(const CInv& inv)
337 // We're using mapAskFor as a priority queue,
338 // the key is the earliest time the request can be sent
339 int64_t& nRequestTime = mapAlreadyAskedFor[inv];
341 printf("askfor %s %" PRId64 " (%s)\n", inv.ToString().c_str(), nRequestTime, DateTimeStrFormat("%H:%M:%S", nRequestTime/1000000).c_str());
343 // Make sure not to reuse time indexes to keep things in the same order
344 int64_t nNow = (GetTime() - 1) * 1000000;
345 static int64_t nLastTime;
347 nNow = std::max(nNow, nLastTime);
350 // Each retry is 2 minutes after the last
351 nRequestTime = std::max(nRequestTime + 2 * 60 * 1000000, nNow);
352 mapAskFor.insert(std::make_pair(nRequestTime, inv));
357 void BeginMessage(const char* pszCommand)
359 ENTER_CRITICAL_SECTION(cs_vSend);
360 if (nHeaderStart != -1)
362 nHeaderStart = vSend.size();
363 vSend << CMessageHeader(pszCommand, 0);
364 nMessageStart = vSend.size();
366 printf("sending: %s ", pszCommand);
371 if (nHeaderStart < 0)
373 vSend.resize(nHeaderStart);
376 LEAVE_CRITICAL_SECTION(cs_vSend);
379 printf("(aborted)\n");
384 if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
386 printf("dropmessages DROPPING SEND MESSAGE\n");
391 if (nHeaderStart < 0)
395 unsigned int nSize = vSend.size() - nMessageStart;
396 memcpy((char*)&vSend[nHeaderStart] + CMessageHeader::MESSAGE_SIZE_OFFSET, &nSize, sizeof(nSize));
399 uint256 hash = Hash(vSend.begin() + nMessageStart, vSend.end());
400 unsigned int nChecksum = 0;
401 memcpy(&nChecksum, &hash, sizeof(nChecksum));
402 assert(nMessageStart - nHeaderStart >= CMessageHeader::CHECKSUM_OFFSET + sizeof(nChecksum));
403 memcpy((char*)&vSend[nHeaderStart] + CMessageHeader::CHECKSUM_OFFSET, &nChecksum, sizeof(nChecksum));
406 printf("(%d bytes)\n", nSize);
411 LEAVE_CRITICAL_SECTION(cs_vSend);
414 void EndMessageAbortIfEmpty()
416 if (nHeaderStart < 0)
418 int nSize = vSend.size() - nMessageStart;
430 void PushMessage(const char* pszCommand)
434 BeginMessage(pszCommand);
444 template<typename T1>
445 void PushMessage(const char* pszCommand, const T1& a1)
449 BeginMessage(pszCommand);
460 template<typename T1, typename T2>
461 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2)
465 BeginMessage(pszCommand);
476 template<typename T1, typename T2, typename T3>
477 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3)
481 BeginMessage(pszCommand);
482 vSend << a1 << a2 << a3;
492 template<typename T1, typename T2, typename T3, typename T4>
493 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4)
497 BeginMessage(pszCommand);
498 vSend << a1 << a2 << a3 << a4;
508 template<typename T1, typename T2, typename T3, typename T4, typename T5>
509 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4, const T5& a5)
513 BeginMessage(pszCommand);
514 vSend << a1 << a2 << a3 << a4 << a5;
524 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6>
525 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4, const T5& a5, const T6& a6)
529 BeginMessage(pszCommand);
530 vSend << a1 << a2 << a3 << a4 << a5 << a6;
540 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7>
541 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)
545 BeginMessage(pszCommand);
546 vSend << a1 << a2 << a3 << a4 << a5 << a6 << a7;
556 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8>
557 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)
561 BeginMessage(pszCommand);
562 vSend << a1 << a2 << a3 << a4 << a5 << a6 << a7 << a8;
572 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9>
573 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)
577 BeginMessage(pszCommand);
578 vSend << a1 << a2 << a3 << a4 << a5 << a6 << a7 << a8 << a9;
589 void PushRequest(const char* pszCommand,
590 void (*fn)(void*, CDataStream&), void* param1)
593 RAND_bytes((unsigned char*)&hashReply, sizeof(hashReply));
596 LOCK(cs_mapRequests);
597 mapRequests[hashReply] = CRequestTracker(fn, param1);
600 PushMessage(pszCommand, hashReply);
603 template<typename T1>
604 void PushRequest(const char* pszCommand, const T1& a1,
605 void (*fn)(void*, CDataStream&), void* param1)
608 RAND_bytes((unsigned char*)&hashReply, sizeof(hashReply));
611 LOCK(cs_mapRequests);
612 mapRequests[hashReply] = CRequestTracker(fn, param1);
615 PushMessage(pszCommand, hashReply, a1);
618 template<typename T1, typename T2>
619 void PushRequest(const char* pszCommand, const T1& a1, const T2& a2,
620 void (*fn)(void*, CDataStream&), void* param1)
623 RAND_bytes((unsigned char*)&hashReply, sizeof(hashReply));
626 LOCK(cs_mapRequests);
627 mapRequests[hashReply] = CRequestTracker(fn, param1);
630 PushMessage(pszCommand, hashReply, a1, a2);
635 void PushGetBlocks(CBlockIndex* pindexBegin, uint256 hashEnd);
636 bool IsSubscribed(unsigned int nChannel);
637 void Subscribe(unsigned int nChannel, unsigned int nHops=0);
638 void CancelSubscribe(unsigned int nChannel);
639 void CloseSocketDisconnect();
643 // Denial-of-service detection/prevention
644 // The idea is to detect peers that are behaving
645 // badly and disconnect/ban them, but do it in a
646 // one-coding-mistake-won't-shatter-the-entire-network
648 // IMPORTANT: There should be nothing I can give a
649 // node that it will forward on that will make that
650 // node's peers drop it. If there is, an attacker
651 // can isolate a node and/or try to split the network.
652 // Dropping a node for sending stuff that is invalid
653 // now but might be valid in a later version is also
654 // dangerous, because it can cause a network split
655 // between nodes running old code and nodes running
657 static void ClearBanned(); // needed for unit testing
658 static bool IsBanned(CNetAddr ip);
659 bool Misbehaving(int howmuch); // 1 == a little, 100 == a lot
660 void copyStats(CNodeStats &stats);
662 static void RecordBytesRecv(uint64_t bytes);
663 static void RecordBytesSent(uint64_t bytes);
665 static uint64_t GetTotalBytesRecv();
666 static uint64_t GetTotalBytesSent();
669 inline void RelayInventory(const CInv& inv)
671 // Put on lists to offer to the other nodes
674 BOOST_FOREACH(CNode* pnode, vNodes)
675 pnode->PushInventory(inv);
680 void RelayTransaction(const CTransaction& tx, const uint256& hash);
681 void RelayTransaction(const CTransaction& tx, const uint256& hash, const CDataStream& ss);