net: rework the way that the messagehandler sleeps
[bitcoinplatinum.git] / src / net.h
blob4fc41bddac602083f73b872101ba0a64f3c78581
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 std::deque<CInv> vRecvGetData;
612 std::list<CNetMessage> vRecvMsg;
613 CCriticalSection cs_vRecvMsg;
614 uint64_t nRecvBytes;
615 std::atomic<int> nRecvVersion;
617 int64_t nLastSend;
618 int64_t nLastRecv;
619 int64_t nTimeConnected;
620 int64_t nTimeOffset;
621 const CAddress addr;
622 std::string addrName;
623 CService addrLocal;
624 int nVersion;
625 // strSubVer is whatever byte array we read from the wire. However, this field is intended
626 // to be printed out, displayed to humans in various forms and so on. So we sanitize it and
627 // store the sanitized version in cleanSubVer. The original should be used when dealing with
628 // the network or wire types and the cleaned string used when displayed or logged.
629 std::string strSubVer, cleanSubVer;
630 bool fWhitelisted; // This peer can bypass DoS banning.
631 bool fFeeler; // If true this node is being used as a short lived feeler.
632 bool fOneShot;
633 bool fClient;
634 const bool fInbound;
635 bool fSuccessfullyConnected;
636 std::atomic_bool fDisconnect;
637 // We use fRelayTxes for two purposes -
638 // a) it allows us to not relay tx invs before receiving the peer's version message
639 // b) the peer may tell us in its version message that we should not relay tx invs
640 // unless it loads a bloom filter.
641 bool fRelayTxes; //protected by cs_filter
642 bool fSentAddr;
643 CSemaphoreGrant grantOutbound;
644 CCriticalSection cs_filter;
645 CBloomFilter* pfilter;
646 int nRefCount;
647 const NodeId id;
649 const uint64_t nKeyedNetGroup;
650 protected:
652 mapMsgCmdSize mapSendBytesPerMsgCmd;
653 mapMsgCmdSize mapRecvBytesPerMsgCmd;
655 public:
656 uint256 hashContinue;
657 int nStartingHeight;
659 // flood relay
660 std::vector<CAddress> vAddrToSend;
661 CRollingBloomFilter addrKnown;
662 bool fGetAddr;
663 std::set<uint256> setKnown;
664 int64_t nNextAddrSend;
665 int64_t nNextLocalAddrSend;
667 // inventory based relay
668 CRollingBloomFilter filterInventoryKnown;
669 // Set of transaction ids we still have to announce.
670 // They are sorted by the mempool before relay, so the order is not important.
671 std::set<uint256> setInventoryTxToSend;
672 // List of block ids we still have announce.
673 // There is no final sorting before sending, as they are always sent immediately
674 // and in the order requested.
675 std::vector<uint256> vInventoryBlockToSend;
676 CCriticalSection cs_inventory;
677 std::set<uint256> setAskFor;
678 std::multimap<int64_t, CInv> mapAskFor;
679 int64_t nNextInvSend;
680 // Used for headers announcements - unfiltered blocks to relay
681 // Also protected by cs_inventory
682 std::vector<uint256> vBlockHashesToAnnounce;
683 // Used for BIP35 mempool sending, also protected by cs_inventory
684 bool fSendMempool;
686 // Last time a "MEMPOOL" request was serviced.
687 std::atomic<int64_t> timeLastMempoolReq;
689 // Block and TXN accept times
690 std::atomic<int64_t> nLastBlockTime;
691 std::atomic<int64_t> nLastTXTime;
693 // Ping time measurement:
694 // The pong reply we're expecting, or 0 if no pong expected.
695 uint64_t nPingNonceSent;
696 // Time (in usec) the last ping was sent, or 0 if no ping was ever sent.
697 int64_t nPingUsecStart;
698 // Last measured round-trip time.
699 int64_t nPingUsecTime;
700 // Best measured round-trip time.
701 int64_t nMinPingUsecTime;
702 // Whether a ping is requested.
703 bool fPingQueued;
704 // Minimum fee rate with which to filter inv's to this node
705 CAmount minFeeFilter;
706 CCriticalSection cs_feeFilter;
707 CAmount lastSentFeeFilter;
708 int64_t nextSendTimeFeeFilter;
710 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);
711 ~CNode();
713 private:
714 CNode(const CNode&);
715 void operator=(const CNode&);
718 const uint64_t nLocalHostNonce;
719 // Services offered to this peer
720 const ServiceFlags nLocalServices;
721 const int nMyStartingHeight;
722 int nSendVersion;
723 public:
725 NodeId GetId() const {
726 return id;
729 uint64_t GetLocalNonce() const {
730 return nLocalHostNonce;
733 int GetMyStartingHeight() const {
734 return nMyStartingHeight;
737 int GetRefCount()
739 assert(nRefCount >= 0);
740 return nRefCount;
743 // requires LOCK(cs_vRecvMsg)
744 unsigned int GetTotalRecvSize()
746 unsigned int total = 0;
747 BOOST_FOREACH(const CNetMessage &msg, vRecvMsg)
748 total += msg.vRecv.size() + 24;
749 return total;
752 // requires LOCK(cs_vRecvMsg)
753 bool ReceiveMsgBytes(const char *pch, unsigned int nBytes, bool& complete);
755 void SetRecvVersion(int nVersionIn)
757 nRecvVersion = nVersionIn;
759 int GetRecvVersion()
761 return nRecvVersion;
763 void SetSendVersion(int nVersionIn)
765 // Send version may only be changed in the version message, and
766 // only one version message is allowed per session. We can therefore
767 // treat this value as const and even atomic as long as it's only used
768 // once the handshake is complete. Any attempt to set this twice is an
769 // error.
770 assert(nSendVersion == 0);
771 nSendVersion = nVersionIn;
774 int GetSendVersion() const
776 // The send version should always be explicitly set to
777 // INIT_PROTO_VERSION rather than using this value until the handshake
778 // is complete.
779 assert(nSendVersion != 0);
780 return nSendVersion;
783 CNode* AddRef()
785 nRefCount++;
786 return this;
789 void Release()
791 nRefCount--;
796 void AddAddressKnown(const CAddress& _addr)
798 addrKnown.insert(_addr.GetKey());
801 void PushAddress(const CAddress& _addr, FastRandomContext &insecure_rand)
803 // Known checking here is only to save space from duplicates.
804 // SendMessages will filter it again for knowns that were added
805 // after addresses were pushed.
806 if (_addr.IsValid() && !addrKnown.contains(_addr.GetKey())) {
807 if (vAddrToSend.size() >= MAX_ADDR_TO_SEND) {
808 vAddrToSend[insecure_rand.rand32() % vAddrToSend.size()] = _addr;
809 } else {
810 vAddrToSend.push_back(_addr);
816 void AddInventoryKnown(const CInv& inv)
819 LOCK(cs_inventory);
820 filterInventoryKnown.insert(inv.hash);
824 void PushInventory(const CInv& inv)
826 LOCK(cs_inventory);
827 if (inv.type == MSG_TX) {
828 if (!filterInventoryKnown.contains(inv.hash)) {
829 setInventoryTxToSend.insert(inv.hash);
831 } else if (inv.type == MSG_BLOCK) {
832 vInventoryBlockToSend.push_back(inv.hash);
836 void PushBlockHash(const uint256 &hash)
838 LOCK(cs_inventory);
839 vBlockHashesToAnnounce.push_back(hash);
842 void AskFor(const CInv& inv);
844 void CloseSocketDisconnect();
846 void copyStats(CNodeStats &stats);
848 ServiceFlags GetLocalServices() const
850 return nLocalServices;
858 /** Return a timestamp in the future (in microseconds) for exponentially distributed events. */
859 int64_t PoissonNextSend(int64_t nNow, int average_interval_seconds);
861 #endif // BITCOIN_NET_H