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
;
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 m_msgproc
= connOptions
.m_msgproc
;
162 nSendBufferMaxSize
= connOptions
.nSendBufferMaxSize
;
163 nReceiveFloodSize
= connOptions
.nReceiveFloodSize
;
164 nMaxOutboundTimeframe
= connOptions
.nMaxOutboundTimeframe
;
165 nMaxOutboundLimit
= connOptions
.nMaxOutboundLimit
;
166 vWhitelistedRange
= connOptions
.vWhitelistedRange
;
169 CConnman(uint64_t seed0
, uint64_t seed1
);
171 bool Start(CScheduler
& scheduler
, const Options
& options
);
174 bool GetNetworkActive() const { return fNetworkActive
; };
175 void SetNetworkActive(bool active
);
176 bool OpenNetworkConnection(const CAddress
& addrConnect
, bool fCountFailure
, CSemaphoreGrant
*grantOutbound
= nullptr, const char *strDest
= nullptr, bool fOneShot
= false, bool fFeeler
= false, bool fAddnode
= false);
177 bool CheckIncomingNonce(uint64_t nonce
);
179 bool ForNode(NodeId id
, std::function
<bool(CNode
* pnode
)> func
);
181 void PushMessage(CNode
* pnode
, CSerializedNetMsg
&& msg
);
183 template<typename Callable
>
184 void ForEachNode(Callable
&& func
)
187 for (auto&& node
: vNodes
) {
188 if (NodeFullyConnected(node
))
193 template<typename Callable
>
194 void ForEachNode(Callable
&& func
) const
197 for (auto&& node
: vNodes
) {
198 if (NodeFullyConnected(node
))
203 template<typename Callable
, typename CallableAfter
>
204 void ForEachNodeThen(Callable
&& pre
, CallableAfter
&& post
)
207 for (auto&& node
: vNodes
) {
208 if (NodeFullyConnected(node
))
214 template<typename Callable
, typename CallableAfter
>
215 void ForEachNodeThen(Callable
&& pre
, CallableAfter
&& post
) const
218 for (auto&& node
: vNodes
) {
219 if (NodeFullyConnected(node
))
226 size_t GetAddressCount() const;
227 void SetServices(const CService
&addr
, ServiceFlags nServices
);
228 void MarkAddressGood(const CAddress
& addr
);
229 void AddNewAddresses(const std::vector
<CAddress
>& vAddr
, const CAddress
& addrFrom
, int64_t nTimePenalty
= 0);
230 std::vector
<CAddress
> GetAddresses();
232 // Denial-of-service detection/prevention
233 // The idea is to detect peers that are behaving
234 // badly and disconnect/ban them, but do it in a
235 // one-coding-mistake-won't-shatter-the-entire-network
237 // IMPORTANT: There should be nothing I can give a
238 // node that it will forward on that will make that
239 // node's peers drop it. If there is, an attacker
240 // can isolate a node and/or try to split the network.
241 // Dropping a node for sending stuff that is invalid
242 // now but might be valid in a later version is also
243 // dangerous, because it can cause a network split
244 // between nodes running old code and nodes running
246 void Ban(const CNetAddr
& netAddr
, const BanReason
& reason
, int64_t bantimeoffset
= 0, bool sinceUnixEpoch
= false);
247 void Ban(const CSubNet
& subNet
, const BanReason
& reason
, int64_t bantimeoffset
= 0, bool sinceUnixEpoch
= false);
248 void ClearBanned(); // needed for unit testing
249 bool IsBanned(CNetAddr ip
);
250 bool IsBanned(CSubNet subnet
);
251 bool Unban(const CNetAddr
&ip
);
252 bool Unban(const CSubNet
&ip
);
253 void GetBanned(banmap_t
&banmap
);
254 void SetBanned(const banmap_t
&banmap
);
256 bool AddNode(const std::string
& node
);
257 bool RemoveAddedNode(const std::string
& node
);
258 std::vector
<AddedNodeInfo
> GetAddedNodeInfo();
260 size_t GetNodeCount(NumConnections num
);
261 void GetNodeStats(std::vector
<CNodeStats
>& vstats
);
262 bool DisconnectNode(const std::string
& node
);
263 bool DisconnectNode(NodeId id
);
265 ServiceFlags
GetLocalServices() const;
267 //!set the max outbound target in bytes
268 void SetMaxOutboundTarget(uint64_t limit
);
269 uint64_t GetMaxOutboundTarget();
271 //!set the timeframe for the max outbound target
272 void SetMaxOutboundTimeframe(uint64_t timeframe
);
273 uint64_t GetMaxOutboundTimeframe();
275 //!check if the outbound target is reached
276 // if param historicalBlockServingLimit is set true, the function will
277 // response true if the limit for serving historical blocks has been reached
278 bool OutboundTargetReached(bool historicalBlockServingLimit
);
280 //!response the bytes left in the current max outbound cycle
281 // in case of no limit, it will always response 0
282 uint64_t GetOutboundTargetBytesLeft();
284 //!response the time in second left in the current max outbound cycle
285 // in case of no limit, it will always response 0
286 uint64_t GetMaxOutboundTimeLeftInCycle();
288 uint64_t GetTotalBytesRecv();
289 uint64_t GetTotalBytesSent();
291 void SetBestHeight(int height
);
292 int GetBestHeight() const;
294 /** Get a unique deterministic randomizer. */
295 CSipHasher
GetDeterministicRandomizer(uint64_t id
) const;
297 unsigned int GetReceiveFloodSize() const;
299 void WakeMessageHandler();
301 struct ListenSocket
{
305 ListenSocket(SOCKET socket_
, bool whitelisted_
) : socket(socket_
), whitelisted(whitelisted_
) {}
308 bool BindListenPort(const CService
&bindAddr
, std::string
& strError
, bool fWhitelisted
= false);
309 bool Bind(const CService
&addr
, unsigned int flags
);
310 bool InitBinds(const std::vector
<CService
>& binds
, const std::vector
<CService
>& whiteBinds
);
311 void ThreadOpenAddedConnections();
312 void AddOneShot(const std::string
& strDest
);
313 void ProcessOneShot();
314 void ThreadOpenConnections(std::vector
<std::string
> connect
);
315 void ThreadMessageHandler();
316 void AcceptConnection(const ListenSocket
& hListenSocket
);
317 void ThreadSocketHandler();
318 void ThreadDNSAddressSeed();
320 uint64_t CalculateKeyedNetGroup(const CAddress
& ad
) const;
322 CNode
* FindNode(const CNetAddr
& ip
);
323 CNode
* FindNode(const CSubNet
& subNet
);
324 CNode
* FindNode(const std::string
& addrName
);
325 CNode
* FindNode(const CService
& addr
);
327 bool AttemptToEvictConnection();
328 CNode
* ConnectNode(CAddress addrConnect
, const char *pszDest
, bool fCountFailure
);
329 bool IsWhitelistedRange(const CNetAddr
&addr
);
331 void DeleteNode(CNode
* pnode
);
333 NodeId
GetNewNodeId();
335 size_t SocketSendData(CNode
*pnode
) const;
336 //!check is the banlist has unwritten changes
337 bool BannedSetIsDirty();
338 //!set the "dirty" flag for the banlist
339 void SetBannedSetDirty(bool dirty
=true);
340 //!clean unused entries (if bantime has expired)
342 void DumpAddresses();
347 void RecordBytesRecv(uint64_t bytes
);
348 void RecordBytesSent(uint64_t bytes
);
350 // Whether the node should be passed out in ForEach* callbacks
351 static bool NodeFullyConnected(const CNode
* pnode
);
353 // Network usage totals
354 CCriticalSection cs_totalBytesRecv
;
355 CCriticalSection cs_totalBytesSent
;
356 uint64_t nTotalBytesRecv
;
357 uint64_t nTotalBytesSent
;
359 // outbound limit & stats
360 uint64_t nMaxOutboundTotalBytesSentInCycle
;
361 uint64_t nMaxOutboundCycleStartTime
;
362 uint64_t nMaxOutboundLimit
;
363 uint64_t nMaxOutboundTimeframe
;
365 // Whitelisted ranges. Any node connecting from these is automatically
366 // whitelisted (as well as those connecting to whitelisted binds).
367 std::vector
<CSubNet
> vWhitelistedRange
;
369 unsigned int nSendBufferMaxSize
;
370 unsigned int nReceiveFloodSize
;
372 std::vector
<ListenSocket
> vhListenSocket
;
373 std::atomic
<bool> fNetworkActive
;
375 CCriticalSection cs_setBanned
;
376 bool setBannedIsDirty
;
377 bool fAddressesInitialized
;
379 std::deque
<std::string
> vOneShots
;
380 CCriticalSection cs_vOneShots
;
381 std::vector
<std::string
> vAddedNodes
;
382 CCriticalSection cs_vAddedNodes
;
383 std::vector
<CNode
*> vNodes
;
384 std::list
<CNode
*> vNodesDisconnected
;
385 mutable CCriticalSection cs_vNodes
;
386 std::atomic
<NodeId
> nLastNodeId
;
388 /** Services this instance offers */
389 ServiceFlags nLocalServices
;
391 /** Services this instance cares about */
392 ServiceFlags nRelevantServices
;
394 CSemaphore
*semOutbound
;
395 CSemaphore
*semAddnode
;
400 std::atomic
<int> nBestHeight
;
401 CClientUIInterface
* clientInterface
;
402 NetEventsInterface
* m_msgproc
;
404 /** SipHasher seeds for deterministic randomness */
405 const uint64_t nSeed0
, nSeed1
;
407 /** flag for waking the message processor. */
410 std::condition_variable condMsgProc
;
411 std::mutex mutexMsgProc
;
412 std::atomic
<bool> flagInterruptMsgProc
;
414 CThreadInterrupt interruptNet
;
416 std::thread threadDNSAddressSeed
;
417 std::thread threadSocketHandler
;
418 std::thread threadOpenAddedConnections
;
419 std::thread threadOpenConnections
;
420 std::thread threadMessageHandler
;
422 extern std::unique_ptr
<CConnman
> g_connman
;
423 void Discover(boost::thread_group
& threadGroup
);
424 void MapPort(bool fUseUPnP
);
425 unsigned short GetListenPort();
426 bool BindListenPort(const CService
&bindAddr
, std::string
& strError
, bool fWhitelisted
= false);
430 typedef bool result_type
;
433 bool operator()(I first
, I last
) const
435 while (first
!= last
) {
436 if (!(*first
)) return false;
444 * Interface for message handling
446 class NetEventsInterface
449 virtual bool ProcessMessages(CNode
* pnode
, std::atomic
<bool>& interrupt
) = 0;
450 virtual bool SendMessages(CNode
* pnode
, std::atomic
<bool>& interrupt
) = 0;
451 virtual void InitializeNode(CNode
* pnode
) = 0;
452 virtual void FinalizeNode(NodeId id
, bool& update_connection_time
) = 0;
457 LOCAL_NONE
, // unknown
458 LOCAL_IF
, // address a local interface listens on
459 LOCAL_BIND
, // address explicit bound to
460 LOCAL_UPNP
, // address reported by UPnP
461 LOCAL_MANUAL
, // address explicitly specified (-externalip=)
466 bool IsPeerAddrLocalGood(CNode
*pnode
);
467 void AdvertiseLocal(CNode
*pnode
);
468 void SetLimited(enum Network net
, bool fLimited
= true);
469 bool IsLimited(enum Network net
);
470 bool IsLimited(const CNetAddr
& addr
);
471 bool AddLocal(const CService
& addr
, int nScore
= LOCAL_NONE
);
472 bool AddLocal(const CNetAddr
& addr
, int nScore
= LOCAL_NONE
);
473 bool RemoveLocal(const CService
& addr
);
474 bool SeenLocal(const CService
& addr
);
475 bool IsLocal(const CService
& addr
);
476 bool GetLocal(CService
&addr
, const CNetAddr
*paddrPeer
= nullptr);
477 bool IsReachable(enum Network net
);
478 bool IsReachable(const CNetAddr
&addr
);
479 CAddress
GetLocalAddress(const CNetAddr
*paddrPeer
, ServiceFlags nLocalServices
);
482 extern bool fDiscover
;
484 extern bool fRelayTxes
;
486 extern limitedmap
<uint256
, int64_t> mapAlreadyAskedFor
;
488 /** Subversion as sent to the P2P network in `version` messages */
489 extern std::string strSubVersion
;
491 struct LocalServiceInfo
{
496 extern CCriticalSection cs_mapLocalHost
;
497 extern std::map
<CNetAddr
, LocalServiceInfo
> mapLocalHost
;
498 typedef std::map
<std::string
, uint64_t> mapMsgCmdSize
; //command, total bytes
504 ServiceFlags nServices
;
508 int64_t nTimeConnected
;
510 std::string addrName
;
512 std::string cleanSubVer
;
517 mapMsgCmdSize mapSendBytesPerMsgCmd
;
519 mapMsgCmdSize mapRecvBytesPerMsgCmd
;
524 // Our address, as reported by the peer
525 std::string addrLocal
;
526 // Address of this peer
528 // Bind address of our side of the connection
537 mutable CHash256 hasher
;
538 mutable uint256 data_hash
;
540 bool in_data
; // parsing header (false) or data (true)
542 CDataStream hdrbuf
; // partially received header
543 CMessageHeader hdr
; // complete header
544 unsigned int nHdrPos
;
546 CDataStream vRecv
; // received message data
547 unsigned int nDataPos
;
549 int64_t nTime
; // time (in microseconds) of message receipt.
551 CNetMessage(const CMessageHeader::MessageStartChars
& pchMessageStartIn
, int nTypeIn
, int nVersionIn
) : hdrbuf(nTypeIn
, nVersionIn
), hdr(pchMessageStartIn
), vRecv(nTypeIn
, nVersionIn
) {
559 bool complete() const
563 return (hdr
.nMessageSize
== nDataPos
);
566 const uint256
& GetMessageHash() const;
568 void SetVersion(int nVersionIn
)
570 hdrbuf
.SetVersion(nVersionIn
);
571 vRecv
.SetVersion(nVersionIn
);
574 int readHeader(const char *pch
, unsigned int nBytes
);
575 int readData(const char *pch
, unsigned int nBytes
);
579 /** Information about a peer */
582 friend class CConnman
;
585 std::atomic
<ServiceFlags
> nServices
;
586 ServiceFlags nServicesExpected
;
588 size_t nSendSize
; // total size of all vSendMsg entries
589 size_t nSendOffset
; // offset inside the first vSendMsg already sent
591 std::deque
<std::vector
<unsigned char>> vSendMsg
;
592 CCriticalSection cs_vSend
;
593 CCriticalSection cs_hSocket
;
594 CCriticalSection cs_vRecv
;
596 CCriticalSection cs_vProcessMsg
;
597 std::list
<CNetMessage
> vProcessMsg
;
598 size_t nProcessQueueSize
;
600 CCriticalSection cs_sendProcessing
;
602 std::deque
<CInv
> vRecvGetData
;
604 std::atomic
<int> nRecvVersion
;
606 std::atomic
<int64_t> nLastSend
;
607 std::atomic
<int64_t> nLastRecv
;
608 const int64_t nTimeConnected
;
609 std::atomic
<int64_t> nTimeOffset
;
610 // Address of this peer
612 // Bind address of our side of the connection
613 const CAddress addrBind
;
614 std::atomic
<int> nVersion
;
615 // strSubVer is whatever byte array we read from the wire. However, this field is intended
616 // to be printed out, displayed to humans in various forms and so on. So we sanitize it and
617 // store the sanitized version in cleanSubVer. The original should be used when dealing with
618 // the network or wire types and the cleaned string used when displayed or logged.
619 std::string strSubVer
, cleanSubVer
;
620 CCriticalSection cs_SubVer
; // used for both cleanSubVer and strSubVer
621 bool fWhitelisted
; // This peer can bypass DoS banning.
622 bool fFeeler
; // If true this node is being used as a short lived feeler.
627 std::atomic_bool fSuccessfullyConnected
;
628 std::atomic_bool fDisconnect
;
629 // We use fRelayTxes for two purposes -
630 // a) it allows us to not relay tx invs before receiving the peer's version message
631 // b) the peer may tell us in its version message that we should not relay tx invs
632 // unless it loads a bloom filter.
633 bool fRelayTxes
; //protected by cs_filter
635 CSemaphoreGrant grantOutbound
;
636 CCriticalSection cs_filter
;
637 CBloomFilter
* pfilter
;
638 std::atomic
<int> nRefCount
;
640 const uint64_t nKeyedNetGroup
;
641 std::atomic_bool fPauseRecv
;
642 std::atomic_bool fPauseSend
;
645 mapMsgCmdSize mapSendBytesPerMsgCmd
;
646 mapMsgCmdSize mapRecvBytesPerMsgCmd
;
649 uint256 hashContinue
;
650 std::atomic
<int> nStartingHeight
;
653 std::vector
<CAddress
> vAddrToSend
;
654 CRollingBloomFilter addrKnown
;
656 std::set
<uint256
> setKnown
;
657 int64_t nNextAddrSend
;
658 int64_t nNextLocalAddrSend
;
660 // inventory based relay
661 CRollingBloomFilter filterInventoryKnown
;
662 // Set of transaction ids we still have to announce.
663 // They are sorted by the mempool before relay, so the order is not important.
664 std::set
<uint256
> setInventoryTxToSend
;
665 // List of block ids we still have announce.
666 // There is no final sorting before sending, as they are always sent immediately
667 // and in the order requested.
668 std::vector
<uint256
> vInventoryBlockToSend
;
669 CCriticalSection cs_inventory
;
670 std::set
<uint256
> setAskFor
;
671 std::multimap
<int64_t, CInv
> mapAskFor
;
672 int64_t nNextInvSend
;
673 // Used for headers announcements - unfiltered blocks to relay
674 // Also protected by cs_inventory
675 std::vector
<uint256
> vBlockHashesToAnnounce
;
676 // Used for BIP35 mempool sending, also protected by cs_inventory
679 // Last time a "MEMPOOL" request was serviced.
680 std::atomic
<int64_t> timeLastMempoolReq
;
682 // Block and TXN accept times
683 std::atomic
<int64_t> nLastBlockTime
;
684 std::atomic
<int64_t> nLastTXTime
;
686 // Ping time measurement:
687 // The pong reply we're expecting, or 0 if no pong expected.
688 std::atomic
<uint64_t> nPingNonceSent
;
689 // Time (in usec) the last ping was sent, or 0 if no ping was ever sent.
690 std::atomic
<int64_t> nPingUsecStart
;
691 // Last measured round-trip time.
692 std::atomic
<int64_t> nPingUsecTime
;
693 // Best measured round-trip time.
694 std::atomic
<int64_t> nMinPingUsecTime
;
695 // Whether a ping is requested.
696 std::atomic
<bool> fPingQueued
;
697 // Minimum fee rate with which to filter inv's to this node
698 CAmount minFeeFilter
;
699 CCriticalSection cs_feeFilter
;
700 CAmount lastSentFeeFilter
;
701 int64_t nextSendTimeFeeFilter
;
703 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);
708 void operator=(const CNode
&);
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