Update License in File Headers
[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
7 using namespace std;
8
9 int CAddrInfo::GetTriedBucket(const std::vector<unsigned char> &nKey) const
10 {
11     CDataStream ss1(SER_GETHASH);
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);
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);
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);
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     int nId1 = vRandom[nRndPos1];
111     int nId2 = vRandom[nRndPos2];
112
113     mapInfo[nId1].nRandomPos = nRndPos2;
114     mapInfo[nId2].nRandomPos = nRndPos1;
115
116     vRandom[nRndPos1] = nId2;
117     vRandom[nRndPos2] = nId1;
118 }
119
120 int CAddrMan::SelectTried(int nKBucket)
121 {
122     std::vector<int> &vTried = vvTried[nKBucket];
123
124     // random shuffle the first few elements (using the entire list)
125     // find the least recently tried among them
126     int64 nOldest = -1;
127     int nOldestPos = -1;
128     for (unsigned int i = 0; i < ADDRMAN_TRIED_ENTRIES_INSPECT_ON_EVICT && i < vTried.size(); i++)
129     {
130         int nPos = GetRandInt(vTried.size() - i) + i;
131         int nTemp = vTried[nPos];
132         vTried[nPos] = vTried[i];
133         vTried[i] = nTemp;
134         if (nOldest == -1 || mapInfo[nTemp].nLastSuccess < mapInfo[nOldest].nLastSuccess) {
135            nOldest = nTemp;
136            nOldestPos = nPos;
137         }
138     }
139
140     return nOldestPos;
141 }
142
143 int CAddrMan::ShrinkNew(int nUBucket)
144 {
145     std::set<int> &vNew = vvNew[nUBucket];
146
147     // first look for deletable items
148     for (std::set<int>::iterator it = vNew.begin(); it != vNew.end(); it++)
149     {
150         CAddrInfo &info = mapInfo[*it];
151         if (info.IsTerrible())
152         {
153             if (--info.nRefCount == 0)
154             {
155                 SwapRandom(info.nRandomPos, vRandom.size()-1);
156                 vRandom.pop_back();
157                 mapAddr.erase(info);
158                 mapInfo.erase(*it);
159                 nNew--;
160             }
161             vNew.erase(it);
162             return 0;
163         }
164     }
165
166     // otherwise, select four randomly, and pick the oldest of those to replace
167     int n[4] = {GetRandInt(vNew.size()), GetRandInt(vNew.size()), GetRandInt(vNew.size()), GetRandInt(vNew.size())};
168     int nI = 0;
169     int nOldest = -1;
170     for (std::set<int>::iterator it = vNew.begin(); it != vNew.end(); it++)
171     {
172         if (nI == n[0] || nI == n[1] || nI == n[2] || nI == n[3])
173         {
174             if (nOldest == -1 || mapInfo[*it].nTime < mapInfo[nOldest].nTime)
175                 nOldest = *it;
176         }
177         nI++;
178     }
179     CAddrInfo &info = mapInfo[nOldest];
180     if (--info.nRefCount == 0) 
181     {
182         SwapRandom(info.nRandomPos, vRandom.size()-1);
183         vRandom.pop_back();
184         mapAddr.erase(info);
185         mapInfo.erase(nOldest);
186         nNew--;
187     }
188     vNew.erase(nOldest);
189
190     return 1;
191 }
192
193 void CAddrMan::MakeTried(CAddrInfo& info, int nId, int nOrigin)
194 {
195     // remove the entry from all new buckets
196     for (std::vector<std::set<int> >::iterator it = vvNew.begin(); it != vvNew.end(); it++)
197     {
198         if ((*it).erase(nId))
199             info.nRefCount--;
200     }
201     nNew--;
202
203     // what tried bucket to move the entry to
204     int nKBucket = info.GetTriedBucket(nKey);
205     std::vector<int> &vTried = vvTried[nKBucket];
206
207     // first check whether there is place to just add it
208     if (vTried.size() < ADDRMAN_TRIED_BUCKET_SIZE)
209     {
210         vTried.push_back(nId);
211         nTried++;
212         info.fInTried = true;
213         return;
214     }
215
216     // otherwise, find an item to evict
217     int nPos = SelectTried(nKBucket);
218
219     // find which new bucket it belongs to
220     int nUBucket = mapInfo[vTried[nPos]].GetNewBucket(nKey);
221     std::set<int> &vNew = vvNew[nUBucket];
222
223     // remove the to-be-replaced tried entry from the tried set
224     CAddrInfo& infoOld = mapInfo[vTried[nPos]];
225     infoOld.fInTried = false;
226     infoOld.nRefCount = 1;
227     // do not update nTried, as we are going to move something else there immediately
228
229     // check whether there is place in that one, 
230     if (vNew.size() < ADDRMAN_NEW_BUCKET_SIZE)
231     {
232         // if so, move it back there
233         vNew.insert(vTried[nPos]);
234     } else {
235         // otherwise, move it to the new bucket nId came from (there is certainly place there)
236         vvNew[nOrigin].insert(vTried[nPos]);
237     }
238     nNew++;
239
240     vTried[nPos] = nId;
241     // we just overwrote an entry in vTried; no need to update nTried
242     info.fInTried = true;
243     return;
244 }
245
246 void CAddrMan::Good_(const CService &addr, int64 nTime)
247 {
248 //    printf("Good: addr=%s\n", addr.ToString().c_str());
249
250     int nId;
251     CAddrInfo *pinfo = Find(addr, &nId);
252
253     // if not found, bail out
254     if (!pinfo)
255         return;
256
257     CAddrInfo &info = *pinfo;
258
259     // check whether we are talking about the exact same CService (including same port)
260     if (info != addr)
261         return;
262
263     // update info
264     info.nLastSuccess = nTime;
265     info.nLastTry = nTime;
266     info.nTime = nTime;
267     info.nAttempts = 0;
268
269     // if it is already in the tried set, don't do anything else
270     if (info.fInTried)
271         return;
272
273     // find a bucket it is in now
274     int nRnd = GetRandInt(vvNew.size());
275     int nUBucket = -1;
276     for (unsigned int n = 0; n < vvNew.size(); n++)
277     {
278         int nB = (n+nRnd) % vvNew.size();
279         std::set<int> &vNew = vvNew[nB];
280         if (vNew.count(nId))
281         {
282             nUBucket = nB;
283             break;
284         }
285     }
286
287     // if no bucket is found, something bad happened;
288     // TODO: maybe re-add the node, but for now, just bail out
289     if (nUBucket == -1) return;
290
291     printf("Moving %s to tried\n", addr.ToString().c_str());
292
293     // move nId to the tried tables
294     MakeTried(info, nId, nUBucket);
295 }
296
297 bool CAddrMan::Add_(const CAddress &addr, const CNetAddr& source, int64 nTimePenalty)
298 {
299     if (!addr.IsRoutable())
300         return false;
301
302     bool fNew = false;
303     int nId;
304     CAddrInfo *pinfo = Find(addr, &nId);
305
306     if (pinfo)
307     {
308         // periodically update nTime
309         bool fCurrentlyOnline = (GetAdjustedTime() - addr.nTime < 24 * 60 * 60);
310         int64 nUpdateInterval = (fCurrentlyOnline ? 60 * 60 : 24 * 60 * 60);
311         if (addr.nTime && (!pinfo->nTime || pinfo->nTime < addr.nTime - nUpdateInterval - nTimePenalty))
312             pinfo->nTime = max((int64)0, addr.nTime - nTimePenalty);
313
314         // add services
315         pinfo->nServices |= addr.nServices;
316
317         // do not update if no new information is present
318         if (!addr.nTime || (pinfo->nTime && addr.nTime <= pinfo->nTime))
319             return false;
320
321         // do not update if the entry was already in the "tried" table
322         if (pinfo->fInTried)
323             return false;
324
325         // do not update if the max reference count is reached
326         if (pinfo->nRefCount == ADDRMAN_NEW_BUCKETS_PER_ADDRESS)
327             return false;
328
329         // stochastic test: previous nRefCount == N: 2^N times harder to increase it
330         int nFactor = 1;
331         for (int n=0; n<pinfo->nRefCount; n++)
332             nFactor *= 2;
333         if (nFactor > 1 && (GetRandInt(nFactor) != 0))
334             return false;
335     } else {
336         pinfo = Create(addr, source, &nId);
337         pinfo->nTime = max((int64)0, (int64)pinfo->nTime - nTimePenalty);
338 //        printf("Added %s [nTime=%fhr]\n", pinfo->ToString().c_str(), (GetAdjustedTime() - pinfo->nTime) / 3600.0);
339         nNew++;
340         fNew = true;
341     }
342
343     int nUBucket = pinfo->GetNewBucket(nKey, source);
344     std::set<int> &vNew = vvNew[nUBucket];
345     if (!vNew.count(nId))
346     {
347         pinfo->nRefCount++;
348         if (vNew.size() == ADDRMAN_NEW_BUCKET_SIZE)
349             ShrinkNew(nUBucket);
350         vvNew[nUBucket].insert(nId);
351     }
352     return fNew;
353 }
354
355 void CAddrMan::Attempt_(const CService &addr, int64 nTime)
356 {
357     CAddrInfo *pinfo = Find(addr);
358
359     // if not found, bail out
360     if (!pinfo)
361         return;
362
363     CAddrInfo &info = *pinfo;
364
365     // check whether we are talking about the exact same CService (including same port)
366     if (info != addr)
367         return;
368
369     // update info
370     info.nLastTry = nTime;
371     info.nAttempts++;
372 }
373
374 CAddress CAddrMan::Select_(int nUnkBias)
375 {
376     if (size() == 0)
377         return CAddress();
378
379     double nCorTried = sqrt(nTried) * (100.0 - nUnkBias);
380     double nCorNew = sqrt(nNew) * nUnkBias;
381     if ((nCorTried + nCorNew)*GetRandInt(1<<30)/(1<<30) < nCorTried)
382     {
383         // use a tried node
384         double fChanceFactor = 1.0;
385         while(1)
386         {
387             int nKBucket = GetRandInt(vvTried.size());
388             std::vector<int> &vTried = vvTried[nKBucket];
389             if (vTried.size() == 0) continue;
390             int nPos = GetRandInt(vTried.size());
391             CAddrInfo &info = mapInfo[vTried[nPos]];
392             if (GetRandInt(1<<30) < fChanceFactor*info.GetChance()*(1<<30))
393                 return info;
394             fChanceFactor *= 1.2;
395         }
396     } else {
397         // use an new node
398         double fChanceFactor = 1.0;
399         while(1)
400         {
401             int nUBucket = GetRandInt(vvNew.size());
402             std::set<int> &vNew = vvNew[nUBucket];
403             if (vNew.size() == 0) continue;
404             int nPos = GetRandInt(vNew.size());
405             std::set<int>::iterator it = vNew.begin();
406             while (nPos--)
407                 it++;
408             CAddrInfo &info = mapInfo[*it];
409             if (GetRandInt(1<<30) < fChanceFactor*info.GetChance()*(1<<30))
410                 return info;
411             fChanceFactor *= 1.2;
412         }
413     }
414 }
415
416 #ifdef DEBUG_ADDRMAN
417 int CAddrMan::Check_()
418 {
419     std::set<int> setTried;
420     std::map<int, int> mapNew;
421
422     if (vRandom.size() != nTried + nNew) return -7;
423
424     for (std::map<int, CAddrInfo>::iterator it = mapInfo.begin(); it != mapInfo.end(); it++)
425     {
426         int n = (*it).first;
427         CAddrInfo &info = (*it).second;
428         if (info.fInTried)
429         {
430
431             if (!info.nLastSuccess) return -1;
432             if (info.nRefCount) return -2;
433             setTried.insert(n);
434         } else {
435             if (info.nRefCount < 0 || info.nRefCount > ADDRMAN_NEW_BUCKETS_PER_ADDRESS) return -3;
436             if (!info.nRefCount) return -4;
437             mapNew[n] = info.nRefCount;
438         }
439         if (mapAddr[info] != n) return -5;
440         if (info.nRandomPos<0 || info.nRandomPos>=vRandom.size() || vRandom[info.nRandomPos] != n) return -14;
441         if (info.nLastTry < 0) return -6;
442         if (info.nLastSuccess < 0) return -8;
443     }
444
445     if (setTried.size() != nTried) return -9;
446     if (mapNew.size() != nNew) return -10;
447
448     for (int n=0; n<vvTried.size(); n++)
449     {
450         std::vector<int> &vTried = vvTried[n];
451         for (std::vector<int>::iterator it = vTried.begin(); it != vTried.end(); it++)
452         {
453             if (!setTried.count(*it)) return -11;
454             setTried.erase(*it);
455         }
456     }
457
458     for (int n=0; n<vvNew.size(); n++)
459     {
460         std::set<int> &vNew = vvNew[n];
461         for (std::set<int>::iterator it = vNew.begin(); it != vNew.end(); it++)
462         {
463             if (!mapNew.count(*it)) return -12;
464             if (--mapNew[*it] == 0)
465                 mapNew.erase(*it);
466         }
467     }
468
469     if (setTried.size()) return -13;
470     if (mapNew.size()) return -15;
471
472     return 0;
473 }
474 #endif
475
476 void CAddrMan::GetAddr_(std::vector<CAddress> &vAddr)
477 {
478     int nNodes = ADDRMAN_GETADDR_MAX_PCT*vRandom.size()/100;
479     if (nNodes > ADDRMAN_GETADDR_MAX)
480         nNodes = ADDRMAN_GETADDR_MAX;
481
482     // perform a random shuffle over the first nNodes elements of vRandom (selecting from all)
483     for (int n = 0; n<nNodes; n++)
484     {
485         int nRndPos = GetRandInt(vRandom.size() - n) + n;
486         SwapRandom(n, nRndPos);
487         vAddr.push_back(mapInfo[vRandom[n]]);
488     }
489 }
490
491 void CAddrMan::Connected_(const CService &addr, int64 nTime)
492 {
493     CAddrInfo *pinfo = Find(addr);
494
495     // if not found, bail out
496     if (!pinfo)
497         return;
498
499     CAddrInfo &info = *pinfo;
500
501     // check whether we are talking about the exact same CService (including same port)
502     if (info != addr)
503         return;
504
505     // update info
506     int64 nUpdateInterval = 20 * 60;
507     if (nTime - info.nTime > nUpdateInterval)
508         info.nTime = nTime;
509 }