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
17 /** Extended statistics about a CAddress */
18 class CAddrInfo : public CAddress
21 // where knowledge about this address first came from
24 // last successful connection by us
27 // last try whatsoever by us:
28 // int64_t CAddress::nLastTry
30 // connection attempts since last successful attempt
33 // reference count in new sets (memory only)
36 // in tried set? (memory only)
39 // position in vRandom
42 friend class CAddrMan;
47 CAddress* pthis = (CAddress*)(this);
50 READWRITE(nLastSuccess);
64 CAddrInfo(const CAddress &addrIn, const CNetAddr &addrSource) : CAddress(addrIn), source(addrSource)
69 CAddrInfo() : CAddress(), source()
74 // Calculate in which "tried" bucket this entry belongs
75 int GetTriedBucket(const std::vector<unsigned char> &nKey) const;
77 // Calculate in which "new" bucket this entry belongs, given a certain source
78 int GetNewBucket(const std::vector<unsigned char> &nKey, const CNetAddr& src) const;
80 // Calculate in which "new" bucket this entry belongs, using its default source
81 int GetNewBucket(const std::vector<unsigned char> &nKey) const
83 return GetNewBucket(nKey, source);
86 // Determine whether the statistics about this entry are bad enough so that it can just be deleted
87 bool IsTerrible(int64_t nNow = GetAdjustedTime()) const;
89 // Calculate the relative chance this entry should be given when selecting nodes to connect to
90 double GetChance(int64_t nNow = GetAdjustedTime()) const;
94 // Stochastic address manager
97 // * Only keep a limited number of addresses around, so that addr.dat and memory requirements do not grow without bound.
98 // * Keep the address tables in-memory, and asynchronously dump the entire to able in addr.dat.
99 // * Make sure no (localized) attacker can fill the entire table with his nodes/addresses.
102 // * Addresses are organized into buckets.
103 // * Address that have not yet been tried go into 256 "new" buckets.
104 // * Based on the address range (/16 for IPv4) of source of the information, 32 buckets are selected at random
105 // * The actual bucket is chosen from one of these, based on the range the address itself is located.
106 // * One single address can occur in up to 4 different buckets, to increase selection chances for addresses that
107 // are seen frequently. The chance for increasing this multiplicity decreases exponentially.
108 // * When adding a new address to a full bucket, a randomly chosen entry (with a bias favoring less recently seen
109 // ones) is removed from it first.
110 // * Addresses of nodes that are known to be accessible go into 64 "tried" buckets.
111 // * Each address range selects at random 4 of these buckets.
112 // * The actual bucket is chosen from one of these, based on the full address.
113 // * When adding a new good address to a full bucket, a randomly chosen entry (with a bias favoring less recently
114 // tried ones) is evicted from it, back to the "new" buckets.
115 // * Bucket selection is based on cryptographic hashing, using a randomly-generated 256-bit key, which should not
116 // be observable by adversaries.
117 // * Several indexes are kept for high performance. Defining DEBUG_ADDRMAN will introduce frequent (and expensive)
118 // consistency checks for the entire data structure.
120 // total number of buckets for tried addresses
121 #define ADDRMAN_TRIED_BUCKET_COUNT 64
123 // maximum allowed number of entries in buckets for tried addresses
124 #define ADDRMAN_TRIED_BUCKET_SIZE 64
126 // total number of buckets for new addresses
127 #define ADDRMAN_NEW_BUCKET_COUNT 256
129 // maximum allowed number of entries in buckets for new addresses
130 #define ADDRMAN_NEW_BUCKET_SIZE 64
132 // over how many buckets entries with tried addresses from a single group (/16 for IPv4) are spread
133 #define ADDRMAN_TRIED_BUCKETS_PER_GROUP 4
135 // over how many buckets entries with new addresses originating from a single group are spread
136 #define ADDRMAN_NEW_BUCKETS_PER_SOURCE_GROUP 32
138 // in how many buckets for entries with new addresses a single address may occur
139 #define ADDRMAN_NEW_BUCKETS_PER_ADDRESS 4
141 // how many entries in a bucket with tried addresses are inspected, when selecting one to replace
142 #define ADDRMAN_TRIED_ENTRIES_INSPECT_ON_EVICT 4
144 // how old addresses can maximally be
145 #define ADDRMAN_HORIZON_DAYS 30
147 // after how many failed attempts we give up on a new node
148 #define ADDRMAN_RETRIES 3
150 // how many successive failures are allowed ...
151 #define ADDRMAN_MAX_FAILURES 10
153 // ... in at least this many days
154 #define ADDRMAN_MIN_FAIL_DAYS 7
156 // the maximum percentage of nodes to return in a getaddr call
157 #define ADDRMAN_GETADDR_MAX_PCT 23
159 // the maximum number of nodes to return in a getaddr call
160 #define ADDRMAN_GETADDR_MAX 2500
162 /** Stochastical (IP) address manager */
166 // critical section to protect the inner data structures
167 mutable CCriticalSection cs;
169 // secret key to randomize bucket select with
170 std::vector<unsigned char> nKey;
175 // table with information about all nIds
176 std::map<int, CAddrInfo> mapInfo;
178 // find an nId based on its network address
179 std::map<CNetAddr, int> mapAddr;
181 // randomly-ordered vector of all nIds
182 std::vector<int> vRandom;
184 // number of "tried" entries
187 // list of "tried" buckets
188 std::vector<std::vector<int> > vvTried;
190 // number of (unique) "new" entries
193 // list of "new" buckets
194 std::vector<std::set<int> > vvNew;
199 CAddrInfo* Find(const CNetAddr& addr, int *pnId = NULL);
201 // find an entry, creating it if necessary.
202 // nTime and nServices of found node is updated, if necessary.
203 CAddrInfo* Create(const CAddress &addr, const CNetAddr &addrSource, int *pnId = NULL);
205 // Swap two elements in vRandom.
206 void SwapRandom(unsigned int nRandomPos1, unsigned int nRandomPos2);
208 // Return position in given bucket to replace.
209 int SelectTried(int nKBucket);
211 // Remove an element from a "new" bucket.
212 // This is the only place where actual deletes occur.
213 // They are never deleted while in the "tried" table, only possibly evicted back to the "new" table.
214 int ShrinkNew(int nUBucket);
216 // Move an entry from the "new" table(s) to the "tried" table
217 // @pre vvUnkown[nOrigin].count(nId) != 0
218 void MakeTried(CAddrInfo& info, int nId, int nOrigin);
220 // Mark an entry "good", possibly moving it from "new" to "tried".
221 void Good_(const CService &addr, int64_t nTime);
223 // Add an entry to the "new" table.
224 bool Add_(const CAddress &addr, const CNetAddr& source, int64_t nTimePenalty);
226 // Mark an entry as attempted to connect.
227 void Attempt_(const CService &addr, int64_t nTime);
229 // Select an address to connect to.
230 // nUnkBias determines how much to favor new addresses over tried ones (min=0, max=100)
231 CAddress Select_(int nUnkBias);
234 // Perform consistency check. Returns an error code or zero.
238 // Select several addresses at once.
239 void GetAddr_(std::vector<CAddress> &vAddr);
240 void GetOnlineAddr_(std::vector<CAddrInfo> &vAddr);
242 // Mark an entry as currently-connected-to.
243 void Connected_(const CService &addr, int64_t nTime);
247 typedef std::map<int, int> MapUnkIds; // For MSVC macro
260 *am = const_cast<CAddrMan*>(this);
265 nUBuckets = ADDRMAN_NEW_BUCKET_COUNT;
267 READWRITE(nUBuckets);
271 for (std::map<int, CAddrInfo>::iterator it = am->mapInfo.begin(); it != am->mapInfo.end(); it++)
274 break; // this means nNew was wrong, oh ow
275 mapUnkIds[(*it).first] = nIds;
278 &info = (*it).second;
287 for (std::map<int, CAddrInfo>::iterator it = am->mapInfo.begin(); it != am->mapInfo.end(); it++)
290 break; /* this means nTried was wrong, oh ow */
293 &info = (*it).second;
302 std::vector<std::set<int> >::iterator it = am->vvNew.begin();
303 it != am->vvNew.end();
311 nSize = int( vNew.size() );
314 for (std::set<int>::iterator it2 = vNew.begin(); it2 != vNew.end(); it2++)
317 nIndex = mapUnkIds[*it2];
327 READWRITE(nUBuckets);
333 std::vector<std::vector<int> >(
334 ADDRMAN_TRIED_BUCKET_COUNT,
338 std::vector<std::set<int> >(
339 ADDRMAN_NEW_BUCKET_COUNT,
342 for (int n = 0; n < am->nNew; n++)
345 &info = am->mapInfo[n];
348 am->mapAddr[info] = n;
349 info.nRandomPos = int( vRandom.size() );
350 am->vRandom.push_back(n);
351 if (nUBuckets != ADDRMAN_NEW_BUCKET_COUNT)
353 am->vvNew[info.GetNewBucket(am->nKey)].insert(n);
357 am->nIdCount = am->nNew;
362 for (int n = 0; n < am->nTried; n++)
370 &vTried = am->vvTried[info.GetTriedBucket(am->nKey)];
372 if (vTried.size() < ADDRMAN_TRIED_BUCKET_SIZE)
374 info.nRandomPos = int( vRandom.size() );
375 info.fInTried = true;
376 am->vRandom.push_back(am->nIdCount);
377 am->mapInfo[am->nIdCount] = info;
378 am->mapAddr[info] = am->nIdCount;
379 vTried.push_back(am->nIdCount);
388 for (int b = 0; b < nUBuckets; b++)
391 &vNew = am->vvNew[b];
397 for (int n = 0; n < nSize; n++)
405 &info = am->mapInfo[nIndex];
408 (nUBuckets == ADDRMAN_NEW_BUCKET_COUNT) &&
409 (info.nRefCount < ADDRMAN_NEW_BUCKETS_PER_ADDRESS)
423 // Return the number of (unique) addresses in all tables.
426 return (int) vRandom.size();
437 printf("ADDRMAN CONSISTENCY CHECK FAILED!!! err=%i\n", err);
442 // Add a single address.
443 bool Add(const CAddress &addr, const CNetAddr& source, int64_t nTimePenalty = 0)
449 fRet |= Add_(addr, source, nTimePenalty);
453 printf("Added %s from %s: %i tried, %i new\n", addr.ToStringIPPort().c_str(), source.ToString().c_str(), nTried, nNew);
457 // Add multiple addresses.
458 bool Add(const std::vector<CAddress> &vAddr, const CNetAddr& source, int64_t nTimePenalty = 0)
464 for (std::vector<CAddress>::const_iterator it = vAddr.begin(); it != vAddr.end(); it++)
465 nAdd += Add_(*it, source, nTimePenalty) ? 1 : 0;
469 printf("Added %i addresses from %s: %i tried, %i new\n", nAdd, source.ToString().c_str(), nTried, nNew);
473 // Mark an entry as accessible.
474 void Good(const CService &addr, int64_t nTime = GetAdjustedTime())
484 // Mark an entry as connection attempted to.
485 void Attempt(const CService &addr, int64_t nTime = GetAdjustedTime())
490 Attempt_(addr, nTime);
495 // Choose an address to connect to.
496 // nUnkBias determines how much "new" entries are favored over "tried" ones (0-100).
497 CAddress Select(int nUnkBias = 50)
503 addrRet = Select_(nUnkBias);
509 // Return a bunch of addresses, selected at random.
510 std::vector<CAddress> GetAddr()
513 std::vector<CAddress> vAddr;
522 std::vector<CAddrInfo> GetOnlineAddr()
525 std::vector<CAddrInfo> vAddr;
528 GetOnlineAddr_(vAddr);
534 // Mark an entry as currently-connected-to.
535 void Connected(const CService &addr, int64_t nTime = GetAdjustedTime())
540 Connected_(addr, nTime);