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.
10 int CAddrInfo::GetTriedBucket(const std::vector<unsigned char> &nKey) const
12 CDataStream ss1(SER_GETHASH, 0);
13 std::vector<unsigned char> vchKey = GetKey();
14 ss1 << nKey << vchKey;
15 uint64 hash1 = Hash(ss1.begin(), ss1.end()).Get64();
17 CDataStream ss2(SER_GETHASH, 0);
18 std::vector<unsigned char> vchGroupKey = GetGroup();
19 ss2 << nKey << vchGroupKey << (hash1 % ADDRMAN_TRIED_BUCKETS_PER_GROUP);
20 uint64 hash2 = Hash(ss2.begin(), ss2.end()).Get64();
21 return hash2 % ADDRMAN_TRIED_BUCKET_COUNT;
24 int CAddrInfo::GetNewBucket(const std::vector<unsigned char> &nKey, const CNetAddr& src) const
26 CDataStream ss1(SER_GETHASH, 0);
27 std::vector<unsigned char> vchGroupKey = GetGroup();
28 std::vector<unsigned char> vchSourceGroupKey = src.GetGroup();
29 ss1 << nKey << vchGroupKey << vchSourceGroupKey;
30 uint64 hash1 = Hash(ss1.begin(), ss1.end()).Get64();
32 CDataStream ss2(SER_GETHASH, 0);
33 ss2 << nKey << vchSourceGroupKey << (hash1 % ADDRMAN_NEW_BUCKETS_PER_SOURCE_GROUP);
34 uint64 hash2 = Hash(ss2.begin(), ss2.end()).Get64();
35 return hash2 % ADDRMAN_NEW_BUCKET_COUNT;
38 bool CAddrInfo::IsTerrible(int64 nNow) const
40 if (nLastTry && nLastTry >= nNow-60) // never remove things tried the last minute
43 if (nTime > nNow + 10*60) // came in a flying DeLorean
46 if (nTime==0 || nNow-nTime > ADDRMAN_HORIZON_DAYS*86400) // not seen in over a month
49 if (nLastSuccess==0 && nAttempts>=ADDRMAN_RETRIES) // tried three times and never a success
52 if (nNow-nLastSuccess > ADDRMAN_MIN_FAIL_DAYS*86400 && nAttempts>=ADDRMAN_MAX_FAILURES) // 10 successive failures in the last week
58 double CAddrInfo::GetChance(int64 nNow) const
62 int64 nSinceLastSeen = nNow - nTime;
63 int64 nSinceLastTry = nNow - nLastTry;
65 if (nSinceLastSeen < 0) nSinceLastSeen = 0;
66 if (nSinceLastTry < 0) nSinceLastTry = 0;
68 fChance *= 600.0 / (600.0 + nSinceLastSeen);
70 // deprioritize very recent attempts away
71 if (nSinceLastTry < 60*10)
74 // deprioritize 50% after each failed attempt
75 for (int n=0; n<nAttempts; n++)
81 CAddrInfo* CAddrMan::Find(const CNetAddr& addr, int *pnId)
83 std::map<CNetAddr, int>::iterator it = mapAddr.find(addr);
84 if (it == mapAddr.end())
88 std::map<int, CAddrInfo>::iterator it2 = mapInfo.find((*it).second);
89 if (it2 != mapInfo.end())
90 return &(*it2).second;
94 CAddrInfo* CAddrMan::Create(const CAddress &addr, const CNetAddr &addrSource, int *pnId)
97 mapInfo[nId] = CAddrInfo(addr, addrSource);
99 mapInfo[nId].nRandomPos = vRandom.size();
100 vRandom.push_back(nId);
103 return &mapInfo[nId];
106 void CAddrMan::SwapRandom(unsigned int nRndPos1, unsigned int nRndPos2)
108 if (nRndPos1 == nRndPos2)
111 assert(nRndPos1 < vRandom.size() && nRndPos2 < vRandom.size());
113 int nId1 = vRandom[nRndPos1];
114 int nId2 = vRandom[nRndPos2];
116 assert(mapInfo.count(nId1) == 1);
117 assert(mapInfo.count(nId2) == 1);
119 mapInfo[nId1].nRandomPos = nRndPos2;
120 mapInfo[nId2].nRandomPos = nRndPos1;
122 vRandom[nRndPos1] = nId2;
123 vRandom[nRndPos2] = nId1;
126 int CAddrMan::SelectTried(int nKBucket)
128 std::vector<int> &vTried = vvTried[nKBucket];
130 // random shuffle the first few elements (using the entire list)
131 // find the least recently tried among them
134 for (unsigned int i = 0; i < ADDRMAN_TRIED_ENTRIES_INSPECT_ON_EVICT && i < vTried.size(); i++)
136 int nPos = GetRandInt(vTried.size() - i) + i;
137 int nTemp = vTried[nPos];
138 vTried[nPos] = vTried[i];
140 assert(nOldest == -1 || mapInfo.count(nTemp) == 1);
141 if (nOldest == -1 || mapInfo[nTemp].nLastSuccess < mapInfo[nOldest].nLastSuccess) {
150 int CAddrMan::ShrinkNew(int nUBucket)
152 assert(nUBucket >= 0 && (unsigned int)nUBucket < vvNew.size());
153 std::set<int> &vNew = vvNew[nUBucket];
155 // first look for deletable items
156 for (std::set<int>::iterator it = vNew.begin(); it != vNew.end(); it++)
158 assert(mapInfo.count(*it));
159 CAddrInfo &info = mapInfo[*it];
160 if (info.IsTerrible())
162 if (--info.nRefCount == 0)
164 SwapRandom(info.nRandomPos, vRandom.size()-1);
175 // otherwise, select four randomly, and pick the oldest of those to replace
176 int n[4] = {GetRandInt(vNew.size()), GetRandInt(vNew.size()), GetRandInt(vNew.size()), GetRandInt(vNew.size())};
179 for (std::set<int>::iterator it = vNew.begin(); it != vNew.end(); it++)
181 if (nI == n[0] || nI == n[1] || nI == n[2] || nI == n[3])
183 assert(nOldest == -1 || mapInfo.count(*it) == 1);
184 if (nOldest == -1 || mapInfo[*it].nTime < mapInfo[nOldest].nTime)
189 assert(mapInfo.count(nOldest) == 1);
190 CAddrInfo &info = mapInfo[nOldest];
191 if (--info.nRefCount == 0)
193 SwapRandom(info.nRandomPos, vRandom.size()-1);
196 mapInfo.erase(nOldest);
204 void CAddrMan::MakeTried(CAddrInfo& info, int nId, int nOrigin)
206 assert(vvNew[nOrigin].count(nId) == 1);
208 // remove the entry from all new buckets
209 for (std::vector<std::set<int> >::iterator it = vvNew.begin(); it != vvNew.end(); it++)
211 if ((*it).erase(nId))
216 assert(info.nRefCount == 0);
218 // what tried bucket to move the entry to
219 int nKBucket = info.GetTriedBucket(nKey);
220 std::vector<int> &vTried = vvTried[nKBucket];
222 // first check whether there is place to just add it
223 if (vTried.size() < ADDRMAN_TRIED_BUCKET_SIZE)
225 vTried.push_back(nId);
227 info.fInTried = true;
231 // otherwise, find an item to evict
232 int nPos = SelectTried(nKBucket);
234 // find which new bucket it belongs to
235 assert(mapInfo.count(vTried[nPos]) == 1);
236 int nUBucket = mapInfo[vTried[nPos]].GetNewBucket(nKey);
237 std::set<int> &vNew = vvNew[nUBucket];
239 // remove the to-be-replaced tried entry from the tried set
240 CAddrInfo& infoOld = mapInfo[vTried[nPos]];
241 infoOld.fInTried = false;
242 infoOld.nRefCount = 1;
243 // do not update nTried, as we are going to move something else there immediately
245 // check whether there is place in that one,
246 if (vNew.size() < ADDRMAN_NEW_BUCKET_SIZE)
248 // if so, move it back there
249 vNew.insert(vTried[nPos]);
251 // otherwise, move it to the new bucket nId came from (there is certainly place there)
252 vvNew[nOrigin].insert(vTried[nPos]);
257 // we just overwrote an entry in vTried; no need to update nTried
258 info.fInTried = true;
262 void CAddrMan::Good_(const CService &addr, int64 nTime)
264 // printf("Good: addr=%s\n", addr.ToString().c_str());
267 CAddrInfo *pinfo = Find(addr, &nId);
269 // if not found, bail out
273 CAddrInfo &info = *pinfo;
275 // check whether we are talking about the exact same CService (including same port)
280 info.nLastSuccess = nTime;
281 info.nLastTry = nTime;
285 // if it is already in the tried set, don't do anything else
289 // find a bucket it is in now
290 int nRnd = GetRandInt(vvNew.size());
292 for (unsigned int n = 0; n < vvNew.size(); n++)
294 int nB = (n+nRnd) % vvNew.size();
295 std::set<int> &vNew = vvNew[nB];
303 // if no bucket is found, something bad happened;
304 // TODO: maybe re-add the node, but for now, just bail out
305 if (nUBucket == -1) return;
307 printf("Moving %s to tried\n", addr.ToString().c_str());
309 // move nId to the tried tables
310 MakeTried(info, nId, nUBucket);
313 bool CAddrMan::Add_(const CAddress &addr, const CNetAddr& source, int64 nTimePenalty)
315 if (!addr.IsRoutable())
320 CAddrInfo *pinfo = Find(addr, &nId);
324 // periodically update nTime
325 bool fCurrentlyOnline = (GetAdjustedTime() - addr.nTime < 24 * 60 * 60);
326 int64 nUpdateInterval = (fCurrentlyOnline ? 60 * 60 : 24 * 60 * 60);
327 if (addr.nTime && (!pinfo->nTime || pinfo->nTime < addr.nTime - nUpdateInterval - nTimePenalty))
328 pinfo->nTime = max((int64)0, addr.nTime - nTimePenalty);
331 pinfo->nServices |= addr.nServices;
333 // do not update if no new information is present
334 if (!addr.nTime || (pinfo->nTime && addr.nTime <= pinfo->nTime))
337 // do not update if the entry was already in the "tried" table
341 // do not update if the max reference count is reached
342 if (pinfo->nRefCount == ADDRMAN_NEW_BUCKETS_PER_ADDRESS)
345 // stochastic test: previous nRefCount == N: 2^N times harder to increase it
347 for (int n=0; n<pinfo->nRefCount; n++)
349 if (nFactor > 1 && (GetRandInt(nFactor) != 0))
352 pinfo = Create(addr, source, &nId);
353 pinfo->nTime = max((int64)0, (int64)pinfo->nTime - nTimePenalty);
354 // printf("Added %s [nTime=%fhr]\n", pinfo->ToString().c_str(), (GetAdjustedTime() - pinfo->nTime) / 3600.0);
359 int nUBucket = pinfo->GetNewBucket(nKey, source);
360 std::set<int> &vNew = vvNew[nUBucket];
361 if (!vNew.count(nId))
364 if (vNew.size() == ADDRMAN_NEW_BUCKET_SIZE)
366 vvNew[nUBucket].insert(nId);
371 void CAddrMan::Attempt_(const CService &addr, int64 nTime)
373 CAddrInfo *pinfo = Find(addr);
375 // if not found, bail out
379 CAddrInfo &info = *pinfo;
381 // check whether we are talking about the exact same CService (including same port)
386 info.nLastTry = nTime;
390 CAddress CAddrMan::Select_(int nUnkBias)
395 double nCorTried = sqrt(nTried) * (100.0 - nUnkBias);
396 double nCorNew = sqrt(nNew) * nUnkBias;
397 if ((nCorTried + nCorNew)*GetRandInt(1<<30)/(1<<30) < nCorTried)
400 double fChanceFactor = 1.0;
403 int nKBucket = GetRandInt(vvTried.size());
404 std::vector<int> &vTried = vvTried[nKBucket];
405 if (vTried.size() == 0) continue;
406 int nPos = GetRandInt(vTried.size());
407 assert(mapInfo.count(vTried[nPos]) == 1);
408 CAddrInfo &info = mapInfo[vTried[nPos]];
409 if (GetRandInt(1<<30) < fChanceFactor*info.GetChance()*(1<<30))
411 fChanceFactor *= 1.2;
415 double fChanceFactor = 1.0;
418 int nUBucket = GetRandInt(vvNew.size());
419 std::set<int> &vNew = vvNew[nUBucket];
420 if (vNew.size() == 0) continue;
421 int nPos = GetRandInt(vNew.size());
422 std::set<int>::iterator it = vNew.begin();
425 assert(mapInfo.count(*it) == 1);
426 CAddrInfo &info = mapInfo[*it];
427 if (GetRandInt(1<<30) < fChanceFactor*info.GetChance()*(1<<30))
429 fChanceFactor *= 1.2;
435 int CAddrMan::Check_()
437 std::set<int> setTried;
438 std::map<int, int> mapNew;
440 if (vRandom.size() != nTried + nNew) return -7;
442 for (std::map<int, CAddrInfo>::iterator it = mapInfo.begin(); it != mapInfo.end(); it++)
445 CAddrInfo &info = (*it).second;
449 if (!info.nLastSuccess) return -1;
450 if (info.nRefCount) return -2;
453 if (info.nRefCount < 0 || info.nRefCount > ADDRMAN_NEW_BUCKETS_PER_ADDRESS) return -3;
454 if (!info.nRefCount) return -4;
455 mapNew[n] = info.nRefCount;
457 if (mapAddr[info] != n) return -5;
458 if (info.nRandomPos<0 || info.nRandomPos>=vRandom.size() || vRandom[info.nRandomPos] != n) return -14;
459 if (info.nLastTry < 0) return -6;
460 if (info.nLastSuccess < 0) return -8;
463 if (setTried.size() != nTried) return -9;
464 if (mapNew.size() != nNew) return -10;
466 for (int n=0; n<vvTried.size(); n++)
468 std::vector<int> &vTried = vvTried[n];
469 for (std::vector<int>::iterator it = vTried.begin(); it != vTried.end(); it++)
471 if (!setTried.count(*it)) return -11;
476 for (int n=0; n<vvNew.size(); n++)
478 std::set<int> &vNew = vvNew[n];
479 for (std::set<int>::iterator it = vNew.begin(); it != vNew.end(); it++)
481 if (!mapNew.count(*it)) return -12;
482 if (--mapNew[*it] == 0)
487 if (setTried.size()) return -13;
488 if (mapNew.size()) return -15;
494 void CAddrMan::GetAddr_(std::vector<CAddress> &vAddr)
496 int nNodes = ADDRMAN_GETADDR_MAX_PCT*vRandom.size()/100;
497 if (nNodes > ADDRMAN_GETADDR_MAX)
498 nNodes = ADDRMAN_GETADDR_MAX;
500 // perform a random shuffle over the first nNodes elements of vRandom (selecting from all)
501 for (int n = 0; n<nNodes; n++)
503 int nRndPos = GetRandInt(vRandom.size() - n) + n;
504 SwapRandom(n, nRndPos);
505 assert(mapInfo.count(vRandom[n]) == 1);
506 vAddr.push_back(mapInfo[vRandom[n]]);
510 void CAddrMan::Connected_(const CService &addr, int64 nTime)
512 CAddrInfo *pinfo = Find(addr);
514 // if not found, bail out
518 CAddrInfo &info = *pinfo;
520 // check whether we are talking about the exact same CService (including same port)
525 int64 nUpdateInterval = 20 * 60;
526 if (nTime - info.nTime > nUpdateInterval)