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"
29 #include <arpa/inet.h>
32 #include <boost/filesystem/path.hpp>
33 #include <boost/foreach.hpp>
34 #include <boost/signals2/signal.hpp>
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 outgoing nodes */
59 static const int MAX_OUTBOUND_CONNECTIONS
= 8;
60 /** -listen default */
61 static const bool DEFAULT_LISTEN
= true;
64 static const bool DEFAULT_UPNP
= USE_UPNP
;
66 static const bool DEFAULT_UPNP
= false;
68 /** The maximum number of entries in mapAskFor */
69 static const size_t MAPASKFOR_MAX_SZ
= MAX_INV_SZ
;
70 /** The maximum number of entries in setAskFor (larger due to getdata latency)*/
71 static const size_t SETASKFOR_MAX_SZ
= 2 * MAX_INV_SZ
;
72 /** The maximum number of peer connections to maintain. */
73 static const unsigned int DEFAULT_MAX_PEER_CONNECTIONS
= 125;
74 /** The default for -maxuploadtarget. 0 = Unlimited */
75 static const uint64_t DEFAULT_MAX_UPLOAD_TARGET
= 0;
76 /** The default timeframe for -maxuploadtarget. 1 day. */
77 static const uint64_t MAX_UPLOAD_TIMEFRAME
= 60 * 60 * 24;
78 /** Default for blocks only*/
79 static const bool DEFAULT_BLOCKSONLY
= false;
81 static const bool DEFAULT_FORCEDNSSEED
= false;
82 static const size_t DEFAULT_MAXRECEIVEBUFFER
= 5 * 1000;
83 static const size_t DEFAULT_MAXSENDBUFFER
= 1 * 1000;
85 static const ServiceFlags REQUIRED_SERVICES
= NODE_NETWORK
;
87 // NOTE: When adjusting this, update rpcnet:setban's help ("24h")
88 static const unsigned int DEFAULT_MISBEHAVING_BANTIME
= 60 * 60 * 24; // Default 24-hour ban
94 std::string strAddedNode
;
95 CService resolvedAddress
;
102 class CClientUIInterface
;
108 enum NumConnections
{
109 CONNECTIONS_NONE
= 0,
110 CONNECTIONS_IN
= (1U << 0),
111 CONNECTIONS_OUT
= (1U << 1),
112 CONNECTIONS_ALL
= (CONNECTIONS_IN
| CONNECTIONS_OUT
),
117 ServiceFlags nLocalServices
= NODE_NONE
;
118 ServiceFlags nRelevantServices
= NODE_NONE
;
119 int nMaxConnections
= 0;
120 int nMaxOutbound
= 0;
123 CClientUIInterface
* uiInterface
= nullptr;
124 unsigned int nSendBufferMaxSize
= 0;
125 unsigned int nReceiveFloodSize
= 0;
126 uint64_t nMaxOutboundTimeframe
= 0;
127 uint64_t nMaxOutboundLimit
= 0;
129 CConnman(uint64_t seed0
, uint64_t seed1
);
131 bool Start(boost::thread_group
& threadGroup
, CScheduler
& scheduler
, std::string
& strNodeError
, Options options
);
133 bool BindListenPort(const CService
&bindAddr
, std::string
& strError
, bool fWhitelisted
= false);
134 bool OpenNetworkConnection(const CAddress
& addrConnect
, bool fCountFailure
, CSemaphoreGrant
*grantOutbound
= NULL
, const char *strDest
= NULL
, bool fOneShot
= false, bool fFeeler
= false);
135 bool CheckIncomingNonce(uint64_t nonce
);
137 bool ForNode(NodeId id
, std::function
<bool(CNode
* pnode
)> func
);
139 template <typename
... Args
>
140 void PushMessageWithVersionAndFlag(CNode
* pnode
, int nVersion
, int flag
, const std::string
& sCommand
, Args
&&... args
)
142 auto msg(BeginMessage(pnode
, nVersion
, flag
, sCommand
));
143 ::SerializeMany(msg
, std::forward
<Args
>(args
)...);
145 PushMessage(pnode
, msg
, sCommand
);
148 template <typename
... Args
>
149 void PushMessageWithFlag(CNode
* pnode
, int flag
, const std::string
& sCommand
, Args
&&... args
)
151 PushMessageWithVersionAndFlag(pnode
, 0, flag
, sCommand
, std::forward
<Args
>(args
)...);
154 template <typename
... Args
>
155 void PushMessageWithVersion(CNode
* pnode
, int nVersion
, const std::string
& sCommand
, Args
&&... args
)
157 PushMessageWithVersionAndFlag(pnode
, nVersion
, 0, sCommand
, std::forward
<Args
>(args
)...);
160 template <typename
... Args
>
161 void PushMessage(CNode
* pnode
, const std::string
& sCommand
, Args
&&... args
)
163 PushMessageWithVersionAndFlag(pnode
, 0, 0, sCommand
, std::forward
<Args
>(args
)...);
166 template<typename Callable
>
167 bool ForEachNodeContinueIf(Callable
&& func
)
170 for (auto&& node
: vNodes
)
176 template<typename Callable
>
177 bool ForEachNodeContinueIf(Callable
&& func
) const
180 for (const auto& node
: vNodes
)
186 template<typename Callable
, typename CallableAfter
>
187 bool ForEachNodeContinueIfThen(Callable
&& pre
, CallableAfter
&& post
)
191 for (auto&& node
: vNodes
)
200 template<typename Callable
, typename CallableAfter
>
201 bool ForEachNodeContinueIfThen(Callable
&& pre
, CallableAfter
&& post
) const
205 for (const auto& node
: vNodes
)
214 template<typename Callable
>
215 void ForEachNode(Callable
&& func
)
218 for (auto&& node
: vNodes
)
222 template<typename Callable
>
223 void ForEachNode(Callable
&& func
) const
226 for (const auto& node
: vNodes
)
230 template<typename Callable
, typename CallableAfter
>
231 void ForEachNodeThen(Callable
&& pre
, CallableAfter
&& post
)
234 for (auto&& node
: vNodes
)
239 template<typename Callable
, typename CallableAfter
>
240 void ForEachNodeThen(Callable
&& pre
, CallableAfter
&& post
) const
243 for (const auto& node
: vNodes
)
248 void RelayTransaction(const CTransaction
& tx
);
251 size_t GetAddressCount() const;
252 void SetServices(const CService
&addr
, ServiceFlags nServices
);
253 void MarkAddressGood(const CAddress
& addr
);
254 void AddNewAddress(const CAddress
& addr
, const CAddress
& addrFrom
, int64_t nTimePenalty
= 0);
255 void AddNewAddresses(const std::vector
<CAddress
>& vAddr
, const CAddress
& addrFrom
, int64_t nTimePenalty
= 0);
256 std::vector
<CAddress
> GetAddresses();
257 void AddressCurrentlyConnected(const CService
& addr
);
259 // Denial-of-service detection/prevention
260 // The idea is to detect peers that are behaving
261 // badly and disconnect/ban them, but do it in a
262 // one-coding-mistake-won't-shatter-the-entire-network
264 // IMPORTANT: There should be nothing I can give a
265 // node that it will forward on that will make that
266 // node's peers drop it. If there is, an attacker
267 // can isolate a node and/or try to split the network.
268 // Dropping a node for sending stuff that is invalid
269 // now but might be valid in a later version is also
270 // dangerous, because it can cause a network split
271 // between nodes running old code and nodes running
273 void Ban(const CNetAddr
& netAddr
, const BanReason
& reason
, int64_t bantimeoffset
= 0, bool sinceUnixEpoch
= false);
274 void Ban(const CSubNet
& subNet
, const BanReason
& reason
, int64_t bantimeoffset
= 0, bool sinceUnixEpoch
= false);
275 void ClearBanned(); // needed for unit testing
276 bool IsBanned(CNetAddr ip
);
277 bool IsBanned(CSubNet subnet
);
278 bool Unban(const CNetAddr
&ip
);
279 bool Unban(const CSubNet
&ip
);
280 void GetBanned(banmap_t
&banmap
);
281 void SetBanned(const banmap_t
&banmap
);
283 void AddOneShot(const std::string
& strDest
);
285 bool AddNode(const std::string
& node
);
286 bool RemoveAddedNode(const std::string
& node
);
287 std::vector
<AddedNodeInfo
> GetAddedNodeInfo();
289 size_t GetNodeCount(NumConnections num
);
290 void GetNodeStats(std::vector
<CNodeStats
>& vstats
);
291 bool DisconnectAddress(const CNetAddr
& addr
);
292 bool DisconnectNode(const std::string
& node
);
293 bool DisconnectNode(NodeId id
);
294 bool DisconnectSubnet(const CSubNet
& subnet
);
296 unsigned int GetSendBufferSize() const;
298 void AddWhitelistedRange(const CSubNet
&subnet
);
300 ServiceFlags
GetLocalServices() const;
302 //!set the max outbound target in bytes
303 void SetMaxOutboundTarget(uint64_t limit
);
304 uint64_t GetMaxOutboundTarget();
306 //!set the timeframe for the max outbound target
307 void SetMaxOutboundTimeframe(uint64_t timeframe
);
308 uint64_t GetMaxOutboundTimeframe();
310 //!check if the outbound target is reached
311 // if param historicalBlockServingLimit is set true, the function will
312 // response true if the limit for serving historical blocks has been reached
313 bool OutboundTargetReached(bool historicalBlockServingLimit
);
315 //!response the bytes left in the current max outbound cycle
316 // in case of no limit, it will always response 0
317 uint64_t GetOutboundTargetBytesLeft();
319 //!response the time in second left in the current max outbound cycle
320 // in case of no limit, it will always response 0
321 uint64_t GetMaxOutboundTimeLeftInCycle();
323 uint64_t GetTotalBytesRecv();
324 uint64_t GetTotalBytesSent();
326 void SetBestHeight(int height
);
327 int GetBestHeight() const;
329 /** Get a unique deterministic randomizer. */
330 CSipHasher
GetDeterministicRandomizer(uint64_t id
);
333 struct ListenSocket
{
337 ListenSocket(SOCKET socket_
, bool whitelisted_
) : socket(socket_
), whitelisted(whitelisted_
) {}
340 void ThreadOpenAddedConnections();
341 void ProcessOneShot();
342 void ThreadOpenConnections();
343 void ThreadMessageHandler();
344 void AcceptConnection(const ListenSocket
& hListenSocket
);
345 void ThreadSocketHandler();
346 void ThreadDNSAddressSeed();
348 uint64_t CalculateKeyedNetGroup(const CAddress
& ad
);
350 CNode
* FindNode(const CNetAddr
& ip
);
351 CNode
* FindNode(const CSubNet
& subNet
);
352 CNode
* FindNode(const std::string
& addrName
);
353 CNode
* FindNode(const CService
& addr
);
355 bool AttemptToEvictConnection();
356 CNode
* ConnectNode(CAddress addrConnect
, const char *pszDest
, bool fCountFailure
);
357 bool IsWhitelistedRange(const CNetAddr
&addr
);
359 void DeleteNode(CNode
* pnode
);
361 NodeId
GetNewNodeId();
363 //!check is the banlist has unwritten changes
364 bool BannedSetIsDirty();
365 //!set the "dirty" flag for the banlist
366 void SetBannedSetDirty(bool dirty
=true);
367 //!clean unused entries (if bantime has expired)
369 void DumpAddresses();
373 unsigned int GetReceiveFloodSize() const;
375 CDataStream
BeginMessage(CNode
* node
, int nVersion
, int flags
, const std::string
& sCommand
);
376 void PushMessage(CNode
* pnode
, CDataStream
& strm
, const std::string
& sCommand
);
377 void EndMessage(CDataStream
& strm
);
380 void RecordBytesRecv(uint64_t bytes
);
381 void RecordBytesSent(uint64_t bytes
);
383 // Network usage totals
384 CCriticalSection cs_totalBytesRecv
;
385 CCriticalSection cs_totalBytesSent
;
386 uint64_t nTotalBytesRecv
;
387 uint64_t nTotalBytesSent
;
389 // outbound limit & stats
390 uint64_t nMaxOutboundTotalBytesSentInCycle
;
391 uint64_t nMaxOutboundCycleStartTime
;
392 uint64_t nMaxOutboundLimit
;
393 uint64_t nMaxOutboundTimeframe
;
395 // Whitelisted ranges. Any node connecting from these is automatically
396 // whitelisted (as well as those connecting to whitelisted binds).
397 std::vector
<CSubNet
> vWhitelistedRange
;
398 CCriticalSection cs_vWhitelistedRange
;
400 unsigned int nSendBufferMaxSize
;
401 unsigned int nReceiveFloodSize
;
403 std::vector
<ListenSocket
> vhListenSocket
;
405 CCriticalSection cs_setBanned
;
406 bool setBannedIsDirty
;
407 bool fAddressesInitialized
;
409 std::deque
<std::string
> vOneShots
;
410 CCriticalSection cs_vOneShots
;
411 std::vector
<std::string
> vAddedNodes
;
412 CCriticalSection cs_vAddedNodes
;
413 std::vector
<CNode
*> vNodes
;
414 std::list
<CNode
*> vNodesDisconnected
;
415 mutable CCriticalSection cs_vNodes
;
416 std::atomic
<NodeId
> nLastNodeId
;
417 boost::condition_variable messageHandlerCondition
;
419 /** Services this instance offers */
420 ServiceFlags nLocalServices
;
422 /** Services this instance cares about */
423 ServiceFlags nRelevantServices
;
425 CSemaphore
*semOutbound
;
429 std::atomic
<int> nBestHeight
;
430 CClientUIInterface
* clientInterface
;
432 /** SipHasher seeds for deterministic randomness */
433 const uint64_t nSeed0
, nSeed1
;
435 extern std::unique_ptr
<CConnman
> g_connman
;
436 void Discover(boost::thread_group
& threadGroup
);
437 void MapPort(bool fUseUPnP
);
438 unsigned short GetListenPort();
439 bool BindListenPort(const CService
&bindAddr
, std::string
& strError
, bool fWhitelisted
= false);
440 size_t SocketSendData(CNode
*pnode
);
444 typedef bool result_type
;
447 bool operator()(I first
, I last
) const
449 while (first
!= last
) {
450 if (!(*first
)) return false;
457 // Signals for message handling
460 boost::signals2::signal
<bool (CNode
*, CConnman
&), CombinerAll
> ProcessMessages
;
461 boost::signals2::signal
<bool (CNode
*, CConnman
&), CombinerAll
> SendMessages
;
462 boost::signals2::signal
<void (CNode
*, CConnman
&)> InitializeNode
;
463 boost::signals2::signal
<void (NodeId
, bool&)> FinalizeNode
;
467 CNodeSignals
& GetNodeSignals();
472 LOCAL_NONE
, // unknown
473 LOCAL_IF
, // address a local interface listens on
474 LOCAL_BIND
, // address explicit bound to
475 LOCAL_UPNP
, // address reported by UPnP
476 LOCAL_MANUAL
, // address explicitly specified (-externalip=)
481 bool IsPeerAddrLocalGood(CNode
*pnode
);
482 void AdvertiseLocal(CNode
*pnode
);
483 void SetLimited(enum Network net
, bool fLimited
= true);
484 bool IsLimited(enum Network net
);
485 bool IsLimited(const CNetAddr
& addr
);
486 bool AddLocal(const CService
& addr
, int nScore
= LOCAL_NONE
);
487 bool AddLocal(const CNetAddr
& addr
, int nScore
= LOCAL_NONE
);
488 bool RemoveLocal(const CService
& addr
);
489 bool SeenLocal(const CService
& addr
);
490 bool IsLocal(const CService
& addr
);
491 bool GetLocal(CService
&addr
, const CNetAddr
*paddrPeer
= NULL
);
492 bool IsReachable(enum Network net
);
493 bool IsReachable(const CNetAddr
&addr
);
494 CAddress
GetLocalAddress(const CNetAddr
*paddrPeer
, ServiceFlags nLocalServices
);
497 extern bool fDiscover
;
499 extern bool fRelayTxes
;
501 extern limitedmap
<uint256
, int64_t> mapAlreadyAskedFor
;
503 /** Subversion as sent to the P2P network in `version` messages */
504 extern std::string strSubVersion
;
506 struct LocalServiceInfo
{
511 extern CCriticalSection cs_mapLocalHost
;
512 extern std::map
<CNetAddr
, LocalServiceInfo
> mapLocalHost
;
513 typedef std::map
<std::string
, uint64_t> mapMsgCmdSize
; //command, total bytes
519 ServiceFlags nServices
;
523 int64_t nTimeConnected
;
525 std::string addrName
;
527 std::string cleanSubVer
;
531 mapMsgCmdSize mapSendBytesPerMsgCmd
;
533 mapMsgCmdSize mapRecvBytesPerMsgCmd
;
538 std::string addrLocal
;
547 bool in_data
; // parsing header (false) or data (true)
549 CDataStream hdrbuf
; // partially received header
550 CMessageHeader hdr
; // complete header
551 unsigned int nHdrPos
;
553 CDataStream vRecv
; // received message data
554 unsigned int nDataPos
;
556 int64_t nTime
; // time (in microseconds) of message receipt.
558 CNetMessage(const CMessageHeader::MessageStartChars
& pchMessageStartIn
, int nTypeIn
, int nVersionIn
) : hdrbuf(nTypeIn
, nVersionIn
), hdr(pchMessageStartIn
), vRecv(nTypeIn
, nVersionIn
) {
566 bool complete() const
570 return (hdr
.nMessageSize
== nDataPos
);
573 void SetVersion(int nVersionIn
)
575 hdrbuf
.SetVersion(nVersionIn
);
576 vRecv
.SetVersion(nVersionIn
);
579 int readHeader(const char *pch
, unsigned int nBytes
);
580 int readData(const char *pch
, unsigned int nBytes
);
584 /** Information about a peer */
587 friend class CConnman
;
590 ServiceFlags nServices
;
591 ServiceFlags nServicesExpected
;
593 size_t nSendSize
; // total size of all vSendMsg entries
594 size_t nSendOffset
; // offset inside the first vSendMsg already sent
596 std::deque
<CSerializeData
> vSendMsg
;
597 CCriticalSection cs_vSend
;
599 std::deque
<CInv
> vRecvGetData
;
600 std::deque
<CNetMessage
> vRecvMsg
;
601 CCriticalSection cs_vRecvMsg
;
607 int64_t nTimeConnected
;
610 std::string addrName
;
613 // strSubVer is whatever byte array we read from the wire. However, this field is intended
614 // to be printed out, displayed to humans in various forms and so on. So we sanitize it and
615 // store the sanitized version in cleanSubVer. The original should be used when dealing with
616 // the network or wire types and the cleaned string used when displayed or logged.
617 std::string strSubVer
, cleanSubVer
;
618 bool fWhitelisted
; // This peer can bypass DoS banning.
619 bool fFeeler
; // If true this node is being used as a short lived feeler.
624 bool fSuccessfullyConnected
;
626 // We use fRelayTxes for two purposes -
627 // a) it allows us to not relay tx invs before receiving the peer's version message
628 // b) the peer may tell us in its version message that we should not relay tx invs
629 // unless it loads a bloom filter.
630 bool fRelayTxes
; //protected by cs_filter
632 CSemaphoreGrant grantOutbound
;
633 CCriticalSection cs_filter
;
634 CBloomFilter
* pfilter
;
638 const uint64_t nKeyedNetGroup
;
641 mapMsgCmdSize mapSendBytesPerMsgCmd
;
642 mapMsgCmdSize mapRecvBytesPerMsgCmd
;
645 uint256 hashContinue
;
649 std::vector
<CAddress
> vAddrToSend
;
650 CRollingBloomFilter addrKnown
;
652 std::set
<uint256
> setKnown
;
653 int64_t nNextAddrSend
;
654 int64_t nNextLocalAddrSend
;
656 // inventory based relay
657 CRollingBloomFilter filterInventoryKnown
;
658 // Set of transaction ids we still have to announce.
659 // They are sorted by the mempool before relay, so the order is not important.
660 std::set
<uint256
> setInventoryTxToSend
;
661 // List of block ids we still have announce.
662 // There is no final sorting before sending, as they are always sent immediately
663 // and in the order requested.
664 std::vector
<uint256
> vInventoryBlockToSend
;
665 CCriticalSection cs_inventory
;
666 std::set
<uint256
> setAskFor
;
667 std::multimap
<int64_t, CInv
> mapAskFor
;
668 int64_t nNextInvSend
;
669 // Used for headers announcements - unfiltered blocks to relay
670 // Also protected by cs_inventory
671 std::vector
<uint256
> vBlockHashesToAnnounce
;
672 // Used for BIP35 mempool sending, also protected by cs_inventory
675 // Last time a "MEMPOOL" request was serviced.
676 std::atomic
<int64_t> timeLastMempoolReq
;
678 // Block and TXN accept times
679 std::atomic
<int64_t> nLastBlockTime
;
680 std::atomic
<int64_t> nLastTXTime
;
682 // Ping time measurement:
683 // The pong reply we're expecting, or 0 if no pong expected.
684 uint64_t nPingNonceSent
;
685 // Time (in usec) the last ping was sent, or 0 if no ping was ever sent.
686 int64_t nPingUsecStart
;
687 // Last measured round-trip time.
688 int64_t nPingUsecTime
;
689 // Best measured round-trip time.
690 int64_t nMinPingUsecTime
;
691 // Whether a ping is requested.
693 // Minimum fee rate with which to filter inv's to this node
694 CAmount minFeeFilter
;
695 CCriticalSection cs_feeFilter
;
696 CAmount lastSentFeeFilter
;
697 int64_t nextSendTimeFeeFilter
;
699 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);
704 void operator=(const CNode
&);
707 const uint64_t nLocalHostNonce
;
708 // Services offered to this peer
709 const ServiceFlags nLocalServices
;
710 const int nMyStartingHeight
;
714 NodeId
GetId() const {
718 uint64_t GetLocalNonce() const {
719 return nLocalHostNonce
;
722 int GetMyStartingHeight() const {
723 return nMyStartingHeight
;
728 assert(nRefCount
>= 0);
732 // requires LOCK(cs_vRecvMsg)
733 unsigned int GetTotalRecvSize()
735 unsigned int total
= 0;
736 BOOST_FOREACH(const CNetMessage
&msg
, vRecvMsg
)
737 total
+= msg
.vRecv
.size() + 24;
741 // requires LOCK(cs_vRecvMsg)
742 bool ReceiveMsgBytes(const char *pch
, unsigned int nBytes
, bool& complete
);
744 // requires LOCK(cs_vRecvMsg)
745 void SetRecvVersion(int nVersionIn
)
747 nRecvVersion
= nVersionIn
;
748 BOOST_FOREACH(CNetMessage
&msg
, vRecvMsg
)
749 msg
.SetVersion(nVersionIn
);
751 void SetSendVersion(int nVersionIn
)
753 // Send version may only be changed in the version message, and
754 // only one version message is allowed per session. We can therefore
755 // treat this value as const and even atomic as long as it's only used
756 // once the handshake is complete. Any attempt to set this twice is an
758 assert(nSendVersion
== 0);
759 nSendVersion
= nVersionIn
;
762 int GetSendVersion() const
764 // The send version should always be explicitly set to
765 // INIT_PROTO_VERSION rather than using this value until the handshake
766 // is complete. See PushMessageWithVersion().
767 assert(nSendVersion
!= 0);
784 void AddAddressKnown(const CAddress
& _addr
)
786 addrKnown
.insert(_addr
.GetKey());
789 void PushAddress(const CAddress
& _addr
, FastRandomContext
&insecure_rand
)
791 // Known checking here is only to save space from duplicates.
792 // SendMessages will filter it again for knowns that were added
793 // after addresses were pushed.
794 if (_addr
.IsValid() && !addrKnown
.contains(_addr
.GetKey())) {
795 if (vAddrToSend
.size() >= MAX_ADDR_TO_SEND
) {
796 vAddrToSend
[insecure_rand
.rand32() % vAddrToSend
.size()] = _addr
;
798 vAddrToSend
.push_back(_addr
);
804 void AddInventoryKnown(const CInv
& inv
)
808 filterInventoryKnown
.insert(inv
.hash
);
812 void PushInventory(const CInv
& inv
)
815 if (inv
.type
== MSG_TX
) {
816 if (!filterInventoryKnown
.contains(inv
.hash
)) {
817 setInventoryTxToSend
.insert(inv
.hash
);
819 } else if (inv
.type
== MSG_BLOCK
) {
820 vInventoryBlockToSend
.push_back(inv
.hash
);
824 void PushBlockHash(const uint256
&hash
)
827 vBlockHashesToAnnounce
.push_back(hash
);
830 void AskFor(const CInv
& inv
);
832 void CloseSocketDisconnect();
834 void copyStats(CNodeStats
&stats
);
836 ServiceFlags
GetLocalServices() const
838 return nLocalServices
;
846 /** Return a timestamp in the future (in microseconds) for exponentially distributed events. */
847 int64_t PoissonNextSend(int64_t nNow
, int average_interval_seconds
);
849 #endif // BITCOIN_NET_H