Update CMakeLists.txt - play with openssl
[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
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 successful connection by us
25     int64_t nLastSuccess;
26
27     // last try whatsoever by us:
28     // int64_t CAddress::nLastTry
29
30     // connection attempts since last successful 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), source(addrSource)
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_t nNow = GetAdjustedTime()) const;
88
89     // Calculate the relative chance this entry should be given when selecting nodes to connect to
90     double GetChance(int64_t 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 data structure.
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 nIds
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 nIds
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(unsigned int nRandomPos1, unsigned 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_t nTime);
222
223     // Add an entry to the "new" table.
224     bool Add_(const CAddress &addr, const CNetAddr& source, int64_t nTimePenalty);
225
226     // Mark an entry as attempted to connect.
227     void Attempt_(const CService &addr, int64_t 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     void GetOnlineAddr_(std::vector<CAddrInfo> &vAddr);
241
242     // Mark an entry as currently-connected-to.
243     void Connected_(const CService &addr, int64_t nTime);
244
245 public:
246
247     typedef std::map<int, int> MapUnkIds; // For MSVC macro
248     IMPLEMENT_SERIALIZE
249             (
250             LOCK(cs);
251                 unsigned char 
252                     nVersion = 0;
253
254                 READWRITE(nVersion);
255                 READWRITE(nKey);
256                 READWRITE(nNew);
257                 READWRITE(nTried);
258
259                 CAddrMan
260                     *am = const_cast<CAddrMan*>(this);
261
262                 if (fWrite)
263                 {
264                     int
265                         nUBuckets = ADDRMAN_NEW_BUCKET_COUNT;
266
267                     READWRITE(nUBuckets);
268                     MapUnkIds mapUnkIds;
269                     int
270                         nIds = 0;
271                     for (std::map<int, CAddrInfo>::iterator it = am->mapInfo.begin(); it != am->mapInfo.end(); it++)
272                     {
273                         if (nIds == nNew)
274                             break; // this means nNew was wrong, oh ow
275                         mapUnkIds[(*it).first] = nIds;
276
277                         CAddrInfo
278                             &info = (*it).second;
279
280                         if (info.nRefCount)
281                         {
282                             READWRITE(info);
283                             nIds++;
284                         }
285                     }
286                     nIds = 0;
287                     for (std::map<int, CAddrInfo>::iterator it = am->mapInfo.begin(); it != am->mapInfo.end(); it++)
288                     {
289                         if (nIds == nTried) 
290                             break; /* this means nTried was wrong, oh ow */
291
292                         CAddrInfo 
293                             &info = (*it).second;
294
295                         if (info.fInTried)
296                         {
297                             READWRITE(info);
298                             nIds++;
299                         }
300                     }
301                     for (
302                          std::vector<std::set<int> >::iterator it = am->vvNew.begin(); 
303                          it != am->vvNew.end(); 
304                          it++
305                         )
306                     {
307                         std::set<int> 
308                             &vNew = (*it);
309
310                         int 
311                             nSize = int( vNew.size() );
312
313                         READWRITE(nSize);
314                         for (std::set<int>::iterator it2 = vNew.begin(); it2 != vNew.end(); it2++)
315                         {
316                         int 
317                             nIndex = mapUnkIds[*it2];
318                         READWRITE(nIndex);
319                         }
320                     }
321                 } 
322                 else 
323                 {
324                     int 
325                         nUBuckets = 0;
326
327                     READWRITE(nUBuckets);
328                     am->nIdCount = 0;
329                     am->mapInfo.clear();
330                     am->mapAddr.clear();
331                     am->vRandom.clear();
332                     am->vvTried = 
333                         std::vector<std::vector<int> >(
334                                                         ADDRMAN_TRIED_BUCKET_COUNT, 
335                                                         std::vector<int>(0)
336                                                       );
337                     am->vvNew = 
338                         std::vector<std::set<int> >(
339                                                     ADDRMAN_NEW_BUCKET_COUNT, 
340                                                     std::set<int>()
341                                                    );
342                     for (int n = 0; n < am->nNew; n++)
343                     {
344                         CAddrInfo 
345                             &info = am->mapInfo[n];
346
347                         READWRITE(info);
348                         am->mapAddr[info] = n;
349                         info.nRandomPos = int( vRandom.size() );
350                         am->vRandom.push_back(n);
351                         if (nUBuckets != ADDRMAN_NEW_BUCKET_COUNT)
352                         {
353                             am->vvNew[info.GetNewBucket(am->nKey)].insert(n);
354                             info.nRefCount++;
355                         }
356                     }
357                     am->nIdCount = am->nNew;
358
359                     int 
360                         nLost = 0;
361
362                     for (int n = 0; n < am->nTried; n++)
363                     {
364                         CAddrInfo 
365                             info;
366
367                         READWRITE(info);
368
369                         std::vector<int> 
370                             &vTried = am->vvTried[info.GetTriedBucket(am->nKey)];
371
372                         if (vTried.size() < ADDRMAN_TRIED_BUCKET_SIZE)
373                         {
374                             info.nRandomPos = int( vRandom.size() );
375                             info.fInTried = true;
376                             am->vRandom.push_back(am->nIdCount);
377                             am->mapInfo[am->nIdCount] = info;
378                             am->mapAddr[info] = am->nIdCount;
379                             vTried.push_back(am->nIdCount);
380                             am->nIdCount++;
381                         } 
382                         else 
383                         {
384                             nLost++;
385                         }
386                     }
387                     am->nTried -= nLost;
388                     for (int b = 0; b < nUBuckets; b++)
389                     {
390                         std::set<int> 
391                             &vNew = am->vvNew[b];
392
393                         int 
394                             nSize = 0;
395
396                         READWRITE(nSize);
397                         for (int n = 0; n < nSize; n++)
398                         {
399                             int 
400                                 nIndex = 0;
401
402                             READWRITE(nIndex);
403
404                             CAddrInfo 
405                                 &info = am->mapInfo[nIndex];
406
407                             if (
408                                 (nUBuckets == ADDRMAN_NEW_BUCKET_COUNT) && 
409                                 (info.nRefCount < ADDRMAN_NEW_BUCKETS_PER_ADDRESS)
410                                )
411                             {
412                                 info.nRefCount++;
413                                 vNew.insert(nIndex);
414                             }
415                         }
416                     }
417                 }
418             )
419
420
421     CAddrMan();
422
423     // Return the number of (unique) addresses in all tables.
424     int size()
425     {
426         return (int) vRandom.size();
427     }
428
429     // Consistency check
430     void Check()
431     {
432 #ifdef DEBUG_ADDRMAN
433         {
434             LOCK(cs);
435             int err;
436             if ((err=Check_()))
437                 printf("ADDRMAN CONSISTENCY CHECK FAILED!!! err=%i\n", err);
438         }
439 #endif
440     }
441
442     // Add a single address.
443     bool Add(const CAddress &addr, const CNetAddr& source, int64_t nTimePenalty = 0)
444     {
445         bool fRet = false;
446         {
447             LOCK(cs);
448             Check();
449             fRet |= Add_(addr, source, nTimePenalty);
450             Check();
451         }
452         if (fRet)
453             printf("Added %s from %s: %i tried, %i new\n", addr.ToStringIPPort().c_str(), source.ToString().c_str(), nTried, nNew);
454         return fRet;
455     }
456
457     // Add multiple addresses.
458     bool Add(const std::vector<CAddress> &vAddr, const CNetAddr& source, int64_t nTimePenalty = 0)
459     {
460         int nAdd = 0;
461         {
462             LOCK(cs);
463             Check();
464             for (std::vector<CAddress>::const_iterator it = vAddr.begin(); it != vAddr.end(); it++)
465                 nAdd += Add_(*it, source, nTimePenalty) ? 1 : 0;
466             Check();
467         }
468         if (nAdd)
469             printf("Added %i addresses from %s: %i tried, %i new\n", nAdd, source.ToString().c_str(), nTried, nNew);
470         return nAdd > 0;
471     }
472
473     // Mark an entry as accessible.
474     void Good(const CService &addr, int64_t nTime = GetAdjustedTime())
475     {
476         {
477             LOCK(cs);
478             Check();
479             Good_(addr, nTime);
480             Check();
481         }
482     }
483
484     // Mark an entry as connection attempted to.
485     void Attempt(const CService &addr, int64_t nTime = GetAdjustedTime())
486     {
487         {
488             LOCK(cs);
489             Check();
490             Attempt_(addr, nTime);
491             Check();
492         }
493     }
494
495     // Choose an address to connect to.
496     // nUnkBias determines how much "new" entries are favored over "tried" ones (0-100).
497     CAddress Select(int nUnkBias = 50)
498     {
499         CAddress addrRet;
500         {
501             LOCK(cs);
502             Check();
503             addrRet = Select_(nUnkBias);
504             Check();
505         }
506         return addrRet;
507     }
508
509     // Return a bunch of addresses, selected at random.
510     std::vector<CAddress> GetAddr()
511     {
512         Check();
513         std::vector<CAddress> vAddr;
514         {
515             LOCK(cs);
516             GetAddr_(vAddr);
517         }
518         Check();
519         return vAddr;
520     }
521
522     std::vector<CAddrInfo> GetOnlineAddr()
523     {
524         Check();
525         std::vector<CAddrInfo> vAddr;
526         {
527             LOCK(cs);
528             GetOnlineAddr_(vAddr);
529         }
530         Check();
531         return vAddr;
532     }
533
534     // Mark an entry as currently-connected-to.
535     void Connected(const CService &addr, int64_t nTime = GetAdjustedTime())
536     {
537         {
538             LOCK(cs);
539             Check();
540             Connected_(addr, nTime);
541             Check();
542         }
543     }
544 };
545
546 #endif