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
16 #include <openssl/rand.h>
19 /** Extended statistics about a CAddress */
20 class CAddrInfo : public CAddress
23 // where knowledge about this address first came from
26 // last succesfull connection by us
29 // last try whatsoever by us:
30 // int64 CAddress::nLastTry
32 // connection attempts since last succesful attempt
35 // reference count in new sets (memory only)
38 // in tried set? (memory only)
41 // position in vRandom
44 friend class CAddrMan;
49 CAddress* pthis = (CAddress*)(this);
52 READWRITE(nLastSuccess);
66 CAddrInfo(const CAddress &addrIn, const CNetAddr &addrSource) : CAddress(addrIn), source(addrSource)
71 CAddrInfo() : CAddress(), source()
76 // Calculate in which "tried" bucket this entry belongs
77 int GetTriedBucket(const std::vector<unsigned char> &nKey) const;
79 // Calculate in which "new" bucket this entry belongs, given a certain source
80 int GetNewBucket(const std::vector<unsigned char> &nKey, const CNetAddr& src) const;
82 // Calculate in which "new" bucket this entry belongs, using its default source
83 int GetNewBucket(const std::vector<unsigned char> &nKey) const
85 return GetNewBucket(nKey, source);
88 // Determine whether the statistics about this entry are bad enough so that it can just be deleted
89 bool IsTerrible(int64 nNow = GetAdjustedTime()) const;
91 // Calculate the relative chance this entry should be given when selecting nodes to connect to
92 double GetChance(int64 nNow = GetAdjustedTime()) const;
96 // Stochastic address manager
99 // * Only keep a limited number of addresses around, so that addr.dat and memory requirements do not grow without bound.
100 // * Keep the address tables in-memory, and asynchronously dump the entire to able in addr.dat.
101 // * Make sure no (localized) attacker can fill the entire table with his nodes/addresses.
104 // * Addresses are organized into buckets.
105 // * Address that have not yet been tried go into 256 "new" buckets.
106 // * Based on the address range (/16 for IPv4) of source of the information, 32 buckets are selected at random
107 // * The actual bucket is chosen from one of these, based on the range the address itself is located.
108 // * One single address can occur in up to 4 different buckets, to increase selection chances for addresses that
109 // are seen frequently. The chance for increasing this multiplicity decreases exponentially.
110 // * When adding a new address to a full bucket, a randomly chosen entry (with a bias favoring less recently seen
111 // ones) is removed from it first.
112 // * Addresses of nodes that are known to be accessible go into 64 "tried" buckets.
113 // * Each address range selects at random 4 of these buckets.
114 // * The actual bucket is chosen from one of these, based on the full address.
115 // * When adding a new good address to a full bucket, a randomly chosen entry (with a bias favoring less recently
116 // tried ones) is evicted from it, back to the "new" buckets.
117 // * Bucket selection is based on cryptographic hashing, using a randomly-generated 256-bit key, which should not
118 // be observable by adversaries.
119 // * Several indexes are kept for high performance. Defining DEBUG_ADDRMAN will introduce frequent (and expensive)
120 // consistency checks for the entire datastructure.
122 // total number of buckets for tried addresses
123 #define ADDRMAN_TRIED_BUCKET_COUNT 64
125 // maximum allowed number of entries in buckets for tried addresses
126 #define ADDRMAN_TRIED_BUCKET_SIZE 64
128 // total number of buckets for new addresses
129 #define ADDRMAN_NEW_BUCKET_COUNT 256
131 // maximum allowed number of entries in buckets for new addresses
132 #define ADDRMAN_NEW_BUCKET_SIZE 64
134 // over how many buckets entries with tried addresses from a single group (/16 for IPv4) are spread
135 #define ADDRMAN_TRIED_BUCKETS_PER_GROUP 4
137 // over how many buckets entries with new addresses originating from a single group are spread
138 #define ADDRMAN_NEW_BUCKETS_PER_SOURCE_GROUP 32
140 // in how many buckets for entries with new addresses a single address may occur
141 #define ADDRMAN_NEW_BUCKETS_PER_ADDRESS 4
143 // how many entries in a bucket with tried addresses are inspected, when selecting one to replace
144 #define ADDRMAN_TRIED_ENTRIES_INSPECT_ON_EVICT 4
146 // how old addresses can maximally be
147 #define ADDRMAN_HORIZON_DAYS 30
149 // after how many failed attempts we give up on a new node
150 #define ADDRMAN_RETRIES 3
152 // how many successive failures are allowed ...
153 #define ADDRMAN_MAX_FAILURES 10
155 // ... in at least this many days
156 #define ADDRMAN_MIN_FAIL_DAYS 7
158 // the maximum percentage of nodes to return in a getaddr call
159 #define ADDRMAN_GETADDR_MAX_PCT 23
161 // the maximum number of nodes to return in a getaddr call
162 #define ADDRMAN_GETADDR_MAX 2500
164 /** Stochastical (IP) address manager */
168 // critical section to protect the inner data structures
169 mutable CCriticalSection cs;
171 // secret key to randomize bucket select with
172 std::vector<unsigned char> nKey;
177 // table with information about all nId's
178 std::map<int, CAddrInfo> mapInfo;
180 // find an nId based on its network address
181 std::map<CNetAddr, int> mapAddr;
183 // randomly-ordered vector of all nId's
184 std::vector<int> vRandom;
186 // number of "tried" entries
189 // list of "tried" buckets
190 std::vector<std::vector<int> > vvTried;
192 // number of (unique) "new" entries
195 // list of "new" buckets
196 std::vector<std::set<int> > vvNew;
201 CAddrInfo* Find(const CNetAddr& addr, int *pnId = NULL);
203 // find an entry, creating it if necessary.
204 // nTime and nServices of found node is updated, if necessary.
205 CAddrInfo* Create(const CAddress &addr, const CNetAddr &addrSource, int *pnId = NULL);
207 // Swap two elements in vRandom.
208 void SwapRandom(unsigned int nRandomPos1, unsigned int nRandomPos2);
210 // Return position in given bucket to replace.
211 int SelectTried(int nKBucket);
213 // Remove an element from a "new" bucket.
214 // This is the only place where actual deletes occur.
215 // They are never deleted while in the "tried" table, only possibly evicted back to the "new" table.
216 int ShrinkNew(int nUBucket);
218 // Move an entry from the "new" table(s) to the "tried" table
219 // @pre vvUnkown[nOrigin].count(nId) != 0
220 void MakeTried(CAddrInfo& info, int nId, int nOrigin);
222 // Mark an entry "good", possibly moving it from "new" to "tried".
223 void Good_(const CService &addr, int64 nTime);
225 // Add an entry to the "new" table.
226 bool Add_(const CAddress &addr, const CNetAddr& source, int64 nTimePenalty);
228 // Mark an entry as attempted to connect.
229 void Attempt_(const CService &addr, int64 nTime);
231 // Select an address to connect to.
232 // nUnkBias determines how much to favor new addresses over tried ones (min=0, max=100)
233 CAddress Select_(int nUnkBias);
236 // Perform consistency check. Returns an error code or zero.
240 // Select several addresses at once.
241 void GetAddr_(std::vector<CAddress> &vAddr);
243 // Mark an entry as currently-connected-to.
244 void Connected_(const CService &addr, int64 nTime);
250 // serialized format:
251 // * version byte (currently 0)
255 // * number of "new" buckets
256 // * all nNew addrinfo's in vvNew
257 // * all nTried addrinfo's in vvTried
258 // * for each bucket:
259 // * number of elements
260 // * for each element: index
262 // Notice that vvTried, mapAddr and vVector are never encoded explicitly;
263 // they are instead reconstructed from the other information.
265 // vvNew is serialized, but only used if ADDRMAN_UNKOWN_BUCKET_COUNT didn't change,
266 // otherwise it is reconstructed as well.
268 // This format is more complex, but significantly smaller (at most 1.5 MiB), and supports
269 // changes to the ADDRMAN_ parameters without breaking the on-disk structure.
272 unsigned char nVersion = 0;
278 CAddrMan *am = const_cast<CAddrMan*>(this);
281 int nUBuckets = ADDRMAN_NEW_BUCKET_COUNT;
282 READWRITE(nUBuckets);
283 std::map<int, int> mapUnkIds;
285 for (std::map<int, CAddrInfo>::iterator it = am->mapInfo.begin(); it != am->mapInfo.end(); it++)
287 if (nIds == nNew) break; // this means nNew was wrong, oh ow
288 mapUnkIds[(*it).first] = nIds;
289 CAddrInfo &info = (*it).second;
297 for (std::map<int, CAddrInfo>::iterator it = am->mapInfo.begin(); it != am->mapInfo.end(); it++)
299 if (nIds == nTried) break; // this means nTried was wrong, oh ow
300 CAddrInfo &info = (*it).second;
307 for (std::vector<std::set<int> >::iterator it = am->vvNew.begin(); it != am->vvNew.end(); it++)
309 const std::set<int> &vNew = (*it);
310 int nSize = vNew.size();
312 for (std::set<int>::iterator it2 = vNew.begin(); it2 != vNew.end(); it2++)
314 int nIndex = mapUnkIds[*it2];
320 READWRITE(nUBuckets);
325 am->vvTried = std::vector<std::vector<int> >(ADDRMAN_TRIED_BUCKET_COUNT, std::vector<int>(0));
326 am->vvNew = std::vector<std::set<int> >(ADDRMAN_NEW_BUCKET_COUNT, std::set<int>());
327 for (int n = 0; n < am->nNew; n++)
329 CAddrInfo &info = am->mapInfo[n];
331 am->mapAddr[info] = n;
332 info.nRandomPos = vRandom.size();
333 am->vRandom.push_back(n);
334 if (nUBuckets != ADDRMAN_NEW_BUCKET_COUNT)
336 am->vvNew[info.GetNewBucket(am->nKey)].insert(n);
340 am->nIdCount = am->nNew;
342 for (int n = 0; n < am->nTried; n++)
346 std::vector<int> &vTried = am->vvTried[info.GetTriedBucket(am->nKey)];
347 if (vTried.size() < ADDRMAN_TRIED_BUCKET_SIZE)
349 info.nRandomPos = vRandom.size();
350 info.fInTried = true;
351 am->vRandom.push_back(am->nIdCount);
352 am->mapInfo[am->nIdCount] = info;
353 am->mapAddr[info] = am->nIdCount;
354 vTried.push_back(am->nIdCount);
361 for (int b = 0; b < nUBuckets; b++)
363 std::set<int> &vNew = am->vvNew[b];
366 for (int n = 0; n < nSize; n++)
370 CAddrInfo &info = am->mapInfo[nIndex];
371 if (nUBuckets == ADDRMAN_NEW_BUCKET_COUNT && info.nRefCount < ADDRMAN_NEW_BUCKETS_PER_ADDRESS)
382 CAddrMan() : vRandom(0), vvTried(ADDRMAN_TRIED_BUCKET_COUNT, std::vector<int>(0)), vvNew(ADDRMAN_NEW_BUCKET_COUNT, std::set<int>())
385 RAND_bytes(&nKey[0], 32);
392 // Return the number of (unique) addresses in all tables.
395 return vRandom.size();
406 printf("ADDRMAN CONSISTENCY CHECK FAILED!!! err=%i\n", err);
411 // Add a single address.
412 bool Add(const CAddress &addr, const CNetAddr& source, int64 nTimePenalty = 0)
418 fRet |= Add_(addr, source, nTimePenalty);
422 printf("Added %s from %s: %i tried, %i new\n", addr.ToStringIPPort().c_str(), source.ToString().c_str(), nTried, nNew);
426 // Add multiple addresses.
427 bool Add(const std::vector<CAddress> &vAddr, const CNetAddr& source, int64 nTimePenalty = 0)
433 for (std::vector<CAddress>::const_iterator it = vAddr.begin(); it != vAddr.end(); it++)
434 nAdd += Add_(*it, source, nTimePenalty) ? 1 : 0;
438 printf("Added %i addresses from %s: %i tried, %i new\n", nAdd, source.ToString().c_str(), nTried, nNew);
442 // Mark an entry as accessible.
443 void Good(const CService &addr, int64 nTime = GetAdjustedTime())
453 // Mark an entry as connection attempted to.
454 void Attempt(const CService &addr, int64 nTime = GetAdjustedTime())
459 Attempt_(addr, nTime);
464 // Choose an address to connect to.
465 // nUnkBias determines how much "new" entries are favored over "tried" ones (0-100).
466 CAddress Select(int nUnkBias = 50)
472 addrRet = Select_(nUnkBias);
478 // Return a bunch of addresses, selected at random.
479 std::vector<CAddress> GetAddr()
482 std::vector<CAddress> vAddr;
491 // Mark an entry as currently-connected-to.
492 void Connected(const CService &addr, int64 nTime = GetAdjustedTime())
497 Connected_(addr, nTime);