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/filesystem/path.hpp>
36 #include <boost/foreach.hpp>
37 #include <boost/signals2/signal.hpp>
47 /** Time between pings automatically sent out for latency probing and keepalive (in seconds). */
48 static const int PING_INTERVAL
= 2 * 60;
49 /** Time after which to disconnect, after waiting for a ping response (or inactivity). */
50 static const int TIMEOUT_INTERVAL
= 20 * 60;
51 /** Run the feeler connection loop once every 2 minutes or 120 seconds. **/
52 static const int FEELER_INTERVAL
= 120;
53 /** The maximum number of entries in an 'inv' protocol message */
54 static const unsigned int MAX_INV_SZ
= 50000;
55 /** The maximum number of new addresses to accumulate before announcing. */
56 static const unsigned int MAX_ADDR_TO_SEND
= 1000;
57 /** Maximum length of incoming protocol messages (no message over 4 MB is currently acceptable). */
58 static const unsigned int MAX_PROTOCOL_MESSAGE_LENGTH
= 4 * 1000 * 1000;
59 /** Maximum length of strSubVer in `version` message */
60 static const unsigned int MAX_SUBVERSION_LENGTH
= 256;
61 /** Maximum number of automatic outgoing nodes */
62 static const int MAX_OUTBOUND_CONNECTIONS
= 8;
63 /** Maximum number of addnode outgoing nodes */
64 static const int MAX_ADDNODE_CONNECTIONS
= 8;
65 /** -listen default */
66 static const bool DEFAULT_LISTEN
= true;
69 static const bool DEFAULT_UPNP
= USE_UPNP
;
71 static const bool DEFAULT_UPNP
= false;
73 /** The maximum number of entries in mapAskFor */
74 static const size_t MAPASKFOR_MAX_SZ
= MAX_INV_SZ
;
75 /** The maximum number of entries in setAskFor (larger due to getdata latency)*/
76 static const size_t SETASKFOR_MAX_SZ
= 2 * MAX_INV_SZ
;
77 /** The maximum number of peer connections to maintain. */
78 static const unsigned int DEFAULT_MAX_PEER_CONNECTIONS
= 125;
79 /** The default for -maxuploadtarget. 0 = Unlimited */
80 static const uint64_t DEFAULT_MAX_UPLOAD_TARGET
= 0;
81 /** The default timeframe for -maxuploadtarget. 1 day. */
82 static const uint64_t MAX_UPLOAD_TIMEFRAME
= 60 * 60 * 24;
83 /** Default for blocks only*/
84 static const bool DEFAULT_BLOCKSONLY
= false;
86 static const bool DEFAULT_FORCEDNSSEED
= false;
87 static const size_t DEFAULT_MAXRECEIVEBUFFER
= 5 * 1000;
88 static const size_t DEFAULT_MAXSENDBUFFER
= 1 * 1000;
90 static const ServiceFlags REQUIRED_SERVICES
= NODE_NETWORK
;
92 // NOTE: When adjusting this, update rpcnet:setban's help ("24h")
93 static const unsigned int DEFAULT_MISBEHAVING_BANTIME
= 60 * 60 * 24; // Default 24-hour ban
99 std::string strAddedNode
;
100 CService resolvedAddress
;
107 class CClientUIInterface
;
109 struct CSerializedNetMsg
111 CSerializedNetMsg() = default;
112 CSerializedNetMsg(CSerializedNetMsg
&&) = default;
113 CSerializedNetMsg
& operator=(CSerializedNetMsg
&&) = default;
114 // No copying, only moves.
115 CSerializedNetMsg(const CSerializedNetMsg
& msg
) = delete;
116 CSerializedNetMsg
& operator=(const CSerializedNetMsg
&) = delete;
118 std::vector
<unsigned char> data
;
127 enum NumConnections
{
128 CONNECTIONS_NONE
= 0,
129 CONNECTIONS_IN
= (1U << 0),
130 CONNECTIONS_OUT
= (1U << 1),
131 CONNECTIONS_ALL
= (CONNECTIONS_IN
| CONNECTIONS_OUT
),
136 ServiceFlags nLocalServices
= NODE_NONE
;
137 ServiceFlags nRelevantServices
= NODE_NONE
;
138 int nMaxConnections
= 0;
139 int nMaxOutbound
= 0;
143 CClientUIInterface
* uiInterface
= nullptr;
144 unsigned int nSendBufferMaxSize
= 0;
145 unsigned int nReceiveFloodSize
= 0;
146 uint64_t nMaxOutboundTimeframe
= 0;
147 uint64_t nMaxOutboundLimit
= 0;
149 CConnman(uint64_t seed0
, uint64_t seed1
);
151 bool Start(CScheduler
& scheduler
, std::string
& strNodeError
, Options options
);
154 bool BindListenPort(const CService
&bindAddr
, std::string
& strError
, bool fWhitelisted
= false);
155 bool GetNetworkActive() const { return fNetworkActive
; };
156 void SetNetworkActive(bool active
);
157 bool OpenNetworkConnection(const CAddress
& addrConnect
, bool fCountFailure
, CSemaphoreGrant
*grantOutbound
= NULL
, const char *strDest
= NULL
, bool fOneShot
= false, bool fFeeler
= false, bool fAddnode
= false);
158 bool CheckIncomingNonce(uint64_t nonce
);
160 bool ForNode(NodeId id
, std::function
<bool(CNode
* pnode
)> func
);
162 void PushMessage(CNode
* pnode
, CSerializedNetMsg
&& msg
);
164 template<typename Callable
>
165 void ForEachNode(Callable
&& func
)
168 for (auto&& node
: vNodes
) {
169 if (NodeFullyConnected(node
))
174 template<typename Callable
>
175 void ForEachNode(Callable
&& func
) const
178 for (auto&& node
: vNodes
) {
179 if (NodeFullyConnected(node
))
184 template<typename Callable
, typename CallableAfter
>
185 void ForEachNodeThen(Callable
&& pre
, CallableAfter
&& post
)
188 for (auto&& node
: vNodes
) {
189 if (NodeFullyConnected(node
))
195 template<typename Callable
, typename CallableAfter
>
196 void ForEachNodeThen(Callable
&& pre
, CallableAfter
&& post
) const
199 for (auto&& node
: vNodes
) {
200 if (NodeFullyConnected(node
))
207 size_t GetAddressCount() const;
208 void SetServices(const CService
&addr
, ServiceFlags nServices
);
209 void MarkAddressGood(const CAddress
& addr
);
210 void AddNewAddresses(const std::vector
<CAddress
>& vAddr
, const CAddress
& addrFrom
, int64_t nTimePenalty
= 0);
211 std::vector
<CAddress
> GetAddresses();
213 // Denial-of-service detection/prevention
214 // The idea is to detect peers that are behaving
215 // badly and disconnect/ban them, but do it in a
216 // one-coding-mistake-won't-shatter-the-entire-network
218 // IMPORTANT: There should be nothing I can give a
219 // node that it will forward on that will make that
220 // node's peers drop it. If there is, an attacker
221 // can isolate a node and/or try to split the network.
222 // Dropping a node for sending stuff that is invalid
223 // now but might be valid in a later version is also
224 // dangerous, because it can cause a network split
225 // between nodes running old code and nodes running
227 void Ban(const CNetAddr
& netAddr
, const BanReason
& reason
, int64_t bantimeoffset
= 0, bool sinceUnixEpoch
= false);
228 void Ban(const CSubNet
& subNet
, const BanReason
& reason
, int64_t bantimeoffset
= 0, bool sinceUnixEpoch
= false);
229 void ClearBanned(); // needed for unit testing
230 bool IsBanned(CNetAddr ip
);
231 bool IsBanned(CSubNet subnet
);
232 bool Unban(const CNetAddr
&ip
);
233 bool Unban(const CSubNet
&ip
);
234 void GetBanned(banmap_t
&banmap
);
235 void SetBanned(const banmap_t
&banmap
);
237 void AddOneShot(const std::string
& strDest
);
239 bool AddNode(const std::string
& node
);
240 bool RemoveAddedNode(const std::string
& node
);
241 std::vector
<AddedNodeInfo
> GetAddedNodeInfo();
243 size_t GetNodeCount(NumConnections num
);
244 void GetNodeStats(std::vector
<CNodeStats
>& vstats
);
245 bool DisconnectNode(const std::string
& node
);
246 bool DisconnectNode(NodeId id
);
248 unsigned int GetSendBufferSize() const;
250 void AddWhitelistedRange(const CSubNet
&subnet
);
252 ServiceFlags
GetLocalServices() const;
254 //!set the max outbound target in bytes
255 void SetMaxOutboundTarget(uint64_t limit
);
256 uint64_t GetMaxOutboundTarget();
258 //!set the timeframe for the max outbound target
259 void SetMaxOutboundTimeframe(uint64_t timeframe
);
260 uint64_t GetMaxOutboundTimeframe();
262 //!check if the outbound target is reached
263 // if param historicalBlockServingLimit is set true, the function will
264 // response true if the limit for serving historical blocks has been reached
265 bool OutboundTargetReached(bool historicalBlockServingLimit
);
267 //!response the bytes left in the current max outbound cycle
268 // in case of no limit, it will always response 0
269 uint64_t GetOutboundTargetBytesLeft();
271 //!response the time in second left in the current max outbound cycle
272 // in case of no limit, it will always response 0
273 uint64_t GetMaxOutboundTimeLeftInCycle();
275 uint64_t GetTotalBytesRecv();
276 uint64_t GetTotalBytesSent();
278 void SetBestHeight(int height
);
279 int GetBestHeight() const;
281 /** Get a unique deterministic randomizer. */
282 CSipHasher
GetDeterministicRandomizer(uint64_t id
) const;
284 unsigned int GetReceiveFloodSize() const;
286 void WakeMessageHandler();
288 struct ListenSocket
{
292 ListenSocket(SOCKET socket_
, bool whitelisted_
) : socket(socket_
), whitelisted(whitelisted_
) {}
295 void ThreadOpenAddedConnections();
296 void ProcessOneShot();
297 void ThreadOpenConnections();
298 void ThreadMessageHandler();
299 void AcceptConnection(const ListenSocket
& hListenSocket
);
300 void ThreadSocketHandler();
301 void ThreadDNSAddressSeed();
303 uint64_t CalculateKeyedNetGroup(const CAddress
& ad
) const;
305 CNode
* FindNode(const CNetAddr
& ip
);
306 CNode
* FindNode(const CSubNet
& subNet
);
307 CNode
* FindNode(const std::string
& addrName
);
308 CNode
* FindNode(const CService
& addr
);
310 bool AttemptToEvictConnection();
311 CNode
* ConnectNode(CAddress addrConnect
, const char *pszDest
, bool fCountFailure
);
312 bool IsWhitelistedRange(const CNetAddr
&addr
);
314 void DeleteNode(CNode
* pnode
);
316 NodeId
GetNewNodeId();
318 size_t SocketSendData(CNode
*pnode
) const;
319 //!check is the banlist has unwritten changes
320 bool BannedSetIsDirty();
321 //!set the "dirty" flag for the banlist
322 void SetBannedSetDirty(bool dirty
=true);
323 //!clean unused entries (if bantime has expired)
325 void DumpAddresses();
330 void RecordBytesRecv(uint64_t bytes
);
331 void RecordBytesSent(uint64_t bytes
);
333 // Whether the node should be passed out in ForEach* callbacks
334 static bool NodeFullyConnected(const CNode
* pnode
);
336 // Network usage totals
337 CCriticalSection cs_totalBytesRecv
;
338 CCriticalSection cs_totalBytesSent
;
339 uint64_t nTotalBytesRecv
;
340 uint64_t nTotalBytesSent
;
342 // outbound limit & stats
343 uint64_t nMaxOutboundTotalBytesSentInCycle
;
344 uint64_t nMaxOutboundCycleStartTime
;
345 uint64_t nMaxOutboundLimit
;
346 uint64_t nMaxOutboundTimeframe
;
348 // Whitelisted ranges. Any node connecting from these is automatically
349 // whitelisted (as well as those connecting to whitelisted binds).
350 std::vector
<CSubNet
> vWhitelistedRange
;
351 CCriticalSection cs_vWhitelistedRange
;
353 unsigned int nSendBufferMaxSize
;
354 unsigned int nReceiveFloodSize
;
356 std::vector
<ListenSocket
> vhListenSocket
;
357 std::atomic
<bool> fNetworkActive
;
359 CCriticalSection cs_setBanned
;
360 bool setBannedIsDirty
;
361 bool fAddressesInitialized
;
363 std::deque
<std::string
> vOneShots
;
364 CCriticalSection cs_vOneShots
;
365 std::vector
<std::string
> vAddedNodes
;
366 CCriticalSection cs_vAddedNodes
;
367 std::vector
<CNode
*> vNodes
;
368 std::list
<CNode
*> vNodesDisconnected
;
369 mutable CCriticalSection cs_vNodes
;
370 std::atomic
<NodeId
> nLastNodeId
;
372 /** Services this instance offers */
373 ServiceFlags nLocalServices
;
375 /** Services this instance cares about */
376 ServiceFlags nRelevantServices
;
378 CSemaphore
*semOutbound
;
379 CSemaphore
*semAddnode
;
384 std::atomic
<int> nBestHeight
;
385 CClientUIInterface
* clientInterface
;
387 /** SipHasher seeds for deterministic randomness */
388 const uint64_t nSeed0
, nSeed1
;
390 /** flag for waking the message processor. */
393 std::condition_variable condMsgProc
;
394 std::mutex mutexMsgProc
;
395 std::atomic
<bool> flagInterruptMsgProc
;
397 CThreadInterrupt interruptNet
;
399 std::thread threadDNSAddressSeed
;
400 std::thread threadSocketHandler
;
401 std::thread threadOpenAddedConnections
;
402 std::thread threadOpenConnections
;
403 std::thread threadMessageHandler
;
405 extern std::unique_ptr
<CConnman
> g_connman
;
406 void Discover(boost::thread_group
& threadGroup
);
407 void MapPort(bool fUseUPnP
);
408 unsigned short GetListenPort();
409 bool BindListenPort(const CService
&bindAddr
, std::string
& strError
, bool fWhitelisted
= false);
413 typedef bool result_type
;
416 bool operator()(I first
, I last
) const
418 while (first
!= last
) {
419 if (!(*first
)) return false;
426 // Signals for message handling
429 boost::signals2::signal
<bool (CNode
*, CConnman
&, std::atomic
<bool>&), CombinerAll
> ProcessMessages
;
430 boost::signals2::signal
<bool (CNode
*, CConnman
&, std::atomic
<bool>&), CombinerAll
> SendMessages
;
431 boost::signals2::signal
<void (CNode
*, CConnman
&)> InitializeNode
;
432 boost::signals2::signal
<void (NodeId
, bool&)> FinalizeNode
;
436 CNodeSignals
& GetNodeSignals();
441 LOCAL_NONE
, // unknown
442 LOCAL_IF
, // address a local interface listens on
443 LOCAL_BIND
, // address explicit bound to
444 LOCAL_UPNP
, // address reported by UPnP
445 LOCAL_MANUAL
, // address explicitly specified (-externalip=)
450 bool IsPeerAddrLocalGood(CNode
*pnode
);
451 void AdvertiseLocal(CNode
*pnode
);
452 void SetLimited(enum Network net
, bool fLimited
= true);
453 bool IsLimited(enum Network net
);
454 bool IsLimited(const CNetAddr
& addr
);
455 bool AddLocal(const CService
& addr
, int nScore
= LOCAL_NONE
);
456 bool AddLocal(const CNetAddr
& addr
, int nScore
= LOCAL_NONE
);
457 bool RemoveLocal(const CService
& addr
);
458 bool SeenLocal(const CService
& addr
);
459 bool IsLocal(const CService
& addr
);
460 bool GetLocal(CService
&addr
, const CNetAddr
*paddrPeer
= NULL
);
461 bool IsReachable(enum Network net
);
462 bool IsReachable(const CNetAddr
&addr
);
463 CAddress
GetLocalAddress(const CNetAddr
*paddrPeer
, ServiceFlags nLocalServices
);
466 extern bool fDiscover
;
468 extern bool fRelayTxes
;
470 extern limitedmap
<uint256
, int64_t> mapAlreadyAskedFor
;
472 /** Subversion as sent to the P2P network in `version` messages */
473 extern std::string strSubVersion
;
475 struct LocalServiceInfo
{
480 extern CCriticalSection cs_mapLocalHost
;
481 extern std::map
<CNetAddr
, LocalServiceInfo
> mapLocalHost
;
482 typedef std::map
<std::string
, uint64_t> mapMsgCmdSize
; //command, total bytes
488 ServiceFlags nServices
;
492 int64_t nTimeConnected
;
494 std::string addrName
;
496 std::string cleanSubVer
;
501 mapMsgCmdSize mapSendBytesPerMsgCmd
;
503 mapMsgCmdSize mapRecvBytesPerMsgCmd
;
508 std::string addrLocal
;
517 mutable CHash256 hasher
;
518 mutable uint256 data_hash
;
520 bool in_data
; // parsing header (false) or data (true)
522 CDataStream hdrbuf
; // partially received header
523 CMessageHeader hdr
; // complete header
524 unsigned int nHdrPos
;
526 CDataStream vRecv
; // received message data
527 unsigned int nDataPos
;
529 int64_t nTime
; // time (in microseconds) of message receipt.
531 CNetMessage(const CMessageHeader::MessageStartChars
& pchMessageStartIn
, int nTypeIn
, int nVersionIn
) : hdrbuf(nTypeIn
, nVersionIn
), hdr(pchMessageStartIn
), vRecv(nTypeIn
, nVersionIn
) {
539 bool complete() const
543 return (hdr
.nMessageSize
== nDataPos
);
546 const uint256
& GetMessageHash() const;
548 void SetVersion(int nVersionIn
)
550 hdrbuf
.SetVersion(nVersionIn
);
551 vRecv
.SetVersion(nVersionIn
);
554 int readHeader(const char *pch
, unsigned int nBytes
);
555 int readData(const char *pch
, unsigned int nBytes
);
559 /** Information about a peer */
562 friend class CConnman
;
565 std::atomic
<ServiceFlags
> nServices
;
566 ServiceFlags nServicesExpected
;
568 size_t nSendSize
; // total size of all vSendMsg entries
569 size_t nSendOffset
; // offset inside the first vSendMsg already sent
571 std::deque
<std::vector
<unsigned char>> vSendMsg
;
572 CCriticalSection cs_vSend
;
573 CCriticalSection cs_hSocket
;
574 CCriticalSection cs_vRecv
;
576 CCriticalSection cs_vProcessMsg
;
577 std::list
<CNetMessage
> vProcessMsg
;
578 size_t nProcessQueueSize
;
580 CCriticalSection cs_sendProcessing
;
582 std::deque
<CInv
> vRecvGetData
;
584 std::atomic
<int> nRecvVersion
;
586 std::atomic
<int64_t> nLastSend
;
587 std::atomic
<int64_t> nLastRecv
;
588 const int64_t nTimeConnected
;
589 std::atomic
<int64_t> nTimeOffset
;
591 std::atomic
<int> nVersion
;
592 // strSubVer is whatever byte array we read from the wire. However, this field is intended
593 // to be printed out, displayed to humans in various forms and so on. So we sanitize it and
594 // store the sanitized version in cleanSubVer. The original should be used when dealing with
595 // the network or wire types and the cleaned string used when displayed or logged.
596 std::string strSubVer
, cleanSubVer
;
597 CCriticalSection cs_SubVer
; // used for both cleanSubVer and strSubVer
598 bool fWhitelisted
; // This peer can bypass DoS banning.
599 bool fFeeler
; // If true this node is being used as a short lived feeler.
604 std::atomic_bool fSuccessfullyConnected
;
605 std::atomic_bool fDisconnect
;
606 // We use fRelayTxes for two purposes -
607 // a) it allows us to not relay tx invs before receiving the peer's version message
608 // b) the peer may tell us in its version message that we should not relay tx invs
609 // unless it loads a bloom filter.
610 bool fRelayTxes
; //protected by cs_filter
612 CSemaphoreGrant grantOutbound
;
613 CCriticalSection cs_filter
;
614 CBloomFilter
* pfilter
;
615 std::atomic
<int> nRefCount
;
618 const uint64_t nKeyedNetGroup
;
619 std::atomic_bool fPauseRecv
;
620 std::atomic_bool fPauseSend
;
623 mapMsgCmdSize mapSendBytesPerMsgCmd
;
624 mapMsgCmdSize mapRecvBytesPerMsgCmd
;
627 uint256 hashContinue
;
628 std::atomic
<int> nStartingHeight
;
631 std::vector
<CAddress
> vAddrToSend
;
632 CRollingBloomFilter addrKnown
;
634 std::set
<uint256
> setKnown
;
635 int64_t nNextAddrSend
;
636 int64_t nNextLocalAddrSend
;
638 // inventory based relay
639 CRollingBloomFilter filterInventoryKnown
;
640 // Set of transaction ids we still have to announce.
641 // They are sorted by the mempool before relay, so the order is not important.
642 std::set
<uint256
> setInventoryTxToSend
;
643 // List of block ids we still have announce.
644 // There is no final sorting before sending, as they are always sent immediately
645 // and in the order requested.
646 std::vector
<uint256
> vInventoryBlockToSend
;
647 CCriticalSection cs_inventory
;
648 std::set
<uint256
> setAskFor
;
649 std::multimap
<int64_t, CInv
> mapAskFor
;
650 int64_t nNextInvSend
;
651 // Used for headers announcements - unfiltered blocks to relay
652 // Also protected by cs_inventory
653 std::vector
<uint256
> vBlockHashesToAnnounce
;
654 // Used for BIP35 mempool sending, also protected by cs_inventory
657 // Last time a "MEMPOOL" request was serviced.
658 std::atomic
<int64_t> timeLastMempoolReq
;
660 // Block and TXN accept times
661 std::atomic
<int64_t> nLastBlockTime
;
662 std::atomic
<int64_t> nLastTXTime
;
664 // Ping time measurement:
665 // The pong reply we're expecting, or 0 if no pong expected.
666 std::atomic
<uint64_t> nPingNonceSent
;
667 // Time (in usec) the last ping was sent, or 0 if no ping was ever sent.
668 std::atomic
<int64_t> nPingUsecStart
;
669 // Last measured round-trip time.
670 std::atomic
<int64_t> nPingUsecTime
;
671 // Best measured round-trip time.
672 std::atomic
<int64_t> nMinPingUsecTime
;
673 // Whether a ping is requested.
674 std::atomic
<bool> fPingQueued
;
675 // Minimum fee rate with which to filter inv's to this node
676 CAmount minFeeFilter
;
677 CCriticalSection cs_feeFilter
;
678 CAmount lastSentFeeFilter
;
679 int64_t nextSendTimeFeeFilter
;
681 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);
686 void operator=(const CNode
&);
689 const uint64_t nLocalHostNonce
;
690 // Services offered to this peer
691 const ServiceFlags nLocalServices
;
692 const int nMyStartingHeight
;
694 std::list
<CNetMessage
> vRecvMsg
; // Used only by SocketHandler thread
696 mutable CCriticalSection cs_addrName
;
697 std::string addrName
;
700 mutable CCriticalSection cs_addrLocal
;
703 NodeId
GetId() const {
707 uint64_t GetLocalNonce() const {
708 return nLocalHostNonce
;
711 int GetMyStartingHeight() const {
712 return nMyStartingHeight
;
717 assert(nRefCount
>= 0);
721 bool ReceiveMsgBytes(const char *pch
, unsigned int nBytes
, bool& complete
);
723 void SetRecvVersion(int nVersionIn
)
725 nRecvVersion
= nVersionIn
;
731 void SetSendVersion(int nVersionIn
);
732 int GetSendVersion() const;
734 CService
GetAddrLocal() const;
735 //! May not be called more than once
736 void SetAddrLocal(const CService
& addrLocalIn
);
751 void AddAddressKnown(const CAddress
& _addr
)
753 addrKnown
.insert(_addr
.GetKey());
756 void PushAddress(const CAddress
& _addr
, FastRandomContext
&insecure_rand
)
758 // Known checking here is only to save space from duplicates.
759 // SendMessages will filter it again for knowns that were added
760 // after addresses were pushed.
761 if (_addr
.IsValid() && !addrKnown
.contains(_addr
.GetKey())) {
762 if (vAddrToSend
.size() >= MAX_ADDR_TO_SEND
) {
763 vAddrToSend
[insecure_rand
.rand32() % vAddrToSend
.size()] = _addr
;
765 vAddrToSend
.push_back(_addr
);
771 void AddInventoryKnown(const CInv
& inv
)
775 filterInventoryKnown
.insert(inv
.hash
);
779 void PushInventory(const CInv
& inv
)
782 if (inv
.type
== MSG_TX
) {
783 if (!filterInventoryKnown
.contains(inv
.hash
)) {
784 setInventoryTxToSend
.insert(inv
.hash
);
786 } else if (inv
.type
== MSG_BLOCK
) {
787 vInventoryBlockToSend
.push_back(inv
.hash
);
791 void PushBlockHash(const uint256
&hash
)
794 vBlockHashesToAnnounce
.push_back(hash
);
797 void AskFor(const CInv
& inv
);
799 void CloseSocketDisconnect();
801 void copyStats(CNodeStats
&stats
);
803 ServiceFlags
GetLocalServices() const
805 return nLocalServices
;
808 std::string
GetAddrName() const;
809 //! Sets the addrName only if it was not previously set
810 void MaybeSetAddrName(const std::string
& addrNameIn
);
817 /** Return a timestamp in the future (in microseconds) for exponentially distributed events. */
818 int64_t PoissonNextSend(int64_t nNow
, int average_interval_seconds
);
820 #endif // BITCOIN_NET_H