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"
22 #include "threadinterrupt.h"
29 #include <condition_variable>
32 #include <arpa/inet.h>
35 #include <boost/foreach.hpp>
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
;
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
;
125 enum NumConnections
{
126 CONNECTIONS_NONE
= 0,
127 CONNECTIONS_IN
= (1U << 0),
128 CONNECTIONS_OUT
= (1U << 1),
129 CONNECTIONS_ALL
= (CONNECTIONS_IN
| CONNECTIONS_OUT
),
134 ServiceFlags nLocalServices
= NODE_NONE
;
135 ServiceFlags nRelevantServices
= NODE_NONE
;
136 int nMaxConnections
= 0;
137 int nMaxOutbound
= 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
);
149 bool Start(CScheduler
& scheduler
, std::string
& strNodeError
, Options options
);
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
)
166 for (auto&& node
: vNodes
) {
167 if (NodeFullyConnected(node
))
172 template<typename Callable
>
173 void ForEachNode(Callable
&& func
) const
176 for (auto&& node
: vNodes
) {
177 if (NodeFullyConnected(node
))
182 template<typename Callable
, typename CallableAfter
>
183 void ForEachNodeThen(Callable
&& pre
, CallableAfter
&& post
)
186 for (auto&& node
: vNodes
) {
187 if (NodeFullyConnected(node
))
193 template<typename Callable
, typename CallableAfter
>
194 void ForEachNodeThen(Callable
&& pre
, CallableAfter
&& post
) const
197 for (auto&& node
: vNodes
) {
198 if (NodeFullyConnected(node
))
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
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
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();
286 struct ListenSocket
{
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)
323 void DumpAddresses();
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
;
357 CCriticalSection cs_setBanned
;
358 bool setBannedIsDirty
;
359 bool fAddressesInitialized
;
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
;
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. */
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);
411 typedef bool result_type
;
414 bool operator()(I first
, I last
) const
416 while (first
!= last
) {
417 if (!(*first
)) return false;
424 // Signals for message handling
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();
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=)
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
;
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
{
478 extern CCriticalSection cs_mapLocalHost
;
479 extern std::map
<CNetAddr
, LocalServiceInfo
> mapLocalHost
;
480 typedef std::map
<std::string
, uint64_t> mapMsgCmdSize
; //command, total bytes
486 ServiceFlags nServices
;
490 int64_t nTimeConnected
;
492 std::string addrName
;
494 std::string cleanSubVer
;
499 mapMsgCmdSize mapSendBytesPerMsgCmd
;
501 mapMsgCmdSize mapRecvBytesPerMsgCmd
;
506 std::string addrLocal
;
515 mutable CHash256 hasher
;
516 mutable uint256 data_hash
;
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
) {
537 bool complete() const
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 */
560 friend class CConnman
;
563 std::atomic
<ServiceFlags
> nServices
;
564 ServiceFlags nServicesExpected
;
566 size_t nSendSize
; // total size of all vSendMsg entries
567 size_t nSendOffset
; // offset inside the first vSendMsg already sent
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
;
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
;
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.
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
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
;
620 mapMsgCmdSize mapSendBytesPerMsgCmd
;
621 mapMsgCmdSize mapRecvBytesPerMsgCmd
;
624 uint256 hashContinue
;
625 std::atomic
<int> nStartingHeight
;
628 std::vector
<CAddress
> vAddrToSend
;
629 CRollingBloomFilter addrKnown
;
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
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);
683 void operator=(const CNode
&);
687 const uint64_t nLocalHostNonce
;
688 // Services offered to this peer
689 const ServiceFlags nLocalServices
;
690 const int nMyStartingHeight
;
692 std::list
<CNetMessage
> vRecvMsg
; // Used only by SocketHandler thread
694 mutable CCriticalSection cs_addrName
;
695 std::string addrName
;
698 mutable CCriticalSection cs_addrLocal
;
701 NodeId
GetId() const {
705 uint64_t GetLocalNonce() const {
706 return nLocalHostNonce
;
709 int GetMyStartingHeight() const {
710 return nMyStartingHeight
;
715 assert(nRefCount
>= 0);
719 bool ReceiveMsgBytes(const char *pch
, unsigned int nBytes
, bool& complete
);
721 void SetRecvVersion(int nVersionIn
)
723 nRecvVersion
= nVersionIn
;
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
);
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
;
763 vAddrToSend
.push_back(_addr
);
769 void AddInventoryKnown(const CInv
& inv
)
773 filterInventoryKnown
.insert(inv
.hash
);
777 void PushInventory(const CInv
& inv
)
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
)
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