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

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