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