You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

net.h 27KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862
  1. // Copyright (c) 2009-2010 Satoshi Nakamoto
  2. // Copyright (c) 2009-2016 The Starwels developers
  3. // Distributed under the MIT software license, see the accompanying
  4. // file COPYING or http://www.opensource.org/licenses/mit-license.php.
  5. #ifndef STARWELS_NET_H
  6. #define STARWELS_NET_H
  7. #include "addrdb.h"
  8. #include "addrman.h"
  9. #include "amount.h"
  10. #include "bloom.h"
  11. #include "compat.h"
  12. #include "hash.h"
  13. #include "limitedmap.h"
  14. #include "netaddress.h"
  15. #include "policy/feerate.h"
  16. #include "protocol.h"
  17. #include "random.h"
  18. #include "streams.h"
  19. #include "sync.h"
  20. #include "uint256.h"
  21. #include "threadinterrupt.h"
  22. #include <atomic>
  23. #include <deque>
  24. #include <stdint.h>
  25. #include <thread>
  26. #include <memory>
  27. #include <condition_variable>
  28. #ifndef WIN32
  29. #include <arpa/inet.h>
  30. #endif
  31. class CScheduler;
  32. class CNode;
  33. namespace boost {
  34. class thread_group;
  35. } // namespace boost
  36. /** Time between pings automatically sent out for latency probing and keepalive (in seconds). */
  37. static const int PING_INTERVAL = 2 * 60;
  38. /** Time after which to disconnect, after waiting for a ping response (or inactivity). */
  39. static const int TIMEOUT_INTERVAL = 20 * 60;
  40. /** Run the feeler connection loop once every 2 minutes or 120 seconds. **/
  41. static const int FEELER_INTERVAL = 120;
  42. /** The maximum number of entries in an 'inv' protocol message */
  43. static const unsigned int MAX_INV_SZ = 50000;
  44. /** The maximum number of new addresses to accumulate before announcing. */
  45. static const unsigned int MAX_ADDR_TO_SEND = 1000;
  46. /** Maximum length of incoming protocol messages (no message over 4 MB is currently acceptable). */
  47. static const unsigned int MAX_PROTOCOL_MESSAGE_LENGTH = 4 * 1000 * 1000;
  48. /** Maximum length of strSubVer in `version` message */
  49. static const unsigned int MAX_SUBVERSION_LENGTH = 256;
  50. /** Maximum number of automatic outgoing nodes */
  51. static const int MAX_OUTBOUND_CONNECTIONS = 8;
  52. /** Maximum number of addnode outgoing nodes */
  53. static const int MAX_ADDNODE_CONNECTIONS = 8;
  54. /** -listen default */
  55. static const bool DEFAULT_LISTEN = true;
  56. /** -upnp default */
  57. #ifdef USE_UPNP
  58. static const bool DEFAULT_UPNP = USE_UPNP;
  59. #else
  60. static const bool DEFAULT_UPNP = false;
  61. #endif
  62. /** The maximum number of entries in mapAskFor */
  63. static const size_t MAPASKFOR_MAX_SZ = MAX_INV_SZ;
  64. /** The maximum number of entries in setAskFor (larger due to getdata latency)*/
  65. static const size_t SETASKFOR_MAX_SZ = 2 * MAX_INV_SZ;
  66. /** The maximum number of peer connections to maintain. */
  67. static const unsigned int DEFAULT_MAX_PEER_CONNECTIONS = 125;
  68. /** The default for -maxuploadtarget. 0 = Unlimited */
  69. static const uint64_t DEFAULT_MAX_UPLOAD_TARGET = 0;
  70. /** The default timeframe for -maxuploadtarget. 1 day. */
  71. static const uint64_t MAX_UPLOAD_TIMEFRAME = 60 * 60 * 24;
  72. /** Default for blocks only*/
  73. static const bool DEFAULT_BLOCKSONLY = false;
  74. static const bool DEFAULT_FORCEDNSSEED = false;
  75. static const size_t DEFAULT_MAXRECEIVEBUFFER = 5 * 1000;
  76. static const size_t DEFAULT_MAXSENDBUFFER = 1 * 1000;
  77. static const ServiceFlags REQUIRED_SERVICES = NODE_NETWORK;
  78. // NOTE: When adjusting this, update rpcnet:setban's help ("24h")
  79. static const unsigned int DEFAULT_MISBEHAVING_BANTIME = 60 * 60 * 24; // Default 24-hour ban
  80. typedef int64_t NodeId;
  81. struct AddedNodeInfo
  82. {
  83. std::string strAddedNode;
  84. CService resolvedAddress;
  85. bool fConnected;
  86. bool fInbound;
  87. };
  88. class CNodeStats;
  89. class CClientUIInterface;
  90. struct CSerializedNetMsg
  91. {
  92. CSerializedNetMsg() = default;
  93. CSerializedNetMsg(CSerializedNetMsg&&) = default;
  94. CSerializedNetMsg& operator=(CSerializedNetMsg&&) = default;
  95. // No copying, only moves.
  96. CSerializedNetMsg(const CSerializedNetMsg& msg) = delete;
  97. CSerializedNetMsg& operator=(const CSerializedNetMsg&) = delete;
  98. std::vector<unsigned char> data;
  99. std::string command;
  100. };
  101. class NetEventsInterface;
  102. class CConnman
  103. {
  104. public:
  105. enum NumConnections {
  106. CONNECTIONS_NONE = 0,
  107. CONNECTIONS_IN = (1U << 0),
  108. CONNECTIONS_OUT = (1U << 1),
  109. CONNECTIONS_ALL = (CONNECTIONS_IN | CONNECTIONS_OUT),
  110. };
  111. struct Options
  112. {
  113. ServiceFlags nLocalServices = NODE_NONE;
  114. ServiceFlags nRelevantServices = NODE_NONE;
  115. int nMaxConnections = 0;
  116. int nMaxOutbound = 0;
  117. int nMaxAddnode = 0;
  118. int nMaxFeeler = 0;
  119. int nBestHeight = 0;
  120. CClientUIInterface* uiInterface = nullptr;
  121. NetEventsInterface* m_msgproc = nullptr;
  122. unsigned int nSendBufferMaxSize = 0;
  123. unsigned int nReceiveFloodSize = 0;
  124. uint64_t nMaxOutboundTimeframe = 0;
  125. uint64_t nMaxOutboundLimit = 0;
  126. std::vector<std::string> vSeedNodes;
  127. std::vector<CSubNet> vWhitelistedRange;
  128. std::vector<CService> vBinds, vWhiteBinds;
  129. };
  130. void Init(const Options& connOptions) {
  131. nLocalServices = connOptions.nLocalServices;
  132. nRelevantServices = connOptions.nRelevantServices;
  133. nMaxConnections = connOptions.nMaxConnections;
  134. nMaxOutbound = std::min(connOptions.nMaxOutbound, connOptions.nMaxConnections);
  135. nMaxAddnode = connOptions.nMaxAddnode;
  136. nMaxFeeler = connOptions.nMaxFeeler;
  137. nBestHeight = connOptions.nBestHeight;
  138. clientInterface = connOptions.uiInterface;
  139. m_msgproc = connOptions.m_msgproc;
  140. nSendBufferMaxSize = connOptions.nSendBufferMaxSize;
  141. nReceiveFloodSize = connOptions.nReceiveFloodSize;
  142. nMaxOutboundTimeframe = connOptions.nMaxOutboundTimeframe;
  143. nMaxOutboundLimit = connOptions.nMaxOutboundLimit;
  144. vWhitelistedRange = connOptions.vWhitelistedRange;
  145. }
  146. CConnman(uint64_t seed0, uint64_t seed1);
  147. ~CConnman();
  148. bool Start(CScheduler& scheduler, const Options& options);
  149. void Stop();
  150. void Interrupt();
  151. bool GetNetworkActive() const { return fNetworkActive; };
  152. void SetNetworkActive(bool active);
  153. bool OpenNetworkConnection(const CAddress& addrConnect, bool fCountFailure, CSemaphoreGrant *grantOutbound = nullptr, const char *strDest = nullptr, bool fOneShot = false, bool fFeeler = false, bool manual_connection = false);
  154. bool CheckIncomingNonce(uint64_t nonce);
  155. bool ForNode(NodeId id, std::function<bool(CNode* pnode)> func);
  156. void PushMessage(CNode* pnode, CSerializedNetMsg&& msg);
  157. template<typename Callable>
  158. void ForEachNode(Callable&& func)
  159. {
  160. LOCK(cs_vNodes);
  161. for (auto&& node : vNodes) {
  162. if (NodeFullyConnected(node))
  163. func(node);
  164. }
  165. };
  166. template<typename Callable>
  167. void ForEachNode(Callable&& func) const
  168. {
  169. LOCK(cs_vNodes);
  170. for (auto&& node : vNodes) {
  171. if (NodeFullyConnected(node))
  172. func(node);
  173. }
  174. };
  175. template<typename Callable, typename CallableAfter>
  176. void ForEachNodeThen(Callable&& pre, CallableAfter&& post)
  177. {
  178. LOCK(cs_vNodes);
  179. for (auto&& node : vNodes) {
  180. if (NodeFullyConnected(node))
  181. pre(node);
  182. }
  183. post();
  184. };
  185. template<typename Callable, typename CallableAfter>
  186. void ForEachNodeThen(Callable&& pre, CallableAfter&& post) const
  187. {
  188. LOCK(cs_vNodes);
  189. for (auto&& node : vNodes) {
  190. if (NodeFullyConnected(node))
  191. pre(node);
  192. }
  193. post();
  194. };
  195. // Addrman functions
  196. size_t GetAddressCount() const;
  197. void SetServices(const CService &addr, ServiceFlags nServices);
  198. void MarkAddressGood(const CAddress& addr);
  199. void AddNewAddresses(const std::vector<CAddress>& vAddr, const CAddress& addrFrom, int64_t nTimePenalty = 0);
  200. std::vector<CAddress> GetAddresses();
  201. // Denial-of-service detection/prevention
  202. // The idea is to detect peers that are behaving
  203. // badly and disconnect/ban them, but do it in a
  204. // one-coding-mistake-won't-shatter-the-entire-network
  205. // way.
  206. // IMPORTANT: There should be nothing I can give a
  207. // node that it will forward on that will make that
  208. // node's peers drop it. If there is, an attacker
  209. // can isolate a node and/or try to split the network.
  210. // Dropping a node for sending stuff that is invalid
  211. // now but might be valid in a later version is also
  212. // dangerous, because it can cause a network split
  213. // between nodes running old code and nodes running
  214. // new code.
  215. void Ban(const CNetAddr& netAddr, const BanReason& reason, int64_t bantimeoffset = 0, bool sinceUnixEpoch = false);
  216. void Ban(const CSubNet& subNet, const BanReason& reason, int64_t bantimeoffset = 0, bool sinceUnixEpoch = false);
  217. void ClearBanned(); // needed for unit testing
  218. bool IsBanned(CNetAddr ip);
  219. bool IsBanned(CSubNet subnet);
  220. bool Unban(const CNetAddr &ip);
  221. bool Unban(const CSubNet &ip);
  222. void GetBanned(banmap_t &banmap);
  223. void SetBanned(const banmap_t &banmap);
  224. // This allows temporarily exceeding nMaxOutbound, with the goal of finding
  225. // a peer that is better than all our current peers.
  226. void SetTryNewOutboundPeer(bool flag);
  227. bool GetTryNewOutboundPeer();
  228. // Return the number of outbound peers we have in excess of our target (eg,
  229. // if we previously called SetTryNewOutboundPeer(true), and have since set
  230. // to false, we may have extra peers that we wish to disconnect). This may
  231. // return a value less than (num_outbound_connections - num_outbound_slots)
  232. // in cases where some outbound connections are not yet fully connected, or
  233. // not yet fully disconnected.
  234. int GetExtraOutboundCount();
  235. bool AddNode(const std::string& node);
  236. bool RemoveAddedNode(const std::string& node);
  237. std::vector<AddedNodeInfo> GetAddedNodeInfo();
  238. size_t GetNodeCount(NumConnections num);
  239. void GetNodeStats(std::vector<CNodeStats>& vstats);
  240. bool DisconnectNode(const std::string& node);
  241. bool DisconnectNode(NodeId id);
  242. ServiceFlags GetLocalServices() const;
  243. //!set the max outbound target in bytes
  244. void SetMaxOutboundTarget(uint64_t limit);
  245. uint64_t GetMaxOutboundTarget();
  246. //!set the timeframe for the max outbound target
  247. void SetMaxOutboundTimeframe(uint64_t timeframe);
  248. uint64_t GetMaxOutboundTimeframe();
  249. //!check if the outbound target is reached
  250. // if param historicalBlockServingLimit is set true, the function will
  251. // response true if the limit for serving historical blocks has been reached
  252. bool OutboundTargetReached(bool historicalBlockServingLimit);
  253. //!response the bytes left in the current max outbound cycle
  254. // in case of no limit, it will always response 0
  255. uint64_t GetOutboundTargetBytesLeft();
  256. //!response the time in second left in the current max outbound cycle
  257. // in case of no limit, it will always response 0
  258. uint64_t GetMaxOutboundTimeLeftInCycle();
  259. uint64_t GetTotalBytesRecv();
  260. uint64_t GetTotalBytesSent();
  261. void SetBestHeight(int height);
  262. int GetBestHeight() const;
  263. /** Get a unique deterministic randomizer. */
  264. CSipHasher GetDeterministicRandomizer(uint64_t id) const;
  265. unsigned int GetReceiveFloodSize() const;
  266. void WakeMessageHandler();
  267. private:
  268. struct ListenSocket {
  269. SOCKET socket;
  270. bool whitelisted;
  271. ListenSocket(SOCKET socket_, bool whitelisted_) : socket(socket_), whitelisted(whitelisted_) {}
  272. };
  273. bool BindListenPort(const CService &bindAddr, std::string& strError, bool fWhitelisted = false);
  274. bool Bind(const CService &addr, unsigned int flags);
  275. bool InitBinds(const std::vector<CService>& binds, const std::vector<CService>& whiteBinds);
  276. void ThreadOpenAddedConnections();
  277. void AddOneShot(const std::string& strDest);
  278. void ProcessOneShot();
  279. void ThreadOpenConnections();
  280. void ThreadMessageHandler();
  281. void AcceptConnection(const ListenSocket& hListenSocket);
  282. void ThreadSocketHandler();
  283. void ThreadDNSAddressSeed();
  284. uint64_t CalculateKeyedNetGroup(const CAddress& ad) const;
  285. CNode* FindNode(const CNetAddr& ip);
  286. CNode* FindNode(const CSubNet& subNet);
  287. CNode* FindNode(const std::string& addrName);
  288. CNode* FindNode(const CService& addr);
  289. bool AttemptToEvictConnection();
  290. CNode* ConnectNode(CAddress addrConnect, const char *pszDest, bool fCountFailure);
  291. bool IsWhitelistedRange(const CNetAddr &addr);
  292. void DeleteNode(CNode* pnode);
  293. NodeId GetNewNodeId();
  294. size_t SocketSendData(CNode *pnode) const;
  295. //!check is the banlist has unwritten changes
  296. bool BannedSetIsDirty();
  297. //!set the "dirty" flag for the banlist
  298. void SetBannedSetDirty(bool dirty=true);
  299. //!clean unused entries (if bantime has expired)
  300. void SweepBanned();
  301. void DumpAddresses();
  302. void DumpData();
  303. void DumpBanlist();
  304. // Network stats
  305. void RecordBytesRecv(uint64_t bytes);
  306. void RecordBytesSent(uint64_t bytes);
  307. // Whether the node should be passed out in ForEach* callbacks
  308. static bool NodeFullyConnected(const CNode* pnode);
  309. // Network usage totals
  310. CCriticalSection cs_totalBytesRecv;
  311. CCriticalSection cs_totalBytesSent;
  312. uint64_t nTotalBytesRecv;
  313. uint64_t nTotalBytesSent;
  314. // outbound limit & stats
  315. uint64_t nMaxOutboundTotalBytesSentInCycle;
  316. uint64_t nMaxOutboundCycleStartTime;
  317. uint64_t nMaxOutboundLimit;
  318. uint64_t nMaxOutboundTimeframe;
  319. // Whitelisted ranges. Any node connecting from these is automatically
  320. // whitelisted (as well as those connecting to whitelisted binds).
  321. std::vector<CSubNet> vWhitelistedRange;
  322. unsigned int nSendBufferMaxSize;
  323. unsigned int nReceiveFloodSize;
  324. std::vector<ListenSocket> vhListenSocket;
  325. std::atomic<bool> fNetworkActive;
  326. banmap_t setBanned;
  327. CCriticalSection cs_setBanned;
  328. bool setBannedIsDirty;
  329. bool fAddressesInitialized;
  330. CAddrMan addrman;
  331. std::deque<std::string> vOneShots;
  332. CCriticalSection cs_vOneShots;
  333. std::vector<std::string> vAddedNodes;
  334. CCriticalSection cs_vAddedNodes;
  335. std::vector<CNode*> vNodes;
  336. std::list<CNode*> vNodesDisconnected;
  337. mutable CCriticalSection cs_vNodes;
  338. std::atomic<NodeId> nLastNodeId;
  339. /** Services this instance offers */
  340. ServiceFlags nLocalServices;
  341. /** Services this instance cares about */
  342. ServiceFlags nRelevantServices;
  343. CSemaphore *semOutbound;
  344. CSemaphore *semAddnode;
  345. int nMaxConnections;
  346. int nMaxOutbound;
  347. int nMaxAddnode;
  348. int nMaxFeeler;
  349. std::atomic<int> nBestHeight;
  350. CClientUIInterface* clientInterface;
  351. NetEventsInterface* m_msgproc;
  352. /** SipHasher seeds for deterministic randomness */
  353. const uint64_t nSeed0, nSeed1;
  354. /** flag for waking the message processor. */
  355. bool fMsgProcWake;
  356. std::condition_variable condMsgProc;
  357. std::mutex mutexMsgProc;
  358. std::atomic<bool> flagInterruptMsgProc;
  359. CThreadInterrupt interruptNet;
  360. std::thread threadDNSAddressSeed;
  361. std::thread threadSocketHandler;
  362. std::thread threadOpenAddedConnections;
  363. std::thread threadOpenConnections;
  364. std::thread threadMessageHandler;
  365. /** flag for deciding to connect to an extra outbound peer,
  366. * in excess of nMaxOutbound
  367. * This takes the place of a feeler connection */
  368. std::atomic_bool m_try_another_outbound_peer;
  369. friend struct CConnmanTest;
  370. };
  371. extern std::unique_ptr<CConnman> g_connman;
  372. void Discover(boost::thread_group& threadGroup);
  373. void MapPort(bool fUseUPnP);
  374. unsigned short GetListenPort();
  375. bool BindListenPort(const CService &bindAddr, std::string& strError, bool fWhitelisted = false);
  376. struct CombinerAll
  377. {
  378. typedef bool result_type;
  379. template<typename I>
  380. bool operator()(I first, I last) const
  381. {
  382. while (first != last) {
  383. if (!(*first)) return false;
  384. ++first;
  385. }
  386. return true;
  387. }
  388. };
  389. /**
  390. * Interface for message handling
  391. */
  392. class NetEventsInterface
  393. {
  394. public:
  395. virtual bool ProcessMessages(CNode* pnode, std::atomic<bool>& interrupt) = 0;
  396. virtual bool SendMessages(CNode* pnode, std::atomic<bool>& interrupt) = 0;
  397. virtual void InitializeNode(CNode* pnode) = 0;
  398. virtual void FinalizeNode(NodeId id, bool& update_connection_time) = 0;
  399. };
  400. enum
  401. {
  402. LOCAL_NONE, // unknown
  403. LOCAL_IF, // address a local interface listens on
  404. LOCAL_BIND, // address explicit bound to
  405. LOCAL_UPNP, // address reported by UPnP
  406. LOCAL_MANUAL, // address explicitly specified (-externalip=)
  407. LOCAL_MAX
  408. };
  409. bool IsPeerAddrLocalGood(CNode *pnode);
  410. void AdvertiseLocal(CNode *pnode);
  411. void SetLimited(enum Network net, bool fLimited = true);
  412. bool IsLimited(enum Network net);
  413. bool IsLimited(const CNetAddr& addr);
  414. bool AddLocal(const CService& addr, int nScore = LOCAL_NONE);
  415. bool AddLocal(const CNetAddr& addr, int nScore = LOCAL_NONE);
  416. bool RemoveLocal(const CService& addr);
  417. bool SeenLocal(const CService& addr);
  418. bool IsLocal(const CService& addr);
  419. bool GetLocal(CService &addr, const CNetAddr *paddrPeer = nullptr);
  420. bool IsReachable(enum Network net);
  421. bool IsReachable(const CNetAddr &addr);
  422. CAddress GetLocalAddress(const CNetAddr *paddrPeer, ServiceFlags nLocalServices);
  423. extern bool fDiscover;
  424. extern bool fListen;
  425. extern bool fRelayTxes;
  426. extern limitedmap<uint256, int64_t> mapAlreadyAskedFor;
  427. /** Subversion as sent to the P2P network in `version` messages */
  428. extern std::string strSubVersion;
  429. struct LocalServiceInfo {
  430. int nScore;
  431. int nPort;
  432. };
  433. extern CCriticalSection cs_mapLocalHost;
  434. extern std::map<CNetAddr, LocalServiceInfo> mapLocalHost;
  435. typedef std::map<std::string, uint64_t> mapMsgCmdSize; //command, total bytes
  436. class CNodeStats
  437. {
  438. public:
  439. NodeId nodeid;
  440. ServiceFlags nServices;
  441. bool fRelayTxes;
  442. int64_t nLastSend;
  443. int64_t nLastRecv;
  444. int64_t nTimeConnected;
  445. int64_t nTimeOffset;
  446. std::string addrName;
  447. int nVersion;
  448. std::string cleanSubVer;
  449. bool fInbound;
  450. bool m_manual_connection;
  451. int nStartingHeight;
  452. uint64_t nSendBytes;
  453. mapMsgCmdSize mapSendBytesPerMsgCmd;
  454. uint64_t nRecvBytes;
  455. mapMsgCmdSize mapRecvBytesPerMsgCmd;
  456. bool fWhitelisted;
  457. double dPingTime;
  458. double dPingWait;
  459. double dMinPing;
  460. // Our address, as reported by the peer
  461. std::string addrLocal;
  462. // Address of this peer
  463. CAddress addr;
  464. // Bind address of our side of the connection
  465. CAddress addrBind;
  466. };
  467. class CNetMessage {
  468. private:
  469. mutable CHash256 hasher;
  470. mutable uint256 data_hash;
  471. public:
  472. bool in_data; // parsing header (false) or data (true)
  473. CDataStream hdrbuf; // partially received header
  474. CMessageHeader hdr; // complete header
  475. unsigned int nHdrPos;
  476. CDataStream vRecv; // received message data
  477. unsigned int nDataPos;
  478. int64_t nTime; // time (in microseconds) of message receipt.
  479. CNetMessage(const CMessageHeader::MessageStartChars& pchMessageStartIn, int nTypeIn, int nVersionIn) : hdrbuf(nTypeIn, nVersionIn), hdr(pchMessageStartIn), vRecv(nTypeIn, nVersionIn) {
  480. hdrbuf.resize(24);
  481. in_data = false;
  482. nHdrPos = 0;
  483. nDataPos = 0;
  484. nTime = 0;
  485. }
  486. bool complete() const
  487. {
  488. if (!in_data)
  489. return false;
  490. return (hdr.nMessageSize == nDataPos);
  491. }
  492. const uint256& GetMessageHash() const;
  493. void SetVersion(int nVersionIn)
  494. {
  495. hdrbuf.SetVersion(nVersionIn);
  496. vRecv.SetVersion(nVersionIn);
  497. }
  498. int readHeader(const char *pch, unsigned int nBytes);
  499. int readData(const char *pch, unsigned int nBytes);
  500. };
  501. /** Information about a peer */
  502. class CNode
  503. {
  504. friend class CConnman;
  505. public:
  506. // socket
  507. std::atomic<ServiceFlags> nServices;
  508. ServiceFlags nServicesExpected;
  509. SOCKET hSocket;
  510. size_t nSendSize; // total size of all vSendMsg entries
  511. size_t nSendOffset; // offset inside the first vSendMsg already sent
  512. uint64_t nSendBytes;
  513. std::deque<std::vector<unsigned char>> vSendMsg;
  514. CCriticalSection cs_vSend;
  515. CCriticalSection cs_hSocket;
  516. CCriticalSection cs_vRecv;
  517. CCriticalSection cs_vProcessMsg;
  518. std::list<CNetMessage> vProcessMsg;
  519. size_t nProcessQueueSize;
  520. CCriticalSection cs_sendProcessing;
  521. std::deque<CInv> vRecvGetData;
  522. uint64_t nRecvBytes;
  523. std::atomic<int> nRecvVersion;
  524. std::atomic<int64_t> nLastSend;
  525. std::atomic<int64_t> nLastRecv;
  526. const int64_t nTimeConnected;
  527. std::atomic<int64_t> nTimeOffset;
  528. // Address of this peer
  529. const CAddress addr;
  530. // Bind address of our side of the connection
  531. const CAddress addrBind;
  532. std::atomic<int> nVersion;
  533. // strSubVer is whatever byte array we read from the wire. However, this field is intended
  534. // to be printed out, displayed to humans in various forms and so on. So we sanitize it and
  535. // store the sanitized version in cleanSubVer. The original should be used when dealing with
  536. // the network or wire types and the cleaned string used when displayed or logged.
  537. std::string strSubVer, cleanSubVer;
  538. CCriticalSection cs_SubVer; // used for both cleanSubVer and strSubVer
  539. bool fWhitelisted; // This peer can bypass DoS banning.
  540. bool fFeeler; // If true this node is being used as a short lived feeler.
  541. bool fOneShot;
  542. bool m_manual_connection;
  543. bool fClient;
  544. const bool fInbound;
  545. std::atomic_bool fSuccessfullyConnected;
  546. std::atomic_bool fDisconnect;
  547. // We use fRelayTxes for two purposes -
  548. // a) it allows us to not relay tx invs before receiving the peer's version message
  549. // b) the peer may tell us in its version message that we should not relay tx invs
  550. // unless it loads a bloom filter.
  551. bool fRelayTxes; //protected by cs_filter
  552. bool fSentAddr;
  553. CSemaphoreGrant grantOutbound;
  554. CCriticalSection cs_filter;
  555. CBloomFilter* pfilter;
  556. std::atomic<int> nRefCount;
  557. const uint64_t nKeyedNetGroup;
  558. std::atomic_bool fPauseRecv;
  559. std::atomic_bool fPauseSend;
  560. protected:
  561. mapMsgCmdSize mapSendBytesPerMsgCmd;
  562. mapMsgCmdSize mapRecvBytesPerMsgCmd;
  563. public:
  564. uint256 hashContinue;
  565. std::atomic<int> nStartingHeight;
  566. // flood relay
  567. std::vector<CAddress> vAddrToSend;
  568. CRollingBloomFilter addrKnown;
  569. bool fGetAddr;
  570. std::set<uint256> setKnown;
  571. int64_t nNextAddrSend;
  572. int64_t nNextLocalAddrSend;
  573. // inventory based relay
  574. CRollingBloomFilter filterInventoryKnown;
  575. // Set of transaction ids we still have to announce.
  576. // They are sorted by the mempool before relay, so the order is not important.
  577. std::set<uint256> setInventoryTxToSend;
  578. // List of block ids we still have announce.
  579. // There is no final sorting before sending, as they are always sent immediately
  580. // and in the order requested.
  581. std::vector<uint256> vInventoryBlockToSend;
  582. CCriticalSection cs_inventory;
  583. std::set<uint256> setAskFor;
  584. std::multimap<int64_t, CInv> mapAskFor;
  585. int64_t nNextInvSend;
  586. // Used for headers announcements - unfiltered blocks to relay
  587. // Also protected by cs_inventory
  588. std::vector<uint256> vBlockHashesToAnnounce;
  589. // Used for BIP35 mempool sending, also protected by cs_inventory
  590. bool fSendMempool;
  591. // Last time a "MEMPOOL" request was serviced.
  592. std::atomic<int64_t> timeLastMempoolReq;
  593. // Block and TXN accept times
  594. std::atomic<int64_t> nLastBlockTime;
  595. std::atomic<int64_t> nLastTXTime;
  596. // Ping time measurement:
  597. // The pong reply we're expecting, or 0 if no pong expected.
  598. std::atomic<uint64_t> nPingNonceSent;
  599. // Time (in usec) the last ping was sent, or 0 if no ping was ever sent.
  600. std::atomic<int64_t> nPingUsecStart;
  601. // Last measured round-trip time.
  602. std::atomic<int64_t> nPingUsecTime;
  603. // Best measured round-trip time.
  604. std::atomic<int64_t> nMinPingUsecTime;
  605. // Whether a ping is requested.
  606. std::atomic<bool> fPingQueued;
  607. // Minimum fee rate with which to filter inv's to this node
  608. CAmount minFeeFilter;
  609. CCriticalSection cs_feeFilter;
  610. CAmount lastSentFeeFilter;
  611. int64_t nextSendTimeFeeFilter;
  612. 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);
  613. ~CNode();
  614. private:
  615. CNode(const CNode&);
  616. void operator=(const CNode&);
  617. const NodeId id;
  618. const uint64_t nLocalHostNonce;
  619. // Services offered to this peer
  620. const ServiceFlags nLocalServices;
  621. const int nMyStartingHeight;
  622. int nSendVersion;
  623. std::list<CNetMessage> vRecvMsg; // Used only by SocketHandler thread
  624. mutable CCriticalSection cs_addrName;
  625. std::string addrName;
  626. // Our address, as reported by the peer
  627. CService addrLocal;
  628. mutable CCriticalSection cs_addrLocal;
  629. public:
  630. NodeId GetId() const {
  631. return id;
  632. }
  633. uint64_t GetLocalNonce() const {
  634. return nLocalHostNonce;
  635. }
  636. int GetMyStartingHeight() const {
  637. return nMyStartingHeight;
  638. }
  639. int GetRefCount() const
  640. {
  641. assert(nRefCount >= 0);
  642. return nRefCount;
  643. }
  644. bool ReceiveMsgBytes(const char *pch, unsigned int nBytes, bool& complete);
  645. void SetRecvVersion(int nVersionIn)
  646. {
  647. nRecvVersion = nVersionIn;
  648. }
  649. int GetRecvVersion() const
  650. {
  651. return nRecvVersion;
  652. }
  653. void SetSendVersion(int nVersionIn);
  654. int GetSendVersion() const;
  655. CService GetAddrLocal() const;
  656. //! May not be called more than once
  657. void SetAddrLocal(const CService& addrLocalIn);
  658. CNode* AddRef()
  659. {
  660. nRefCount++;
  661. return this;
  662. }
  663. void Release()
  664. {
  665. nRefCount--;
  666. }
  667. void AddAddressKnown(const CAddress& _addr)
  668. {
  669. addrKnown.insert(_addr.GetKey());
  670. }
  671. void PushAddress(const CAddress& _addr, FastRandomContext &insecure_rand)
  672. {
  673. // Known checking here is only to save space from duplicates.
  674. // SendMessages will filter it again for knowns that were added
  675. // after addresses were pushed.
  676. if (_addr.IsValid() && !addrKnown.contains(_addr.GetKey())) {
  677. if (vAddrToSend.size() >= MAX_ADDR_TO_SEND) {
  678. vAddrToSend[insecure_rand.randrange(vAddrToSend.size())] = _addr;
  679. } else {
  680. vAddrToSend.push_back(_addr);
  681. }
  682. }
  683. }
  684. void AddInventoryKnown(const CInv& inv)
  685. {
  686. {
  687. LOCK(cs_inventory);
  688. filterInventoryKnown.insert(inv.hash);
  689. }
  690. }
  691. void PushInventory(const CInv& inv)
  692. {
  693. LOCK(cs_inventory);
  694. if (inv.type == MSG_TX) {
  695. if (!filterInventoryKnown.contains(inv.hash)) {
  696. setInventoryTxToSend.insert(inv.hash);
  697. }
  698. } else if (inv.type == MSG_BLOCK) {
  699. vInventoryBlockToSend.push_back(inv.hash);
  700. }
  701. }
  702. void PushBlockHash(const uint256 &hash)
  703. {
  704. LOCK(cs_inventory);
  705. vBlockHashesToAnnounce.push_back(hash);
  706. }
  707. void AskFor(const CInv& inv);
  708. void CloseSocketDisconnect();
  709. void copyStats(CNodeStats &stats);
  710. ServiceFlags GetLocalServices() const
  711. {
  712. return nLocalServices;
  713. }
  714. std::string GetAddrName() const;
  715. //! Sets the addrName only if it was not previously set
  716. void MaybeSetAddrName(const std::string& addrNameIn);
  717. };
  718. /** Return a timestamp in the future (in microseconds) for exponentially distributed events. */
  719. int64_t PoissonNextSend(int64_t nNow, int average_interval_seconds);
  720. #endif // STARWELS_NET_H