Remove unused variable int64_t nEnd
[bitcoinplatinum.git] / src / net.h
blobb9a11c62f2123f63eaae4e03ed25e21cb113347d
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
36 #include <boost/signals2/signal.hpp>
38 class CScheduler;
39 class CNode;
41 namespace boost {
42 class thread_group;
43 } // namespace boost
45 /** Time between pings automatically sent out for latency probing and keepalive (in seconds). */
46 static const int PING_INTERVAL = 2 * 60;
47 /** Time after which to disconnect, after waiting for a ping response (or inactivity). */
48 static const int TIMEOUT_INTERVAL = 20 * 60;
49 /** Run the feeler connection loop once every 2 minutes or 120 seconds. **/
50 static const int FEELER_INTERVAL = 120;
51 /** The maximum number of entries in an 'inv' protocol message */
52 static const unsigned int MAX_INV_SZ = 50000;
53 /** The maximum number of new addresses to accumulate before announcing. */
54 static const unsigned int MAX_ADDR_TO_SEND = 1000;
55 /** Maximum length of incoming protocol messages (no message over 4 MB is currently acceptable). */
56 static const unsigned int MAX_PROTOCOL_MESSAGE_LENGTH = 4 * 1000 * 1000;
57 /** Maximum length of strSubVer in `version` message */
58 static const unsigned int MAX_SUBVERSION_LENGTH = 256;
59 /** Maximum number of automatic outgoing nodes */
60 static const int MAX_OUTBOUND_CONNECTIONS = 8;
61 /** Maximum number of addnode outgoing nodes */
62 static const int MAX_ADDNODE_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 int64_t NodeId;
95 struct AddedNodeInfo
97 std::string strAddedNode;
98 CService resolvedAddress;
99 bool fConnected;
100 bool fInbound;
103 class CNodeStats;
104 class CClientUIInterface;
106 struct CSerializedNetMsg
108 CSerializedNetMsg() = default;
109 CSerializedNetMsg(CSerializedNetMsg&&) = default;
110 CSerializedNetMsg& operator=(CSerializedNetMsg&&) = default;
111 // No copying, only moves.
112 CSerializedNetMsg(const CSerializedNetMsg& msg) = delete;
113 CSerializedNetMsg& operator=(const CSerializedNetMsg&) = delete;
115 std::vector<unsigned char> data;
116 std::string command;
120 class CConnman
122 public:
124 enum NumConnections {
125 CONNECTIONS_NONE = 0,
126 CONNECTIONS_IN = (1U << 0),
127 CONNECTIONS_OUT = (1U << 1),
128 CONNECTIONS_ALL = (CONNECTIONS_IN | CONNECTIONS_OUT),
131 struct Options
133 ServiceFlags nLocalServices = NODE_NONE;
134 ServiceFlags nRelevantServices = NODE_NONE;
135 int nMaxConnections = 0;
136 int nMaxOutbound = 0;
137 int nMaxAddnode = 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;
145 std::vector<std::string> vSeedNodes;
146 std::vector<CSubNet> vWhitelistedRange;
147 std::vector<CService> vBinds, vWhiteBinds;
149 CConnman(uint64_t seed0, uint64_t seed1);
150 ~CConnman();
151 bool Start(CScheduler& scheduler, Options options);
152 void Stop();
153 void Interrupt();
154 bool GetNetworkActive() const { return fNetworkActive; };
155 void SetNetworkActive(bool active);
156 bool OpenNetworkConnection(const CAddress& addrConnect, bool fCountFailure, CSemaphoreGrant *grantOutbound = NULL, const char *strDest = NULL, bool fOneShot = false, bool fFeeler = false, bool fAddnode = false);
157 bool CheckIncomingNonce(uint64_t nonce);
159 bool ForNode(NodeId id, std::function<bool(CNode* pnode)> func);
161 void PushMessage(CNode* pnode, CSerializedNetMsg&& msg);
163 template<typename Callable>
164 void ForEachNode(Callable&& func)
166 LOCK(cs_vNodes);
167 for (auto&& node : vNodes) {
168 if (NodeFullyConnected(node))
169 func(node);
173 template<typename Callable>
174 void ForEachNode(Callable&& func) const
176 LOCK(cs_vNodes);
177 for (auto&& node : vNodes) {
178 if (NodeFullyConnected(node))
179 func(node);
183 template<typename Callable, typename CallableAfter>
184 void ForEachNodeThen(Callable&& pre, CallableAfter&& post)
186 LOCK(cs_vNodes);
187 for (auto&& node : vNodes) {
188 if (NodeFullyConnected(node))
189 pre(node);
191 post();
194 template<typename Callable, typename CallableAfter>
195 void ForEachNodeThen(Callable&& pre, CallableAfter&& post) const
197 LOCK(cs_vNodes);
198 for (auto&& node : vNodes) {
199 if (NodeFullyConnected(node))
200 pre(node);
202 post();
205 // Addrman functions
206 size_t GetAddressCount() const;
207 void SetServices(const CService &addr, ServiceFlags nServices);
208 void MarkAddressGood(const CAddress& addr);
209 void AddNewAddresses(const std::vector<CAddress>& vAddr, const CAddress& addrFrom, int64_t nTimePenalty = 0);
210 std::vector<CAddress> GetAddresses();
212 // Denial-of-service detection/prevention
213 // The idea is to detect peers that are behaving
214 // badly and disconnect/ban them, but do it in a
215 // one-coding-mistake-won't-shatter-the-entire-network
216 // way.
217 // IMPORTANT: There should be nothing I can give a
218 // node that it will forward on that will make that
219 // node's peers drop it. If there is, an attacker
220 // can isolate a node and/or try to split the network.
221 // Dropping a node for sending stuff that is invalid
222 // now but might be valid in a later version is also
223 // dangerous, because it can cause a network split
224 // between nodes running old code and nodes running
225 // new code.
226 void Ban(const CNetAddr& netAddr, const BanReason& reason, int64_t bantimeoffset = 0, bool sinceUnixEpoch = false);
227 void Ban(const CSubNet& subNet, const BanReason& reason, int64_t bantimeoffset = 0, bool sinceUnixEpoch = false);
228 void ClearBanned(); // needed for unit testing
229 bool IsBanned(CNetAddr ip);
230 bool IsBanned(CSubNet subnet);
231 bool Unban(const CNetAddr &ip);
232 bool Unban(const CSubNet &ip);
233 void GetBanned(banmap_t &banmap);
234 void SetBanned(const banmap_t &banmap);
236 bool AddNode(const std::string& node);
237 bool RemoveAddedNode(const std::string& node);
238 std::vector<AddedNodeInfo> GetAddedNodeInfo();
240 size_t GetNodeCount(NumConnections num);
241 void GetNodeStats(std::vector<CNodeStats>& vstats);
242 bool DisconnectNode(const std::string& node);
243 bool DisconnectNode(NodeId id);
245 unsigned int GetSendBufferSize() const;
247 ServiceFlags GetLocalServices() const;
249 //!set the max outbound target in bytes
250 void SetMaxOutboundTarget(uint64_t limit);
251 uint64_t GetMaxOutboundTarget();
253 //!set the timeframe for the max outbound target
254 void SetMaxOutboundTimeframe(uint64_t timeframe);
255 uint64_t GetMaxOutboundTimeframe();
257 //!check if the outbound target is reached
258 // if param historicalBlockServingLimit is set true, the function will
259 // response true if the limit for serving historical blocks has been reached
260 bool OutboundTargetReached(bool historicalBlockServingLimit);
262 //!response the bytes left in the current max outbound cycle
263 // in case of no limit, it will always response 0
264 uint64_t GetOutboundTargetBytesLeft();
266 //!response the time in second left in the current max outbound cycle
267 // in case of no limit, it will always response 0
268 uint64_t GetMaxOutboundTimeLeftInCycle();
270 uint64_t GetTotalBytesRecv();
271 uint64_t GetTotalBytesSent();
273 void SetBestHeight(int height);
274 int GetBestHeight() const;
276 /** Get a unique deterministic randomizer. */
277 CSipHasher GetDeterministicRandomizer(uint64_t id) const;
279 unsigned int GetReceiveFloodSize() const;
281 void WakeMessageHandler();
282 private:
283 struct ListenSocket {
284 SOCKET socket;
285 bool whitelisted;
287 ListenSocket(SOCKET socket_, bool whitelisted_) : socket(socket_), whitelisted(whitelisted_) {}
290 bool BindListenPort(const CService &bindAddr, std::string& strError, bool fWhitelisted = false);
291 bool Bind(const CService &addr, unsigned int flags);
292 bool InitBinds(const std::vector<CService>& binds, const std::vector<CService>& whiteBinds);
293 void ThreadOpenAddedConnections();
294 void AddOneShot(const std::string& strDest);
295 void ProcessOneShot();
296 void ThreadOpenConnections();
297 void ThreadMessageHandler();
298 void AcceptConnection(const ListenSocket& hListenSocket);
299 void ThreadSocketHandler();
300 void ThreadDNSAddressSeed();
302 uint64_t CalculateKeyedNetGroup(const CAddress& ad) const;
304 CNode* FindNode(const CNetAddr& ip);
305 CNode* FindNode(const CSubNet& subNet);
306 CNode* FindNode(const std::string& addrName);
307 CNode* FindNode(const CService& addr);
309 bool AttemptToEvictConnection();
310 CNode* ConnectNode(CAddress addrConnect, const char *pszDest, bool fCountFailure);
311 bool IsWhitelistedRange(const CNetAddr &addr);
313 void DeleteNode(CNode* pnode);
315 NodeId GetNewNodeId();
317 size_t SocketSendData(CNode *pnode) const;
318 //!check is the banlist has unwritten changes
319 bool BannedSetIsDirty();
320 //!set the "dirty" flag for the banlist
321 void SetBannedSetDirty(bool dirty=true);
322 //!clean unused entries (if bantime has expired)
323 void SweepBanned();
324 void DumpAddresses();
325 void DumpData();
326 void DumpBanlist();
328 // Network stats
329 void RecordBytesRecv(uint64_t bytes);
330 void RecordBytesSent(uint64_t bytes);
332 // Whether the node should be passed out in ForEach* callbacks
333 static bool NodeFullyConnected(const CNode* pnode);
335 // Network usage totals
336 CCriticalSection cs_totalBytesRecv;
337 CCriticalSection cs_totalBytesSent;
338 uint64_t nTotalBytesRecv;
339 uint64_t nTotalBytesSent;
341 // outbound limit & stats
342 uint64_t nMaxOutboundTotalBytesSentInCycle;
343 uint64_t nMaxOutboundCycleStartTime;
344 uint64_t nMaxOutboundLimit;
345 uint64_t nMaxOutboundTimeframe;
347 // Whitelisted ranges. Any node connecting from these is automatically
348 // whitelisted (as well as those connecting to whitelisted binds).
349 std::vector<CSubNet> vWhitelistedRange;
351 unsigned int nSendBufferMaxSize;
352 unsigned int nReceiveFloodSize;
354 std::vector<ListenSocket> vhListenSocket;
355 std::atomic<bool> fNetworkActive;
356 banmap_t setBanned;
357 CCriticalSection cs_setBanned;
358 bool setBannedIsDirty;
359 bool fAddressesInitialized;
360 CAddrMan addrman;
361 std::deque<std::string> vOneShots;
362 CCriticalSection cs_vOneShots;
363 std::vector<std::string> vAddedNodes;
364 CCriticalSection cs_vAddedNodes;
365 std::vector<CNode*> vNodes;
366 std::list<CNode*> vNodesDisconnected;
367 mutable CCriticalSection cs_vNodes;
368 std::atomic<NodeId> nLastNodeId;
370 /** Services this instance offers */
371 ServiceFlags nLocalServices;
373 /** Services this instance cares about */
374 ServiceFlags nRelevantServices;
376 CSemaphore *semOutbound;
377 CSemaphore *semAddnode;
378 int nMaxConnections;
379 int nMaxOutbound;
380 int nMaxAddnode;
381 int nMaxFeeler;
382 std::atomic<int> nBestHeight;
383 CClientUIInterface* clientInterface;
385 /** SipHasher seeds for deterministic randomness */
386 const uint64_t nSeed0, nSeed1;
388 /** flag for waking the message processor. */
389 bool fMsgProcWake;
391 std::condition_variable condMsgProc;
392 std::mutex mutexMsgProc;
393 std::atomic<bool> flagInterruptMsgProc;
395 CThreadInterrupt interruptNet;
397 std::thread threadDNSAddressSeed;
398 std::thread threadSocketHandler;
399 std::thread threadOpenAddedConnections;
400 std::thread threadOpenConnections;
401 std::thread threadMessageHandler;
403 extern std::unique_ptr<CConnman> g_connman;
404 void Discover(boost::thread_group& threadGroup);
405 void MapPort(bool fUseUPnP);
406 unsigned short GetListenPort();
407 bool BindListenPort(const CService &bindAddr, std::string& strError, bool fWhitelisted = false);
409 struct CombinerAll
411 typedef bool result_type;
413 template<typename I>
414 bool operator()(I first, I last) const
416 while (first != last) {
417 if (!(*first)) return false;
418 ++first;
420 return true;
424 // Signals for message handling
425 struct CNodeSignals
427 boost::signals2::signal<bool (CNode*, CConnman&, std::atomic<bool>&), CombinerAll> ProcessMessages;
428 boost::signals2::signal<bool (CNode*, CConnman&, std::atomic<bool>&), CombinerAll> SendMessages;
429 boost::signals2::signal<void (CNode*, CConnman&)> InitializeNode;
430 boost::signals2::signal<void (NodeId, bool&)> FinalizeNode;
434 CNodeSignals& GetNodeSignals();
437 enum
439 LOCAL_NONE, // unknown
440 LOCAL_IF, // address a local interface listens on
441 LOCAL_BIND, // address explicit bound to
442 LOCAL_UPNP, // address reported by UPnP
443 LOCAL_MANUAL, // address explicitly specified (-externalip=)
445 LOCAL_MAX
448 bool IsPeerAddrLocalGood(CNode *pnode);
449 void AdvertiseLocal(CNode *pnode);
450 void SetLimited(enum Network net, bool fLimited = true);
451 bool IsLimited(enum Network net);
452 bool IsLimited(const CNetAddr& addr);
453 bool AddLocal(const CService& addr, int nScore = LOCAL_NONE);
454 bool AddLocal(const CNetAddr& addr, int nScore = LOCAL_NONE);
455 bool RemoveLocal(const CService& addr);
456 bool SeenLocal(const CService& addr);
457 bool IsLocal(const CService& addr);
458 bool GetLocal(CService &addr, const CNetAddr *paddrPeer = NULL);
459 bool IsReachable(enum Network net);
460 bool IsReachable(const CNetAddr &addr);
461 CAddress GetLocalAddress(const CNetAddr *paddrPeer, ServiceFlags nLocalServices);
464 extern bool fDiscover;
465 extern bool fListen;
466 extern bool fRelayTxes;
468 extern limitedmap<uint256, int64_t> mapAlreadyAskedFor;
470 /** Subversion as sent to the P2P network in `version` messages */
471 extern std::string strSubVersion;
473 struct LocalServiceInfo {
474 int nScore;
475 int nPort;
478 extern CCriticalSection cs_mapLocalHost;
479 extern std::map<CNetAddr, LocalServiceInfo> mapLocalHost;
480 typedef std::map<std::string, uint64_t> mapMsgCmdSize; //command, total bytes
482 class CNodeStats
484 public:
485 NodeId nodeid;
486 ServiceFlags nServices;
487 bool fRelayTxes;
488 int64_t nLastSend;
489 int64_t nLastRecv;
490 int64_t nTimeConnected;
491 int64_t nTimeOffset;
492 std::string addrName;
493 int nVersion;
494 std::string cleanSubVer;
495 bool fInbound;
496 bool fAddnode;
497 int nStartingHeight;
498 uint64_t nSendBytes;
499 mapMsgCmdSize mapSendBytesPerMsgCmd;
500 uint64_t nRecvBytes;
501 mapMsgCmdSize mapRecvBytesPerMsgCmd;
502 bool fWhitelisted;
503 double dPingTime;
504 double dPingWait;
505 double dMinPing;
506 // Our address, as reported by the peer
507 std::string addrLocal;
508 // Address of this peer
509 CAddress addr;
510 // Bind address of our side of the connection
511 CAddress addrBind;
517 class CNetMessage {
518 private:
519 mutable CHash256 hasher;
520 mutable uint256 data_hash;
521 public:
522 bool in_data; // parsing header (false) or data (true)
524 CDataStream hdrbuf; // partially received header
525 CMessageHeader hdr; // complete header
526 unsigned int nHdrPos;
528 CDataStream vRecv; // received message data
529 unsigned int nDataPos;
531 int64_t nTime; // time (in microseconds) of message receipt.
533 CNetMessage(const CMessageHeader::MessageStartChars& pchMessageStartIn, int nTypeIn, int nVersionIn) : hdrbuf(nTypeIn, nVersionIn), hdr(pchMessageStartIn), vRecv(nTypeIn, nVersionIn) {
534 hdrbuf.resize(24);
535 in_data = false;
536 nHdrPos = 0;
537 nDataPos = 0;
538 nTime = 0;
541 bool complete() const
543 if (!in_data)
544 return false;
545 return (hdr.nMessageSize == nDataPos);
548 const uint256& GetMessageHash() const;
550 void SetVersion(int nVersionIn)
552 hdrbuf.SetVersion(nVersionIn);
553 vRecv.SetVersion(nVersionIn);
556 int readHeader(const char *pch, unsigned int nBytes);
557 int readData(const char *pch, unsigned int nBytes);
561 /** Information about a peer */
562 class CNode
564 friend class CConnman;
565 public:
566 // socket
567 std::atomic<ServiceFlags> nServices;
568 ServiceFlags nServicesExpected;
569 SOCKET hSocket;
570 size_t nSendSize; // total size of all vSendMsg entries
571 size_t nSendOffset; // offset inside the first vSendMsg already sent
572 uint64_t nSendBytes;
573 std::deque<std::vector<unsigned char>> vSendMsg;
574 CCriticalSection cs_vSend;
575 CCriticalSection cs_hSocket;
576 CCriticalSection cs_vRecv;
578 CCriticalSection cs_vProcessMsg;
579 std::list<CNetMessage> vProcessMsg;
580 size_t nProcessQueueSize;
582 CCriticalSection cs_sendProcessing;
584 std::deque<CInv> vRecvGetData;
585 uint64_t nRecvBytes;
586 std::atomic<int> nRecvVersion;
588 std::atomic<int64_t> nLastSend;
589 std::atomic<int64_t> nLastRecv;
590 const int64_t nTimeConnected;
591 std::atomic<int64_t> nTimeOffset;
592 // Address of this peer
593 const CAddress addr;
594 // Bind address of our side of the connection
595 const CAddress addrBind;
596 std::atomic<int> nVersion;
597 // strSubVer is whatever byte array we read from the wire. However, this field is intended
598 // to be printed out, displayed to humans in various forms and so on. So we sanitize it and
599 // store the sanitized version in cleanSubVer. The original should be used when dealing with
600 // the network or wire types and the cleaned string used when displayed or logged.
601 std::string strSubVer, cleanSubVer;
602 CCriticalSection cs_SubVer; // used for both cleanSubVer and strSubVer
603 bool fWhitelisted; // This peer can bypass DoS banning.
604 bool fFeeler; // If true this node is being used as a short lived feeler.
605 bool fOneShot;
606 bool fAddnode;
607 bool fClient;
608 const bool fInbound;
609 std::atomic_bool fSuccessfullyConnected;
610 std::atomic_bool fDisconnect;
611 // We use fRelayTxes for two purposes -
612 // a) it allows us to not relay tx invs before receiving the peer's version message
613 // b) the peer may tell us in its version message that we should not relay tx invs
614 // unless it loads a bloom filter.
615 bool fRelayTxes; //protected by cs_filter
616 bool fSentAddr;
617 CSemaphoreGrant grantOutbound;
618 CCriticalSection cs_filter;
619 CBloomFilter* pfilter;
620 std::atomic<int> nRefCount;
622 const uint64_t nKeyedNetGroup;
623 std::atomic_bool fPauseRecv;
624 std::atomic_bool fPauseSend;
625 protected:
627 mapMsgCmdSize mapSendBytesPerMsgCmd;
628 mapMsgCmdSize mapRecvBytesPerMsgCmd;
630 public:
631 uint256 hashContinue;
632 std::atomic<int> nStartingHeight;
634 // flood relay
635 std::vector<CAddress> vAddrToSend;
636 CRollingBloomFilter addrKnown;
637 bool fGetAddr;
638 std::set<uint256> setKnown;
639 int64_t nNextAddrSend;
640 int64_t nNextLocalAddrSend;
642 // inventory based relay
643 CRollingBloomFilter filterInventoryKnown;
644 // Set of transaction ids we still have to announce.
645 // They are sorted by the mempool before relay, so the order is not important.
646 std::set<uint256> setInventoryTxToSend;
647 // List of block ids we still have announce.
648 // There is no final sorting before sending, as they are always sent immediately
649 // and in the order requested.
650 std::vector<uint256> vInventoryBlockToSend;
651 CCriticalSection cs_inventory;
652 std::set<uint256> setAskFor;
653 std::multimap<int64_t, CInv> mapAskFor;
654 int64_t nNextInvSend;
655 // Used for headers announcements - unfiltered blocks to relay
656 // Also protected by cs_inventory
657 std::vector<uint256> vBlockHashesToAnnounce;
658 // Used for BIP35 mempool sending, also protected by cs_inventory
659 bool fSendMempool;
661 // Last time a "MEMPOOL" request was serviced.
662 std::atomic<int64_t> timeLastMempoolReq;
664 // Block and TXN accept times
665 std::atomic<int64_t> nLastBlockTime;
666 std::atomic<int64_t> nLastTXTime;
668 // Ping time measurement:
669 // The pong reply we're expecting, or 0 if no pong expected.
670 std::atomic<uint64_t> nPingNonceSent;
671 // Time (in usec) the last ping was sent, or 0 if no ping was ever sent.
672 std::atomic<int64_t> nPingUsecStart;
673 // Last measured round-trip time.
674 std::atomic<int64_t> nPingUsecTime;
675 // Best measured round-trip time.
676 std::atomic<int64_t> nMinPingUsecTime;
677 // Whether a ping is requested.
678 std::atomic<bool> fPingQueued;
679 // Minimum fee rate with which to filter inv's to this node
680 CAmount minFeeFilter;
681 CCriticalSection cs_feeFilter;
682 CAmount lastSentFeeFilter;
683 int64_t nextSendTimeFeeFilter;
685 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);
686 ~CNode();
688 private:
689 CNode(const CNode&);
690 void operator=(const CNode&);
691 const NodeId id;
694 const uint64_t nLocalHostNonce;
695 // Services offered to this peer
696 const ServiceFlags nLocalServices;
697 const int nMyStartingHeight;
698 int nSendVersion;
699 std::list<CNetMessage> vRecvMsg; // Used only by SocketHandler thread
701 mutable CCriticalSection cs_addrName;
702 std::string addrName;
704 // Our address, as reported by the peer
705 CService addrLocal;
706 mutable CCriticalSection cs_addrLocal;
707 public:
709 NodeId GetId() const {
710 return id;
713 uint64_t GetLocalNonce() const {
714 return nLocalHostNonce;
717 int GetMyStartingHeight() const {
718 return nMyStartingHeight;
721 int GetRefCount() const
723 assert(nRefCount >= 0);
724 return nRefCount;
727 bool ReceiveMsgBytes(const char *pch, unsigned int nBytes, bool& complete);
729 void SetRecvVersion(int nVersionIn)
731 nRecvVersion = nVersionIn;
733 int GetRecvVersion() const
735 return nRecvVersion;
737 void SetSendVersion(int nVersionIn);
738 int GetSendVersion() const;
740 CService GetAddrLocal() const;
741 //! May not be called more than once
742 void SetAddrLocal(const CService& addrLocalIn);
744 CNode* AddRef()
746 nRefCount++;
747 return this;
750 void Release()
752 nRefCount--;
757 void AddAddressKnown(const CAddress& _addr)
759 addrKnown.insert(_addr.GetKey());
762 void PushAddress(const CAddress& _addr, FastRandomContext &insecure_rand)
764 // Known checking here is only to save space from duplicates.
765 // SendMessages will filter it again for knowns that were added
766 // after addresses were pushed.
767 if (_addr.IsValid() && !addrKnown.contains(_addr.GetKey())) {
768 if (vAddrToSend.size() >= MAX_ADDR_TO_SEND) {
769 vAddrToSend[insecure_rand.randrange(vAddrToSend.size())] = _addr;
770 } else {
771 vAddrToSend.push_back(_addr);
777 void AddInventoryKnown(const CInv& inv)
780 LOCK(cs_inventory);
781 filterInventoryKnown.insert(inv.hash);
785 void PushInventory(const CInv& inv)
787 LOCK(cs_inventory);
788 if (inv.type == MSG_TX) {
789 if (!filterInventoryKnown.contains(inv.hash)) {
790 setInventoryTxToSend.insert(inv.hash);
792 } else if (inv.type == MSG_BLOCK) {
793 vInventoryBlockToSend.push_back(inv.hash);
797 void PushBlockHash(const uint256 &hash)
799 LOCK(cs_inventory);
800 vBlockHashesToAnnounce.push_back(hash);
803 void AskFor(const CInv& inv);
805 void CloseSocketDisconnect();
807 void copyStats(CNodeStats &stats);
809 ServiceFlags GetLocalServices() const
811 return nLocalServices;
814 std::string GetAddrName() const;
815 //! Sets the addrName only if it was not previously set
816 void MaybeSetAddrName(const std::string& addrNameIn);
823 /** Return a timestamp in the future (in microseconds) for exponentially distributed events. */
824 int64_t PoissonNextSend(int64_t nNow, int average_interval_seconds);
826 #endif // BITCOIN_NET_H