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