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 24KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837
  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.
  5. #ifndef BITCOIN_NET_H
  6. #define BITCOIN_NET_H
  7. #include "amount.h"
  8. #include "bloom.h"
  9. #include "compat.h"
  10. #include "limitedmap.h"
  11. #include "netbase.h"
  12. #include "protocol.h"
  13. #include "random.h"
  14. #include "streams.h"
  15. #include "sync.h"
  16. #include "uint256.h"
  17. #include <atomic>
  18. #include <deque>
  19. #include <stdint.h>
  20. #ifndef WIN32
  21. #include <arpa/inet.h>
  22. #endif
  23. #include <boost/filesystem/path.hpp>
  24. #include <boost/foreach.hpp>
  25. #include <boost/signals2/signal.hpp>
  26. class CAddrMan;
  27. class CScheduler;
  28. class CNode;
  29. namespace boost {
  30. class thread_group;
  31. } // namespace boost
  32. /** Time between pings automatically sent out for latency probing and keepalive (in seconds). */
  33. static const int PING_INTERVAL = 2 * 60;
  34. /** Time after which to disconnect, after waiting for a ping response (or inactivity). */
  35. static const int TIMEOUT_INTERVAL = 20 * 60;
  36. /** The maximum number of entries in an 'inv' protocol message */
  37. static const unsigned int MAX_INV_SZ = 50000;
  38. /** The maximum number of new addresses to accumulate before announcing. */
  39. static const unsigned int MAX_ADDR_TO_SEND = 1000;
  40. /** Maximum length of incoming protocol messages (no message over 2 MiB is currently acceptable). */
  41. static const unsigned int MAX_PROTOCOL_MESSAGE_LENGTH = 2 * 1024 * 1024;
  42. /** Maximum length of strSubVer in `version` message */
  43. static const unsigned int MAX_SUBVERSION_LENGTH = 256;
  44. /** -listen default */
  45. static const bool DEFAULT_LISTEN = true;
  46. /** -upnp default */
  47. #ifdef USE_UPNP
  48. static const bool DEFAULT_UPNP = USE_UPNP;
  49. #else
  50. static const bool DEFAULT_UPNP = false;
  51. #endif
  52. /** The maximum number of entries in mapAskFor */
  53. static const size_t MAPASKFOR_MAX_SZ = MAX_INV_SZ;
  54. /** The maximum number of entries in setAskFor (larger due to getdata latency)*/
  55. static const size_t SETASKFOR_MAX_SZ = 2 * MAX_INV_SZ;
  56. /** The maximum number of peer connections to maintain. */
  57. static const unsigned int DEFAULT_MAX_PEER_CONNECTIONS = 125;
  58. /** The default for -maxuploadtarget. 0 = Unlimited */
  59. static const uint64_t DEFAULT_MAX_UPLOAD_TARGET = 0;
  60. /** Default for blocks only*/
  61. static const bool DEFAULT_BLOCKSONLY = false;
  62. static const bool DEFAULT_FORCEDNSSEED = false;
  63. static const size_t DEFAULT_MAXRECEIVEBUFFER = 5 * 1000;
  64. static const size_t DEFAULT_MAXSENDBUFFER = 1 * 1000;
  65. static const ServiceFlags REQUIRED_SERVICES = NODE_NETWORK;
  66. // NOTE: When adjusting this, update rpcnet:setban's help ("24h")
  67. static const unsigned int DEFAULT_MISBEHAVING_BANTIME = 60 * 60 * 24; // Default 24-hour ban
  68. unsigned int ReceiveFloodSize();
  69. unsigned int SendBufferSize();
  70. typedef int NodeId;
  71. void AddOneShot(const std::string& strDest);
  72. void AddressCurrentlyConnected(const CService& addr);
  73. CNode* FindNode(const CNetAddr& ip);
  74. CNode* FindNode(const CSubNet& subNet);
  75. CNode* FindNode(const std::string& addrName);
  76. CNode* FindNode(const CService& ip);
  77. CNode* FindNode(const NodeId id); //TODO: Remove this
  78. bool OpenNetworkConnection(const CAddress& addrConnect, bool fCountFailure, CSemaphoreGrant *grantOutbound = NULL, const char *strDest = NULL, bool fOneShot = false);
  79. void MapPort(bool fUseUPnP);
  80. unsigned short GetListenPort();
  81. bool BindListenPort(const CService &bindAddr, std::string& strError, bool fWhitelisted = false);
  82. void StartNode(boost::thread_group& threadGroup, CScheduler& scheduler);
  83. bool StopNode();
  84. void SocketSendData(CNode *pnode);
  85. struct CombinerAll
  86. {
  87. typedef bool result_type;
  88. template<typename I>
  89. bool operator()(I first, I last) const
  90. {
  91. while (first != last) {
  92. if (!(*first)) return false;
  93. ++first;
  94. }
  95. return true;
  96. }
  97. };
  98. // Signals for message handling
  99. struct CNodeSignals
  100. {
  101. boost::signals2::signal<int ()> GetHeight;
  102. boost::signals2::signal<bool (CNode*), CombinerAll> ProcessMessages;
  103. boost::signals2::signal<bool (CNode*), CombinerAll> SendMessages;
  104. boost::signals2::signal<void (NodeId, const CNode*)> InitializeNode;
  105. boost::signals2::signal<void (NodeId)> FinalizeNode;
  106. };
  107. CNodeSignals& GetNodeSignals();
  108. enum
  109. {
  110. LOCAL_NONE, // unknown
  111. LOCAL_IF, // address a local interface listens on
  112. LOCAL_BIND, // address explicit bound to
  113. LOCAL_UPNP, // address reported by UPnP
  114. LOCAL_MANUAL, // address explicitly specified (-externalip=)
  115. LOCAL_MAX
  116. };
  117. bool IsPeerAddrLocalGood(CNode *pnode);
  118. void AdvertiseLocal(CNode *pnode);
  119. void SetLimited(enum Network net, bool fLimited = true);
  120. bool IsLimited(enum Network net);
  121. bool IsLimited(const CNetAddr& addr);
  122. bool AddLocal(const CService& addr, int nScore = LOCAL_NONE);
  123. bool AddLocal(const CNetAddr& addr, int nScore = LOCAL_NONE);
  124. bool RemoveLocal(const CService& addr);
  125. bool SeenLocal(const CService& addr);
  126. bool IsLocal(const CService& addr);
  127. bool GetLocal(CService &addr, const CNetAddr *paddrPeer = NULL);
  128. bool IsReachable(enum Network net);
  129. bool IsReachable(const CNetAddr &addr);
  130. CAddress GetLocalAddress(const CNetAddr *paddrPeer = NULL);
  131. extern bool fDiscover;
  132. extern bool fListen;
  133. extern ServiceFlags nLocalServices;
  134. extern bool fRelayTxes;
  135. extern uint64_t nLocalHostNonce;
  136. extern CAddrMan addrman;
  137. /** Maximum number of connections to simultaneously allow (aka connection slots) */
  138. extern int nMaxConnections;
  139. extern std::vector<CNode*> vNodes;
  140. extern CCriticalSection cs_vNodes;
  141. extern limitedmap<uint256, int64_t> mapAlreadyAskedFor;
  142. extern std::vector<std::string> vAddedNodes;
  143. extern CCriticalSection cs_vAddedNodes;
  144. extern NodeId nLastNodeId;
  145. extern CCriticalSection cs_nLastNodeId;
  146. /** Subversion as sent to the P2P network in `version` messages */
  147. extern std::string strSubVersion;
  148. struct LocalServiceInfo {
  149. int nScore;
  150. int nPort;
  151. };
  152. extern CCriticalSection cs_mapLocalHost;
  153. extern std::map<CNetAddr, LocalServiceInfo> mapLocalHost;
  154. typedef std::map<std::string, uint64_t> mapMsgCmdSize; //command, total bytes
  155. class CNodeStats
  156. {
  157. public:
  158. NodeId nodeid;
  159. ServiceFlags nServices;
  160. bool fRelayTxes;
  161. int64_t nLastSend;
  162. int64_t nLastRecv;
  163. int64_t nTimeConnected;
  164. int64_t nTimeOffset;
  165. std::string addrName;
  166. int nVersion;
  167. std::string cleanSubVer;
  168. bool fInbound;
  169. int nStartingHeight;
  170. uint64_t nSendBytes;
  171. mapMsgCmdSize mapSendBytesPerMsgCmd;
  172. uint64_t nRecvBytes;
  173. mapMsgCmdSize mapRecvBytesPerMsgCmd;
  174. bool fWhitelisted;
  175. double dPingTime;
  176. double dPingWait;
  177. double dPingMin;
  178. std::string addrLocal;
  179. };
  180. class CNetMessage {
  181. public:
  182. bool in_data; // parsing header (false) or data (true)
  183. CDataStream hdrbuf; // partially received header
  184. CMessageHeader hdr; // complete header
  185. unsigned int nHdrPos;
  186. CDataStream vRecv; // received message data
  187. unsigned int nDataPos;
  188. int64_t nTime; // time (in microseconds) of message receipt.
  189. CNetMessage(const CMessageHeader::MessageStartChars& pchMessageStartIn, int nTypeIn, int nVersionIn) : hdrbuf(nTypeIn, nVersionIn), hdr(pchMessageStartIn), vRecv(nTypeIn, nVersionIn) {
  190. hdrbuf.resize(24);
  191. in_data = false;
  192. nHdrPos = 0;
  193. nDataPos = 0;
  194. nTime = 0;
  195. }
  196. bool complete() const
  197. {
  198. if (!in_data)
  199. return false;
  200. return (hdr.nMessageSize == nDataPos);
  201. }
  202. void SetVersion(int nVersionIn)
  203. {
  204. hdrbuf.SetVersion(nVersionIn);
  205. vRecv.SetVersion(nVersionIn);
  206. }
  207. int readHeader(const char *pch, unsigned int nBytes);
  208. int readData(const char *pch, unsigned int nBytes);
  209. };
  210. typedef enum BanReason
  211. {
  212. BanReasonUnknown = 0,
  213. BanReasonNodeMisbehaving = 1,
  214. BanReasonManuallyAdded = 2
  215. } BanReason;
  216. class CBanEntry
  217. {
  218. public:
  219. static const int CURRENT_VERSION=1;
  220. int nVersion;
  221. int64_t nCreateTime;
  222. int64_t nBanUntil;
  223. uint8_t banReason;
  224. CBanEntry()
  225. {
  226. SetNull();
  227. }
  228. CBanEntry(int64_t nCreateTimeIn)
  229. {
  230. SetNull();
  231. nCreateTime = nCreateTimeIn;
  232. }
  233. ADD_SERIALIZE_METHODS;
  234. template <typename Stream, typename Operation>
  235. inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
  236. READWRITE(this->nVersion);
  237. nVersion = this->nVersion;
  238. READWRITE(nCreateTime);
  239. READWRITE(nBanUntil);
  240. READWRITE(banReason);
  241. }
  242. void SetNull()
  243. {
  244. nVersion = CBanEntry::CURRENT_VERSION;
  245. nCreateTime = 0;
  246. nBanUntil = 0;
  247. banReason = BanReasonUnknown;
  248. }
  249. std::string banReasonToString()
  250. {
  251. switch (banReason) {
  252. case BanReasonNodeMisbehaving:
  253. return "node misbehaving";
  254. case BanReasonManuallyAdded:
  255. return "manually added";
  256. default:
  257. return "unknown";
  258. }
  259. }
  260. };
  261. typedef std::map<CSubNet, CBanEntry> banmap_t;
  262. /** Information about a peer */
  263. class CNode
  264. {
  265. public:
  266. // socket
  267. ServiceFlags nServices;
  268. ServiceFlags nServicesExpected;
  269. SOCKET hSocket;
  270. CDataStream ssSend;
  271. size_t nSendSize; // total size of all vSendMsg entries
  272. size_t nSendOffset; // offset inside the first vSendMsg already sent
  273. uint64_t nSendBytes;
  274. std::deque<CSerializeData> vSendMsg;
  275. CCriticalSection cs_vSend;
  276. std::deque<CInv> vRecvGetData;
  277. std::deque<CNetMessage> vRecvMsg;
  278. CCriticalSection cs_vRecvMsg;
  279. uint64_t nRecvBytes;
  280. int nRecvVersion;
  281. int64_t nLastSend;
  282. int64_t nLastRecv;
  283. int64_t nTimeConnected;
  284. int64_t nTimeOffset;
  285. const CAddress addr;
  286. std::string addrName;
  287. CService addrLocal;
  288. int nVersion;
  289. // strSubVer is whatever byte array we read from the wire. However, this field is intended
  290. // to be printed out, displayed to humans in various forms and so on. So we sanitize it and
  291. // store the sanitized version in cleanSubVer. The original should be used when dealing with
  292. // the network or wire types and the cleaned string used when displayed or logged.
  293. std::string strSubVer, cleanSubVer;
  294. bool fWhitelisted; // This peer can bypass DoS banning.
  295. bool fOneShot;
  296. bool fClient;
  297. bool fInbound;
  298. bool fNetworkNode;
  299. bool fSuccessfullyConnected;
  300. bool fDisconnect;
  301. // We use fRelayTxes for two purposes -
  302. // a) it allows us to not relay tx invs before receiving the peer's version message
  303. // b) the peer may tell us in its version message that we should not relay tx invs
  304. // unless it loads a bloom filter.
  305. bool fRelayTxes; //protected by cs_filter
  306. bool fSentAddr;
  307. CSemaphoreGrant grantOutbound;
  308. CCriticalSection cs_filter;
  309. CBloomFilter* pfilter;
  310. int nRefCount;
  311. NodeId id;
  312. const uint64_t nKeyedNetGroup;
  313. protected:
  314. // Denial-of-service detection/prevention
  315. // Key is IP address, value is banned-until-time
  316. static banmap_t setBanned;
  317. static CCriticalSection cs_setBanned;
  318. static bool setBannedIsDirty;
  319. // Whitelisted ranges. Any node connecting from these is automatically
  320. // whitelisted (as well as those connecting to whitelisted binds).
  321. static std::vector<CSubNet> vWhitelistedRange;
  322. static CCriticalSection cs_vWhitelistedRange;
  323. mapMsgCmdSize mapSendBytesPerMsgCmd;
  324. mapMsgCmdSize mapRecvBytesPerMsgCmd;
  325. // Basic fuzz-testing
  326. void Fuzz(int nChance); // modifies ssSend
  327. public:
  328. uint256 hashContinue;
  329. int nStartingHeight;
  330. // flood relay
  331. std::vector<CAddress> vAddrToSend;
  332. CRollingBloomFilter addrKnown;
  333. bool fGetAddr;
  334. std::set<uint256> setKnown;
  335. int64_t nNextAddrSend;
  336. int64_t nNextLocalAddrSend;
  337. // inventory based relay
  338. CRollingBloomFilter filterInventoryKnown;
  339. // Set of transaction ids we still have to announce.
  340. // They are sorted by the mempool before relay, so the order is not important.
  341. std::set<uint256> setInventoryTxToSend;
  342. // List of block ids we still have announce.
  343. // There is no final sorting before sending, as they are always sent immediately
  344. // and in the order requested.
  345. std::vector<uint256> vInventoryBlockToSend;
  346. CCriticalSection cs_inventory;
  347. std::set<uint256> setAskFor;
  348. std::multimap<int64_t, CInv> mapAskFor;
  349. int64_t nNextInvSend;
  350. // Used for headers announcements - unfiltered blocks to relay
  351. // Also protected by cs_inventory
  352. std::vector<uint256> vBlockHashesToAnnounce;
  353. // Used for BIP35 mempool sending, also protected by cs_inventory
  354. bool fSendMempool;
  355. // Last time a "MEMPOOL" request was serviced.
  356. std::atomic<int64_t> timeLastMempoolReq;
  357. // Block and TXN accept times
  358. std::atomic<int64_t> nLastBlockTime;
  359. std::atomic<int64_t> nLastTXTime;
  360. // Ping time measurement:
  361. // The pong reply we're expecting, or 0 if no pong expected.
  362. uint64_t nPingNonceSent;
  363. // Time (in usec) the last ping was sent, or 0 if no ping was ever sent.
  364. int64_t nPingUsecStart;
  365. // Last measured round-trip time.
  366. int64_t nPingUsecTime;
  367. // Best measured round-trip time.
  368. int64_t nMinPingUsecTime;
  369. // Whether a ping is requested.
  370. bool fPingQueued;
  371. // Minimum fee rate with which to filter inv's to this node
  372. CAmount minFeeFilter;
  373. CCriticalSection cs_feeFilter;
  374. CAmount lastSentFeeFilter;
  375. int64_t nextSendTimeFeeFilter;
  376. CNode(SOCKET hSocketIn, const CAddress &addrIn, const std::string &addrNameIn = "", bool fInboundIn = false);
  377. ~CNode();
  378. private:
  379. // Network usage totals
  380. static CCriticalSection cs_totalBytesRecv;
  381. static CCriticalSection cs_totalBytesSent;
  382. static uint64_t nTotalBytesRecv;
  383. static uint64_t nTotalBytesSent;
  384. // outbound limit & stats
  385. static uint64_t nMaxOutboundTotalBytesSentInCycle;
  386. static uint64_t nMaxOutboundCycleStartTime;
  387. static uint64_t nMaxOutboundLimit;
  388. static uint64_t nMaxOutboundTimeframe;
  389. CNode(const CNode&);
  390. void operator=(const CNode&);
  391. static uint64_t CalculateKeyedNetGroup(const CAddress& ad);
  392. public:
  393. NodeId GetId() const {
  394. return id;
  395. }
  396. int GetRefCount()
  397. {
  398. assert(nRefCount >= 0);
  399. return nRefCount;
  400. }
  401. // requires LOCK(cs_vRecvMsg)
  402. unsigned int GetTotalRecvSize()
  403. {
  404. unsigned int total = 0;
  405. BOOST_FOREACH(const CNetMessage &msg, vRecvMsg)
  406. total += msg.vRecv.size() + 24;
  407. return total;
  408. }
  409. // requires LOCK(cs_vRecvMsg)
  410. bool ReceiveMsgBytes(const char *pch, unsigned int nBytes);
  411. // requires LOCK(cs_vRecvMsg)
  412. void SetRecvVersion(int nVersionIn)
  413. {
  414. nRecvVersion = nVersionIn;
  415. BOOST_FOREACH(CNetMessage &msg, vRecvMsg)
  416. msg.SetVersion(nVersionIn);
  417. }
  418. CNode* AddRef()
  419. {
  420. nRefCount++;
  421. return this;
  422. }
  423. void Release()
  424. {
  425. nRefCount--;
  426. }
  427. void AddAddressKnown(const CAddress& addr)
  428. {
  429. addrKnown.insert(addr.GetKey());
  430. }
  431. void PushAddress(const CAddress& addr)
  432. {
  433. // Known checking here is only to save space from duplicates.
  434. // SendMessages will filter it again for knowns that were added
  435. // after addresses were pushed.
  436. if (addr.IsValid() && !addrKnown.contains(addr.GetKey())) {
  437. if (vAddrToSend.size() >= MAX_ADDR_TO_SEND) {
  438. vAddrToSend[insecure_rand() % vAddrToSend.size()] = addr;
  439. } else {
  440. vAddrToSend.push_back(addr);
  441. }
  442. }
  443. }
  444. void AddInventoryKnown(const CInv& inv)
  445. {
  446. {
  447. LOCK(cs_inventory);
  448. filterInventoryKnown.insert(inv.hash);
  449. }
  450. }
  451. void PushInventory(const CInv& inv)
  452. {
  453. LOCK(cs_inventory);
  454. if (inv.type == MSG_TX) {
  455. if (!filterInventoryKnown.contains(inv.hash)) {
  456. setInventoryTxToSend.insert(inv.hash);
  457. }
  458. } else if (inv.type == MSG_BLOCK) {
  459. vInventoryBlockToSend.push_back(inv.hash);
  460. }
  461. }
  462. void PushBlockHash(const uint256 &hash)
  463. {
  464. LOCK(cs_inventory);
  465. vBlockHashesToAnnounce.push_back(hash);
  466. }
  467. void AskFor(const CInv& inv);
  468. // TODO: Document the postcondition of this function. Is cs_vSend locked?
  469. void BeginMessage(const char* pszCommand) EXCLUSIVE_LOCK_FUNCTION(cs_vSend);
  470. // TODO: Document the precondition of this function. Is cs_vSend locked?
  471. void AbortMessage() UNLOCK_FUNCTION(cs_vSend);
  472. // TODO: Document the precondition of this function. Is cs_vSend locked?
  473. void EndMessage(const char* pszCommand) UNLOCK_FUNCTION(cs_vSend);
  474. void PushVersion();
  475. void PushMessage(const char* pszCommand)
  476. {
  477. try
  478. {
  479. BeginMessage(pszCommand);
  480. EndMessage(pszCommand);
  481. }
  482. catch (...)
  483. {
  484. AbortMessage();
  485. throw;
  486. }
  487. }
  488. template<typename T1>
  489. void PushMessage(const char* pszCommand, const T1& a1)
  490. {
  491. try
  492. {
  493. BeginMessage(pszCommand);
  494. ssSend << a1;
  495. EndMessage(pszCommand);
  496. }
  497. catch (...)
  498. {
  499. AbortMessage();
  500. throw;
  501. }
  502. }
  503. template<typename T1, typename T2>
  504. void PushMessage(const char* pszCommand, const T1& a1, const T2& a2)
  505. {
  506. try
  507. {
  508. BeginMessage(pszCommand);
  509. ssSend << a1 << a2;
  510. EndMessage(pszCommand);
  511. }
  512. catch (...)
  513. {
  514. AbortMessage();
  515. throw;
  516. }
  517. }
  518. template<typename T1, typename T2, typename T3>
  519. void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3)
  520. {
  521. try
  522. {
  523. BeginMessage(pszCommand);
  524. ssSend << a1 << a2 << a3;
  525. EndMessage(pszCommand);
  526. }
  527. catch (...)
  528. {
  529. AbortMessage();
  530. throw;
  531. }
  532. }
  533. template<typename T1, typename T2, typename T3, typename T4>
  534. void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4)
  535. {
  536. try
  537. {
  538. BeginMessage(pszCommand);
  539. ssSend << a1 << a2 << a3 << a4;
  540. EndMessage(pszCommand);
  541. }
  542. catch (...)
  543. {
  544. AbortMessage();
  545. throw;
  546. }
  547. }
  548. template<typename T1, typename T2, typename T3, typename T4, typename T5>
  549. void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4, const T5& a5)
  550. {
  551. try
  552. {
  553. BeginMessage(pszCommand);
  554. ssSend << a1 << a2 << a3 << a4 << a5;
  555. EndMessage(pszCommand);
  556. }
  557. catch (...)
  558. {
  559. AbortMessage();
  560. throw;
  561. }
  562. }
  563. template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6>
  564. void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4, const T5& a5, const T6& a6)
  565. {
  566. try
  567. {
  568. BeginMessage(pszCommand);
  569. ssSend << a1 << a2 << a3 << a4 << a5 << a6;
  570. EndMessage(pszCommand);
  571. }
  572. catch (...)
  573. {
  574. AbortMessage();
  575. throw;
  576. }
  577. }
  578. template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7>
  579. void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4, const T5& a5, const T6& a6, const T7& a7)
  580. {
  581. try
  582. {
  583. BeginMessage(pszCommand);
  584. ssSend << a1 << a2 << a3 << a4 << a5 << a6 << a7;
  585. EndMessage(pszCommand);
  586. }
  587. catch (...)
  588. {
  589. AbortMessage();
  590. throw;
  591. }
  592. }
  593. template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8>
  594. void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4, const T5& a5, const T6& a6, const T7& a7, const T8& a8)
  595. {
  596. try
  597. {
  598. BeginMessage(pszCommand);
  599. ssSend << a1 << a2 << a3 << a4 << a5 << a6 << a7 << a8;
  600. EndMessage(pszCommand);
  601. }
  602. catch (...)
  603. {
  604. AbortMessage();
  605. throw;
  606. }
  607. }
  608. template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9>
  609. void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4, const T5& a5, const T6& a6, const T7& a7, const T8& a8, const T9& a9)
  610. {
  611. try
  612. {
  613. BeginMessage(pszCommand);
  614. ssSend << a1 << a2 << a3 << a4 << a5 << a6 << a7 << a8 << a9;
  615. EndMessage(pszCommand);
  616. }
  617. catch (...)
  618. {
  619. AbortMessage();
  620. throw;
  621. }
  622. }
  623. void CloseSocketDisconnect();
  624. // Denial-of-service detection/prevention
  625. // The idea is to detect peers that are behaving
  626. // badly and disconnect/ban them, but do it in a
  627. // one-coding-mistake-won't-shatter-the-entire-network
  628. // way.
  629. // IMPORTANT: There should be nothing I can give a
  630. // node that it will forward on that will make that
  631. // node's peers drop it. If there is, an attacker
  632. // can isolate a node and/or try to split the network.
  633. // Dropping a node for sending stuff that is invalid
  634. // now but might be valid in a later version is also
  635. // dangerous, because it can cause a network split
  636. // between nodes running old code and nodes running
  637. // new code.
  638. static void ClearBanned(); // needed for unit testing
  639. static bool IsBanned(CNetAddr ip);
  640. static bool IsBanned(CSubNet subnet);
  641. static void Ban(const CNetAddr &ip, const BanReason &banReason, int64_t bantimeoffset = 0, bool sinceUnixEpoch = false);
  642. static void Ban(const CSubNet &subNet, const BanReason &banReason, int64_t bantimeoffset = 0, bool sinceUnixEpoch = false);
  643. static bool Unban(const CNetAddr &ip);
  644. static bool Unban(const CSubNet &ip);
  645. static void GetBanned(banmap_t &banmap);
  646. static void SetBanned(const banmap_t &banmap);
  647. //!check is the banlist has unwritten changes
  648. static bool BannedSetIsDirty();
  649. //!set the "dirty" flag for the banlist
  650. static void SetBannedSetDirty(bool dirty=true);
  651. //!clean unused entries (if bantime has expired)
  652. static void SweepBanned();
  653. void copyStats(CNodeStats &stats);
  654. static bool IsWhitelistedRange(const CNetAddr &ip);
  655. static void AddWhitelistedRange(const CSubNet &subnet);
  656. // Network stats
  657. static void RecordBytesRecv(uint64_t bytes);
  658. static void RecordBytesSent(uint64_t bytes);
  659. static uint64_t GetTotalBytesRecv();
  660. static uint64_t GetTotalBytesSent();
  661. //!set the max outbound target in bytes
  662. static void SetMaxOutboundTarget(uint64_t limit);
  663. static uint64_t GetMaxOutboundTarget();
  664. //!set the timeframe for the max outbound target
  665. static void SetMaxOutboundTimeframe(uint64_t timeframe);
  666. static uint64_t GetMaxOutboundTimeframe();
  667. //!check if the outbound target is reached
  668. // if param historicalBlockServingLimit is set true, the function will
  669. // response true if the limit for serving historical blocks has been reached
  670. static bool OutboundTargetReached(bool historicalBlockServingLimit);
  671. //!response the bytes left in the current max outbound cycle
  672. // in case of no limit, it will always response 0
  673. static uint64_t GetOutboundTargetBytesLeft();
  674. //!response the time in second left in the current max outbound cycle
  675. // in case of no limit, it will always response 0
  676. static uint64_t GetMaxOutboundTimeLeftInCycle();
  677. };
  678. class CTransaction;
  679. void RelayTransaction(const CTransaction& tx);
  680. /** Access to the (IP) address database (peers.dat) */
  681. class CAddrDB
  682. {
  683. private:
  684. boost::filesystem::path pathAddr;
  685. public:
  686. CAddrDB();
  687. bool Write(const CAddrMan& addr);
  688. bool Read(CAddrMan& addr);
  689. bool Read(CAddrMan& addr, CDataStream& ssPeers);
  690. };
  691. /** Access to the banlist database (banlist.dat) */
  692. class CBanDB
  693. {
  694. private:
  695. boost::filesystem::path pathBanlist;
  696. public:
  697. CBanDB();
  698. bool Write(const banmap_t& banSet);
  699. bool Read(banmap_t& banSet);
  700. };
  701. /** Return a timestamp in the future (in microseconds) for exponentially distributed events. */
  702. int64_t PoissonNextSend(int64_t nNow, int average_interval_seconds);
  703. struct AddedNodeInfo
  704. {
  705. std::string strAddedNode;
  706. CService resolvedAddress;
  707. bool fConnected;
  708. bool fInbound;
  709. };
  710. std::vector<AddedNodeInfo> GetAddedNodeInfo();
  711. #endif // BITCOIN_NET_H