Remove headers.h
[novacoin.git] / src / addrman.h
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
6
7 #include "netbase.h"
8 #include "protocol.h"
9
10
11 #include <map>
12 #include <vector>
13
14 #include <openssl/rand.h>
15
16
17 /** Extended statistics about a CAddress */
18 class CAddrInfo : public CAddress
19 {
20 private:
21     // where knowledge about this address first came from
22     CNetAddr source;
23
24     // last succesfull connection by us
25     int64 nLastSuccess;
26
27     // last try whatsoever by us:
28     // int64 CAddress::nLastTry
29
30     // connection attempts since last succesful attempt
31     int nAttempts;
32
33     // reference count in new sets (memory only)
34     int nRefCount;
35
36     // in tried set? (memory only)
37     bool fInTried;
38
39     // position in vRandom
40     int nRandomPos;
41
42     friend class CAddrMan;
43
44 public:
45
46     IMPLEMENT_SERIALIZE(
47         CAddress* pthis = (CAddress*)(this);
48         READWRITE(*pthis);
49         READWRITE(source);
50         READWRITE(nLastSuccess);
51         READWRITE(nAttempts);
52     )
53
54     void Init()
55     {
56         nLastSuccess = 0;
57         nLastTry = 0;
58         nAttempts = 0;
59         nRefCount = 0;
60         fInTried = false;
61         nRandomPos = -1;
62     }
63
64     CAddrInfo(const CAddress &addrIn, const CNetAddr &addrSource) : CAddress(addrIn)
65     {
66         Init();
67     }
68
69     CAddrInfo() : CAddress(), source()
70     {
71         Init();
72     }
73
74     // Calculate in which "tried" bucket this entry belongs
75     int GetTriedBucket(const std::vector<unsigned char> &nKey) const;
76
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;
79
80     // Calculate in which "new" bucket this entry belongs, using its default source
81     int GetNewBucket(const std::vector<unsigned char> &nKey) const
82     {
83         return GetNewBucket(nKey, source);
84     }
85
86     // Determine whether the statistics about this entry are bad enough so that it can just be deleted
87     bool IsTerrible(int64 nNow = GetAdjustedTime()) const;
88
89     // Calculate the relative chance this entry should be given when selecting nodes to connect to
90     double GetChance(int64 nNow = GetAdjustedTime()) const;
91
92 };
93
94 // Stochastic address manager
95 //
96 // Design goals:
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.
100 //
101 // To that end:
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 datastructure.
119
120 // total number of buckets for tried addresses
121 #define ADDRMAN_TRIED_BUCKET_COUNT 64
122
123 // maximum allowed number of entries in buckets for tried addresses
124 #define ADDRMAN_TRIED_BUCKET_SIZE 64
125
126 // total number of buckets for new addresses
127 #define ADDRMAN_NEW_BUCKET_COUNT 256
128
129 // maximum allowed number of entries in buckets for new addresses
130 #define ADDRMAN_NEW_BUCKET_SIZE 64
131
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
134
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
137
138 // in how many buckets for entries with new addresses a single address may occur
139 #define ADDRMAN_NEW_BUCKETS_PER_ADDRESS 4
140
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
143
144 // how old addresses can maximally be
145 #define ADDRMAN_HORIZON_DAYS 30
146
147 // after how many failed attempts we give up on a new node
148 #define ADDRMAN_RETRIES 3
149
150 // how many successive failures are allowed ...
151 #define ADDRMAN_MAX_FAILURES 10
152
153 // ... in at least this many days
154 #define ADDRMAN_MIN_FAIL_DAYS 7
155
156 // the maximum percentage of nodes to return in a getaddr call
157 #define ADDRMAN_GETADDR_MAX_PCT 23
158
159 // the maximum number of nodes to return in a getaddr call
160 #define ADDRMAN_GETADDR_MAX 2500
161
162 /** Stochastical (IP) address manager */
163 class CAddrMan
164 {
165 private:
166     // critical section to protect the inner data structures
167     mutable CCriticalSection cs;
168
169     // secret key to randomize bucket select with
170     std::vector<unsigned char> nKey;
171
172     // last used nId
173     int nIdCount;
174
175     // table with information about all nId's
176     std::map<int, CAddrInfo> mapInfo;
177
178     // find an nId based on its network address
179     std::map<CNetAddr, int> mapAddr;
180
181     // randomly-ordered vector of all nId's
182     std::vector<int> vRandom;
183
184     // number of "tried" entries
185     int nTried;
186
187     // list of "tried" buckets
188     std::vector<std::vector<int> > vvTried;
189
190     // number of (unique) "new" entries
191     int nNew;
192
193     // list of "new" buckets
194     std::vector<std::set<int> > vvNew;
195
196 protected:
197
198     // Find an entry.
199     CAddrInfo* Find(const CNetAddr& addr, int *pnId = NULL);
200
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);
204
205     // Swap two elements in vRandom.
206     void SwapRandom(int nRandomPos1, int nRandomPos2);
207
208     // Return position in given bucket to replace.
209     int SelectTried(int nKBucket);
210
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);
215  
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);
219
220     // Mark an entry "good", possibly moving it from "new" to "tried".
221     void Good_(const CService &addr, int64 nTime);
222
223     // Add an entry to the "new" table.
224     bool Add_(const CAddress &addr, const CNetAddr& source, int64 nTimePenalty);
225
226     // Mark an entry as attempted to connect.
227     void Attempt_(const CService &addr, int64 nTime);
228
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);
232
233 #ifdef DEBUG_ADDRMAN
234     // Perform consistency check. Returns an error code or zero.
235     int Check_();
236 #endif
237
238     // Select several addresses at once.
239     void GetAddr_(std::vector<CAddress> &vAddr);
240
241     // Mark an entry as currently-connected-to.
242     void Connected_(const CService &addr, int64 nTime);
243
244 public:
245
246     IMPLEMENT_SERIALIZE
247     (({
248         // serialized format:
249         // * version byte (currently 0)
250         // * nKey
251         // * nNew
252         // * nTried
253         // * number of "new" buckets
254         // * all nNew addrinfo's in vvNew
255         // * all nTried addrinfo's in vvTried
256         // * for each bucket:
257         //   * number of elements
258         //   * for each element: index
259         //
260         // Notice that vvTried, mapAddr and vVector are never encoded explicitly;
261         // they are instead reconstructed from the other information.
262         //
263         // vvNew is serialized, but only used if ADDRMAN_UNKOWN_BUCKET_COUNT didn't change,
264         // otherwise it is reconstructed as well.
265         //
266         // This format is more complex, but significantly smaller (at most 1.5 MiB), and supports
267         // changes to the ADDRMAN_ parameters without breaking the on-disk structure.
268         {
269             LOCK(cs);
270             unsigned char nVersion = 0;
271             READWRITE(nVersion);
272             READWRITE(nKey);
273             READWRITE(nNew);
274             READWRITE(nTried);
275
276             CAddrMan *am = const_cast<CAddrMan*>(this);
277             if (fWrite)
278             {
279                 int nUBuckets = ADDRMAN_NEW_BUCKET_COUNT;
280                 READWRITE(nUBuckets);
281                 std::map<int, int> mapUnkIds;
282                 int nIds = 0;
283                 for (std::map<int, CAddrInfo>::iterator it = am->mapInfo.begin(); it != am->mapInfo.end(); it++)
284                 {
285                     if (nIds == nNew) break; // this means nNew was wrong, oh ow
286                     mapUnkIds[(*it).first] = nIds;
287                     CAddrInfo &info = (*it).second;
288                     if (info.nRefCount)
289                     {
290                         READWRITE(info);
291                         nIds++;
292                     }
293                 }
294                 nIds = 0;
295                 for (std::map<int, CAddrInfo>::iterator it = am->mapInfo.begin(); it != am->mapInfo.end(); it++)
296                 {
297                     if (nIds == nTried) break; // this means nTried was wrong, oh ow
298                     CAddrInfo &info = (*it).second;
299                     if (info.fInTried)
300                     {
301                         READWRITE(info);
302                         nIds++;
303                     }
304                 }
305                 for (std::vector<std::set<int> >::iterator it = am->vvNew.begin(); it != am->vvNew.end(); it++)
306                 {
307                     const std::set<int> &vNew = (*it);
308                     int nSize = vNew.size();
309                     READWRITE(nSize);
310                     for (std::set<int>::iterator it2 = vNew.begin(); it2 != vNew.end(); it2++)
311                     {
312                         int nIndex = mapUnkIds[*it2];
313                         READWRITE(nIndex);
314                     }
315                 }
316             } else {
317                 int nUBuckets = 0;
318                 READWRITE(nUBuckets);
319                 am->nIdCount = 0;
320                 am->mapInfo.clear();
321                 am->mapAddr.clear();
322                 am->vRandom.clear();
323                 am->vvTried = std::vector<std::vector<int> >(ADDRMAN_TRIED_BUCKET_COUNT, std::vector<int>(0));
324                 am->vvNew = std::vector<std::set<int> >(ADDRMAN_NEW_BUCKET_COUNT, std::set<int>());
325                 for (int n = 0; n < am->nNew; n++)
326                 {
327                     CAddrInfo &info = am->mapInfo[n];
328                     READWRITE(info);
329                     am->mapAddr[info] = n;
330                     info.nRandomPos = vRandom.size();
331                     am->vRandom.push_back(n);
332                     if (nUBuckets != ADDRMAN_NEW_BUCKET_COUNT)
333                     {
334                         am->vvNew[info.GetNewBucket(am->nKey)].insert(n);
335                         info.nRefCount++;
336                     }
337                 }
338                 am->nIdCount = am->nNew;
339                 int nLost = 0;
340                 for (int n = 0; n < am->nTried; n++)
341                 {
342                     CAddrInfo info;
343                     READWRITE(info);
344                     std::vector<int> &vTried = am->vvTried[info.GetTriedBucket(am->nKey)];
345                     if (vTried.size() < ADDRMAN_TRIED_BUCKET_SIZE)
346                     {
347                         info.nRandomPos = vRandom.size();
348                         info.fInTried = true;
349                         am->vRandom.push_back(am->nIdCount);
350                         am->mapInfo[am->nIdCount] = info;
351                         am->mapAddr[info] = am->nIdCount;
352                         vTried.push_back(am->nIdCount);
353                         am->nIdCount++;
354                     } else {
355                         nLost++;
356                     }
357                 }
358                 am->nTried -= nLost;
359                 for (int b = 0; b < nUBuckets; b++)
360                 {
361                     std::set<int> &vNew = am->vvNew[b];
362                     int nSize = 0;
363                     READWRITE(nSize);
364                     for (int n = 0; n < nSize; n++)
365                     {
366                         int nIndex = 0;
367                         READWRITE(nIndex);
368                         CAddrInfo &info = am->mapInfo[nIndex];
369                         if (nUBuckets == ADDRMAN_NEW_BUCKET_COUNT && info.nRefCount < ADDRMAN_NEW_BUCKETS_PER_ADDRESS)
370                         {
371                             info.nRefCount++;
372                             vNew.insert(nIndex);
373                         }
374                     }
375                 }
376             }
377         }
378     });)
379
380     CAddrMan() : vRandom(0), vvTried(ADDRMAN_TRIED_BUCKET_COUNT, std::vector<int>(0)), vvNew(ADDRMAN_NEW_BUCKET_COUNT, std::set<int>())
381     {
382          nKey.resize(32);
383          RAND_bytes(&nKey[0], 32);
384
385          nIdCount = 0;
386          nTried = 0;
387          nNew = 0;
388     }
389
390     // Return the number of (unique) addresses in all tables.
391     int size()
392     {
393         return vRandom.size();
394     }
395
396     // Consistency check
397     void Check()
398     {
399 #ifdef DEBUG_ADDRMAN
400         {
401             LOCK(cs);
402             int err;
403             if ((err=Check_()))
404                 printf("ADDRMAN CONSISTENCY CHECK FAILED!!! err=%i\n", err);
405         }
406 #endif
407     }
408
409     // Add a single address.
410     bool Add(const CAddress &addr, const CNetAddr& source, int64 nTimePenalty = 0)
411     {
412         bool fRet = false;
413         {
414             LOCK(cs);
415             Check();
416             fRet |= Add_(addr, source, nTimePenalty);
417             Check();
418         }
419         if (fRet)
420             printf("Added %s from %s: %i tried, %i new\n", addr.ToStringIPPort().c_str(), source.ToString().c_str(), nTried, nNew);
421         return fRet;
422     }
423
424     // Add multiple addresses.
425     bool Add(const std::vector<CAddress> &vAddr, const CNetAddr& source, int64 nTimePenalty = 0)
426     {
427         int nAdd = 0;
428         {
429             LOCK(cs);
430             Check();
431             for (std::vector<CAddress>::const_iterator it = vAddr.begin(); it != vAddr.end(); it++)
432                 nAdd += Add_(*it, source, nTimePenalty) ? 1 : 0;
433             Check();
434         }
435         if (nAdd)
436             printf("Added %i addresses from %s: %i tried, %i new\n", nAdd, source.ToString().c_str(), nTried, nNew);
437         return nAdd > 0;
438     }
439
440     // Mark an entry as accessible.
441     void Good(const CService &addr, int64 nTime = GetAdjustedTime())
442     {
443         {
444             LOCK(cs);
445             Check();
446             Good_(addr, nTime);
447             Check();
448         }
449     }
450
451     // Mark an entry as connection attempted to.
452     void Attempt(const CService &addr, int64 nTime = GetAdjustedTime())
453     {
454         {
455             LOCK(cs);
456             Check();
457             Attempt_(addr, nTime);
458             Check();
459         }
460     }
461
462     // Choose an address to connect to.
463     // nUnkBias determines how much "new" entries are favored over "tried" ones (0-100).
464     CAddress Select(int nUnkBias = 50)
465     {
466         CAddress addrRet;
467         {
468             LOCK(cs);
469             Check();
470             addrRet = Select_(nUnkBias);
471             Check();
472         }
473         return addrRet;
474     }
475
476     // Return a bunch of addresses, selected at random.
477     std::vector<CAddress> GetAddr()
478     {
479         Check();
480         std::vector<CAddress> vAddr;
481         {
482             LOCK(cs);
483             GetAddr_(vAddr);
484         }
485         Check();
486         return vAddr;
487     }
488
489     // Mark an entry as currently-connected-to.
490     void Connected(const CService &addr, int64 nTime = GetAdjustedTime())
491     {
492         {
493             LOCK(cs);
494             Check();
495             Connected_(addr, nTime);
496             Check();
497         }
498     }
499 };
500
501 #endif