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.
15 #include "limitedmap.h"
16 #include "netaddress.h"
17 #include "policy/feerate.h"
23 #include "threadinterrupt.h"
30 #include <condition_variable>
33 #include <arpa/inet.h>
44 /** Time between pings automatically sent out for latency probing and keepalive (in seconds). */
45 static const int PING_INTERVAL
= 2 * 60;
46 /** Time after which to disconnect, after waiting for a ping response (or inactivity). */
47 static const int TIMEOUT_INTERVAL
= 20 * 60;
48 /** Run the feeler connection loop once every 2 minutes or 120 seconds. **/
49 static const int FEELER_INTERVAL
= 120;
50 /** The maximum number of entries in an 'inv' protocol message */
51 static const unsigned int MAX_INV_SZ
= 50000;
52 /** The maximum number of new addresses to accumulate before announcing. */
53 static const unsigned int MAX_ADDR_TO_SEND
= 1000;
54 /** Maximum length of incoming protocol messages (no message over 4 MB is currently acceptable). */
55 static const unsigned int MAX_PROTOCOL_MESSAGE_LENGTH
= 4 * 1000 * 1000;
56 /** Maximum length of strSubVer in `version` message */
57 static const unsigned int MAX_SUBVERSION_LENGTH
= 256;
58 /** Maximum number of automatic outgoing nodes */
59 static const int MAX_OUTBOUND_CONNECTIONS
= 8;
60 /** Maximum number of addnode outgoing nodes */
61 static const int MAX_ADDNODE_CONNECTIONS
= 8;
62 /** -listen default */
63 static const bool DEFAULT_LISTEN
= true;
66 static const bool DEFAULT_UPNP
= USE_UPNP
;
68 static const bool DEFAULT_UPNP
= false;
70 /** The maximum number of entries in mapAskFor */
71 static const size_t MAPASKFOR_MAX_SZ
= MAX_INV_SZ
;
72 /** The maximum number of entries in setAskFor (larger due to getdata latency)*/
73 static const size_t SETASKFOR_MAX_SZ
= 2 * MAX_INV_SZ
;
74 /** The maximum number of peer connections to maintain. */
75 static const unsigned int DEFAULT_MAX_PEER_CONNECTIONS
= 125;
76 /** The default for -maxuploadtarget. 0 = Unlimited */
77 static const uint64_t DEFAULT_MAX_UPLOAD_TARGET
= 0;
78 /** The default timeframe for -maxuploadtarget. 1 day. */
79 static const uint64_t MAX_UPLOAD_TIMEFRAME
= 60 * 60 * 24;
80 /** Default for blocks only*/
81 static const bool DEFAULT_BLOCKSONLY
= false;
83 static const bool DEFAULT_FORCEDNSSEED
= false;
84 static const size_t DEFAULT_MAXRECEIVEBUFFER
= 5 * 1000;
85 static const size_t DEFAULT_MAXSENDBUFFER
= 1 * 1000;
87 static const ServiceFlags REQUIRED_SERVICES
= NODE_NETWORK
;
89 // NOTE: When adjusting this, update rpcnet:setban's help ("24h")
90 static const unsigned int DEFAULT_MISBEHAVING_BANTIME
= 60 * 60 * 24; // Default 24-hour ban
92 typedef int64_t NodeId
;
96 std::string strAddedNode
;
97 CService resolvedAddress
;
103 class CClientUIInterface
;
105 struct CSerializedNetMsg
107 CSerializedNetMsg() = default;
108 CSerializedNetMsg(CSerializedNetMsg
&&) = default;
109 CSerializedNetMsg
& operator=(CSerializedNetMsg
&&) = default;
110 // No copying, only moves.
111 CSerializedNetMsg(const CSerializedNetMsg
& msg
) = delete;
112 CSerializedNetMsg
& operator=(const CSerializedNetMsg
&) = delete;
114 std::vector
<unsigned char> data
;
118 class NetEventsInterface
;
123 enum NumConnections
{
124 CONNECTIONS_NONE
= 0,
125 CONNECTIONS_IN
= (1U << 0),
126 CONNECTIONS_OUT
= (1U << 1),
127 CONNECTIONS_ALL
= (CONNECTIONS_IN
| CONNECTIONS_OUT
),
132 ServiceFlags nLocalServices
= NODE_NONE
;
133 ServiceFlags nRelevantServices
= NODE_NONE
;
134 int nMaxConnections
= 0;
135 int nMaxOutbound
= 0;
139 CClientUIInterface
* uiInterface
= nullptr;
140 NetEventsInterface
* m_msgproc
= 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
;
148 bool m_use_addrman_outgoing
= true;
149 std::vector
<std::string
> m_specified_outgoing
;
150 std::vector
<std::string
> m_added_nodes
;
153 void Init(const Options
& connOptions
) {
154 nLocalServices
= connOptions
.nLocalServices
;
155 nRelevantServices
= connOptions
.nRelevantServices
;
156 nMaxConnections
= connOptions
.nMaxConnections
;
157 nMaxOutbound
= std::min(connOptions
.nMaxOutbound
, connOptions
.nMaxConnections
);
158 nMaxAddnode
= connOptions
.nMaxAddnode
;
159 nMaxFeeler
= connOptions
.nMaxFeeler
;
160 nBestHeight
= connOptions
.nBestHeight
;
161 clientInterface
= connOptions
.uiInterface
;
162 m_msgproc
= connOptions
.m_msgproc
;
163 nSendBufferMaxSize
= connOptions
.nSendBufferMaxSize
;
164 nReceiveFloodSize
= connOptions
.nReceiveFloodSize
;
165 nMaxOutboundTimeframe
= connOptions
.nMaxOutboundTimeframe
;
166 nMaxOutboundLimit
= connOptions
.nMaxOutboundLimit
;
167 vWhitelistedRange
= connOptions
.vWhitelistedRange
;
168 vAddedNodes
= connOptions
.m_added_nodes
;
171 CConnman(uint64_t seed0
, uint64_t seed1
);
173 bool Start(CScheduler
& scheduler
, const Options
& options
);
176 bool GetNetworkActive() const { return fNetworkActive
; };
177 void SetNetworkActive(bool active
);
178 bool OpenNetworkConnection(const CAddress
& addrConnect
, bool fCountFailure
, CSemaphoreGrant
*grantOutbound
= nullptr, const char *strDest
= nullptr, bool fOneShot
= false, bool fFeeler
= false, bool fAddnode
= false);
179 bool CheckIncomingNonce(uint64_t nonce
);
181 bool ForNode(NodeId id
, std::function
<bool(CNode
* pnode
)> func
);
183 void PushMessage(CNode
* pnode
, CSerializedNetMsg
&& msg
);
185 template<typename Callable
>
186 void ForEachNode(Callable
&& func
)
189 for (auto&& node
: vNodes
) {
190 if (NodeFullyConnected(node
))
195 template<typename Callable
>
196 void ForEachNode(Callable
&& func
) const
199 for (auto&& node
: vNodes
) {
200 if (NodeFullyConnected(node
))
205 template<typename Callable
, typename CallableAfter
>
206 void ForEachNodeThen(Callable
&& pre
, CallableAfter
&& post
)
209 for (auto&& node
: vNodes
) {
210 if (NodeFullyConnected(node
))
216 template<typename Callable
, typename CallableAfter
>
217 void ForEachNodeThen(Callable
&& pre
, CallableAfter
&& post
) const
220 for (auto&& node
: vNodes
) {
221 if (NodeFullyConnected(node
))
228 size_t GetAddressCount() const;
229 void SetServices(const CService
&addr
, ServiceFlags nServices
);
230 void MarkAddressGood(const CAddress
& addr
);
231 void AddNewAddresses(const std::vector
<CAddress
>& vAddr
, const CAddress
& addrFrom
, int64_t nTimePenalty
= 0);
232 std::vector
<CAddress
> GetAddresses();
234 // Denial-of-service detection/prevention
235 // The idea is to detect peers that are behaving
236 // badly and disconnect/ban them, but do it in a
237 // one-coding-mistake-won't-shatter-the-entire-network
239 // IMPORTANT: There should be nothing I can give a
240 // node that it will forward on that will make that
241 // node's peers drop it. If there is, an attacker
242 // can isolate a node and/or try to split the network.
243 // Dropping a node for sending stuff that is invalid
244 // now but might be valid in a later version is also
245 // dangerous, because it can cause a network split
246 // between nodes running old code and nodes running
248 void Ban(const CNetAddr
& netAddr
, const BanReason
& reason
, int64_t bantimeoffset
= 0, bool sinceUnixEpoch
= false);
249 void Ban(const CSubNet
& subNet
, const BanReason
& reason
, int64_t bantimeoffset
= 0, bool sinceUnixEpoch
= false);
250 void ClearBanned(); // needed for unit testing
251 bool IsBanned(CNetAddr ip
);
252 bool IsBanned(CSubNet subnet
);
253 bool Unban(const CNetAddr
&ip
);
254 bool Unban(const CSubNet
&ip
);
255 void GetBanned(banmap_t
&banmap
);
256 void SetBanned(const banmap_t
&banmap
);
258 bool AddNode(const std::string
& node
);
259 bool RemoveAddedNode(const std::string
& node
);
260 std::vector
<AddedNodeInfo
> GetAddedNodeInfo();
262 size_t GetNodeCount(NumConnections num
);
263 void GetNodeStats(std::vector
<CNodeStats
>& vstats
);
264 bool DisconnectNode(const std::string
& node
);
265 bool DisconnectNode(NodeId id
);
267 ServiceFlags
GetLocalServices() const;
269 //!set the max outbound target in bytes
270 void SetMaxOutboundTarget(uint64_t limit
);
271 uint64_t GetMaxOutboundTarget();
273 //!set the timeframe for the max outbound target
274 void SetMaxOutboundTimeframe(uint64_t timeframe
);
275 uint64_t GetMaxOutboundTimeframe();
277 //!check if the outbound target is reached
278 // if param historicalBlockServingLimit is set true, the function will
279 // response true if the limit for serving historical blocks has been reached
280 bool OutboundTargetReached(bool historicalBlockServingLimit
);
282 //!response the bytes left in the current max outbound cycle
283 // in case of no limit, it will always response 0
284 uint64_t GetOutboundTargetBytesLeft();
286 //!response the time in second left in the current max outbound cycle
287 // in case of no limit, it will always response 0
288 uint64_t GetMaxOutboundTimeLeftInCycle();
290 uint64_t GetTotalBytesRecv();
291 uint64_t GetTotalBytesSent();
293 void SetBestHeight(int height
);
294 int GetBestHeight() const;
296 /** Get a unique deterministic randomizer. */
297 CSipHasher
GetDeterministicRandomizer(uint64_t id
) const;
299 unsigned int GetReceiveFloodSize() const;
301 void WakeMessageHandler();
303 struct ListenSocket
{
307 ListenSocket(SOCKET socket_
, bool whitelisted_
) : socket(socket_
), whitelisted(whitelisted_
) {}
310 bool BindListenPort(const CService
&bindAddr
, std::string
& strError
, bool fWhitelisted
= false);
311 bool Bind(const CService
&addr
, unsigned int flags
);
312 bool InitBinds(const std::vector
<CService
>& binds
, const std::vector
<CService
>& whiteBinds
);
313 void ThreadOpenAddedConnections();
314 void AddOneShot(const std::string
& strDest
);
315 void ProcessOneShot();
316 void ThreadOpenConnections(std::vector
<std::string
> connect
);
317 void ThreadMessageHandler();
318 void AcceptConnection(const ListenSocket
& hListenSocket
);
319 void ThreadSocketHandler();
320 void ThreadDNSAddressSeed();
322 uint64_t CalculateKeyedNetGroup(const CAddress
& ad
) const;
324 CNode
* FindNode(const CNetAddr
& ip
);
325 CNode
* FindNode(const CSubNet
& subNet
);
326 CNode
* FindNode(const std::string
& addrName
);
327 CNode
* FindNode(const CService
& addr
);
329 bool AttemptToEvictConnection();
330 CNode
* ConnectNode(CAddress addrConnect
, const char *pszDest
, bool fCountFailure
);
331 bool IsWhitelistedRange(const CNetAddr
&addr
);
333 void DeleteNode(CNode
* pnode
);
335 NodeId
GetNewNodeId();
337 size_t SocketSendData(CNode
*pnode
) const;
338 //!check is the banlist has unwritten changes
339 bool BannedSetIsDirty();
340 //!set the "dirty" flag for the banlist
341 void SetBannedSetDirty(bool dirty
=true);
342 //!clean unused entries (if bantime has expired)
344 void DumpAddresses();
349 void RecordBytesRecv(uint64_t bytes
);
350 void RecordBytesSent(uint64_t bytes
);
352 // Whether the node should be passed out in ForEach* callbacks
353 static bool NodeFullyConnected(const CNode
* pnode
);
355 // Network usage totals
356 CCriticalSection cs_totalBytesRecv
;
357 CCriticalSection cs_totalBytesSent
;
358 uint64_t nTotalBytesRecv
;
359 uint64_t nTotalBytesSent
;
361 // outbound limit & stats
362 uint64_t nMaxOutboundTotalBytesSentInCycle
;
363 uint64_t nMaxOutboundCycleStartTime
;
364 uint64_t nMaxOutboundLimit
;
365 uint64_t nMaxOutboundTimeframe
;
367 // Whitelisted ranges. Any node connecting from these is automatically
368 // whitelisted (as well as those connecting to whitelisted binds).
369 std::vector
<CSubNet
> vWhitelistedRange
;
371 unsigned int nSendBufferMaxSize
;
372 unsigned int nReceiveFloodSize
;
374 std::vector
<ListenSocket
> vhListenSocket
;
375 std::atomic
<bool> fNetworkActive
;
377 CCriticalSection cs_setBanned
;
378 bool setBannedIsDirty
;
379 bool fAddressesInitialized
;
381 std::deque
<std::string
> vOneShots
;
382 CCriticalSection cs_vOneShots
;
383 std::vector
<std::string
> vAddedNodes
;
384 CCriticalSection cs_vAddedNodes
;
385 std::vector
<CNode
*> vNodes
;
386 std::list
<CNode
*> vNodesDisconnected
;
387 mutable CCriticalSection cs_vNodes
;
388 std::atomic
<NodeId
> nLastNodeId
;
390 /** Services this instance offers */
391 ServiceFlags nLocalServices
;
393 /** Services this instance cares about */
394 ServiceFlags nRelevantServices
;
396 CSemaphore
*semOutbound
;
397 CSemaphore
*semAddnode
;
402 std::atomic
<int> nBestHeight
;
403 CClientUIInterface
* clientInterface
;
404 NetEventsInterface
* m_msgproc
;
406 /** SipHasher seeds for deterministic randomness */
407 const uint64_t nSeed0
, nSeed1
;
409 /** flag for waking the message processor. */
412 std::condition_variable condMsgProc
;
413 std::mutex mutexMsgProc
;
414 std::atomic
<bool> flagInterruptMsgProc
;
416 CThreadInterrupt interruptNet
;
418 std::thread threadDNSAddressSeed
;
419 std::thread threadSocketHandler
;
420 std::thread threadOpenAddedConnections
;
421 std::thread threadOpenConnections
;
422 std::thread threadMessageHandler
;
424 extern std::unique_ptr
<CConnman
> g_connman
;
425 void Discover(boost::thread_group
& threadGroup
);
426 void MapPort(bool fUseUPnP
);
427 unsigned short GetListenPort();
428 bool BindListenPort(const CService
&bindAddr
, std::string
& strError
, bool fWhitelisted
= false);
432 typedef bool result_type
;
435 bool operator()(I first
, I last
) const
437 while (first
!= last
) {
438 if (!(*first
)) return false;
446 * Interface for message handling
448 class NetEventsInterface
451 virtual bool ProcessMessages(CNode
* pnode
, std::atomic
<bool>& interrupt
) = 0;
452 virtual bool SendMessages(CNode
* pnode
, std::atomic
<bool>& interrupt
) = 0;
453 virtual void InitializeNode(CNode
* pnode
) = 0;
454 virtual void FinalizeNode(NodeId id
, bool& update_connection_time
) = 0;
459 LOCAL_NONE
, // unknown
460 LOCAL_IF
, // address a local interface listens on
461 LOCAL_BIND
, // address explicit bound to
462 LOCAL_UPNP
, // address reported by UPnP
463 LOCAL_MANUAL
, // address explicitly specified (-externalip=)
468 bool IsPeerAddrLocalGood(CNode
*pnode
);
469 void AdvertiseLocal(CNode
*pnode
);
470 void SetLimited(enum Network net
, bool fLimited
= true);
471 bool IsLimited(enum Network net
);
472 bool IsLimited(const CNetAddr
& addr
);
473 bool AddLocal(const CService
& addr
, int nScore
= LOCAL_NONE
);
474 bool AddLocal(const CNetAddr
& addr
, int nScore
= LOCAL_NONE
);
475 bool RemoveLocal(const CService
& addr
);
476 bool SeenLocal(const CService
& addr
);
477 bool IsLocal(const CService
& addr
);
478 bool GetLocal(CService
&addr
, const CNetAddr
*paddrPeer
= nullptr);
479 bool IsReachable(enum Network net
);
480 bool IsReachable(const CNetAddr
&addr
);
481 CAddress
GetLocalAddress(const CNetAddr
*paddrPeer
, ServiceFlags nLocalServices
);
484 extern bool fDiscover
;
486 extern bool fRelayTxes
;
488 extern limitedmap
<uint256
, int64_t> mapAlreadyAskedFor
;
490 /** Subversion as sent to the P2P network in `version` messages */
491 extern std::string strSubVersion
;
493 struct LocalServiceInfo
{
498 extern CCriticalSection cs_mapLocalHost
;
499 extern std::map
<CNetAddr
, LocalServiceInfo
> mapLocalHost
;
500 typedef std::map
<std::string
, uint64_t> mapMsgCmdSize
; //command, total bytes
506 ServiceFlags nServices
;
510 int64_t nTimeConnected
;
512 std::string addrName
;
514 std::string cleanSubVer
;
519 mapMsgCmdSize mapSendBytesPerMsgCmd
;
521 mapMsgCmdSize mapRecvBytesPerMsgCmd
;
526 // Our address, as reported by the peer
527 std::string addrLocal
;
528 // Address of this peer
530 // Bind address of our side of the connection
539 mutable CHash256 hasher
;
540 mutable uint256 data_hash
;
542 bool in_data
; // parsing header (false) or data (true)
544 CDataStream hdrbuf
; // partially received header
545 CMessageHeader hdr
; // complete header
546 unsigned int nHdrPos
;
548 CDataStream vRecv
; // received message data
549 unsigned int nDataPos
;
551 int64_t nTime
; // time (in microseconds) of message receipt.
553 CNetMessage(const CMessageHeader::MessageStartChars
& pchMessageStartIn
, int nTypeIn
, int nVersionIn
) : hdrbuf(nTypeIn
, nVersionIn
), hdr(pchMessageStartIn
), vRecv(nTypeIn
, nVersionIn
) {
561 bool complete() const
565 return (hdr
.nMessageSize
== nDataPos
);
568 const uint256
& GetMessageHash() const;
570 void SetVersion(int nVersionIn
)
572 hdrbuf
.SetVersion(nVersionIn
);
573 vRecv
.SetVersion(nVersionIn
);
576 int readHeader(const char *pch
, unsigned int nBytes
);
577 int readData(const char *pch
, unsigned int nBytes
);
581 /** Information about a peer */
584 friend class CConnman
;
587 std::atomic
<ServiceFlags
> nServices
;
588 ServiceFlags nServicesExpected
;
590 size_t nSendSize
; // total size of all vSendMsg entries
591 size_t nSendOffset
; // offset inside the first vSendMsg already sent
593 std::deque
<std::vector
<unsigned char>> vSendMsg
;
594 CCriticalSection cs_vSend
;
595 CCriticalSection cs_hSocket
;
596 CCriticalSection cs_vRecv
;
598 CCriticalSection cs_vProcessMsg
;
599 std::list
<CNetMessage
> vProcessMsg
;
600 size_t nProcessQueueSize
;
602 CCriticalSection cs_sendProcessing
;
604 std::deque
<CInv
> vRecvGetData
;
606 std::atomic
<int> nRecvVersion
;
608 std::atomic
<int64_t> nLastSend
;
609 std::atomic
<int64_t> nLastRecv
;
610 const int64_t nTimeConnected
;
611 std::atomic
<int64_t> nTimeOffset
;
612 // Address of this peer
614 // Bind address of our side of the connection
615 const CAddress addrBind
;
616 std::atomic
<int> nVersion
;
617 // strSubVer is whatever byte array we read from the wire. However, this field is intended
618 // to be printed out, displayed to humans in various forms and so on. So we sanitize it and
619 // store the sanitized version in cleanSubVer. The original should be used when dealing with
620 // the network or wire types and the cleaned string used when displayed or logged.
621 std::string strSubVer
, cleanSubVer
;
622 CCriticalSection cs_SubVer
; // used for both cleanSubVer and strSubVer
623 bool fWhitelisted
; // This peer can bypass DoS banning.
624 bool fFeeler
; // If true this node is being used as a short lived feeler.
629 std::atomic_bool fSuccessfullyConnected
;
630 std::atomic_bool fDisconnect
;
631 // We use fRelayTxes for two purposes -
632 // a) it allows us to not relay tx invs before receiving the peer's version message
633 // b) the peer may tell us in its version message that we should not relay tx invs
634 // unless it loads a bloom filter.
635 bool fRelayTxes
; //protected by cs_filter
637 CSemaphoreGrant grantOutbound
;
638 CCriticalSection cs_filter
;
639 CBloomFilter
* pfilter
;
640 std::atomic
<int> nRefCount
;
642 const uint64_t nKeyedNetGroup
;
643 std::atomic_bool fPauseRecv
;
644 std::atomic_bool fPauseSend
;
647 mapMsgCmdSize mapSendBytesPerMsgCmd
;
648 mapMsgCmdSize mapRecvBytesPerMsgCmd
;
651 uint256 hashContinue
;
652 std::atomic
<int> nStartingHeight
;
655 std::vector
<CAddress
> vAddrToSend
;
656 CRollingBloomFilter addrKnown
;
658 std::set
<uint256
> setKnown
;
659 int64_t nNextAddrSend
;
660 int64_t nNextLocalAddrSend
;
662 // inventory based relay
663 CRollingBloomFilter filterInventoryKnown
;
664 // Set of transaction ids we still have to announce.
665 // They are sorted by the mempool before relay, so the order is not important.
666 std::set
<uint256
> setInventoryTxToSend
;
667 // List of block ids we still have announce.
668 // There is no final sorting before sending, as they are always sent immediately
669 // and in the order requested.
670 std::vector
<uint256
> vInventoryBlockToSend
;
671 CCriticalSection cs_inventory
;
672 std::set
<uint256
> setAskFor
;
673 std::multimap
<int64_t, CInv
> mapAskFor
;
674 int64_t nNextInvSend
;
675 // Used for headers announcements - unfiltered blocks to relay
676 // Also protected by cs_inventory
677 std::vector
<uint256
> vBlockHashesToAnnounce
;
678 // Used for BIP35 mempool sending, also protected by cs_inventory
681 // Last time a "MEMPOOL" request was serviced.
682 std::atomic
<int64_t> timeLastMempoolReq
;
684 // Block and TXN accept times
685 std::atomic
<int64_t> nLastBlockTime
;
686 std::atomic
<int64_t> nLastTXTime
;
688 // Ping time measurement:
689 // The pong reply we're expecting, or 0 if no pong expected.
690 std::atomic
<uint64_t> nPingNonceSent
;
691 // Time (in usec) the last ping was sent, or 0 if no ping was ever sent.
692 std::atomic
<int64_t> nPingUsecStart
;
693 // Last measured round-trip time.
694 std::atomic
<int64_t> nPingUsecTime
;
695 // Best measured round-trip time.
696 std::atomic
<int64_t> nMinPingUsecTime
;
697 // Whether a ping is requested.
698 std::atomic
<bool> fPingQueued
;
699 // Minimum fee rate with which to filter inv's to this node
700 CAmount minFeeFilter
;
701 CCriticalSection cs_feeFilter
;
702 CAmount lastSentFeeFilter
;
703 int64_t nextSendTimeFeeFilter
;
705 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);
707 CNode(const CNode
&) = delete;
708 CNode
& operator=(const CNode
&) = delete;
712 const uint64_t nLocalHostNonce
;
713 // Services offered to this peer
714 const ServiceFlags nLocalServices
;
715 const int nMyStartingHeight
;
717 std::list
<CNetMessage
> vRecvMsg
; // Used only by SocketHandler thread
719 mutable CCriticalSection cs_addrName
;
720 std::string addrName
;
722 // Our address, as reported by the peer
724 mutable CCriticalSection cs_addrLocal
;
727 NodeId
GetId() const {
731 uint64_t GetLocalNonce() const {
732 return nLocalHostNonce
;
735 int GetMyStartingHeight() const {
736 return nMyStartingHeight
;
739 int GetRefCount() const
741 assert(nRefCount
>= 0);
745 bool ReceiveMsgBytes(const char *pch
, unsigned int nBytes
, bool& complete
);
747 void SetRecvVersion(int nVersionIn
)
749 nRecvVersion
= nVersionIn
;
751 int GetRecvVersion() const
755 void SetSendVersion(int nVersionIn
);
756 int GetSendVersion() const;
758 CService
GetAddrLocal() const;
759 //! May not be called more than once
760 void SetAddrLocal(const CService
& addrLocalIn
);
775 void AddAddressKnown(const CAddress
& _addr
)
777 addrKnown
.insert(_addr
.GetKey());
780 void PushAddress(const CAddress
& _addr
, FastRandomContext
&insecure_rand
)
782 // Known checking here is only to save space from duplicates.
783 // SendMessages will filter it again for knowns that were added
784 // after addresses were pushed.
785 if (_addr
.IsValid() && !addrKnown
.contains(_addr
.GetKey())) {
786 if (vAddrToSend
.size() >= MAX_ADDR_TO_SEND
) {
787 vAddrToSend
[insecure_rand
.randrange(vAddrToSend
.size())] = _addr
;
789 vAddrToSend
.push_back(_addr
);
795 void AddInventoryKnown(const CInv
& inv
)
799 filterInventoryKnown
.insert(inv
.hash
);
803 void PushInventory(const CInv
& inv
)
806 if (inv
.type
== MSG_TX
) {
807 if (!filterInventoryKnown
.contains(inv
.hash
)) {
808 setInventoryTxToSend
.insert(inv
.hash
);
810 } else if (inv
.type
== MSG_BLOCK
) {
811 vInventoryBlockToSend
.push_back(inv
.hash
);
815 void PushBlockHash(const uint256
&hash
)
818 vBlockHashesToAnnounce
.push_back(hash
);
821 void AskFor(const CInv
& inv
);
823 void CloseSocketDisconnect();
825 void copyStats(CNodeStats
&stats
);
827 ServiceFlags
GetLocalServices() const
829 return nLocalServices
;
832 std::string
GetAddrName() const;
833 //! Sets the addrName only if it was not previously set
834 void MaybeSetAddrName(const std::string
& addrNameIn
);
841 /** Return a timestamp in the future (in microseconds) for exponentially distributed events. */
842 int64_t PoissonNextSend(int64_t nNow
, int average_interval_seconds
);
844 #endif // BITCOIN_NET_H