Remove unused variable int64_t nEnd
[bitcoinplatinum.git] / src / addrman.h
blob70d907488f3d92bdf432d5091aa68e7714887193
1 // Copyright (c) 2012 Pieter Wuille
2 // Copyright (c) 2012-2016 The Bitcoin Core developers
3 // Distributed under the MIT software license, see the accompanying
4 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
6 #ifndef BITCOIN_ADDRMAN_H
7 #define BITCOIN_ADDRMAN_H
9 #include "netaddress.h"
10 #include "protocol.h"
11 #include "random.h"
12 #include "sync.h"
13 #include "timedata.h"
14 #include "util.h"
16 #include <map>
17 #include <set>
18 #include <stdint.h>
19 #include <vector>
21 /**
22 * Extended statistics about a CAddress
24 class CAddrInfo : public CAddress
28 public:
29 //! last try whatsoever by us (memory only)
30 int64_t nLastTry;
32 //! last counted attempt (memory only)
33 int64_t nLastCountAttempt;
35 private:
36 //! where knowledge about this address first came from
37 CNetAddr source;
39 //! last successful connection by us
40 int64_t nLastSuccess;
42 //! connection attempts since last successful attempt
43 int nAttempts;
45 //! reference count in new sets (memory only)
46 int nRefCount;
48 //! in tried set? (memory only)
49 bool fInTried;
51 //! position in vRandom
52 int nRandomPos;
54 friend class CAddrMan;
56 public:
58 ADD_SERIALIZE_METHODS;
60 template <typename Stream, typename Operation>
61 inline void SerializationOp(Stream& s, Operation ser_action) {
62 READWRITE(*(CAddress*)this);
63 READWRITE(source);
64 READWRITE(nLastSuccess);
65 READWRITE(nAttempts);
68 void Init()
70 nLastSuccess = 0;
71 nLastTry = 0;
72 nLastCountAttempt = 0;
73 nAttempts = 0;
74 nRefCount = 0;
75 fInTried = false;
76 nRandomPos = -1;
79 CAddrInfo(const CAddress &addrIn, const CNetAddr &addrSource) : CAddress(addrIn), source(addrSource)
81 Init();
84 CAddrInfo() : CAddress(), source()
86 Init();
89 //! Calculate in which "tried" bucket this entry belongs
90 int GetTriedBucket(const uint256 &nKey) const;
92 //! Calculate in which "new" bucket this entry belongs, given a certain source
93 int GetNewBucket(const uint256 &nKey, const CNetAddr& src) const;
95 //! Calculate in which "new" bucket this entry belongs, using its default source
96 int GetNewBucket(const uint256 &nKey) const
98 return GetNewBucket(nKey, source);
101 //! Calculate in which position of a bucket to store this entry.
102 int GetBucketPosition(const uint256 &nKey, bool fNew, int nBucket) const;
104 //! Determine whether the statistics about this entry are bad enough so that it can just be deleted
105 bool IsTerrible(int64_t nNow = GetAdjustedTime()) const;
107 //! Calculate the relative chance this entry should be given when selecting nodes to connect to
108 double GetChance(int64_t nNow = GetAdjustedTime()) const;
112 /** Stochastic address manager
114 * Design goals:
115 * * Keep the address tables in-memory, and asynchronously dump the entire table to peers.dat.
116 * * Make sure no (localized) attacker can fill the entire table with his nodes/addresses.
118 * To that end:
119 * * Addresses are organized into buckets.
120 * * Addresses that have not yet been tried go into 1024 "new" buckets.
121 * * Based on the address range (/16 for IPv4) of the source of information, 64 buckets are selected at random.
122 * * The actual bucket is chosen from one of these, based on the range in which the address itself is located.
123 * * One single address can occur in up to 8 different buckets to increase selection chances for addresses that
124 * are seen frequently. The chance for increasing this multiplicity decreases exponentially.
125 * * When adding a new address to a full bucket, a randomly chosen entry (with a bias favoring less recently seen
126 * ones) is removed from it first.
127 * * Addresses of nodes that are known to be accessible go into 256 "tried" buckets.
128 * * Each address range selects at random 8 of these buckets.
129 * * The actual bucket is chosen from one of these, based on the full address.
130 * * When adding a new good address to a full bucket, a randomly chosen entry (with a bias favoring less recently
131 * tried ones) is evicted from it, back to the "new" buckets.
132 * * Bucket selection is based on cryptographic hashing, using a randomly-generated 256-bit key, which should not
133 * be observable by adversaries.
134 * * Several indexes are kept for high performance. Defining DEBUG_ADDRMAN will introduce frequent (and expensive)
135 * consistency checks for the entire data structure.
138 //! total number of buckets for tried addresses
139 #define ADDRMAN_TRIED_BUCKET_COUNT_LOG2 8
141 //! total number of buckets for new addresses
142 #define ADDRMAN_NEW_BUCKET_COUNT_LOG2 10
144 //! maximum allowed number of entries in buckets for new and tried addresses
145 #define ADDRMAN_BUCKET_SIZE_LOG2 6
147 //! over how many buckets entries with tried addresses from a single group (/16 for IPv4) are spread
148 #define ADDRMAN_TRIED_BUCKETS_PER_GROUP 8
150 //! over how many buckets entries with new addresses originating from a single group are spread
151 #define ADDRMAN_NEW_BUCKETS_PER_SOURCE_GROUP 64
153 //! in how many buckets for entries with new addresses a single address may occur
154 #define ADDRMAN_NEW_BUCKETS_PER_ADDRESS 8
156 //! how old addresses can maximally be
157 #define ADDRMAN_HORIZON_DAYS 30
159 //! after how many failed attempts we give up on a new node
160 #define ADDRMAN_RETRIES 3
162 //! how many successive failures are allowed ...
163 #define ADDRMAN_MAX_FAILURES 10
165 //! ... in at least this many days
166 #define ADDRMAN_MIN_FAIL_DAYS 7
168 //! the maximum percentage of nodes to return in a getaddr call
169 #define ADDRMAN_GETADDR_MAX_PCT 23
171 //! the maximum number of nodes to return in a getaddr call
172 #define ADDRMAN_GETADDR_MAX 2500
174 //! Convenience
175 #define ADDRMAN_TRIED_BUCKET_COUNT (1 << ADDRMAN_TRIED_BUCKET_COUNT_LOG2)
176 #define ADDRMAN_NEW_BUCKET_COUNT (1 << ADDRMAN_NEW_BUCKET_COUNT_LOG2)
177 #define ADDRMAN_BUCKET_SIZE (1 << ADDRMAN_BUCKET_SIZE_LOG2)
179 /**
180 * Stochastical (IP) address manager
182 class CAddrMan
184 private:
185 //! critical section to protect the inner data structures
186 mutable CCriticalSection cs;
188 //! last used nId
189 int nIdCount;
191 //! table with information about all nIds
192 std::map<int, CAddrInfo> mapInfo;
194 //! find an nId based on its network address
195 std::map<CNetAddr, int> mapAddr;
197 //! randomly-ordered vector of all nIds
198 std::vector<int> vRandom;
200 // number of "tried" entries
201 int nTried;
203 //! list of "tried" buckets
204 int vvTried[ADDRMAN_TRIED_BUCKET_COUNT][ADDRMAN_BUCKET_SIZE];
206 //! number of (unique) "new" entries
207 int nNew;
209 //! list of "new" buckets
210 int vvNew[ADDRMAN_NEW_BUCKET_COUNT][ADDRMAN_BUCKET_SIZE];
212 //! last time Good was called (memory only)
213 int64_t nLastGood;
215 protected:
216 //! secret key to randomize bucket select with
217 uint256 nKey;
219 //! Source of random numbers for randomization in inner loops
220 FastRandomContext insecure_rand;
222 //! Find an entry.
223 CAddrInfo* Find(const CNetAddr& addr, int *pnId = NULL);
225 //! find an entry, creating it if necessary.
226 //! nTime and nServices of the found node are updated, if necessary.
227 CAddrInfo* Create(const CAddress &addr, const CNetAddr &addrSource, int *pnId = NULL);
229 //! Swap two elements in vRandom.
230 void SwapRandom(unsigned int nRandomPos1, unsigned int nRandomPos2);
232 //! Move an entry from the "new" table(s) to the "tried" table
233 void MakeTried(CAddrInfo& info, int nId);
235 //! Delete an entry. It must not be in tried, and have refcount 0.
236 void Delete(int nId);
238 //! Clear a position in a "new" table. This is the only place where entries are actually deleted.
239 void ClearNew(int nUBucket, int nUBucketPos);
241 //! Mark an entry "good", possibly moving it from "new" to "tried".
242 void Good_(const CService &addr, int64_t nTime);
244 //! Add an entry to the "new" table.
245 bool Add_(const CAddress &addr, const CNetAddr& source, int64_t nTimePenalty);
247 //! Mark an entry as attempted to connect.
248 void Attempt_(const CService &addr, bool fCountFailure, int64_t nTime);
250 //! Select an address to connect to, if newOnly is set to true, only the new table is selected from.
251 CAddrInfo Select_(bool newOnly);
253 //! Wraps GetRandInt to allow tests to override RandomInt and make it determinismistic.
254 virtual int RandomInt(int nMax);
256 #ifdef DEBUG_ADDRMAN
257 //! Perform consistency check. Returns an error code or zero.
258 int Check_();
259 #endif
261 //! Select several addresses at once.
262 void GetAddr_(std::vector<CAddress> &vAddr);
264 //! Mark an entry as currently-connected-to.
265 void Connected_(const CService &addr, int64_t nTime);
267 //! Update an entry's service bits.
268 void SetServices_(const CService &addr, ServiceFlags nServices);
270 public:
272 * serialized format:
273 * * version byte (currently 1)
274 * * 0x20 + nKey (serialized as if it were a vector, for backward compatibility)
275 * * nNew
276 * * nTried
277 * * number of "new" buckets XOR 2**30
278 * * all nNew addrinfos in vvNew
279 * * all nTried addrinfos in vvTried
280 * * for each bucket:
281 * * number of elements
282 * * for each element: index
284 * 2**30 is xorred with the number of buckets to make addrman deserializer v0 detect it
285 * as incompatible. This is necessary because it did not check the version number on
286 * deserialization.
288 * Notice that vvTried, mapAddr and vVector are never encoded explicitly;
289 * they are instead reconstructed from the other information.
291 * vvNew is serialized, but only used if ADDRMAN_UNKNOWN_BUCKET_COUNT didn't change,
292 * otherwise it is reconstructed as well.
294 * This format is more complex, but significantly smaller (at most 1.5 MiB), and supports
295 * changes to the ADDRMAN_ parameters without breaking the on-disk structure.
297 * We don't use ADD_SERIALIZE_METHODS since the serialization and deserialization code has
298 * very little in common.
300 template<typename Stream>
301 void Serialize(Stream &s) const
303 LOCK(cs);
305 unsigned char nVersion = 1;
306 s << nVersion;
307 s << ((unsigned char)32);
308 s << nKey;
309 s << nNew;
310 s << nTried;
312 int nUBuckets = ADDRMAN_NEW_BUCKET_COUNT ^ (1 << 30);
313 s << nUBuckets;
314 std::map<int, int> mapUnkIds;
315 int nIds = 0;
316 for (std::map<int, CAddrInfo>::const_iterator it = mapInfo.begin(); it != mapInfo.end(); it++) {
317 mapUnkIds[(*it).first] = nIds;
318 const CAddrInfo &info = (*it).second;
319 if (info.nRefCount) {
320 assert(nIds != nNew); // this means nNew was wrong, oh ow
321 s << info;
322 nIds++;
325 nIds = 0;
326 for (std::map<int, CAddrInfo>::const_iterator it = mapInfo.begin(); it != mapInfo.end(); it++) {
327 const CAddrInfo &info = (*it).second;
328 if (info.fInTried) {
329 assert(nIds != nTried); // this means nTried was wrong, oh ow
330 s << info;
331 nIds++;
334 for (int bucket = 0; bucket < ADDRMAN_NEW_BUCKET_COUNT; bucket++) {
335 int nSize = 0;
336 for (int i = 0; i < ADDRMAN_BUCKET_SIZE; i++) {
337 if (vvNew[bucket][i] != -1)
338 nSize++;
340 s << nSize;
341 for (int i = 0; i < ADDRMAN_BUCKET_SIZE; i++) {
342 if (vvNew[bucket][i] != -1) {
343 int nIndex = mapUnkIds[vvNew[bucket][i]];
344 s << nIndex;
350 template<typename Stream>
351 void Unserialize(Stream& s)
353 LOCK(cs);
355 Clear();
357 unsigned char nVersion;
358 s >> nVersion;
359 unsigned char nKeySize;
360 s >> nKeySize;
361 if (nKeySize != 32) throw std::ios_base::failure("Incorrect keysize in addrman deserialization");
362 s >> nKey;
363 s >> nNew;
364 s >> nTried;
365 int nUBuckets = 0;
366 s >> nUBuckets;
367 if (nVersion != 0) {
368 nUBuckets ^= (1 << 30);
371 if (nNew > ADDRMAN_NEW_BUCKET_COUNT * ADDRMAN_BUCKET_SIZE) {
372 throw std::ios_base::failure("Corrupt CAddrMan serialization, nNew exceeds limit.");
375 if (nTried > ADDRMAN_TRIED_BUCKET_COUNT * ADDRMAN_BUCKET_SIZE) {
376 throw std::ios_base::failure("Corrupt CAddrMan serialization, nTried exceeds limit.");
379 // Deserialize entries from the new table.
380 for (int n = 0; n < nNew; n++) {
381 CAddrInfo &info = mapInfo[n];
382 s >> info;
383 mapAddr[info] = n;
384 info.nRandomPos = vRandom.size();
385 vRandom.push_back(n);
386 if (nVersion != 1 || nUBuckets != ADDRMAN_NEW_BUCKET_COUNT) {
387 // In case the new table data cannot be used (nVersion unknown, or bucket count wrong),
388 // immediately try to give them a reference based on their primary source address.
389 int nUBucket = info.GetNewBucket(nKey);
390 int nUBucketPos = info.GetBucketPosition(nKey, true, nUBucket);
391 if (vvNew[nUBucket][nUBucketPos] == -1) {
392 vvNew[nUBucket][nUBucketPos] = n;
393 info.nRefCount++;
397 nIdCount = nNew;
399 // Deserialize entries from the tried table.
400 int nLost = 0;
401 for (int n = 0; n < nTried; n++) {
402 CAddrInfo info;
403 s >> info;
404 int nKBucket = info.GetTriedBucket(nKey);
405 int nKBucketPos = info.GetBucketPosition(nKey, false, nKBucket);
406 if (vvTried[nKBucket][nKBucketPos] == -1) {
407 info.nRandomPos = vRandom.size();
408 info.fInTried = true;
409 vRandom.push_back(nIdCount);
410 mapInfo[nIdCount] = info;
411 mapAddr[info] = nIdCount;
412 vvTried[nKBucket][nKBucketPos] = nIdCount;
413 nIdCount++;
414 } else {
415 nLost++;
418 nTried -= nLost;
420 // Deserialize positions in the new table (if possible).
421 for (int bucket = 0; bucket < nUBuckets; bucket++) {
422 int nSize = 0;
423 s >> nSize;
424 for (int n = 0; n < nSize; n++) {
425 int nIndex = 0;
426 s >> nIndex;
427 if (nIndex >= 0 && nIndex < nNew) {
428 CAddrInfo &info = mapInfo[nIndex];
429 int nUBucketPos = info.GetBucketPosition(nKey, true, bucket);
430 if (nVersion == 1 && nUBuckets == ADDRMAN_NEW_BUCKET_COUNT && vvNew[bucket][nUBucketPos] == -1 && info.nRefCount < ADDRMAN_NEW_BUCKETS_PER_ADDRESS) {
431 info.nRefCount++;
432 vvNew[bucket][nUBucketPos] = nIndex;
438 // Prune new entries with refcount 0 (as a result of collisions).
439 int nLostUnk = 0;
440 for (std::map<int, CAddrInfo>::const_iterator it = mapInfo.begin(); it != mapInfo.end(); ) {
441 if (it->second.fInTried == false && it->second.nRefCount == 0) {
442 std::map<int, CAddrInfo>::const_iterator itCopy = it++;
443 Delete(itCopy->first);
444 nLostUnk++;
445 } else {
446 it++;
449 if (nLost + nLostUnk > 0) {
450 LogPrint(BCLog::ADDRMAN, "addrman lost %i new and %i tried addresses due to collisions\n", nLostUnk, nLost);
453 Check();
456 void Clear()
458 std::vector<int>().swap(vRandom);
459 nKey = GetRandHash();
460 for (size_t bucket = 0; bucket < ADDRMAN_NEW_BUCKET_COUNT; bucket++) {
461 for (size_t entry = 0; entry < ADDRMAN_BUCKET_SIZE; entry++) {
462 vvNew[bucket][entry] = -1;
465 for (size_t bucket = 0; bucket < ADDRMAN_TRIED_BUCKET_COUNT; bucket++) {
466 for (size_t entry = 0; entry < ADDRMAN_BUCKET_SIZE; entry++) {
467 vvTried[bucket][entry] = -1;
471 nIdCount = 0;
472 nTried = 0;
473 nNew = 0;
474 nLastGood = 1; //Initially at 1 so that "never" is strictly worse.
477 CAddrMan()
479 Clear();
482 ~CAddrMan()
484 nKey.SetNull();
487 //! Return the number of (unique) addresses in all tables.
488 size_t size() const
490 LOCK(cs); // TODO: Cache this in an atomic to avoid this overhead
491 return vRandom.size();
494 //! Consistency check
495 void Check()
497 #ifdef DEBUG_ADDRMAN
499 LOCK(cs);
500 int err;
501 if ((err=Check_()))
502 LogPrintf("ADDRMAN CONSISTENCY CHECK FAILED!!! err=%i\n", err);
504 #endif
507 //! Add a single address.
508 bool Add(const CAddress &addr, const CNetAddr& source, int64_t nTimePenalty = 0)
510 LOCK(cs);
511 bool fRet = false;
512 Check();
513 fRet |= Add_(addr, source, nTimePenalty);
514 Check();
515 if (fRet) {
516 LogPrint(BCLog::ADDRMAN, "Added %s from %s: %i tried, %i new\n", addr.ToStringIPPort(), source.ToString(), nTried, nNew);
518 return fRet;
521 //! Add multiple addresses.
522 bool Add(const std::vector<CAddress> &vAddr, const CNetAddr& source, int64_t nTimePenalty = 0)
524 LOCK(cs);
525 int nAdd = 0;
526 Check();
527 for (std::vector<CAddress>::const_iterator it = vAddr.begin(); it != vAddr.end(); it++)
528 nAdd += Add_(*it, source, nTimePenalty) ? 1 : 0;
529 Check();
530 if (nAdd) {
531 LogPrint(BCLog::ADDRMAN, "Added %i addresses from %s: %i tried, %i new\n", nAdd, source.ToString(), nTried, nNew);
533 return nAdd > 0;
536 //! Mark an entry as accessible.
537 void Good(const CService &addr, int64_t nTime = GetAdjustedTime())
539 LOCK(cs);
540 Check();
541 Good_(addr, nTime);
542 Check();
545 //! Mark an entry as connection attempted to.
546 void Attempt(const CService &addr, bool fCountFailure, int64_t nTime = GetAdjustedTime())
548 LOCK(cs);
549 Check();
550 Attempt_(addr, fCountFailure, nTime);
551 Check();
555 * Choose an address to connect to.
557 CAddrInfo Select(bool newOnly = false)
559 CAddrInfo addrRet;
561 LOCK(cs);
562 Check();
563 addrRet = Select_(newOnly);
564 Check();
566 return addrRet;
569 //! Return a bunch of addresses, selected at random.
570 std::vector<CAddress> GetAddr()
572 Check();
573 std::vector<CAddress> vAddr;
575 LOCK(cs);
576 GetAddr_(vAddr);
578 Check();
579 return vAddr;
582 //! Mark an entry as currently-connected-to.
583 void Connected(const CService &addr, int64_t nTime = GetAdjustedTime())
585 LOCK(cs);
586 Check();
587 Connected_(addr, nTime);
588 Check();
591 void SetServices(const CService &addr, ServiceFlags nServices)
593 LOCK(cs);
594 Check();
595 SetServices_(addr, nServices);
596 Check();
601 #endif // BITCOIN_ADDRMAN_H