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.
15 #include <arpa/inet.h>
22 class CRequestTracker;
25 extern int nBestHeight;
27 const uint16_t nSocksDefault = 9050;
28 const uint16_t nPortZero = 0;
31 inline uint64_t ReceiveBufferSize() { return 1000*GetArg("-maxreceivebuffer", 5*1000); }
32 inline uint64_t SendBufferSize() { return 1000*GetArg("-maxsendbuffer", 1*1000); }
34 void AddOneShot(std::string strDest);
35 bool RecvLine(SOCKET hSocket, std::string& strLine);
36 bool GetMyExternalIP(CNetAddr& ipRet);
37 void AddressCurrentlyConnected(const CService& addr);
38 CNode* FindNode(const CNetAddr& ip);
39 CNode* FindNode(const CService& ip);
40 CNode* ConnectNode(CAddress addrConnect, const char *strDest = NULL, int64_t nTimeout=0);
41 bool OpenNetworkConnection(const CAddress& addrConnect, CSemaphoreGrant *grantOutbound = NULL, const char *strDest = NULL, bool fOneShot = false);
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_IRC, // address reported by IRC (deprecated)
54 LOCAL_HTTP, // address reported by whatismyip.com and similar
55 LOCAL_MANUAL, // address explicitly specified (-externalip=)
61 bool IsPeerAddrLocalGood(CNode *pnode);
62 void AdvertiseLocal(CNode *pnode);
63 void SetLimited(enum Network net, bool fLimited = true);
64 bool IsLimited(enum Network net);
65 bool IsLimited(const CNetAddr& addr);
66 bool AddLocal(const CService& addr, int nScore = LOCAL_NONE);
67 bool AddLocal(const CNetAddr& addr, int nScore = LOCAL_NONE);
68 bool SeenLocal(const CService& addr);
69 bool IsLocal(const CService& addr);
70 bool GetLocal(CService &addr, const CNetAddr *paddrPeer = NULL);
71 bool IsReachable(const CNetAddr &addr);
72 void SetReachable(enum Network net, bool fFlag = true);
73 CAddress GetLocalAddress(const CNetAddr *paddrPeer = NULL);
85 void (*fn)(void*, CDataStream&);
88 explicit CRequestTracker(void (*fnIn)(void*, CDataStream&)=NULL, void* param1In=NULL)
104 THREAD_SOCKETHANDLER,
105 THREAD_OPENCONNECTIONS,
106 THREAD_MESSAGEHANDLER,
109 THREAD_ADDEDCONNECTIONS,
121 extern bool fDiscover;
122 extern bool fNoListen;
124 extern bool fDiscover;
125 extern uint64_t nLocalServices;
126 extern uint64_t nLocalHostNonce;
127 extern CAddress addrSeenByPeer;
128 extern std::array<int, THREAD_MAX> vnThreadsRunning;
129 extern CAddrMan addrman;
131 extern std::vector<CNode*> vNodes;
132 extern CCriticalSection cs_vNodes;
133 extern std::vector<std::string> vAddedNodes;
134 extern CCriticalSection cs_vAddedNodes;
135 extern std::map<CInv, CDataStream> mapRelay;
136 extern std::deque<std::pair<int64_t, CInv> > vRelayExpiration;
137 extern CCriticalSection cs_mapRelay;
138 extern std::map<CInv, int64_t> mapAlreadyAskedFor;
149 int64_t nTimeConnected;
150 std::string addrName;
152 std::string strSubVer;
154 int64_t nReleaseTime;
155 int32_t nStartingHeight;
156 int32_t nMisbehavior;
166 /** Information about a peer */
177 CCriticalSection cs_vSend;
178 CCriticalSection cs_vRecv;
181 int64_t nLastSendEmpty;
182 int64_t nTimeConnected;
183 int32_t nHeaderStart;
184 uint32_t nMessageStart;
186 std::string addrName;
189 std::string strSubVer;
194 bool fSuccessfullyConnected;
196 CSemaphoreGrant grantOutbound;
200 // Denial-of-service detection/prevention
201 // Key is IP address, value is banned-until-time
202 static std::map<CNetAddr, int64_t> setBanned;
203 static CCriticalSection cs_setBanned;
207 int64_t nReleaseTime;
208 std::map<uint256, CRequestTracker> mapRequests;
209 CCriticalSection cs_mapRequests;
210 uint256 hashContinue;
211 CBlockIndex* pindexLastGetBlocksBegin;
212 uint256 hashLastGetBlocksEnd;
213 int32_t nStartingHeight;
217 std::vector<CAddress> vAddrToSend;
218 std::set<CAddress> setAddrKnown;
220 std::set<uint256> setKnown;
221 uint256 hashCheckpointKnown; // ppcoin: known sent sync-checkpoint
222 int64_t nNextAddrSend;
223 int64_t nNextLocalAddrSend;
224 int64_t nNextInvSend;
226 // inventory based relay
227 mruset<CInv> setInventoryKnown;
228 std::vector<CInv> vInventoryToSend;
229 CCriticalSection cs_inventory;
230 std::multimap<int64_t, CInv> mapAskFor;
232 CNode(SOCKET hSocketIn, CAddress addrIn, std::string addrNameIn = "", bool fInboundIn=false) : vSend(SER_NETWORK, MIN_PROTO_VERSION), vRecv(SER_NETWORK, MIN_PROTO_VERSION)
240 nLastSendEmpty = GetTime();
241 nTimeConnected = GetTime();
243 nMessageStart = std::numeric_limits<uint32_t>::max();
245 addrName = addrNameIn.empty() ? addr.ToStringIPPort() : addrNameIn;
249 fClient = false; // set by version message
250 fInbound = fInboundIn;
251 fNetworkNode = false;
252 fSuccessfullyConnected = false;
257 pindexLastGetBlocksBegin = 0;
258 hashLastGetBlocksEnd = 0;
259 nStartingHeight = -1;
260 nNextLocalAddrSend = 0;
266 hashCheckpointKnown = 0;
267 setInventoryKnown.max_size((size_t)SendBufferSize() / 1000);
269 // Be shy and don't send version until we hear
270 if (hSocket != INVALID_SOCKET && !fInbound)
276 if (hSocket != INVALID_SOCKET)
278 CloseSocket(hSocket);
284 // Network usage totals
285 static CCriticalSection cs_totalBytesRecv;
286 static CCriticalSection cs_totalBytesSent;
287 static uint64_t nTotalBytesRecv;
288 static uint64_t nTotalBytesSent;
290 void operator=(const CNode&);
296 return std::max(nRefCount, 0) + (GetTime() < nReleaseTime ? 1 : 0);
299 CNode* AddRef(int64_t nTimeout=0)
302 nReleaseTime = std::max(nReleaseTime, GetTime() + nTimeout);
315 void AddAddressKnown(const CAddress& addr)
317 setAddrKnown.insert(addr);
320 void PushAddress(const CAddress& addr)
322 // Known checking here is only to save space from duplicates.
323 // SendMessages will filter it again for knowns that were added
324 // after addresses were pushed.
325 if (addr.IsValid() && !setAddrKnown.count(addr))
326 vAddrToSend.push_back(addr);
330 void AddInventoryKnown(const CInv& inv)
334 setInventoryKnown.insert(inv);
338 void PushInventory(const CInv& inv)
342 if (!setInventoryKnown.count(inv))
343 vInventoryToSend.push_back(inv);
347 void AskFor(const CInv& inv)
349 // We're using mapAskFor as a priority queue,
350 // the key is the earliest time the request can be sent
351 int64_t& nRequestTime = mapAlreadyAskedFor[inv];
353 printf("askfor %s %" PRId64 " (%s)\n", inv.ToString().c_str(), nRequestTime, DateTimeStrFormat("%H:%M:%S", nRequestTime/1000000).c_str());
355 // Make sure not to reuse time indexes to keep things in the same order
356 int64_t nNow = (GetTime() - 1) * 1000000;
357 static int64_t nLastTime;
359 nNow = std::max(nNow, nLastTime);
362 // Each retry is 2 minutes after the last
363 nRequestTime = std::max(nRequestTime + 2 * 60 * 1000000, nNow);
364 mapAskFor.insert(std::make_pair(nRequestTime, inv));
367 void BeginMessage(const char* pszCommand)
369 ENTER_CRITICAL_SECTION(cs_vSend);
370 if (nHeaderStart != -1)
372 nHeaderStart = (int32_t)vSend.size();
373 vSend << CMessageHeader(pszCommand, 0);
374 nMessageStart = (uint32_t)vSend.size();
376 printf("sending: %s ", pszCommand);
381 if (nHeaderStart < 0)
383 vSend.resize(nHeaderStart);
385 nMessageStart = std::numeric_limits<uint32_t>::max();
386 LEAVE_CRITICAL_SECTION(cs_vSend);
389 printf("(aborted)\n");
394 void EndMessageAbortIfEmpty()
396 if (nHeaderStart < 0)
398 int nSize = (int) vSend.size() - nMessageStart;
407 template<typename ...Args>
408 void PushMessage(const char* pszCommand, const Args&... args)
412 BeginMessage(pszCommand);
413 if constexpr (sizeof...(Args) > 0)
414 (vSend << ... << args);
424 void PushGetBlocks(CBlockIndex* pindexBegin, uint256 hashEnd);
425 bool IsSubscribed(unsigned int nChannel);
426 void Subscribe(unsigned int nChannel, unsigned int nHops=0);
427 void CancelSubscribe(unsigned int nChannel);
428 void CloseSocketDisconnect();
432 // Denial-of-service detection/prevention
433 // The idea is to detect peers that are behaving
434 // badly and disconnect/ban them, but do it in a
435 // one-coding-mistake-won't-shatter-the-entire-network
437 // IMPORTANT: There should be nothing I can give a
438 // node that it will forward on that will make that
439 // node's peers drop it. If there is, an attacker
440 // can isolate a node and/or try to split the network.
441 // Dropping a node for sending stuff that is invalid
442 // now but might be valid in a later version is also
443 // dangerous, because it can cause a network split
444 // between nodes running old code and nodes running
446 static void ClearBanned(); // needed for unit testing
447 static bool IsBanned(CNetAddr ip);
448 bool Misbehaving(int howmuch); // 1 == a little, 100 == a lot
449 void copyStats(CNodeStats &stats);
451 static void RecordBytesRecv(uint64_t bytes);
452 static void RecordBytesSent(uint64_t bytes);
454 static uint64_t GetTotalBytesRecv();
455 static uint64_t GetTotalBytesSent();
459 void RelayTransaction(const CTransaction& tx, const uint256& hash);
460 void RelayTransaction(const CTransaction& tx, const uint256& hash, const CDataStream& ss);
463 /** Return a timestamp in the future (in microseconds) for exponentially distributed events. */
464 int64_t PoissonNextSend(int64_t nNow, int average_interval_seconds);