Remove wxWidgets .exe and locales during setup
[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 #include "util.h"
10
11
12 #include <map>
13 #include <vector>
14
15 #include <openssl/rand.h>
16
17
18 // Extended statistics about a CAddress
19 class CAddrInfo : public CAddress
20 {
21 private:
22     // where knowledge about this address first came from
23     CNetAddr source;
24
25     // last succesfull connection by us
26     int64 nLastSuccess;
27
28     // last try whatsoever by us:
29     // int64 CAddress::nLastTry
30
31     // connection attempts since last succesful attempt
32     int nAttempts;
33
34     // reference count in new sets (memory only)
35     int nRefCount;
36
37     // in tried set? (memory only)
38     bool fInTried;
39
40     // position in vRandom
41     int nRandomPos;
42
43     friend class CAddrMan;
44
45 public:
46
47     IMPLEMENT_SERIALIZE(
48         CAddress* pthis = (CAddress*)(this);
49         READWRITE(*pthis);
50         READWRITE(source);
51         READWRITE(nLastSuccess);
52         READWRITE(nAttempts);
53     )
54
55     void Init()
56     {
57         nLastSuccess = 0;
58         nLastTry = 0;
59         nAttempts = 0;
60         nRefCount = 0;
61         fInTried = false;
62         nRandomPos = -1;
63     }
64
65     CAddrInfo(const CAddress &addrIn, const CNetAddr &addrSource) : CAddress(addrIn)
66     {
67         Init();
68     }
69
70     CAddrInfo() : CAddress(), source()
71     {
72         Init();
73     }
74
75     // Calculate in which "tried" bucket this entry belongs
76     int GetTriedBucket(const std::vector<unsigned char> &nKey) const;
77
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;
80
81     // Calculate in which "new" bucket this entry belongs, using its default source
82     int GetNewBucket(const std::vector<unsigned char> &nKey) const
83     {
84         return GetNewBucket(nKey, source);
85     }
86
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;
89
90     // Calculate the relative chance this entry should be given when selecting nodes to connect to
91     double GetChance(int64 nNow = GetAdjustedTime()) const;
92
93 };
94
95 // Stochastic address manager
96 //
97 // Design goals:
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.
101 //
102 // To that end:
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.
120
121 // total number of buckets for tried addresses
122 #define ADDRMAN_TRIED_BUCKET_COUNT 64
123
124 // maximum allowed number of entries in buckets for tried addresses
125 #define ADDRMAN_TRIED_BUCKET_SIZE 64
126
127 // total number of buckets for new addresses
128 #define ADDRMAN_NEW_BUCKET_COUNT 256
129
130 // maximum allowed number of entries in buckets for new addresses
131 #define ADDRMAN_NEW_BUCKET_SIZE 64
132
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
135
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
138
139 // in how many buckets for entries with new addresses a single address may occur
140 #define ADDRMAN_NEW_BUCKETS_PER_ADDRESS 4
141
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
144
145 // how old addresses can maximally be
146 #define ADDRMAN_HORIZON_DAYS 30
147
148 // after how many failed attempts we give up on a new node
149 #define ADDRMAN_RETRIES 3
150
151 // how many successive failures are allowed ...
152 #define ADDRMAN_MAX_FAILURES 10
153
154 // ... in at least this many days
155 #define ADDRMAN_MIN_FAIL_DAYS 7
156
157 // the maximum percentage of nodes to return in a getaddr call
158 #define ADDRMAN_GETADDR_MAX_PCT 23
159
160 // the maximum number of nodes to return in a getaddr call
161 #define ADDRMAN_GETADDR_MAX 2500
162
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         CRITICAL_BLOCK(cs)
269         {
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         CRITICAL_BLOCK(cs)
401         {
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         CRITICAL_BLOCK(cs)
414         {
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         CRITICAL_BLOCK(cs)
429         {
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         CRITICAL_BLOCK(cs)
444         {
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         CRITICAL_BLOCK(cs)
455         {
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         CRITICAL_BLOCK(cs)
468         {
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         CRITICAL_BLOCK(cs)
482             GetAddr_(vAddr);
483         Check();
484         return vAddr;
485     }
486
487     // Mark an entry as currently-connected-to.
488     void Connected(const CService &addr, int64 nTime = GetAdjustedTime())
489     {
490         CRITICAL_BLOCK(cs)
491         {
492             Check();
493             Connected_(addr, nTime);
494             Check();
495         }
496     }
497 };
498
499 #endif