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