net: add a flag to indicate when a node's process queue is full
[bitcoinplatinum.git] / src / net.h
blob0eb430a8bfcb850772e16388e5f3b71584cf0145
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 "protocol.h"
18 #include "random.h"
19 #include "streams.h"
20 #include "sync.h"
21 #include "uint256.h"
22 #include "threadinterrupt.h"
24 #include <atomic>
25 #include <deque>
26 #include <stdint.h>
27 #include <thread>
28 #include <memory>
29 #include <condition_variable>
31 #ifndef WIN32
32 #include <arpa/inet.h>
33 #endif
35 #include <boost/filesystem/path.hpp>
36 #include <boost/foreach.hpp>
37 #include <boost/signals2/signal.hpp>
39 class CAddrMan;
40 class CScheduler;
41 class CNode;
43 namespace boost {
44 class thread_group;
45 } // namespace boost
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;
65 /** -upnp default */
66 #ifdef USE_UPNP
67 static const bool DEFAULT_UPNP = USE_UPNP;
68 #else
69 static const bool DEFAULT_UPNP = false;
70 #endif
71 /** The maximum number of entries in mapAskFor */
72 static const size_t MAPASKFOR_MAX_SZ = MAX_INV_SZ;
73 /** The maximum number of entries in setAskFor (larger due to getdata latency)*/
74 static const size_t SETASKFOR_MAX_SZ = 2 * MAX_INV_SZ;
75 /** The maximum number of peer connections to maintain. */
76 static const unsigned int DEFAULT_MAX_PEER_CONNECTIONS = 125;
77 /** The default for -maxuploadtarget. 0 = Unlimited */
78 static const uint64_t DEFAULT_MAX_UPLOAD_TARGET = 0;
79 /** The default timeframe for -maxuploadtarget. 1 day. */
80 static const uint64_t MAX_UPLOAD_TIMEFRAME = 60 * 60 * 24;
81 /** Default for blocks only*/
82 static const bool DEFAULT_BLOCKSONLY = false;
84 static const bool DEFAULT_FORCEDNSSEED = false;
85 static const size_t DEFAULT_MAXRECEIVEBUFFER = 5 * 1000;
86 static const size_t DEFAULT_MAXSENDBUFFER = 1 * 1000;
88 static const ServiceFlags REQUIRED_SERVICES = NODE_NETWORK;
90 // NOTE: When adjusting this, update rpcnet:setban's help ("24h")
91 static const unsigned int DEFAULT_MISBEHAVING_BANTIME = 60 * 60 * 24; // Default 24-hour ban
93 typedef int NodeId;
95 struct AddedNodeInfo
97 std::string strAddedNode;
98 CService resolvedAddress;
99 bool fConnected;
100 bool fInbound;
103 class CTransaction;
104 class CNodeStats;
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;
117 std::string command;
121 class CConnman
123 public:
125 enum NumConnections {
126 CONNECTIONS_NONE = 0,
127 CONNECTIONS_IN = (1U << 0),
128 CONNECTIONS_OUT = (1U << 1),
129 CONNECTIONS_ALL = (CONNECTIONS_IN | CONNECTIONS_OUT),
132 struct Options
134 ServiceFlags nLocalServices = NODE_NONE;
135 ServiceFlags nRelevantServices = NODE_NONE;
136 int nMaxConnections = 0;
137 int nMaxOutbound = 0;
138 int nMaxFeeler = 0;
139 int nBestHeight = 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);
147 ~CConnman();
148 bool Start(CScheduler& scheduler, std::string& strNodeError, Options options);
149 void Stop();
150 void Interrupt();
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)
164 LOCK(cs_vNodes);
165 for (auto&& node : vNodes)
166 if(!func(node))
167 return false;
168 return true;
171 template<typename Callable>
172 bool ForEachNodeContinueIf(Callable&& func) const
174 LOCK(cs_vNodes);
175 for (const auto& node : vNodes)
176 if(!func(node))
177 return false;
178 return true;
181 template<typename Callable, typename CallableAfter>
182 bool ForEachNodeContinueIfThen(Callable&& pre, CallableAfter&& post)
184 bool ret = true;
185 LOCK(cs_vNodes);
186 for (auto&& node : vNodes)
187 if(!pre(node)) {
188 ret = false;
189 break;
191 post();
192 return ret;
195 template<typename Callable, typename CallableAfter>
196 bool ForEachNodeContinueIfThen(Callable&& pre, CallableAfter&& post) const
198 bool ret = true;
199 LOCK(cs_vNodes);
200 for (const auto& node : vNodes)
201 if(!pre(node)) {
202 ret = false;
203 break;
205 post();
206 return ret;
209 template<typename Callable>
210 void ForEachNode(Callable&& func)
212 LOCK(cs_vNodes);
213 for (auto&& node : vNodes)
214 func(node);
217 template<typename Callable>
218 void ForEachNode(Callable&& func) const
220 LOCK(cs_vNodes);
221 for (const auto& node : vNodes)
222 func(node);
225 template<typename Callable, typename CallableAfter>
226 void ForEachNodeThen(Callable&& pre, CallableAfter&& post)
228 LOCK(cs_vNodes);
229 for (auto&& node : vNodes)
230 pre(node);
231 post();
234 template<typename Callable, typename CallableAfter>
235 void ForEachNodeThen(Callable&& pre, CallableAfter&& post) const
237 LOCK(cs_vNodes);
238 for (const auto& node : vNodes)
239 pre(node);
240 post();
243 void RelayTransaction(const CTransaction& tx);
245 // Addrman functions
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
258 // way.
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
267 // new code.
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);
327 unsigned int GetReceiveFloodSize() const;
328 private:
329 struct ListenSocket {
330 SOCKET socket;
331 bool whitelisted;
333 ListenSocket(SOCKET socket_, bool whitelisted_) : socket(socket_), whitelisted(whitelisted_) {}
336 void ThreadOpenAddedConnections();
337 void ProcessOneShot();
338 void ThreadOpenConnections();
339 void ThreadMessageHandler();
340 void AcceptConnection(const ListenSocket& hListenSocket);
341 void ThreadSocketHandler();
342 void ThreadDNSAddressSeed();
344 void WakeMessageHandler();
346 uint64_t CalculateKeyedNetGroup(const CAddress& ad);
348 CNode* FindNode(const CNetAddr& ip);
349 CNode* FindNode(const CSubNet& subNet);
350 CNode* FindNode(const std::string& addrName);
351 CNode* FindNode(const CService& addr);
353 bool AttemptToEvictConnection();
354 CNode* ConnectNode(CAddress addrConnect, const char *pszDest, bool fCountFailure);
355 bool IsWhitelistedRange(const CNetAddr &addr);
357 void DeleteNode(CNode* pnode);
359 NodeId GetNewNodeId();
361 //!check is the banlist has unwritten changes
362 bool BannedSetIsDirty();
363 //!set the "dirty" flag for the banlist
364 void SetBannedSetDirty(bool dirty=true);
365 //!clean unused entries (if bantime has expired)
366 void SweepBanned();
367 void DumpAddresses();
368 void DumpData();
369 void DumpBanlist();
371 // Network stats
372 void RecordBytesRecv(uint64_t bytes);
373 void RecordBytesSent(uint64_t bytes);
375 // Network usage totals
376 CCriticalSection cs_totalBytesRecv;
377 CCriticalSection cs_totalBytesSent;
378 uint64_t nTotalBytesRecv;
379 uint64_t nTotalBytesSent;
381 // outbound limit & stats
382 uint64_t nMaxOutboundTotalBytesSentInCycle;
383 uint64_t nMaxOutboundCycleStartTime;
384 uint64_t nMaxOutboundLimit;
385 uint64_t nMaxOutboundTimeframe;
387 // Whitelisted ranges. Any node connecting from these is automatically
388 // whitelisted (as well as those connecting to whitelisted binds).
389 std::vector<CSubNet> vWhitelistedRange;
390 CCriticalSection cs_vWhitelistedRange;
392 unsigned int nSendBufferMaxSize;
393 unsigned int nReceiveFloodSize;
395 std::vector<ListenSocket> vhListenSocket;
396 std::atomic<bool> fNetworkActive;
397 banmap_t setBanned;
398 CCriticalSection cs_setBanned;
399 bool setBannedIsDirty;
400 bool fAddressesInitialized;
401 CAddrMan addrman;
402 std::deque<std::string> vOneShots;
403 CCriticalSection cs_vOneShots;
404 std::vector<std::string> vAddedNodes;
405 CCriticalSection cs_vAddedNodes;
406 std::vector<CNode*> vNodes;
407 std::list<CNode*> vNodesDisconnected;
408 mutable CCriticalSection cs_vNodes;
409 std::atomic<NodeId> nLastNodeId;
411 /** Services this instance offers */
412 ServiceFlags nLocalServices;
414 /** Services this instance cares about */
415 ServiceFlags nRelevantServices;
417 CSemaphore *semOutbound;
418 int nMaxConnections;
419 int nMaxOutbound;
420 int nMaxFeeler;
421 std::atomic<int> nBestHeight;
422 CClientUIInterface* clientInterface;
424 /** SipHasher seeds for deterministic randomness */
425 const uint64_t nSeed0, nSeed1;
427 /** flag for waking the message processor. */
428 bool fMsgProcWake;
430 std::condition_variable condMsgProc;
431 std::mutex mutexMsgProc;
432 std::atomic<bool> flagInterruptMsgProc;
434 CThreadInterrupt interruptNet;
436 std::thread threadDNSAddressSeed;
437 std::thread threadSocketHandler;
438 std::thread threadOpenAddedConnections;
439 std::thread threadOpenConnections;
440 std::thread threadMessageHandler;
442 extern std::unique_ptr<CConnman> g_connman;
443 void Discover(boost::thread_group& threadGroup);
444 void MapPort(bool fUseUPnP);
445 unsigned short GetListenPort();
446 bool BindListenPort(const CService &bindAddr, std::string& strError, bool fWhitelisted = false);
447 size_t SocketSendData(CNode *pnode);
449 struct CombinerAll
451 typedef bool result_type;
453 template<typename I>
454 bool operator()(I first, I last) const
456 while (first != last) {
457 if (!(*first)) return false;
458 ++first;
460 return true;
464 // Signals for message handling
465 struct CNodeSignals
467 boost::signals2::signal<bool (CNode*, CConnman&, std::atomic<bool>&), CombinerAll> ProcessMessages;
468 boost::signals2::signal<bool (CNode*, CConnman&, std::atomic<bool>&), CombinerAll> SendMessages;
469 boost::signals2::signal<void (CNode*, CConnman&)> InitializeNode;
470 boost::signals2::signal<void (NodeId, bool&)> FinalizeNode;
474 CNodeSignals& GetNodeSignals();
477 enum
479 LOCAL_NONE, // unknown
480 LOCAL_IF, // address a local interface listens on
481 LOCAL_BIND, // address explicit bound to
482 LOCAL_UPNP, // address reported by UPnP
483 LOCAL_MANUAL, // address explicitly specified (-externalip=)
485 LOCAL_MAX
488 bool IsPeerAddrLocalGood(CNode *pnode);
489 void AdvertiseLocal(CNode *pnode);
490 void SetLimited(enum Network net, bool fLimited = true);
491 bool IsLimited(enum Network net);
492 bool IsLimited(const CNetAddr& addr);
493 bool AddLocal(const CService& addr, int nScore = LOCAL_NONE);
494 bool AddLocal(const CNetAddr& addr, int nScore = LOCAL_NONE);
495 bool RemoveLocal(const CService& addr);
496 bool SeenLocal(const CService& addr);
497 bool IsLocal(const CService& addr);
498 bool GetLocal(CService &addr, const CNetAddr *paddrPeer = NULL);
499 bool IsReachable(enum Network net);
500 bool IsReachable(const CNetAddr &addr);
501 CAddress GetLocalAddress(const CNetAddr *paddrPeer, ServiceFlags nLocalServices);
504 extern bool fDiscover;
505 extern bool fListen;
506 extern bool fRelayTxes;
508 extern limitedmap<uint256, int64_t> mapAlreadyAskedFor;
510 /** Subversion as sent to the P2P network in `version` messages */
511 extern std::string strSubVersion;
513 struct LocalServiceInfo {
514 int nScore;
515 int nPort;
518 extern CCriticalSection cs_mapLocalHost;
519 extern std::map<CNetAddr, LocalServiceInfo> mapLocalHost;
520 typedef std::map<std::string, uint64_t> mapMsgCmdSize; //command, total bytes
522 class CNodeStats
524 public:
525 NodeId nodeid;
526 ServiceFlags nServices;
527 bool fRelayTxes;
528 int64_t nLastSend;
529 int64_t nLastRecv;
530 int64_t nTimeConnected;
531 int64_t nTimeOffset;
532 std::string addrName;
533 int nVersion;
534 std::string cleanSubVer;
535 bool fInbound;
536 int nStartingHeight;
537 uint64_t nSendBytes;
538 mapMsgCmdSize mapSendBytesPerMsgCmd;
539 uint64_t nRecvBytes;
540 mapMsgCmdSize mapRecvBytesPerMsgCmd;
541 bool fWhitelisted;
542 double dPingTime;
543 double dPingWait;
544 double dMinPing;
545 std::string addrLocal;
546 CAddress addr;
552 class CNetMessage {
553 private:
554 mutable CHash256 hasher;
555 mutable uint256 data_hash;
556 public:
557 bool in_data; // parsing header (false) or data (true)
559 CDataStream hdrbuf; // partially received header
560 CMessageHeader hdr; // complete header
561 unsigned int nHdrPos;
563 CDataStream vRecv; // received message data
564 unsigned int nDataPos;
566 int64_t nTime; // time (in microseconds) of message receipt.
568 CNetMessage(const CMessageHeader::MessageStartChars& pchMessageStartIn, int nTypeIn, int nVersionIn) : hdrbuf(nTypeIn, nVersionIn), hdr(pchMessageStartIn), vRecv(nTypeIn, nVersionIn) {
569 hdrbuf.resize(24);
570 in_data = false;
571 nHdrPos = 0;
572 nDataPos = 0;
573 nTime = 0;
576 bool complete() const
578 if (!in_data)
579 return false;
580 return (hdr.nMessageSize == nDataPos);
583 const uint256& GetMessageHash() const;
585 void SetVersion(int nVersionIn)
587 hdrbuf.SetVersion(nVersionIn);
588 vRecv.SetVersion(nVersionIn);
591 int readHeader(const char *pch, unsigned int nBytes);
592 int readData(const char *pch, unsigned int nBytes);
596 /** Information about a peer */
597 class CNode
599 friend class CConnman;
600 public:
601 // socket
602 ServiceFlags nServices;
603 ServiceFlags nServicesExpected;
604 SOCKET hSocket;
605 size_t nSendSize; // total size of all vSendMsg entries
606 size_t nSendOffset; // offset inside the first vSendMsg already sent
607 uint64_t nSendBytes;
608 std::deque<std::vector<unsigned char>> vSendMsg;
609 CCriticalSection cs_vSend;
611 CCriticalSection cs_vProcessMsg;
612 std::list<CNetMessage> vProcessMsg;
613 size_t nProcessQueueSize;
615 std::deque<CInv> vRecvGetData;
616 std::list<CNetMessage> vRecvMsg;
617 CCriticalSection cs_vRecvMsg;
618 uint64_t nRecvBytes;
619 std::atomic<int> nRecvVersion;
621 int64_t nLastSend;
622 int64_t nLastRecv;
623 int64_t nTimeConnected;
624 int64_t nTimeOffset;
625 const CAddress addr;
626 std::string addrName;
627 CService addrLocal;
628 int nVersion;
629 // strSubVer is whatever byte array we read from the wire. However, this field is intended
630 // to be printed out, displayed to humans in various forms and so on. So we sanitize it and
631 // store the sanitized version in cleanSubVer. The original should be used when dealing with
632 // the network or wire types and the cleaned string used when displayed or logged.
633 std::string strSubVer, cleanSubVer;
634 bool fWhitelisted; // This peer can bypass DoS banning.
635 bool fFeeler; // If true this node is being used as a short lived feeler.
636 bool fOneShot;
637 bool fClient;
638 const bool fInbound;
639 bool fSuccessfullyConnected;
640 std::atomic_bool fDisconnect;
641 // We use fRelayTxes for two purposes -
642 // a) it allows us to not relay tx invs before receiving the peer's version message
643 // b) the peer may tell us in its version message that we should not relay tx invs
644 // unless it loads a bloom filter.
645 bool fRelayTxes; //protected by cs_filter
646 bool fSentAddr;
647 CSemaphoreGrant grantOutbound;
648 CCriticalSection cs_filter;
649 CBloomFilter* pfilter;
650 int nRefCount;
651 const NodeId id;
653 const uint64_t nKeyedNetGroup;
654 std::atomic_bool fPauseRecv;
655 protected:
657 mapMsgCmdSize mapSendBytesPerMsgCmd;
658 mapMsgCmdSize mapRecvBytesPerMsgCmd;
660 public:
661 uint256 hashContinue;
662 int nStartingHeight;
664 // flood relay
665 std::vector<CAddress> vAddrToSend;
666 CRollingBloomFilter addrKnown;
667 bool fGetAddr;
668 std::set<uint256> setKnown;
669 int64_t nNextAddrSend;
670 int64_t nNextLocalAddrSend;
672 // inventory based relay
673 CRollingBloomFilter filterInventoryKnown;
674 // Set of transaction ids we still have to announce.
675 // They are sorted by the mempool before relay, so the order is not important.
676 std::set<uint256> setInventoryTxToSend;
677 // List of block ids we still have announce.
678 // There is no final sorting before sending, as they are always sent immediately
679 // and in the order requested.
680 std::vector<uint256> vInventoryBlockToSend;
681 CCriticalSection cs_inventory;
682 std::set<uint256> setAskFor;
683 std::multimap<int64_t, CInv> mapAskFor;
684 int64_t nNextInvSend;
685 // Used for headers announcements - unfiltered blocks to relay
686 // Also protected by cs_inventory
687 std::vector<uint256> vBlockHashesToAnnounce;
688 // Used for BIP35 mempool sending, also protected by cs_inventory
689 bool fSendMempool;
691 // Last time a "MEMPOOL" request was serviced.
692 std::atomic<int64_t> timeLastMempoolReq;
694 // Block and TXN accept times
695 std::atomic<int64_t> nLastBlockTime;
696 std::atomic<int64_t> nLastTXTime;
698 // Ping time measurement:
699 // The pong reply we're expecting, or 0 if no pong expected.
700 uint64_t nPingNonceSent;
701 // Time (in usec) the last ping was sent, or 0 if no ping was ever sent.
702 int64_t nPingUsecStart;
703 // Last measured round-trip time.
704 int64_t nPingUsecTime;
705 // Best measured round-trip time.
706 int64_t nMinPingUsecTime;
707 // Whether a ping is requested.
708 bool fPingQueued;
709 // Minimum fee rate with which to filter inv's to this node
710 CAmount minFeeFilter;
711 CCriticalSection cs_feeFilter;
712 CAmount lastSentFeeFilter;
713 int64_t nextSendTimeFeeFilter;
715 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);
716 ~CNode();
718 private:
719 CNode(const CNode&);
720 void operator=(const CNode&);
723 const uint64_t nLocalHostNonce;
724 // Services offered to this peer
725 const ServiceFlags nLocalServices;
726 const int nMyStartingHeight;
727 int nSendVersion;
728 public:
730 NodeId GetId() const {
731 return id;
734 uint64_t GetLocalNonce() const {
735 return nLocalHostNonce;
738 int GetMyStartingHeight() const {
739 return nMyStartingHeight;
742 int GetRefCount()
744 assert(nRefCount >= 0);
745 return nRefCount;
748 // requires LOCK(cs_vRecvMsg)
749 bool ReceiveMsgBytes(const char *pch, unsigned int nBytes, bool& complete);
751 void SetRecvVersion(int nVersionIn)
753 nRecvVersion = nVersionIn;
755 int GetRecvVersion()
757 return nRecvVersion;
759 void SetSendVersion(int nVersionIn)
761 // Send version may only be changed in the version message, and
762 // only one version message is allowed per session. We can therefore
763 // treat this value as const and even atomic as long as it's only used
764 // once the handshake is complete. Any attempt to set this twice is an
765 // error.
766 assert(nSendVersion == 0);
767 nSendVersion = nVersionIn;
770 int GetSendVersion() const
772 // The send version should always be explicitly set to
773 // INIT_PROTO_VERSION rather than using this value until the handshake
774 // is complete.
775 assert(nSendVersion != 0);
776 return nSendVersion;
779 CNode* AddRef()
781 nRefCount++;
782 return this;
785 void Release()
787 nRefCount--;
792 void AddAddressKnown(const CAddress& _addr)
794 addrKnown.insert(_addr.GetKey());
797 void PushAddress(const CAddress& _addr, FastRandomContext &insecure_rand)
799 // Known checking here is only to save space from duplicates.
800 // SendMessages will filter it again for knowns that were added
801 // after addresses were pushed.
802 if (_addr.IsValid() && !addrKnown.contains(_addr.GetKey())) {
803 if (vAddrToSend.size() >= MAX_ADDR_TO_SEND) {
804 vAddrToSend[insecure_rand.rand32() % vAddrToSend.size()] = _addr;
805 } else {
806 vAddrToSend.push_back(_addr);
812 void AddInventoryKnown(const CInv& inv)
815 LOCK(cs_inventory);
816 filterInventoryKnown.insert(inv.hash);
820 void PushInventory(const CInv& inv)
822 LOCK(cs_inventory);
823 if (inv.type == MSG_TX) {
824 if (!filterInventoryKnown.contains(inv.hash)) {
825 setInventoryTxToSend.insert(inv.hash);
827 } else if (inv.type == MSG_BLOCK) {
828 vInventoryBlockToSend.push_back(inv.hash);
832 void PushBlockHash(const uint256 &hash)
834 LOCK(cs_inventory);
835 vBlockHashesToAnnounce.push_back(hash);
838 void AskFor(const CInv& inv);
840 void CloseSocketDisconnect();
842 void copyStats(CNodeStats &stats);
844 ServiceFlags GetLocalServices() const
846 return nLocalServices;
854 /** Return a timestamp in the future (in microseconds) for exponentially distributed events. */
855 int64_t PoissonNextSend(int64_t nNow, int average_interval_seconds);
857 #endif // BITCOIN_NET_H