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>
18 // Extended statistics about a CAddress
19 class CAddrInfo : public CAddress
22 // where knowledge about this address first came from
25 // last successful connection by us
28 // last try whatsoever by us:
29 // int64_t CAddress::nLastTry
31 // connection attempts since last successful 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);
57 CAddrInfo(const CAddress &addrIn, const CNetAddr &addrSource);
60 // Calculate in which "tried" bucket this entry belongs
61 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;
66 // Calculate in which "new" bucket this entry belongs, using its default source
67 int GetNewBucket(const std::vector<unsigned char> &nKey) const;
69 // Determine whether the statistics about this entry are bad enough so that it can just be deleted
70 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;
77 // Stochastic address manager
80 // * Only keep a limited number of addresses around, so that addr.dat and memory requirements do not grow without bound.
81 // * Keep the address tables in-memory, and asynchronously dump the entire to able in addr.dat.
82 // * Make sure no (localized) attacker can fill the entire table with his nodes/addresses.
85 // * Addresses are organized into buckets.
86 // * Address that have not yet been tried go into 256 "new" buckets.
87 // * Based on the address range (/16 for IPv4) of source of the information, 32 buckets are selected at random
88 // * The actual bucket is chosen from one of these, based on the range the address itself is located.
89 // * One single address can occur in up to 4 different buckets, to increase selection chances for addresses that
90 // are seen frequently. The chance for increasing this multiplicity decreases exponentially.
91 // * When adding a new address to a full bucket, a randomly chosen entry (with a bias favoring less recently seen
92 // ones) is removed from it first.
93 // * Addresses of nodes that are known to be accessible go into 64 "tried" buckets.
94 // * Each address range selects at random 4 of these buckets.
95 // * The actual bucket is chosen from one of these, based on the full address.
96 // * When adding a new good address to a full bucket, a randomly chosen entry (with a bias favoring less recently
97 // tried ones) is evicted from it, back to the "new" buckets.
98 // * Bucket selection is based on cryptographic hashing, using a randomly-generated 256-bit key, which should not
99 // be observable by adversaries.
100 // * Several indexes are kept for high performance.
102 // total number of buckets for tried addresses
103 #define ADDRMAN_TRIED_BUCKET_COUNT 64
105 // maximum allowed number of entries in buckets for tried addresses
106 #define ADDRMAN_TRIED_BUCKET_SIZE 64
108 // total number of buckets for new addresses
109 #define ADDRMAN_NEW_BUCKET_COUNT 256
111 // maximum allowed number of entries in buckets for new addresses
112 #define ADDRMAN_NEW_BUCKET_SIZE 64
114 // over how many buckets entries with tried addresses from a single group (/16 for IPv4) are spread
115 #define ADDRMAN_TRIED_BUCKETS_PER_GROUP 4
117 // over how many buckets entries with new addresses originating from a single group are spread
118 #define ADDRMAN_NEW_BUCKETS_PER_SOURCE_GROUP 32
120 // in how many buckets for entries with new addresses a single address may occur
121 #define ADDRMAN_NEW_BUCKETS_PER_ADDRESS 4
123 // how many entries in a bucket with tried addresses are inspected, when selecting one to replace
124 #define ADDRMAN_TRIED_ENTRIES_INSPECT_ON_EVICT 4
126 // how old addresses can maximally be
127 #define ADDRMAN_HORIZON_DAYS 30
129 // after how many failed attempts we give up on a new node
130 #define ADDRMAN_RETRIES 3
132 // how many successive failures are allowed ...
133 #define ADDRMAN_MAX_FAILURES 10
135 // ... in at least this many days
136 #define ADDRMAN_MIN_FAIL_DAYS 7
138 // the maximum percentage of nodes to return in a getaddr call
139 #define ADDRMAN_GETADDR_MAX_PCT 23
141 // the maximum number of nodes to return in a getaddr call
142 #define ADDRMAN_GETADDR_MAX 2500
144 // Stochastical (IP) address manager
148 // critical section to protect the inner data structures
149 mutable CCriticalSection cs;
151 // secret key to randomize bucket select with
152 std::vector<unsigned char> nKey;
157 // table with information about all nIds
158 std::map<int, CAddrInfo> mapInfo;
160 // find an nId based on its network address
161 std::map<CNetAddr, int> mapAddr;
163 // randomly-ordered vector of all nIds
164 std::vector<int> vRandom;
166 // number of "tried" entries
169 // list of "tried" buckets
170 std::vector<std::vector<int> > vvTried;
172 // number of (unique) "new" entries
175 // list of "new" buckets
176 std::vector<std::set<int> > vvNew;
181 CAddrInfo* Find(const CNetAddr& addr, int *pnId = NULL);
183 // find an entry, creating it if necessary.
184 // nTime and nServices of found node is updated, if necessary.
185 CAddrInfo* Create(const CAddress &addr, const CNetAddr &addrSource, int *pnId = NULL);
187 // Swap two elements in vRandom.
188 void SwapRandom(unsigned int nRandomPos1, unsigned int nRandomPos2);
190 // Return position in given bucket to replace.
191 int SelectTried(int nKBucket);
193 // Remove an element from a "new" bucket.
194 // This is the only place where actual deletes occur.
195 // They are never deleted while in the "tried" table, only possibly evicted back to the "new" table.
196 int ShrinkNew(int nUBucket);
198 // Move an entry from the "new" table(s) to the "tried" table
199 // @pre vvUnkown[nOrigin].count(nId) != 0
200 void MakeTried(CAddrInfo& info, int nId, int nOrigin);
202 // Mark an entry "good", possibly moving it from "new" to "tried".
203 void Good_(const CService &addr, int64_t nTime);
205 // Add an entry to the "new" table.
206 bool Add_(const CAddress &addr, const CNetAddr& source, int64_t nTimePenalty);
208 // Mark an entry as attempted to connect.
209 void Attempt_(const CService &addr, int64_t nTime);
211 // Select an address to connect to.
212 // nUnkBias determines how much to favor new addresses over tried ones (min=0, max=100)
213 CAddress Select_(int nUnkBias);
215 // Select several addresses at once.
216 void GetAddr_(std::vector<CAddress> &vAddr);
217 void GetOnlineAddr_(std::vector<CAddrInfo> &vAddr);
219 // Mark an entry as currently-connected-to.
220 void Connected_(const CService &addr, int64_t nTime);
224 typedef std::map<int, int> MapUnkIds; // For MSVC macro
237 *am = const_cast<CAddrMan*>(this);
242 nUBuckets = ADDRMAN_NEW_BUCKET_COUNT;
244 READWRITE(nUBuckets);
248 for (auto it = am->mapInfo.begin(); it != am->mapInfo.end(); it++)
251 break; // this means nNew was wrong, oh ow
252 mapUnkIds[(*it).first] = nIds;
255 &info = (*it).second;
264 for (auto it = am->mapInfo.begin(); it != am->mapInfo.end(); it++)
267 break; /* this means nTried was wrong, oh ow */
270 &info = (*it).second;
279 auto it = am->vvNew.begin();
280 it != am->vvNew.end();
288 nSize = int( vNew.size() );
291 for (auto it2 = vNew.begin(); it2 != vNew.end(); it2++)
294 nIndex = mapUnkIds[*it2];
304 READWRITE(nUBuckets);
310 std::vector<std::vector<int> >(
311 ADDRMAN_TRIED_BUCKET_COUNT,
315 std::vector<std::set<int> >(
316 ADDRMAN_NEW_BUCKET_COUNT,
319 for (int n = 0; n < am->nNew; n++)
322 &info = am->mapInfo[n];
325 am->mapAddr[info] = n;
326 info.nRandomPos = int( vRandom.size() );
327 am->vRandom.push_back(n);
328 if (nUBuckets != ADDRMAN_NEW_BUCKET_COUNT)
330 am->vvNew[info.GetNewBucket(am->nKey)].insert(n);
334 am->nIdCount = am->nNew;
339 for (int n = 0; n < am->nTried; n++)
347 &vTried = am->vvTried[info.GetTriedBucket(am->nKey)];
349 if (vTried.size() < ADDRMAN_TRIED_BUCKET_SIZE)
351 info.nRandomPos = int( vRandom.size() );
352 info.fInTried = true;
353 am->vRandom.push_back(am->nIdCount);
354 am->mapInfo[am->nIdCount] = info;
355 am->mapAddr[info] = am->nIdCount;
356 vTried.push_back(am->nIdCount);
365 for (int b = 0; b < nUBuckets; b++)
368 &vNew = am->vvNew[b];
374 for (int n = 0; n < nSize; n++)
382 &info = am->mapInfo[nIndex];
385 (nUBuckets == ADDRMAN_NEW_BUCKET_COUNT) &&
386 (info.nRefCount < ADDRMAN_NEW_BUCKETS_PER_ADDRESS)
399 // Return the number of (unique) addresses in all tables.
402 // Add a single address.
403 bool Add(const CAddress &addr, const CNetAddr& source, int64_t nTimePenalty = 0);
405 // Add multiple addresses.
406 bool Add(const std::vector<CAddress> &vAddr, const CNetAddr& source, int64_t nTimePenalty = 0);
408 // Mark an entry as accessible.
409 void Good(const CService &addr, int64_t nTime = GetAdjustedTime());
411 // Mark an entry as connection attempted to.
412 void Attempt(const CService &addr, int64_t nTime = GetAdjustedTime());
414 // Choose an address to connect to.
415 // nUnkBias determines how much "new" entries are favored over "tried" ones (0-100).
416 CAddress Select(int nUnkBias = 50);
418 // Return a bunch of addresses, selected at random.
419 std::vector<CAddress> GetAddr();
421 std::vector<CAddrInfo> GetOnlineAddr();
423 // Mark an entry as currently-connected-to.
424 void Connected(const CService &addr, int64_t nTime = GetAdjustedTime());