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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504
  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 1
  6. #include "netbase.h"
  7. #include "protocol.h"
  8. #include "sync.h"
  9. #include "util.h"
  10. #include <map>
  11. #include <set>
  12. #include <stdint.h>
  13. #include <vector>
  14. #include <openssl/rand.h>
  15. /** Extended statistics about a CAddress */
  16. class CAddrInfo : public CAddress
  17. {
  18. private:
  19. // where knowledge about this address first came from
  20. CNetAddr source;
  21. // last successful connection by us
  22. int64_t nLastSuccess;
  23. // last try whatsoever by us:
  24. // int64_t CAddress::nLastTry
  25. // connection attempts since last successful attempt
  26. int nAttempts;
  27. // reference count in new sets (memory only)
  28. int nRefCount;
  29. // in tried set? (memory only)
  30. bool fInTried;
  31. // position in vRandom
  32. int nRandomPos;
  33. friend class CAddrMan;
  34. public:
  35. IMPLEMENT_SERIALIZE(
  36. CAddress* pthis = (CAddress*)(this);
  37. READWRITE(*pthis);
  38. READWRITE(source);
  39. READWRITE(nLastSuccess);
  40. READWRITE(nAttempts);
  41. )
  42. void Init()
  43. {
  44. nLastSuccess = 0;
  45. nLastTry = 0;
  46. nAttempts = 0;
  47. nRefCount = 0;
  48. fInTried = false;
  49. nRandomPos = -1;
  50. }
  51. CAddrInfo(const CAddress &addrIn, const CNetAddr &addrSource) : CAddress(addrIn), source(addrSource)
  52. {
  53. Init();
  54. }
  55. CAddrInfo() : CAddress(), source()
  56. {
  57. Init();
  58. }
  59. // Calculate in which "tried" bucket this entry belongs
  60. int GetTriedBucket(const std::vector<unsigned char> &nKey) const;
  61. // Calculate in which "new" bucket this entry belongs, given a certain source
  62. int GetNewBucket(const std::vector<unsigned char> &nKey, const CNetAddr& src) const;
  63. // Calculate in which "new" bucket this entry belongs, using its default source
  64. int GetNewBucket(const std::vector<unsigned char> &nKey) const
  65. {
  66. return GetNewBucket(nKey, source);
  67. }
  68. // Determine whether the statistics about this entry are bad enough so that it can just be deleted
  69. bool IsTerrible(int64_t nNow = GetAdjustedTime()) const;
  70. // Calculate the relative chance this entry should be given when selecting nodes to connect to
  71. double GetChance(int64_t nNow = GetAdjustedTime()) const;
  72. };
  73. // Stochastic address manager
  74. //
  75. // Design goals:
  76. // * Only keep a limited number of addresses around, so that addr.dat and memory requirements do not grow without bound.
  77. // * Keep the address tables in-memory, and asynchronously dump the entire to able in addr.dat.
  78. // * Make sure no (localized) attacker can fill the entire table with his nodes/addresses.
  79. //
  80. // To that end:
  81. // * Addresses are organized into buckets.
  82. // * Address that have not yet been tried go into 256 "new" buckets.
  83. // * Based on the address range (/16 for IPv4) of source of the information, 32 buckets are selected at random
  84. // * The actual bucket is chosen from one of these, based on the range the address itself is located.
  85. // * One single address can occur in up to 4 different buckets, to increase selection chances for addresses that
  86. // are seen frequently. The chance for increasing this multiplicity decreases exponentially.
  87. // * When adding a new address to a full bucket, a randomly chosen entry (with a bias favoring less recently seen
  88. // ones) is removed from it first.
  89. // * Addresses of nodes that are known to be accessible go into 64 "tried" buckets.
  90. // * Each address range selects at random 4 of these buckets.
  91. // * The actual bucket is chosen from one of these, based on the full address.
  92. // * When adding a new good address to a full bucket, a randomly chosen entry (with a bias favoring less recently
  93. // tried ones) is evicted from it, back to the "new" buckets.
  94. // * Bucket selection is based on cryptographic hashing, using a randomly-generated 256-bit key, which should not
  95. // be observable by adversaries.
  96. // * Several indexes are kept for high performance. Defining DEBUG_ADDRMAN will introduce frequent (and expensive)
  97. // consistency checks for the entire data structure.
  98. // total number of buckets for tried addresses
  99. #define ADDRMAN_TRIED_BUCKET_COUNT 64
  100. // maximum allowed number of entries in buckets for tried addresses
  101. #define ADDRMAN_TRIED_BUCKET_SIZE 64
  102. // total number of buckets for new addresses
  103. #define ADDRMAN_NEW_BUCKET_COUNT 256
  104. // maximum allowed number of entries in buckets for new addresses
  105. #define ADDRMAN_NEW_BUCKET_SIZE 64
  106. // over how many buckets entries with tried addresses from a single group (/16 for IPv4) are spread
  107. #define ADDRMAN_TRIED_BUCKETS_PER_GROUP 4
  108. // over how many buckets entries with new addresses originating from a single group are spread
  109. #define ADDRMAN_NEW_BUCKETS_PER_SOURCE_GROUP 32
  110. // in how many buckets for entries with new addresses a single address may occur
  111. #define ADDRMAN_NEW_BUCKETS_PER_ADDRESS 4
  112. // how many entries in a bucket with tried addresses are inspected, when selecting one to replace
  113. #define ADDRMAN_TRIED_ENTRIES_INSPECT_ON_EVICT 4
  114. // how old addresses can maximally be
  115. #define ADDRMAN_HORIZON_DAYS 30
  116. // after how many failed attempts we give up on a new node
  117. #define ADDRMAN_RETRIES 3
  118. // how many successive failures are allowed ...
  119. #define ADDRMAN_MAX_FAILURES 10
  120. // ... in at least this many days
  121. #define ADDRMAN_MIN_FAIL_DAYS 7
  122. // the maximum percentage of nodes to return in a getaddr call
  123. #define ADDRMAN_GETADDR_MAX_PCT 23
  124. // the maximum number of nodes to return in a getaddr call
  125. #define ADDRMAN_GETADDR_MAX 2500
  126. /** Stochastical (IP) address manager */
  127. class CAddrMan
  128. {
  129. private:
  130. // critical section to protect the inner data structures
  131. mutable CCriticalSection cs;
  132. // secret key to randomize bucket select with
  133. std::vector<unsigned char> nKey;
  134. // last used nId
  135. int nIdCount;
  136. // table with information about all nIds
  137. std::map<int, CAddrInfo> mapInfo;
  138. // find an nId based on its network address
  139. std::map<CNetAddr, int> mapAddr;
  140. // randomly-ordered vector of all nIds
  141. std::vector<int> vRandom;
  142. // number of "tried" entries
  143. int nTried;
  144. // list of "tried" buckets
  145. std::vector<std::vector<int> > vvTried;
  146. // number of (unique) "new" entries
  147. int nNew;
  148. // list of "new" buckets
  149. std::vector<std::set<int> > vvNew;
  150. protected:
  151. // Find an entry.
  152. CAddrInfo* Find(const CNetAddr& addr, int *pnId = NULL);
  153. // find an entry, creating it if necessary.
  154. // nTime and nServices of found node is updated, if necessary.
  155. CAddrInfo* Create(const CAddress &addr, const CNetAddr &addrSource, int *pnId = NULL);
  156. // Swap two elements in vRandom.
  157. void SwapRandom(unsigned int nRandomPos1, unsigned int nRandomPos2);
  158. // Return position in given bucket to replace.
  159. int SelectTried(int nKBucket);
  160. // Remove an element from a "new" bucket.
  161. // This is the only place where actual deletes occur.
  162. // They are never deleted while in the "tried" table, only possibly evicted back to the "new" table.
  163. int ShrinkNew(int nUBucket);
  164. // Move an entry from the "new" table(s) to the "tried" table
  165. // @pre vvUnkown[nOrigin].count(nId) != 0
  166. void MakeTried(CAddrInfo& info, int nId, int nOrigin);
  167. // Mark an entry "good", possibly moving it from "new" to "tried".
  168. void Good_(const CService &addr, int64_t nTime);
  169. // Add an entry to the "new" table.
  170. bool Add_(const CAddress &addr, const CNetAddr& source, int64_t nTimePenalty);
  171. // Mark an entry as attempted to connect.
  172. void Attempt_(const CService &addr, int64_t nTime);
  173. // Select an address to connect to.
  174. // nUnkBias determines how much to favor new addresses over tried ones (min=0, max=100)
  175. CAddress Select_(int nUnkBias);
  176. #ifdef DEBUG_ADDRMAN
  177. // Perform consistency check. Returns an error code or zero.
  178. int Check_();
  179. #endif
  180. // Select several addresses at once.
  181. void GetAddr_(std::vector<CAddress> &vAddr);
  182. // Mark an entry as currently-connected-to.
  183. void Connected_(const CService &addr, int64_t nTime);
  184. public:
  185. IMPLEMENT_SERIALIZE
  186. (({
  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. LOCK(cs);
  209. unsigned char nVersion = 0;
  210. READWRITE(nVersion);
  211. READWRITE(nKey);
  212. READWRITE(nNew);
  213. READWRITE(nTried);
  214. CAddrMan *am = const_cast<CAddrMan*>(this);
  215. if (fWrite)
  216. {
  217. int nUBuckets = ADDRMAN_NEW_BUCKET_COUNT;
  218. READWRITE(nUBuckets);
  219. std::map<int, int> mapUnkIds;
  220. int nIds = 0;
  221. for (std::map<int, CAddrInfo>::iterator it = am->mapInfo.begin(); it != am->mapInfo.end(); it++)
  222. {
  223. if (nIds == nNew) break; // this means nNew was wrong, oh ow
  224. mapUnkIds[(*it).first] = nIds;
  225. CAddrInfo &info = (*it).second;
  226. if (info.nRefCount)
  227. {
  228. READWRITE(info);
  229. nIds++;
  230. }
  231. }
  232. nIds = 0;
  233. for (std::map<int, CAddrInfo>::iterator it = am->mapInfo.begin(); it != am->mapInfo.end(); it++)
  234. {
  235. if (nIds == nTried) break; // this means nTried was wrong, oh ow
  236. CAddrInfo &info = (*it).second;
  237. if (info.fInTried)
  238. {
  239. READWRITE(info);
  240. nIds++;
  241. }
  242. }
  243. for (std::vector<std::set<int> >::iterator it = am->vvNew.begin(); it != am->vvNew.end(); it++)
  244. {
  245. const std::set<int> &vNew = (*it);
  246. int nSize = vNew.size();
  247. READWRITE(nSize);
  248. for (std::set<int>::iterator it2 = vNew.begin(); it2 != vNew.end(); it2++)
  249. {
  250. int nIndex = mapUnkIds[*it2];
  251. READWRITE(nIndex);
  252. }
  253. }
  254. } else {
  255. int nUBuckets = 0;
  256. READWRITE(nUBuckets);
  257. am->nIdCount = 0;
  258. am->mapInfo.clear();
  259. am->mapAddr.clear();
  260. am->vRandom.clear();
  261. am->vvTried = std::vector<std::vector<int> >(ADDRMAN_TRIED_BUCKET_COUNT, std::vector<int>(0));
  262. am->vvNew = std::vector<std::set<int> >(ADDRMAN_NEW_BUCKET_COUNT, std::set<int>());
  263. for (int n = 0; n < am->nNew; n++)
  264. {
  265. CAddrInfo &info = am->mapInfo[n];
  266. READWRITE(info);
  267. am->mapAddr[info] = n;
  268. info.nRandomPos = vRandom.size();
  269. am->vRandom.push_back(n);
  270. if (nUBuckets != ADDRMAN_NEW_BUCKET_COUNT)
  271. {
  272. am->vvNew[info.GetNewBucket(am->nKey)].insert(n);
  273. info.nRefCount++;
  274. }
  275. }
  276. am->nIdCount = am->nNew;
  277. int nLost = 0;
  278. for (int n = 0; n < am->nTried; n++)
  279. {
  280. CAddrInfo info;
  281. READWRITE(info);
  282. std::vector<int> &vTried = am->vvTried[info.GetTriedBucket(am->nKey)];
  283. if (vTried.size() < ADDRMAN_TRIED_BUCKET_SIZE)
  284. {
  285. info.nRandomPos = vRandom.size();
  286. info.fInTried = true;
  287. am->vRandom.push_back(am->nIdCount);
  288. am->mapInfo[am->nIdCount] = info;
  289. am->mapAddr[info] = am->nIdCount;
  290. vTried.push_back(am->nIdCount);
  291. am->nIdCount++;
  292. } else {
  293. nLost++;
  294. }
  295. }
  296. am->nTried -= nLost;
  297. for (int b = 0; b < nUBuckets; b++)
  298. {
  299. std::set<int> &vNew = am->vvNew[b];
  300. int nSize = 0;
  301. READWRITE(nSize);
  302. for (int n = 0; n < nSize; n++)
  303. {
  304. int nIndex = 0;
  305. READWRITE(nIndex);
  306. CAddrInfo &info = am->mapInfo[nIndex];
  307. if (nUBuckets == ADDRMAN_NEW_BUCKET_COUNT && info.nRefCount < ADDRMAN_NEW_BUCKETS_PER_ADDRESS)
  308. {
  309. info.nRefCount++;
  310. vNew.insert(nIndex);
  311. }
  312. }
  313. }
  314. }
  315. }
  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. RAND_bytes(&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().c_str(), 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().c_str(), 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