1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2015 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 outgoing nodes */
62 static const int MAX_OUTBOUND_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
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;
140 CClientUIInterface
* uiInterface
= nullptr;
141 unsigned int nSendBufferMaxSize
= 0;
142 unsigned int nReceiveFloodSize
= 0;
143 uint64_t nMaxOutboundTimeframe
= 0;
144 uint64_t nMaxOutboundLimit
= 0;
146 CConnman(uint64_t seed0
, uint64_t seed1
);
148 bool Start(CScheduler
& scheduler
, std::string
& strNodeError
, Options options
);
151 bool BindListenPort(const CService
&bindAddr
, std::string
& strError
, bool fWhitelisted
= false);
152 bool GetNetworkActive() const { return fNetworkActive
; };
153 void SetNetworkActive(bool active
);
154 bool OpenNetworkConnection(const CAddress
& addrConnect
, bool fCountFailure
, CSemaphoreGrant
*grantOutbound
= NULL
, const char *strDest
= NULL
, bool fOneShot
= false, bool fFeeler
= false);
155 bool CheckIncomingNonce(uint64_t nonce
);
157 bool ForNode(NodeId id
, std::function
<bool(CNode
* pnode
)> func
);
159 void PushMessage(CNode
* pnode
, CSerializedNetMsg
&& msg
);
161 template<typename Callable
>
162 bool ForEachNodeContinueIf(Callable
&& func
)
165 for (auto&& node
: vNodes
)
171 template<typename Callable
>
172 bool ForEachNodeContinueIf(Callable
&& func
) const
175 for (const auto& node
: vNodes
)
181 template<typename Callable
, typename CallableAfter
>
182 bool ForEachNodeContinueIfThen(Callable
&& pre
, CallableAfter
&& post
)
186 for (auto&& node
: vNodes
)
195 template<typename Callable
, typename CallableAfter
>
196 bool ForEachNodeContinueIfThen(Callable
&& pre
, CallableAfter
&& post
) const
200 for (const auto& node
: vNodes
)
209 template<typename Callable
>
210 void ForEachNode(Callable
&& func
)
213 for (auto&& node
: vNodes
)
217 template<typename Callable
>
218 void ForEachNode(Callable
&& func
) const
221 for (const auto& node
: vNodes
)
225 template<typename Callable
, typename CallableAfter
>
226 void ForEachNodeThen(Callable
&& pre
, CallableAfter
&& post
)
229 for (auto&& node
: vNodes
)
234 template<typename Callable
, typename CallableAfter
>
235 void ForEachNodeThen(Callable
&& pre
, CallableAfter
&& post
) const
238 for (const auto& node
: vNodes
)
243 void RelayTransaction(const CTransaction
& tx
);
246 size_t GetAddressCount() const;
247 void SetServices(const CService
&addr
, ServiceFlags nServices
);
248 void MarkAddressGood(const CAddress
& addr
);
249 void AddNewAddress(const CAddress
& addr
, const CAddress
& addrFrom
, int64_t nTimePenalty
= 0);
250 void AddNewAddresses(const std::vector
<CAddress
>& vAddr
, const CAddress
& addrFrom
, int64_t nTimePenalty
= 0);
251 std::vector
<CAddress
> GetAddresses();
252 void AddressCurrentlyConnected(const CService
& addr
);
254 // Denial-of-service detection/prevention
255 // The idea is to detect peers that are behaving
256 // badly and disconnect/ban them, but do it in a
257 // one-coding-mistake-won't-shatter-the-entire-network
259 // IMPORTANT: There should be nothing I can give a
260 // node that it will forward on that will make that
261 // node's peers drop it. If there is, an attacker
262 // can isolate a node and/or try to split the network.
263 // Dropping a node for sending stuff that is invalid
264 // now but might be valid in a later version is also
265 // dangerous, because it can cause a network split
266 // between nodes running old code and nodes running
268 void Ban(const CNetAddr
& netAddr
, const BanReason
& reason
, int64_t bantimeoffset
= 0, bool sinceUnixEpoch
= false);
269 void Ban(const CSubNet
& subNet
, const BanReason
& reason
, int64_t bantimeoffset
= 0, bool sinceUnixEpoch
= false);
270 void ClearBanned(); // needed for unit testing
271 bool IsBanned(CNetAddr ip
);
272 bool IsBanned(CSubNet subnet
);
273 bool Unban(const CNetAddr
&ip
);
274 bool Unban(const CSubNet
&ip
);
275 void GetBanned(banmap_t
&banmap
);
276 void SetBanned(const banmap_t
&banmap
);
278 void AddOneShot(const std::string
& strDest
);
280 bool AddNode(const std::string
& node
);
281 bool RemoveAddedNode(const std::string
& node
);
282 std::vector
<AddedNodeInfo
> GetAddedNodeInfo();
284 size_t GetNodeCount(NumConnections num
);
285 void GetNodeStats(std::vector
<CNodeStats
>& vstats
);
286 bool DisconnectAddress(const CNetAddr
& addr
);
287 bool DisconnectNode(const std::string
& node
);
288 bool DisconnectNode(NodeId id
);
289 bool DisconnectSubnet(const CSubNet
& subnet
);
291 unsigned int GetSendBufferSize() const;
293 void AddWhitelistedRange(const CSubNet
&subnet
);
295 ServiceFlags
GetLocalServices() const;
297 //!set the max outbound target in bytes
298 void SetMaxOutboundTarget(uint64_t limit
);
299 uint64_t GetMaxOutboundTarget();
301 //!set the timeframe for the max outbound target
302 void SetMaxOutboundTimeframe(uint64_t timeframe
);
303 uint64_t GetMaxOutboundTimeframe();
305 //!check if the outbound target is reached
306 // if param historicalBlockServingLimit is set true, the function will
307 // response true if the limit for serving historical blocks has been reached
308 bool OutboundTargetReached(bool historicalBlockServingLimit
);
310 //!response the bytes left in the current max outbound cycle
311 // in case of no limit, it will always response 0
312 uint64_t GetOutboundTargetBytesLeft();
314 //!response the time in second left in the current max outbound cycle
315 // in case of no limit, it will always response 0
316 uint64_t GetMaxOutboundTimeLeftInCycle();
318 uint64_t GetTotalBytesRecv();
319 uint64_t GetTotalBytesSent();
321 void SetBestHeight(int height
);
322 int GetBestHeight() const;
324 /** Get a unique deterministic randomizer. */
325 CSipHasher
GetDeterministicRandomizer(uint64_t id
);
328 struct ListenSocket
{
332 ListenSocket(SOCKET socket_
, bool whitelisted_
) : socket(socket_
), whitelisted(whitelisted_
) {}
335 void ThreadOpenAddedConnections();
336 void ProcessOneShot();
337 void ThreadOpenConnections();
338 void ThreadMessageHandler();
339 void AcceptConnection(const ListenSocket
& hListenSocket
);
340 void ThreadSocketHandler();
341 void ThreadDNSAddressSeed();
343 uint64_t CalculateKeyedNetGroup(const CAddress
& ad
);
345 CNode
* FindNode(const CNetAddr
& ip
);
346 CNode
* FindNode(const CSubNet
& subNet
);
347 CNode
* FindNode(const std::string
& addrName
);
348 CNode
* FindNode(const CService
& addr
);
350 bool AttemptToEvictConnection();
351 CNode
* ConnectNode(CAddress addrConnect
, const char *pszDest
, bool fCountFailure
);
352 bool IsWhitelistedRange(const CNetAddr
&addr
);
354 void DeleteNode(CNode
* pnode
);
356 NodeId
GetNewNodeId();
358 //!check is the banlist has unwritten changes
359 bool BannedSetIsDirty();
360 //!set the "dirty" flag for the banlist
361 void SetBannedSetDirty(bool dirty
=true);
362 //!clean unused entries (if bantime has expired)
364 void DumpAddresses();
368 unsigned int GetReceiveFloodSize() const;
371 void RecordBytesRecv(uint64_t bytes
);
372 void RecordBytesSent(uint64_t bytes
);
374 // Network usage totals
375 CCriticalSection cs_totalBytesRecv
;
376 CCriticalSection cs_totalBytesSent
;
377 uint64_t nTotalBytesRecv
;
378 uint64_t nTotalBytesSent
;
380 // outbound limit & stats
381 uint64_t nMaxOutboundTotalBytesSentInCycle
;
382 uint64_t nMaxOutboundCycleStartTime
;
383 uint64_t nMaxOutboundLimit
;
384 uint64_t nMaxOutboundTimeframe
;
386 // Whitelisted ranges. Any node connecting from these is automatically
387 // whitelisted (as well as those connecting to whitelisted binds).
388 std::vector
<CSubNet
> vWhitelistedRange
;
389 CCriticalSection cs_vWhitelistedRange
;
391 unsigned int nSendBufferMaxSize
;
392 unsigned int nReceiveFloodSize
;
394 std::vector
<ListenSocket
> vhListenSocket
;
395 std::atomic
<bool> fNetworkActive
;
397 CCriticalSection cs_setBanned
;
398 bool setBannedIsDirty
;
399 bool fAddressesInitialized
;
401 std::deque
<std::string
> vOneShots
;
402 CCriticalSection cs_vOneShots
;
403 std::vector
<std::string
> vAddedNodes
;
404 CCriticalSection cs_vAddedNodes
;
405 std::vector
<CNode
*> vNodes
;
406 std::list
<CNode
*> vNodesDisconnected
;
407 mutable CCriticalSection cs_vNodes
;
408 std::atomic
<NodeId
> nLastNodeId
;
410 /** Services this instance offers */
411 ServiceFlags nLocalServices
;
413 /** Services this instance cares about */
414 ServiceFlags nRelevantServices
;
416 CSemaphore
*semOutbound
;
420 std::atomic
<int> nBestHeight
;
421 CClientUIInterface
* clientInterface
;
423 /** SipHasher seeds for deterministic randomness */
424 const uint64_t nSeed0
, nSeed1
;
426 std::condition_variable condMsgProc
;
427 std::mutex mutexMsgProc
;
428 std::atomic
<bool> flagInterruptMsgProc
;
430 CThreadInterrupt interruptNet
;
432 std::thread threadDNSAddressSeed
;
433 std::thread threadSocketHandler
;
434 std::thread threadOpenAddedConnections
;
435 std::thread threadOpenConnections
;
436 std::thread threadMessageHandler
;
438 extern std::unique_ptr
<CConnman
> g_connman
;
439 void Discover(boost::thread_group
& threadGroup
);
440 void MapPort(bool fUseUPnP
);
441 unsigned short GetListenPort();
442 bool BindListenPort(const CService
&bindAddr
, std::string
& strError
, bool fWhitelisted
= false);
443 size_t SocketSendData(CNode
*pnode
);
447 typedef bool result_type
;
450 bool operator()(I first
, I last
) const
452 while (first
!= last
) {
453 if (!(*first
)) return false;
460 // Signals for message handling
463 boost::signals2::signal
<bool (CNode
*, CConnman
&), CombinerAll
> ProcessMessages
;
464 boost::signals2::signal
<bool (CNode
*, CConnman
&), CombinerAll
> SendMessages
;
465 boost::signals2::signal
<void (CNode
*, CConnman
&)> InitializeNode
;
466 boost::signals2::signal
<void (NodeId
, bool&)> FinalizeNode
;
470 CNodeSignals
& GetNodeSignals();
475 LOCAL_NONE
, // unknown
476 LOCAL_IF
, // address a local interface listens on
477 LOCAL_BIND
, // address explicit bound to
478 LOCAL_UPNP
, // address reported by UPnP
479 LOCAL_MANUAL
, // address explicitly specified (-externalip=)
484 bool IsPeerAddrLocalGood(CNode
*pnode
);
485 void AdvertiseLocal(CNode
*pnode
);
486 void SetLimited(enum Network net
, bool fLimited
= true);
487 bool IsLimited(enum Network net
);
488 bool IsLimited(const CNetAddr
& addr
);
489 bool AddLocal(const CService
& addr
, int nScore
= LOCAL_NONE
);
490 bool AddLocal(const CNetAddr
& addr
, int nScore
= LOCAL_NONE
);
491 bool RemoveLocal(const CService
& addr
);
492 bool SeenLocal(const CService
& addr
);
493 bool IsLocal(const CService
& addr
);
494 bool GetLocal(CService
&addr
, const CNetAddr
*paddrPeer
= NULL
);
495 bool IsReachable(enum Network net
);
496 bool IsReachable(const CNetAddr
&addr
);
497 CAddress
GetLocalAddress(const CNetAddr
*paddrPeer
, ServiceFlags nLocalServices
);
500 extern bool fDiscover
;
502 extern bool fRelayTxes
;
504 extern limitedmap
<uint256
, int64_t> mapAlreadyAskedFor
;
506 /** Subversion as sent to the P2P network in `version` messages */
507 extern std::string strSubVersion
;
509 struct LocalServiceInfo
{
514 extern CCriticalSection cs_mapLocalHost
;
515 extern std::map
<CNetAddr
, LocalServiceInfo
> mapLocalHost
;
516 typedef std::map
<std::string
, uint64_t> mapMsgCmdSize
; //command, total bytes
522 ServiceFlags nServices
;
526 int64_t nTimeConnected
;
528 std::string addrName
;
530 std::string cleanSubVer
;
534 mapMsgCmdSize mapSendBytesPerMsgCmd
;
536 mapMsgCmdSize mapRecvBytesPerMsgCmd
;
541 std::string addrLocal
;
550 mutable CHash256 hasher
;
551 mutable uint256 data_hash
;
553 bool in_data
; // parsing header (false) or data (true)
555 CDataStream hdrbuf
; // partially received header
556 CMessageHeader hdr
; // complete header
557 unsigned int nHdrPos
;
559 CDataStream vRecv
; // received message data
560 unsigned int nDataPos
;
562 int64_t nTime
; // time (in microseconds) of message receipt.
564 CNetMessage(const CMessageHeader::MessageStartChars
& pchMessageStartIn
, int nTypeIn
, int nVersionIn
) : hdrbuf(nTypeIn
, nVersionIn
), hdr(pchMessageStartIn
), vRecv(nTypeIn
, nVersionIn
) {
572 bool complete() const
576 return (hdr
.nMessageSize
== nDataPos
);
579 const uint256
& GetMessageHash() const;
581 void SetVersion(int nVersionIn
)
583 hdrbuf
.SetVersion(nVersionIn
);
584 vRecv
.SetVersion(nVersionIn
);
587 int readHeader(const char *pch
, unsigned int nBytes
);
588 int readData(const char *pch
, unsigned int nBytes
);
592 /** Information about a peer */
595 friend class CConnman
;
598 ServiceFlags nServices
;
599 ServiceFlags nServicesExpected
;
601 size_t nSendSize
; // total size of all vSendMsg entries
602 size_t nSendOffset
; // offset inside the first vSendMsg already sent
604 std::deque
<std::vector
<unsigned char>> vSendMsg
;
605 CCriticalSection cs_vSend
;
607 std::deque
<CInv
> vRecvGetData
;
608 std::deque
<CNetMessage
> vRecvMsg
;
609 CCriticalSection cs_vRecvMsg
;
615 int64_t nTimeConnected
;
618 std::string addrName
;
621 // strSubVer is whatever byte array we read from the wire. However, this field is intended
622 // to be printed out, displayed to humans in various forms and so on. So we sanitize it and
623 // store the sanitized version in cleanSubVer. The original should be used when dealing with
624 // the network or wire types and the cleaned string used when displayed or logged.
625 std::string strSubVer
, cleanSubVer
;
626 bool fWhitelisted
; // This peer can bypass DoS banning.
627 bool fFeeler
; // If true this node is being used as a short lived feeler.
631 bool fSuccessfullyConnected
;
632 std::atomic_bool fDisconnect
;
633 // We use fRelayTxes for two purposes -
634 // a) it allows us to not relay tx invs before receiving the peer's version message
635 // b) the peer may tell us in its version message that we should not relay tx invs
636 // unless it loads a bloom filter.
637 bool fRelayTxes
; //protected by cs_filter
639 CSemaphoreGrant grantOutbound
;
640 CCriticalSection cs_filter
;
641 CBloomFilter
* pfilter
;
645 const uint64_t nKeyedNetGroup
;
648 mapMsgCmdSize mapSendBytesPerMsgCmd
;
649 mapMsgCmdSize mapRecvBytesPerMsgCmd
;
652 uint256 hashContinue
;
656 std::vector
<CAddress
> vAddrToSend
;
657 CRollingBloomFilter addrKnown
;
659 std::set
<uint256
> setKnown
;
660 int64_t nNextAddrSend
;
661 int64_t nNextLocalAddrSend
;
663 // inventory based relay
664 CRollingBloomFilter filterInventoryKnown
;
665 // Set of transaction ids we still have to announce.
666 // They are sorted by the mempool before relay, so the order is not important.
667 std::set
<uint256
> setInventoryTxToSend
;
668 // List of block ids we still have announce.
669 // There is no final sorting before sending, as they are always sent immediately
670 // and in the order requested.
671 std::vector
<uint256
> vInventoryBlockToSend
;
672 CCriticalSection cs_inventory
;
673 std::set
<uint256
> setAskFor
;
674 std::multimap
<int64_t, CInv
> mapAskFor
;
675 int64_t nNextInvSend
;
676 // Used for headers announcements - unfiltered blocks to relay
677 // Also protected by cs_inventory
678 std::vector
<uint256
> vBlockHashesToAnnounce
;
679 // Used for BIP35 mempool sending, also protected by cs_inventory
682 // Last time a "MEMPOOL" request was serviced.
683 std::atomic
<int64_t> timeLastMempoolReq
;
685 // Block and TXN accept times
686 std::atomic
<int64_t> nLastBlockTime
;
687 std::atomic
<int64_t> nLastTXTime
;
689 // Ping time measurement:
690 // The pong reply we're expecting, or 0 if no pong expected.
691 uint64_t nPingNonceSent
;
692 // Time (in usec) the last ping was sent, or 0 if no ping was ever sent.
693 int64_t nPingUsecStart
;
694 // Last measured round-trip time.
695 int64_t nPingUsecTime
;
696 // Best measured round-trip time.
697 int64_t nMinPingUsecTime
;
698 // Whether a ping is requested.
700 // Minimum fee rate with which to filter inv's to this node
701 CAmount minFeeFilter
;
702 CCriticalSection cs_feeFilter
;
703 CAmount lastSentFeeFilter
;
704 int64_t nextSendTimeFeeFilter
;
706 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);
711 void operator=(const CNode
&);
714 const uint64_t nLocalHostNonce
;
715 // Services offered to this peer
716 const ServiceFlags nLocalServices
;
717 const int nMyStartingHeight
;
721 NodeId
GetId() const {
725 uint64_t GetLocalNonce() const {
726 return nLocalHostNonce
;
729 int GetMyStartingHeight() const {
730 return nMyStartingHeight
;
735 assert(nRefCount
>= 0);
739 // requires LOCK(cs_vRecvMsg)
740 unsigned int GetTotalRecvSize()
742 unsigned int total
= 0;
743 BOOST_FOREACH(const CNetMessage
&msg
, vRecvMsg
)
744 total
+= msg
.vRecv
.size() + 24;
748 // requires LOCK(cs_vRecvMsg)
749 bool ReceiveMsgBytes(const char *pch
, unsigned int nBytes
, bool& complete
);
751 // requires LOCK(cs_vRecvMsg)
752 void SetRecvVersion(int nVersionIn
)
754 nRecvVersion
= nVersionIn
;
755 BOOST_FOREACH(CNetMessage
&msg
, vRecvMsg
)
756 msg
.SetVersion(nVersionIn
);
758 void SetSendVersion(int nVersionIn
)
760 // Send version may only be changed in the version message, and
761 // only one version message is allowed per session. We can therefore
762 // treat this value as const and even atomic as long as it's only used
763 // once the handshake is complete. Any attempt to set this twice is an
765 assert(nSendVersion
== 0);
766 nSendVersion
= nVersionIn
;
769 int GetSendVersion() const
771 // The send version should always be explicitly set to
772 // INIT_PROTO_VERSION rather than using this value until the handshake
774 assert(nSendVersion
!= 0);
791 void AddAddressKnown(const CAddress
& _addr
)
793 addrKnown
.insert(_addr
.GetKey());
796 void PushAddress(const CAddress
& _addr
, FastRandomContext
&insecure_rand
)
798 // Known checking here is only to save space from duplicates.
799 // SendMessages will filter it again for knowns that were added
800 // after addresses were pushed.
801 if (_addr
.IsValid() && !addrKnown
.contains(_addr
.GetKey())) {
802 if (vAddrToSend
.size() >= MAX_ADDR_TO_SEND
) {
803 vAddrToSend
[insecure_rand
.rand32() % vAddrToSend
.size()] = _addr
;
805 vAddrToSend
.push_back(_addr
);
811 void AddInventoryKnown(const CInv
& inv
)
815 filterInventoryKnown
.insert(inv
.hash
);
819 void PushInventory(const CInv
& inv
)
822 if (inv
.type
== MSG_TX
) {
823 if (!filterInventoryKnown
.contains(inv
.hash
)) {
824 setInventoryTxToSend
.insert(inv
.hash
);
826 } else if (inv
.type
== MSG_BLOCK
) {
827 vInventoryBlockToSend
.push_back(inv
.hash
);
831 void PushBlockHash(const uint256
&hash
)
834 vBlockHashesToAnnounce
.push_back(hash
);
837 void AskFor(const CInv
& inv
);
839 void CloseSocketDisconnect();
841 void copyStats(CNodeStats
&stats
);
843 ServiceFlags
GetLocalServices() const
845 return nLocalServices
;
853 /** Return a timestamp in the future (in microseconds) for exponentially distributed events. */
854 int64_t PoissonNextSend(int64_t nNow
, int average_interval_seconds
);
856 #endif // BITCOIN_NET_H