LCOV - code coverage report
Current view: top level - src - addrman.h (source / functions) Hit Total Coverage
Test: total_coverage.info Lines: 234 263 89.0 %
Date: 2020-09-26 01:30:44 Functions: 48 52 92.3 %

          Line data    Source code
       1             : // Copyright (c) 2012 Pieter Wuille
       2             : // Copyright (c) 2012-2020 The Bitcoin Core developers
       3             : // Distributed under the MIT software license, see the accompanying
       4             : // file COPYING or http://www.opensource.org/licenses/mit-license.php.
       5             : 
       6             : #ifndef BITCOIN_ADDRMAN_H
       7             : #define BITCOIN_ADDRMAN_H
       8             : 
       9             : #include <clientversion.h>
      10             : #include <netaddress.h>
      11             : #include <protocol.h>
      12             : #include <random.h>
      13             : #include <sync.h>
      14             : #include <timedata.h>
      15             : #include <util/system.h>
      16             : 
      17             : #include <fs.h>
      18             : #include <hash.h>
      19             : #include <iostream>
      20             : #include <map>
      21             : #include <set>
      22             : #include <stdint.h>
      23             : #include <streams.h>
      24             : #include <vector>
      25             : 
      26             : /**
      27             :  * Extended statistics about a CAddress
      28             :  */
      29     1863222 : class CAddrInfo : public CAddress
      30             : {
      31             : public:
      32             :     //! last try whatsoever by us (memory only)
      33      734985 :     int64_t nLastTry{0};
      34             : 
      35             :     //! last counted attempt (memory only)
      36      734985 :     int64_t nLastCountAttempt{0};
      37             : 
      38             : private:
      39             :     //! where knowledge about this address first came from
      40             :     CNetAddr source;
      41             : 
      42             :     //! last successful connection by us
      43      734985 :     int64_t nLastSuccess{0};
      44             : 
      45             :     //! connection attempts since last successful attempt
      46      734985 :     int nAttempts{0};
      47             : 
      48             :     //! reference count in new sets (memory only)
      49      734985 :     int nRefCount{0};
      50             : 
      51             :     //! in tried set? (memory only)
      52      734985 :     bool fInTried{false};
      53             : 
      54             :     //! position in vRandom
      55      734985 :     int nRandomPos{-1};
      56             : 
      57             :     friend class CAddrMan;
      58             : 
      59             : public:
      60             : 
      61       74712 :     SERIALIZE_METHODS(CAddrInfo, obj)
      62             :     {
      63       24904 :         READWRITEAS(CAddress, obj);
      64       24904 :         READWRITE(obj.source, obj.nLastSuccess, obj.nAttempts);
      65       24904 :     }
      66             : 
      67      636158 :     CAddrInfo(const CAddress &addrIn, const CNetAddr &addrSource) : CAddress(addrIn), source(addrSource)
      68      636158 :     {
      69      636158 :     }
      70             : 
      71      833812 :     CAddrInfo() : CAddress(), source()
      72      833812 :     {
      73      833812 :     }
      74             : 
      75             :     //! Calculate in which "tried" bucket this entry belongs
      76             :     int GetTriedBucket(const uint256 &nKey, const std::vector<bool> &asmap) const;
      77             : 
      78             :     //! Calculate in which "new" bucket this entry belongs, given a certain source
      79             :     int GetNewBucket(const uint256 &nKey, const CNetAddr& src, const std::vector<bool> &asmap) const;
      80             : 
      81             :     //! Calculate in which "new" bucket this entry belongs, using its default source
      82        3330 :     int GetNewBucket(const uint256 &nKey, const std::vector<bool> &asmap) const
      83             :     {
      84        3330 :         return GetNewBucket(nKey, source, asmap);
      85             :     }
      86             : 
      87             :     //! Calculate in which position of a bucket to store this entry.
      88             :     int GetBucketPosition(const uint256 &nKey, bool fNew, int nBucket) const;
      89             : 
      90             :     //! Determine whether the statistics about this entry are bad enough so that it can just be deleted
      91             :     bool IsTerrible(int64_t nNow = GetAdjustedTime()) const;
      92             : 
      93             :     //! Calculate the relative chance this entry should be given when selecting nodes to connect to
      94             :     double GetChance(int64_t nNow = GetAdjustedTime()) const;
      95             : };
      96             : 
      97             : /** Stochastic address manager
      98             :  *
      99             :  * Design goals:
     100             :  *  * Keep the address tables in-memory, and asynchronously dump the entire table to peers.dat.
     101             :  *  * Make sure no (localized) attacker can fill the entire table with his nodes/addresses.
     102             :  *
     103             :  * To that end:
     104             :  *  * Addresses are organized into buckets.
     105             :  *    * Addresses that have not yet been tried go into 1024 "new" buckets.
     106             :  *      * Based on the address range (/16 for IPv4) of the source of information, 64 buckets are selected at random.
     107             :  *      * The actual bucket is chosen from one of these, based on the range in which the address itself is located.
     108             :  *      * One single address can occur in up to 8 different buckets to increase selection chances for addresses that
     109             :  *        are seen frequently. The chance for increasing this multiplicity decreases exponentially.
     110             :  *      * When adding a new address to a full bucket, a randomly chosen entry (with a bias favoring less recently seen
     111             :  *        ones) is removed from it first.
     112             :  *    * Addresses of nodes that are known to be accessible go into 256 "tried" buckets.
     113             :  *      * Each address range selects at random 8 of these buckets.
     114             :  *      * The actual bucket is chosen from one of these, based on the full address.
     115             :  *      * When adding a new good address to a full bucket, a randomly chosen entry (with a bias favoring less recently
     116             :  *        tried ones) is evicted from it, back to the "new" buckets.
     117             :  *    * Bucket selection is based on cryptographic hashing, using a randomly-generated 256-bit key, which should not
     118             :  *      be observable by adversaries.
     119             :  *    * Several indexes are kept for high performance. Defining DEBUG_ADDRMAN will introduce frequent (and expensive)
     120             :  *      consistency checks for the entire data structure.
     121             :  */
     122             : 
     123             : //! total number of buckets for tried addresses
     124             : #define ADDRMAN_TRIED_BUCKET_COUNT_LOG2 8
     125             : 
     126             : //! total number of buckets for new addresses
     127             : #define ADDRMAN_NEW_BUCKET_COUNT_LOG2 10
     128             : 
     129             : //! maximum allowed number of entries in buckets for new and tried addresses
     130             : #define ADDRMAN_BUCKET_SIZE_LOG2 6
     131             : 
     132             : //! over how many buckets entries with tried addresses from a single group (/16 for IPv4) are spread
     133             : #define ADDRMAN_TRIED_BUCKETS_PER_GROUP 8
     134             : 
     135             : //! over how many buckets entries with new addresses originating from a single group are spread
     136             : #define ADDRMAN_NEW_BUCKETS_PER_SOURCE_GROUP 64
     137             : 
     138             : //! in how many buckets for entries with new addresses a single address may occur
     139             : #define ADDRMAN_NEW_BUCKETS_PER_ADDRESS 8
     140             : 
     141             : //! how old addresses can maximally be
     142             : #define ADDRMAN_HORIZON_DAYS 30
     143             : 
     144             : //! after how many failed attempts we give up on a new node
     145             : #define ADDRMAN_RETRIES 3
     146             : 
     147             : //! how many successive failures are allowed ...
     148             : #define ADDRMAN_MAX_FAILURES 10
     149             : 
     150             : //! ... in at least this many days
     151             : #define ADDRMAN_MIN_FAIL_DAYS 7
     152             : 
     153             : //! how recent a successful connection should be before we allow an address to be evicted from tried
     154             : #define ADDRMAN_REPLACEMENT_HOURS 4
     155             : 
     156             : //! Convenience
     157             : #define ADDRMAN_TRIED_BUCKET_COUNT (1 << ADDRMAN_TRIED_BUCKET_COUNT_LOG2)
     158             : #define ADDRMAN_NEW_BUCKET_COUNT (1 << ADDRMAN_NEW_BUCKET_COUNT_LOG2)
     159             : #define ADDRMAN_BUCKET_SIZE (1 << ADDRMAN_BUCKET_SIZE_LOG2)
     160             : 
     161             : //! the maximum number of tried addr collisions to store
     162             : #define ADDRMAN_SET_TRIED_COLLISION_SIZE 10
     163             : 
     164             : //! the maximum time we'll spend trying to resolve a tried table collision, in seconds
     165             : static const int64_t ADDRMAN_TEST_WINDOW = 40*60; // 40 minutes
     166             : 
     167             : /**
     168             :  * Stochastical (IP) address manager
     169             :  */
     170             : class CAddrMan
     171             : {
     172             : friend class CAddrManTest;
     173             : protected:
     174             :     //! critical section to protect the inner data structures
     175             :     mutable RecursiveMutex cs;
     176             : 
     177             : private:
     178             :     //! last used nId
     179             :     int nIdCount GUARDED_BY(cs);
     180             : 
     181             :     //! table with information about all nIds
     182             :     std::map<int, CAddrInfo> mapInfo GUARDED_BY(cs);
     183             : 
     184             :     //! find an nId based on its network address
     185             :     std::map<CNetAddr, int> mapAddr GUARDED_BY(cs);
     186             : 
     187             :     //! randomly-ordered vector of all nIds
     188             :     std::vector<int> vRandom GUARDED_BY(cs);
     189             : 
     190             :     // number of "tried" entries
     191             :     int nTried GUARDED_BY(cs);
     192             : 
     193             :     //! list of "tried" buckets
     194             :     int vvTried[ADDRMAN_TRIED_BUCKET_COUNT][ADDRMAN_BUCKET_SIZE] GUARDED_BY(cs);
     195             : 
     196             :     //! number of (unique) "new" entries
     197             :     int nNew GUARDED_BY(cs);
     198             : 
     199             :     //! list of "new" buckets
     200             :     int vvNew[ADDRMAN_NEW_BUCKET_COUNT][ADDRMAN_BUCKET_SIZE] GUARDED_BY(cs);
     201             : 
     202             :     //! last time Good was called (memory only)
     203             :     int64_t nLastGood GUARDED_BY(cs);
     204             : 
     205             :     //! Holds addrs inserted into tried table that collide with existing entries. Test-before-evict discipline used to resolve these collisions.
     206             :     std::set<int> m_tried_collisions;
     207             : 
     208             : protected:
     209             :     //! secret key to randomize bucket select with
     210             :     uint256 nKey;
     211             : 
     212             :     //! Source of random numbers for randomization in inner loops
     213             :     FastRandomContext insecure_rand;
     214             : 
     215             :     //! Find an entry.
     216             :     CAddrInfo* Find(const CNetAddr& addr, int *pnId = nullptr) EXCLUSIVE_LOCKS_REQUIRED(cs);
     217             : 
     218             :     //! find an entry, creating it if necessary.
     219             :     //! nTime and nServices of the found node are updated, if necessary.
     220             :     CAddrInfo* Create(const CAddress &addr, const CNetAddr &addrSource, int *pnId = nullptr) EXCLUSIVE_LOCKS_REQUIRED(cs);
     221             : 
     222             :     //! Swap two elements in vRandom.
     223             :     void SwapRandom(unsigned int nRandomPos1, unsigned int nRandomPos2) EXCLUSIVE_LOCKS_REQUIRED(cs);
     224             : 
     225             :     //! Move an entry from the "new" table(s) to the "tried" table
     226             :     void MakeTried(CAddrInfo& info, int nId) EXCLUSIVE_LOCKS_REQUIRED(cs);
     227             : 
     228             :     //! Delete an entry. It must not be in tried, and have refcount 0.
     229             :     void Delete(int nId) EXCLUSIVE_LOCKS_REQUIRED(cs);
     230             : 
     231             :     //! Clear a position in a "new" table. This is the only place where entries are actually deleted.
     232             :     void ClearNew(int nUBucket, int nUBucketPos) EXCLUSIVE_LOCKS_REQUIRED(cs);
     233             : 
     234             :     //! Mark an entry "good", possibly moving it from "new" to "tried".
     235             :     void Good_(const CService &addr, bool test_before_evict, int64_t time) EXCLUSIVE_LOCKS_REQUIRED(cs);
     236             : 
     237             :     //! Add an entry to the "new" table.
     238             :     bool Add_(const CAddress &addr, const CNetAddr& source, int64_t nTimePenalty) EXCLUSIVE_LOCKS_REQUIRED(cs);
     239             : 
     240             :     //! Mark an entry as attempted to connect.
     241             :     void Attempt_(const CService &addr, bool fCountFailure, int64_t nTime) EXCLUSIVE_LOCKS_REQUIRED(cs);
     242             : 
     243             :     //! Select an address to connect to, if newOnly is set to true, only the new table is selected from.
     244             :     CAddrInfo Select_(bool newOnly) EXCLUSIVE_LOCKS_REQUIRED(cs);
     245             : 
     246             :     //! See if any to-be-evicted tried table entries have been tested and if so resolve the collisions.
     247             :     void ResolveCollisions_() EXCLUSIVE_LOCKS_REQUIRED(cs);
     248             : 
     249             :     //! Return a random to-be-evicted tried table address.
     250             :     CAddrInfo SelectTriedCollision_() EXCLUSIVE_LOCKS_REQUIRED(cs);
     251             : 
     252             : #ifdef DEBUG_ADDRMAN
     253             :     //! Perform consistency check. Returns an error code or zero.
     254             :     int Check_() EXCLUSIVE_LOCKS_REQUIRED(cs);
     255             : #endif
     256             : 
     257             :     //! Select several addresses at once.
     258             :     void GetAddr_(std::vector<CAddress> &vAddr, size_t max_addresses, size_t max_pct) EXCLUSIVE_LOCKS_REQUIRED(cs);
     259             : 
     260             :     //! Mark an entry as currently-connected-to.
     261             :     void Connected_(const CService &addr, int64_t nTime) EXCLUSIVE_LOCKS_REQUIRED(cs);
     262             : 
     263             :     //! Update an entry's service bits.
     264             :     void SetServices_(const CService &addr, ServiceFlags nServices) EXCLUSIVE_LOCKS_REQUIRED(cs);
     265             : 
     266             : public:
     267             :     // Compressed IP->ASN mapping, loaded from a file when a node starts.
     268             :     // Should be always empty if no file was provided.
     269             :     // This mapping is then used for bucketing nodes in Addrman.
     270             :     //
     271             :     // If asmap is provided, nodes will be bucketed by
     272             :     // AS they belong to, in order to make impossible for a node
     273             :     // to connect to several nodes hosted in a single AS.
     274             :     // This is done in response to Erebus attack, but also to generally
     275             :     // diversify the connections every node creates,
     276             :     // especially useful when a large fraction of nodes
     277             :     // operate under a couple of cloud providers.
     278             :     //
     279             :     // If a new asmap was provided, the existing records
     280             :     // would be re-bucketed accordingly.
     281             :     std::vector<bool> m_asmap;
     282             : 
     283             :     // Read asmap from provided binary file
     284             :     static std::vector<bool> DecodeAsmap(fs::path path);
     285             : 
     286             : 
     287             :     /**
     288             :      * serialized format:
     289             :      * * version byte (1 for pre-asmap files, 2 for files including asmap version)
     290             :      * * 0x20 + nKey (serialized as if it were a vector, for backward compatibility)
     291             :      * * nNew
     292             :      * * nTried
     293             :      * * number of "new" buckets XOR 2**30
     294             :      * * all nNew addrinfos in vvNew
     295             :      * * all nTried addrinfos in vvTried
     296             :      * * for each bucket:
     297             :      *   * number of elements
     298             :      *   * for each element: index
     299             :      *
     300             :      * 2**30 is xorred with the number of buckets to make addrman deserializer v0 detect it
     301             :      * as incompatible. This is necessary because it did not check the version number on
     302             :      * deserialization.
     303             :      *
     304             :      * Notice that vvTried, mapAddr and vVector are never encoded explicitly;
     305             :      * they are instead reconstructed from the other information.
     306             :      *
     307             :      * vvNew is serialized, but only used if ADDRMAN_UNKNOWN_BUCKET_COUNT didn't change,
     308             :      * otherwise it is reconstructed as well.
     309             :      *
     310             :      * This format is more complex, but significantly smaller (at most 1.5 MiB), and supports
     311             :      * changes to the ADDRMAN_ parameters without breaking the on-disk structure.
     312             :      *
     313             :      * We don't use SERIALIZE_METHODS since the serialization and deserialization code has
     314             :      * very little in common.
     315             :      */
     316             :     template<typename Stream>
     317        1604 :     void Serialize(Stream &s) const
     318             :     {
     319        1604 :         LOCK(cs);
     320             : 
     321        1604 :         unsigned char nVersion = 2;
     322        1604 :         s << nVersion;
     323        1604 :         s << ((unsigned char)32);
     324        1604 :         s << nKey;
     325        1604 :         s << nNew;
     326        1604 :         s << nTried;
     327             : 
     328        1604 :         int nUBuckets = ADDRMAN_NEW_BUCKET_COUNT ^ (1 << 30);
     329        1604 :         s << nUBuckets;
     330        1604 :         std::map<int, int> mapUnkIds;
     331             :         int nIds = 0;
     332       26491 :         for (const auto& entry : mapInfo) {
     333       24887 :             mapUnkIds[entry.first] = nIds;
     334       24887 :             const CAddrInfo &info = entry.second;
     335       24887 :             if (info.nRefCount) {
     336       24887 :                 assert(nIds != nNew); // this means nNew was wrong, oh ow
     337       24887 :                 s << info;
     338       24887 :                 nIds++;
     339       24887 :             }
     340           0 :         }
     341             :         nIds = 0;
     342       26491 :         for (const auto& entry : mapInfo) {
     343       24887 :             const CAddrInfo &info = entry.second;
     344       24887 :             if (info.fInTried) {
     345           0 :                 assert(nIds != nTried); // this means nTried was wrong, oh ow
     346           0 :                 s << info;
     347           0 :                 nIds++;
     348           0 :             }
     349           0 :         }
     350     1644100 :         for (int bucket = 0; bucket < ADDRMAN_NEW_BUCKET_COUNT; bucket++) {
     351     1642496 :             int nSize = 0;
     352   106762240 :             for (int i = 0; i < ADDRMAN_BUCKET_SIZE; i++) {
     353   105119744 :                 if (vvNew[bucket][i] != -1)
     354       24887 :                     nSize++;
     355             :             }
     356     1642496 :             s << nSize;
     357   106762240 :             for (int i = 0; i < ADDRMAN_BUCKET_SIZE; i++) {
     358   105119744 :                 if (vvNew[bucket][i] != -1) {
     359       24887 :                     int nIndex = mapUnkIds[vvNew[bucket][i]];
     360       24887 :                     s << nIndex;
     361       24887 :                 }
     362             :             }
     363     1642496 :         }
     364             :         // Store asmap version after bucket entries so that it
     365             :         // can be ignored by older clients for backward compatibility.
     366        1604 :         uint256 asmap_version;
     367        1604 :         if (m_asmap.size() != 0) {
     368          10 :             asmap_version = SerializeHash(m_asmap);
     369          10 :         }
     370        1604 :         s << asmap_version;
     371        1604 :     }
     372             : 
     373             :     template<typename Stream>
     374         196 :     void Unserialize(Stream& s)
     375             :     {
     376         196 :         LOCK(cs);
     377             : 
     378         196 :         Clear();
     379         196 :         unsigned char nVersion;
     380         196 :         s >> nVersion;
     381         196 :         unsigned char nKeySize;
     382         196 :         s >> nKeySize;
     383         196 :         if (nKeySize != 32) throw std::ios_base::failure("Incorrect keysize in addrman deserialization");
     384         196 :         s >> nKey;
     385         196 :         s >> nNew;
     386         196 :         s >> nTried;
     387         196 :         int nUBuckets = 0;
     388         196 :         s >> nUBuckets;
     389         196 :         if (nVersion != 0) {
     390         196 :             nUBuckets ^= (1 << 30);
     391         196 :         }
     392             : 
     393         196 :         if (nNew > ADDRMAN_NEW_BUCKET_COUNT * ADDRMAN_BUCKET_SIZE) {
     394           0 :             throw std::ios_base::failure("Corrupt CAddrMan serialization, nNew exceeds limit.");
     395             :         }
     396             : 
     397         196 :         if (nTried > ADDRMAN_TRIED_BUCKET_COUNT * ADDRMAN_BUCKET_SIZE) {
     398           0 :             throw std::ios_base::failure("Corrupt CAddrMan serialization, nTried exceeds limit.");
     399             :         }
     400             : 
     401             :         // Deserialize entries from the new table.
     402         211 :         for (int n = 0; n < nNew; n++) {
     403          15 :             CAddrInfo &info = mapInfo[n];
     404          15 :             s >> info;
     405          13 :             mapAddr[info] = n;
     406          13 :             info.nRandomPos = vRandom.size();
     407          13 :             vRandom.push_back(n);
     408             :         }
     409         194 :         nIdCount = nNew;
     410             : 
     411             :         // Deserialize entries from the tried table.
     412         194 :         int nLost = 0;
     413         194 :         for (int n = 0; n < nTried; n++) {
     414           0 :             CAddrInfo info;
     415           0 :             s >> info;
     416           0 :             int nKBucket = info.GetTriedBucket(nKey, m_asmap);
     417           0 :             int nKBucketPos = info.GetBucketPosition(nKey, false, nKBucket);
     418           0 :             if (vvTried[nKBucket][nKBucketPos] == -1) {
     419           0 :                 info.nRandomPos = vRandom.size();
     420           0 :                 info.fInTried = true;
     421           0 :                 vRandom.push_back(nIdCount);
     422           0 :                 mapInfo[nIdCount] = info;
     423           0 :                 mapAddr[info] = nIdCount;
     424           0 :                 vvTried[nKBucket][nKBucketPos] = nIdCount;
     425           0 :                 nIdCount++;
     426           0 :             } else {
     427           0 :                 nLost++;
     428             :             }
     429           0 :         }
     430         194 :         nTried -= nLost;
     431             : 
     432             :         // Store positions in the new table buckets to apply later (if possible).
     433         194 :         std::map<int, int> entryToBucket; // Represents which entry belonged to which bucket when serializing
     434             : 
     435      198850 :         for (int bucket = 0; bucket < nUBuckets; bucket++) {
     436      198656 :             int nSize = 0;
     437      198656 :             s >> nSize;
     438      198667 :             for (int n = 0; n < nSize; n++) {
     439          11 :                 int nIndex = 0;
     440          11 :                 s >> nIndex;
     441          11 :                 if (nIndex >= 0 && nIndex < nNew) {
     442          11 :                     entryToBucket[nIndex] = bucket;
     443          11 :                 }
     444          11 :             }
     445      198656 :         }
     446             : 
     447         194 :         uint256 supplied_asmap_version;
     448         194 :         if (m_asmap.size() != 0) {
     449           7 :             supplied_asmap_version = SerializeHash(m_asmap);
     450           7 :         }
     451         194 :         uint256 serialized_asmap_version;
     452         194 :         if (nVersion > 1) {
     453         194 :             s >> serialized_asmap_version;
     454             :         }
     455             : 
     456         205 :         for (int n = 0; n < nNew; n++) {
     457          11 :             CAddrInfo &info = mapInfo[n];
     458          11 :             int bucket = entryToBucket[n];
     459          11 :             int nUBucketPos = info.GetBucketPosition(nKey, true, bucket);
     460          22 :             if (nVersion == 2 && nUBuckets == ADDRMAN_NEW_BUCKET_COUNT && vvNew[bucket][nUBucketPos] == -1 &&
     461          11 :                 info.nRefCount < ADDRMAN_NEW_BUCKETS_PER_ADDRESS && serialized_asmap_version == supplied_asmap_version) {
     462             :                 // Bucketing has not changed, using existing bucket positions for the new table
     463           7 :                 vvNew[bucket][nUBucketPos] = n;
     464           7 :                 info.nRefCount++;
     465           7 :             } else {
     466             :                 // In case the new table data cannot be used (nVersion unknown, bucket count wrong or new asmap),
     467             :                 // try to give them a reference based on their primary source address.
     468           4 :                 LogPrint(BCLog::ADDRMAN, "Bucketing method was updated, re-bucketing addrman entries from disk\n");
     469           4 :                 bucket = info.GetNewBucket(nKey, m_asmap);
     470           4 :                 nUBucketPos = info.GetBucketPosition(nKey, true, bucket);
     471           4 :                 if (vvNew[bucket][nUBucketPos] == -1) {
     472           4 :                     vvNew[bucket][nUBucketPos] = n;
     473           4 :                     info.nRefCount++;
     474           4 :                 }
     475             :             }
     476           0 :         }
     477             : 
     478             :         // Prune new entries with refcount 0 (as a result of collisions).
     479         194 :         int nLostUnk = 0;
     480         205 :         for (std::map<int, CAddrInfo>::const_iterator it = mapInfo.begin(); it != mapInfo.end(); ) {
     481          11 :             if (it->second.fInTried == false && it->second.nRefCount == 0) {
     482           0 :                 std::map<int, CAddrInfo>::const_iterator itCopy = it++;
     483           0 :                 Delete(itCopy->first);
     484           0 :                 nLostUnk++;
     485           0 :             } else {
     486          11 :                 it++;
     487             :             }
     488             :         }
     489         194 :         if (nLost + nLostUnk > 0) {
     490           0 :             LogPrint(BCLog::ADDRMAN, "addrman lost %i new and %i tried addresses due to collisions\n", nLostUnk, nLost);
     491             :         }
     492             : 
     493         194 :         Check();
     494         196 :     }
     495             : 
     496        1160 :     void Clear()
     497             :     {
     498        1160 :         LOCK(cs);
     499        1160 :         std::vector<int>().swap(vRandom);
     500        1160 :         nKey = insecure_rand.rand256();
     501     1189000 :         for (size_t bucket = 0; bucket < ADDRMAN_NEW_BUCKET_COUNT; bucket++) {
     502    77209600 :             for (size_t entry = 0; entry < ADDRMAN_BUCKET_SIZE; entry++) {
     503    76021760 :                 vvNew[bucket][entry] = -1;
     504             :             }
     505             :         }
     506      298120 :         for (size_t bucket = 0; bucket < ADDRMAN_TRIED_BUCKET_COUNT; bucket++) {
     507    19302400 :             for (size_t entry = 0; entry < ADDRMAN_BUCKET_SIZE; entry++) {
     508    19005440 :                 vvTried[bucket][entry] = -1;
     509             :             }
     510             :         }
     511             : 
     512        1160 :         nIdCount = 0;
     513        1160 :         nTried = 0;
     514        1160 :         nNew = 0;
     515        1160 :         nLastGood = 1; //Initially at 1 so that "never" is strictly worse.
     516        1160 :         mapInfo.clear();
     517        1160 :         mapAddr.clear();
     518        1160 :     }
     519             : 
     520        1265 :     CAddrMan()
     521         622 :     {
     522         643 :         Clear();
     523        1265 :     }
     524             : 
     525        1265 :     ~CAddrMan()
     526         622 :     {
     527         643 :         nKey.SetNull();
     528        1265 :     }
     529             : 
     530             :     //! Return the number of (unique) addresses in all tables.
     531       52620 :     size_t size() const
     532             :     {
     533       52620 :         LOCK(cs); // TODO: Cache this in an atomic to avoid this overhead
     534       52620 :         return vRandom.size();
     535       52620 :     }
     536             : 
     537             :     //! Consistency check
     538      190090 :     void Check()
     539             :     {
     540             : #ifdef DEBUG_ADDRMAN
     541             :         {
     542             :             LOCK(cs);
     543             :             int err;
     544             :             if ((err=Check_()))
     545             :                 LogPrintf("ADDRMAN CONSISTENCY CHECK FAILED!!! err=%i\n", err);
     546             :         }
     547             : #endif
     548      190090 :     }
     549             : 
     550             :     //! Add a single address.
     551        2255 :     bool Add(const CAddress &addr, const CNetAddr& source, int64_t nTimePenalty = 0)
     552             :     {
     553        2255 :         LOCK(cs);
     554             :         bool fRet = false;
     555        2255 :         Check();
     556        2255 :         fRet |= Add_(addr, source, nTimePenalty);
     557        2255 :         Check();
     558        2255 :         if (fRet) {
     559        2226 :             LogPrint(BCLog::ADDRMAN, "Added %s from %s: %i tried, %i new\n", addr.ToStringIPPort(), source.ToString(), nTried, nNew);
     560             :         }
     561             :         return fRet;
     562        2255 :     }
     563             : 
     564             :     //! Add multiple addresses.
     565       11230 :     bool Add(const std::vector<CAddress> &vAddr, const CNetAddr& source, int64_t nTimePenalty = 0)
     566             :     {
     567       11230 :         LOCK(cs);
     568       11230 :         int nAdd = 0;
     569       11230 :         Check();
     570      326157 :         for (std::vector<CAddress>::const_iterator it = vAddr.begin(); it != vAddr.end(); it++)
     571      314927 :             nAdd += Add_(*it, source, nTimePenalty) ? 1 : 0;
     572       11230 :         Check();
     573       11230 :         if (nAdd) {
     574       10652 :             LogPrint(BCLog::ADDRMAN, "Added %i addresses from %s: %i tried, %i new\n", nAdd, source.ToString(), nTried, nNew);
     575             :         }
     576       11230 :         return nAdd > 0;
     577       11230 :     }
     578             : 
     579             :     //! Mark an entry as accessible.
     580        3242 :     void Good(const CService &addr, bool test_before_evict = true, int64_t nTime = GetAdjustedTime())
     581             :     {
     582        3242 :         LOCK(cs);
     583        3242 :         Check();
     584        3242 :         Good_(addr, test_before_evict, nTime);
     585        3242 :         Check();
     586        3242 :     }
     587             : 
     588             :     //! Mark an entry as connection attempted to.
     589         253 :     void Attempt(const CService &addr, bool fCountFailure, int64_t nTime = GetAdjustedTime())
     590             :     {
     591         253 :         LOCK(cs);
     592         253 :         Check();
     593         253 :         Attempt_(addr, fCountFailure, nTime);
     594         253 :         Check();
     595         253 :     }
     596             : 
     597             :     //! See if any to-be-evicted tried table entries have been tested and if so resolve the collisions.
     598       25467 :     void ResolveCollisions()
     599             :     {
     600       25467 :         LOCK(cs);
     601       25467 :         Check();
     602       25467 :         ResolveCollisions_();
     603       25467 :         Check();
     604       25467 :     }
     605             : 
     606             :     //! Randomly select an address in tried that another address is attempting to evict.
     607       25884 :     CAddrInfo SelectTriedCollision()
     608             :     {
     609       25884 :         CAddrInfo ret;
     610             :         {
     611       25884 :             LOCK(cs);
     612       25884 :             Check();
     613       25884 :             ret = SelectTriedCollision_();
     614       25884 :             Check();
     615       25884 :         }
     616             :         return ret;
     617       25884 :     }
     618             : 
     619             :     /**
     620             :      * Choose an address to connect to.
     621             :      */
     622       25935 :     CAddrInfo Select(bool newOnly = false)
     623             :     {
     624       25935 :         CAddrInfo addrRet;
     625             :         {
     626       25935 :             LOCK(cs);
     627       25935 :             Check();
     628       25935 :             addrRet = Select_(newOnly);
     629       25935 :             Check();
     630       25935 :         }
     631             :         return addrRet;
     632       25935 :     }
     633             : 
     634             :     //! Return a bunch of addresses, selected at random.
     635         207 :     std::vector<CAddress> GetAddr(size_t max_addresses, size_t max_pct)
     636             :     {
     637         207 :         Check();
     638         207 :         std::vector<CAddress> vAddr;
     639             :         {
     640         207 :             LOCK(cs);
     641         207 :             GetAddr_(vAddr, max_addresses, max_pct);
     642         207 :         }
     643         207 :         Check();
     644             :         return vAddr;
     645         207 :     }
     646             : 
     647             :     //! Mark an entry as currently-connected-to.
     648         237 :     void Connected(const CService &addr, int64_t nTime = GetAdjustedTime())
     649             :     {
     650         237 :         LOCK(cs);
     651         237 :         Check();
     652         237 :         Connected_(addr, nTime);
     653         237 :         Check();
     654         237 :     }
     655             : 
     656         238 :     void SetServices(const CService &addr, ServiceFlags nServices)
     657             :     {
     658         238 :         LOCK(cs);
     659         238 :         Check();
     660         238 :         SetServices_(addr, nServices);
     661         238 :         Check();
     662         238 :     }
     663             : 
     664             : };
     665             : 
     666             : #endif // BITCOIN_ADDRMAN_H

Generated by: LCOV version 1.15