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