LCOV - code coverage report
Current view: top level - src - addrman.h (source / functions) Hit Total Coverage
Test: test_dash_coverage.info Lines: 5 8 62.5 %
Date: 2026-06-25 07:23:51 Functions: 3 14 21.4 %

          Line data    Source code
       1             : // Copyright (c) 2012 Pieter Wuille
       2             : // Copyright (c) 2012-2021 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 <netaddress.h>
      10             : #include <netgroup.h>
      11             : #include <protocol.h>
      12             : #include <streams.h>
      13             : #include <util/time.h>
      14             : 
      15             : #include <cstdint>
      16             : #include <memory>
      17             : #include <optional>
      18             : #include <utility>
      19             : #include <vector>
      20             : 
      21             : class DbInconsistentError : public std::exception
      22             : {
      23             :     using std::exception::exception;
      24             :     const std::string error;
      25             : 
      26             : public:
      27           0 :     explicit DbInconsistentError(const std::string _error) : error{_error} {}
      28           0 :     const char* what() const noexcept override { return error.c_str(); }
      29             : };
      30             : 
      31             : class InvalidAddrManVersionError : public std::ios_base::failure
      32             : {
      33             : public:
      34           0 :     InvalidAddrManVersionError(std::string msg) : std::ios_base::failure(msg) { }
      35             : };
      36             : 
      37             : class AddrInfo;
      38             : class AddrManImpl;
      39             : 
      40             : /** Default for -checkaddrman */
      41             : static constexpr int32_t DEFAULT_ADDRMAN_CONSISTENCY_CHECKS{0};
      42             : 
      43             : /** Test-only struct, capturing info about an address in AddrMan */
      44             : struct AddressPosition {
      45             :     // Whether the address is in the new or tried table
      46             :     const bool tried;
      47             : 
      48             :     // Addresses in the tried table should always have a multiplicity of 1.
      49             :     // Addresses in the new table can have multiplicity between 1 and
      50             :     // ADDRMAN_NEW_BUCKETS_PER_ADDRESS
      51             :     const int multiplicity;
      52             : 
      53             :     // If the address is in the new table, the bucket and position are
      54             :     // populated based on the first source who sent the address.
      55             :     // In certain edge cases, this may not be where the address is currently
      56             :     // located.
      57             :     const int bucket;
      58             :     const int position;
      59             : 
      60           2 :     bool operator==(AddressPosition other) {
      61           4 :         return std::tie(tried, multiplicity, bucket, position) ==
      62           2 :                std::tie(other.tried, other.multiplicity, other.bucket, other.position);
      63             :     }
      64          26 :     explicit AddressPosition(bool tried_in, int multiplicity_in, int bucket_in, int position_in)
      65          26 :         : tried{tried_in}, multiplicity{multiplicity_in}, bucket{bucket_in}, position{position_in} {}
      66             : };
      67             : 
      68             : /** Stochastic address manager
      69             :  *
      70             :  * Design goals:
      71             :  *  * Keep the address tables in-memory, and asynchronously dump the entire table to peers.dat.
      72             :  *  * Make sure no (localized) attacker can fill the entire table with his nodes/addresses.
      73             :  *
      74             :  * To that end:
      75             :  *  * Addresses are organized into buckets that can each store up to 64 entries.
      76             :  *    * Addresses to which our node has not successfully connected go into 1024 "new" buckets.
      77             :  *      * Based on the address range (/16 for IPv4) of the source of information, or if an asmap is provided,
      78             :  *        the AS it belongs to (for IPv4/IPv6), 64 buckets are selected at random.
      79             :  *      * The actual bucket is chosen from one of these, based on the range in which the address itself is located.
      80             :  *      * The position in the bucket is chosen based on the full address.
      81             :  *      * One single address can occur in up to 8 different buckets to increase selection chances for addresses that
      82             :  *        are seen frequently. The chance for increasing this multiplicity decreases exponentially.
      83             :  *      * When adding a new address to an occupied position of a bucket, it will not replace the existing entry
      84             :  *        unless that address is also stored in another bucket or it doesn't meet one of several quality criteria
      85             :  *        (see IsTerrible for exact criteria).
      86             :  *    * Addresses of nodes that are known to be accessible go into 256 "tried" buckets.
      87             :  *      * Each address range selects at random 8 of these buckets.
      88             :  *      * The actual bucket is chosen from one of these, based on the full address.
      89             :  *      * When adding a new good address to an occupied position of a bucket, a FEELER connection to the
      90             :  *        old address is attempted. The old entry is only replaced and moved back to the "new" buckets if this
      91             :  *        attempt was unsuccessful.
      92             :  *    * Bucket selection is based on cryptographic hashing, using a randomly-generated 256-bit key, which should not
      93             :  *      be observable by adversaries.
      94             :  *    * Several indexes are kept for high performance. Setting m_consistency_check_ratio with the -checkaddrman
      95             :  *      configuration option will introduce (expensive) consistency checks for the entire data structure.
      96             :  */
      97             : class AddrMan
      98             : {
      99             : protected:
     100             :     const std::unique_ptr<AddrManImpl> m_impl;
     101             : 
     102             : public:
     103             :     explicit AddrMan(const NetGroupManager& netgroupman, bool deterministic, int32_t consistency_check_ratio);
     104             : 
     105             :     ~AddrMan();
     106             : 
     107             :     template <typename Stream>
     108             :     void Serialize(Stream& s_) const;
     109             : 
     110             :     template <typename Stream>
     111             :     void Unserialize(Stream& s_);
     112             : 
     113             :     /**
     114             :     * Return size information about addrman.
     115             :     *
     116             :     * @param[in] net              Select addresses only from specified network (nullopt = all)
     117             :     * @param[in] in_new           Select addresses only from one table (true = new, false = tried, nullopt = both)
     118             :     * @return                     Number of unique addresses that match specified options.
     119             :     */
     120             :     size_t Size(std::optional<Network> net = std::nullopt, std::optional<bool> in_new = std::nullopt) const;
     121             : 
     122             :     /**
     123             :      * Attempt to add one or more addresses to addrman's new table.
     124             :      * If an address already exists in addrman, the existing entry may be updated
     125             :      * (e.g. adding additional service flags). If the existing entry is in the new table,
     126             :      * it may be added to more buckets, improving the probability of selection.
     127             :      *
     128             :      * @param[in] vAddr           Address records to attempt to add.
     129             :      * @param[in] source          The address of the node that sent us these addr records.
     130             :      * @param[in] time_penalty    A "time penalty" to apply to the address record's nTime. If a peer
     131             :      *                            sends us an address record with nTime=n, then we'll add it to our
     132             :      *                            addrman with nTime=(n - time_penalty).
     133             :      * @return    true if at least one address is successfully added, or added to an additional bucket. Unaffected by updates. */
     134             :     bool Add(const std::vector<CAddress>& vAddr, const CNetAddr& source, std::chrono::seconds time_penalty = 0s);
     135             : 
     136             :     /**
     137             :      * Mark an address record as accessible and attempt to move it to addrman's tried table.
     138             :      *
     139             :      * @param[in] addr            Address record to attempt to move to tried table.
     140             :      * @param[in] time            The time that we were last connected to this peer.
     141             :      * @return    true if the address is successfully moved from the new table to the tried table.
     142             :      */
     143             :     bool Good(const CService& addr, NodeSeconds time = Now<NodeSeconds>());
     144             : 
     145             :     //! Mark an entry as connection attempted to.
     146             :     void Attempt(const CService& addr, bool fCountFailure, NodeSeconds time = Now<NodeSeconds>());
     147             : 
     148             :     //! See if any to-be-evicted tried table entries have been tested and if so resolve the collisions.
     149             :     void ResolveCollisions();
     150             : 
     151             :     /**
     152             :      * Randomly select an address in the tried table that another address is
     153             :      * attempting to evict.
     154             :      *
     155             :      * @return CAddress The record for the selected tried peer.
     156             :      *         seconds  The last time we attempted to connect to that peer.
     157             :      */
     158             :     std::pair<CAddress, NodeSeconds> SelectTriedCollision();
     159             : 
     160             :     /**
     161             :      * Choose an address to connect to.
     162             :      *
     163             :      * @param[in] new_only Whether to only select addresses from the new table. Passing `true` returns
     164             :      *                     an address from the new table or an empty pair. Passing `false` will return an
     165             :      *                     empty pair or an address from either the new or tried table (it does not
     166             :      *                     guarantee a tried entry).
     167             :      * @param[in] network  Select only addresses of this network (nullopt = all). Passing a network may
     168             :      *                     slow down the search.
     169             :      * @return    CAddress The record for the selected peer.
     170             :      *            seconds  The last time we attempted to connect to that peer.
     171             :      */
     172             :     std::pair<CAddress, NodeSeconds> Select(bool new_only = false, std::optional<Network> network = std::nullopt) const;
     173             : 
     174             :     /**
     175             :      * Return all or many randomly selected addresses, optionally by network.
     176             :      *
     177             :      * @param[in] max_addresses  Maximum number of addresses to return (0 = all).
     178             :      * @param[in] max_pct        Maximum percentage of addresses to return (0 = all).
     179             :      * @param[in] network        Select only addresses of this network (nullopt = all).
     180             :      * @param[in] filtered       Select only addresses that are considered good quality (false = all).
     181             :      *
     182             :      * @return                   A vector of randomly selected addresses from vRandom.
     183             :      */
     184             :     std::vector<CAddress> GetAddr(size_t max_addresses, size_t max_pct, std::optional<Network> network, const bool filtered = true) const;
     185             : 
     186             :     /** We have successfully connected to this peer. Calling this function
     187             :      *  updates the CAddress's nTime, which is used in our IsTerrible()
     188             :      *  decisions and gossiped to peers. Callers should be careful that updating
     189             :      *  this information doesn't leak topology information to network spies.
     190             :      *
     191             :      *  net_processing calls this function when it *disconnects* from a peer to
     192             :      *  not leak information about currently connected peers.
     193             :      *
     194             :      * @param[in]   addr     The address of the peer we were connected to
     195             :      * @param[in]   time     The time that we were last connected to this peer
     196             :      */
     197             :     void Connected(const CService& addr, NodeSeconds time = Now<NodeSeconds>());
     198             : 
     199             :     //! Update an entry's service bits.
     200             :     void SetServices(const CService& addr, ServiceFlags nServices);
     201             : 
     202             :     //! See if any to-be-evicted tried table entries have been tested and if so resolve the collisions.
     203             :     AddrInfo GetAddressInfo(const CService& addr);
     204             : 
     205             :     /** Test-only function
     206             :      * Find the address record in AddrMan and return information about its
     207             :      * position.
     208             :      * @param[in] addr       The address record to look up.
     209             :      * @return               Information about the address record in AddrMan
     210             :      *                       or nullopt if address is not found.
     211             :      */
     212             :     std::optional<AddressPosition> FindAddressEntry(const CAddress& addr);
     213             : };
     214             : 
     215             : #endif // BITCOIN_ADDRMAN_H

Generated by: LCOV version 1.16