Merge #10767: [wallet] Clarify wallet initialization / destruction interface
[bitcoinplatinum.git] / src / net.h
blobca2433aa54ddfe99bb35bc6c71709bbac107f599
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.
6 #ifndef BITCOIN_NET_H
7 #define BITCOIN_NET_H
9 #include "addrdb.h"
10 #include "addrman.h"
11 #include "amount.h"
12 #include "bloom.h"
13 #include "compat.h"
14 #include "hash.h"
15 #include "limitedmap.h"
16 #include "netaddress.h"
17 #include "policy/feerate.h"
18 #include "protocol.h"
19 #include "random.h"
20 #include "streams.h"
21 #include "sync.h"
22 #include "uint256.h"
23 #include "threadinterrupt.h"
25 #include <atomic>
26 #include <deque>
27 #include <stdint.h>
28 #include <thread>
29 #include <memory>
30 #include <condition_variable>
32 #ifndef WIN32
33 #include <arpa/inet.h>
34 #endif
37 class CScheduler;
38 class CNode;
40 namespace boost {
41 class thread_group;
42 } // namespace boost
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;
64 /** -upnp default */
65 #ifdef USE_UPNP
66 static const bool DEFAULT_UPNP = USE_UPNP;
67 #else
68 static const bool DEFAULT_UPNP = false;
69 #endif
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;
94 struct AddedNodeInfo
96 std::string strAddedNode;
97 CService resolvedAddress;
98 bool fConnected;
99 bool fInbound;
102 class CNodeStats;
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;
115 std::string command;
118 class NetEventsInterface;
119 class CConnman
121 public:
123 enum NumConnections {
124 CONNECTIONS_NONE = 0,
125 CONNECTIONS_IN = (1U << 0),
126 CONNECTIONS_OUT = (1U << 1),
127 CONNECTIONS_ALL = (CONNECTIONS_IN | CONNECTIONS_OUT),
130 struct Options
132 ServiceFlags nLocalServices = NODE_NONE;
133 ServiceFlags nRelevantServices = NODE_NONE;
134 int nMaxConnections = 0;
135 int nMaxOutbound = 0;
136 int nMaxAddnode = 0;
137 int nMaxFeeler = 0;
138 int nBestHeight = 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);
170 ~CConnman();
171 bool Start(CScheduler& scheduler, const Options& options);
172 void Stop();
173 void Interrupt();
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)
186 LOCK(cs_vNodes);
187 for (auto&& node : vNodes) {
188 if (NodeFullyConnected(node))
189 func(node);
193 template<typename Callable>
194 void ForEachNode(Callable&& func) const
196 LOCK(cs_vNodes);
197 for (auto&& node : vNodes) {
198 if (NodeFullyConnected(node))
199 func(node);
203 template<typename Callable, typename CallableAfter>
204 void ForEachNodeThen(Callable&& pre, CallableAfter&& post)
206 LOCK(cs_vNodes);
207 for (auto&& node : vNodes) {
208 if (NodeFullyConnected(node))
209 pre(node);
211 post();
214 template<typename Callable, typename CallableAfter>
215 void ForEachNodeThen(Callable&& pre, CallableAfter&& post) const
217 LOCK(cs_vNodes);
218 for (auto&& node : vNodes) {
219 if (NodeFullyConnected(node))
220 pre(node);
222 post();
225 // Addrman functions
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
236 // way.
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
245 // new code.
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();
300 private:
301 struct ListenSocket {
302 SOCKET socket;
303 bool whitelisted;
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)
341 void SweepBanned();
342 void DumpAddresses();
343 void DumpData();
344 void DumpBanlist();
346 // Network stats
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;
374 banmap_t setBanned;
375 CCriticalSection cs_setBanned;
376 bool setBannedIsDirty;
377 bool fAddressesInitialized;
378 CAddrMan addrman;
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;
396 int nMaxConnections;
397 int nMaxOutbound;
398 int nMaxAddnode;
399 int nMaxFeeler;
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. */
408 bool fMsgProcWake;
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);
428 struct CombinerAll
430 typedef bool result_type;
432 template<typename I>
433 bool operator()(I first, I last) const
435 while (first != last) {
436 if (!(*first)) return false;
437 ++first;
439 return true;
444 * Interface for message handling
446 class NetEventsInterface
448 public:
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;
455 enum
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=)
463 LOCAL_MAX
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;
483 extern bool fListen;
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 {
492 int nScore;
493 int nPort;
496 extern CCriticalSection cs_mapLocalHost;
497 extern std::map<CNetAddr, LocalServiceInfo> mapLocalHost;
498 typedef std::map<std::string, uint64_t> mapMsgCmdSize; //command, total bytes
500 class CNodeStats
502 public:
503 NodeId nodeid;
504 ServiceFlags nServices;
505 bool fRelayTxes;
506 int64_t nLastSend;
507 int64_t nLastRecv;
508 int64_t nTimeConnected;
509 int64_t nTimeOffset;
510 std::string addrName;
511 int nVersion;
512 std::string cleanSubVer;
513 bool fInbound;
514 bool fAddnode;
515 int nStartingHeight;
516 uint64_t nSendBytes;
517 mapMsgCmdSize mapSendBytesPerMsgCmd;
518 uint64_t nRecvBytes;
519 mapMsgCmdSize mapRecvBytesPerMsgCmd;
520 bool fWhitelisted;
521 double dPingTime;
522 double dPingWait;
523 double dMinPing;
524 // Our address, as reported by the peer
525 std::string addrLocal;
526 // Address of this peer
527 CAddress addr;
528 // Bind address of our side of the connection
529 CAddress addrBind;
535 class CNetMessage {
536 private:
537 mutable CHash256 hasher;
538 mutable uint256 data_hash;
539 public:
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) {
552 hdrbuf.resize(24);
553 in_data = false;
554 nHdrPos = 0;
555 nDataPos = 0;
556 nTime = 0;
559 bool complete() const
561 if (!in_data)
562 return false;
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 */
580 class CNode
582 friend class CConnman;
583 public:
584 // socket
585 std::atomic<ServiceFlags> nServices;
586 ServiceFlags nServicesExpected;
587 SOCKET hSocket;
588 size_t nSendSize; // total size of all vSendMsg entries
589 size_t nSendOffset; // offset inside the first vSendMsg already sent
590 uint64_t nSendBytes;
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;
603 uint64_t nRecvBytes;
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
611 const CAddress addr;
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.
623 bool fOneShot;
624 bool fAddnode;
625 bool fClient;
626 const bool fInbound;
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
634 bool fSentAddr;
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;
643 protected:
645 mapMsgCmdSize mapSendBytesPerMsgCmd;
646 mapMsgCmdSize mapRecvBytesPerMsgCmd;
648 public:
649 uint256 hashContinue;
650 std::atomic<int> nStartingHeight;
652 // flood relay
653 std::vector<CAddress> vAddrToSend;
654 CRollingBloomFilter addrKnown;
655 bool fGetAddr;
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
677 bool fSendMempool;
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);
704 ~CNode();
706 private:
707 CNode(const CNode&);
708 void operator=(const CNode&);
709 const NodeId id;
712 const uint64_t nLocalHostNonce;
713 // Services offered to this peer
714 const ServiceFlags nLocalServices;
715 const int nMyStartingHeight;
716 int nSendVersion;
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
723 CService addrLocal;
724 mutable CCriticalSection cs_addrLocal;
725 public:
727 NodeId GetId() const {
728 return id;
731 uint64_t GetLocalNonce() const {
732 return nLocalHostNonce;
735 int GetMyStartingHeight() const {
736 return nMyStartingHeight;
739 int GetRefCount() const
741 assert(nRefCount >= 0);
742 return nRefCount;
745 bool ReceiveMsgBytes(const char *pch, unsigned int nBytes, bool& complete);
747 void SetRecvVersion(int nVersionIn)
749 nRecvVersion = nVersionIn;
751 int GetRecvVersion() const
753 return nRecvVersion;
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);
762 CNode* AddRef()
764 nRefCount++;
765 return this;
768 void Release()
770 nRefCount--;
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;
788 } else {
789 vAddrToSend.push_back(_addr);
795 void AddInventoryKnown(const CInv& inv)
798 LOCK(cs_inventory);
799 filterInventoryKnown.insert(inv.hash);
803 void PushInventory(const CInv& inv)
805 LOCK(cs_inventory);
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)
817 LOCK(cs_inventory);
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