Merge #9226: Remove fNetworkNode and pnodeLocalHost.
[bitcoinplatinum.git] / src / net.h
bloba7c0ecf324270f52163dfa3857a61c9f226907f8
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2015 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"
23 #include <atomic>
24 #include <deque>
25 #include <stdint.h>
26 #include <memory>
28 #ifndef WIN32
29 #include <arpa/inet.h>
30 #endif
32 #include <boost/filesystem/path.hpp>
33 #include <boost/foreach.hpp>
34 #include <boost/signals2/signal.hpp>
36 class CAddrMan;
37 class CScheduler;
38 class CNode;
40 namespace boost {
41 class thread_group;
42 } // namespace boost
44 /** Time between pings automatically sent out for latency probing and keepalive (in seconds). */
45 static const int PING_INTERVAL = 2 * 60;
46 /** Time after which to disconnect, after waiting for a ping response (or inactivity). */
47 static const int TIMEOUT_INTERVAL = 20 * 60;
48 /** Run the feeler connection loop once every 2 minutes or 120 seconds. **/
49 static const int FEELER_INTERVAL = 120;
50 /** The maximum number of entries in an 'inv' protocol message */
51 static const unsigned int MAX_INV_SZ = 50000;
52 /** The maximum number of new addresses to accumulate before announcing. */
53 static const unsigned int MAX_ADDR_TO_SEND = 1000;
54 /** Maximum length of incoming protocol messages (no message over 4 MB is currently acceptable). */
55 static const unsigned int MAX_PROTOCOL_MESSAGE_LENGTH = 4 * 1000 * 1000;
56 /** Maximum length of strSubVer in `version` message */
57 static const unsigned int MAX_SUBVERSION_LENGTH = 256;
58 /** Maximum number of outgoing nodes */
59 static const int MAX_OUTBOUND_CONNECTIONS = 8;
60 /** -listen default */
61 static const bool DEFAULT_LISTEN = true;
62 /** -upnp default */
63 #ifdef USE_UPNP
64 static const bool DEFAULT_UPNP = USE_UPNP;
65 #else
66 static const bool DEFAULT_UPNP = false;
67 #endif
68 /** The maximum number of entries in mapAskFor */
69 static const size_t MAPASKFOR_MAX_SZ = MAX_INV_SZ;
70 /** The maximum number of entries in setAskFor (larger due to getdata latency)*/
71 static const size_t SETASKFOR_MAX_SZ = 2 * MAX_INV_SZ;
72 /** The maximum number of peer connections to maintain. */
73 static const unsigned int DEFAULT_MAX_PEER_CONNECTIONS = 125;
74 /** The default for -maxuploadtarget. 0 = Unlimited */
75 static const uint64_t DEFAULT_MAX_UPLOAD_TARGET = 0;
76 /** The default timeframe for -maxuploadtarget. 1 day. */
77 static const uint64_t MAX_UPLOAD_TIMEFRAME = 60 * 60 * 24;
78 /** Default for blocks only*/
79 static const bool DEFAULT_BLOCKSONLY = false;
81 static const bool DEFAULT_FORCEDNSSEED = false;
82 static const size_t DEFAULT_MAXRECEIVEBUFFER = 5 * 1000;
83 static const size_t DEFAULT_MAXSENDBUFFER = 1 * 1000;
85 static const ServiceFlags REQUIRED_SERVICES = NODE_NETWORK;
87 // NOTE: When adjusting this, update rpcnet:setban's help ("24h")
88 static const unsigned int DEFAULT_MISBEHAVING_BANTIME = 60 * 60 * 24; // Default 24-hour ban
90 typedef int NodeId;
92 struct AddedNodeInfo
94 std::string strAddedNode;
95 CService resolvedAddress;
96 bool fConnected;
97 bool fInbound;
100 class CTransaction;
101 class CNodeStats;
102 class CClientUIInterface;
104 struct CSerializedNetMsg
106 CSerializedNetMsg() = default;
107 CSerializedNetMsg(CSerializedNetMsg&&) = default;
108 CSerializedNetMsg& operator=(CSerializedNetMsg&&) = default;
109 // No copying, only moves.
110 CSerializedNetMsg(const CSerializedNetMsg& msg) = delete;
111 CSerializedNetMsg& operator=(const CSerializedNetMsg&) = delete;
113 std::vector<unsigned char> data;
114 std::string command;
118 class CConnman
120 public:
122 enum NumConnections {
123 CONNECTIONS_NONE = 0,
124 CONNECTIONS_IN = (1U << 0),
125 CONNECTIONS_OUT = (1U << 1),
126 CONNECTIONS_ALL = (CONNECTIONS_IN | CONNECTIONS_OUT),
129 struct Options
131 ServiceFlags nLocalServices = NODE_NONE;
132 ServiceFlags nRelevantServices = NODE_NONE;
133 int nMaxConnections = 0;
134 int nMaxOutbound = 0;
135 int nMaxFeeler = 0;
136 int nBestHeight = 0;
137 CClientUIInterface* uiInterface = nullptr;
138 unsigned int nSendBufferMaxSize = 0;
139 unsigned int nReceiveFloodSize = 0;
140 uint64_t nMaxOutboundTimeframe = 0;
141 uint64_t nMaxOutboundLimit = 0;
143 CConnman(uint64_t seed0, uint64_t seed1);
144 ~CConnman();
145 bool Start(boost::thread_group& threadGroup, CScheduler& scheduler, std::string& strNodeError, Options options);
146 void Stop();
147 bool BindListenPort(const CService &bindAddr, std::string& strError, bool fWhitelisted = false);
148 bool GetNetworkActive() const { return fNetworkActive; };
149 void SetNetworkActive(bool active);
150 bool OpenNetworkConnection(const CAddress& addrConnect, bool fCountFailure, CSemaphoreGrant *grantOutbound = NULL, const char *strDest = NULL, bool fOneShot = false, bool fFeeler = false);
151 bool CheckIncomingNonce(uint64_t nonce);
153 bool ForNode(NodeId id, std::function<bool(CNode* pnode)> func);
155 void PushMessage(CNode* pnode, CSerializedNetMsg&& msg);
157 template<typename Callable>
158 bool ForEachNodeContinueIf(Callable&& func)
160 LOCK(cs_vNodes);
161 for (auto&& node : vNodes)
162 if(!func(node))
163 return false;
164 return true;
167 template<typename Callable>
168 bool ForEachNodeContinueIf(Callable&& func) const
170 LOCK(cs_vNodes);
171 for (const auto& node : vNodes)
172 if(!func(node))
173 return false;
174 return true;
177 template<typename Callable, typename CallableAfter>
178 bool ForEachNodeContinueIfThen(Callable&& pre, CallableAfter&& post)
180 bool ret = true;
181 LOCK(cs_vNodes);
182 for (auto&& node : vNodes)
183 if(!pre(node)) {
184 ret = false;
185 break;
187 post();
188 return ret;
191 template<typename Callable, typename CallableAfter>
192 bool ForEachNodeContinueIfThen(Callable&& pre, CallableAfter&& post) const
194 bool ret = true;
195 LOCK(cs_vNodes);
196 for (const auto& node : vNodes)
197 if(!pre(node)) {
198 ret = false;
199 break;
201 post();
202 return ret;
205 template<typename Callable>
206 void ForEachNode(Callable&& func)
208 LOCK(cs_vNodes);
209 for (auto&& node : vNodes)
210 func(node);
213 template<typename Callable>
214 void ForEachNode(Callable&& func) const
216 LOCK(cs_vNodes);
217 for (const auto& node : vNodes)
218 func(node);
221 template<typename Callable, typename CallableAfter>
222 void ForEachNodeThen(Callable&& pre, CallableAfter&& post)
224 LOCK(cs_vNodes);
225 for (auto&& node : vNodes)
226 pre(node);
227 post();
230 template<typename Callable, typename CallableAfter>
231 void ForEachNodeThen(Callable&& pre, CallableAfter&& post) const
233 LOCK(cs_vNodes);
234 for (const auto& node : vNodes)
235 pre(node);
236 post();
239 void RelayTransaction(const CTransaction& tx);
241 // Addrman functions
242 size_t GetAddressCount() const;
243 void SetServices(const CService &addr, ServiceFlags nServices);
244 void MarkAddressGood(const CAddress& addr);
245 void AddNewAddress(const CAddress& addr, const CAddress& addrFrom, int64_t nTimePenalty = 0);
246 void AddNewAddresses(const std::vector<CAddress>& vAddr, const CAddress& addrFrom, int64_t nTimePenalty = 0);
247 std::vector<CAddress> GetAddresses();
248 void AddressCurrentlyConnected(const CService& addr);
250 // Denial-of-service detection/prevention
251 // The idea is to detect peers that are behaving
252 // badly and disconnect/ban them, but do it in a
253 // one-coding-mistake-won't-shatter-the-entire-network
254 // way.
255 // IMPORTANT: There should be nothing I can give a
256 // node that it will forward on that will make that
257 // node's peers drop it. If there is, an attacker
258 // can isolate a node and/or try to split the network.
259 // Dropping a node for sending stuff that is invalid
260 // now but might be valid in a later version is also
261 // dangerous, because it can cause a network split
262 // between nodes running old code and nodes running
263 // new code.
264 void Ban(const CNetAddr& netAddr, const BanReason& reason, int64_t bantimeoffset = 0, bool sinceUnixEpoch = false);
265 void Ban(const CSubNet& subNet, const BanReason& reason, int64_t bantimeoffset = 0, bool sinceUnixEpoch = false);
266 void ClearBanned(); // needed for unit testing
267 bool IsBanned(CNetAddr ip);
268 bool IsBanned(CSubNet subnet);
269 bool Unban(const CNetAddr &ip);
270 bool Unban(const CSubNet &ip);
271 void GetBanned(banmap_t &banmap);
272 void SetBanned(const banmap_t &banmap);
274 void AddOneShot(const std::string& strDest);
276 bool AddNode(const std::string& node);
277 bool RemoveAddedNode(const std::string& node);
278 std::vector<AddedNodeInfo> GetAddedNodeInfo();
280 size_t GetNodeCount(NumConnections num);
281 void GetNodeStats(std::vector<CNodeStats>& vstats);
282 bool DisconnectAddress(const CNetAddr& addr);
283 bool DisconnectNode(const std::string& node);
284 bool DisconnectNode(NodeId id);
285 bool DisconnectSubnet(const CSubNet& subnet);
287 unsigned int GetSendBufferSize() const;
289 void AddWhitelistedRange(const CSubNet &subnet);
291 ServiceFlags GetLocalServices() const;
293 //!set the max outbound target in bytes
294 void SetMaxOutboundTarget(uint64_t limit);
295 uint64_t GetMaxOutboundTarget();
297 //!set the timeframe for the max outbound target
298 void SetMaxOutboundTimeframe(uint64_t timeframe);
299 uint64_t GetMaxOutboundTimeframe();
301 //!check if the outbound target is reached
302 // if param historicalBlockServingLimit is set true, the function will
303 // response true if the limit for serving historical blocks has been reached
304 bool OutboundTargetReached(bool historicalBlockServingLimit);
306 //!response the bytes left in the current max outbound cycle
307 // in case of no limit, it will always response 0
308 uint64_t GetOutboundTargetBytesLeft();
310 //!response the time in second left in the current max outbound cycle
311 // in case of no limit, it will always response 0
312 uint64_t GetMaxOutboundTimeLeftInCycle();
314 uint64_t GetTotalBytesRecv();
315 uint64_t GetTotalBytesSent();
317 void SetBestHeight(int height);
318 int GetBestHeight() const;
320 /** Get a unique deterministic randomizer. */
321 CSipHasher GetDeterministicRandomizer(uint64_t id);
323 private:
324 struct ListenSocket {
325 SOCKET socket;
326 bool whitelisted;
328 ListenSocket(SOCKET socket_, bool whitelisted_) : socket(socket_), whitelisted(whitelisted_) {}
331 void ThreadOpenAddedConnections();
332 void ProcessOneShot();
333 void ThreadOpenConnections();
334 void ThreadMessageHandler();
335 void AcceptConnection(const ListenSocket& hListenSocket);
336 void ThreadSocketHandler();
337 void ThreadDNSAddressSeed();
339 uint64_t CalculateKeyedNetGroup(const CAddress& ad);
341 CNode* FindNode(const CNetAddr& ip);
342 CNode* FindNode(const CSubNet& subNet);
343 CNode* FindNode(const std::string& addrName);
344 CNode* FindNode(const CService& addr);
346 bool AttemptToEvictConnection();
347 CNode* ConnectNode(CAddress addrConnect, const char *pszDest, bool fCountFailure);
348 bool IsWhitelistedRange(const CNetAddr &addr);
350 void DeleteNode(CNode* pnode);
352 NodeId GetNewNodeId();
354 //!check is the banlist has unwritten changes
355 bool BannedSetIsDirty();
356 //!set the "dirty" flag for the banlist
357 void SetBannedSetDirty(bool dirty=true);
358 //!clean unused entries (if bantime has expired)
359 void SweepBanned();
360 void DumpAddresses();
361 void DumpData();
362 void DumpBanlist();
364 unsigned int GetReceiveFloodSize() const;
366 // Network stats
367 void RecordBytesRecv(uint64_t bytes);
368 void RecordBytesSent(uint64_t bytes);
370 // Network usage totals
371 CCriticalSection cs_totalBytesRecv;
372 CCriticalSection cs_totalBytesSent;
373 uint64_t nTotalBytesRecv;
374 uint64_t nTotalBytesSent;
376 // outbound limit & stats
377 uint64_t nMaxOutboundTotalBytesSentInCycle;
378 uint64_t nMaxOutboundCycleStartTime;
379 uint64_t nMaxOutboundLimit;
380 uint64_t nMaxOutboundTimeframe;
382 // Whitelisted ranges. Any node connecting from these is automatically
383 // whitelisted (as well as those connecting to whitelisted binds).
384 std::vector<CSubNet> vWhitelistedRange;
385 CCriticalSection cs_vWhitelistedRange;
387 unsigned int nSendBufferMaxSize;
388 unsigned int nReceiveFloodSize;
390 std::vector<ListenSocket> vhListenSocket;
391 std::atomic<bool> fNetworkActive;
392 banmap_t setBanned;
393 CCriticalSection cs_setBanned;
394 bool setBannedIsDirty;
395 bool fAddressesInitialized;
396 CAddrMan addrman;
397 std::deque<std::string> vOneShots;
398 CCriticalSection cs_vOneShots;
399 std::vector<std::string> vAddedNodes;
400 CCriticalSection cs_vAddedNodes;
401 std::vector<CNode*> vNodes;
402 std::list<CNode*> vNodesDisconnected;
403 mutable CCriticalSection cs_vNodes;
404 std::atomic<NodeId> nLastNodeId;
405 boost::condition_variable messageHandlerCondition;
407 /** Services this instance offers */
408 ServiceFlags nLocalServices;
410 /** Services this instance cares about */
411 ServiceFlags nRelevantServices;
413 CSemaphore *semOutbound;
414 int nMaxConnections;
415 int nMaxOutbound;
416 int nMaxFeeler;
417 std::atomic<int> nBestHeight;
418 CClientUIInterface* clientInterface;
420 /** SipHasher seeds for deterministic randomness */
421 const uint64_t nSeed0, nSeed1;
423 extern std::unique_ptr<CConnman> g_connman;
424 void Discover(boost::thread_group& threadGroup);
425 void MapPort(bool fUseUPnP);
426 unsigned short GetListenPort();
427 bool BindListenPort(const CService &bindAddr, std::string& strError, bool fWhitelisted = false);
428 size_t SocketSendData(CNode *pnode);
430 struct CombinerAll
432 typedef bool result_type;
434 template<typename I>
435 bool operator()(I first, I last) const
437 while (first != last) {
438 if (!(*first)) return false;
439 ++first;
441 return true;
445 // Signals for message handling
446 struct CNodeSignals
448 boost::signals2::signal<bool (CNode*, CConnman&), CombinerAll> ProcessMessages;
449 boost::signals2::signal<bool (CNode*, CConnman&), CombinerAll> SendMessages;
450 boost::signals2::signal<void (CNode*, CConnman&)> InitializeNode;
451 boost::signals2::signal<void (NodeId, bool&)> FinalizeNode;
455 CNodeSignals& GetNodeSignals();
458 enum
460 LOCAL_NONE, // unknown
461 LOCAL_IF, // address a local interface listens on
462 LOCAL_BIND, // address explicit bound to
463 LOCAL_UPNP, // address reported by UPnP
464 LOCAL_MANUAL, // address explicitly specified (-externalip=)
466 LOCAL_MAX
469 bool IsPeerAddrLocalGood(CNode *pnode);
470 void AdvertiseLocal(CNode *pnode);
471 void SetLimited(enum Network net, bool fLimited = true);
472 bool IsLimited(enum Network net);
473 bool IsLimited(const CNetAddr& addr);
474 bool AddLocal(const CService& addr, int nScore = LOCAL_NONE);
475 bool AddLocal(const CNetAddr& addr, int nScore = LOCAL_NONE);
476 bool RemoveLocal(const CService& addr);
477 bool SeenLocal(const CService& addr);
478 bool IsLocal(const CService& addr);
479 bool GetLocal(CService &addr, const CNetAddr *paddrPeer = NULL);
480 bool IsReachable(enum Network net);
481 bool IsReachable(const CNetAddr &addr);
482 CAddress GetLocalAddress(const CNetAddr *paddrPeer, ServiceFlags nLocalServices);
485 extern bool fDiscover;
486 extern bool fListen;
487 extern bool fRelayTxes;
489 extern limitedmap<uint256, int64_t> mapAlreadyAskedFor;
491 /** Subversion as sent to the P2P network in `version` messages */
492 extern std::string strSubVersion;
494 struct LocalServiceInfo {
495 int nScore;
496 int nPort;
499 extern CCriticalSection cs_mapLocalHost;
500 extern std::map<CNetAddr, LocalServiceInfo> mapLocalHost;
501 typedef std::map<std::string, uint64_t> mapMsgCmdSize; //command, total bytes
503 class CNodeStats
505 public:
506 NodeId nodeid;
507 ServiceFlags nServices;
508 bool fRelayTxes;
509 int64_t nLastSend;
510 int64_t nLastRecv;
511 int64_t nTimeConnected;
512 int64_t nTimeOffset;
513 std::string addrName;
514 int nVersion;
515 std::string cleanSubVer;
516 bool fInbound;
517 int nStartingHeight;
518 uint64_t nSendBytes;
519 mapMsgCmdSize mapSendBytesPerMsgCmd;
520 uint64_t nRecvBytes;
521 mapMsgCmdSize mapRecvBytesPerMsgCmd;
522 bool fWhitelisted;
523 double dPingTime;
524 double dPingWait;
525 double dMinPing;
526 std::string addrLocal;
527 CAddress addr;
533 class CNetMessage {
534 private:
535 mutable CHash256 hasher;
536 mutable uint256 data_hash;
537 public:
538 bool in_data; // parsing header (false) or data (true)
540 CDataStream hdrbuf; // partially received header
541 CMessageHeader hdr; // complete header
542 unsigned int nHdrPos;
544 CDataStream vRecv; // received message data
545 unsigned int nDataPos;
547 int64_t nTime; // time (in microseconds) of message receipt.
549 CNetMessage(const CMessageHeader::MessageStartChars& pchMessageStartIn, int nTypeIn, int nVersionIn) : hdrbuf(nTypeIn, nVersionIn), hdr(pchMessageStartIn), vRecv(nTypeIn, nVersionIn) {
550 hdrbuf.resize(24);
551 in_data = false;
552 nHdrPos = 0;
553 nDataPos = 0;
554 nTime = 0;
557 bool complete() const
559 if (!in_data)
560 return false;
561 return (hdr.nMessageSize == nDataPos);
564 const uint256& GetMessageHash() const;
566 void SetVersion(int nVersionIn)
568 hdrbuf.SetVersion(nVersionIn);
569 vRecv.SetVersion(nVersionIn);
572 int readHeader(const char *pch, unsigned int nBytes);
573 int readData(const char *pch, unsigned int nBytes);
577 /** Information about a peer */
578 class CNode
580 friend class CConnman;
581 public:
582 // socket
583 ServiceFlags nServices;
584 ServiceFlags nServicesExpected;
585 SOCKET hSocket;
586 size_t nSendSize; // total size of all vSendMsg entries
587 size_t nSendOffset; // offset inside the first vSendMsg already sent
588 uint64_t nSendBytes;
589 std::deque<std::vector<unsigned char>> vSendMsg;
590 CCriticalSection cs_vSend;
592 std::deque<CInv> vRecvGetData;
593 std::deque<CNetMessage> vRecvMsg;
594 CCriticalSection cs_vRecvMsg;
595 uint64_t nRecvBytes;
596 int nRecvVersion;
598 int64_t nLastSend;
599 int64_t nLastRecv;
600 int64_t nTimeConnected;
601 int64_t nTimeOffset;
602 const CAddress addr;
603 std::string addrName;
604 CService addrLocal;
605 int nVersion;
606 // strSubVer is whatever byte array we read from the wire. However, this field is intended
607 // to be printed out, displayed to humans in various forms and so on. So we sanitize it and
608 // store the sanitized version in cleanSubVer. The original should be used when dealing with
609 // the network or wire types and the cleaned string used when displayed or logged.
610 std::string strSubVer, cleanSubVer;
611 bool fWhitelisted; // This peer can bypass DoS banning.
612 bool fFeeler; // If true this node is being used as a short lived feeler.
613 bool fOneShot;
614 bool fClient;
615 const bool fInbound;
616 bool fSuccessfullyConnected;
617 std::atomic_bool fDisconnect;
618 // We use fRelayTxes for two purposes -
619 // a) it allows us to not relay tx invs before receiving the peer's version message
620 // b) the peer may tell us in its version message that we should not relay tx invs
621 // unless it loads a bloom filter.
622 bool fRelayTxes; //protected by cs_filter
623 bool fSentAddr;
624 CSemaphoreGrant grantOutbound;
625 CCriticalSection cs_filter;
626 CBloomFilter* pfilter;
627 int nRefCount;
628 const NodeId id;
630 const uint64_t nKeyedNetGroup;
631 protected:
633 mapMsgCmdSize mapSendBytesPerMsgCmd;
634 mapMsgCmdSize mapRecvBytesPerMsgCmd;
636 public:
637 uint256 hashContinue;
638 int nStartingHeight;
640 // flood relay
641 std::vector<CAddress> vAddrToSend;
642 CRollingBloomFilter addrKnown;
643 bool fGetAddr;
644 std::set<uint256> setKnown;
645 int64_t nNextAddrSend;
646 int64_t nNextLocalAddrSend;
648 // inventory based relay
649 CRollingBloomFilter filterInventoryKnown;
650 // Set of transaction ids we still have to announce.
651 // They are sorted by the mempool before relay, so the order is not important.
652 std::set<uint256> setInventoryTxToSend;
653 // List of block ids we still have announce.
654 // There is no final sorting before sending, as they are always sent immediately
655 // and in the order requested.
656 std::vector<uint256> vInventoryBlockToSend;
657 CCriticalSection cs_inventory;
658 std::set<uint256> setAskFor;
659 std::multimap<int64_t, CInv> mapAskFor;
660 int64_t nNextInvSend;
661 // Used for headers announcements - unfiltered blocks to relay
662 // Also protected by cs_inventory
663 std::vector<uint256> vBlockHashesToAnnounce;
664 // Used for BIP35 mempool sending, also protected by cs_inventory
665 bool fSendMempool;
667 // Last time a "MEMPOOL" request was serviced.
668 std::atomic<int64_t> timeLastMempoolReq;
670 // Block and TXN accept times
671 std::atomic<int64_t> nLastBlockTime;
672 std::atomic<int64_t> nLastTXTime;
674 // Ping time measurement:
675 // The pong reply we're expecting, or 0 if no pong expected.
676 uint64_t nPingNonceSent;
677 // Time (in usec) the last ping was sent, or 0 if no ping was ever sent.
678 int64_t nPingUsecStart;
679 // Last measured round-trip time.
680 int64_t nPingUsecTime;
681 // Best measured round-trip time.
682 int64_t nMinPingUsecTime;
683 // Whether a ping is requested.
684 bool fPingQueued;
685 // Minimum fee rate with which to filter inv's to this node
686 CAmount minFeeFilter;
687 CCriticalSection cs_feeFilter;
688 CAmount lastSentFeeFilter;
689 int64_t nextSendTimeFeeFilter;
691 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);
692 ~CNode();
694 private:
695 CNode(const CNode&);
696 void operator=(const CNode&);
699 const uint64_t nLocalHostNonce;
700 // Services offered to this peer
701 const ServiceFlags nLocalServices;
702 const int nMyStartingHeight;
703 int nSendVersion;
704 public:
706 NodeId GetId() const {
707 return id;
710 uint64_t GetLocalNonce() const {
711 return nLocalHostNonce;
714 int GetMyStartingHeight() const {
715 return nMyStartingHeight;
718 int GetRefCount()
720 assert(nRefCount >= 0);
721 return nRefCount;
724 // requires LOCK(cs_vRecvMsg)
725 unsigned int GetTotalRecvSize()
727 unsigned int total = 0;
728 BOOST_FOREACH(const CNetMessage &msg, vRecvMsg)
729 total += msg.vRecv.size() + 24;
730 return total;
733 // requires LOCK(cs_vRecvMsg)
734 bool ReceiveMsgBytes(const char *pch, unsigned int nBytes, bool& complete);
736 // requires LOCK(cs_vRecvMsg)
737 void SetRecvVersion(int nVersionIn)
739 nRecvVersion = nVersionIn;
740 BOOST_FOREACH(CNetMessage &msg, vRecvMsg)
741 msg.SetVersion(nVersionIn);
743 void SetSendVersion(int nVersionIn)
745 // Send version may only be changed in the version message, and
746 // only one version message is allowed per session. We can therefore
747 // treat this value as const and even atomic as long as it's only used
748 // once the handshake is complete. Any attempt to set this twice is an
749 // error.
750 assert(nSendVersion == 0);
751 nSendVersion = nVersionIn;
754 int GetSendVersion() const
756 // The send version should always be explicitly set to
757 // INIT_PROTO_VERSION rather than using this value until the handshake
758 // is complete.
759 assert(nSendVersion != 0);
760 return nSendVersion;
763 CNode* AddRef()
765 nRefCount++;
766 return this;
769 void Release()
771 nRefCount--;
776 void AddAddressKnown(const CAddress& _addr)
778 addrKnown.insert(_addr.GetKey());
781 void PushAddress(const CAddress& _addr, FastRandomContext &insecure_rand)
783 // Known checking here is only to save space from duplicates.
784 // SendMessages will filter it again for knowns that were added
785 // after addresses were pushed.
786 if (_addr.IsValid() && !addrKnown.contains(_addr.GetKey())) {
787 if (vAddrToSend.size() >= MAX_ADDR_TO_SEND) {
788 vAddrToSend[insecure_rand.rand32() % vAddrToSend.size()] = _addr;
789 } else {
790 vAddrToSend.push_back(_addr);
796 void AddInventoryKnown(const CInv& inv)
799 LOCK(cs_inventory);
800 filterInventoryKnown.insert(inv.hash);
804 void PushInventory(const CInv& inv)
806 LOCK(cs_inventory);
807 if (inv.type == MSG_TX) {
808 if (!filterInventoryKnown.contains(inv.hash)) {
809 setInventoryTxToSend.insert(inv.hash);
811 } else if (inv.type == MSG_BLOCK) {
812 vInventoryBlockToSend.push_back(inv.hash);
816 void PushBlockHash(const uint256 &hash)
818 LOCK(cs_inventory);
819 vBlockHashesToAnnounce.push_back(hash);
822 void AskFor(const CInv& inv);
824 void CloseSocketDisconnect();
826 void copyStats(CNodeStats &stats);
828 ServiceFlags GetLocalServices() const
830 return nLocalServices;
838 /** Return a timestamp in the future (in microseconds) for exponentially distributed events. */
839 int64_t PoissonNextSend(int64_t nNow, int average_interval_seconds);
841 #endif // BITCOIN_NET_H