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>
36 #include <boost/signals2/signal.hpp>
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;
67 static const bool DEFAULT_UPNP
= USE_UPNP
;
69 static const bool DEFAULT_UPNP
= false;
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
;
97 std::string strAddedNode
;
98 CService resolvedAddress
;
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
;
124 enum NumConnections
{
125 CONNECTIONS_NONE
= 0,
126 CONNECTIONS_IN
= (1U << 0),
127 CONNECTIONS_OUT
= (1U << 1),
128 CONNECTIONS_ALL
= (CONNECTIONS_IN
| CONNECTIONS_OUT
),
133 ServiceFlags nLocalServices
= NODE_NONE
;
134 ServiceFlags nRelevantServices
= NODE_NONE
;
135 int nMaxConnections
= 0;
136 int nMaxOutbound
= 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
;
148 bool m_use_addrman_outgoing
= true;
149 std::vector
<std::string
> m_specified_outgoing
;
152 void Init(const Options
& connOptions
) {
153 nLocalServices
= connOptions
.nLocalServices
;
154 nRelevantServices
= connOptions
.nRelevantServices
;
155 nMaxConnections
= connOptions
.nMaxConnections
;
156 nMaxOutbound
= std::min(connOptions
.nMaxOutbound
, connOptions
.nMaxConnections
);
157 nMaxAddnode
= connOptions
.nMaxAddnode
;
158 nMaxFeeler
= connOptions
.nMaxFeeler
;
159 nBestHeight
= connOptions
.nBestHeight
;
160 clientInterface
= connOptions
.uiInterface
;
161 nSendBufferMaxSize
= connOptions
.nSendBufferMaxSize
;
162 nReceiveFloodSize
= connOptions
.nReceiveFloodSize
;
163 nMaxOutboundTimeframe
= connOptions
.nMaxOutboundTimeframe
;
164 nMaxOutboundLimit
= connOptions
.nMaxOutboundLimit
;
165 vWhitelistedRange
= connOptions
.vWhitelistedRange
;
168 CConnman(uint64_t seed0
, uint64_t seed1
);
170 bool Start(CScheduler
& scheduler
, const Options
& options
);
173 bool GetNetworkActive() const { return fNetworkActive
; };
174 void SetNetworkActive(bool active
);
175 bool OpenNetworkConnection(const CAddress
& addrConnect
, bool fCountFailure
, CSemaphoreGrant
*grantOutbound
= nullptr, const char *strDest
= nullptr, bool fOneShot
= false, bool fFeeler
= false, bool fAddnode
= false);
176 bool CheckIncomingNonce(uint64_t nonce
);
178 bool ForNode(NodeId id
, std::function
<bool(CNode
* pnode
)> func
);
180 void PushMessage(CNode
* pnode
, CSerializedNetMsg
&& msg
);
182 template<typename Callable
>
183 void ForEachNode(Callable
&& func
)
186 for (auto&& node
: vNodes
) {
187 if (NodeFullyConnected(node
))
192 template<typename Callable
>
193 void ForEachNode(Callable
&& func
) const
196 for (auto&& node
: vNodes
) {
197 if (NodeFullyConnected(node
))
202 template<typename Callable
, typename CallableAfter
>
203 void ForEachNodeThen(Callable
&& pre
, CallableAfter
&& post
)
206 for (auto&& node
: vNodes
) {
207 if (NodeFullyConnected(node
))
213 template<typename Callable
, typename CallableAfter
>
214 void ForEachNodeThen(Callable
&& pre
, CallableAfter
&& post
) const
217 for (auto&& node
: vNodes
) {
218 if (NodeFullyConnected(node
))
225 size_t GetAddressCount() const;
226 void SetServices(const CService
&addr
, ServiceFlags nServices
);
227 void MarkAddressGood(const CAddress
& addr
);
228 void AddNewAddresses(const std::vector
<CAddress
>& vAddr
, const CAddress
& addrFrom
, int64_t nTimePenalty
= 0);
229 std::vector
<CAddress
> GetAddresses();
231 // Denial-of-service detection/prevention
232 // The idea is to detect peers that are behaving
233 // badly and disconnect/ban them, but do it in a
234 // one-coding-mistake-won't-shatter-the-entire-network
236 // IMPORTANT: There should be nothing I can give a
237 // node that it will forward on that will make that
238 // node's peers drop it. If there is, an attacker
239 // can isolate a node and/or try to split the network.
240 // Dropping a node for sending stuff that is invalid
241 // now but might be valid in a later version is also
242 // dangerous, because it can cause a network split
243 // between nodes running old code and nodes running
245 void Ban(const CNetAddr
& netAddr
, const BanReason
& reason
, int64_t bantimeoffset
= 0, bool sinceUnixEpoch
= false);
246 void Ban(const CSubNet
& subNet
, const BanReason
& reason
, int64_t bantimeoffset
= 0, bool sinceUnixEpoch
= false);
247 void ClearBanned(); // needed for unit testing
248 bool IsBanned(CNetAddr ip
);
249 bool IsBanned(CSubNet subnet
);
250 bool Unban(const CNetAddr
&ip
);
251 bool Unban(const CSubNet
&ip
);
252 void GetBanned(banmap_t
&banmap
);
253 void SetBanned(const banmap_t
&banmap
);
255 bool AddNode(const std::string
& node
);
256 bool RemoveAddedNode(const std::string
& node
);
257 std::vector
<AddedNodeInfo
> GetAddedNodeInfo();
259 size_t GetNodeCount(NumConnections num
);
260 void GetNodeStats(std::vector
<CNodeStats
>& vstats
);
261 bool DisconnectNode(const std::string
& node
);
262 bool DisconnectNode(NodeId id
);
264 ServiceFlags
GetLocalServices() const;
266 //!set the max outbound target in bytes
267 void SetMaxOutboundTarget(uint64_t limit
);
268 uint64_t GetMaxOutboundTarget();
270 //!set the timeframe for the max outbound target
271 void SetMaxOutboundTimeframe(uint64_t timeframe
);
272 uint64_t GetMaxOutboundTimeframe();
274 //!check if the outbound target is reached
275 // if param historicalBlockServingLimit is set true, the function will
276 // response true if the limit for serving historical blocks has been reached
277 bool OutboundTargetReached(bool historicalBlockServingLimit
);
279 //!response the bytes left in the current max outbound cycle
280 // in case of no limit, it will always response 0
281 uint64_t GetOutboundTargetBytesLeft();
283 //!response the time in second left in the current max outbound cycle
284 // in case of no limit, it will always response 0
285 uint64_t GetMaxOutboundTimeLeftInCycle();
287 uint64_t GetTotalBytesRecv();
288 uint64_t GetTotalBytesSent();
290 void SetBestHeight(int height
);
291 int GetBestHeight() const;
293 /** Get a unique deterministic randomizer. */
294 CSipHasher
GetDeterministicRandomizer(uint64_t id
) const;
296 unsigned int GetReceiveFloodSize() const;
298 void WakeMessageHandler();
300 struct ListenSocket
{
304 ListenSocket(SOCKET socket_
, bool whitelisted_
) : socket(socket_
), whitelisted(whitelisted_
) {}
307 bool BindListenPort(const CService
&bindAddr
, std::string
& strError
, bool fWhitelisted
= false);
308 bool Bind(const CService
&addr
, unsigned int flags
);
309 bool InitBinds(const std::vector
<CService
>& binds
, const std::vector
<CService
>& whiteBinds
);
310 void ThreadOpenAddedConnections();
311 void AddOneShot(const std::string
& strDest
);
312 void ProcessOneShot();
313 void ThreadOpenConnections(std::vector
<std::string
> connect
);
314 void ThreadMessageHandler();
315 void AcceptConnection(const ListenSocket
& hListenSocket
);
316 void ThreadSocketHandler();
317 void ThreadDNSAddressSeed();
319 uint64_t CalculateKeyedNetGroup(const CAddress
& ad
) const;
321 CNode
* FindNode(const CNetAddr
& ip
);
322 CNode
* FindNode(const CSubNet
& subNet
);
323 CNode
* FindNode(const std::string
& addrName
);
324 CNode
* FindNode(const CService
& addr
);
326 bool AttemptToEvictConnection();
327 CNode
* ConnectNode(CAddress addrConnect
, const char *pszDest
, bool fCountFailure
);
328 bool IsWhitelistedRange(const CNetAddr
&addr
);
330 void DeleteNode(CNode
* pnode
);
332 NodeId
GetNewNodeId();
334 size_t SocketSendData(CNode
*pnode
) const;
335 //!check is the banlist has unwritten changes
336 bool BannedSetIsDirty();
337 //!set the "dirty" flag for the banlist
338 void SetBannedSetDirty(bool dirty
=true);
339 //!clean unused entries (if bantime has expired)
341 void DumpAddresses();
346 void RecordBytesRecv(uint64_t bytes
);
347 void RecordBytesSent(uint64_t bytes
);
349 // Whether the node should be passed out in ForEach* callbacks
350 static bool NodeFullyConnected(const CNode
* pnode
);
352 // Network usage totals
353 CCriticalSection cs_totalBytesRecv
;
354 CCriticalSection cs_totalBytesSent
;
355 uint64_t nTotalBytesRecv
;
356 uint64_t nTotalBytesSent
;
358 // outbound limit & stats
359 uint64_t nMaxOutboundTotalBytesSentInCycle
;
360 uint64_t nMaxOutboundCycleStartTime
;
361 uint64_t nMaxOutboundLimit
;
362 uint64_t nMaxOutboundTimeframe
;
364 // Whitelisted ranges. Any node connecting from these is automatically
365 // whitelisted (as well as those connecting to whitelisted binds).
366 std::vector
<CSubNet
> vWhitelistedRange
;
368 unsigned int nSendBufferMaxSize
;
369 unsigned int nReceiveFloodSize
;
371 std::vector
<ListenSocket
> vhListenSocket
;
372 std::atomic
<bool> fNetworkActive
;
374 CCriticalSection cs_setBanned
;
375 bool setBannedIsDirty
;
376 bool fAddressesInitialized
;
378 std::deque
<std::string
> vOneShots
;
379 CCriticalSection cs_vOneShots
;
380 std::vector
<std::string
> vAddedNodes
;
381 CCriticalSection cs_vAddedNodes
;
382 std::vector
<CNode
*> vNodes
;
383 std::list
<CNode
*> vNodesDisconnected
;
384 mutable CCriticalSection cs_vNodes
;
385 std::atomic
<NodeId
> nLastNodeId
;
387 /** Services this instance offers */
388 ServiceFlags nLocalServices
;
390 /** Services this instance cares about */
391 ServiceFlags nRelevantServices
;
393 CSemaphore
*semOutbound
;
394 CSemaphore
*semAddnode
;
399 std::atomic
<int> nBestHeight
;
400 CClientUIInterface
* clientInterface
;
402 /** SipHasher seeds for deterministic randomness */
403 const uint64_t nSeed0
, nSeed1
;
405 /** flag for waking the message processor. */
408 std::condition_variable condMsgProc
;
409 std::mutex mutexMsgProc
;
410 std::atomic
<bool> flagInterruptMsgProc
;
412 CThreadInterrupt interruptNet
;
414 std::thread threadDNSAddressSeed
;
415 std::thread threadSocketHandler
;
416 std::thread threadOpenAddedConnections
;
417 std::thread threadOpenConnections
;
418 std::thread threadMessageHandler
;
420 extern std::unique_ptr
<CConnman
> g_connman
;
421 void Discover(boost::thread_group
& threadGroup
);
422 void MapPort(bool fUseUPnP
);
423 unsigned short GetListenPort();
424 bool BindListenPort(const CService
&bindAddr
, std::string
& strError
, bool fWhitelisted
= false);
428 typedef bool result_type
;
431 bool operator()(I first
, I last
) const
433 while (first
!= last
) {
434 if (!(*first
)) return false;
441 // Signals for message handling
444 boost::signals2::signal
<bool (CNode
*, CConnman
&, std::atomic
<bool>&), CombinerAll
> ProcessMessages
;
445 boost::signals2::signal
<bool (CNode
*, CConnman
&, std::atomic
<bool>&), CombinerAll
> SendMessages
;
446 boost::signals2::signal
<void (CNode
*, CConnman
&)> InitializeNode
;
447 boost::signals2::signal
<void (NodeId
, bool&)> FinalizeNode
;
451 CNodeSignals
& GetNodeSignals();
456 LOCAL_NONE
, // unknown
457 LOCAL_IF
, // address a local interface listens on
458 LOCAL_BIND
, // address explicit bound to
459 LOCAL_UPNP
, // address reported by UPnP
460 LOCAL_MANUAL
, // address explicitly specified (-externalip=)
465 bool IsPeerAddrLocalGood(CNode
*pnode
);
466 void AdvertiseLocal(CNode
*pnode
);
467 void SetLimited(enum Network net
, bool fLimited
= true);
468 bool IsLimited(enum Network net
);
469 bool IsLimited(const CNetAddr
& addr
);
470 bool AddLocal(const CService
& addr
, int nScore
= LOCAL_NONE
);
471 bool AddLocal(const CNetAddr
& addr
, int nScore
= LOCAL_NONE
);
472 bool RemoveLocal(const CService
& addr
);
473 bool SeenLocal(const CService
& addr
);
474 bool IsLocal(const CService
& addr
);
475 bool GetLocal(CService
&addr
, const CNetAddr
*paddrPeer
= nullptr);
476 bool IsReachable(enum Network net
);
477 bool IsReachable(const CNetAddr
&addr
);
478 CAddress
GetLocalAddress(const CNetAddr
*paddrPeer
, ServiceFlags nLocalServices
);
481 extern bool fDiscover
;
483 extern bool fRelayTxes
;
485 extern limitedmap
<uint256
, int64_t> mapAlreadyAskedFor
;
487 /** Subversion as sent to the P2P network in `version` messages */
488 extern std::string strSubVersion
;
490 struct LocalServiceInfo
{
495 extern CCriticalSection cs_mapLocalHost
;
496 extern std::map
<CNetAddr
, LocalServiceInfo
> mapLocalHost
;
497 typedef std::map
<std::string
, uint64_t> mapMsgCmdSize
; //command, total bytes
503 ServiceFlags nServices
;
507 int64_t nTimeConnected
;
509 std::string addrName
;
511 std::string cleanSubVer
;
516 mapMsgCmdSize mapSendBytesPerMsgCmd
;
518 mapMsgCmdSize mapRecvBytesPerMsgCmd
;
523 // Our address, as reported by the peer
524 std::string addrLocal
;
525 // Address of this peer
527 // Bind address of our side of the connection
536 mutable CHash256 hasher
;
537 mutable uint256 data_hash
;
539 bool in_data
; // parsing header (false) or data (true)
541 CDataStream hdrbuf
; // partially received header
542 CMessageHeader hdr
; // complete header
543 unsigned int nHdrPos
;
545 CDataStream vRecv
; // received message data
546 unsigned int nDataPos
;
548 int64_t nTime
; // time (in microseconds) of message receipt.
550 CNetMessage(const CMessageHeader::MessageStartChars
& pchMessageStartIn
, int nTypeIn
, int nVersionIn
) : hdrbuf(nTypeIn
, nVersionIn
), hdr(pchMessageStartIn
), vRecv(nTypeIn
, nVersionIn
) {
558 bool complete() const
562 return (hdr
.nMessageSize
== nDataPos
);
565 const uint256
& GetMessageHash() const;
567 void SetVersion(int nVersionIn
)
569 hdrbuf
.SetVersion(nVersionIn
);
570 vRecv
.SetVersion(nVersionIn
);
573 int readHeader(const char *pch
, unsigned int nBytes
);
574 int readData(const char *pch
, unsigned int nBytes
);
578 /** Information about a peer */
581 friend class CConnman
;
584 std::atomic
<ServiceFlags
> nServices
;
585 ServiceFlags nServicesExpected
;
587 size_t nSendSize
; // total size of all vSendMsg entries
588 size_t nSendOffset
; // offset inside the first vSendMsg already sent
590 std::deque
<std::vector
<unsigned char>> vSendMsg
;
591 CCriticalSection cs_vSend
;
592 CCriticalSection cs_hSocket
;
593 CCriticalSection cs_vRecv
;
595 CCriticalSection cs_vProcessMsg
;
596 std::list
<CNetMessage
> vProcessMsg
;
597 size_t nProcessQueueSize
;
599 CCriticalSection cs_sendProcessing
;
601 std::deque
<CInv
> vRecvGetData
;
603 std::atomic
<int> nRecvVersion
;
605 std::atomic
<int64_t> nLastSend
;
606 std::atomic
<int64_t> nLastRecv
;
607 const int64_t nTimeConnected
;
608 std::atomic
<int64_t> nTimeOffset
;
609 // Address of this peer
611 // Bind address of our side of the connection
612 const CAddress addrBind
;
613 std::atomic
<int> nVersion
;
614 // strSubVer is whatever byte array we read from the wire. However, this field is intended
615 // to be printed out, displayed to humans in various forms and so on. So we sanitize it and
616 // store the sanitized version in cleanSubVer. The original should be used when dealing with
617 // the network or wire types and the cleaned string used when displayed or logged.
618 std::string strSubVer
, cleanSubVer
;
619 CCriticalSection cs_SubVer
; // used for both cleanSubVer and strSubVer
620 bool fWhitelisted
; // This peer can bypass DoS banning.
621 bool fFeeler
; // If true this node is being used as a short lived feeler.
626 std::atomic_bool fSuccessfullyConnected
;
627 std::atomic_bool fDisconnect
;
628 // We use fRelayTxes for two purposes -
629 // a) it allows us to not relay tx invs before receiving the peer's version message
630 // b) the peer may tell us in its version message that we should not relay tx invs
631 // unless it loads a bloom filter.
632 bool fRelayTxes
; //protected by cs_filter
634 CSemaphoreGrant grantOutbound
;
635 CCriticalSection cs_filter
;
636 CBloomFilter
* pfilter
;
637 std::atomic
<int> nRefCount
;
639 const uint64_t nKeyedNetGroup
;
640 std::atomic_bool fPauseRecv
;
641 std::atomic_bool fPauseSend
;
644 mapMsgCmdSize mapSendBytesPerMsgCmd
;
645 mapMsgCmdSize mapRecvBytesPerMsgCmd
;
648 uint256 hashContinue
;
649 std::atomic
<int> nStartingHeight
;
652 std::vector
<CAddress
> vAddrToSend
;
653 CRollingBloomFilter addrKnown
;
655 std::set
<uint256
> setKnown
;
656 int64_t nNextAddrSend
;
657 int64_t nNextLocalAddrSend
;
659 // inventory based relay
660 CRollingBloomFilter filterInventoryKnown
;
661 // Set of transaction ids we still have to announce.
662 // They are sorted by the mempool before relay, so the order is not important.
663 std::set
<uint256
> setInventoryTxToSend
;
664 // List of block ids we still have announce.
665 // There is no final sorting before sending, as they are always sent immediately
666 // and in the order requested.
667 std::vector
<uint256
> vInventoryBlockToSend
;
668 CCriticalSection cs_inventory
;
669 std::set
<uint256
> setAskFor
;
670 std::multimap
<int64_t, CInv
> mapAskFor
;
671 int64_t nNextInvSend
;
672 // Used for headers announcements - unfiltered blocks to relay
673 // Also protected by cs_inventory
674 std::vector
<uint256
> vBlockHashesToAnnounce
;
675 // Used for BIP35 mempool sending, also protected by cs_inventory
678 // Last time a "MEMPOOL" request was serviced.
679 std::atomic
<int64_t> timeLastMempoolReq
;
681 // Block and TXN accept times
682 std::atomic
<int64_t> nLastBlockTime
;
683 std::atomic
<int64_t> nLastTXTime
;
685 // Ping time measurement:
686 // The pong reply we're expecting, or 0 if no pong expected.
687 std::atomic
<uint64_t> nPingNonceSent
;
688 // Time (in usec) the last ping was sent, or 0 if no ping was ever sent.
689 std::atomic
<int64_t> nPingUsecStart
;
690 // Last measured round-trip time.
691 std::atomic
<int64_t> nPingUsecTime
;
692 // Best measured round-trip time.
693 std::atomic
<int64_t> nMinPingUsecTime
;
694 // Whether a ping is requested.
695 std::atomic
<bool> fPingQueued
;
696 // Minimum fee rate with which to filter inv's to this node
697 CAmount minFeeFilter
;
698 CCriticalSection cs_feeFilter
;
699 CAmount lastSentFeeFilter
;
700 int64_t nextSendTimeFeeFilter
;
702 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 void operator=(const CNode
&);
711 const uint64_t nLocalHostNonce
;
712 // Services offered to this peer
713 const ServiceFlags nLocalServices
;
714 const int nMyStartingHeight
;
716 std::list
<CNetMessage
> vRecvMsg
; // Used only by SocketHandler thread
718 mutable CCriticalSection cs_addrName
;
719 std::string addrName
;
721 // Our address, as reported by the peer
723 mutable CCriticalSection cs_addrLocal
;
726 NodeId
GetId() const {
730 uint64_t GetLocalNonce() const {
731 return nLocalHostNonce
;
734 int GetMyStartingHeight() const {
735 return nMyStartingHeight
;
738 int GetRefCount() const
740 assert(nRefCount
>= 0);
744 bool ReceiveMsgBytes(const char *pch
, unsigned int nBytes
, bool& complete
);
746 void SetRecvVersion(int nVersionIn
)
748 nRecvVersion
= nVersionIn
;
750 int GetRecvVersion() const
754 void SetSendVersion(int nVersionIn
);
755 int GetSendVersion() const;
757 CService
GetAddrLocal() const;
758 //! May not be called more than once
759 void SetAddrLocal(const CService
& addrLocalIn
);
774 void AddAddressKnown(const CAddress
& _addr
)
776 addrKnown
.insert(_addr
.GetKey());
779 void PushAddress(const CAddress
& _addr
, FastRandomContext
&insecure_rand
)
781 // Known checking here is only to save space from duplicates.
782 // SendMessages will filter it again for knowns that were added
783 // after addresses were pushed.
784 if (_addr
.IsValid() && !addrKnown
.contains(_addr
.GetKey())) {
785 if (vAddrToSend
.size() >= MAX_ADDR_TO_SEND
) {
786 vAddrToSend
[insecure_rand
.randrange(vAddrToSend
.size())] = _addr
;
788 vAddrToSend
.push_back(_addr
);
794 void AddInventoryKnown(const CInv
& inv
)
798 filterInventoryKnown
.insert(inv
.hash
);
802 void PushInventory(const CInv
& inv
)
805 if (inv
.type
== MSG_TX
) {
806 if (!filterInventoryKnown
.contains(inv
.hash
)) {
807 setInventoryTxToSend
.insert(inv
.hash
);
809 } else if (inv
.type
== MSG_BLOCK
) {
810 vInventoryBlockToSend
.push_back(inv
.hash
);
814 void PushBlockHash(const uint256
&hash
)
817 vBlockHashesToAnnounce
.push_back(hash
);
820 void AskFor(const CInv
& inv
);
822 void CloseSocketDisconnect();
824 void copyStats(CNodeStats
&stats
);
826 ServiceFlags
GetLocalServices() const
828 return nLocalServices
;
831 std::string
GetAddrName() const;
832 //! Sets the addrName only if it was not previously set
833 void MaybeSetAddrName(const std::string
& addrNameIn
);
840 /** Return a timestamp in the future (in microseconds) for exponentially distributed events. */
841 int64_t PoissonNextSend(int64_t nNow
, int average_interval_seconds
);
843 #endif // BITCOIN_NET_H