Use the variable name _ for unused return values
[bitcoinplatinum.git] / src / net.h
bloba32736aa97bf2be8153d63ee0e7fdaa3618cc99b
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2016 The Bitcoin Core developers
3 // Distributed under the MIT software license, see the accompanying
4 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
6 #ifndef BITCOIN_NET_H
7 #define BITCOIN_NET_H
9 #include "addrdb.h"
10 #include "addrman.h"
11 #include "amount.h"
12 #include "bloom.h"
13 #include "compat.h"
14 #include "hash.h"
15 #include "limitedmap.h"
16 #include "netaddress.h"
17 #include "policy/feerate.h"
18 #include "protocol.h"
19 #include "random.h"
20 #include "streams.h"
21 #include "sync.h"
22 #include "uint256.h"
23 #include "threadinterrupt.h"
25 #include <atomic>
26 #include <deque>
27 #include <stdint.h>
28 #include <thread>
29 #include <memory>
30 #include <condition_variable>
32 #ifndef WIN32
33 #include <arpa/inet.h>
34 #endif
36 #include <boost/signals2/signal.hpp>
38 class CScheduler;
39 class CNode;
41 namespace boost {
42 class thread_group;
43 } // namespace boost
45 /** Time between pings automatically sent out for latency probing and keepalive (in seconds). */
46 static const int PING_INTERVAL = 2 * 60;
47 /** Time after which to disconnect, after waiting for a ping response (or inactivity). */
48 static const int TIMEOUT_INTERVAL = 20 * 60;
49 /** Run the feeler connection loop once every 2 minutes or 120 seconds. **/
50 static const int FEELER_INTERVAL = 120;
51 /** The maximum number of entries in an 'inv' protocol message */
52 static const unsigned int MAX_INV_SZ = 50000;
53 /** The maximum number of new addresses to accumulate before announcing. */
54 static const unsigned int MAX_ADDR_TO_SEND = 1000;
55 /** Maximum length of incoming protocol messages (no message over 4 MB is currently acceptable). */
56 static const unsigned int MAX_PROTOCOL_MESSAGE_LENGTH = 4 * 1000 * 1000;
57 /** Maximum length of strSubVer in `version` message */
58 static const unsigned int MAX_SUBVERSION_LENGTH = 256;
59 /** Maximum number of automatic outgoing nodes */
60 static const int MAX_OUTBOUND_CONNECTIONS = 8;
61 /** Maximum number of addnode outgoing nodes */
62 static const int MAX_ADDNODE_CONNECTIONS = 8;
63 /** -listen default */
64 static const bool DEFAULT_LISTEN = true;
65 /** -upnp default */
66 #ifdef USE_UPNP
67 static const bool DEFAULT_UPNP = USE_UPNP;
68 #else
69 static const bool DEFAULT_UPNP = false;
70 #endif
71 /** The maximum number of entries in mapAskFor */
72 static const size_t MAPASKFOR_MAX_SZ = MAX_INV_SZ;
73 /** The maximum number of entries in setAskFor (larger due to getdata latency)*/
74 static const size_t SETASKFOR_MAX_SZ = 2 * MAX_INV_SZ;
75 /** The maximum number of peer connections to maintain. */
76 static const unsigned int DEFAULT_MAX_PEER_CONNECTIONS = 125;
77 /** The default for -maxuploadtarget. 0 = Unlimited */
78 static const uint64_t DEFAULT_MAX_UPLOAD_TARGET = 0;
79 /** The default timeframe for -maxuploadtarget. 1 day. */
80 static const uint64_t MAX_UPLOAD_TIMEFRAME = 60 * 60 * 24;
81 /** Default for blocks only*/
82 static const bool DEFAULT_BLOCKSONLY = false;
84 static const bool DEFAULT_FORCEDNSSEED = false;
85 static const size_t DEFAULT_MAXRECEIVEBUFFER = 5 * 1000;
86 static const size_t DEFAULT_MAXSENDBUFFER = 1 * 1000;
88 static const ServiceFlags REQUIRED_SERVICES = NODE_NETWORK;
90 // NOTE: When adjusting this, update rpcnet:setban's help ("24h")
91 static const unsigned int DEFAULT_MISBEHAVING_BANTIME = 60 * 60 * 24; // Default 24-hour ban
93 typedef int64_t NodeId;
95 struct AddedNodeInfo
97 std::string strAddedNode;
98 CService resolvedAddress;
99 bool fConnected;
100 bool fInbound;
103 class CNodeStats;
104 class CClientUIInterface;
106 struct CSerializedNetMsg
108 CSerializedNetMsg() = default;
109 CSerializedNetMsg(CSerializedNetMsg&&) = default;
110 CSerializedNetMsg& operator=(CSerializedNetMsg&&) = default;
111 // No copying, only moves.
112 CSerializedNetMsg(const CSerializedNetMsg& msg) = delete;
113 CSerializedNetMsg& operator=(const CSerializedNetMsg&) = delete;
115 std::vector<unsigned char> data;
116 std::string command;
120 class CConnman
122 public:
124 enum NumConnections {
125 CONNECTIONS_NONE = 0,
126 CONNECTIONS_IN = (1U << 0),
127 CONNECTIONS_OUT = (1U << 1),
128 CONNECTIONS_ALL = (CONNECTIONS_IN | CONNECTIONS_OUT),
131 struct Options
133 ServiceFlags nLocalServices = NODE_NONE;
134 ServiceFlags nRelevantServices = NODE_NONE;
135 int nMaxConnections = 0;
136 int nMaxOutbound = 0;
137 int nMaxAddnode = 0;
138 int nMaxFeeler = 0;
139 int nBestHeight = 0;
140 CClientUIInterface* uiInterface = nullptr;
141 unsigned int nSendBufferMaxSize = 0;
142 unsigned int nReceiveFloodSize = 0;
143 uint64_t nMaxOutboundTimeframe = 0;
144 uint64_t nMaxOutboundLimit = 0;
145 std::vector<std::string> vSeedNodes;
146 std::vector<CSubNet> vWhitelistedRange;
147 std::vector<CService> vBinds, vWhiteBinds;
150 void Init(const Options& connOptions) {
151 nLocalServices = connOptions.nLocalServices;
152 nRelevantServices = connOptions.nRelevantServices;
153 nMaxConnections = connOptions.nMaxConnections;
154 nMaxOutbound = std::min(connOptions.nMaxOutbound, connOptions.nMaxConnections);
155 nMaxAddnode = connOptions.nMaxAddnode;
156 nMaxFeeler = connOptions.nMaxFeeler;
157 nBestHeight = connOptions.nBestHeight;
158 clientInterface = connOptions.uiInterface;
159 nSendBufferMaxSize = connOptions.nSendBufferMaxSize;
160 nReceiveFloodSize = connOptions.nReceiveFloodSize;
161 nMaxOutboundTimeframe = connOptions.nMaxOutboundTimeframe;
162 nMaxOutboundLimit = connOptions.nMaxOutboundLimit;
163 vWhitelistedRange = connOptions.vWhitelistedRange;
166 CConnman(uint64_t seed0, uint64_t seed1);
167 ~CConnman();
168 bool Start(CScheduler& scheduler, const Options& options);
169 void Stop();
170 void Interrupt();
171 bool GetNetworkActive() const { return fNetworkActive; };
172 void SetNetworkActive(bool active);
173 bool OpenNetworkConnection(const CAddress& addrConnect, bool fCountFailure, CSemaphoreGrant *grantOutbound = nullptr, const char *strDest = nullptr, bool fOneShot = false, bool fFeeler = false, bool fAddnode = false);
174 bool CheckIncomingNonce(uint64_t nonce);
176 bool ForNode(NodeId id, std::function<bool(CNode* pnode)> func);
178 void PushMessage(CNode* pnode, CSerializedNetMsg&& msg);
180 template<typename Callable>
181 void ForEachNode(Callable&& func)
183 LOCK(cs_vNodes);
184 for (auto&& node : vNodes) {
185 if (NodeFullyConnected(node))
186 func(node);
190 template<typename Callable>
191 void ForEachNode(Callable&& func) const
193 LOCK(cs_vNodes);
194 for (auto&& node : vNodes) {
195 if (NodeFullyConnected(node))
196 func(node);
200 template<typename Callable, typename CallableAfter>
201 void ForEachNodeThen(Callable&& pre, CallableAfter&& post)
203 LOCK(cs_vNodes);
204 for (auto&& node : vNodes) {
205 if (NodeFullyConnected(node))
206 pre(node);
208 post();
211 template<typename Callable, typename CallableAfter>
212 void ForEachNodeThen(Callable&& pre, CallableAfter&& post) const
214 LOCK(cs_vNodes);
215 for (auto&& node : vNodes) {
216 if (NodeFullyConnected(node))
217 pre(node);
219 post();
222 // Addrman functions
223 size_t GetAddressCount() const;
224 void SetServices(const CService &addr, ServiceFlags nServices);
225 void MarkAddressGood(const CAddress& addr);
226 void AddNewAddresses(const std::vector<CAddress>& vAddr, const CAddress& addrFrom, int64_t nTimePenalty = 0);
227 std::vector<CAddress> GetAddresses();
229 // Denial-of-service detection/prevention
230 // The idea is to detect peers that are behaving
231 // badly and disconnect/ban them, but do it in a
232 // one-coding-mistake-won't-shatter-the-entire-network
233 // way.
234 // IMPORTANT: There should be nothing I can give a
235 // node that it will forward on that will make that
236 // node's peers drop it. If there is, an attacker
237 // can isolate a node and/or try to split the network.
238 // Dropping a node for sending stuff that is invalid
239 // now but might be valid in a later version is also
240 // dangerous, because it can cause a network split
241 // between nodes running old code and nodes running
242 // new code.
243 void Ban(const CNetAddr& netAddr, const BanReason& reason, int64_t bantimeoffset = 0, bool sinceUnixEpoch = false);
244 void Ban(const CSubNet& subNet, const BanReason& reason, int64_t bantimeoffset = 0, bool sinceUnixEpoch = false);
245 void ClearBanned(); // needed for unit testing
246 bool IsBanned(CNetAddr ip);
247 bool IsBanned(CSubNet subnet);
248 bool Unban(const CNetAddr &ip);
249 bool Unban(const CSubNet &ip);
250 void GetBanned(banmap_t &banmap);
251 void SetBanned(const banmap_t &banmap);
253 bool AddNode(const std::string& node);
254 bool RemoveAddedNode(const std::string& node);
255 std::vector<AddedNodeInfo> GetAddedNodeInfo();
257 size_t GetNodeCount(NumConnections num);
258 void GetNodeStats(std::vector<CNodeStats>& vstats);
259 bool DisconnectNode(const std::string& node);
260 bool DisconnectNode(NodeId id);
262 ServiceFlags GetLocalServices() const;
264 //!set the max outbound target in bytes
265 void SetMaxOutboundTarget(uint64_t limit);
266 uint64_t GetMaxOutboundTarget();
268 //!set the timeframe for the max outbound target
269 void SetMaxOutboundTimeframe(uint64_t timeframe);
270 uint64_t GetMaxOutboundTimeframe();
272 //!check if the outbound target is reached
273 // if param historicalBlockServingLimit is set true, the function will
274 // response true if the limit for serving historical blocks has been reached
275 bool OutboundTargetReached(bool historicalBlockServingLimit);
277 //!response the bytes left in the current max outbound cycle
278 // in case of no limit, it will always response 0
279 uint64_t GetOutboundTargetBytesLeft();
281 //!response the time in second left in the current max outbound cycle
282 // in case of no limit, it will always response 0
283 uint64_t GetMaxOutboundTimeLeftInCycle();
285 uint64_t GetTotalBytesRecv();
286 uint64_t GetTotalBytesSent();
288 void SetBestHeight(int height);
289 int GetBestHeight() const;
291 /** Get a unique deterministic randomizer. */
292 CSipHasher GetDeterministicRandomizer(uint64_t id) const;
294 unsigned int GetReceiveFloodSize() const;
296 void WakeMessageHandler();
297 private:
298 struct ListenSocket {
299 SOCKET socket;
300 bool whitelisted;
302 ListenSocket(SOCKET socket_, bool whitelisted_) : socket(socket_), whitelisted(whitelisted_) {}
305 bool BindListenPort(const CService &bindAddr, std::string& strError, bool fWhitelisted = false);
306 bool Bind(const CService &addr, unsigned int flags);
307 bool InitBinds(const std::vector<CService>& binds, const std::vector<CService>& whiteBinds);
308 void ThreadOpenAddedConnections();
309 void AddOneShot(const std::string& strDest);
310 void ProcessOneShot();
311 void ThreadOpenConnections();
312 void ThreadMessageHandler();
313 void AcceptConnection(const ListenSocket& hListenSocket);
314 void ThreadSocketHandler();
315 void ThreadDNSAddressSeed();
317 uint64_t CalculateKeyedNetGroup(const CAddress& ad) const;
319 CNode* FindNode(const CNetAddr& ip);
320 CNode* FindNode(const CSubNet& subNet);
321 CNode* FindNode(const std::string& addrName);
322 CNode* FindNode(const CService& addr);
324 bool AttemptToEvictConnection();
325 CNode* ConnectNode(CAddress addrConnect, const char *pszDest, bool fCountFailure);
326 bool IsWhitelistedRange(const CNetAddr &addr);
328 void DeleteNode(CNode* pnode);
330 NodeId GetNewNodeId();
332 size_t SocketSendData(CNode *pnode) const;
333 //!check is the banlist has unwritten changes
334 bool BannedSetIsDirty();
335 //!set the "dirty" flag for the banlist
336 void SetBannedSetDirty(bool dirty=true);
337 //!clean unused entries (if bantime has expired)
338 void SweepBanned();
339 void DumpAddresses();
340 void DumpData();
341 void DumpBanlist();
343 // Network stats
344 void RecordBytesRecv(uint64_t bytes);
345 void RecordBytesSent(uint64_t bytes);
347 // Whether the node should be passed out in ForEach* callbacks
348 static bool NodeFullyConnected(const CNode* pnode);
350 // Network usage totals
351 CCriticalSection cs_totalBytesRecv;
352 CCriticalSection cs_totalBytesSent;
353 uint64_t nTotalBytesRecv;
354 uint64_t nTotalBytesSent;
356 // outbound limit & stats
357 uint64_t nMaxOutboundTotalBytesSentInCycle;
358 uint64_t nMaxOutboundCycleStartTime;
359 uint64_t nMaxOutboundLimit;
360 uint64_t nMaxOutboundTimeframe;
362 // Whitelisted ranges. Any node connecting from these is automatically
363 // whitelisted (as well as those connecting to whitelisted binds).
364 std::vector<CSubNet> vWhitelistedRange;
366 unsigned int nSendBufferMaxSize;
367 unsigned int nReceiveFloodSize;
369 std::vector<ListenSocket> vhListenSocket;
370 std::atomic<bool> fNetworkActive;
371 banmap_t setBanned;
372 CCriticalSection cs_setBanned;
373 bool setBannedIsDirty;
374 bool fAddressesInitialized;
375 CAddrMan addrman;
376 std::deque<std::string> vOneShots;
377 CCriticalSection cs_vOneShots;
378 std::vector<std::string> vAddedNodes;
379 CCriticalSection cs_vAddedNodes;
380 std::vector<CNode*> vNodes;
381 std::list<CNode*> vNodesDisconnected;
382 mutable CCriticalSection cs_vNodes;
383 std::atomic<NodeId> nLastNodeId;
385 /** Services this instance offers */
386 ServiceFlags nLocalServices;
388 /** Services this instance cares about */
389 ServiceFlags nRelevantServices;
391 CSemaphore *semOutbound;
392 CSemaphore *semAddnode;
393 int nMaxConnections;
394 int nMaxOutbound;
395 int nMaxAddnode;
396 int nMaxFeeler;
397 std::atomic<int> nBestHeight;
398 CClientUIInterface* clientInterface;
400 /** SipHasher seeds for deterministic randomness */
401 const uint64_t nSeed0, nSeed1;
403 /** flag for waking the message processor. */
404 bool fMsgProcWake;
406 std::condition_variable condMsgProc;
407 std::mutex mutexMsgProc;
408 std::atomic<bool> flagInterruptMsgProc;
410 CThreadInterrupt interruptNet;
412 std::thread threadDNSAddressSeed;
413 std::thread threadSocketHandler;
414 std::thread threadOpenAddedConnections;
415 std::thread threadOpenConnections;
416 std::thread threadMessageHandler;
418 extern std::unique_ptr<CConnman> g_connman;
419 void Discover(boost::thread_group& threadGroup);
420 void MapPort(bool fUseUPnP);
421 unsigned short GetListenPort();
422 bool BindListenPort(const CService &bindAddr, std::string& strError, bool fWhitelisted = false);
424 struct CombinerAll
426 typedef bool result_type;
428 template<typename I>
429 bool operator()(I first, I last) const
431 while (first != last) {
432 if (!(*first)) return false;
433 ++first;
435 return true;
439 // Signals for message handling
440 struct CNodeSignals
442 boost::signals2::signal<bool (CNode*, CConnman&, std::atomic<bool>&), CombinerAll> ProcessMessages;
443 boost::signals2::signal<bool (CNode*, CConnman&, std::atomic<bool>&), CombinerAll> SendMessages;
444 boost::signals2::signal<void (CNode*, CConnman&)> InitializeNode;
445 boost::signals2::signal<void (NodeId, bool&)> FinalizeNode;
449 CNodeSignals& GetNodeSignals();
452 enum
454 LOCAL_NONE, // unknown
455 LOCAL_IF, // address a local interface listens on
456 LOCAL_BIND, // address explicit bound to
457 LOCAL_UPNP, // address reported by UPnP
458 LOCAL_MANUAL, // address explicitly specified (-externalip=)
460 LOCAL_MAX
463 bool IsPeerAddrLocalGood(CNode *pnode);
464 void AdvertiseLocal(CNode *pnode);
465 void SetLimited(enum Network net, bool fLimited = true);
466 bool IsLimited(enum Network net);
467 bool IsLimited(const CNetAddr& addr);
468 bool AddLocal(const CService& addr, int nScore = LOCAL_NONE);
469 bool AddLocal(const CNetAddr& addr, int nScore = LOCAL_NONE);
470 bool RemoveLocal(const CService& addr);
471 bool SeenLocal(const CService& addr);
472 bool IsLocal(const CService& addr);
473 bool GetLocal(CService &addr, const CNetAddr *paddrPeer = nullptr);
474 bool IsReachable(enum Network net);
475 bool IsReachable(const CNetAddr &addr);
476 CAddress GetLocalAddress(const CNetAddr *paddrPeer, ServiceFlags nLocalServices);
479 extern bool fDiscover;
480 extern bool fListen;
481 extern bool fRelayTxes;
483 extern limitedmap<uint256, int64_t> mapAlreadyAskedFor;
485 /** Subversion as sent to the P2P network in `version` messages */
486 extern std::string strSubVersion;
488 struct LocalServiceInfo {
489 int nScore;
490 int nPort;
493 extern CCriticalSection cs_mapLocalHost;
494 extern std::map<CNetAddr, LocalServiceInfo> mapLocalHost;
495 typedef std::map<std::string, uint64_t> mapMsgCmdSize; //command, total bytes
497 class CNodeStats
499 public:
500 NodeId nodeid;
501 ServiceFlags nServices;
502 bool fRelayTxes;
503 int64_t nLastSend;
504 int64_t nLastRecv;
505 int64_t nTimeConnected;
506 int64_t nTimeOffset;
507 std::string addrName;
508 int nVersion;
509 std::string cleanSubVer;
510 bool fInbound;
511 bool fAddnode;
512 int nStartingHeight;
513 uint64_t nSendBytes;
514 mapMsgCmdSize mapSendBytesPerMsgCmd;
515 uint64_t nRecvBytes;
516 mapMsgCmdSize mapRecvBytesPerMsgCmd;
517 bool fWhitelisted;
518 double dPingTime;
519 double dPingWait;
520 double dMinPing;
521 // Our address, as reported by the peer
522 std::string addrLocal;
523 // Address of this peer
524 CAddress addr;
525 // Bind address of our side of the connection
526 CAddress addrBind;
532 class CNetMessage {
533 private:
534 mutable CHash256 hasher;
535 mutable uint256 data_hash;
536 public:
537 bool in_data; // parsing header (false) or data (true)
539 CDataStream hdrbuf; // partially received header
540 CMessageHeader hdr; // complete header
541 unsigned int nHdrPos;
543 CDataStream vRecv; // received message data
544 unsigned int nDataPos;
546 int64_t nTime; // time (in microseconds) of message receipt.
548 CNetMessage(const CMessageHeader::MessageStartChars& pchMessageStartIn, int nTypeIn, int nVersionIn) : hdrbuf(nTypeIn, nVersionIn), hdr(pchMessageStartIn), vRecv(nTypeIn, nVersionIn) {
549 hdrbuf.resize(24);
550 in_data = false;
551 nHdrPos = 0;
552 nDataPos = 0;
553 nTime = 0;
556 bool complete() const
558 if (!in_data)
559 return false;
560 return (hdr.nMessageSize == nDataPos);
563 const uint256& GetMessageHash() const;
565 void SetVersion(int nVersionIn)
567 hdrbuf.SetVersion(nVersionIn);
568 vRecv.SetVersion(nVersionIn);
571 int readHeader(const char *pch, unsigned int nBytes);
572 int readData(const char *pch, unsigned int nBytes);
576 /** Information about a peer */
577 class CNode
579 friend class CConnman;
580 public:
581 // socket
582 std::atomic<ServiceFlags> nServices;
583 ServiceFlags nServicesExpected;
584 SOCKET hSocket;
585 size_t nSendSize; // total size of all vSendMsg entries
586 size_t nSendOffset; // offset inside the first vSendMsg already sent
587 uint64_t nSendBytes;
588 std::deque<std::vector<unsigned char>> vSendMsg;
589 CCriticalSection cs_vSend;
590 CCriticalSection cs_hSocket;
591 CCriticalSection cs_vRecv;
593 CCriticalSection cs_vProcessMsg;
594 std::list<CNetMessage> vProcessMsg;
595 size_t nProcessQueueSize;
597 CCriticalSection cs_sendProcessing;
599 std::deque<CInv> vRecvGetData;
600 uint64_t nRecvBytes;
601 std::atomic<int> nRecvVersion;
603 std::atomic<int64_t> nLastSend;
604 std::atomic<int64_t> nLastRecv;
605 const int64_t nTimeConnected;
606 std::atomic<int64_t> nTimeOffset;
607 // Address of this peer
608 const CAddress addr;
609 // Bind address of our side of the connection
610 const CAddress addrBind;
611 std::atomic<int> nVersion;
612 // strSubVer is whatever byte array we read from the wire. However, this field is intended
613 // to be printed out, displayed to humans in various forms and so on. So we sanitize it and
614 // store the sanitized version in cleanSubVer. The original should be used when dealing with
615 // the network or wire types and the cleaned string used when displayed or logged.
616 std::string strSubVer, cleanSubVer;
617 CCriticalSection cs_SubVer; // used for both cleanSubVer and strSubVer
618 bool fWhitelisted; // This peer can bypass DoS banning.
619 bool fFeeler; // If true this node is being used as a short lived feeler.
620 bool fOneShot;
621 bool fAddnode;
622 bool fClient;
623 const bool fInbound;
624 std::atomic_bool fSuccessfullyConnected;
625 std::atomic_bool fDisconnect;
626 // We use fRelayTxes for two purposes -
627 // a) it allows us to not relay tx invs before receiving the peer's version message
628 // b) the peer may tell us in its version message that we should not relay tx invs
629 // unless it loads a bloom filter.
630 bool fRelayTxes; //protected by cs_filter
631 bool fSentAddr;
632 CSemaphoreGrant grantOutbound;
633 CCriticalSection cs_filter;
634 CBloomFilter* pfilter;
635 std::atomic<int> nRefCount;
637 const uint64_t nKeyedNetGroup;
638 std::atomic_bool fPauseRecv;
639 std::atomic_bool fPauseSend;
640 protected:
642 mapMsgCmdSize mapSendBytesPerMsgCmd;
643 mapMsgCmdSize mapRecvBytesPerMsgCmd;
645 public:
646 uint256 hashContinue;
647 std::atomic<int> nStartingHeight;
649 // flood relay
650 std::vector<CAddress> vAddrToSend;
651 CRollingBloomFilter addrKnown;
652 bool fGetAddr;
653 std::set<uint256> setKnown;
654 int64_t nNextAddrSend;
655 int64_t nNextLocalAddrSend;
657 // inventory based relay
658 CRollingBloomFilter filterInventoryKnown;
659 // Set of transaction ids we still have to announce.
660 // They are sorted by the mempool before relay, so the order is not important.
661 std::set<uint256> setInventoryTxToSend;
662 // List of block ids we still have announce.
663 // There is no final sorting before sending, as they are always sent immediately
664 // and in the order requested.
665 std::vector<uint256> vInventoryBlockToSend;
666 CCriticalSection cs_inventory;
667 std::set<uint256> setAskFor;
668 std::multimap<int64_t, CInv> mapAskFor;
669 int64_t nNextInvSend;
670 // Used for headers announcements - unfiltered blocks to relay
671 // Also protected by cs_inventory
672 std::vector<uint256> vBlockHashesToAnnounce;
673 // Used for BIP35 mempool sending, also protected by cs_inventory
674 bool fSendMempool;
676 // Last time a "MEMPOOL" request was serviced.
677 std::atomic<int64_t> timeLastMempoolReq;
679 // Block and TXN accept times
680 std::atomic<int64_t> nLastBlockTime;
681 std::atomic<int64_t> nLastTXTime;
683 // Ping time measurement:
684 // The pong reply we're expecting, or 0 if no pong expected.
685 std::atomic<uint64_t> nPingNonceSent;
686 // Time (in usec) the last ping was sent, or 0 if no ping was ever sent.
687 std::atomic<int64_t> nPingUsecStart;
688 // Last measured round-trip time.
689 std::atomic<int64_t> nPingUsecTime;
690 // Best measured round-trip time.
691 std::atomic<int64_t> nMinPingUsecTime;
692 // Whether a ping is requested.
693 std::atomic<bool> fPingQueued;
694 // Minimum fee rate with which to filter inv's to this node
695 CAmount minFeeFilter;
696 CCriticalSection cs_feeFilter;
697 CAmount lastSentFeeFilter;
698 int64_t nextSendTimeFeeFilter;
700 CNode(NodeId id, ServiceFlags nLocalServicesIn, int nMyStartingHeightIn, SOCKET hSocketIn, const CAddress &addrIn, uint64_t nKeyedNetGroupIn, uint64_t nLocalHostNonceIn, const CAddress &addrBindIn, const std::string &addrNameIn = "", bool fInboundIn = false);
701 ~CNode();
703 private:
704 CNode(const CNode&);
705 void operator=(const CNode&);
706 const NodeId id;
709 const uint64_t nLocalHostNonce;
710 // Services offered to this peer
711 const ServiceFlags nLocalServices;
712 const int nMyStartingHeight;
713 int nSendVersion;
714 std::list<CNetMessage> vRecvMsg; // Used only by SocketHandler thread
716 mutable CCriticalSection cs_addrName;
717 std::string addrName;
719 // Our address, as reported by the peer
720 CService addrLocal;
721 mutable CCriticalSection cs_addrLocal;
722 public:
724 NodeId GetId() const {
725 return id;
728 uint64_t GetLocalNonce() const {
729 return nLocalHostNonce;
732 int GetMyStartingHeight() const {
733 return nMyStartingHeight;
736 int GetRefCount() const
738 assert(nRefCount >= 0);
739 return nRefCount;
742 bool ReceiveMsgBytes(const char *pch, unsigned int nBytes, bool& complete);
744 void SetRecvVersion(int nVersionIn)
746 nRecvVersion = nVersionIn;
748 int GetRecvVersion() const
750 return nRecvVersion;
752 void SetSendVersion(int nVersionIn);
753 int GetSendVersion() const;
755 CService GetAddrLocal() const;
756 //! May not be called more than once
757 void SetAddrLocal(const CService& addrLocalIn);
759 CNode* AddRef()
761 nRefCount++;
762 return this;
765 void Release()
767 nRefCount--;
772 void AddAddressKnown(const CAddress& _addr)
774 addrKnown.insert(_addr.GetKey());
777 void PushAddress(const CAddress& _addr, FastRandomContext &insecure_rand)
779 // Known checking here is only to save space from duplicates.
780 // SendMessages will filter it again for knowns that were added
781 // after addresses were pushed.
782 if (_addr.IsValid() && !addrKnown.contains(_addr.GetKey())) {
783 if (vAddrToSend.size() >= MAX_ADDR_TO_SEND) {
784 vAddrToSend[insecure_rand.randrange(vAddrToSend.size())] = _addr;
785 } else {
786 vAddrToSend.push_back(_addr);
792 void AddInventoryKnown(const CInv& inv)
795 LOCK(cs_inventory);
796 filterInventoryKnown.insert(inv.hash);
800 void PushInventory(const CInv& inv)
802 LOCK(cs_inventory);
803 if (inv.type == MSG_TX) {
804 if (!filterInventoryKnown.contains(inv.hash)) {
805 setInventoryTxToSend.insert(inv.hash);
807 } else if (inv.type == MSG_BLOCK) {
808 vInventoryBlockToSend.push_back(inv.hash);
812 void PushBlockHash(const uint256 &hash)
814 LOCK(cs_inventory);
815 vBlockHashesToAnnounce.push_back(hash);
818 void AskFor(const CInv& inv);
820 void CloseSocketDisconnect();
822 void copyStats(CNodeStats &stats);
824 ServiceFlags GetLocalServices() const
826 return nLocalServices;
829 std::string GetAddrName() const;
830 //! Sets the addrName only if it was not previously set
831 void MaybeSetAddrName(const std::string& addrNameIn);
838 /** Return a timestamp in the future (in microseconds) for exponentially distributed events. */
839 int64_t PoissonNextSend(int64_t nNow, int average_interval_seconds);
841 #endif // BITCOIN_NET_H