Remove boost namespace from init.cpp
[novacoin.git] / src / addrman.h
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
6
7 #include "netbase.h"
8 #include "protocol.h"
9 #include "timedata.h"
10 #include "util.h"
11 #include "sync.h"
12
13 #include <map>
14 #include <vector>
15
16 #include <openssl/rand.h>
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 successful connection by us
26     int64_t nLastSuccess;
27
28     // last try whatsoever by us:
29     // int64_t CAddress::nLastTry
30
31     // connection attempts since last successful 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     CAddrInfo(const CAddress &addrIn, const CNetAddr &addrSource);
58     CAddrInfo();
59
60     // Calculate in which "tried" bucket this entry belongs
61     int GetTriedBucket(const std::vector<unsigned char> &nKey) const;
62
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;
65
66     // Calculate in which "new" bucket this entry belongs, using its default source
67     int GetNewBucket(const std::vector<unsigned char> &nKey) const;
68
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;
71
72     // Calculate the relative chance this entry should be given when selecting nodes to connect to
73     double GetChance(int64_t nNow = GetAdjustedTime()) const;
74
75 };
76
77 // Stochastic address manager
78 //
79 // Design goals:
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.
83 //
84 // To that end:
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.
101
102 // total number of buckets for tried addresses
103 #define ADDRMAN_TRIED_BUCKET_COUNT 64
104
105 // maximum allowed number of entries in buckets for tried addresses
106 #define ADDRMAN_TRIED_BUCKET_SIZE 64
107
108 // total number of buckets for new addresses
109 #define ADDRMAN_NEW_BUCKET_COUNT 256
110
111 // maximum allowed number of entries in buckets for new addresses
112 #define ADDRMAN_NEW_BUCKET_SIZE 64
113
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
116
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
119
120 // in how many buckets for entries with new addresses a single address may occur
121 #define ADDRMAN_NEW_BUCKETS_PER_ADDRESS 4
122
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
125
126 // how old addresses can maximally be
127 #define ADDRMAN_HORIZON_DAYS 30
128
129 // after how many failed attempts we give up on a new node
130 #define ADDRMAN_RETRIES 3
131
132 // how many successive failures are allowed ...
133 #define ADDRMAN_MAX_FAILURES 10
134
135 // ... in at least this many days
136 #define ADDRMAN_MIN_FAIL_DAYS 7
137
138 // the maximum percentage of nodes to return in a getaddr call
139 #define ADDRMAN_GETADDR_MAX_PCT 23
140
141 // the maximum number of nodes to return in a getaddr call
142 #define ADDRMAN_GETADDR_MAX 2500
143
144 // Stochastical (IP) address manager
145 class CAddrMan
146 {
147 private:
148     // critical section to protect the inner data structures
149     mutable CCriticalSection cs;
150
151     // secret key to randomize bucket select with
152     std::vector<unsigned char> nKey;
153
154     // last used nId
155     int nIdCount;
156
157     // table with information about all nIds
158     std::map<int, CAddrInfo> mapInfo;
159
160     // find an nId based on its network address
161     std::map<CNetAddr, int> mapAddr;
162
163     // randomly-ordered vector of all nIds
164     std::vector<int> vRandom;
165
166     // number of "tried" entries
167     int nTried;
168
169     // list of "tried" buckets
170     std::vector<std::vector<int> > vvTried;
171
172     // number of (unique) "new" entries
173     int nNew;
174
175     // list of "new" buckets
176     std::vector<std::set<int> > vvNew;
177
178 protected:
179
180     // Find an entry.
181     CAddrInfo* Find(const CNetAddr& addr, int *pnId = NULL);
182
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);
186
187     // Swap two elements in vRandom.
188     void SwapRandom(unsigned int nRandomPos1, unsigned int nRandomPos2);
189
190     // Return position in given bucket to replace.
191     int SelectTried(int nKBucket);
192
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);
197
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);
201
202     // Mark an entry "good", possibly moving it from "new" to "tried".
203     void Good_(const CService &addr, int64_t nTime);
204
205     // Add an entry to the "new" table.
206     bool Add_(const CAddress &addr, const CNetAddr& source, int64_t nTimePenalty);
207
208     // Mark an entry as attempted to connect.
209     void Attempt_(const CService &addr, int64_t nTime);
210
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);
214
215     // Select several addresses at once.
216     void GetAddr_(std::vector<CAddress> &vAddr);
217     void GetOnlineAddr_(std::vector<CAddrInfo> &vAddr);
218
219     // Mark an entry as currently-connected-to.
220     void Connected_(const CService &addr, int64_t nTime);
221
222 public:
223
224     typedef std::map<int, int> MapUnkIds; // For MSVC macro
225     IMPLEMENT_SERIALIZE
226             (
227             LOCK(cs);
228                 unsigned char 
229                     nVersion = 0;
230
231                 READWRITE(nVersion);
232                 READWRITE(nKey);
233                 READWRITE(nNew);
234                 READWRITE(nTried);
235
236                 CAddrMan
237                     *am = const_cast<CAddrMan*>(this);
238
239                 if (fWrite)
240                 {
241                     int
242                         nUBuckets = ADDRMAN_NEW_BUCKET_COUNT;
243
244                     READWRITE(nUBuckets);
245                     MapUnkIds mapUnkIds;
246                     int
247                         nIds = 0;
248                     for (auto it = am->mapInfo.begin(); it != am->mapInfo.end(); it++)
249                     {
250                         if (nIds == nNew)
251                             break; // this means nNew was wrong, oh ow
252                         mapUnkIds[(*it).first] = nIds;
253
254                         CAddrInfo
255                             &info = (*it).second;
256
257                         if (info.nRefCount)
258                         {
259                             READWRITE(info);
260                             nIds++;
261                         }
262                     }
263                     nIds = 0;
264                     for (auto it = am->mapInfo.begin(); it != am->mapInfo.end(); it++)
265                     {
266                         if (nIds == nTried) 
267                             break; /* this means nTried was wrong, oh ow */
268
269                         CAddrInfo 
270                             &info = (*it).second;
271
272                         if (info.fInTried)
273                         {
274                             READWRITE(info);
275                             nIds++;
276                         }
277                     }
278                     for (
279                          auto it = am->vvNew.begin(); 
280                          it != am->vvNew.end(); 
281                          it++
282                         )
283                     {
284                         std::set<int> 
285                             &vNew = (*it);
286
287                         int 
288                             nSize = int( vNew.size() );
289
290                         READWRITE(nSize);
291                         for (auto it2 = vNew.begin(); it2 != vNew.end(); it2++)
292                         {
293                         int 
294                             nIndex = mapUnkIds[*it2];
295                         READWRITE(nIndex);
296                         }
297                     }
298                 } 
299                 else 
300                 {
301                     int 
302                         nUBuckets = 0;
303
304                     READWRITE(nUBuckets);
305                     am->nIdCount = 0;
306                     am->mapInfo.clear();
307                     am->mapAddr.clear();
308                     am->vRandom.clear();
309                     am->vvTried = 
310                         std::vector<std::vector<int> >(
311                                                         ADDRMAN_TRIED_BUCKET_COUNT, 
312                                                         std::vector<int>(0)
313                                                       );
314                     am->vvNew = 
315                         std::vector<std::set<int> >(
316                                                     ADDRMAN_NEW_BUCKET_COUNT, 
317                                                     std::set<int>()
318                                                    );
319                     for (int n = 0; n < am->nNew; n++)
320                     {
321                         CAddrInfo 
322                             &info = am->mapInfo[n];
323
324                         READWRITE(info);
325                         am->mapAddr[info] = n;
326                         info.nRandomPos = int( vRandom.size() );
327                         am->vRandom.push_back(n);
328                         if (nUBuckets != ADDRMAN_NEW_BUCKET_COUNT)
329                         {
330                             am->vvNew[info.GetNewBucket(am->nKey)].insert(n);
331                             info.nRefCount++;
332                         }
333                     }
334                     am->nIdCount = am->nNew;
335
336                     int 
337                         nLost = 0;
338
339                     for (int n = 0; n < am->nTried; n++)
340                     {
341                         CAddrInfo 
342                             info;
343
344                         READWRITE(info);
345
346                         std::vector<int> 
347                             &vTried = am->vvTried[info.GetTriedBucket(am->nKey)];
348
349                         if (vTried.size() < ADDRMAN_TRIED_BUCKET_SIZE)
350                         {
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);
357                             am->nIdCount++;
358                         } 
359                         else 
360                         {
361                             nLost++;
362                         }
363                     }
364                     am->nTried -= nLost;
365                     for (int b = 0; b < nUBuckets; b++)
366                     {
367                         std::set<int> 
368                             &vNew = am->vvNew[b];
369
370                         int 
371                             nSize = 0;
372
373                         READWRITE(nSize);
374                         for (int n = 0; n < nSize; n++)
375                         {
376                             int 
377                                 nIndex = 0;
378
379                             READWRITE(nIndex);
380
381                             CAddrInfo 
382                                 &info = am->mapInfo[nIndex];
383
384                             if (
385                                 (nUBuckets == ADDRMAN_NEW_BUCKET_COUNT) && 
386                                 (info.nRefCount < ADDRMAN_NEW_BUCKETS_PER_ADDRESS)
387                                )
388                             {
389                                 info.nRefCount++;
390                                 vNew.insert(nIndex);
391                             }
392                         }
393                     }
394                 }
395             )
396
397     CAddrMan();
398
399     // Return the number of (unique) addresses in all tables.
400     int size();
401
402     // Add a single address.
403     bool Add(const CAddress &addr, const CNetAddr& source, int64_t nTimePenalty = 0);
404
405     // Add multiple addresses.
406     bool Add(const std::vector<CAddress> &vAddr, const CNetAddr& source, int64_t nTimePenalty = 0);
407
408     // Mark an entry as accessible.
409     void Good(const CService &addr, int64_t nTime = GetAdjustedTime());
410
411     // Mark an entry as connection attempted to.
412     void Attempt(const CService &addr, int64_t nTime = GetAdjustedTime());
413
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);
417
418     // Return a bunch of addresses, selected at random.
419     std::vector<CAddress> GetAddr();
420
421     std::vector<CAddrInfo> GetOnlineAddr();
422
423     // Mark an entry as currently-connected-to.
424     void Connected(const CService &addr, int64_t nTime = GetAdjustedTime());
425 };
426
427 #endif