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.

addrman.h 16KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508
  1. // Copyright (c) 2012 Pieter Wuille
  2. // Distributed under the MIT/X11 software license, see the accompanying
  3. // file COPYING or http://www.opensource.org/licenses/mit-license.php.
  4. #ifndef _BITCOIN_ADDRMAN
  5. #define _BITCOIN_ADDRMAN
  6. #include "netbase.h"
  7. #include "protocol.h"
  8. #include "random.h"
  9. #include "sync.h"
  10. #include "timedata.h"
  11. #include "util.h"
  12. #include <map>
  13. #include <set>
  14. #include <stdint.h>
  15. #include <vector>
  16. /** Extended statistics about a CAddress */
  17. class CAddrInfo : public CAddress
  18. {
  19. private:
  20. // where knowledge about this address first came from
  21. CNetAddr source;
  22. // last successful connection by us
  23. int64_t nLastSuccess;
  24. // last try whatsoever by us:
  25. // int64_t CAddress::nLastTry
  26. // connection attempts since last successful attempt
  27. int nAttempts;
  28. // reference count in new sets (memory only)
  29. int nRefCount;
  30. // in tried set? (memory only)
  31. bool fInTried;
  32. // position in vRandom
  33. int nRandomPos;
  34. friend class CAddrMan;
  35. public:
  36. ADD_SERIALIZE_METHODS;
  37. template <typename Stream, typename Operation>
  38. inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
  39. READWRITE(*(CAddress*)this);
  40. READWRITE(source);
  41. READWRITE(nLastSuccess);
  42. READWRITE(nAttempts);
  43. }
  44. void Init()
  45. {
  46. nLastSuccess = 0;
  47. nLastTry = 0;
  48. nAttempts = 0;
  49. nRefCount = 0;
  50. fInTried = false;
  51. nRandomPos = -1;
  52. }
  53. CAddrInfo(const CAddress &addrIn, const CNetAddr &addrSource) : CAddress(addrIn), source(addrSource)
  54. {
  55. Init();
  56. }
  57. CAddrInfo() : CAddress(), source()
  58. {
  59. Init();
  60. }
  61. // Calculate in which "tried" bucket this entry belongs
  62. int GetTriedBucket(const std::vector<unsigned char> &nKey) const;
  63. // Calculate in which "new" bucket this entry belongs, given a certain source
  64. int GetNewBucket(const std::vector<unsigned char> &nKey, const CNetAddr& src) const;
  65. // Calculate in which "new" bucket this entry belongs, using its default source
  66. int GetNewBucket(const std::vector<unsigned char> &nKey) const
  67. {
  68. return GetNewBucket(nKey, source);
  69. }
  70. // Determine whether the statistics about this entry are bad enough so that it can just be deleted
  71. bool IsTerrible(int64_t nNow = GetAdjustedTime()) const;
  72. // Calculate the relative chance this entry should be given when selecting nodes to connect to
  73. double GetChance(int64_t nNow = GetAdjustedTime()) const;
  74. };
  75. // Stochastic address manager
  76. //
  77. // Design goals:
  78. // * Only keep a limited number of addresses around, so that addr.dat and memory requirements do not grow without bound.
  79. // * Keep the address tables in-memory, and asynchronously dump the entire to able in addr.dat.
  80. // * Make sure no (localized) attacker can fill the entire table with his nodes/addresses.
  81. //
  82. // To that end:
  83. // * Addresses are organized into buckets.
  84. // * Address that have not yet been tried go into 256 "new" buckets.
  85. // * Based on the address range (/16 for IPv4) of source of the information, 32 buckets are selected at random
  86. // * The actual bucket is chosen from one of these, based on the range the address itself is located.
  87. // * One single address can occur in up to 4 different buckets, to increase selection chances for addresses that
  88. // are seen frequently. The chance for increasing this multiplicity decreases exponentially.
  89. // * When adding a new address to a full bucket, a randomly chosen entry (with a bias favoring less recently seen
  90. // ones) is removed from it first.
  91. // * Addresses of nodes that are known to be accessible go into 64 "tried" buckets.
  92. // * Each address range selects at random 4 of these buckets.
  93. // * The actual bucket is chosen from one of these, based on the full address.
  94. // * When adding a new good address to a full bucket, a randomly chosen entry (with a bias favoring less recently
  95. // tried ones) is evicted from it, back to the "new" buckets.
  96. // * Bucket selection is based on cryptographic hashing, using a randomly-generated 256-bit key, which should not
  97. // be observable by adversaries.
  98. // * Several indexes are kept for high performance. Defining DEBUG_ADDRMAN will introduce frequent (and expensive)
  99. // consistency checks for the entire data structure.
  100. // total number of buckets for tried addresses
  101. #define ADDRMAN_TRIED_BUCKET_COUNT 64
  102. // maximum allowed number of entries in buckets for tried addresses
  103. #define ADDRMAN_TRIED_BUCKET_SIZE 64
  104. // total number of buckets for new addresses
  105. #define ADDRMAN_NEW_BUCKET_COUNT 256
  106. // maximum allowed number of entries in buckets for new addresses
  107. #define ADDRMAN_NEW_BUCKET_SIZE 64
  108. // over how many buckets entries with tried addresses from a single group (/16 for IPv4) are spread
  109. #define ADDRMAN_TRIED_BUCKETS_PER_GROUP 4
  110. // over how many buckets entries with new addresses originating from a single group are spread
  111. #define ADDRMAN_NEW_BUCKETS_PER_SOURCE_GROUP 32
  112. // in how many buckets for entries with new addresses a single address may occur
  113. #define ADDRMAN_NEW_BUCKETS_PER_ADDRESS 4
  114. // how many entries in a bucket with tried addresses are inspected, when selecting one to replace
  115. #define ADDRMAN_TRIED_ENTRIES_INSPECT_ON_EVICT 4
  116. // how old addresses can maximally be
  117. #define ADDRMAN_HORIZON_DAYS 30
  118. // after how many failed attempts we give up on a new node
  119. #define ADDRMAN_RETRIES 3
  120. // how many successive failures are allowed ...
  121. #define ADDRMAN_MAX_FAILURES 10
  122. // ... in at least this many days
  123. #define ADDRMAN_MIN_FAIL_DAYS 7
  124. // the maximum percentage of nodes to return in a getaddr call
  125. #define ADDRMAN_GETADDR_MAX_PCT 23
  126. // the maximum number of nodes to return in a getaddr call
  127. #define ADDRMAN_GETADDR_MAX 2500
  128. /** Stochastical (IP) address manager */
  129. class CAddrMan
  130. {
  131. private:
  132. // critical section to protect the inner data structures
  133. mutable CCriticalSection cs;
  134. // secret key to randomize bucket select with
  135. std::vector<unsigned char> nKey;
  136. // last used nId
  137. int nIdCount;
  138. // table with information about all nIds
  139. std::map<int, CAddrInfo> mapInfo;
  140. // find an nId based on its network address
  141. std::map<CNetAddr, int> mapAddr;
  142. // randomly-ordered vector of all nIds
  143. std::vector<int> vRandom;
  144. // number of "tried" entries
  145. int nTried;
  146. // list of "tried" buckets
  147. std::vector<std::vector<int> > vvTried;
  148. // number of (unique) "new" entries
  149. int nNew;
  150. // list of "new" buckets
  151. std::vector<std::set<int> > vvNew;
  152. protected:
  153. // Find an entry.
  154. CAddrInfo* Find(const CNetAddr& addr, int *pnId = NULL);
  155. // find an entry, creating it if necessary.
  156. // nTime and nServices of found node is updated, if necessary.
  157. CAddrInfo* Create(const CAddress &addr, const CNetAddr &addrSource, int *pnId = NULL);
  158. // Swap two elements in vRandom.
  159. void SwapRandom(unsigned int nRandomPos1, unsigned int nRandomPos2);
  160. // Return position in given bucket to replace.
  161. int SelectTried(int nKBucket);
  162. // Remove an element from a "new" bucket.
  163. // This is the only place where actual deletes occur.
  164. // They are never deleted while in the "tried" table, only possibly evicted back to the "new" table.
  165. int ShrinkNew(int nUBucket);
  166. // Move an entry from the "new" table(s) to the "tried" table
  167. // @pre vvUnkown[nOrigin].count(nId) != 0
  168. void MakeTried(CAddrInfo& info, int nId, int nOrigin);
  169. // Mark an entry "good", possibly moving it from "new" to "tried".
  170. void Good_(const CService &addr, int64_t nTime);
  171. // Add an entry to the "new" table.
  172. bool Add_(const CAddress &addr, const CNetAddr& source, int64_t nTimePenalty);
  173. // Mark an entry as attempted to connect.
  174. void Attempt_(const CService &addr, int64_t nTime);
  175. // Select an address to connect to.
  176. // nUnkBias determines how much to favor new addresses over tried ones (min=0, max=100)
  177. CAddress Select_(int nUnkBias);
  178. #ifdef DEBUG_ADDRMAN
  179. // Perform consistency check. Returns an error code or zero.
  180. int Check_();
  181. #endif
  182. // Select several addresses at once.
  183. void GetAddr_(std::vector<CAddress> &vAddr);
  184. // Mark an entry as currently-connected-to.
  185. void Connected_(const CService &addr, int64_t nTime);
  186. public:
  187. // serialized format:
  188. // * version byte (currently 0)
  189. // * nKey
  190. // * nNew
  191. // * nTried
  192. // * number of "new" buckets
  193. // * all nNew addrinfos in vvNew
  194. // * all nTried addrinfos in vvTried
  195. // * for each bucket:
  196. // * number of elements
  197. // * for each element: index
  198. //
  199. // Notice that vvTried, mapAddr and vVector are never encoded explicitly;
  200. // they are instead reconstructed from the other information.
  201. //
  202. // vvNew is serialized, but only used if ADDRMAN_UNKOWN_BUCKET_COUNT didn't change,
  203. // otherwise it is reconstructed as well.
  204. //
  205. // This format is more complex, but significantly smaller (at most 1.5 MiB), and supports
  206. // changes to the ADDRMAN_ parameters without breaking the on-disk structure.
  207. //
  208. // We don't use ADD_SERIALIZE_METHODS since the serialization and deserialization code has
  209. // very little in common.
  210. template<typename Stream>
  211. void Serialize(Stream &s, int nType, int nVersionDummy) const
  212. {
  213. LOCK(cs);
  214. unsigned char nVersion = 0;
  215. s << nVersion;
  216. s << nKey;
  217. s << nNew;
  218. s << nTried;
  219. int nUBuckets = ADDRMAN_NEW_BUCKET_COUNT;
  220. s << nUBuckets;
  221. std::map<int, int> mapUnkIds;
  222. int nIds = 0;
  223. for (std::map<int, CAddrInfo>::const_iterator it = mapInfo.begin(); it != mapInfo.end(); it++) {
  224. if (nIds == nNew) break; // this means nNew was wrong, oh ow
  225. mapUnkIds[(*it).first] = nIds;
  226. const CAddrInfo &info = (*it).second;
  227. if (info.nRefCount) {
  228. s << info;
  229. nIds++;
  230. }
  231. }
  232. nIds = 0;
  233. for (std::map<int, CAddrInfo>::const_iterator it = mapInfo.begin(); it != mapInfo.end(); it++) {
  234. if (nIds == nTried) break; // this means nTried was wrong, oh ow
  235. const CAddrInfo &info = (*it).second;
  236. if (info.fInTried) {
  237. s << info;
  238. nIds++;
  239. }
  240. }
  241. for (std::vector<std::set<int> >::const_iterator it = vvNew.begin(); it != vvNew.end(); it++) {
  242. const std::set<int> &vNew = (*it);
  243. int nSize = vNew.size();
  244. s << nSize;
  245. for (std::set<int>::const_iterator it2 = vNew.begin(); it2 != vNew.end(); it2++) {
  246. int nIndex = mapUnkIds[*it2];
  247. s << nIndex;
  248. }
  249. }
  250. }
  251. template<typename Stream>
  252. void Unserialize(Stream& s, int nType, int nVersionDummy)
  253. {
  254. LOCK(cs);
  255. unsigned char nVersion;
  256. s >> nVersion;
  257. s >> nKey;
  258. s >> nNew;
  259. s >> nTried;
  260. int nUBuckets = 0;
  261. s >> nUBuckets;
  262. nIdCount = 0;
  263. mapInfo.clear();
  264. mapAddr.clear();
  265. vRandom.clear();
  266. vvTried = std::vector<std::vector<int> >(ADDRMAN_TRIED_BUCKET_COUNT, std::vector<int>(0));
  267. vvNew = std::vector<std::set<int> >(ADDRMAN_NEW_BUCKET_COUNT, std::set<int>());
  268. for (int n = 0; n < nNew; n++) {
  269. CAddrInfo &info = mapInfo[n];
  270. s >> info;
  271. mapAddr[info] = n;
  272. info.nRandomPos = vRandom.size();
  273. vRandom.push_back(n);
  274. if (nUBuckets != ADDRMAN_NEW_BUCKET_COUNT) {
  275. vvNew[info.GetNewBucket(nKey)].insert(n);
  276. info.nRefCount++;
  277. }
  278. }
  279. nIdCount = nNew;
  280. int nLost = 0;
  281. for (int n = 0; n < nTried; n++) {
  282. CAddrInfo info;
  283. s >> info;
  284. std::vector<int> &vTried = vvTried[info.GetTriedBucket(nKey)];
  285. if (vTried.size() < ADDRMAN_TRIED_BUCKET_SIZE) {
  286. info.nRandomPos = vRandom.size();
  287. info.fInTried = true;
  288. vRandom.push_back(nIdCount);
  289. mapInfo[nIdCount] = info;
  290. mapAddr[info] = nIdCount;
  291. vTried.push_back(nIdCount);
  292. nIdCount++;
  293. } else {
  294. nLost++;
  295. }
  296. }
  297. nTried -= nLost;
  298. for (int b = 0; b < nUBuckets; b++) {
  299. std::set<int> &vNew = vvNew[b];
  300. int nSize = 0;
  301. s >> nSize;
  302. for (int n = 0; n < nSize; n++) {
  303. int nIndex = 0;
  304. s >> nIndex;
  305. CAddrInfo &info = mapInfo[nIndex];
  306. if (nUBuckets == ADDRMAN_NEW_BUCKET_COUNT && info.nRefCount < ADDRMAN_NEW_BUCKETS_PER_ADDRESS) {
  307. info.nRefCount++;
  308. vNew.insert(nIndex);
  309. }
  310. }
  311. }
  312. }
  313. unsigned int GetSerializeSize(int nType, int nVersion) const
  314. {
  315. return (CSizeComputer(nType, nVersion) << *this).size();
  316. }
  317. CAddrMan() : vRandom(0), vvTried(ADDRMAN_TRIED_BUCKET_COUNT, std::vector<int>(0)), vvNew(ADDRMAN_NEW_BUCKET_COUNT, std::set<int>())
  318. {
  319. nKey.resize(32);
  320. GetRandBytes(&nKey[0], 32);
  321. nIdCount = 0;
  322. nTried = 0;
  323. nNew = 0;
  324. }
  325. // Return the number of (unique) addresses in all tables.
  326. int size()
  327. {
  328. return vRandom.size();
  329. }
  330. // Consistency check
  331. void Check()
  332. {
  333. #ifdef DEBUG_ADDRMAN
  334. {
  335. LOCK(cs);
  336. int err;
  337. if ((err=Check_()))
  338. LogPrintf("ADDRMAN CONSISTENCY CHECK FAILED!!! err=%i\n", err);
  339. }
  340. #endif
  341. }
  342. // Add a single address.
  343. bool Add(const CAddress &addr, const CNetAddr& source, int64_t nTimePenalty = 0)
  344. {
  345. bool fRet = false;
  346. {
  347. LOCK(cs);
  348. Check();
  349. fRet |= Add_(addr, source, nTimePenalty);
  350. Check();
  351. }
  352. if (fRet)
  353. LogPrint("addrman", "Added %s from %s: %i tried, %i new\n", addr.ToStringIPPort().c_str(), source.ToString(), nTried, nNew);
  354. return fRet;
  355. }
  356. // Add multiple addresses.
  357. bool Add(const std::vector<CAddress> &vAddr, const CNetAddr& source, int64_t nTimePenalty = 0)
  358. {
  359. int nAdd = 0;
  360. {
  361. LOCK(cs);
  362. Check();
  363. for (std::vector<CAddress>::const_iterator it = vAddr.begin(); it != vAddr.end(); it++)
  364. nAdd += Add_(*it, source, nTimePenalty) ? 1 : 0;
  365. Check();
  366. }
  367. if (nAdd)
  368. LogPrint("addrman", "Added %i addresses from %s: %i tried, %i new\n", nAdd, source.ToString(), nTried, nNew);
  369. return nAdd > 0;
  370. }
  371. // Mark an entry as accessible.
  372. void Good(const CService &addr, int64_t nTime = GetAdjustedTime())
  373. {
  374. {
  375. LOCK(cs);
  376. Check();
  377. Good_(addr, nTime);
  378. Check();
  379. }
  380. }
  381. // Mark an entry as connection attempted to.
  382. void Attempt(const CService &addr, int64_t nTime = GetAdjustedTime())
  383. {
  384. {
  385. LOCK(cs);
  386. Check();
  387. Attempt_(addr, nTime);
  388. Check();
  389. }
  390. }
  391. // Choose an address to connect to.
  392. // nUnkBias determines how much "new" entries are favored over "tried" ones (0-100).
  393. CAddress Select(int nUnkBias = 50)
  394. {
  395. CAddress addrRet;
  396. {
  397. LOCK(cs);
  398. Check();
  399. addrRet = Select_(nUnkBias);
  400. Check();
  401. }
  402. return addrRet;
  403. }
  404. // Return a bunch of addresses, selected at random.
  405. std::vector<CAddress> GetAddr()
  406. {
  407. Check();
  408. std::vector<CAddress> vAddr;
  409. {
  410. LOCK(cs);
  411. GetAddr_(vAddr);
  412. }
  413. Check();
  414. return vAddr;
  415. }
  416. // Mark an entry as currently-connected-to.
  417. void Connected(const CService &addr, int64_t nTime = GetAdjustedTime())
  418. {
  419. {
  420. LOCK(cs);
  421. Check();
  422. Connected_(addr, nTime);
  423. Check();
  424. }
  425. }
  426. };
  427. #endif // _BITCOIN_ADDRMAN