net: correctly ban before the handshake is complete
[bitcoinplatinum.git] / src / net.h
blob38f8d82ceb306a617840553f8a03abea12dd1335
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 AddNewAddress(const CAddress& addr, const CAddress& addrFrom, int64_t nTimePenalty = 0);
211 void AddNewAddresses(const std::vector<CAddress>& vAddr, const CAddress& addrFrom, int64_t nTimePenalty = 0);
212 std::vector<CAddress> GetAddresses();
213 void AddressCurrentlyConnected(const CService& addr);
215 // Denial-of-service detection/prevention
216 // The idea is to detect peers that are behaving
217 // badly and disconnect/ban them, but do it in a
218 // one-coding-mistake-won't-shatter-the-entire-network
219 // way.
220 // IMPORTANT: There should be nothing I can give a
221 // node that it will forward on that will make that
222 // node's peers drop it. If there is, an attacker
223 // can isolate a node and/or try to split the network.
224 // Dropping a node for sending stuff that is invalid
225 // now but might be valid in a later version is also
226 // dangerous, because it can cause a network split
227 // between nodes running old code and nodes running
228 // new code.
229 void Ban(const CNetAddr& netAddr, const BanReason& reason, int64_t bantimeoffset = 0, bool sinceUnixEpoch = false);
230 void Ban(const CSubNet& subNet, const BanReason& reason, int64_t bantimeoffset = 0, bool sinceUnixEpoch = false);
231 void ClearBanned(); // needed for unit testing
232 bool IsBanned(CNetAddr ip);
233 bool IsBanned(CSubNet subnet);
234 bool Unban(const CNetAddr &ip);
235 bool Unban(const CSubNet &ip);
236 void GetBanned(banmap_t &banmap);
237 void SetBanned(const banmap_t &banmap);
239 void AddOneShot(const std::string& strDest);
241 bool AddNode(const std::string& node);
242 bool RemoveAddedNode(const std::string& node);
243 std::vector<AddedNodeInfo> GetAddedNodeInfo();
245 size_t GetNodeCount(NumConnections num);
246 void GetNodeStats(std::vector<CNodeStats>& vstats);
247 bool DisconnectNode(const std::string& node);
248 bool DisconnectNode(NodeId id);
250 unsigned int GetSendBufferSize() const;
252 void AddWhitelistedRange(const CSubNet &subnet);
254 ServiceFlags GetLocalServices() const;
256 //!set the max outbound target in bytes
257 void SetMaxOutboundTarget(uint64_t limit);
258 uint64_t GetMaxOutboundTarget();
260 //!set the timeframe for the max outbound target
261 void SetMaxOutboundTimeframe(uint64_t timeframe);
262 uint64_t GetMaxOutboundTimeframe();
264 //!check if the outbound target is reached
265 // if param historicalBlockServingLimit is set true, the function will
266 // response true if the limit for serving historical blocks has been reached
267 bool OutboundTargetReached(bool historicalBlockServingLimit);
269 //!response the bytes left in the current max outbound cycle
270 // in case of no limit, it will always response 0
271 uint64_t GetOutboundTargetBytesLeft();
273 //!response the time in second left in the current max outbound cycle
274 // in case of no limit, it will always response 0
275 uint64_t GetMaxOutboundTimeLeftInCycle();
277 uint64_t GetTotalBytesRecv();
278 uint64_t GetTotalBytesSent();
280 void SetBestHeight(int height);
281 int GetBestHeight() const;
283 /** Get a unique deterministic randomizer. */
284 CSipHasher GetDeterministicRandomizer(uint64_t id) const;
286 unsigned int GetReceiveFloodSize() const;
288 void WakeMessageHandler();
289 private:
290 struct ListenSocket {
291 SOCKET socket;
292 bool whitelisted;
294 ListenSocket(SOCKET socket_, bool whitelisted_) : socket(socket_), whitelisted(whitelisted_) {}
297 void ThreadOpenAddedConnections();
298 void ProcessOneShot();
299 void ThreadOpenConnections();
300 void ThreadMessageHandler();
301 void AcceptConnection(const ListenSocket& hListenSocket);
302 void ThreadSocketHandler();
303 void ThreadDNSAddressSeed();
305 uint64_t CalculateKeyedNetGroup(const CAddress& ad) const;
307 CNode* FindNode(const CNetAddr& ip);
308 CNode* FindNode(const CSubNet& subNet);
309 CNode* FindNode(const std::string& addrName);
310 CNode* FindNode(const CService& addr);
312 bool AttemptToEvictConnection();
313 CNode* ConnectNode(CAddress addrConnect, const char *pszDest, bool fCountFailure);
314 bool IsWhitelistedRange(const CNetAddr &addr);
316 void DeleteNode(CNode* pnode);
318 NodeId GetNewNodeId();
320 size_t SocketSendData(CNode *pnode) const;
321 //!check is the banlist has unwritten changes
322 bool BannedSetIsDirty();
323 //!set the "dirty" flag for the banlist
324 void SetBannedSetDirty(bool dirty=true);
325 //!clean unused entries (if bantime has expired)
326 void SweepBanned();
327 void DumpAddresses();
328 void DumpData();
329 void DumpBanlist();
331 // Network stats
332 void RecordBytesRecv(uint64_t bytes);
333 void RecordBytesSent(uint64_t bytes);
335 // Whether the node should be passed out in ForEach* callbacks
336 static bool NodeFullyConnected(const CNode* pnode);
338 // Network usage totals
339 CCriticalSection cs_totalBytesRecv;
340 CCriticalSection cs_totalBytesSent;
341 uint64_t nTotalBytesRecv;
342 uint64_t nTotalBytesSent;
344 // outbound limit & stats
345 uint64_t nMaxOutboundTotalBytesSentInCycle;
346 uint64_t nMaxOutboundCycleStartTime;
347 uint64_t nMaxOutboundLimit;
348 uint64_t nMaxOutboundTimeframe;
350 // Whitelisted ranges. Any node connecting from these is automatically
351 // whitelisted (as well as those connecting to whitelisted binds).
352 std::vector<CSubNet> vWhitelistedRange;
353 CCriticalSection cs_vWhitelistedRange;
355 unsigned int nSendBufferMaxSize;
356 unsigned int nReceiveFloodSize;
358 std::vector<ListenSocket> vhListenSocket;
359 std::atomic<bool> fNetworkActive;
360 banmap_t setBanned;
361 CCriticalSection cs_setBanned;
362 bool setBannedIsDirty;
363 bool fAddressesInitialized;
364 CAddrMan addrman;
365 std::deque<std::string> vOneShots;
366 CCriticalSection cs_vOneShots;
367 std::vector<std::string> vAddedNodes;
368 CCriticalSection cs_vAddedNodes;
369 std::vector<CNode*> vNodes;
370 std::list<CNode*> vNodesDisconnected;
371 mutable CCriticalSection cs_vNodes;
372 std::atomic<NodeId> nLastNodeId;
374 /** Services this instance offers */
375 ServiceFlags nLocalServices;
377 /** Services this instance cares about */
378 ServiceFlags nRelevantServices;
380 CSemaphore *semOutbound;
381 CSemaphore *semAddnode;
382 int nMaxConnections;
383 int nMaxOutbound;
384 int nMaxAddnode;
385 int nMaxFeeler;
386 std::atomic<int> nBestHeight;
387 CClientUIInterface* clientInterface;
389 /** SipHasher seeds for deterministic randomness */
390 const uint64_t nSeed0, nSeed1;
392 /** flag for waking the message processor. */
393 bool fMsgProcWake;
395 std::condition_variable condMsgProc;
396 std::mutex mutexMsgProc;
397 std::atomic<bool> flagInterruptMsgProc;
399 CThreadInterrupt interruptNet;
401 std::thread threadDNSAddressSeed;
402 std::thread threadSocketHandler;
403 std::thread threadOpenAddedConnections;
404 std::thread threadOpenConnections;
405 std::thread threadMessageHandler;
407 extern std::unique_ptr<CConnman> g_connman;
408 void Discover(boost::thread_group& threadGroup);
409 void MapPort(bool fUseUPnP);
410 unsigned short GetListenPort();
411 bool BindListenPort(const CService &bindAddr, std::string& strError, bool fWhitelisted = false);
413 struct CombinerAll
415 typedef bool result_type;
417 template<typename I>
418 bool operator()(I first, I last) const
420 while (first != last) {
421 if (!(*first)) return false;
422 ++first;
424 return true;
428 // Signals for message handling
429 struct CNodeSignals
431 boost::signals2::signal<bool (CNode*, CConnman&, std::atomic<bool>&), CombinerAll> ProcessMessages;
432 boost::signals2::signal<bool (CNode*, CConnman&, std::atomic<bool>&), CombinerAll> SendMessages;
433 boost::signals2::signal<void (CNode*, CConnman&)> InitializeNode;
434 boost::signals2::signal<void (NodeId, bool&)> FinalizeNode;
438 CNodeSignals& GetNodeSignals();
441 enum
443 LOCAL_NONE, // unknown
444 LOCAL_IF, // address a local interface listens on
445 LOCAL_BIND, // address explicit bound to
446 LOCAL_UPNP, // address reported by UPnP
447 LOCAL_MANUAL, // address explicitly specified (-externalip=)
449 LOCAL_MAX
452 bool IsPeerAddrLocalGood(CNode *pnode);
453 void AdvertiseLocal(CNode *pnode);
454 void SetLimited(enum Network net, bool fLimited = true);
455 bool IsLimited(enum Network net);
456 bool IsLimited(const CNetAddr& addr);
457 bool AddLocal(const CService& addr, int nScore = LOCAL_NONE);
458 bool AddLocal(const CNetAddr& addr, int nScore = LOCAL_NONE);
459 bool RemoveLocal(const CService& addr);
460 bool SeenLocal(const CService& addr);
461 bool IsLocal(const CService& addr);
462 bool GetLocal(CService &addr, const CNetAddr *paddrPeer = NULL);
463 bool IsReachable(enum Network net);
464 bool IsReachable(const CNetAddr &addr);
465 CAddress GetLocalAddress(const CNetAddr *paddrPeer, ServiceFlags nLocalServices);
468 extern bool fDiscover;
469 extern bool fListen;
470 extern bool fRelayTxes;
472 extern limitedmap<uint256, int64_t> mapAlreadyAskedFor;
474 /** Subversion as sent to the P2P network in `version` messages */
475 extern std::string strSubVersion;
477 struct LocalServiceInfo {
478 int nScore;
479 int nPort;
482 extern CCriticalSection cs_mapLocalHost;
483 extern std::map<CNetAddr, LocalServiceInfo> mapLocalHost;
484 typedef std::map<std::string, uint64_t> mapMsgCmdSize; //command, total bytes
486 class CNodeStats
488 public:
489 NodeId nodeid;
490 ServiceFlags nServices;
491 bool fRelayTxes;
492 int64_t nLastSend;
493 int64_t nLastRecv;
494 int64_t nTimeConnected;
495 int64_t nTimeOffset;
496 std::string addrName;
497 int nVersion;
498 std::string cleanSubVer;
499 bool fInbound;
500 bool fAddnode;
501 int nStartingHeight;
502 uint64_t nSendBytes;
503 mapMsgCmdSize mapSendBytesPerMsgCmd;
504 uint64_t nRecvBytes;
505 mapMsgCmdSize mapRecvBytesPerMsgCmd;
506 bool fWhitelisted;
507 double dPingTime;
508 double dPingWait;
509 double dMinPing;
510 std::string addrLocal;
511 CAddress addr;
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 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;
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 int64_t nLastSend;
587 int64_t nLastRecv;
588 int64_t nTimeConnected;
589 int64_t nTimeOffset;
590 const CAddress addr;
591 std::string addrName;
592 CService addrLocal;
593 std::atomic<int> nVersion;
594 // strSubVer is whatever byte array we read from the wire. However, this field is intended
595 // to be printed out, displayed to humans in various forms and so on. So we sanitize it and
596 // store the sanitized version in cleanSubVer. The original should be used when dealing with
597 // the network or wire types and the cleaned string used when displayed or logged.
598 std::string strSubVer, cleanSubVer;
599 bool fWhitelisted; // This peer can bypass DoS banning.
600 bool fFeeler; // If true this node is being used as a short lived feeler.
601 bool fOneShot;
602 bool fAddnode;
603 bool fClient;
604 const bool fInbound;
605 std::atomic_bool fSuccessfullyConnected;
606 std::atomic_bool fDisconnect;
607 // We use fRelayTxes for two purposes -
608 // a) it allows us to not relay tx invs before receiving the peer's version message
609 // b) the peer may tell us in its version message that we should not relay tx invs
610 // unless it loads a bloom filter.
611 bool fRelayTxes; //protected by cs_filter
612 bool fSentAddr;
613 CSemaphoreGrant grantOutbound;
614 CCriticalSection cs_filter;
615 CBloomFilter* pfilter;
616 int nRefCount;
617 const NodeId id;
619 const uint64_t nKeyedNetGroup;
620 std::atomic_bool fPauseRecv;
621 std::atomic_bool fPauseSend;
622 protected:
624 mapMsgCmdSize mapSendBytesPerMsgCmd;
625 mapMsgCmdSize mapRecvBytesPerMsgCmd;
627 public:
628 uint256 hashContinue;
629 int nStartingHeight;
631 // flood relay
632 std::vector<CAddress> vAddrToSend;
633 CRollingBloomFilter addrKnown;
634 bool fGetAddr;
635 std::set<uint256> setKnown;
636 int64_t nNextAddrSend;
637 int64_t nNextLocalAddrSend;
639 // inventory based relay
640 CRollingBloomFilter filterInventoryKnown;
641 // Set of transaction ids we still have to announce.
642 // They are sorted by the mempool before relay, so the order is not important.
643 std::set<uint256> setInventoryTxToSend;
644 // List of block ids we still have announce.
645 // There is no final sorting before sending, as they are always sent immediately
646 // and in the order requested.
647 std::vector<uint256> vInventoryBlockToSend;
648 CCriticalSection cs_inventory;
649 std::set<uint256> setAskFor;
650 std::multimap<int64_t, CInv> mapAskFor;
651 int64_t nNextInvSend;
652 // Used for headers announcements - unfiltered blocks to relay
653 // Also protected by cs_inventory
654 std::vector<uint256> vBlockHashesToAnnounce;
655 // Used for BIP35 mempool sending, also protected by cs_inventory
656 bool fSendMempool;
658 // Last time a "MEMPOOL" request was serviced.
659 std::atomic<int64_t> timeLastMempoolReq;
661 // Block and TXN accept times
662 std::atomic<int64_t> nLastBlockTime;
663 std::atomic<int64_t> nLastTXTime;
665 // Ping time measurement:
666 // The pong reply we're expecting, or 0 if no pong expected.
667 uint64_t nPingNonceSent;
668 // Time (in usec) the last ping was sent, or 0 if no ping was ever sent.
669 int64_t nPingUsecStart;
670 // Last measured round-trip time.
671 int64_t nPingUsecTime;
672 // Best measured round-trip time.
673 int64_t nMinPingUsecTime;
674 // Whether a ping is requested.
675 bool fPingQueued;
676 // Minimum fee rate with which to filter inv's to this node
677 CAmount minFeeFilter;
678 CCriticalSection cs_feeFilter;
679 CAmount lastSentFeeFilter;
680 int64_t nextSendTimeFeeFilter;
682 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);
683 ~CNode();
685 private:
686 CNode(const CNode&);
687 void operator=(const CNode&);
690 const uint64_t nLocalHostNonce;
691 // Services offered to this peer
692 const ServiceFlags nLocalServices;
693 const int nMyStartingHeight;
694 int nSendVersion;
695 std::list<CNetMessage> vRecvMsg; // Used only by SocketHandler thread
696 public:
698 NodeId GetId() const {
699 return id;
702 uint64_t GetLocalNonce() const {
703 return nLocalHostNonce;
706 int GetMyStartingHeight() const {
707 return nMyStartingHeight;
710 int GetRefCount()
712 assert(nRefCount >= 0);
713 return nRefCount;
716 bool ReceiveMsgBytes(const char *pch, unsigned int nBytes, bool& complete);
718 void SetRecvVersion(int nVersionIn)
720 nRecvVersion = nVersionIn;
722 int GetRecvVersion()
724 return nRecvVersion;
726 void SetSendVersion(int nVersionIn);
727 int GetSendVersion() const;
729 CNode* AddRef()
731 nRefCount++;
732 return this;
735 void Release()
737 nRefCount--;
742 void AddAddressKnown(const CAddress& _addr)
744 addrKnown.insert(_addr.GetKey());
747 void PushAddress(const CAddress& _addr, FastRandomContext &insecure_rand)
749 // Known checking here is only to save space from duplicates.
750 // SendMessages will filter it again for knowns that were added
751 // after addresses were pushed.
752 if (_addr.IsValid() && !addrKnown.contains(_addr.GetKey())) {
753 if (vAddrToSend.size() >= MAX_ADDR_TO_SEND) {
754 vAddrToSend[insecure_rand.rand32() % vAddrToSend.size()] = _addr;
755 } else {
756 vAddrToSend.push_back(_addr);
762 void AddInventoryKnown(const CInv& inv)
765 LOCK(cs_inventory);
766 filterInventoryKnown.insert(inv.hash);
770 void PushInventory(const CInv& inv)
772 LOCK(cs_inventory);
773 if (inv.type == MSG_TX) {
774 if (!filterInventoryKnown.contains(inv.hash)) {
775 setInventoryTxToSend.insert(inv.hash);
777 } else if (inv.type == MSG_BLOCK) {
778 vInventoryBlockToSend.push_back(inv.hash);
782 void PushBlockHash(const uint256 &hash)
784 LOCK(cs_inventory);
785 vBlockHashesToAnnounce.push_back(hash);
788 void AskFor(const CInv& inv);
790 void CloseSocketDisconnect();
792 void copyStats(CNodeStats &stats);
794 ServiceFlags GetLocalServices() const
796 return nLocalServices;
804 /** Return a timestamp in the future (in microseconds) for exponentially distributed events. */
805 int64_t PoissonNextSend(int64_t nNow, int average_interval_seconds);
807 #endif // BITCOIN_NET_H