Update CMakeLists.txt - play with openssl
[novacoin.git] / src / addrman.cpp
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
5 #include "addrman.h"
6 #include "hash.h"
7 #include "random.h"
8 #include "streams.h"
9
10 using namespace std;
11
12 int CAddrInfo::GetTriedBucket(const std::vector<unsigned char> &nKey) const
13 {
14     CDataStream ss1(SER_GETHASH, 0);
15     std::vector<unsigned char> vchKey = GetKey();
16     ss1 << nKey << vchKey;
17     uint64_t hash1 = Hash(ss1.begin(), ss1.end()).Get64();
18
19     CDataStream ss2(SER_GETHASH, 0);
20     std::vector<unsigned char> vchGroupKey = GetGroup();
21     ss2 << nKey << vchGroupKey << (hash1 % ADDRMAN_TRIED_BUCKETS_PER_GROUP);
22     uint64_t hash2 = Hash(ss2.begin(), ss2.end()).Get64();
23     return hash2 % ADDRMAN_TRIED_BUCKET_COUNT;
24 }
25
26 int CAddrInfo::GetNewBucket(const std::vector<unsigned char> &nKey, const CNetAddr& src) const
27 {
28     CDataStream ss1(SER_GETHASH, 0);
29     std::vector<unsigned char> vchGroupKey = GetGroup();
30     std::vector<unsigned char> vchSourceGroupKey = src.GetGroup();
31     ss1 << nKey << vchGroupKey << vchSourceGroupKey;
32     uint64_t hash1 = Hash(ss1.begin(), ss1.end()).Get64();
33
34     CDataStream ss2(SER_GETHASH, 0);
35     ss2 << nKey << vchSourceGroupKey << (hash1 % ADDRMAN_NEW_BUCKETS_PER_SOURCE_GROUP);
36     uint64_t hash2 = Hash(ss2.begin(), ss2.end()).Get64();
37     return hash2 % ADDRMAN_NEW_BUCKET_COUNT;
38 }
39
40 bool CAddrInfo::IsTerrible(int64_t nNow) const
41 {
42     if (nLastTry && nLastTry >= nNow-60) // never remove things tried the last minute
43         return false;
44
45     if (nTime > nNow + 10*60) // came in a flying DeLorean
46         return true;
47
48     if (nTime==0 || nNow-nTime > ADDRMAN_HORIZON_DAYS*nOneDay) // not seen in over a month
49         return true;
50
51     if (nLastSuccess==0 && nAttempts>=ADDRMAN_RETRIES) // tried three times and never a success
52         return true;
53
54     if (nNow-nLastSuccess > ADDRMAN_MIN_FAIL_DAYS*nOneDay && nAttempts>=ADDRMAN_MAX_FAILURES) // 10 successive failures in the last week
55         return true;
56
57     return false;
58 }
59
60 double CAddrInfo::GetChance(int64_t nNow) const
61 {
62     double fChance = 1.0;
63
64     int64_t nSinceLastSeen = nNow - nTime;
65     int64_t nSinceLastTry = nNow - nLastTry;
66
67     if (nSinceLastSeen < 0) nSinceLastSeen = 0;
68     if (nSinceLastTry < 0) nSinceLastTry = 0;
69
70     fChance *= 600.0 / (600.0 + nSinceLastSeen);
71
72     // deprioritize very recent attempts away
73     if (nSinceLastTry < 60*10)
74         fChance *= 0.01;
75
76     // deprioritize 50% after each failed attempt
77     for (int n=0; n<nAttempts; n++)
78         fChance /= 1.5;
79
80     return fChance;
81 }
82
83 CAddrInfo* CAddrMan::Find(const CNetAddr& addr, int *pnId)
84 {
85     std::map<CNetAddr, int>::iterator it = mapAddr.find(addr);
86     if (it == mapAddr.end())
87         return NULL;
88     if (pnId)
89         *pnId = (*it).second;
90     std::map<int, CAddrInfo>::iterator it2 = mapInfo.find((*it).second);
91     if (it2 != mapInfo.end())
92         return &(*it2).second;
93     return NULL;
94 }
95
96 CAddrInfo* CAddrMan::Create(const CAddress &addr, const CNetAddr &addrSource, int *pnId)
97 {
98     int nId = nIdCount++;
99     mapInfo[nId] = CAddrInfo(addr, addrSource);
100     mapAddr[addr] = nId;
101     mapInfo[nId].nRandomPos = vRandom.size();
102     vRandom.push_back(nId);
103     if (pnId)
104         *pnId = nId;
105     return &mapInfo[nId];
106 }
107
108 void CAddrMan::SwapRandom(unsigned int nRndPos1, unsigned int nRndPos2)
109 {
110     if (nRndPos1 == nRndPos2)
111         return;
112
113     assert(nRndPos1 < vRandom.size() && nRndPos2 < vRandom.size());
114
115     int nId1 = vRandom[nRndPos1];
116     int nId2 = vRandom[nRndPos2];
117
118     assert(mapInfo.count(nId1) == 1);
119     assert(mapInfo.count(nId2) == 1);
120
121     mapInfo[nId1].nRandomPos = nRndPos2;
122     mapInfo[nId2].nRandomPos = nRndPos1;
123
124     vRandom[nRndPos1] = nId2;
125     vRandom[nRndPos2] = nId1;
126 }
127
128 int CAddrMan::SelectTried(int nKBucket)
129 {
130     std::vector<int> &vTried = vvTried[nKBucket];
131
132     // random shuffle the first few elements (using the entire list)
133     // find the least recently tried among them
134     int64_t nOldest = -1;
135     int nOldestPos = -1;
136     for (unsigned int i = 0; i < ADDRMAN_TRIED_ENTRIES_INSPECT_ON_EVICT && i < vTried.size(); i++)
137     {
138         int nPos = GetRandInt(vTried.size() - i) + i;
139         int nTemp = vTried[nPos];
140         vTried[nPos] = vTried[i];
141         vTried[i] = nTemp;
142         assert(nOldest == -1 || mapInfo.count(nTemp) == 1);
143         if (nOldest == -1 || mapInfo[nTemp].nLastSuccess < mapInfo[nOldest].nLastSuccess) {
144            nOldest = nTemp;
145            nOldestPos = nPos;
146         }
147     }
148
149     return nOldestPos;
150 }
151
152 int CAddrMan::ShrinkNew(int nUBucket)
153 {
154     assert(nUBucket >= 0 && (unsigned int)nUBucket < vvNew.size());
155     std::set<int> &vNew = vvNew[nUBucket];
156
157     // first look for deletable items
158     for (std::set<int>::iterator it = vNew.begin(); it != vNew.end(); it++)
159     {
160         assert(mapInfo.count(*it));
161         CAddrInfo &info = mapInfo[*it];
162         if (info.IsTerrible())
163         {
164             if (--info.nRefCount == 0)
165             {
166                 SwapRandom(info.nRandomPos, vRandom.size()-1);
167                 vRandom.pop_back();
168                 mapAddr.erase(info);
169                 mapInfo.erase(*it);
170                 nNew--;
171             }
172             vNew.erase(it);
173             return 0;
174         }
175     }
176
177     // otherwise, select four randomly, and pick the oldest of those to replace
178     int n[4] = {GetRandInt(vNew.size()), GetRandInt(vNew.size()), GetRandInt(vNew.size()), GetRandInt(vNew.size())};
179     int nI = 0;
180     int nOldest = -1;
181     for (std::set<int>::iterator it = vNew.begin(); it != vNew.end(); it++)
182     {
183         if (nI == n[0] || nI == n[1] || nI == n[2] || nI == n[3])
184         {
185             assert(nOldest == -1 || mapInfo.count(*it) == 1);
186             if (nOldest == -1 || mapInfo[*it].nTime < mapInfo[nOldest].nTime)
187                 nOldest = *it;
188         }
189         nI++;
190     }
191     assert(mapInfo.count(nOldest) == 1);
192     CAddrInfo &info = mapInfo[nOldest];
193     if (--info.nRefCount == 0)
194     {
195         SwapRandom(info.nRandomPos, vRandom.size()-1);
196         vRandom.pop_back();
197         mapAddr.erase(info);
198         mapInfo.erase(nOldest);
199         nNew--;
200     }
201     vNew.erase(nOldest);
202
203     return 1;
204 }
205
206 void CAddrMan::MakeTried(CAddrInfo& info, int nId, int nOrigin)
207 {
208     assert(vvNew[nOrigin].count(nId) == 1);
209
210     // remove the entry from all new buckets
211     for (std::vector<std::set<int> >::iterator it = vvNew.begin(); it != vvNew.end(); it++)
212     {
213         if ((*it).erase(nId))
214             info.nRefCount--;
215     }
216     nNew--;
217
218     assert(info.nRefCount == 0);
219
220     // what tried bucket to move the entry to
221     int nKBucket = info.GetTriedBucket(nKey);
222     std::vector<int> &vTried = vvTried[nKBucket];
223
224     // first check whether there is place to just add it
225     if (vTried.size() < ADDRMAN_TRIED_BUCKET_SIZE)
226     {
227         vTried.push_back(nId);
228         nTried++;
229         info.fInTried = true;
230         return;
231     }
232
233     // otherwise, find an item to evict
234     int nPos = SelectTried(nKBucket);
235
236     // find which new bucket it belongs to
237     assert(mapInfo.count(vTried[nPos]) == 1);
238     int nUBucket = mapInfo[vTried[nPos]].GetNewBucket(nKey);
239     std::set<int> &vNew = vvNew[nUBucket];
240
241     // remove the to-be-replaced tried entry from the tried set
242     CAddrInfo& infoOld = mapInfo[vTried[nPos]];
243     infoOld.fInTried = false;
244     infoOld.nRefCount = 1;
245     // do not update nTried, as we are going to move something else there immediately
246
247     // check whether there is place in that one,
248     if (vNew.size() < ADDRMAN_NEW_BUCKET_SIZE)
249     {
250         // if so, move it back there
251         vNew.insert(vTried[nPos]);
252     } else {
253         // otherwise, move it to the new bucket nId came from (there is certainly place there)
254         vvNew[nOrigin].insert(vTried[nPos]);
255     }
256     nNew++;
257
258     vTried[nPos] = nId;
259     // we just overwrote an entry in vTried; no need to update nTried
260     info.fInTried = true;
261     return;
262 }
263
264 void CAddrMan::Good_(const CService &addr, int64_t nTime)
265 {
266 //    printf("Good: addr=%s\n", addr.ToString().c_str());
267
268     int nId;
269     CAddrInfo *pinfo = Find(addr, &nId);
270
271     // if not found, bail out
272     if (!pinfo)
273         return;
274
275     CAddrInfo &info = *pinfo;
276
277     // check whether we are talking about the exact same CService (including same port)
278     if (info != addr)
279         return;
280
281     // update info
282     info.nLastSuccess = nTime;
283     info.nLastTry = nTime;
284     info.nTime = nTime;
285     info.nAttempts = 0;
286
287     // if it is already in the tried set, don't do anything else
288     if (info.fInTried)
289         return;
290
291     // find a bucket it is in now
292     int nRnd = GetRandInt(vvNew.size());
293     int nUBucket = -1;
294     for (unsigned int n = 0; n < vvNew.size(); n++)
295     {
296         int nB = (n+nRnd) % vvNew.size();
297         std::set<int> &vNew = vvNew[nB];
298         if (vNew.count(nId))
299         {
300             nUBucket = nB;
301             break;
302         }
303     }
304
305     // if no bucket is found, something bad happened;
306     // TODO: maybe re-add the node, but for now, just bail out
307     if (nUBucket == -1) return;
308
309     printf("Moving %s to tried\n", addr.ToString().c_str());
310
311     // move nId to the tried tables
312     MakeTried(info, nId, nUBucket);
313 }
314
315 bool CAddrMan::Add_(const CAddress &addr, const CNetAddr& source, int64_t nTimePenalty)
316 {
317     if (!addr.IsRoutable())
318         return false;
319
320     bool fNew = false;
321     int nId;
322     CAddrInfo *pinfo = Find(addr, &nId);
323
324     if (pinfo)
325     {
326         // periodically update nTime
327         bool fCurrentlyOnline = (GetAdjustedTime() - addr.nTime < nOneDay);
328         int64_t nUpdateInterval = (fCurrentlyOnline ? nOneHour : nOneDay);
329         if (addr.nTime && (!pinfo->nTime || pinfo->nTime < addr.nTime - nUpdateInterval - nTimePenalty))
330             pinfo->nTime = max((int64_t)0, addr.nTime - nTimePenalty);
331
332         // add services
333         pinfo->nServices |= addr.nServices;
334
335         // do not update if no new information is present
336         if (!addr.nTime || (pinfo->nTime && addr.nTime <= pinfo->nTime))
337             return false;
338
339         // do not update if the entry was already in the "tried" table
340         if (pinfo->fInTried)
341             return false;
342
343         // do not update if the max reference count is reached
344         if (pinfo->nRefCount == ADDRMAN_NEW_BUCKETS_PER_ADDRESS)
345             return false;
346
347         // stochastic test: previous nRefCount == N: 2^N times harder to increase it
348         int nFactor = 1;
349         for (int n=0; n<pinfo->nRefCount; n++)
350             nFactor *= 2;
351         if (nFactor > 1 && (GetRandInt(nFactor) != 0))
352             return false;
353     } else {
354         pinfo = Create(addr, source, &nId);
355         pinfo->nTime = max((int64_t)0, (int64_t)pinfo->nTime - nTimePenalty);
356 //        printf("Added %s [nTime=%fhr]\n", pinfo->ToString().c_str(), (GetAdjustedTime() - pinfo->nTime) / 3600.0);
357         nNew++;
358         fNew = true;
359     }
360
361     int nUBucket = pinfo->GetNewBucket(nKey, source);
362     std::set<int> &vNew = vvNew[nUBucket];
363     if (!vNew.count(nId))
364     {
365         pinfo->nRefCount++;
366         if (vNew.size() == ADDRMAN_NEW_BUCKET_SIZE)
367             ShrinkNew(nUBucket);
368         vvNew[nUBucket].insert(nId);
369     }
370     return fNew;
371 }
372
373 void CAddrMan::Attempt_(const CService &addr, int64_t nTime)
374 {
375     CAddrInfo *pinfo = Find(addr);
376
377     // if not found, bail out
378     if (!pinfo)
379         return;
380
381     CAddrInfo &info = *pinfo;
382
383     // check whether we are talking about the exact same CService (including same port)
384     if (info != addr)
385         return;
386
387     // update info
388     info.nLastTry = nTime;
389     info.nAttempts++;
390 }
391
392 CAddress CAddrMan::Select_(int nUnkBias)
393 {
394     if (size() == 0)
395         return CAddress();
396
397     double nCorTried = sqrt(nTried) * (100.0 - nUnkBias);
398     double nCorNew = sqrt(nNew) * nUnkBias;
399     if ((nCorTried + nCorNew)*GetRandInt(1<<30)/(1<<30) < nCorTried)
400     {
401         // use a tried node
402         double fChanceFactor = 1.0;
403         for ( ; ; )
404         {
405             int nKBucket = GetRandInt(vvTried.size());
406             std::vector<int> &vTried = vvTried[nKBucket];
407             if (vTried.size() == 0) continue;
408             int nPos = GetRandInt(vTried.size());
409             assert(mapInfo.count(vTried[nPos]) == 1);
410             CAddrInfo &info = mapInfo[vTried[nPos]];
411             if (GetRandInt(1<<30) < fChanceFactor*info.GetChance()*(1<<30))
412                 return info;
413             fChanceFactor *= 1.2;
414         }
415     } else {
416         // use a new node
417         double fChanceFactor = 1.0;
418         for ( ; ; )
419         {
420             int nUBucket = GetRandInt(vvNew.size());
421             std::set<int> &vNew = vvNew[nUBucket];
422             if (vNew.size() == 0) continue;
423             int nPos = GetRandInt(vNew.size());
424             std::set<int>::iterator it = vNew.begin();
425             while (nPos--)
426                 it++;
427             assert(mapInfo.count(*it) == 1);
428             CAddrInfo &info = mapInfo[*it];
429             if (GetRandInt(1<<30) < fChanceFactor*info.GetChance()*(1<<30))
430                 return info;
431             fChanceFactor *= 1.2;
432         }
433     }
434 }
435
436 #ifdef DEBUG_ADDRMAN
437 int CAddrMan::Check_()
438 {
439     std::set<int> setTried;
440     std::map<int, int> mapNew;
441
442     if (vRandom.size() != nTried + nNew) return -7;
443
444     for (std::map<int, CAddrInfo>::iterator it = mapInfo.begin(); it != mapInfo.end(); it++)
445     {
446         int n = (*it).first;
447         CAddrInfo &info = (*it).second;
448         if (info.fInTried)
449         {
450
451             if (!info.nLastSuccess) return -1;
452             if (info.nRefCount) return -2;
453             setTried.insert(n);
454         } else {
455             if (info.nRefCount < 0 || info.nRefCount > ADDRMAN_NEW_BUCKETS_PER_ADDRESS) return -3;
456             if (!info.nRefCount) return -4;
457             mapNew[n] = info.nRefCount;
458         }
459         if (mapAddr[info] != n) return -5;
460         if (info.nRandomPos<0 || info.nRandomPos>=vRandom.size() || vRandom[info.nRandomPos] != n) return -14;
461         if (info.nLastTry < 0) return -6;
462         if (info.nLastSuccess < 0) return -8;
463     }
464
465     if (setTried.size() != nTried) return -9;
466     if (mapNew.size() != nNew) return -10;
467
468     for (int n=0; n<vvTried.size(); n++)
469     {
470         std::vector<int> &vTried = vvTried[n];
471         for (std::vector<int>::iterator it = vTried.begin(); it != vTried.end(); it++)
472         {
473             if (!setTried.count(*it)) return -11;
474             setTried.erase(*it);
475         }
476     }
477
478     for (int n=0; n<vvNew.size(); n++)
479     {
480         std::set<int> &vNew = vvNew[n];
481         for (std::set<int>::iterator it = vNew.begin(); it != vNew.end(); it++)
482         {
483             if (!mapNew.count(*it)) return -12;
484             if (--mapNew[*it] == 0)
485                 mapNew.erase(*it);
486         }
487     }
488
489     if (setTried.size()) return -13;
490     if (mapNew.size()) return -15;
491
492     return 0;
493 }
494 #endif
495
496 void CAddrMan::GetAddr_(std::vector<CAddress> &vAddr)
497 {
498     size_t nNodes = ADDRMAN_GETADDR_MAX_PCT*vRandom.size()/100;
499     if (nNodes > ADDRMAN_GETADDR_MAX)
500         nNodes = ADDRMAN_GETADDR_MAX;
501
502     // perform a random shuffle over the first nNodes elements of vRandom (selecting from all)
503     for (unsigned int n = 0; n<nNodes; n++)
504     {
505         int nRndPos = GetRandInt(vRandom.size() - n) + n;
506         SwapRandom(n, nRndPos);
507         assert(mapInfo.count(vRandom[n]) == 1);
508         vAddr.push_back(mapInfo[vRandom[n]]);
509     }
510 }
511
512 void CAddrMan::GetOnlineAddr_(std::vector<CAddrInfo> &vAddr)
513 {
514     for (std::map<int, CAddrInfo>::const_iterator it = mapInfo.begin(); it != mapInfo.end(); it++)
515     {
516         CAddrInfo addr = it->second;
517         bool fCurrentlyOnline = (GetAdjustedTime() - addr.nTime < nOneDay);
518         if (fCurrentlyOnline)
519             vAddr.push_back(addr);
520     }
521 }
522
523 void CAddrMan::Connected_(const CService &addr, int64_t nTime)
524 {
525     CAddrInfo *pinfo = Find(addr);
526
527     // if not found, bail out
528     if (!pinfo)
529         return;
530
531     CAddrInfo &info = *pinfo;
532
533     // check whether we are talking about the exact same CService (including same port)
534     if (info != addr)
535         return;
536
537     // update info
538     int64_t nUpdateInterval = 20 * 60;
539     if (nTime - info.nTime > nUpdateInterval)
540         info.nTime = nTime;
541 }
542
543 CAddrMan::CAddrMan() : vRandom(0), vvTried(ADDRMAN_TRIED_BUCKET_COUNT, std::vector<int>(0)), vvNew(ADDRMAN_NEW_BUCKET_COUNT, std::set<int>())
544 {
545     nKey.resize(32);
546     GetRandBytes(&nKey[0], 32);
547
548     nIdCount = 0;
549     nTried = 0;
550     nNew = 0;
551 }