5f5bf7999866ad60fe62e9a0bc51e26c7419dda4
[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 "util.h"
10 #include "sync.h"
11
12
13 #include <map>
14 #include <vector>
15
16 #include <openssl/rand.h>
17
18
19 /** Extended statistics about a CAddress */
20 class CAddrInfo : public CAddress
21 {
22 private:
23     // where knowledge about this address first came from
24     CNetAddr source;
25
26     // last successful connection by us
27     int64_t nLastSuccess;
28
29     // last try whatsoever by us:
30     // int64_t CAddress::nLastTry
31
32     // connection attempts since last successful attempt
33     int nAttempts;
34
35     // reference count in new sets (memory only)
36     int nRefCount;
37
38     // in tried set? (memory only)
39     bool fInTried;
40
41     // position in vRandom
42     int nRandomPos;
43
44     friend class CAddrMan;
45
46 public:
47
48     IMPLEMENT_SERIALIZE(
49         CAddress* pthis = (CAddress*)(this);
50         READWRITE(*pthis);
51         READWRITE(source);
52         READWRITE(nLastSuccess);
53         READWRITE(nAttempts);
54     )
55
56     void Init()
57     {
58         nLastSuccess = 0;
59         nLastTry = 0;
60         nAttempts = 0;
61         nRefCount = 0;
62         fInTried = false;
63         nRandomPos = -1;
64     }
65
66     CAddrInfo(const CAddress &addrIn, const CNetAddr &addrSource) : CAddress(addrIn), source(addrSource)
67     {
68         Init();
69     }
70
71     CAddrInfo() : CAddress(), source()
72     {
73         Init();
74     }
75
76     // Calculate in which "tried" bucket this entry belongs
77     int GetTriedBucket(const std::vector<unsigned char> &nKey) const;
78
79     // Calculate in which "new" bucket this entry belongs, given a certain source
80     int GetNewBucket(const std::vector<unsigned char> &nKey, const CNetAddr& src) const;
81
82     // Calculate in which "new" bucket this entry belongs, using its default source
83     int GetNewBucket(const std::vector<unsigned char> &nKey) const
84     {
85         return GetNewBucket(nKey, source);
86     }
87
88     // Determine whether the statistics about this entry are bad enough so that it can just be deleted
89     bool IsTerrible(int64_t nNow = GetAdjustedTime()) const;
90
91     // Calculate the relative chance this entry should be given when selecting nodes to connect to
92     double GetChance(int64_t nNow = GetAdjustedTime()) const;
93
94 };
95
96 // Stochastic address manager
97 //
98 // Design goals:
99 //  * Only keep a limited number of addresses around, so that addr.dat and memory requirements do not grow without bound.
100 //  * Keep the address tables in-memory, and asynchronously dump the entire to able in addr.dat.
101 //  * Make sure no (localized) attacker can fill the entire table with his nodes/addresses.
102 //
103 // To that end:
104 //  * Addresses are organized into buckets.
105 //    * Address that have not yet been tried go into 256 "new" buckets.
106 //      * Based on the address range (/16 for IPv4) of source of the information, 32 buckets are selected at random
107 //      * The actual bucket is chosen from one of these, based on the range the address itself is located.
108 //      * One single address can occur in up to 4 different buckets, to increase selection chances for addresses that
109 //        are seen frequently. The chance for increasing this multiplicity decreases exponentially.
110 //      * When adding a new address to a full bucket, a randomly chosen entry (with a bias favoring less recently seen
111 //        ones) is removed from it first.
112 //    * Addresses of nodes that are known to be accessible go into 64 "tried" buckets.
113 //      * Each address range selects at random 4 of these buckets.
114 //      * The actual bucket is chosen from one of these, based on the full address.
115 //      * When adding a new good address to a full bucket, a randomly chosen entry (with a bias favoring less recently
116 //        tried ones) is evicted from it, back to the "new" buckets.
117 //    * Bucket selection is based on cryptographic hashing, using a randomly-generated 256-bit key, which should not
118 //      be observable by adversaries.
119 //    * Several indexes are kept for high performance. Defining DEBUG_ADDRMAN will introduce frequent (and expensive)
120 //      consistency checks for the entire data structure.
121
122 // total number of buckets for tried addresses
123 #define ADDRMAN_TRIED_BUCKET_COUNT 64
124
125 // maximum allowed number of entries in buckets for tried addresses
126 #define ADDRMAN_TRIED_BUCKET_SIZE 64
127
128 // total number of buckets for new addresses
129 #define ADDRMAN_NEW_BUCKET_COUNT 256
130
131 // maximum allowed number of entries in buckets for new addresses
132 #define ADDRMAN_NEW_BUCKET_SIZE 64
133
134 // over how many buckets entries with tried addresses from a single group (/16 for IPv4) are spread
135 #define ADDRMAN_TRIED_BUCKETS_PER_GROUP 4
136
137 // over how many buckets entries with new addresses originating from a single group are spread
138 #define ADDRMAN_NEW_BUCKETS_PER_SOURCE_GROUP 32
139
140 // in how many buckets for entries with new addresses a single address may occur
141 #define ADDRMAN_NEW_BUCKETS_PER_ADDRESS 4
142
143 // how many entries in a bucket with tried addresses are inspected, when selecting one to replace
144 #define ADDRMAN_TRIED_ENTRIES_INSPECT_ON_EVICT 4
145
146 // how old addresses can maximally be
147 #define ADDRMAN_HORIZON_DAYS 30
148
149 // after how many failed attempts we give up on a new node
150 #define ADDRMAN_RETRIES 3
151
152 // how many successive failures are allowed ...
153 #define ADDRMAN_MAX_FAILURES 10
154
155 // ... in at least this many days
156 #define ADDRMAN_MIN_FAIL_DAYS 7
157
158 // the maximum percentage of nodes to return in a getaddr call
159 #define ADDRMAN_GETADDR_MAX_PCT 23
160
161 // the maximum number of nodes to return in a getaddr call
162 #define ADDRMAN_GETADDR_MAX 2500
163
164 /** Stochastical (IP) address manager */
165 class CAddrMan
166 {
167 private:
168     // critical section to protect the inner data structures
169     mutable CCriticalSection cs;
170
171     // secret key to randomize bucket select with
172     std::vector<unsigned char> nKey;
173
174     // last used nId
175     int nIdCount;
176
177     // table with information about all nIds
178     std::map<int, CAddrInfo> mapInfo;
179
180     // find an nId based on its network address
181     std::map<CNetAddr, int> mapAddr;
182
183     // randomly-ordered vector of all nIds
184     std::vector<int> vRandom;
185
186     // number of "tried" entries
187     int nTried;
188
189     // list of "tried" buckets
190     std::vector<std::vector<int> > vvTried;
191
192     // number of (unique) "new" entries
193     int nNew;
194
195     // list of "new" buckets
196     std::vector<std::set<int> > vvNew;
197
198 protected:
199
200     // Find an entry.
201     CAddrInfo* Find(const CNetAddr& addr, int *pnId = NULL);
202
203     // find an entry, creating it if necessary.
204     // nTime and nServices of found node is updated, if necessary.
205     CAddrInfo* Create(const CAddress &addr, const CNetAddr &addrSource, int *pnId = NULL);
206
207     // Swap two elements in vRandom.
208     void SwapRandom(unsigned int nRandomPos1, unsigned int nRandomPos2);
209
210     // Return position in given bucket to replace.
211     int SelectTried(int nKBucket);
212
213     // Remove an element from a "new" bucket.
214     // This is the only place where actual deletes occur.
215     // They are never deleted while in the "tried" table, only possibly evicted back to the "new" table.
216     int ShrinkNew(int nUBucket);
217
218     // Move an entry from the "new" table(s) to the "tried" table
219     // @pre vvUnkown[nOrigin].count(nId) != 0
220     void MakeTried(CAddrInfo& info, int nId, int nOrigin);
221
222     // Mark an entry "good", possibly moving it from "new" to "tried".
223     void Good_(const CService &addr, int64_t nTime);
224
225     // Add an entry to the "new" table.
226     bool Add_(const CAddress &addr, const CNetAddr& source, int64_t nTimePenalty);
227
228     // Mark an entry as attempted to connect.
229     void Attempt_(const CService &addr, int64_t nTime);
230
231     // Select an address to connect to.
232     // nUnkBias determines how much to favor new addresses over tried ones (min=0, max=100)
233     CAddress Select_(int nUnkBias);
234
235 #ifdef DEBUG_ADDRMAN
236     // Perform consistency check. Returns an error code or zero.
237     int Check_();
238 #endif
239
240     // Select several addresses at once.
241     void GetAddr_(std::vector<CAddress> &vAddr);
242
243     // Mark an entry as currently-connected-to.
244     void Connected_(const CService &addr, int64_t nTime);
245
246 public:
247
248 #ifndef _MSC_VER 
249     IMPLEMENT_SERIALIZE
250     (({
251         // serialized format:
252         // * version byte (currently 0)
253         // * nKey
254         // * nNew
255         // * nTried
256         // * number of "new" buckets
257         // * all nNew addrinfos in vvNew
258         // * all nTried addrinfos in vvTried
259         // * for each bucket:
260         //   * number of elements
261         //   * for each element: index
262         //
263         // Notice that vvTried, mapAddr and vVector are never encoded explicitly;
264         // they are instead reconstructed from the other information.
265         //
266         // vvNew is serialized, but only used if ADDRMAN_UNKOWN_BUCKET_COUNT didn't change,
267         // otherwise it is reconstructed as well.
268         //
269         // This format is more complex, but significantly smaller (at most 1.5 MiB), and supports
270         // changes to the ADDRMAN_ parameters without breaking the on-disk structure.
271         {
272             LOCK(cs);
273             unsigned char nVersion = 0;
274             READWRITE(nVersion);
275             READWRITE(nKey);
276             READWRITE(nNew);
277             READWRITE(nTried);
278
279             CAddrMan *am = const_cast<CAddrMan*>(this);
280             if (fWrite)
281             {
282                 int nUBuckets = ADDRMAN_NEW_BUCKET_COUNT;
283                 READWRITE(nUBuckets);
284                 std::map<int, int> mapUnkIds;
285                 int nIds = 0;
286                 for (std::map<int, CAddrInfo>::iterator it = am->mapInfo.begin(); it != am->mapInfo.end(); it++)
287                 {
288                     if (nIds == nNew) break; // this means nNew was wrong, oh ow
289                     mapUnkIds[(*it).first] = nIds;
290                     CAddrInfo &info = (*it).second;
291                     if (info.nRefCount)
292                     {
293                         READWRITE(info);
294                         nIds++;
295                     }
296                 }
297                 nIds = 0;
298                 for (std::map<int, CAddrInfo>::iterator it = am->mapInfo.begin(); it != am->mapInfo.end(); it++)
299                 {
300                     if (nIds == nTried) break; // this means nTried was wrong, oh ow
301                     CAddrInfo &info = (*it).second;
302                     if (info.fInTried)
303                     {
304                         READWRITE(info);
305                         nIds++;
306                     }
307                 }
308                 for (std::vector<std::set<int> >::iterator it = am->vvNew.begin(); it != am->vvNew.end(); it++)
309                 {
310                     const std::set<int> &vNew = (*it);
311                     int nSize = vNew.size();
312                     READWRITE(nSize);
313                     for (std::set<int>::iterator it2 = vNew.begin(); it2 != vNew.end(); it2++)
314                     {
315                         int nIndex = mapUnkIds[*it2];
316                         READWRITE(nIndex);
317                     }
318                 }
319             } else {
320                 int nUBuckets = 0;
321                 READWRITE(nUBuckets);
322                 am->nIdCount = 0;
323                 am->mapInfo.clear();
324                 am->mapAddr.clear();
325                 am->vRandom.clear();
326                 am->vvTried = std::vector<std::vector<int> >(ADDRMAN_TRIED_BUCKET_COUNT, std::vector<int>(0));
327                 am->vvNew = std::vector<std::set<int> >(ADDRMAN_NEW_BUCKET_COUNT, std::set<int>());
328                 for (int n = 0; n < am->nNew; n++)
329                 {
330                     CAddrInfo &info = am->mapInfo[n];
331                     READWRITE(info);
332                     am->mapAddr[info] = n;
333                     info.nRandomPos = vRandom.size();
334                     am->vRandom.push_back(n);
335                     if (nUBuckets != ADDRMAN_NEW_BUCKET_COUNT)
336                     {
337                         am->vvNew[info.GetNewBucket(am->nKey)].insert(n);
338                         info.nRefCount++;
339                     }
340                 }
341                 am->nIdCount = am->nNew;
342                 int nLost = 0;
343                 for (int n = 0; n < am->nTried; n++)
344                 {
345                     CAddrInfo info;
346                     READWRITE(info);
347                     std::vector<int> &vTried = am->vvTried[info.GetTriedBucket(am->nKey)];
348                     if (vTried.size() < ADDRMAN_TRIED_BUCKET_SIZE)
349                     {
350                         info.nRandomPos = vRandom.size();
351                         info.fInTried = true;
352                         am->vRandom.push_back(am->nIdCount);
353                         am->mapInfo[am->nIdCount] = info;
354                         am->mapAddr[info] = am->nIdCount;
355                         vTried.push_back(am->nIdCount);
356                         am->nIdCount++;
357                     } else {
358                         nLost++;
359                     }
360                 }
361                 am->nTried -= nLost;
362                 for (int b = 0; b < nUBuckets; b++)
363                 {
364                     std::set<int> &vNew = am->vvNew[b];
365                     int nSize = 0;
366                     READWRITE(nSize);
367                     for (int n = 0; n < nSize; n++)
368                     {
369                         int nIndex = 0;
370                         READWRITE(nIndex);
371                         CAddrInfo &info = am->mapInfo[nIndex];
372                         if (nUBuckets == ADDRMAN_NEW_BUCKET_COUNT && info.nRefCount < ADDRMAN_NEW_BUCKETS_PER_ADDRESS)
373                         {
374                             info.nRefCount++;
375                             vNew.insert(nIndex);
376                         }
377                     }
378                 }
379             }
380         }
381     });)
382 #else
383     IMPLEMENT_SERIALIZE
384             (
385             LOCK(cs);
386                 unsigned char 
387                     nVersion = 0;
388
389                 READWRITE(nVersion);
390                 READWRITE(nKey);
391                 READWRITE(nNew);
392                 READWRITE(nTried);
393
394                 CAddrMan 
395                     *am = const_cast<CAddrMan*>(this);
396
397                 if (fWrite)
398                 {
399                     int 
400                         nUBuckets = ADDRMAN_NEW_BUCKET_COUNT;
401
402                     READWRITE(nUBuckets);
403 /************
404                     std::map<int, int>  
405                         mapUnkIds;
406 ************/  
407                     int 
408                         nIds = 0;
409                     for (std::map<int, CAddrInfo>::iterator it = am->mapInfo.begin(); it != am->mapInfo.end(); it++)
410                     {
411                         if (nIds == nNew) 
412                             break; // this means nNew was wrong, oh ow
413                         mapUnkIds[(*it).first] = nIds;
414
415                         CAddrInfo 
416                             &info = (*it).second;
417
418                         if (info.nRefCount)
419                         {
420                             READWRITE(info);
421                             nIds++;
422                         }
423                     }
424                     nIds = 0;
425                     for (std::map<int, CAddrInfo>::iterator it = am->mapInfo.begin(); it != am->mapInfo.end(); it++)
426                     {
427                         if (nIds == nTried) 
428                             break; /* this means nTried was wrong, oh ow */
429
430                         CAddrInfo 
431                             &info = (*it).second;
432
433                         if (info.fInTried)
434                         {
435                             READWRITE(info);
436                             nIds++;
437                         }
438                     }
439                     for (
440                          std::vector<std::set<int> >::iterator it = am->vvNew.begin(); 
441                          it != am->vvNew.end(); 
442                          it++
443                         )
444                     {
445                         std::set<int> 
446                             &vNew = (*it);
447
448                         int 
449                             nSize = int( vNew.size() );
450
451                         READWRITE(nSize);
452                         for (std::set<int>::iterator it2 = vNew.begin(); it2 != vNew.end(); it2++)
453                         {
454                         int 
455                             nIndex = mapUnkIds[*it2];
456                         READWRITE(nIndex);
457                         }
458                     }
459                 } 
460                 else 
461                 {
462                     int 
463                         nUBuckets = 0;
464
465                     READWRITE(nUBuckets);
466                     am->nIdCount = 0;
467                     am->mapInfo.clear();
468                     am->mapAddr.clear();
469                     am->vRandom.clear();
470                     am->vvTried = 
471                         std::vector<std::vector<int> >(
472                                                         ADDRMAN_TRIED_BUCKET_COUNT, 
473                                                         std::vector<int>(0)
474                                                       );
475                     am->vvNew = 
476                         std::vector<std::set<int> >(
477                                                     ADDRMAN_NEW_BUCKET_COUNT, 
478                                                     std::set<int>()
479                                                    );
480                     for (int n = 0; n < am->nNew; n++)
481                     {
482                         CAddrInfo 
483                             &info = am->mapInfo[n];
484
485                         READWRITE(info);
486                         am->mapAddr[info] = n;
487                         info.nRandomPos = int( vRandom.size() );
488                         am->vRandom.push_back(n);
489                         if (nUBuckets != ADDRMAN_NEW_BUCKET_COUNT)
490                         {
491                             am->vvNew[info.GetNewBucket(am->nKey)].insert(n);
492                             info.nRefCount++;
493                         }
494                     }
495                     am->nIdCount = am->nNew;
496
497                     int 
498                         nLost = 0;
499
500                     for (int n = 0; n < am->nTried; n++)
501                     {
502                         CAddrInfo 
503                             info;
504
505                         READWRITE(info);
506
507                         std::vector<int> 
508                             &vTried = am->vvTried[info.GetTriedBucket(am->nKey)];
509
510                         if (vTried.size() < ADDRMAN_TRIED_BUCKET_SIZE)
511                         {
512                             info.nRandomPos = int( vRandom.size() );
513                             info.fInTried = true;
514                             am->vRandom.push_back(am->nIdCount);
515                             am->mapInfo[am->nIdCount] = info;
516                             am->mapAddr[info] = am->nIdCount;
517                             vTried.push_back(am->nIdCount);
518                             am->nIdCount++;
519                         } 
520                         else 
521                         {
522                             nLost++;
523                         }
524                     }
525                     am->nTried -= nLost;
526                     for (int b = 0; b < nUBuckets; b++)
527                     {
528                         std::set<int> 
529                             &vNew = am->vvNew[b];
530
531                         int 
532                             nSize = 0;
533
534                         READWRITE(nSize);
535                         for (int n = 0; n < nSize; n++)
536                         {
537                             int 
538                                 nIndex = 0;
539
540                             READWRITE(nIndex);
541
542                             CAddrInfo 
543                                 &info = am->mapInfo[nIndex];
544
545                             if (
546                                 (nUBuckets == ADDRMAN_NEW_BUCKET_COUNT) && 
547                                 (info.nRefCount < ADDRMAN_NEW_BUCKETS_PER_ADDRESS)
548                                )
549                             {
550                                 info.nRefCount++;
551                                 vNew.insert(nIndex);
552                             }
553                         }
554                     }
555                 }
556             )
557
558 #endif  //_MSC_VER
559     CAddrMan() : vRandom(0), vvTried(ADDRMAN_TRIED_BUCKET_COUNT, std::vector<int>(0)), vvNew(ADDRMAN_NEW_BUCKET_COUNT, std::set<int>())
560     {
561          nKey.resize(32);
562          RAND_bytes(&nKey[0], 32);
563
564          nIdCount = 0;
565          nTried = 0;
566          nNew = 0;
567     }
568
569     // Return the number of (unique) addresses in all tables.
570     int size()
571     {
572         return vRandom.size();
573     }
574
575     // Consistency check
576     void Check()
577     {
578 #ifdef DEBUG_ADDRMAN
579         {
580             LOCK(cs);
581             int err;
582             if ((err=Check_()))
583                 printf("ADDRMAN CONSISTENCY CHECK FAILED!!! err=%i\n", err);
584         }
585 #endif
586     }
587
588     // Add a single address.
589     bool Add(const CAddress &addr, const CNetAddr& source, int64_t nTimePenalty = 0)
590     {
591         bool fRet = false;
592         {
593             LOCK(cs);
594             Check();
595             fRet |= Add_(addr, source, nTimePenalty);
596             Check();
597         }
598         if (fRet)
599             printf("Added %s from %s: %i tried, %i new\n", addr.ToStringIPPort().c_str(), source.ToString().c_str(), nTried, nNew);
600         return fRet;
601     }
602
603     // Add multiple addresses.
604     bool Add(const std::vector<CAddress> &vAddr, const CNetAddr& source, int64_t nTimePenalty = 0)
605     {
606         int nAdd = 0;
607         {
608             LOCK(cs);
609             Check();
610             for (std::vector<CAddress>::const_iterator it = vAddr.begin(); it != vAddr.end(); it++)
611                 nAdd += Add_(*it, source, nTimePenalty) ? 1 : 0;
612             Check();
613         }
614         if (nAdd)
615             printf("Added %i addresses from %s: %i tried, %i new\n", nAdd, source.ToString().c_str(), nTried, nNew);
616         return nAdd > 0;
617     }
618
619     // Mark an entry as accessible.
620     void Good(const CService &addr, int64_t nTime = GetAdjustedTime())
621     {
622         {
623             LOCK(cs);
624             Check();
625             Good_(addr, nTime);
626             Check();
627         }
628     }
629
630     // Mark an entry as connection attempted to.
631     void Attempt(const CService &addr, int64_t nTime = GetAdjustedTime())
632     {
633         {
634             LOCK(cs);
635             Check();
636             Attempt_(addr, nTime);
637             Check();
638         }
639     }
640
641     // Choose an address to connect to.
642     // nUnkBias determines how much "new" entries are favored over "tried" ones (0-100).
643     CAddress Select(int nUnkBias = 50)
644     {
645         CAddress addrRet;
646         {
647             LOCK(cs);
648             Check();
649             addrRet = Select_(nUnkBias);
650             Check();
651         }
652         return addrRet;
653     }
654
655     // Return a bunch of addresses, selected at random.
656     std::vector<CAddress> GetAddr()
657     {
658         Check();
659         std::vector<CAddress> vAddr;
660         {
661             LOCK(cs);
662             GetAddr_(vAddr);
663         }
664         Check();
665         return vAddr;
666     }
667
668     // Mark an entry as currently-connected-to.
669     void Connected(const CService &addr, int64_t nTime = GetAdjustedTime())
670     {
671         {
672             LOCK(cs);
673             Check();
674             Connected_(addr, nTime);
675             Check();
676         }
677     }
678 };
679
680 #endif