[tests] Add libFuzzer support.
[bitcoinplatinum.git] / src / net.h
blobbea04bc5805c3fc4fe75f0f6afc541b80670d935
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/foreach.hpp>
37 #include <boost/signals2/signal.hpp>
39 class CScheduler;
40 class CNode;
42 namespace boost {
43 class thread_group;
44 } // namespace boost
46 /** Time between pings automatically sent out for latency probing and keepalive (in seconds). */
47 static const int PING_INTERVAL = 2 * 60;
48 /** Time after which to disconnect, after waiting for a ping response (or inactivity). */
49 static const int TIMEOUT_INTERVAL = 20 * 60;
50 /** Run the feeler connection loop once every 2 minutes or 120 seconds. **/
51 static const int FEELER_INTERVAL = 120;
52 /** The maximum number of entries in an 'inv' protocol message */
53 static const unsigned int MAX_INV_SZ = 50000;
54 /** The maximum number of new addresses to accumulate before announcing. */
55 static const unsigned int MAX_ADDR_TO_SEND = 1000;
56 /** Maximum length of incoming protocol messages (no message over 4 MB is currently acceptable). */
57 static const unsigned int MAX_PROTOCOL_MESSAGE_LENGTH = 4 * 1000 * 1000;
58 /** Maximum length of strSubVer in `version` message */
59 static const unsigned int MAX_SUBVERSION_LENGTH = 256;
60 /** Maximum number of automatic outgoing nodes */
61 static const int MAX_OUTBOUND_CONNECTIONS = 8;
62 /** Maximum number of addnode outgoing nodes */
63 static const int MAX_ADDNODE_CONNECTIONS = 8;
64 /** -listen default */
65 static const bool DEFAULT_LISTEN = true;
66 /** -upnp default */
67 #ifdef USE_UPNP
68 static const bool DEFAULT_UPNP = USE_UPNP;
69 #else
70 static const bool DEFAULT_UPNP = false;
71 #endif
72 /** The maximum number of entries in mapAskFor */
73 static const size_t MAPASKFOR_MAX_SZ = MAX_INV_SZ;
74 /** The maximum number of entries in setAskFor (larger due to getdata latency)*/
75 static const size_t SETASKFOR_MAX_SZ = 2 * MAX_INV_SZ;
76 /** The maximum number of peer connections to maintain. */
77 static const unsigned int DEFAULT_MAX_PEER_CONNECTIONS = 125;
78 /** The default for -maxuploadtarget. 0 = Unlimited */
79 static const uint64_t DEFAULT_MAX_UPLOAD_TARGET = 0;
80 /** The default timeframe for -maxuploadtarget. 1 day. */
81 static const uint64_t MAX_UPLOAD_TIMEFRAME = 60 * 60 * 24;
82 /** Default for blocks only*/
83 static const bool DEFAULT_BLOCKSONLY = false;
85 static const bool DEFAULT_FORCEDNSSEED = false;
86 static const size_t DEFAULT_MAXRECEIVEBUFFER = 5 * 1000;
87 static const size_t DEFAULT_MAXSENDBUFFER = 1 * 1000;
89 static const ServiceFlags REQUIRED_SERVICES = NODE_NETWORK;
91 // NOTE: When adjusting this, update rpcnet:setban's help ("24h")
92 static const unsigned int DEFAULT_MISBEHAVING_BANTIME = 60 * 60 * 24; // Default 24-hour ban
94 typedef int64_t NodeId;
96 struct AddedNodeInfo
98 std::string strAddedNode;
99 CService resolvedAddress;
100 bool fConnected;
101 bool fInbound;
104 class CTransaction;
105 class CNodeStats;
106 class CClientUIInterface;
108 struct CSerializedNetMsg
110 CSerializedNetMsg() = default;
111 CSerializedNetMsg(CSerializedNetMsg&&) = default;
112 CSerializedNetMsg& operator=(CSerializedNetMsg&&) = default;
113 // No copying, only moves.
114 CSerializedNetMsg(const CSerializedNetMsg& msg) = delete;
115 CSerializedNetMsg& operator=(const CSerializedNetMsg&) = delete;
117 std::vector<unsigned char> data;
118 std::string command;
122 class CConnman
124 public:
126 enum NumConnections {
127 CONNECTIONS_NONE = 0,
128 CONNECTIONS_IN = (1U << 0),
129 CONNECTIONS_OUT = (1U << 1),
130 CONNECTIONS_ALL = (CONNECTIONS_IN | CONNECTIONS_OUT),
133 struct Options
135 ServiceFlags nLocalServices = NODE_NONE;
136 ServiceFlags nRelevantServices = NODE_NONE;
137 int nMaxConnections = 0;
138 int nMaxOutbound = 0;
139 int nMaxAddnode = 0;
140 int nMaxFeeler = 0;
141 int nBestHeight = 0;
142 CClientUIInterface* uiInterface = nullptr;
143 unsigned int nSendBufferMaxSize = 0;
144 unsigned int nReceiveFloodSize = 0;
145 uint64_t nMaxOutboundTimeframe = 0;
146 uint64_t nMaxOutboundLimit = 0;
148 CConnman(uint64_t seed0, uint64_t seed1);
149 ~CConnman();
150 bool Start(CScheduler& scheduler, std::string& strNodeError, Options options);
151 void Stop();
152 void Interrupt();
153 bool BindListenPort(const CService &bindAddr, std::string& strError, bool fWhitelisted = false);
154 bool GetNetworkActive() const { return fNetworkActive; };
155 void SetNetworkActive(bool active);
156 bool OpenNetworkConnection(const CAddress& addrConnect, bool fCountFailure, CSemaphoreGrant *grantOutbound = NULL, const char *strDest = NULL, bool fOneShot = false, bool fFeeler = false, bool fAddnode = false);
157 bool CheckIncomingNonce(uint64_t nonce);
159 bool ForNode(NodeId id, std::function<bool(CNode* pnode)> func);
161 void PushMessage(CNode* pnode, CSerializedNetMsg&& msg);
163 template<typename Callable>
164 void ForEachNode(Callable&& func)
166 LOCK(cs_vNodes);
167 for (auto&& node : vNodes) {
168 if (NodeFullyConnected(node))
169 func(node);
173 template<typename Callable>
174 void ForEachNode(Callable&& func) const
176 LOCK(cs_vNodes);
177 for (auto&& node : vNodes) {
178 if (NodeFullyConnected(node))
179 func(node);
183 template<typename Callable, typename CallableAfter>
184 void ForEachNodeThen(Callable&& pre, CallableAfter&& post)
186 LOCK(cs_vNodes);
187 for (auto&& node : vNodes) {
188 if (NodeFullyConnected(node))
189 pre(node);
191 post();
194 template<typename Callable, typename CallableAfter>
195 void ForEachNodeThen(Callable&& pre, CallableAfter&& post) const
197 LOCK(cs_vNodes);
198 for (auto&& node : vNodes) {
199 if (NodeFullyConnected(node))
200 pre(node);
202 post();
205 // Addrman functions
206 size_t GetAddressCount() const;
207 void SetServices(const CService &addr, ServiceFlags nServices);
208 void MarkAddressGood(const CAddress& addr);
209 void AddNewAddresses(const std::vector<CAddress>& vAddr, const CAddress& addrFrom, int64_t nTimePenalty = 0);
210 std::vector<CAddress> GetAddresses();
212 // Denial-of-service detection/prevention
213 // The idea is to detect peers that are behaving
214 // badly and disconnect/ban them, but do it in a
215 // one-coding-mistake-won't-shatter-the-entire-network
216 // way.
217 // IMPORTANT: There should be nothing I can give a
218 // node that it will forward on that will make that
219 // node's peers drop it. If there is, an attacker
220 // can isolate a node and/or try to split the network.
221 // Dropping a node for sending stuff that is invalid
222 // now but might be valid in a later version is also
223 // dangerous, because it can cause a network split
224 // between nodes running old code and nodes running
225 // new code.
226 void Ban(const CNetAddr& netAddr, const BanReason& reason, int64_t bantimeoffset = 0, bool sinceUnixEpoch = false);
227 void Ban(const CSubNet& subNet, const BanReason& reason, int64_t bantimeoffset = 0, bool sinceUnixEpoch = false);
228 void ClearBanned(); // needed for unit testing
229 bool IsBanned(CNetAddr ip);
230 bool IsBanned(CSubNet subnet);
231 bool Unban(const CNetAddr &ip);
232 bool Unban(const CSubNet &ip);
233 void GetBanned(banmap_t &banmap);
234 void SetBanned(const banmap_t &banmap);
236 void AddOneShot(const std::string& strDest);
238 bool AddNode(const std::string& node);
239 bool RemoveAddedNode(const std::string& node);
240 std::vector<AddedNodeInfo> GetAddedNodeInfo();
242 size_t GetNodeCount(NumConnections num);
243 void GetNodeStats(std::vector<CNodeStats>& vstats);
244 bool DisconnectNode(const std::string& node);
245 bool DisconnectNode(NodeId id);
247 unsigned int GetSendBufferSize() const;
249 void AddWhitelistedRange(const CSubNet &subnet);
251 ServiceFlags GetLocalServices() const;
253 //!set the max outbound target in bytes
254 void SetMaxOutboundTarget(uint64_t limit);
255 uint64_t GetMaxOutboundTarget();
257 //!set the timeframe for the max outbound target
258 void SetMaxOutboundTimeframe(uint64_t timeframe);
259 uint64_t GetMaxOutboundTimeframe();
261 //!check if the outbound target is reached
262 // if param historicalBlockServingLimit is set true, the function will
263 // response true if the limit for serving historical blocks has been reached
264 bool OutboundTargetReached(bool historicalBlockServingLimit);
266 //!response the bytes left in the current max outbound cycle
267 // in case of no limit, it will always response 0
268 uint64_t GetOutboundTargetBytesLeft();
270 //!response the time in second left in the current max outbound cycle
271 // in case of no limit, it will always response 0
272 uint64_t GetMaxOutboundTimeLeftInCycle();
274 uint64_t GetTotalBytesRecv();
275 uint64_t GetTotalBytesSent();
277 void SetBestHeight(int height);
278 int GetBestHeight() const;
280 /** Get a unique deterministic randomizer. */
281 CSipHasher GetDeterministicRandomizer(uint64_t id) const;
283 unsigned int GetReceiveFloodSize() const;
285 void WakeMessageHandler();
286 private:
287 struct ListenSocket {
288 SOCKET socket;
289 bool whitelisted;
291 ListenSocket(SOCKET socket_, bool whitelisted_) : socket(socket_), whitelisted(whitelisted_) {}
294 void ThreadOpenAddedConnections();
295 void ProcessOneShot();
296 void ThreadOpenConnections();
297 void ThreadMessageHandler();
298 void AcceptConnection(const ListenSocket& hListenSocket);
299 void ThreadSocketHandler();
300 void ThreadDNSAddressSeed();
302 uint64_t CalculateKeyedNetGroup(const CAddress& ad) const;
304 CNode* FindNode(const CNetAddr& ip);
305 CNode* FindNode(const CSubNet& subNet);
306 CNode* FindNode(const std::string& addrName);
307 CNode* FindNode(const CService& addr);
309 bool AttemptToEvictConnection();
310 CNode* ConnectNode(CAddress addrConnect, const char *pszDest, bool fCountFailure);
311 bool IsWhitelistedRange(const CNetAddr &addr);
313 void DeleteNode(CNode* pnode);
315 NodeId GetNewNodeId();
317 size_t SocketSendData(CNode *pnode) const;
318 //!check is the banlist has unwritten changes
319 bool BannedSetIsDirty();
320 //!set the "dirty" flag for the banlist
321 void SetBannedSetDirty(bool dirty=true);
322 //!clean unused entries (if bantime has expired)
323 void SweepBanned();
324 void DumpAddresses();
325 void DumpData();
326 void DumpBanlist();
328 // Network stats
329 void RecordBytesRecv(uint64_t bytes);
330 void RecordBytesSent(uint64_t bytes);
332 // Whether the node should be passed out in ForEach* callbacks
333 static bool NodeFullyConnected(const CNode* pnode);
335 // Network usage totals
336 CCriticalSection cs_totalBytesRecv;
337 CCriticalSection cs_totalBytesSent;
338 uint64_t nTotalBytesRecv;
339 uint64_t nTotalBytesSent;
341 // outbound limit & stats
342 uint64_t nMaxOutboundTotalBytesSentInCycle;
343 uint64_t nMaxOutboundCycleStartTime;
344 uint64_t nMaxOutboundLimit;
345 uint64_t nMaxOutboundTimeframe;
347 // Whitelisted ranges. Any node connecting from these is automatically
348 // whitelisted (as well as those connecting to whitelisted binds).
349 std::vector<CSubNet> vWhitelistedRange;
350 CCriticalSection cs_vWhitelistedRange;
352 unsigned int nSendBufferMaxSize;
353 unsigned int nReceiveFloodSize;
355 std::vector<ListenSocket> vhListenSocket;
356 std::atomic<bool> fNetworkActive;
357 banmap_t setBanned;
358 CCriticalSection cs_setBanned;
359 bool setBannedIsDirty;
360 bool fAddressesInitialized;
361 CAddrMan addrman;
362 std::deque<std::string> vOneShots;
363 CCriticalSection cs_vOneShots;
364 std::vector<std::string> vAddedNodes;
365 CCriticalSection cs_vAddedNodes;
366 std::vector<CNode*> vNodes;
367 std::list<CNode*> vNodesDisconnected;
368 mutable CCriticalSection cs_vNodes;
369 std::atomic<NodeId> nLastNodeId;
371 /** Services this instance offers */
372 ServiceFlags nLocalServices;
374 /** Services this instance cares about */
375 ServiceFlags nRelevantServices;
377 CSemaphore *semOutbound;
378 CSemaphore *semAddnode;
379 int nMaxConnections;
380 int nMaxOutbound;
381 int nMaxAddnode;
382 int nMaxFeeler;
383 std::atomic<int> nBestHeight;
384 CClientUIInterface* clientInterface;
386 /** SipHasher seeds for deterministic randomness */
387 const uint64_t nSeed0, nSeed1;
389 /** flag for waking the message processor. */
390 bool fMsgProcWake;
392 std::condition_variable condMsgProc;
393 std::mutex mutexMsgProc;
394 std::atomic<bool> flagInterruptMsgProc;
396 CThreadInterrupt interruptNet;
398 std::thread threadDNSAddressSeed;
399 std::thread threadSocketHandler;
400 std::thread threadOpenAddedConnections;
401 std::thread threadOpenConnections;
402 std::thread threadMessageHandler;
404 extern std::unique_ptr<CConnman> g_connman;
405 void Discover(boost::thread_group& threadGroup);
406 void MapPort(bool fUseUPnP);
407 unsigned short GetListenPort();
408 bool BindListenPort(const CService &bindAddr, std::string& strError, bool fWhitelisted = false);
410 struct CombinerAll
412 typedef bool result_type;
414 template<typename I>
415 bool operator()(I first, I last) const
417 while (first != last) {
418 if (!(*first)) return false;
419 ++first;
421 return true;
425 // Signals for message handling
426 struct CNodeSignals
428 boost::signals2::signal<bool (CNode*, CConnman&, std::atomic<bool>&), CombinerAll> ProcessMessages;
429 boost::signals2::signal<bool (CNode*, CConnman&, std::atomic<bool>&), CombinerAll> SendMessages;
430 boost::signals2::signal<void (CNode*, CConnman&)> InitializeNode;
431 boost::signals2::signal<void (NodeId, bool&)> FinalizeNode;
435 CNodeSignals& GetNodeSignals();
438 enum
440 LOCAL_NONE, // unknown
441 LOCAL_IF, // address a local interface listens on
442 LOCAL_BIND, // address explicit bound to
443 LOCAL_UPNP, // address reported by UPnP
444 LOCAL_MANUAL, // address explicitly specified (-externalip=)
446 LOCAL_MAX
449 bool IsPeerAddrLocalGood(CNode *pnode);
450 void AdvertiseLocal(CNode *pnode);
451 void SetLimited(enum Network net, bool fLimited = true);
452 bool IsLimited(enum Network net);
453 bool IsLimited(const CNetAddr& addr);
454 bool AddLocal(const CService& addr, int nScore = LOCAL_NONE);
455 bool AddLocal(const CNetAddr& addr, int nScore = LOCAL_NONE);
456 bool RemoveLocal(const CService& addr);
457 bool SeenLocal(const CService& addr);
458 bool IsLocal(const CService& addr);
459 bool GetLocal(CService &addr, const CNetAddr *paddrPeer = NULL);
460 bool IsReachable(enum Network net);
461 bool IsReachable(const CNetAddr &addr);
462 CAddress GetLocalAddress(const CNetAddr *paddrPeer, ServiceFlags nLocalServices);
465 extern bool fDiscover;
466 extern bool fListen;
467 extern bool fRelayTxes;
469 extern limitedmap<uint256, int64_t> mapAlreadyAskedFor;
471 /** Subversion as sent to the P2P network in `version` messages */
472 extern std::string strSubVersion;
474 struct LocalServiceInfo {
475 int nScore;
476 int nPort;
479 extern CCriticalSection cs_mapLocalHost;
480 extern std::map<CNetAddr, LocalServiceInfo> mapLocalHost;
481 typedef std::map<std::string, uint64_t> mapMsgCmdSize; //command, total bytes
483 class CNodeStats
485 public:
486 NodeId nodeid;
487 ServiceFlags nServices;
488 bool fRelayTxes;
489 int64_t nLastSend;
490 int64_t nLastRecv;
491 int64_t nTimeConnected;
492 int64_t nTimeOffset;
493 std::string addrName;
494 int nVersion;
495 std::string cleanSubVer;
496 bool fInbound;
497 bool fAddnode;
498 int nStartingHeight;
499 uint64_t nSendBytes;
500 mapMsgCmdSize mapSendBytesPerMsgCmd;
501 uint64_t nRecvBytes;
502 mapMsgCmdSize mapRecvBytesPerMsgCmd;
503 bool fWhitelisted;
504 double dPingTime;
505 double dPingWait;
506 double dMinPing;
507 std::string addrLocal;
508 CAddress addr;
514 class CNetMessage {
515 private:
516 mutable CHash256 hasher;
517 mutable uint256 data_hash;
518 public:
519 bool in_data; // parsing header (false) or data (true)
521 CDataStream hdrbuf; // partially received header
522 CMessageHeader hdr; // complete header
523 unsigned int nHdrPos;
525 CDataStream vRecv; // received message data
526 unsigned int nDataPos;
528 int64_t nTime; // time (in microseconds) of message receipt.
530 CNetMessage(const CMessageHeader::MessageStartChars& pchMessageStartIn, int nTypeIn, int nVersionIn) : hdrbuf(nTypeIn, nVersionIn), hdr(pchMessageStartIn), vRecv(nTypeIn, nVersionIn) {
531 hdrbuf.resize(24);
532 in_data = false;
533 nHdrPos = 0;
534 nDataPos = 0;
535 nTime = 0;
538 bool complete() const
540 if (!in_data)
541 return false;
542 return (hdr.nMessageSize == nDataPos);
545 const uint256& GetMessageHash() const;
547 void SetVersion(int nVersionIn)
549 hdrbuf.SetVersion(nVersionIn);
550 vRecv.SetVersion(nVersionIn);
553 int readHeader(const char *pch, unsigned int nBytes);
554 int readData(const char *pch, unsigned int nBytes);
558 /** Information about a peer */
559 class CNode
561 friend class CConnman;
562 public:
563 // socket
564 std::atomic<ServiceFlags> nServices;
565 ServiceFlags nServicesExpected;
566 SOCKET hSocket;
567 size_t nSendSize; // total size of all vSendMsg entries
568 size_t nSendOffset; // offset inside the first vSendMsg already sent
569 uint64_t nSendBytes;
570 std::deque<std::vector<unsigned char>> vSendMsg;
571 CCriticalSection cs_vSend;
572 CCriticalSection cs_hSocket;
573 CCriticalSection cs_vRecv;
575 CCriticalSection cs_vProcessMsg;
576 std::list<CNetMessage> vProcessMsg;
577 size_t nProcessQueueSize;
579 CCriticalSection cs_sendProcessing;
581 std::deque<CInv> vRecvGetData;
582 uint64_t nRecvBytes;
583 std::atomic<int> nRecvVersion;
585 std::atomic<int64_t> nLastSend;
586 std::atomic<int64_t> nLastRecv;
587 const int64_t nTimeConnected;
588 std::atomic<int64_t> nTimeOffset;
589 const CAddress addr;
590 std::atomic<int> nVersion;
591 // strSubVer is whatever byte array we read from the wire. However, this field is intended
592 // to be printed out, displayed to humans in various forms and so on. So we sanitize it and
593 // store the sanitized version in cleanSubVer. The original should be used when dealing with
594 // the network or wire types and the cleaned string used when displayed or logged.
595 std::string strSubVer, cleanSubVer;
596 CCriticalSection cs_SubVer; // used for both cleanSubVer and strSubVer
597 bool fWhitelisted; // This peer can bypass DoS banning.
598 bool fFeeler; // If true this node is being used as a short lived feeler.
599 bool fOneShot;
600 bool fAddnode;
601 bool fClient;
602 const bool fInbound;
603 std::atomic_bool fSuccessfullyConnected;
604 std::atomic_bool fDisconnect;
605 // We use fRelayTxes for two purposes -
606 // a) it allows us to not relay tx invs before receiving the peer's version message
607 // b) the peer may tell us in its version message that we should not relay tx invs
608 // unless it loads a bloom filter.
609 bool fRelayTxes; //protected by cs_filter
610 bool fSentAddr;
611 CSemaphoreGrant grantOutbound;
612 CCriticalSection cs_filter;
613 CBloomFilter* pfilter;
614 std::atomic<int> nRefCount;
616 const uint64_t nKeyedNetGroup;
617 std::atomic_bool fPauseRecv;
618 std::atomic_bool fPauseSend;
619 protected:
621 mapMsgCmdSize mapSendBytesPerMsgCmd;
622 mapMsgCmdSize mapRecvBytesPerMsgCmd;
624 public:
625 uint256 hashContinue;
626 std::atomic<int> nStartingHeight;
628 // flood relay
629 std::vector<CAddress> vAddrToSend;
630 CRollingBloomFilter addrKnown;
631 bool fGetAddr;
632 std::set<uint256> setKnown;
633 int64_t nNextAddrSend;
634 int64_t nNextLocalAddrSend;
636 // inventory based relay
637 CRollingBloomFilter filterInventoryKnown;
638 // Set of transaction ids we still have to announce.
639 // They are sorted by the mempool before relay, so the order is not important.
640 std::set<uint256> setInventoryTxToSend;
641 // List of block ids we still have announce.
642 // There is no final sorting before sending, as they are always sent immediately
643 // and in the order requested.
644 std::vector<uint256> vInventoryBlockToSend;
645 CCriticalSection cs_inventory;
646 std::set<uint256> setAskFor;
647 std::multimap<int64_t, CInv> mapAskFor;
648 int64_t nNextInvSend;
649 // Used for headers announcements - unfiltered blocks to relay
650 // Also protected by cs_inventory
651 std::vector<uint256> vBlockHashesToAnnounce;
652 // Used for BIP35 mempool sending, also protected by cs_inventory
653 bool fSendMempool;
655 // Last time a "MEMPOOL" request was serviced.
656 std::atomic<int64_t> timeLastMempoolReq;
658 // Block and TXN accept times
659 std::atomic<int64_t> nLastBlockTime;
660 std::atomic<int64_t> nLastTXTime;
662 // Ping time measurement:
663 // The pong reply we're expecting, or 0 if no pong expected.
664 std::atomic<uint64_t> nPingNonceSent;
665 // Time (in usec) the last ping was sent, or 0 if no ping was ever sent.
666 std::atomic<int64_t> nPingUsecStart;
667 // Last measured round-trip time.
668 std::atomic<int64_t> nPingUsecTime;
669 // Best measured round-trip time.
670 std::atomic<int64_t> nMinPingUsecTime;
671 // Whether a ping is requested.
672 std::atomic<bool> fPingQueued;
673 // Minimum fee rate with which to filter inv's to this node
674 CAmount minFeeFilter;
675 CCriticalSection cs_feeFilter;
676 CAmount lastSentFeeFilter;
677 int64_t nextSendTimeFeeFilter;
679 CNode(NodeId id, ServiceFlags nLocalServicesIn, int nMyStartingHeightIn, SOCKET hSocketIn, const CAddress &addrIn, uint64_t nKeyedNetGroupIn, uint64_t nLocalHostNonceIn, const std::string &addrNameIn = "", bool fInboundIn = false);
680 ~CNode();
682 private:
683 CNode(const CNode&);
684 void operator=(const CNode&);
685 const NodeId id;
688 const uint64_t nLocalHostNonce;
689 // Services offered to this peer
690 const ServiceFlags nLocalServices;
691 const int nMyStartingHeight;
692 int nSendVersion;
693 std::list<CNetMessage> vRecvMsg; // Used only by SocketHandler thread
695 mutable CCriticalSection cs_addrName;
696 std::string addrName;
698 CService addrLocal;
699 mutable CCriticalSection cs_addrLocal;
700 public:
702 NodeId GetId() const {
703 return id;
706 uint64_t GetLocalNonce() const {
707 return nLocalHostNonce;
710 int GetMyStartingHeight() const {
711 return nMyStartingHeight;
714 int GetRefCount()
716 assert(nRefCount >= 0);
717 return nRefCount;
720 bool ReceiveMsgBytes(const char *pch, unsigned int nBytes, bool& complete);
722 void SetRecvVersion(int nVersionIn)
724 nRecvVersion = nVersionIn;
726 int GetRecvVersion()
728 return nRecvVersion;
730 void SetSendVersion(int nVersionIn);
731 int GetSendVersion() const;
733 CService GetAddrLocal() const;
734 //! May not be called more than once
735 void SetAddrLocal(const CService& addrLocalIn);
737 CNode* AddRef()
739 nRefCount++;
740 return this;
743 void Release()
745 nRefCount--;
750 void AddAddressKnown(const CAddress& _addr)
752 addrKnown.insert(_addr.GetKey());
755 void PushAddress(const CAddress& _addr, FastRandomContext &insecure_rand)
757 // Known checking here is only to save space from duplicates.
758 // SendMessages will filter it again for knowns that were added
759 // after addresses were pushed.
760 if (_addr.IsValid() && !addrKnown.contains(_addr.GetKey())) {
761 if (vAddrToSend.size() >= MAX_ADDR_TO_SEND) {
762 vAddrToSend[insecure_rand.randrange(vAddrToSend.size())] = _addr;
763 } else {
764 vAddrToSend.push_back(_addr);
770 void AddInventoryKnown(const CInv& inv)
773 LOCK(cs_inventory);
774 filterInventoryKnown.insert(inv.hash);
778 void PushInventory(const CInv& inv)
780 LOCK(cs_inventory);
781 if (inv.type == MSG_TX) {
782 if (!filterInventoryKnown.contains(inv.hash)) {
783 setInventoryTxToSend.insert(inv.hash);
785 } else if (inv.type == MSG_BLOCK) {
786 vInventoryBlockToSend.push_back(inv.hash);
790 void PushBlockHash(const uint256 &hash)
792 LOCK(cs_inventory);
793 vBlockHashesToAnnounce.push_back(hash);
796 void AskFor(const CInv& inv);
798 void CloseSocketDisconnect();
800 void copyStats(CNodeStats &stats);
802 ServiceFlags GetLocalServices() const
804 return nLocalServices;
807 std::string GetAddrName() const;
808 //! Sets the addrName only if it was not previously set
809 void MaybeSetAddrName(const std::string& addrNameIn);
816 /** Return a timestamp in the future (in microseconds) for exponentially distributed events. */
817 int64_t PoissonNextSend(int64_t nNow, int average_interval_seconds);
819 #endif // BITCOIN_NET_H