Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

net.h 17KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616
  1. // Copyright (c) 2009-2010 Satoshi Nakamoto
  2. // Copyright (c) 2009-2014 The Bitcoin developers
  3. // Distributed under the MIT/X11 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 "hash.h"
  10. #include "limitedmap.h"
  11. #include "mruset.h"
  12. #include "netbase.h"
  13. #include "protocol.h"
  14. #include "random.h"
  15. #include "sync.h"
  16. #include "uint256.h"
  17. #include "utilstrencodings.h"
  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 CBlockIndex;
  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. /** -listen default */
  39. static const bool DEFAULT_LISTEN = true;
  40. /** -upnp default */
  41. #ifdef USE_UPNP
  42. static const bool DEFAULT_UPNP = USE_UPNP;
  43. #else
  44. static const bool DEFAULT_UPNP = false;
  45. #endif
  46. /** The maximum number of entries in mapAskFor */
  47. static const size_t MAPASKFOR_MAX_SZ = MAX_INV_SZ;
  48. unsigned int ReceiveFloodSize();
  49. unsigned int SendBufferSize();
  50. void AddOneShot(std::string strDest);
  51. bool RecvLine(SOCKET hSocket, std::string& strLine);
  52. bool GetMyExternalIP(CNetAddr& ipRet);
  53. void AddressCurrentlyConnected(const CService& addr);
  54. CNode* FindNode(const CNetAddr& ip);
  55. CNode* FindNode(const std::string& addrName);
  56. CNode* FindNode(const CService& ip);
  57. CNode* ConnectNode(CAddress addrConnect, const char *pszDest = NULL);
  58. bool OpenNetworkConnection(const CAddress& addrConnect, CSemaphoreGrant *grantOutbound = NULL, const char *strDest = NULL, bool fOneShot = false);
  59. void MapPort(bool fUseUPnP);
  60. unsigned short GetListenPort();
  61. bool BindListenPort(const CService &bindAddr, std::string& strError, bool fWhitelisted = false);
  62. void StartNode(boost::thread_group& threadGroup);
  63. bool StopNode();
  64. void SocketSendData(CNode *pnode);
  65. typedef int NodeId;
  66. // Signals for message handling
  67. struct CNodeSignals
  68. {
  69. boost::signals2::signal<int ()> GetHeight;
  70. boost::signals2::signal<bool (CNode*)> ProcessMessages;
  71. boost::signals2::signal<bool (CNode*, bool)> SendMessages;
  72. boost::signals2::signal<void (NodeId, const CNode*)> InitializeNode;
  73. boost::signals2::signal<void (NodeId)> FinalizeNode;
  74. };
  75. CNodeSignals& GetNodeSignals();
  76. enum
  77. {
  78. LOCAL_NONE, // unknown
  79. LOCAL_IF, // address a local interface listens on
  80. LOCAL_BIND, // address explicit bound to
  81. LOCAL_UPNP, // address reported by UPnP
  82. LOCAL_HTTP, // address reported by whatismyip.com and similar
  83. LOCAL_MANUAL, // address explicitly specified (-externalip=)
  84. LOCAL_MAX
  85. };
  86. void SetLimited(enum Network net, bool fLimited = true);
  87. bool IsLimited(enum Network net);
  88. bool IsLimited(const CNetAddr& addr);
  89. bool AddLocal(const CService& addr, int nScore = LOCAL_NONE);
  90. bool AddLocal(const CNetAddr& addr, int nScore = LOCAL_NONE);
  91. bool SeenLocal(const CService& addr);
  92. bool IsLocal(const CService& addr);
  93. bool GetLocal(CService &addr, const CNetAddr *paddrPeer = NULL);
  94. bool IsReachable(enum Network net);
  95. bool IsReachable(const CNetAddr &addr);
  96. void SetReachable(enum Network net, bool fFlag = true);
  97. CAddress GetLocalAddress(const CNetAddr *paddrPeer = NULL);
  98. extern bool fDiscover;
  99. extern bool fListen;
  100. extern uint64_t nLocalServices;
  101. extern uint64_t nLocalHostNonce;
  102. extern CAddrMan addrman;
  103. extern int nMaxConnections;
  104. extern std::vector<CNode*> vNodes;
  105. extern CCriticalSection cs_vNodes;
  106. extern std::map<CInv, CDataStream> mapRelay;
  107. extern std::deque<std::pair<int64_t, CInv> > vRelayExpiration;
  108. extern CCriticalSection cs_mapRelay;
  109. extern limitedmap<CInv, int64_t> mapAlreadyAskedFor;
  110. extern std::vector<std::string> vAddedNodes;
  111. extern CCriticalSection cs_vAddedNodes;
  112. extern NodeId nLastNodeId;
  113. extern CCriticalSection cs_nLastNodeId;
  114. struct LocalServiceInfo {
  115. int nScore;
  116. int nPort;
  117. };
  118. extern CCriticalSection cs_mapLocalHost;
  119. extern std::map<CNetAddr, LocalServiceInfo> mapLocalHost;
  120. class CNodeStats
  121. {
  122. public:
  123. NodeId nodeid;
  124. uint64_t nServices;
  125. int64_t nLastSend;
  126. int64_t nLastRecv;
  127. int64_t nTimeConnected;
  128. std::string addrName;
  129. int nVersion;
  130. std::string cleanSubVer;
  131. bool fInbound;
  132. int nStartingHeight;
  133. uint64_t nSendBytes;
  134. uint64_t nRecvBytes;
  135. bool fWhitelisted;
  136. double dPingTime;
  137. double dPingWait;
  138. std::string addrLocal;
  139. };
  140. class CNetMessage {
  141. public:
  142. bool in_data; // parsing header (false) or data (true)
  143. CDataStream hdrbuf; // partially received header
  144. CMessageHeader hdr; // complete header
  145. unsigned int nHdrPos;
  146. CDataStream vRecv; // received message data
  147. unsigned int nDataPos;
  148. int64_t nTime; // time (in microseconds) of message receipt.
  149. CNetMessage(int nTypeIn, int nVersionIn) : hdrbuf(nTypeIn, nVersionIn), vRecv(nTypeIn, nVersionIn) {
  150. hdrbuf.resize(24);
  151. in_data = false;
  152. nHdrPos = 0;
  153. nDataPos = 0;
  154. nTime = 0;
  155. }
  156. bool complete() const
  157. {
  158. if (!in_data)
  159. return false;
  160. return (hdr.nMessageSize == nDataPos);
  161. }
  162. void SetVersion(int nVersionIn)
  163. {
  164. hdrbuf.SetVersion(nVersionIn);
  165. vRecv.SetVersion(nVersionIn);
  166. }
  167. int readHeader(const char *pch, unsigned int nBytes);
  168. int readData(const char *pch, unsigned int nBytes);
  169. };
  170. /** Information about a peer */
  171. class CNode
  172. {
  173. public:
  174. // socket
  175. uint64_t nServices;
  176. SOCKET hSocket;
  177. CDataStream ssSend;
  178. size_t nSendSize; // total size of all vSendMsg entries
  179. size_t nSendOffset; // offset inside the first vSendMsg already sent
  180. uint64_t nSendBytes;
  181. std::deque<CSerializeData> vSendMsg;
  182. CCriticalSection cs_vSend;
  183. std::deque<CInv> vRecvGetData;
  184. std::deque<CNetMessage> vRecvMsg;
  185. CCriticalSection cs_vRecvMsg;
  186. uint64_t nRecvBytes;
  187. int nRecvVersion;
  188. int64_t nLastSend;
  189. int64_t nLastRecv;
  190. int64_t nTimeConnected;
  191. CAddress addr;
  192. std::string addrName;
  193. CService addrLocal;
  194. int nVersion;
  195. // strSubVer is whatever byte array we read from the wire. However, this field is intended
  196. // to be printed out, displayed to humans in various forms and so on. So we sanitize it and
  197. // store the sanitized version in cleanSubVer. The original should be used when dealing with
  198. // the network or wire types and the cleaned string used when displayed or logged.
  199. std::string strSubVer, cleanSubVer;
  200. bool fWhitelisted; // This peer can bypass DoS banning.
  201. bool fOneShot;
  202. bool fClient;
  203. bool fInbound;
  204. bool fNetworkNode;
  205. bool fSuccessfullyConnected;
  206. bool fDisconnect;
  207. // We use fRelayTxes for two purposes -
  208. // a) it allows us to not relay tx invs before receiving the peer's version message
  209. // b) the peer may tell us in their version message that we should not relay tx invs
  210. // until they have initialized their bloom filter.
  211. bool fRelayTxes;
  212. CSemaphoreGrant grantOutbound;
  213. CCriticalSection cs_filter;
  214. CBloomFilter* pfilter;
  215. int nRefCount;
  216. NodeId id;
  217. protected:
  218. // Denial-of-service detection/prevention
  219. // Key is IP address, value is banned-until-time
  220. static std::map<CNetAddr, int64_t> setBanned;
  221. static CCriticalSection cs_setBanned;
  222. // Whitelisted ranges. Any node connecting from these is automatically
  223. // whitelisted (as well as those connecting to whitelisted binds).
  224. static std::vector<CSubNet> vWhitelistedRange;
  225. static CCriticalSection cs_vWhitelistedRange;
  226. // Basic fuzz-testing
  227. void Fuzz(int nChance); // modifies ssSend
  228. public:
  229. uint256 hashContinue;
  230. int nStartingHeight;
  231. // flood relay
  232. std::vector<CAddress> vAddrToSend;
  233. mruset<CAddress> setAddrKnown;
  234. bool fGetAddr;
  235. std::set<uint256> setKnown;
  236. // inventory based relay
  237. mruset<CInv> setInventoryKnown;
  238. std::vector<CInv> vInventoryToSend;
  239. CCriticalSection cs_inventory;
  240. std::multimap<int64_t, CInv> mapAskFor;
  241. // Ping time measurement:
  242. // The pong reply we're expecting, or 0 if no pong expected.
  243. uint64_t nPingNonceSent;
  244. // Time (in usec) the last ping was sent, or 0 if no ping was ever sent.
  245. int64_t nPingUsecStart;
  246. // Last measured round-trip time.
  247. int64_t nPingUsecTime;
  248. // Whether a ping is requested.
  249. bool fPingQueued;
  250. CNode(SOCKET hSocketIn, CAddress addrIn, std::string addrNameIn = "", bool fInboundIn=false);
  251. ~CNode();
  252. private:
  253. // Network usage totals
  254. static CCriticalSection cs_totalBytesRecv;
  255. static CCriticalSection cs_totalBytesSent;
  256. static uint64_t nTotalBytesRecv;
  257. static uint64_t nTotalBytesSent;
  258. CNode(const CNode&);
  259. void operator=(const CNode&);
  260. public:
  261. NodeId GetId() const {
  262. return id;
  263. }
  264. int GetRefCount()
  265. {
  266. assert(nRefCount >= 0);
  267. return nRefCount;
  268. }
  269. // requires LOCK(cs_vRecvMsg)
  270. unsigned int GetTotalRecvSize()
  271. {
  272. unsigned int total = 0;
  273. BOOST_FOREACH(const CNetMessage &msg, vRecvMsg)
  274. total += msg.vRecv.size() + 24;
  275. return total;
  276. }
  277. // requires LOCK(cs_vRecvMsg)
  278. bool ReceiveMsgBytes(const char *pch, unsigned int nBytes);
  279. // requires LOCK(cs_vRecvMsg)
  280. void SetRecvVersion(int nVersionIn)
  281. {
  282. nRecvVersion = nVersionIn;
  283. BOOST_FOREACH(CNetMessage &msg, vRecvMsg)
  284. msg.SetVersion(nVersionIn);
  285. }
  286. CNode* AddRef()
  287. {
  288. nRefCount++;
  289. return this;
  290. }
  291. void Release()
  292. {
  293. nRefCount--;
  294. }
  295. void AddAddressKnown(const CAddress& addr)
  296. {
  297. setAddrKnown.insert(addr);
  298. }
  299. void PushAddress(const CAddress& addr)
  300. {
  301. // Known checking here is only to save space from duplicates.
  302. // SendMessages will filter it again for knowns that were added
  303. // after addresses were pushed.
  304. if (addr.IsValid() && !setAddrKnown.count(addr))
  305. vAddrToSend.push_back(addr);
  306. }
  307. void AddInventoryKnown(const CInv& inv)
  308. {
  309. {
  310. LOCK(cs_inventory);
  311. setInventoryKnown.insert(inv);
  312. }
  313. }
  314. void PushInventory(const CInv& inv)
  315. {
  316. {
  317. LOCK(cs_inventory);
  318. if (!setInventoryKnown.count(inv))
  319. vInventoryToSend.push_back(inv);
  320. }
  321. }
  322. void AskFor(const CInv& inv);
  323. // TODO: Document the postcondition of this function. Is cs_vSend locked?
  324. void BeginMessage(const char* pszCommand) EXCLUSIVE_LOCK_FUNCTION(cs_vSend);
  325. // TODO: Document the precondition of this function. Is cs_vSend locked?
  326. void AbortMessage() UNLOCK_FUNCTION(cs_vSend);
  327. // TODO: Document the precondition of this function. Is cs_vSend locked?
  328. void EndMessage() UNLOCK_FUNCTION(cs_vSend);
  329. void PushVersion();
  330. void PushMessage(const char* pszCommand)
  331. {
  332. try
  333. {
  334. BeginMessage(pszCommand);
  335. EndMessage();
  336. }
  337. catch (...)
  338. {
  339. AbortMessage();
  340. throw;
  341. }
  342. }
  343. template<typename T1>
  344. void PushMessage(const char* pszCommand, const T1& a1)
  345. {
  346. try
  347. {
  348. BeginMessage(pszCommand);
  349. ssSend << a1;
  350. EndMessage();
  351. }
  352. catch (...)
  353. {
  354. AbortMessage();
  355. throw;
  356. }
  357. }
  358. template<typename T1, typename T2>
  359. void PushMessage(const char* pszCommand, const T1& a1, const T2& a2)
  360. {
  361. try
  362. {
  363. BeginMessage(pszCommand);
  364. ssSend << a1 << a2;
  365. EndMessage();
  366. }
  367. catch (...)
  368. {
  369. AbortMessage();
  370. throw;
  371. }
  372. }
  373. template<typename T1, typename T2, typename T3>
  374. void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3)
  375. {
  376. try
  377. {
  378. BeginMessage(pszCommand);
  379. ssSend << a1 << a2 << a3;
  380. EndMessage();
  381. }
  382. catch (...)
  383. {
  384. AbortMessage();
  385. throw;
  386. }
  387. }
  388. template<typename T1, typename T2, typename T3, typename T4>
  389. void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4)
  390. {
  391. try
  392. {
  393. BeginMessage(pszCommand);
  394. ssSend << a1 << a2 << a3 << a4;
  395. EndMessage();
  396. }
  397. catch (...)
  398. {
  399. AbortMessage();
  400. throw;
  401. }
  402. }
  403. template<typename T1, typename T2, typename T3, typename T4, typename T5>
  404. void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4, const T5& a5)
  405. {
  406. try
  407. {
  408. BeginMessage(pszCommand);
  409. ssSend << a1 << a2 << a3 << a4 << a5;
  410. EndMessage();
  411. }
  412. catch (...)
  413. {
  414. AbortMessage();
  415. throw;
  416. }
  417. }
  418. template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6>
  419. void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4, const T5& a5, const T6& a6)
  420. {
  421. try
  422. {
  423. BeginMessage(pszCommand);
  424. ssSend << a1 << a2 << a3 << a4 << a5 << a6;
  425. EndMessage();
  426. }
  427. catch (...)
  428. {
  429. AbortMessage();
  430. throw;
  431. }
  432. }
  433. template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7>
  434. 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)
  435. {
  436. try
  437. {
  438. BeginMessage(pszCommand);
  439. ssSend << a1 << a2 << a3 << a4 << a5 << a6 << a7;
  440. EndMessage();
  441. }
  442. catch (...)
  443. {
  444. AbortMessage();
  445. throw;
  446. }
  447. }
  448. template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8>
  449. 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)
  450. {
  451. try
  452. {
  453. BeginMessage(pszCommand);
  454. ssSend << a1 << a2 << a3 << a4 << a5 << a6 << a7 << a8;
  455. EndMessage();
  456. }
  457. catch (...)
  458. {
  459. AbortMessage();
  460. throw;
  461. }
  462. }
  463. template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9>
  464. 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)
  465. {
  466. try
  467. {
  468. BeginMessage(pszCommand);
  469. ssSend << a1 << a2 << a3 << a4 << a5 << a6 << a7 << a8 << a9;
  470. EndMessage();
  471. }
  472. catch (...)
  473. {
  474. AbortMessage();
  475. throw;
  476. }
  477. }
  478. bool IsSubscribed(unsigned int nChannel);
  479. void Subscribe(unsigned int nChannel, unsigned int nHops=0);
  480. void CancelSubscribe(unsigned int nChannel);
  481. void CloseSocketDisconnect();
  482. // Denial-of-service detection/prevention
  483. // The idea is to detect peers that are behaving
  484. // badly and disconnect/ban them, but do it in a
  485. // one-coding-mistake-won't-shatter-the-entire-network
  486. // way.
  487. // IMPORTANT: There should be nothing I can give a
  488. // node that it will forward on that will make that
  489. // node's peers drop it. If there is, an attacker
  490. // can isolate a node and/or try to split the network.
  491. // Dropping a node for sending stuff that is invalid
  492. // now but might be valid in a later version is also
  493. // dangerous, because it can cause a network split
  494. // between nodes running old code and nodes running
  495. // new code.
  496. static void ClearBanned(); // needed for unit testing
  497. static bool IsBanned(CNetAddr ip);
  498. static bool Ban(const CNetAddr &ip);
  499. void copyStats(CNodeStats &stats);
  500. static bool IsWhitelistedRange(const CNetAddr &ip);
  501. static void AddWhitelistedRange(const CSubNet &subnet);
  502. // Network stats
  503. static void RecordBytesRecv(uint64_t bytes);
  504. static void RecordBytesSent(uint64_t bytes);
  505. static uint64_t GetTotalBytesRecv();
  506. static uint64_t GetTotalBytesSent();
  507. };
  508. class CTransaction;
  509. void RelayTransaction(const CTransaction& tx);
  510. void RelayTransaction(const CTransaction& tx, const CDataStream& ss);
  511. /** Access to the (IP) address database (peers.dat) */
  512. class CAddrDB
  513. {
  514. private:
  515. boost::filesystem::path pathAddr;
  516. public:
  517. CAddrDB();
  518. bool Write(const CAddrMan& addr);
  519. bool Read(CAddrMan& addr);
  520. };
  521. #endif // BITCOIN_NET_H