net: make CNode's id private
[bitcoinplatinum.git] / src / net.h
blob8b0ebc0ffecf1a03893201ac03d521577f20f0cc
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 "protocol.h"
18 #include "random.h"
19 #include "streams.h"
20 #include "sync.h"
21 #include "uint256.h"
22 #include "threadinterrupt.h"
24 #include <atomic>
25 #include <deque>
26 #include <stdint.h>
27 #include <thread>
28 #include <memory>
29 #include <condition_variable>
31 #ifndef WIN32
32 #include <arpa/inet.h>
33 #endif
35 #include <boost/foreach.hpp>
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 CTransaction;
104 class CNodeStats;
105 class CClientUIInterface;
107 struct CSerializedNetMsg
109 CSerializedNetMsg() = default;
110 CSerializedNetMsg(CSerializedNetMsg&&) = default;
111 CSerializedNetMsg& operator=(CSerializedNetMsg&&) = default;
112 // No copying, only moves.
113 CSerializedNetMsg(const CSerializedNetMsg& msg) = delete;
114 CSerializedNetMsg& operator=(const CSerializedNetMsg&) = delete;
116 std::vector<unsigned char> data;
117 std::string command;
121 class CConnman
123 public:
125 enum NumConnections {
126 CONNECTIONS_NONE = 0,
127 CONNECTIONS_IN = (1U << 0),
128 CONNECTIONS_OUT = (1U << 1),
129 CONNECTIONS_ALL = (CONNECTIONS_IN | CONNECTIONS_OUT),
132 struct Options
134 ServiceFlags nLocalServices = NODE_NONE;
135 ServiceFlags nRelevantServices = NODE_NONE;
136 int nMaxConnections = 0;
137 int nMaxOutbound = 0;
138 int nMaxAddnode = 0;
139 int nMaxFeeler = 0;
140 int nBestHeight = 0;
141 CClientUIInterface* uiInterface = nullptr;
142 unsigned int nSendBufferMaxSize = 0;
143 unsigned int nReceiveFloodSize = 0;
144 uint64_t nMaxOutboundTimeframe = 0;
145 uint64_t nMaxOutboundLimit = 0;
147 CConnman(uint64_t seed0, uint64_t seed1);
148 ~CConnman();
149 bool Start(CScheduler& scheduler, std::string& strNodeError, Options options);
150 void Stop();
151 void Interrupt();
152 bool BindListenPort(const CService &bindAddr, std::string& strError, bool fWhitelisted = false);
153 bool GetNetworkActive() const { return fNetworkActive; };
154 void SetNetworkActive(bool active);
155 bool OpenNetworkConnection(const CAddress& addrConnect, bool fCountFailure, CSemaphoreGrant *grantOutbound = NULL, const char *strDest = NULL, bool fOneShot = false, bool fFeeler = false, bool fAddnode = false);
156 bool CheckIncomingNonce(uint64_t nonce);
158 bool ForNode(NodeId id, std::function<bool(CNode* pnode)> func);
160 void PushMessage(CNode* pnode, CSerializedNetMsg&& msg);
162 template<typename Callable>
163 void ForEachNode(Callable&& func)
165 LOCK(cs_vNodes);
166 for (auto&& node : vNodes) {
167 if (NodeFullyConnected(node))
168 func(node);
172 template<typename Callable>
173 void ForEachNode(Callable&& func) const
175 LOCK(cs_vNodes);
176 for (auto&& node : vNodes) {
177 if (NodeFullyConnected(node))
178 func(node);
182 template<typename Callable, typename CallableAfter>
183 void ForEachNodeThen(Callable&& pre, CallableAfter&& post)
185 LOCK(cs_vNodes);
186 for (auto&& node : vNodes) {
187 if (NodeFullyConnected(node))
188 pre(node);
190 post();
193 template<typename Callable, typename CallableAfter>
194 void ForEachNodeThen(Callable&& pre, CallableAfter&& post) const
196 LOCK(cs_vNodes);
197 for (auto&& node : vNodes) {
198 if (NodeFullyConnected(node))
199 pre(node);
201 post();
204 // Addrman functions
205 size_t GetAddressCount() const;
206 void SetServices(const CService &addr, ServiceFlags nServices);
207 void MarkAddressGood(const CAddress& addr);
208 void AddNewAddresses(const std::vector<CAddress>& vAddr, const CAddress& addrFrom, int64_t nTimePenalty = 0);
209 std::vector<CAddress> GetAddresses();
211 // Denial-of-service detection/prevention
212 // The idea is to detect peers that are behaving
213 // badly and disconnect/ban them, but do it in a
214 // one-coding-mistake-won't-shatter-the-entire-network
215 // way.
216 // IMPORTANT: There should be nothing I can give a
217 // node that it will forward on that will make that
218 // node's peers drop it. If there is, an attacker
219 // can isolate a node and/or try to split the network.
220 // Dropping a node for sending stuff that is invalid
221 // now but might be valid in a later version is also
222 // dangerous, because it can cause a network split
223 // between nodes running old code and nodes running
224 // new code.
225 void Ban(const CNetAddr& netAddr, const BanReason& reason, int64_t bantimeoffset = 0, bool sinceUnixEpoch = false);
226 void Ban(const CSubNet& subNet, const BanReason& reason, int64_t bantimeoffset = 0, bool sinceUnixEpoch = false);
227 void ClearBanned(); // needed for unit testing
228 bool IsBanned(CNetAddr ip);
229 bool IsBanned(CSubNet subnet);
230 bool Unban(const CNetAddr &ip);
231 bool Unban(const CSubNet &ip);
232 void GetBanned(banmap_t &banmap);
233 void SetBanned(const banmap_t &banmap);
235 void AddOneShot(const std::string& strDest);
237 bool AddNode(const std::string& node);
238 bool RemoveAddedNode(const std::string& node);
239 std::vector<AddedNodeInfo> GetAddedNodeInfo();
241 size_t GetNodeCount(NumConnections num);
242 void GetNodeStats(std::vector<CNodeStats>& vstats);
243 bool DisconnectNode(const std::string& node);
244 bool DisconnectNode(NodeId id);
246 unsigned int GetSendBufferSize() const;
248 void AddWhitelistedRange(const CSubNet &subnet);
250 ServiceFlags GetLocalServices() const;
252 //!set the max outbound target in bytes
253 void SetMaxOutboundTarget(uint64_t limit);
254 uint64_t GetMaxOutboundTarget();
256 //!set the timeframe for the max outbound target
257 void SetMaxOutboundTimeframe(uint64_t timeframe);
258 uint64_t GetMaxOutboundTimeframe();
260 //!check if the outbound target is reached
261 // if param historicalBlockServingLimit is set true, the function will
262 // response true if the limit for serving historical blocks has been reached
263 bool OutboundTargetReached(bool historicalBlockServingLimit);
265 //!response the bytes left in the current max outbound cycle
266 // in case of no limit, it will always response 0
267 uint64_t GetOutboundTargetBytesLeft();
269 //!response the time in second left in the current max outbound cycle
270 // in case of no limit, it will always response 0
271 uint64_t GetMaxOutboundTimeLeftInCycle();
273 uint64_t GetTotalBytesRecv();
274 uint64_t GetTotalBytesSent();
276 void SetBestHeight(int height);
277 int GetBestHeight() const;
279 /** Get a unique deterministic randomizer. */
280 CSipHasher GetDeterministicRandomizer(uint64_t id) const;
282 unsigned int GetReceiveFloodSize() const;
284 void WakeMessageHandler();
285 private:
286 struct ListenSocket {
287 SOCKET socket;
288 bool whitelisted;
290 ListenSocket(SOCKET socket_, bool whitelisted_) : socket(socket_), whitelisted(whitelisted_) {}
293 void ThreadOpenAddedConnections();
294 void ProcessOneShot();
295 void ThreadOpenConnections();
296 void ThreadMessageHandler();
297 void AcceptConnection(const ListenSocket& hListenSocket);
298 void ThreadSocketHandler();
299 void ThreadDNSAddressSeed();
301 uint64_t CalculateKeyedNetGroup(const CAddress& ad) const;
303 CNode* FindNode(const CNetAddr& ip);
304 CNode* FindNode(const CSubNet& subNet);
305 CNode* FindNode(const std::string& addrName);
306 CNode* FindNode(const CService& addr);
308 bool AttemptToEvictConnection();
309 CNode* ConnectNode(CAddress addrConnect, const char *pszDest, bool fCountFailure);
310 bool IsWhitelistedRange(const CNetAddr &addr);
312 void DeleteNode(CNode* pnode);
314 NodeId GetNewNodeId();
316 size_t SocketSendData(CNode *pnode) const;
317 //!check is the banlist has unwritten changes
318 bool BannedSetIsDirty();
319 //!set the "dirty" flag for the banlist
320 void SetBannedSetDirty(bool dirty=true);
321 //!clean unused entries (if bantime has expired)
322 void SweepBanned();
323 void DumpAddresses();
324 void DumpData();
325 void DumpBanlist();
327 // Network stats
328 void RecordBytesRecv(uint64_t bytes);
329 void RecordBytesSent(uint64_t bytes);
331 // Whether the node should be passed out in ForEach* callbacks
332 static bool NodeFullyConnected(const CNode* pnode);
334 // Network usage totals
335 CCriticalSection cs_totalBytesRecv;
336 CCriticalSection cs_totalBytesSent;
337 uint64_t nTotalBytesRecv;
338 uint64_t nTotalBytesSent;
340 // outbound limit & stats
341 uint64_t nMaxOutboundTotalBytesSentInCycle;
342 uint64_t nMaxOutboundCycleStartTime;
343 uint64_t nMaxOutboundLimit;
344 uint64_t nMaxOutboundTimeframe;
346 // Whitelisted ranges. Any node connecting from these is automatically
347 // whitelisted (as well as those connecting to whitelisted binds).
348 std::vector<CSubNet> vWhitelistedRange;
349 CCriticalSection cs_vWhitelistedRange;
351 unsigned int nSendBufferMaxSize;
352 unsigned int nReceiveFloodSize;
354 std::vector<ListenSocket> vhListenSocket;
355 std::atomic<bool> fNetworkActive;
356 banmap_t setBanned;
357 CCriticalSection cs_setBanned;
358 bool setBannedIsDirty;
359 bool fAddressesInitialized;
360 CAddrMan addrman;
361 std::deque<std::string> vOneShots;
362 CCriticalSection cs_vOneShots;
363 std::vector<std::string> vAddedNodes;
364 CCriticalSection cs_vAddedNodes;
365 std::vector<CNode*> vNodes;
366 std::list<CNode*> vNodesDisconnected;
367 mutable CCriticalSection cs_vNodes;
368 std::atomic<NodeId> nLastNodeId;
370 /** Services this instance offers */
371 ServiceFlags nLocalServices;
373 /** Services this instance cares about */
374 ServiceFlags nRelevantServices;
376 CSemaphore *semOutbound;
377 CSemaphore *semAddnode;
378 int nMaxConnections;
379 int nMaxOutbound;
380 int nMaxAddnode;
381 int nMaxFeeler;
382 std::atomic<int> nBestHeight;
383 CClientUIInterface* clientInterface;
385 /** SipHasher seeds for deterministic randomness */
386 const uint64_t nSeed0, nSeed1;
388 /** flag for waking the message processor. */
389 bool fMsgProcWake;
391 std::condition_variable condMsgProc;
392 std::mutex mutexMsgProc;
393 std::atomic<bool> flagInterruptMsgProc;
395 CThreadInterrupt interruptNet;
397 std::thread threadDNSAddressSeed;
398 std::thread threadSocketHandler;
399 std::thread threadOpenAddedConnections;
400 std::thread threadOpenConnections;
401 std::thread threadMessageHandler;
403 extern std::unique_ptr<CConnman> g_connman;
404 void Discover(boost::thread_group& threadGroup);
405 void MapPort(bool fUseUPnP);
406 unsigned short GetListenPort();
407 bool BindListenPort(const CService &bindAddr, std::string& strError, bool fWhitelisted = false);
409 struct CombinerAll
411 typedef bool result_type;
413 template<typename I>
414 bool operator()(I first, I last) const
416 while (first != last) {
417 if (!(*first)) return false;
418 ++first;
420 return true;
424 // Signals for message handling
425 struct CNodeSignals
427 boost::signals2::signal<bool (CNode*, CConnman&, std::atomic<bool>&), CombinerAll> ProcessMessages;
428 boost::signals2::signal<bool (CNode*, CConnman&, std::atomic<bool>&), CombinerAll> SendMessages;
429 boost::signals2::signal<void (CNode*, CConnman&)> InitializeNode;
430 boost::signals2::signal<void (NodeId, bool&)> FinalizeNode;
434 CNodeSignals& GetNodeSignals();
437 enum
439 LOCAL_NONE, // unknown
440 LOCAL_IF, // address a local interface listens on
441 LOCAL_BIND, // address explicit bound to
442 LOCAL_UPNP, // address reported by UPnP
443 LOCAL_MANUAL, // address explicitly specified (-externalip=)
445 LOCAL_MAX
448 bool IsPeerAddrLocalGood(CNode *pnode);
449 void AdvertiseLocal(CNode *pnode);
450 void SetLimited(enum Network net, bool fLimited = true);
451 bool IsLimited(enum Network net);
452 bool IsLimited(const CNetAddr& addr);
453 bool AddLocal(const CService& addr, int nScore = LOCAL_NONE);
454 bool AddLocal(const CNetAddr& addr, int nScore = LOCAL_NONE);
455 bool RemoveLocal(const CService& addr);
456 bool SeenLocal(const CService& addr);
457 bool IsLocal(const CService& addr);
458 bool GetLocal(CService &addr, const CNetAddr *paddrPeer = NULL);
459 bool IsReachable(enum Network net);
460 bool IsReachable(const CNetAddr &addr);
461 CAddress GetLocalAddress(const CNetAddr *paddrPeer, ServiceFlags nLocalServices);
464 extern bool fDiscover;
465 extern bool fListen;
466 extern bool fRelayTxes;
468 extern limitedmap<uint256, int64_t> mapAlreadyAskedFor;
470 /** Subversion as sent to the P2P network in `version` messages */
471 extern std::string strSubVersion;
473 struct LocalServiceInfo {
474 int nScore;
475 int nPort;
478 extern CCriticalSection cs_mapLocalHost;
479 extern std::map<CNetAddr, LocalServiceInfo> mapLocalHost;
480 typedef std::map<std::string, uint64_t> mapMsgCmdSize; //command, total bytes
482 class CNodeStats
484 public:
485 NodeId nodeid;
486 ServiceFlags nServices;
487 bool fRelayTxes;
488 int64_t nLastSend;
489 int64_t nLastRecv;
490 int64_t nTimeConnected;
491 int64_t nTimeOffset;
492 std::string addrName;
493 int nVersion;
494 std::string cleanSubVer;
495 bool fInbound;
496 bool fAddnode;
497 int nStartingHeight;
498 uint64_t nSendBytes;
499 mapMsgCmdSize mapSendBytesPerMsgCmd;
500 uint64_t nRecvBytes;
501 mapMsgCmdSize mapRecvBytesPerMsgCmd;
502 bool fWhitelisted;
503 double dPingTime;
504 double dPingWait;
505 double dMinPing;
506 std::string addrLocal;
507 CAddress addr;
513 class CNetMessage {
514 private:
515 mutable CHash256 hasher;
516 mutable uint256 data_hash;
517 public:
518 bool in_data; // parsing header (false) or data (true)
520 CDataStream hdrbuf; // partially received header
521 CMessageHeader hdr; // complete header
522 unsigned int nHdrPos;
524 CDataStream vRecv; // received message data
525 unsigned int nDataPos;
527 int64_t nTime; // time (in microseconds) of message receipt.
529 CNetMessage(const CMessageHeader::MessageStartChars& pchMessageStartIn, int nTypeIn, int nVersionIn) : hdrbuf(nTypeIn, nVersionIn), hdr(pchMessageStartIn), vRecv(nTypeIn, nVersionIn) {
530 hdrbuf.resize(24);
531 in_data = false;
532 nHdrPos = 0;
533 nDataPos = 0;
534 nTime = 0;
537 bool complete() const
539 if (!in_data)
540 return false;
541 return (hdr.nMessageSize == nDataPos);
544 const uint256& GetMessageHash() const;
546 void SetVersion(int nVersionIn)
548 hdrbuf.SetVersion(nVersionIn);
549 vRecv.SetVersion(nVersionIn);
552 int readHeader(const char *pch, unsigned int nBytes);
553 int readData(const char *pch, unsigned int nBytes);
557 /** Information about a peer */
558 class CNode
560 friend class CConnman;
561 public:
562 // socket
563 std::atomic<ServiceFlags> nServices;
564 ServiceFlags nServicesExpected;
565 SOCKET hSocket;
566 size_t nSendSize; // total size of all vSendMsg entries
567 size_t nSendOffset; // offset inside the first vSendMsg already sent
568 uint64_t nSendBytes;
569 std::deque<std::vector<unsigned char>> vSendMsg;
570 CCriticalSection cs_vSend;
571 CCriticalSection cs_hSocket;
572 CCriticalSection cs_vRecv;
574 CCriticalSection cs_vProcessMsg;
575 std::list<CNetMessage> vProcessMsg;
576 size_t nProcessQueueSize;
578 CCriticalSection cs_sendProcessing;
580 std::deque<CInv> vRecvGetData;
581 uint64_t nRecvBytes;
582 std::atomic<int> nRecvVersion;
584 std::atomic<int64_t> nLastSend;
585 std::atomic<int64_t> nLastRecv;
586 const int64_t nTimeConnected;
587 std::atomic<int64_t> nTimeOffset;
588 const CAddress addr;
589 std::atomic<int> nVersion;
590 // strSubVer is whatever byte array we read from the wire. However, this field is intended
591 // to be printed out, displayed to humans in various forms and so on. So we sanitize it and
592 // store the sanitized version in cleanSubVer. The original should be used when dealing with
593 // the network or wire types and the cleaned string used when displayed or logged.
594 std::string strSubVer, cleanSubVer;
595 CCriticalSection cs_SubVer; // used for both cleanSubVer and strSubVer
596 bool fWhitelisted; // This peer can bypass DoS banning.
597 bool fFeeler; // If true this node is being used as a short lived feeler.
598 bool fOneShot;
599 bool fAddnode;
600 bool fClient;
601 const bool fInbound;
602 std::atomic_bool fSuccessfullyConnected;
603 std::atomic_bool fDisconnect;
604 // We use fRelayTxes for two purposes -
605 // a) it allows us to not relay tx invs before receiving the peer's version message
606 // b) the peer may tell us in its version message that we should not relay tx invs
607 // unless it loads a bloom filter.
608 bool fRelayTxes; //protected by cs_filter
609 bool fSentAddr;
610 CSemaphoreGrant grantOutbound;
611 CCriticalSection cs_filter;
612 CBloomFilter* pfilter;
613 std::atomic<int> nRefCount;
615 const uint64_t nKeyedNetGroup;
616 std::atomic_bool fPauseRecv;
617 std::atomic_bool fPauseSend;
618 protected:
620 mapMsgCmdSize mapSendBytesPerMsgCmd;
621 mapMsgCmdSize mapRecvBytesPerMsgCmd;
623 public:
624 uint256 hashContinue;
625 std::atomic<int> nStartingHeight;
627 // flood relay
628 std::vector<CAddress> vAddrToSend;
629 CRollingBloomFilter addrKnown;
630 bool fGetAddr;
631 std::set<uint256> setKnown;
632 int64_t nNextAddrSend;
633 int64_t nNextLocalAddrSend;
635 // inventory based relay
636 CRollingBloomFilter filterInventoryKnown;
637 // Set of transaction ids we still have to announce.
638 // They are sorted by the mempool before relay, so the order is not important.
639 std::set<uint256> setInventoryTxToSend;
640 // List of block ids we still have announce.
641 // There is no final sorting before sending, as they are always sent immediately
642 // and in the order requested.
643 std::vector<uint256> vInventoryBlockToSend;
644 CCriticalSection cs_inventory;
645 std::set<uint256> setAskFor;
646 std::multimap<int64_t, CInv> mapAskFor;
647 int64_t nNextInvSend;
648 // Used for headers announcements - unfiltered blocks to relay
649 // Also protected by cs_inventory
650 std::vector<uint256> vBlockHashesToAnnounce;
651 // Used for BIP35 mempool sending, also protected by cs_inventory
652 bool fSendMempool;
654 // Last time a "MEMPOOL" request was serviced.
655 std::atomic<int64_t> timeLastMempoolReq;
657 // Block and TXN accept times
658 std::atomic<int64_t> nLastBlockTime;
659 std::atomic<int64_t> nLastTXTime;
661 // Ping time measurement:
662 // The pong reply we're expecting, or 0 if no pong expected.
663 std::atomic<uint64_t> nPingNonceSent;
664 // Time (in usec) the last ping was sent, or 0 if no ping was ever sent.
665 std::atomic<int64_t> nPingUsecStart;
666 // Last measured round-trip time.
667 std::atomic<int64_t> nPingUsecTime;
668 // Best measured round-trip time.
669 std::atomic<int64_t> nMinPingUsecTime;
670 // Whether a ping is requested.
671 std::atomic<bool> fPingQueued;
672 // Minimum fee rate with which to filter inv's to this node
673 CAmount minFeeFilter;
674 CCriticalSection cs_feeFilter;
675 CAmount lastSentFeeFilter;
676 int64_t nextSendTimeFeeFilter;
678 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);
679 ~CNode();
681 private:
682 CNode(const CNode&);
683 void operator=(const CNode&);
684 const NodeId id;
687 const uint64_t nLocalHostNonce;
688 // Services offered to this peer
689 const ServiceFlags nLocalServices;
690 const int nMyStartingHeight;
691 int nSendVersion;
692 std::list<CNetMessage> vRecvMsg; // Used only by SocketHandler thread
694 mutable CCriticalSection cs_addrName;
695 std::string addrName;
697 CService addrLocal;
698 mutable CCriticalSection cs_addrLocal;
699 public:
701 NodeId GetId() const {
702 return id;
705 uint64_t GetLocalNonce() const {
706 return nLocalHostNonce;
709 int GetMyStartingHeight() const {
710 return nMyStartingHeight;
713 int GetRefCount()
715 assert(nRefCount >= 0);
716 return nRefCount;
719 bool ReceiveMsgBytes(const char *pch, unsigned int nBytes, bool& complete);
721 void SetRecvVersion(int nVersionIn)
723 nRecvVersion = nVersionIn;
725 int GetRecvVersion()
727 return nRecvVersion;
729 void SetSendVersion(int nVersionIn);
730 int GetSendVersion() const;
732 CService GetAddrLocal() const;
733 //! May not be called more than once
734 void SetAddrLocal(const CService& addrLocalIn);
736 CNode* AddRef()
738 nRefCount++;
739 return this;
742 void Release()
744 nRefCount--;
749 void AddAddressKnown(const CAddress& _addr)
751 addrKnown.insert(_addr.GetKey());
754 void PushAddress(const CAddress& _addr, FastRandomContext &insecure_rand)
756 // Known checking here is only to save space from duplicates.
757 // SendMessages will filter it again for knowns that were added
758 // after addresses were pushed.
759 if (_addr.IsValid() && !addrKnown.contains(_addr.GetKey())) {
760 if (vAddrToSend.size() >= MAX_ADDR_TO_SEND) {
761 vAddrToSend[insecure_rand.randrange(vAddrToSend.size())] = _addr;
762 } else {
763 vAddrToSend.push_back(_addr);
769 void AddInventoryKnown(const CInv& inv)
772 LOCK(cs_inventory);
773 filterInventoryKnown.insert(inv.hash);
777 void PushInventory(const CInv& inv)
779 LOCK(cs_inventory);
780 if (inv.type == MSG_TX) {
781 if (!filterInventoryKnown.contains(inv.hash)) {
782 setInventoryTxToSend.insert(inv.hash);
784 } else if (inv.type == MSG_BLOCK) {
785 vInventoryBlockToSend.push_back(inv.hash);
789 void PushBlockHash(const uint256 &hash)
791 LOCK(cs_inventory);
792 vBlockHashesToAnnounce.push_back(hash);
795 void AskFor(const CInv& inv);
797 void CloseSocketDisconnect();
799 void copyStats(CNodeStats &stats);
801 ServiceFlags GetLocalServices() const
803 return nLocalServices;
806 std::string GetAddrName() const;
807 //! Sets the addrName only if it was not previously set
808 void MaybeSetAddrName(const std::string& addrNameIn);
815 /** Return a timestamp in the future (in microseconds) for exponentially distributed events. */
816 int64_t PoissonNextSend(int64_t nNow, int average_interval_seconds);
818 #endif // BITCOIN_NET_H