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