6#include <bitcoin-build-config.h>
75 if (
nTime > now + 10min) {
113 , m_netgroupman{netgroupman}
115 for (
auto& bucket :
vvNew) {
116 for (
auto& entry : bucket) {
121 for (
auto& entry : bucket) {
132template <
typename Stream>
191 std::unordered_map<nid_type, int>
mapUnkIds;
193 for (
const auto& entry :
mapInfo) {
195 const AddrInfo& info = entry.second;
203 for (
const auto& entry :
mapInfo) {
204 const AddrInfo& info = entry.second;
214 if (
vvNew[bucket][i] != -1)
219 if (
vvNew[bucket][i] != -1) {
230template <
typename Stream>
247 "Corrupted addrman database: The compat value (%u) "
248 "is lower than the expected minimum value %u.",
254 "Unsupported format of addrman database: %u. It is compatible with formats >=%u, "
255 "but the maximum supported by this version of %s is %u.",
269 throw std::ios_base::failure(
270 strprintf(
"Corrupt AddrMan serialization: nNew=%d, should be in [0, %d]",
276 throw std::ios_base::failure(
277 strprintf(
"Corrupt AddrMan serialization: nTried=%d, should be in [0, %d]",
283 for (
int n = 0; n <
nNew; n++) {
295 for (
int n = 0; n <
nTried; n++) {
321 for (
int bucket = 0; bucket <
nUBuckets; ++bucket) {
381 if (it->second.fInTried ==
false && it->second.nRefCount == 0) {
396 "Corrupt data. Consistency check failed with code %s",
405 const auto it =
mapAddr.find(addr);
409 *
pnId = (*it).second;
412 return &(*it2).second;
501 vvNew[bucket][pos] = -1;
590 if (
pinfo->nRefCount > 0) {
618 if (
pinfo->nRefCount == 0) {
637 if (!
pinfo)
return false;
684 for (std::vector<CAddress>::const_iterator it =
vAddr.begin(); it !=
vAddr.end(); it++) {
717 if (
vRandom.empty())
return {};
801 return vvTried[bucket][position];
805 return vvNew[bucket][position];
830 for (
unsigned int n = 0; n <
vRandom.size(); n++) {
842 if (network != std::nullopt &&
ai.GetNetClass() != network)
continue;
858 std::vector<std::pair<AddrInfo, AddressPosition>>
infos;
1030 if (!
net.has_value()) {
1031 if (
in_new.has_value()) {
1039 if (
in_new.has_value()) {
1058 LogError(
"ADDRMAN CONSISTENCY CHECK FAILED!!! err=%i", err);
1070 std::unordered_set<nid_type>
setTried;
1071 std::unordered_map<nid_type, int>
mapNew;
1072 std::unordered_map<Network, NewTriedCount>
local_counts;
1077 for (
const auto& entry :
mapInfo) {
1079 const AddrInfo& info = entry.second;
1096 const auto it{
mapAddr.find(info)};
1097 if (it ==
mapAddr.end() || it->second != n) {
1121 if (it ==
mapInfo.end() || it->second.GetTriedBucket(nKey, m_netgroupman) != n) {
1124 if (it->second.GetBucketPosition(nKey,
false, n) != i) {
1134 if (
vvNew[n][i] != -1) {
1138 if (it ==
mapInfo.end() || it->second.GetBucketPosition(nKey,
true, n) != i) {
1190 auto ret =
Good_(addr,
true, time);
1277template <
typename Stream>
1283template <
typename Stream>
1309 return m_impl->Good(addr, time);
1319 m_impl->ResolveCollisions();
1324 return m_impl->SelectTriedCollision();
1344 m_impl->Connected(addr, time);
1349 m_impl->SetServices(addr, nServices);
1354 return m_impl->FindAddressEntry(addr);
static constexpr uint32_t ADDRMAN_NEW_BUCKETS_PER_SOURCE_GROUP
Over how many buckets entries with new addresses originating from a single group are spread.
static constexpr auto ADDRMAN_HORIZON
How old addresses can maximally be.
static constexpr int32_t ADDRMAN_MAX_FAILURES
How many successive failures are allowed ...
static constexpr auto ADDRMAN_MIN_FAIL
... in at least this duration
static constexpr auto ADDRMAN_TEST_WINDOW
The maximum time we'll spend trying to resolve a tried table collision.
static constexpr auto ADDRMAN_REPLACEMENT
How recent a successful connection should be before we allow an address to be evicted from tried.
static constexpr int32_t ADDRMAN_RETRIES
After how many failed attempts we give up on a new node.
static constexpr size_t ADDRMAN_SET_TRIED_COLLISION_SIZE
The maximum number of tried addr collisions to store.
static constexpr uint32_t ADDRMAN_TRIED_BUCKETS_PER_GROUP
Over how many buckets entries with tried addresses from a single group (/16 for IPv4) are spread.
static constexpr int32_t ADDRMAN_NEW_BUCKETS_PER_ADDRESS
Maximum number of times an address can occur in the new table.
static constexpr int ADDRMAN_TRIED_BUCKET_COUNT
static constexpr int ADDRMAN_BUCKET_SIZE
int64_t nid_type
User-defined type for the internally used nIds This used to be int, making it feasible for attackers ...
static constexpr int ADDRMAN_NEW_BUCKET_COUNT
#define Assume(val)
Assume is the identity function.
Extended statistics about a CAddress.
int GetNewBucket(const uint256 &nKey, const CNetAddr &src, const NetGroupManager &netgroupman) const
Calculate in which "new" bucket this entry belongs, given a certain source.
int GetTriedBucket(const uint256 &nKey, const NetGroupManager &netgroupman) const
Calculate in which "tried" bucket this entry belongs.
int nRandomPos
position in vRandom
int GetBucketPosition(const uint256 &nKey, bool fNew, int bucket) const
Calculate in which position of a bucket to store this entry.
bool fInTried
in tried set? (memory only)
NodeSeconds m_last_success
last successful connection by us
NodeSeconds m_last_count_attempt
last counted attempt (memory only)
NodeSeconds m_last_try
last try whatsoever by us (memory only)
double GetChance(NodeSeconds now=Now< NodeSeconds >()) const
Calculate the relative chance this entry should be given when selecting nodes to connect to.
bool IsTerrible(NodeSeconds now=Now< NodeSeconds >()) const
Determine whether the statistics about this entry are bad enough so that it can just be deleted.
int nRefCount
reference count in new sets (memory only)
int nAttempts
connection attempts since last successful attempt
void Connected(const CService &addr, NodeSeconds time=Now< NodeSeconds >())
We have successfully connected to this peer.
std::pair< CAddress, NodeSeconds > Select(bool new_only=false, const std::unordered_set< Network > &networks={}) const
Choose an address to connect to.
const std::unique_ptr< AddrManImpl > m_impl
void Attempt(const CService &addr, bool fCountFailure, NodeSeconds time=Now< NodeSeconds >())
Mark an entry as connection attempted to.
size_t Size(std::optional< Network > net=std::nullopt, std::optional< bool > in_new=std::nullopt) const
Return size information about addrman.
std::optional< AddressPosition > FindAddressEntry(const CAddress &addr)
Test-only function Find the address record in AddrMan and return information about its position.
std::vector< std::pair< AddrInfo, AddressPosition > > GetEntries(bool from_tried) const
Returns an information-location pair for all addresses in the selected addrman table.
std::vector< CAddress > GetAddr(size_t max_addresses, size_t max_pct, std::optional< Network > network, bool filtered=true) const
Return all or many randomly selected addresses, optionally by network.
void ResolveCollisions()
See if any to-be-evicted tried table entries have been tested and if so resolve the collisions.
bool Good(const CService &addr, NodeSeconds time=Now< NodeSeconds >())
Mark an address record as accessible and attempt to move it to addrman's tried table.
void Serialize(Stream &s_) const
void Unserialize(Stream &s_)
AddrMan(const NetGroupManager &netgroupman, bool deterministic, int32_t consistency_check_ratio)
std::pair< CAddress, NodeSeconds > SelectTriedCollision()
Randomly select an address in the tried table that another address is attempting to evict.
bool Add(const std::vector< CAddress > &vAddr, const CNetAddr &source, std::chrono::seconds time_penalty=0s)
Attempt to add one or more addresses to addrman's new table.
void SetServices(const CService &addr, ServiceFlags nServices)
Update an entry's service bits.
void ClearNew(int nUBucket, int nUBucketPos) EXCLUSIVE_LOCKS_REQUIRED(cs)
Clear a position in a "new" table. This is the only place where entries are actually deleted.
AddrInfo * Create(const CAddress &addr, const CNetAddr &addrSource, nid_type *pnId=nullptr) EXCLUSIVE_LOCKS_REQUIRED(cs)
Create a new entry and add it to the internal data structures mapInfo, mapAddr and vRandom.
void Connected_(const CService &addr, NodeSeconds time) EXCLUSIVE_LOCKS_REQUIRED(cs)
void Attempt_(const CService &addr, bool fCountFailure, NodeSeconds time) EXCLUSIVE_LOCKS_REQUIRED(cs)
static constexpr Format FILE_FORMAT
The maximum format this software knows it can unserialize.
void ResolveCollisions_() EXCLUSIVE_LOCKS_REQUIRED(cs)
std::vector< CAddress > GetAddr(size_t max_addresses, size_t max_pct, std::optional< Network > network, bool filtered=true) const EXCLUSIVE_LOCKS_REQUIRED(!cs)
@ V4_MULTIPORT
adds support for multiple ports per IP
@ V3_BIP155
same as V2_ASMAP plus addresses are in BIP155 format
@ V2_ASMAP
for files including asmap version
@ V1_DETERMINISTIC
for pre-asmap files
void Serialize(Stream &s_) const EXCLUSIVE_LOCKS_REQUIRED(!cs)
void Delete(nid_type nId) EXCLUSIVE_LOCKS_REQUIRED(cs)
Delete an entry. It must not be in tried, and have refcount 0.
std::pair< CAddress, NodeSeconds > Select_(bool new_only, const std::unordered_set< Network > &networks) const EXCLUSIVE_LOCKS_REQUIRED(cs)
void Connected(const CService &addr, NodeSeconds time) EXCLUSIVE_LOCKS_REQUIRED(!cs)
void SetServices(const CService &addr, ServiceFlags nServices) EXCLUSIVE_LOCKS_REQUIRED(!cs)
std::optional< AddressPosition > FindAddressEntry_(const CAddress &addr) EXCLUSIVE_LOCKS_REQUIRED(cs)
void MakeTried(AddrInfo &info, nid_type nId) EXCLUSIVE_LOCKS_REQUIRED(cs)
Move an entry from the "new" table(s) to the "tried" table.
void SetServices_(const CService &addr, ServiceFlags nServices) EXCLUSIVE_LOCKS_REQUIRED(cs)
AddrInfo * Find(const CService &addr, nid_type *pnId=nullptr) EXCLUSIVE_LOCKS_REQUIRED(cs)
Find an entry.
AddrManImpl(const NetGroupManager &netgroupman, bool deterministic, int32_t consistency_check_ratio)
std::vector< std::pair< AddrInfo, AddressPosition > > GetEntries(bool from_tried) const EXCLUSIVE_LOCKS_REQUIRED(!cs)
const int32_t m_consistency_check_ratio
Perform consistency checks every m_consistency_check_ratio operations (if non-zero).
std::vector< std::pair< AddrInfo, AddressPosition > > GetEntries_(bool from_tried) const EXCLUSIVE_LOCKS_REQUIRED(cs)
void Check() const EXCLUSIVE_LOCKS_REQUIRED(cs)
Consistency check, taking into account m_consistency_check_ratio.
int CheckAddrman() const EXCLUSIVE_LOCKS_REQUIRED(cs)
Perform consistency check, regardless of m_consistency_check_ratio.
bool Add(const std::vector< CAddress > &vAddr, const CNetAddr &source, std::chrono::seconds time_penalty) EXCLUSIVE_LOCKS_REQUIRED(!cs)
std::optional< AddressPosition > FindAddressEntry(const CAddress &addr) EXCLUSIVE_LOCKS_REQUIRED(!cs)
bool Good_(const CService &addr, bool test_before_evict, NodeSeconds time) EXCLUSIVE_LOCKS_REQUIRED(cs)
std::vector< CAddress > GetAddr_(size_t max_addresses, size_t max_pct, std::optional< Network > network, bool filtered=true) const EXCLUSIVE_LOCKS_REQUIRED(cs)
Mutex cs
A mutex to protect the inner data structures.
size_t Size_(std::optional< Network > net, std::optional< bool > in_new) const EXCLUSIVE_LOCKS_REQUIRED(cs)
std::pair< CAddress, NodeSeconds > SelectTriedCollision_() EXCLUSIVE_LOCKS_REQUIRED(cs)
std::pair< CAddress, NodeSeconds > SelectTriedCollision() EXCLUSIVE_LOCKS_REQUIRED(!cs)
std::set< nid_type > m_tried_collisions
Holds addrs inserted into tried table that collide with existing entries. Test-before-evict disciplin...
static constexpr uint8_t INCOMPATIBILITY_BASE
The initial value of a field that is incremented every time an incompatible format change is made (su...
void SwapRandom(unsigned int nRandomPos1, unsigned int nRandomPos2) const EXCLUSIVE_LOCKS_REQUIRED(cs)
Swap two elements in vRandom.
std::pair< CAddress, NodeSeconds > Select(bool new_only, const std::unordered_set< Network > &networks) const EXCLUSIVE_LOCKS_REQUIRED(!cs)
void Attempt(const CService &addr, bool fCountFailure, NodeSeconds time) EXCLUSIVE_LOCKS_REQUIRED(!cs)
void Unserialize(Stream &s_) EXCLUSIVE_LOCKS_REQUIRED(!cs)
nid_type GetEntry(bool use_tried, size_t bucket, size_t position) const EXCLUSIVE_LOCKS_REQUIRED(cs)
Helper to generalize looking up an addrman entry from either table.
uint256 nKey
secret key to randomize bucket select with
void ResolveCollisions() EXCLUSIVE_LOCKS_REQUIRED(!cs)
const NetGroupManager & m_netgroupman
Reference to the netgroup manager.
bool Add_(const std::vector< CAddress > &vAddr, const CNetAddr &source, std::chrono::seconds time_penalty) EXCLUSIVE_LOCKS_REQUIRED(cs)
bool Good(const CService &addr, NodeSeconds time) EXCLUSIVE_LOCKS_REQUIRED(!cs)
size_t Size(std::optional< Network > net, std::optional< bool > in_new) const EXCLUSIVE_LOCKS_REQUIRED(!cs)
bool AddSingle(const CAddress &addr, const CNetAddr &source, std::chrono::seconds time_penalty) EXCLUSIVE_LOCKS_REQUIRED(cs)
Attempt to add a single address to addrman's new table.
Non-refcounted RAII wrapper for FILE*.
A CService with information about it as peer.
ServiceFlags nServices
Serialized as uint64_t in V1, and as CompactSize in V2.
NodeSeconds nTime
Always included in serialization. The behavior is unspecified if the value is not representable as ui...
static constexpr SerParams V1_DISK
static constexpr SerParams V2_DISK
enum Network GetNetwork() const
A combination of a network address (CNetAddr) and a (TCP) port.
std::string ToStringAddrPort() const
std::vector< unsigned char > GetKey() const
Double ended buffer combining vector and stream-like interfaces.
Reads data from an underlying stream, while hashing the read data.
A writer stream (for serialization) that computes a 256-bit hash.
Writes data to an underlying source stream, while hashing the written data.
uint256 GetAsmapVersion() const
Get the asmap version, a checksum identifying the asmap being used.
std::vector< unsigned char > GetGroup(const CNetAddr &address) const
Get the canonical identifier of the network group for address.
uint32_t GetMappedAS(const CNetAddr &address) const
Get the autonomous system on the BGP path to address.
Wrapper that overrides the GetParams() function of a stream.
#define LogDebug(category,...)
ServiceFlags
nServices flags
Location information for an address in AddrMan.
static time_point now() noexcept
Return current system time or mocked time, if set.
#define AssertLockHeld(cs)
#define LOG_TIME_MILLIS_WITH_CATEGORY_MSG_ONCE(end_msg, log_category)
std::chrono::time_point< NodeClock, std::chrono::seconds > NodeSeconds
constexpr auto Ticks(Dur2 d)
Helper to count the seconds of a duration/time_point.