FormatMoney cleanup
[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     void GetOnlineAddr_(std::vector<CAddrInfo> &vAddr);
243
244     // Mark an entry as currently-connected-to.
245     void Connected_(const CService &addr, int64_t nTime);
246
247 public:
248
249 #ifndef _MSC_VER 
250     IMPLEMENT_SERIALIZE
251     (({
252         // serialized format:
253         // * version byte (currently 0)
254         // * nKey
255         // * nNew
256         // * nTried
257         // * number of "new" buckets
258         // * all nNew addrinfos in vvNew
259         // * all nTried addrinfos in vvTried
260         // * for each bucket:
261         //   * number of elements
262         //   * for each element: index
263         //
264         // Notice that vvTried, mapAddr and vVector are never encoded explicitly;
265         // they are instead reconstructed from the other information.
266         //
267         // vvNew is serialized, but only used if ADDRMAN_UNKOWN_BUCKET_COUNT didn't change,
268         // otherwise it is reconstructed as well.
269         //
270         // This format is more complex, but significantly smaller (at most 1.5 MiB), and supports
271         // changes to the ADDRMAN_ parameters without breaking the on-disk structure.
272         {
273             LOCK(cs);
274             unsigned char nVersion = 0;
275             READWRITE(nVersion);
276             READWRITE(nKey);
277             READWRITE(nNew);
278             READWRITE(nTried);
279
280             CAddrMan *am = const_cast<CAddrMan*>(this);
281             if (fWrite)
282             {
283                 int nUBuckets = ADDRMAN_NEW_BUCKET_COUNT;
284                 READWRITE(nUBuckets);
285                 std::map<int, int> mapUnkIds;
286                 int nIds = 0;
287                 for (std::map<int, CAddrInfo>::iterator it = am->mapInfo.begin(); it != am->mapInfo.end(); it++)
288                 {
289                     if (nIds == nNew) break; // this means nNew was wrong, oh ow
290                     mapUnkIds[(*it).first] = nIds;
291                     CAddrInfo &info = (*it).second;
292                     if (info.nRefCount)
293                     {
294                         READWRITE(info);
295                         nIds++;
296                     }
297                 }
298                 nIds = 0;
299                 for (std::map<int, CAddrInfo>::iterator it = am->mapInfo.begin(); it != am->mapInfo.end(); it++)
300                 {
301                     if (nIds == nTried) break; // this means nTried was wrong, oh ow
302                     CAddrInfo &info = (*it).second;
303                     if (info.fInTried)
304                     {
305                         READWRITE(info);
306                         nIds++;
307                     }
308                 }
309                 for (std::vector<std::set<int> >::iterator it = am->vvNew.begin(); it != am->vvNew.end(); it++)
310                 {
311                     const std::set<int> &vNew = (*it);
312                     int nSize = vNew.size();
313                     READWRITE(nSize);
314                     for (std::set<int>::iterator it2 = vNew.begin(); it2 != vNew.end(); it2++)
315                     {
316                         int nIndex = mapUnkIds[*it2];
317                         READWRITE(nIndex);
318                     }
319                 }
320             } else {
321                 int nUBuckets = 0;
322                 READWRITE(nUBuckets);
323                 am->nIdCount = 0;
324                 am->mapInfo.clear();
325                 am->mapAddr.clear();
326                 am->vRandom.clear();
327                 am->vvTried = std::vector<std::vector<int> >(ADDRMAN_TRIED_BUCKET_COUNT, std::vector<int>(0));
328                 am->vvNew = std::vector<std::set<int> >(ADDRMAN_NEW_BUCKET_COUNT, std::set<int>());
329                 for (int n = 0; n < am->nNew; n++)
330                 {
331                     CAddrInfo &info = am->mapInfo[n];
332                     READWRITE(info);
333                     am->mapAddr[info] = n;
334                     info.nRandomPos = vRandom.size();
335                     am->vRandom.push_back(n);
336                     if (nUBuckets != ADDRMAN_NEW_BUCKET_COUNT)
337                     {
338                         am->vvNew[info.GetNewBucket(am->nKey)].insert(n);
339                         info.nRefCount++;
340                     }
341                 }
342                 am->nIdCount = am->nNew;
343                 int nLost = 0;
344                 for (int n = 0; n < am->nTried; n++)
345                 {
346                     CAddrInfo info;
347                     READWRITE(info);
348                     std::vector<int> &vTried = am->vvTried[info.GetTriedBucket(am->nKey)];
349                     if (vTried.size() < ADDRMAN_TRIED_BUCKET_SIZE)
350                     {
351                         info.nRandomPos = 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                     } else {
359                         nLost++;
360                     }
361                 }
362                 am->nTried -= nLost;
363                 for (int b = 0; b < nUBuckets; b++)
364                 {
365                     std::set<int> &vNew = am->vvNew[b];
366                     int nSize = 0;
367                     READWRITE(nSize);
368                     for (int n = 0; n < nSize; n++)
369                     {
370                         int nIndex = 0;
371                         READWRITE(nIndex);
372                         CAddrInfo &info = am->mapInfo[nIndex];
373                         if (nUBuckets == ADDRMAN_NEW_BUCKET_COUNT && info.nRefCount < ADDRMAN_NEW_BUCKETS_PER_ADDRESS)
374                         {
375                             info.nRefCount++;
376                             vNew.insert(nIndex);
377                         }
378                     }
379                 }
380             }
381         }
382     });)
383 #else
384     IMPLEMENT_SERIALIZE
385             (
386             LOCK(cs);
387                 unsigned char 
388                     nVersion = 0;
389
390                 READWRITE(nVersion);
391                 READWRITE(nKey);
392                 READWRITE(nNew);
393                 READWRITE(nTried);
394
395                 CAddrMan 
396                     *am = const_cast<CAddrMan*>(this);
397
398                 if (fWrite)
399                 {
400                     int 
401                         nUBuckets = ADDRMAN_NEW_BUCKET_COUNT;
402
403                     READWRITE(nUBuckets);
404 /************
405                     std::map<int, int>  
406                         mapUnkIds;
407 ************/  
408                     int 
409                         nIds = 0;
410                     for (std::map<int, CAddrInfo>::iterator it = am->mapInfo.begin(); it != am->mapInfo.end(); it++)
411                     {
412                         if (nIds == nNew) 
413                             break; // this means nNew was wrong, oh ow
414                         mapUnkIds[(*it).first] = nIds;
415
416                         CAddrInfo 
417                             &info = (*it).second;
418
419                         if (info.nRefCount)
420                         {
421                             READWRITE(info);
422                             nIds++;
423                         }
424                     }
425                     nIds = 0;
426                     for (std::map<int, CAddrInfo>::iterator it = am->mapInfo.begin(); it != am->mapInfo.end(); it++)
427                     {
428                         if (nIds == nTried) 
429                             break; /* this means nTried was wrong, oh ow */
430
431                         CAddrInfo 
432                             &info = (*it).second;
433
434                         if (info.fInTried)
435                         {
436                             READWRITE(info);
437                             nIds++;
438                         }
439                     }
440                     for (
441                          std::vector<std::set<int> >::iterator it = am->vvNew.begin(); 
442                          it != am->vvNew.end(); 
443                          it++
444                         )
445                     {
446                         std::set<int> 
447                             &vNew = (*it);
448
449                         int 
450                             nSize = int( vNew.size() );
451
452                         READWRITE(nSize);
453                         for (std::set<int>::iterator it2 = vNew.begin(); it2 != vNew.end(); it2++)
454                         {
455                         int 
456                             nIndex = mapUnkIds[*it2];
457                         READWRITE(nIndex);
458                         }
459                     }
460                 } 
461                 else 
462                 {
463                     int 
464                         nUBuckets = 0;
465
466                     READWRITE(nUBuckets);
467                     am->nIdCount = 0;
468                     am->mapInfo.clear();
469                     am->mapAddr.clear();
470                     am->vRandom.clear();
471                     am->vvTried = 
472                         std::vector<std::vector<int> >(
473                                                         ADDRMAN_TRIED_BUCKET_COUNT, 
474                                                         std::vector<int>(0)
475                                                       );
476                     am->vvNew = 
477                         std::vector<std::set<int> >(
478                                                     ADDRMAN_NEW_BUCKET_COUNT, 
479                                                     std::set<int>()
480                                                    );
481                     for (int n = 0; n < am->nNew; n++)
482                     {
483                         CAddrInfo 
484                             &info = am->mapInfo[n];
485
486                         READWRITE(info);
487                         am->mapAddr[info] = n;
488                         info.nRandomPos = int( vRandom.size() );
489                         am->vRandom.push_back(n);
490                         if (nUBuckets != ADDRMAN_NEW_BUCKET_COUNT)
491                         {
492                             am->vvNew[info.GetNewBucket(am->nKey)].insert(n);
493                             info.nRefCount++;
494                         }
495                     }
496                     am->nIdCount = am->nNew;
497
498                     int 
499                         nLost = 0;
500
501                     for (int n = 0; n < am->nTried; n++)
502                     {
503                         CAddrInfo 
504                             info;
505
506                         READWRITE(info);
507
508                         std::vector<int> 
509                             &vTried = am->vvTried[info.GetTriedBucket(am->nKey)];
510
511                         if (vTried.size() < ADDRMAN_TRIED_BUCKET_SIZE)
512                         {
513                             info.nRandomPos = int( vRandom.size() );
514                             info.fInTried = true;
515                             am->vRandom.push_back(am->nIdCount);
516                             am->mapInfo[am->nIdCount] = info;
517                             am->mapAddr[info] = am->nIdCount;
518                             vTried.push_back(am->nIdCount);
519                             am->nIdCount++;
520                         } 
521                         else 
522                         {
523                             nLost++;
524                         }
525                     }
526                     am->nTried -= nLost;
527                     for (int b = 0; b < nUBuckets; b++)
528                     {
529                         std::set<int> 
530                             &vNew = am->vvNew[b];
531
532                         int 
533                             nSize = 0;
534
535                         READWRITE(nSize);
536                         for (int n = 0; n < nSize; n++)
537                         {
538                             int 
539                                 nIndex = 0;
540
541                             READWRITE(nIndex);
542
543                             CAddrInfo 
544                                 &info = am->mapInfo[nIndex];
545
546                             if (
547                                 (nUBuckets == ADDRMAN_NEW_BUCKET_COUNT) && 
548                                 (info.nRefCount < ADDRMAN_NEW_BUCKETS_PER_ADDRESS)
549                                )
550                             {
551                                 info.nRefCount++;
552                                 vNew.insert(nIndex);
553                             }
554                         }
555                     }
556                 }
557             )
558
559 #endif  //_MSC_VER
560     CAddrMan() : vRandom(0), vvTried(ADDRMAN_TRIED_BUCKET_COUNT, std::vector<int>(0)), vvNew(ADDRMAN_NEW_BUCKET_COUNT, std::set<int>())
561     {
562          nKey.resize(32);
563          RAND_bytes(&nKey[0], 32);
564
565          nIdCount = 0;
566          nTried = 0;
567          nNew = 0;
568     }
569
570     // Return the number of (unique) addresses in all tables.
571     int size()
572     {
573         return (int) vRandom.size();
574     }
575
576     // Consistency check
577     void Check()
578     {
579 #ifdef DEBUG_ADDRMAN
580         {
581             LOCK(cs);
582             int err;
583             if ((err=Check_()))
584                 printf("ADDRMAN CONSISTENCY CHECK FAILED!!! err=%i\n", err);
585         }
586 #endif
587     }
588
589     // Add a single address.
590     bool Add(const CAddress &addr, const CNetAddr& source, int64_t nTimePenalty = 0)
591     {
592         bool fRet = false;
593         {
594             LOCK(cs);
595             Check();
596             fRet |= Add_(addr, source, nTimePenalty);
597             Check();
598         }
599         if (fRet)
600             printf("Added %s from %s: %i tried, %i new\n", addr.ToStringIPPort().c_str(), source.ToString().c_str(), nTried, nNew);
601         return fRet;
602     }
603
604     // Add multiple addresses.
605     bool Add(const std::vector<CAddress> &vAddr, const CNetAddr& source, int64_t nTimePenalty = 0)
606     {
607         int nAdd = 0;
608         {
609             LOCK(cs);
610             Check();
611             for (std::vector<CAddress>::const_iterator it = vAddr.begin(); it != vAddr.end(); it++)
612                 nAdd += Add_(*it, source, nTimePenalty) ? 1 : 0;
613             Check();
614         }
615         if (nAdd)
616             printf("Added %i addresses from %s: %i tried, %i new\n", nAdd, source.ToString().c_str(), nTried, nNew);
617         return nAdd > 0;
618     }
619
620     // Mark an entry as accessible.
621     void Good(const CService &addr, int64_t nTime = GetAdjustedTime())
622     {
623         {
624             LOCK(cs);
625             Check();
626             Good_(addr, nTime);
627             Check();
628         }
629     }
630
631     // Mark an entry as connection attempted to.
632     void Attempt(const CService &addr, int64_t nTime = GetAdjustedTime())
633     {
634         {
635             LOCK(cs);
636             Check();
637             Attempt_(addr, nTime);
638             Check();
639         }
640     }
641
642     // Choose an address to connect to.
643     // nUnkBias determines how much "new" entries are favored over "tried" ones (0-100).
644     CAddress Select(int nUnkBias = 50)
645     {
646         CAddress addrRet;
647         {
648             LOCK(cs);
649             Check();
650             addrRet = Select_(nUnkBias);
651             Check();
652         }
653         return addrRet;
654     }
655
656     // Return a bunch of addresses, selected at random.
657     std::vector<CAddress> GetAddr()
658     {
659         Check();
660         std::vector<CAddress> vAddr;
661         {
662             LOCK(cs);
663             GetAddr_(vAddr);
664         }
665         Check();
666         return vAddr;
667     }
668
669     std::vector<CAddrInfo> GetOnlineAddr()
670     {
671         Check();
672         std::vector<CAddrInfo> vAddr;
673         {
674             LOCK(cs);
675             GetOnlineAddr_(vAddr);
676         }
677         Check();
678         return vAddr;
679     }
680
681     // Mark an entry as currently-connected-to.
682     void Connected(const CService &addr, int64_t nTime = GetAdjustedTime())
683     {
684         {
685             LOCK(cs);
686             Check();
687             Connected_(addr, nTime);
688             Check();
689         }
690     }
691 };
692
693 #endif