1 // Copyright (c) 2012 Pieter Wuille
2 // Distributed under the MIT/X11 software license, see the accompanying
3 // file license.txt or http://www.opensource.org/licenses/mit-license.php.
4 #ifndef _BITCOIN_ADDRMAN
5 #define _BITCOIN_ADDRMAN 1
15 #include <openssl/rand.h>
18 /** Extended statistics about a CAddress */
19 class CAddrInfo : public CAddress
22 // where knowledge about this address first came from
25 // last succesfull connection by us
28 // last try whatsoever by us:
29 // int64 CAddress::nLastTry
31 // connection attempts since last succesful attempt
34 // reference count in new sets (memory only)
37 // in tried set? (memory only)
40 // position in vRandom
43 friend class CAddrMan;
48 CAddress* pthis = (CAddress*)(this);
51 READWRITE(nLastSuccess);
65 CAddrInfo(const CAddress &addrIn, const CNetAddr &addrSource) : CAddress(addrIn), source(addrSource)
70 CAddrInfo() : CAddress(), source()
75 // Calculate in which "tried" bucket this entry belongs
76 int GetTriedBucket(const std::vector<unsigned char> &nKey) const;
78 // Calculate in which "new" bucket this entry belongs, given a certain source
79 int GetNewBucket(const std::vector<unsigned char> &nKey, const CNetAddr& src) const;
81 // Calculate in which "new" bucket this entry belongs, using its default source
82 int GetNewBucket(const std::vector<unsigned char> &nKey) const
84 return GetNewBucket(nKey, source);
87 // Determine whether the statistics about this entry are bad enough so that it can just be deleted
88 bool IsTerrible(int64 nNow = GetAdjustedTime()) const;
90 // Calculate the relative chance this entry should be given when selecting nodes to connect to
91 double GetChance(int64 nNow = GetAdjustedTime()) const;
95 // Stochastic address manager
98 // * Only keep a limited number of addresses around, so that addr.dat and memory requirements do not grow without bound.
99 // * Keep the address tables in-memory, and asynchronously dump the entire to able in addr.dat.
100 // * Make sure no (localized) attacker can fill the entire table with his nodes/addresses.
103 // * Addresses are organized into buckets.
104 // * Address that have not yet been tried go into 256 "new" buckets.
105 // * Based on the address range (/16 for IPv4) of source of the information, 32 buckets are selected at random
106 // * The actual bucket is chosen from one of these, based on the range the address itself is located.
107 // * One single address can occur in up to 4 different buckets, to increase selection chances for addresses that
108 // are seen frequently. The chance for increasing this multiplicity decreases exponentially.
109 // * When adding a new address to a full bucket, a randomly chosen entry (with a bias favoring less recently seen
110 // ones) is removed from it first.
111 // * Addresses of nodes that are known to be accessible go into 64 "tried" buckets.
112 // * Each address range selects at random 4 of these buckets.
113 // * The actual bucket is chosen from one of these, based on the full address.
114 // * When adding a new good address to a full bucket, a randomly chosen entry (with a bias favoring less recently
115 // tried ones) is evicted from it, back to the "new" buckets.
116 // * Bucket selection is based on cryptographic hashing, using a randomly-generated 256-bit key, which should not
117 // be observable by adversaries.
118 // * Several indexes are kept for high performance. Defining DEBUG_ADDRMAN will introduce frequent (and expensive)
119 // consistency checks for the entire datastructure.
121 // total number of buckets for tried addresses
122 #define ADDRMAN_TRIED_BUCKET_COUNT 64
124 // maximum allowed number of entries in buckets for tried addresses
125 #define ADDRMAN_TRIED_BUCKET_SIZE 64
127 // total number of buckets for new addresses
128 #define ADDRMAN_NEW_BUCKET_COUNT 256
130 // maximum allowed number of entries in buckets for new addresses
131 #define ADDRMAN_NEW_BUCKET_SIZE 64
133 // over how many buckets entries with tried addresses from a single group (/16 for IPv4) are spread
134 #define ADDRMAN_TRIED_BUCKETS_PER_GROUP 4
136 // over how many buckets entries with new addresses originating from a single group are spread
137 #define ADDRMAN_NEW_BUCKETS_PER_SOURCE_GROUP 32
139 // in how many buckets for entries with new addresses a single address may occur
140 #define ADDRMAN_NEW_BUCKETS_PER_ADDRESS 4
142 // how many entries in a bucket with tried addresses are inspected, when selecting one to replace
143 #define ADDRMAN_TRIED_ENTRIES_INSPECT_ON_EVICT 4
145 // how old addresses can maximally be
146 #define ADDRMAN_HORIZON_DAYS 30
148 // after how many failed attempts we give up on a new node
149 #define ADDRMAN_RETRIES 3
151 // how many successive failures are allowed ...
152 #define ADDRMAN_MAX_FAILURES 10
154 // ... in at least this many days
155 #define ADDRMAN_MIN_FAIL_DAYS 7
157 // the maximum percentage of nodes to return in a getaddr call
158 #define ADDRMAN_GETADDR_MAX_PCT 23
160 // the maximum number of nodes to return in a getaddr call
161 #define ADDRMAN_GETADDR_MAX 2500
163 /** Stochastical (IP) address manager */
167 // critical section to protect the inner data structures
168 mutable CCriticalSection cs;
170 // secret key to randomize bucket select with
171 std::vector<unsigned char> nKey;
176 // table with information about all nId's
177 std::map<int, CAddrInfo> mapInfo;
179 // find an nId based on its network address
180 std::map<CNetAddr, int> mapAddr;
182 // randomly-ordered vector of all nId's
183 std::vector<int> vRandom;
185 // number of "tried" entries
188 // list of "tried" buckets
189 std::vector<std::vector<int> > vvTried;
191 // number of (unique) "new" entries
194 // list of "new" buckets
195 std::vector<std::set<int> > vvNew;
200 CAddrInfo* Find(const CNetAddr& addr, int *pnId = NULL);
202 // find an entry, creating it if necessary.
203 // nTime and nServices of found node is updated, if necessary.
204 CAddrInfo* Create(const CAddress &addr, const CNetAddr &addrSource, int *pnId = NULL);
206 // Swap two elements in vRandom.
207 void SwapRandom(int nRandomPos1, int nRandomPos2);
209 // Return position in given bucket to replace.
210 int SelectTried(int nKBucket);
212 // Remove an element from a "new" bucket.
213 // This is the only place where actual deletes occur.
214 // They are never deleted while in the "tried" table, only possibly evicted back to the "new" table.
215 int ShrinkNew(int nUBucket);
217 // Move an entry from the "new" table(s) to the "tried" table
218 // @pre vvUnkown[nOrigin].count(nId) != 0
219 void MakeTried(CAddrInfo& info, int nId, int nOrigin);
221 // Mark an entry "good", possibly moving it from "new" to "tried".
222 void Good_(const CService &addr, int64 nTime);
224 // Add an entry to the "new" table.
225 bool Add_(const CAddress &addr, const CNetAddr& source, int64 nTimePenalty);
227 // Mark an entry as attempted to connect.
228 void Attempt_(const CService &addr, int64 nTime);
230 // Select an address to connect to.
231 // nUnkBias determines how much to favor new addresses over tried ones (min=0, max=100)
232 CAddress Select_(int nUnkBias);
235 // Perform consistency check. Returns an error code or zero.
239 // Select several addresses at once.
240 void GetAddr_(std::vector<CAddress> &vAddr);
242 // Mark an entry as currently-connected-to.
243 void Connected_(const CService &addr, int64 nTime);
249 // serialized format:
250 // * version byte (currently 0)
254 // * number of "new" buckets
255 // * all nNew addrinfo's in vvNew
256 // * all nTried addrinfo's in vvTried
257 // * for each bucket:
258 // * number of elements
259 // * for each element: index
261 // Notice that vvTried, mapAddr and vVector are never encoded explicitly;
262 // they are instead reconstructed from the other information.
264 // vvNew is serialized, but only used if ADDRMAN_UNKOWN_BUCKET_COUNT didn't change,
265 // otherwise it is reconstructed as well.
267 // This format is more complex, but significantly smaller (at most 1.5 MiB), and supports
268 // changes to the ADDRMAN_ parameters without breaking the on-disk structure.
271 unsigned char nVersion = 0;
277 CAddrMan *am = const_cast<CAddrMan*>(this);
280 int nUBuckets = ADDRMAN_NEW_BUCKET_COUNT;
281 READWRITE(nUBuckets);
282 std::map<int, int> mapUnkIds;
284 for (std::map<int, CAddrInfo>::iterator it = am->mapInfo.begin(); it != am->mapInfo.end(); it++)
286 if (nIds == nNew) break; // this means nNew was wrong, oh ow
287 mapUnkIds[(*it).first] = nIds;
288 CAddrInfo &info = (*it).second;
296 for (std::map<int, CAddrInfo>::iterator it = am->mapInfo.begin(); it != am->mapInfo.end(); it++)
298 if (nIds == nTried) break; // this means nTried was wrong, oh ow
299 CAddrInfo &info = (*it).second;
306 for (std::vector<std::set<int> >::iterator it = am->vvNew.begin(); it != am->vvNew.end(); it++)
308 const std::set<int> &vNew = (*it);
309 int nSize = vNew.size();
311 for (std::set<int>::iterator it2 = vNew.begin(); it2 != vNew.end(); it2++)
313 int nIndex = mapUnkIds[*it2];
319 READWRITE(nUBuckets);
324 am->vvTried = std::vector<std::vector<int> >(ADDRMAN_TRIED_BUCKET_COUNT, std::vector<int>(0));
325 am->vvNew = std::vector<std::set<int> >(ADDRMAN_NEW_BUCKET_COUNT, std::set<int>());
326 for (int n = 0; n < am->nNew; n++)
328 CAddrInfo &info = am->mapInfo[n];
330 am->mapAddr[info] = n;
331 info.nRandomPos = vRandom.size();
332 am->vRandom.push_back(n);
333 if (nUBuckets != ADDRMAN_NEW_BUCKET_COUNT)
335 am->vvNew[info.GetNewBucket(am->nKey)].insert(n);
339 am->nIdCount = am->nNew;
341 for (int n = 0; n < am->nTried; n++)
345 std::vector<int> &vTried = am->vvTried[info.GetTriedBucket(am->nKey)];
346 if (vTried.size() < ADDRMAN_TRIED_BUCKET_SIZE)
348 info.nRandomPos = vRandom.size();
349 info.fInTried = true;
350 am->vRandom.push_back(am->nIdCount);
351 am->mapInfo[am->nIdCount] = info;
352 am->mapAddr[info] = am->nIdCount;
353 vTried.push_back(am->nIdCount);
360 for (int b = 0; b < nUBuckets; b++)
362 std::set<int> &vNew = am->vvNew[b];
365 for (int n = 0; n < nSize; n++)
369 CAddrInfo &info = am->mapInfo[nIndex];
370 if (nUBuckets == ADDRMAN_NEW_BUCKET_COUNT && info.nRefCount < ADDRMAN_NEW_BUCKETS_PER_ADDRESS)
381 CAddrMan() : vRandom(0), vvTried(ADDRMAN_TRIED_BUCKET_COUNT, std::vector<int>(0)), vvNew(ADDRMAN_NEW_BUCKET_COUNT, std::set<int>())
384 RAND_bytes(&nKey[0], 32);
391 // Return the number of (unique) addresses in all tables.
394 return vRandom.size();
405 printf("ADDRMAN CONSISTENCY CHECK FAILED!!! err=%i\n", err);
410 // Add a single address.
411 bool Add(const CAddress &addr, const CNetAddr& source, int64 nTimePenalty = 0)
417 fRet |= Add_(addr, source, nTimePenalty);
421 printf("Added %s from %s: %i tried, %i new\n", addr.ToStringIPPort().c_str(), source.ToString().c_str(), nTried, nNew);
425 // Add multiple addresses.
426 bool Add(const std::vector<CAddress> &vAddr, const CNetAddr& source, int64 nTimePenalty = 0)
432 for (std::vector<CAddress>::const_iterator it = vAddr.begin(); it != vAddr.end(); it++)
433 nAdd += Add_(*it, source, nTimePenalty) ? 1 : 0;
437 printf("Added %i addresses from %s: %i tried, %i new\n", nAdd, source.ToString().c_str(), nTried, nNew);
441 // Mark an entry as accessible.
442 void Good(const CService &addr, int64 nTime = GetAdjustedTime())
452 // Mark an entry as connection attempted to.
453 void Attempt(const CService &addr, int64 nTime = GetAdjustedTime())
458 Attempt_(addr, nTime);
463 // Choose an address to connect to.
464 // nUnkBias determines how much "new" entries are favored over "tried" ones (0-100).
465 CAddress Select(int nUnkBias = 50)
471 addrRet = Select_(nUnkBias);
477 // Return a bunch of addresses, selected at random.
478 std::vector<CAddress> GetAddr()
481 std::vector<CAddress> vAddr;
490 // Mark an entry as currently-connected-to.
491 void Connected(const CService &addr, int64 nTime = GetAdjustedTime())
496 Connected_(addr, nTime);