btclib_node.p2p package

Subpackages

Submodules

btclib_node.p2p.address module

Where a peer is, and the table of the ones this node knows of.

The address itself is btclib’s, and btclib.p2p.addrv2.NetworkAddressV2 is the one this node holds a peer in: BIP155’s record is the only encoding that carries every network a peer can be on, so the narrower addr entry would lose an onion peer the moment one is gossiped. The translation between the two is btclib’s as well – btclib.p2p.addrv2.addr_entry and peer_from_addr_entry – for what goes on the wire wherever the peer has not asked for BIP155.

What is left here is what btclib has no business holding: dialling a socket, and the table of addresses to dial. btclib is a codec – it speaks to nobody – so the question “can this be connected to” and the answer to it are this node’s.

class btclib_node.p2p.address.AddrResponseCache(sample: list[NetworkAddressV2] = <factory>, expiration: float = 0.0)[source]

Bases: object

One getaddr cache entry: a sample, and until when it is good for.

Core’s CConnman::CachedAddrResponse (src/net.h, at bitcoin/bitcoin@9be056a8a7, the v31.1 tag): m_addrs_response_cache and m_cache_entry_expiration. PeerDB.addr_response_caches holds one of these per key, in place of the one shared sample this table used to hold – callbacks.getaddr’s own docstring is where the key itself, and the reason for more than one, is argued.

class btclib_node.p2p.address.PeerDB(chain: Chain, data_dir: Path | None)[source]

Bases: object

The table of addresses this node knows of, gossiped and self-confirmed.

Core’s addrman (src/addrman.cpp, at bitcoin/bitcoin@9be056a8a7, the v31.1 tag). addresses is its mapInfo, every address heard about, and active_addresses is its tried table, the subset this node has itself dialled and heard back from. Each is behind its own lock, taken separately and never nested – the comment beside each lock’s own field says which thread reaches it and why sharing the other lock was declined – and a move between the two holds a third around the other two.

An address is in the new table, in up to _NEW_BUCKETS_PER_ADDRESS buckets (_insert_new), or in the tried table (_make_tried), as in Core.

add_active_address(addr: NetworkAddressV2, *, test_before_evict: bool = True) → bool[source]

Record addr as answered, and say whether it moved to the tried one.

Core’s AddrManImpl::Good_ (src/addrman.cpp, at bitcoin/bitcoin@9be056a8a7, the v31.1 tag): the entry is marked as connected to now, its attempts are reset, and nTime is left alone, “to avoid leaking information about currently-connected peers” – the known row is not written, and the answered row is stamped now, m_last_success, which nothing serves. connected is what moves nTime. An endpoint addresses does not hold is not recorded, as Good_ updates only an entry addrman already has, and neither is an address _storable refuses, which addresses never holds.

The entry leaves every bucket of the new table for its slot in the tried table, and the entry that held that slot goes back to the new table. With test_before_evict, Good’s own default, an entry that would take a held slot waits instead in the collisions resolve_collisions settles, and this answers False, as it does for an entry already tried, whose row a repeat handshake settles onto (#270). Takes _move_lock, then _addresses_lock and _active_lock in turn, never nested.

add_addresses(addresses: Iterable[__annotationlib_name_1__], *, source: NetworkAddressV2 | None = None, time_penalty: float = 7200) → int[source]

Merge addresses into the new table, checked and deduplicated.

Returns how many of them the new table took a slot for, new endpoints and further buckets of held ones alike: Core’s Add answers whether there were any.

An address _storable refuses is dropped. Every other address settles onto its own endpoint_key row, its services ORed into those the row held. The services are ORed into the endpoint’s answered row as well, where it has one. Takes _addresses_lock, then _active_lock, the two never nested.

Placement is Core’s AddSingle (_insert_new): a new endpoint takes the slot its group and the group of source map it to, and an endpoint held and not tried may take a further one, up to _NEW_BUCKETS_PER_ADDRESS, if the gossip is newer than its time and a draw of one in two to the power of the slots it holds comes up. What one source group gives spreads over _NEW_BUCKETS_PER_SOURCE_GROUP buckets at most. With no source an address is its own source.

A new row’s timestamp is the gossiped one, time_penalty seconds less, floored at zero; a row held keeps its own unless the gossip is newer by more than an hour, a day where it is a day old itself (btclib-org/btclib-node#1603) – Core’s AddrManImpl::AddSingle (src/addrman.cpp, at bitcoin/bitcoin@9be056a8a7, the v31.1 tag): pinfo->nTime = max(0, addr.nTime - time_penalty). time_penalty defaults to _GOSSIP_TIME_PENALTY, the flat two hours Core’s own ADDR/ ADDRV2 handler passes AddrMan::Add for a whole gossiped batch (net_processing.cpp, same sha); query_dns_seed below and P2pManager._maybe_add_fixed_seeds both pass 0, AddrMan::Add’s own default (ThreadOpenConnections’s addrman.get().Add(seed_addrs, local) and ThreadDNSAddressSeed’s addrman.get().Add(vAdd, resolveSource) alike pass no third argument), each answer already carrying a timestamp Core backdates itself before it ever reaches here. An address equal to source – host only, _host rather than ==, since two records differing in timestamp, services or even port are still one self-announcement – is exempted from the penalty, as AddSingle’s own if (addr == source) { time_penalty = 0s; } is: a peer’s word for its own address costs it nothing, where the same word for somebody else’s does. The port is dropped from the comparison because Core’s is: source there is a CNetAddr, not a CAddress, and addr == source slices addr down to its own CNetAddr base first (AddrManImpl::AddSingle, src/addrman.cpp, at bitcoin/bitcoin@9be056a8a7, the v31.1 tag) – _host’s own docstring is where CNetAddr::operator== itself is read. An inbound source carries the peer’s ephemeral source port from sock.accept()’s own peername (callbacks.py’s own version handler rewrites conn.address for an outbound connection alone), which an endpoint-including comparison would have compared against the peer’s own announced listening port and almost never matched (btclib-org/btclib-node#1380, review round 2) – host-only is not merely Core’s own comparison, it is what makes the exemption reachable for an inbound peer at all.

address_sampler(*, new_only: bool = False, network: Network | None = None) → Callable[[], __annotationlib_name_1__][source]

Return a draw over the dialable addresses of both tables, as of now.

Each call of what this returns is one _select, between the answered table and the gossiped one, and in either a bucket before an address in it, kept as GetChance weighs it, so P2pManager can draw many times a pass for the price of a copy of each table’s slots. An answered endpoint holds no slot of the gossiped table, as Core’s Good_ moves an entry from the new table to the tried one and Select_ flips between two tables that never hold one endpoint twice. With new_only the draw is from the gossiped side alone, Core’s Select(true, …) that a feeler makes, and with network from both sides kept to the one network, as CNetAddr::GetNetwork names it: Core’s Select(false, {network}), which an extra network peer makes.

A terrible entry is not left out of a draw: Core’s Select_ (src/addrman.cpp, at bitcoin/bitcoin@9be056a8a7, the v31.1 tag) never calls IsTerrible, only GetAddr_’s serving and AddSingle’s overwrite of a slot do (btclib-org/btclib-node#1434). A terrible tried entry stays in the tried table until another address takes its slot, as Core’s does.

attempt(address: NetworkAddressV2, *, count_failure: bool = False) → None[source]

Record a try to connect to address, as Core’s Attempt_ does.

AddrManImpl::Attempt_ (src/addrman.cpp, at bitcoin/bitcoin@9be056a8a7, the v31.1 tag) sets m_last_try on the entry addrman holds for the address, and does nothing where it holds none; so is an endpoint _known_keys does not hold left out here, an answered one being known too. With count_failure it also counts an attempt, nAttempts, once for the tries since the last Good_: ThreadOpenConnections passes it once the node holds outbound peers in enough net groups to be online. A try is kept as long as Good_ and ResolveCollisions_ read it, _ADDRMAN_REPLACEMENT.

close() → None[source]

Close the durable store, if this table has one.

connected(address: NetworkAddressV2) → None[source]

Move the time of address’s endpoint forward to now, if it is stale.

Core’s AddrManImpl::Connected_ (src/addrman.cpp, at bitcoin/bitcoin@9be056a8a7, the v31.1 tag), which FinalizeNode calls for a full outbound peer alone: nTime moves only where it is older than _CONNECTED_UPDATE_INTERVAL, and an endpoint the table does not hold is left out. Only the known row is written: the answered row’s timestamp is m_last_success. Takes _addresses_lock.

get_addr(max_addresses: int, max_pct: int, network: Network | None = None) → list[NetworkAddressV2][source]

Return a random sample of the known addresses, the terrible left out.

Core’s AddrManImpl::GetAddr_ (src/addrman.cpp, at bitcoin/bitcoin@9be056a8a7, the v31.1 tag): the answer is sized from every entry, new and tried – here addresses, which holds every answered endpoint too – as max_pct percent of them, 0 for all, then at most max_addresses, 0 for no limit. Entries are then drawn at random, skipping one _aged_out calls terrible and, with network, one on another network, until the size is reached or the table is spent, so a table of terrible entries answers less than its size. The percentage rounds up where Core’s rounds down: a table of a handful of addresses, every functional test’s own two-node regtest, would otherwise answer none (btclib-org/btclib-node#71).

holds_network(network_id: int) → bool[source]

Whether either table holds an address on network_id.

Core’s addrman.Size(net) != 0, which GetReachableEmptyNetworks asks of each reachable network (src/net.cpp, at bitcoin/bitcoin@9be056a8a7, the v31.1 tag). Each table is read under its own lock, one after the other.

init_from_db() → None[source]

Load every stored address into addresses or active_addresses.

One store keyed by several prefixes (the comment on _KNOWN and its neighbours above argues why), so this walks it whole and dispatches on the prefix rather than stopping at the first key without one. A row _storable refuses is deleted rather than loaded, as Core’s addrman holds no such address, and so is an answered row whose endpoint no known row holds, as Core’s tried table holds nothing addrman does not.

Rows are placed again as Core places what it reads from peers.dat (_place_stored). A row with no stored source, as an earlier release wrote them, is its own source: the rows of one group share its one bucket, and those over its room are dropped.

property is_empty: bool

Whether addresses holds nothing at all, read without a lock.

last_try(address: NetworkAddressV2) → float[source]

Return when address was last tried, 0.0 for never or long ago.

async query_dns_seed(seed: str) → str | None[source]

Ask one chain DNS seed’s x9. subdomain; return it if unanswered.

Core’s ThreadDNSAddressSeed asks x%x.<seed> of requiredServiceBits, SeedsServiceFlags() (x9. for NODE_NETWORK | NODE_WITNESS), on which a seed answers only with peers it believes offer those services – src/net.cpp and src/protocol.h, at bitcoin/bitcoin@9be056a8a7, the v31.1 tag – and keeps at most nMaxIPs, 32, of the answers. One seed at a time, rather than every one of them in a single call, is what lets P2pManager._dns_address_seed wait between batches of _DNS_SEEDS_TO_QUERY_AT_ONCE (btclib-org/btclib-node#1265): that coroutine is what shuffles the chain’s seeds, decides how many to ask before the next wait, and queues seed as its own addr-fetch where this returns it rather than None – Core makes an ADDR_FETCH connection to the bare name instead (AddAddrFetch(seed)).

random_address() → NetworkAddressV2 | None[source]

Return a random dialable address, or None if there is none.

One draw of address_sampler.

resolve_collisions() → None[source]

Settle the tried-table collisions that can be, ResolveCollisions_.

An entry waiting for the slot of one tried within _ADDRMAN_REPLACEMENT stops waiting and the old one stays. An old entry that was tried and failed in that time, for over a minute, or that has had neither a success nor a try in it and whose waiting entry answered over _ADDRMAN_TEST_WINDOW ago, is replaced. ThreadOpenConnections calls it before each draw, as P2pManager does; the feeler’s connection to the old entry that select_tried_collision names is what gives it a success to read. Takes _move_lock.

select_tried_collision() → NetworkAddressV2 | None[source]

Return a tried address another is waiting to replace, or None.

Core’s SelectTriedCollision, whose caller makes a feeler connection to the address it names: that connection’s handshake is what Good_ reads as the old entry answering.

set_services(address: NetworkAddressV2, services: ServiceFlags) → None[source]

Overwrite the services held for address’s endpoint.

Core’s AddrMan::SetServices, which ProcessMessage calls with an outbound peer’s own version (src/net_processing.cpp, src/addrman.cpp, at bitcoin/bitcoin@9be056a8a7, the v31.1 tag): what a gossip only adds to, the peer’s own word replaces. The known row and the answered row are both written, standing for Core’s one entry, and an endpoint neither holds is not recorded. Takes _addresses_lock, then _active_lock, the two never nested.

property size: int

every distinct endpoint known.

Core’s vRandom.size() (AddrManImpl::Size_, src/addrman.cpp, at bitcoin/bitcoin@9be056a8a7, the v31.1 tag) counts one entry per address, new or tried, because Good_ moves an entry from the new table to the tried one rather than copying it – the two never hold the one address at once there. This table’s own active_addresses is not addresses with one row moved out: an answered endpoint is left in addresses too (_good leaves the known row in place). A bare len(self.addresses) + len(self.active_addresses) therefore counted every answered endpoint twice. The honest count is addresses’ own size plus whatever active_addresses holds that addresses does not – read as _known_keys, kept in step with addresses by add_addresses (a slot taken over by a newcomer drops its holder’s key), and _active_index, kept in step with active_addresses the same way, so counting keys rather than walking either table answers without a stale-row’s own fields mattering. Locked, unlike is_empty below: _known_keys is snapshotted under _addresses_lock first, into a local set this thread alone holds, so the walk of _active_index under _active_lock next reads no collection a third thread could still be mutating – add_addresses’s own two-lock methods take the two the same way, never nested.

Type:

Return Core’s addrman.Size()

btclib_node.p2p.address.can_connect(address: NetworkAddressV2) → bool[source]

Answer whether this node has a dial for the peer’s network.

A different question from btclib.p2p.addrv2.can_addrv1, which asks whether the address fits an addr version 1 entry at all. The two agree on every network this node knows of today and are not the same rule: a dial through a SOCKS proxy would reach a network the version 1 wire format still has no room for.

async btclib_node.p2p.address.dial(address: NetworkAddressV2) → socket | None[source]

Return a socket connected to the peer, or nothing if it never came up.

dial and not connect, which is what P2pManager calls the whole of making a connection out of one: this is the socket alone.

loop.sock_connect is the kernel’s own answer rather than a guess at it: a refusal is SO_ERROR on the socket, read the moment the OS notifies the loop’s writer callback, not inferred after a fixed number of getpeername polls that cannot tell a refusal from a peer that is merely slow. And where connect completes without ever raising BlockingIOError – a local peer most often – sock_connect returns at once instead of an except arm that never runs.

No separate check for a host with no route to the family being dialled: _DIAL_TIMEOUT already bounds every attempt, and an unreachable family fails either the socket creation itself – a host with no IPv6 support at all, socket.socket(AF_INET6, …) raising OSError before there is anything to connect – or the same sock_connect a slow or refusing peer does, landing on the same None P2pManager already treats as “try someone else” either way. Core’s ConnectDirectly (src/netbase.cpp, at bitcoin/bitcoin@9be056a8a7, the v31.1 tag) answers the same way: a CreateSock that comes back null is logged and returned as the same {} a failed Connect answers with, one nullptr for both. Core’s own default reachability check (ReachableNets, src/netbase.h at 58a7869f86: “Everything is reachable by default”) is the same bet – reachability is what a dial’s outcome says it is, not a property guessed at beforehand – so there is nothing here for a heavier check to buy.

btclib_node.p2p.address.endpoint_key(address: NetworkAddressV2) → bytes[source]

Return the octets a persisted address is keyed on.

The network id, the address and the port – what names an endpoint on the wire – and not timestamp or services: those are this node’s own opinion of the endpoint, not part of what it is, so two records differing only in them settle on the one row written last rather than growing the table an entry per gossip or per reconnect.

btclib_node.p2p.address.fixed_seed_addresses(seeds: bytes) → list[NetworkAddressV2][source]

Decode a chain’s fixed_seeds, as Core’s ConvertSeeds does.

Each endpoint is a BIP155 network id, a compact-size length, the address and a big-endian port (src/net.cpp, at bitcoin/bitcoin@9be056a8a7, the v31.1 tag), and is given Core’s SeedsServiceFlags, NODE_NETWORK | NODE_WITNESS, and _fixed_seed_timestamp’s own draw for Core’s random time one to two weeks past (ConvertSeeds, same sha) – btclib-org/btclib-node#1571.

btclib_node.p2p.address.host_key(address: NetworkAddressV2) → bytes[source]

Return the octets Core’s CNetAddr::GetAddrBytes gives: no port.

What P2pManager.discourage keys on, as Core’s BanMan::Discourage does (src/banman.cpp, at bitcoin/bitcoin@9be056a8a7, the v31.1 tag), so every peer on one host shares one entry whatever port it connects from. An address an addr entry can carry is that entry’s sixteen octets, an IPv4 one mapped, which makes an IPv4 peer and the same peer mapped into IPv6 one host; any other is its own octets, with no network id, as in Core.

btclib_node.p2p.address.internal_source(name: str) → NetworkAddressV2[source]

Return the source Core gives what it learns from name: SetInternal.

CNetAddr::SetInternal (src/netaddress.cpp, at bitcoin/bitcoin@9be056a8a7, the v31.1 tag) is the first ten octets of the SHA-256 of name, held in IPv6 under INTERNAL_IN_IPV6_PREFIX. ThreadDNSAddressSeed passes one per DNS seed, and ThreadOpenConnections one named fixedseeds, to addrman.Add, so what a seed gives is placed as one source group’s.

btclib_node.p2p.address.ip_and_port(ip: str, port: int) → str[source]

Return the endpoint the way Core’s CService::ToStringAddrPort does.

“[” + ToStringAddr() + “]:” + port_str for every network that function’s IsIPv4() || IsTor() || IsI2P() || IsInternal() does not name. The brackets are what tells a v6 host from its port: 2001:db8::1 on port 8333 and 2001:db8::1:8333 on some other port are both addresses, and without brackets both render as the second.

The host’s text rather than the NetworkAddress a peer is held in, because a socket’s getpeername has no such object to offer and answers with this.

A v4-mapped host is unwrapped rather than bracketed, which is Core’s answer too: CNetAddr::SetLegacyIPv6 files a mapped address under NET_IPV4, which that predicate names. Without the unwrapping a v4 peer would read [::ffff:1.2.3.4]:8333, a NetworkAddress holding every address in the sixteen octets of an IPv6 one.

Raises ValueError where the host is not an IP address, which is what ipaddress.ip_address answers with: a hostname is refused rather than shown with brackets guessed at.

btclib_node.p2p.address.network_class(address: NetworkAddressV2) → Network[source]

Return Core’s CNetAddr::GetNetClass, what addrman and the RPCs name.

An IPv6 address linked to an IPv4 one (6to4, Teredo) is IPv4, as in net_class; any other network is get_network’s.

btclib_node.p2p.address.peer_address(ip: str, port: int, timestamp: int = 0, services: int = 0) → NetworkAddressV2[source]

Return the BIP155 record of a peer named by the text of its IP.

ipaddress.ip_address is what tells the two IP networks apart, and the octets it packs are what BIP155 asks for: four for a v4 peer and sixteen for a v6 one, where an addr entry would carry the v4 one mapped into sixteen.

btclib_node.p2p.address.service_key(address: NetworkAddressV2) → bytes[source]

Return the octets Core’s CService::GetKey gives: the port added.

host_key, then the port big-endian (src/netaddress.cpp, at bitcoin/bitcoin@9be056a8a7, the v31.1 tag). What Connection.addr_known keys on, as Core’s m_addr_known does.

btclib_node.p2p.addrrelay module

Which peers a gossiped address is relayed to, as Core’s RelayAddress.

RelayAddress (src/net_processing.cpp, at bitcoin/bitcoin@9be056a8a7, the v31.1 tag) picks the same one or two peers for an address for 24 hours at a time, so a peer’s addr_known keeps the address from going to it twice, and a peer that sends its own address often gains no reach. It hashes with SipHash under P2pManager’s per-process key, as Core does with nSeed0 and nSeed1, writing the same 8-byte little-endian words.

btclib_node.p2p.addrrelay.is_relayable(address: NetworkAddressV2) → bool[source]

Core’s CNetAddr::IsRelayable: IPv4, IPv6, Tor, I2P or CJDNS.

btclib_node.p2p.addrrelay.relay_destinations(key: tuple[int, int], address: NetworkAddressV2, peer_ids: Iterable[__annotationlib_name_1__], *, reachable: bool, now: float) → list[int][source]

Return the ids of the peers to relay address to, at most two.

A reachable address goes to two peers; any other to one or two, by one bit of the hash. A peer ranks by the hash of the address, the 24-hour window and its id; one that hashes to 0 is passed over, and a tie goes to the lower id. The address’s unkeyed hash offsets the window, so addresses rotate their peers at different times.

btclib_node.p2p.anchors module

The block-relay-only peers kept across a restart, in anchors.dat.

dump_anchors is Core’s DumpAnchors and read_anchors its ReadAnchors (src/addrdb.cpp, at bitcoin/bitcoin@9be056a8a7, the v31.1 tag), in the same file format, so that either program reads the other’s: the network magic, a CompactSize count, each address as CAddress::V2_DISK writes it – a four-octet disk version, then the addrv2 entry – and the double SHA-256 of everything before it.

btclib_node.p2p.anchors.dump_anchors(path: Path, magic: bytes, anchors: list[NetworkAddressV2]) → None[source]

Write anchors to path, through a temporary file renamed over it.

SerializeFileDB’s own sequence: a randomly named file beside the target, synced, then renamed into place, and removed where any step fails before the error is raised on.

btclib_node.p2p.anchors.read_anchors(path: Path, magic: bytes, log: Callable[__annotationlib_name_1__, __annotationlib_name_2__] | None = None) → list[NetworkAddressV2][source]

Return the addresses path holds, then delete it.

A whole file is reported to log, where one is given, in the line Core’s ReadAnchors logs.

Anything short of a whole file for this network, checksum included, answers no address, as Core’s ReadAnchors catches every exception of its read; what follows the checksum is not read, as Core does not read it. The file goes either way, so an anchor is tried on one start only.

btclib_node.p2p.banman module

The hosts and subnets an operator has banned, Core’s BanMan.

BanMan is Core’s class of the same name (src/banman.cpp), Subnet its CSubNet (src/netaddress.cpp) and lookup_subnet its LookupSubNet (src/netbase.cpp), all read at bitcoin/bitcoin@9be056a8a7, the v31.1 tag. The list is kept in banlist.json in Core’s own format (src/addrdb.cpp, src/net_types.cpp), so either node reads the other’s.

A subnet is an IPv4 or an IPv6 one, or a single onion or I2P host, as CSubNet holds them. An address is read as LookupHost reads one: SetSpecial’s onion and I2P names first, then whatever the platform’s getaddrinfo reads as a numeric address. A CJDNS address is an IPv6 one here, as it is in Core without -cjdnsreachable, which this node does not have.

class btclib_node.p2p.banman.BanEntry(create_time: int, ban_until: int)[source]

Bases: object

Core’s CBanEntry: when the ban was set, and until when it holds.

class btclib_node.p2p.banman.BanMan(path: Path | None, logger: Logger, default_ban_time: int = 86400)[source]

Bases: object

Core’s BanMan, without the discouragement filter.

P2pManager.discourage keeps that filter. Every method takes the lock Core’s m_banned_mutex is, the RPC reaching this list on Node’s thread and the accept and dial paths on P2pManager’s. path None keeps the list in memory only.

ban(subnet: Subnet, ban_time_offset: int = 0, *, absolute: bool = False) → None[source]

Core’s Ban: for ban_time_offset seconds, or until it if absolute.

An offset of zero or less is the default ban time from now. A ban already held is replaced only by one that ends later.

banned() → list[tuple[Subnet, BanEntry]][source]

Core’s GetBanned: swept first, in the list’s own order.

clear() → None[source]

Core’s ClearBanned.

dump() → None[source]

Core’s DumpBanlist: sweep, then write the list if it changed.

is_banned(host: Host) → bool[source]

Core’s IsBanned of an address: any unexpired ban matching it.

is_peer_banned(address: NetworkAddressV2) → bool[source]

is_banned of a peer’s address, never true off these networks.

is_subnet_banned(subnet: Subnet) → bool[source]

Core’s IsBanned of a subnet: that very subnet, unexpired.

unban(subnet: Subnet) → bool[source]

Core’s Unban: whether subnet was on the list to remove.

type btclib_node.p2p.banman.Host = IPv4Address | IPv6Address | SpecialAddress

An address lookup_host reads: an IP one, or an onion or I2P host.

class btclib_node.p2p.banman.SpecialAddress(network: BIP155Network, packed: bytes)[source]

Bases: object

Core’s CNetAddr of an onion or an I2P host: its network and key.

classmethod parse(text: str) → SpecialAddress | None[source]

Core’s CNetAddr::SetSpecial: a v3 onion name or an I2P one.

class btclib_node.p2p.banman.Subnet(network: Host, prefix: int, scope: int = 0)[source]

Bases: object

Core’s CSubNet: an IP network and its prefix length, or one host.

network is already masked, and has no scope: an IPv6 one’s scope is scope, which Core writes and does not compare, so two subnets differing in scope alone are the one entry. An onion or I2P host has a prefix of zero, its netmask being all zeros in Core. sort_key orders them as Core’s std::map of them does.

matches(host: Host) → bool[source]

Core’s CSubNet::Match of a valid address.

An onion or I2P subnet matches its own host alone.

matches_peer(address: NetworkAddressV2) → bool[source]

Answer matches of a peer’s address.

classmethod of(host: Host, prefix: int | None = None) → Subnet[source]

Return the prefix-bit subnet holding host, alone if none.

sort_key() → tuple[int, bytes, int][source]

Core’s operator< of two CSubNet: network, octets, netmask.

btclib_node.p2p.banman.is_valid_host(host: Host) → bool[source]

Core’s CNetAddr::IsValid of an address lookup_host gave.

An onion or I2P host is always valid.

btclib_node.p2p.banman.lookup_host(text: str, *, allow_lookup: bool = False) → Host | None[source]

Core’s LookupHost of the first address it answers.

Brackets around the address are stripped. An onion or I2P name is SetSpecial’s. Anything else is what getaddrinfo reads, as WrappedGetAddrInfo asks it, handed the octets as Core hands them: with AI_NUMERICHOST where allow_lookup is false, so that only a numeric address is read, and with AI_ADDRCONFIG, retried without it, where it is true. Forms such as 1.2.3 and a scope id are the platform’s to accept. An IPv6 address keeps its numeric scope. An IPv4 address mapped into IPv6 is IPv4, an address under Core’s internal prefix is dropped, and one under the Tor v2 prefix is the unspecified address, as CNetAddr::SetLegacyIPv6 reads them.

btclib_node.p2p.banman.lookup_subnet(text: str) → Subnet | None[source]

Core’s LookupSubNet: an address, then a CIDR prefix or a netmask.

Split at the last slash. A suffix of decimal digits up to 255 is a prefix length, valid up to the address’s own; anything else is read as a netmask of the same kind, which has to be contiguous. With no slash the subnet is the one host. An onion or I2P host takes no suffix, as CSubNet has neither constructor for one.

btclib_node.p2p.block_availability module

What this node knows one peer has of the block chain, and asks it for.

BlockAvailability is the part of Core’s CNodeState that is about blocks: pindexBestKnownBlock, hashLastUnknownBlock, pindexLastCommonBlock, pindexBestHeaderSent, m_stalling_since and m_downloading_since (src/net_processing.cpp, at bitcoin/bitcoin@9be056a8a7, the v31.1 tag); Connection.download_queue is its vBlocksInFlight. The functions below are the ones of Core’s that read and write those fields, under the same names: callbacks.headers and callbacks.inv call update_block_availability, callbacks.getheaders and main’s block announcement set best_header_sent, the announcement asks peer_has_header, DownloadManager.block_download runs find_next_blocks_to_download, and callbacks.block runs remove_block_request. in_flight_from and first_in_flight read Core’s mapBlocksInFlight, which here is every connection’s queue. getpeerinfo’s synced_headers and synced_blocks are the heights of best_known and last_common.

A block is a hash here where Core holds a CBlockIndex*, and an ancestor is read through BlockIndex.get_ancestor and BlockIndex.last_common_ancestor, Core’s GetAncestor and LastCommonAncestor over the same skip pointers.

class btclib_node.p2p.block_availability.BlockAvailability(best_known: bytes | None = None, last_unknown: bytes | None = None, last_common: bytes | None = None, best_header_sent: bytes | None = None, stalling_since: float = 0.0, downloading_since: float = 0.0)[source]

Bases: object

The blocks one peer is known to have, and how its downloads stand.

best_known is the most-work block the peer announced, and last_unknown the last one it announced that was not yet indexed. last_common is the last block both this node and the peer hold in full. best_header_sent is the best header this node sent the peer. Each is None until first set, as Core’s pointers start null. stalling_since is when the peer started holding up the download window, and downloading_since when the block at the front of its queue became the one awaited: wall-clock times, each 0 where Core’s is zero.

partial_blocks is Core’s QueuedBlock::partialBlock, for the blocks of the queue a cmpctblock is being rebuilt from: None once the blocktxn was used, where Core nulls its header. request_order is where callbacks.cmpctblock queued a block among the peers it is asked of, Core’s mapBlocksInFlight being a multimap that keeps that order. A block missing from it was queued first.

btclib_node.p2p.block_availability.find_next_blocks_to_download(block_index: BlockIndex, state: BlockAvailability, count: int, minimum_chain_work: int, segwit_height: int, *, in_flight: Mapping[__annotationlib_name_1__, __annotationlib_name_2__], peer_id: int, limited: bool, can_serve_witnesses: bool) → tuple[list[bytes], int | None][source]

Choose up to count blocks to ask this peer for: Core’s own walk.

FindNextBlocksToDownload and FindNextBlocks. Nothing is chosen, and last_common stays, where count is 0, where best_known is unset or has less work than the active tip or than minimum_chain_work. last_common is then reset to the fork point between best_known and the active tip where it is unset, has less work than that fork point, or is no longer an ancestor of best_known; nothing is chosen where it is best_known itself.

The walk goes up best_known’s chain from last_common, BLOCK_DOWNLOAD_WINDOW + 1 blocks at most, and ends at an invalid block. A block this node holds is passed over, and becomes last_common while every block before it is held too. A block in in_flight, which maps each block asked for to a peer it is asked of, is passed over, and the first one’s peer is who this peer waits on. A block past the window’s end ends the walk, and where nothing was chosen the peer waited on is returned as the staller, unless it is this one. A limited peer is not asked for a block MIN_BLOCKS_TO_KEEP - 2 or more below its best_known: Core’s NODE_NETWORK_LIMITED_MIN_BLOCKS, with “two blocks buffer for possible races”.

Core also passes over a block of the active chain, which a walk starting at or above the fork point never meets, and ends the walk, ahead of every other check on that block, at the first one at or past segwit_height where can_serve_witnesses is false – DeploymentActiveAt(*pindex, …, DEPLOYMENT_SEGWIT) held against a peer that fails CanServeWitnesses. A block this node already holds does not move last_common past that point either, ending the walk the same way an invalid block does rather than being passed over.

btclib_node.p2p.block_availability.first_in_flight(connections: Iterable[Connection]) → dict[bytes, int][source]

Map each block in flight to the peer it was first asked of.

Core’s mapBlocksInFlight, where the first entry of a block is the one FindNextBlocks reads.

btclib_node.p2p.block_availability.get_ancestor(block_index: BlockIndex, block_hash: bytes, height: int) → bytes | None[source]

Return the ancestor of block_hash at height: Core’s GetAncestor.

None for a height above the block’s own, as Core answers nullptr.

btclib_node.p2p.block_availability.in_flight_from(connections: Iterable[Connection], block_hash: bytes) → list[Connection][source]

Return the peers block_hash is asked of, the first asked first.

Core’s mapBlocksInFlight.equal_range.

btclib_node.p2p.block_availability.peer_has_header(block_index: BlockIndex, state: BlockAvailability, block_hash: bytes) → bool[source]

Whether the peer has block_hash’s header: Core’s PeerHasHeader.

It does where the header is an ancestor of, or is, the best block it announced or the best header it was sent.

btclib_node.p2p.block_availability.process_block_availability(block_index: BlockIndex, state: BlockAvailability) → None[source]

Take up last_unknown once indexed: Core’s ProcessBlockAvailability.

It becomes best_known unless that has more work. Core also asks that the block’s chain work be positive, which every header indexed here has, genesis included.

btclib_node.p2p.block_availability.remove_block_request(connections: Iterable[Connection], block_hash: bytes, now: float, from_peer: int | None = None) → None[source]

Drop block_hash from the queues it is asked in: RemoveBlockRequest.

Every connection’s, or from_peer’s alone. A peer the block was asked of stops stalling, and where it was the block awaited at the front of the queue, the one after it is awaited from now. Its partial block goes with it.

btclib_node.p2p.block_availability.update_block_availability(block_index: BlockIndex, state: BlockAvailability, block_hash: bytes) → None[source]

Record that the peer has block_hash: Core’s UpdateBlockAvailability.

An indexed block becomes best_known unless that has more work; one not indexed yet is kept as last_unknown until it is.

btclib_node.p2p.callbacks module

One handler per p2p message type, and the two tables that dispatch to them.

callbacks is read by p2p.main.handle_p2p for a connection past its handshake; handshake_callbacks is read by p2p.main.handle_p2p_handshake for a connection still completing one. Every handler shares the same signature, (node, msg, conn), whether or not its own body reads every argument – the dispatch table calls each one uniformly, and an unread msg or conn documents that rather than a mistake.

advance_getdata and advance_cfilters are the two exceptions to “one handler, one message”: getdata and get_cfilters below, and p2p.main.resume_getdata and resume_cfilters, each call one of them to pace an answer against the connection’s own send queue, across however many turns of Node’s own loop that answer takes to drain.

btclib_node.p2p.callbacks.addr(node: Node, msg: bytes, conn: Connection) → None[source]

Merge the addr-version-1 entries a peer gossiped into the table.

Ignored from a block-relay-only peer once parsed, as Core’s ADDR handler (net_processing.cpp, at bitcoin/bitcoin@9be056a8a7, the v31.1 tag) ignores it, SetupAddressRelay refusing the peer ahead of the MAX_ADDR_TO_SEND check. A payload the parse refuses is logged by main.handle_p2p and costs the peer nothing, as in Core, whose parse reads a count past that bound where btclib’s refuses it.

btclib_node.p2p.callbacks.addrv2(node: Node, msg: bytes, conn: Connection) → None[source]

Merge the BIP155 entries a peer gossiped into the address table.

Ignored from a block-relay-only peer once parsed, as addr above ignores it.

btclib_node.p2p.callbacks.advance_cfilters(node: Node, conn: Connection, block_hashes: deque[bytes]) → bool[source]

Send from the front of block_hashes until conn.pause_send is set.

Shared by get_cfilters, dispatching a request for the first time, and by p2p.main.resume_cfilters, retrying one already paused, on a later pass of Node’s loop. Each pops what it sends off the front of the same deque. Answers whether block_hashes is now empty.

Core’s ProcessGetCFilters (src/net_processing.cpp, at bitcoin/bitcoin@9be056a8a7, the v31.1 tag) queues every filter of the answer at once, and ProcessMessages reads nothing more from the peer until its send buffer is back within nSendBufferMaxSize. This checks conn.pause_send before each filter instead, as advance_getdata checks it before each item, and _hold_message (p2p/main.py) holds the peer while filters are left. The peer sees the same filters, in the same order, and its next message is read at the same point: once the last filter is queued and the buffer is back within the bound. What differs is memory: an answer of MAX_GETCFILTERS_SIZE filters is never queued whole.

conn.status is read unlocked: seen one turn late it costs a filter serialized for a socket already closed, which Connection._deliver suppresses.

btclib_node.p2p.callbacks.advance_getdata(node: Node, conn: Connection, items: deque[Inventory]) → bool[source]

Serve from the front of items as Core’s ProcessGetData does.

Shared by getdata below, dispatching a request for the first time, and by p2p.main.resume_getdata, Core’s next call, which serves a paused request on a later pass of Node’s loop. Each pops what it serves off the front of the same deque. Answers whether items is now empty.

Core’s ProcessGetData (src/net_processing.cpp, at bitcoin/bitcoin@9be056a8a7, the v31.1 tag) serves the transactions at the front, then one other item, checking fPauseSend before each: “the send buffer provides backpressure”. conn.pause_send is that flag. conn.send counts each item on this thread before scheduling its write, so the item that sets it pauses the next.

A transaction is served from the mempool, then from the most recent block, only if the peer wants it relayed, answered notfound on a miss; a requested block not held is silent. Both match Core – BIP37’s fRelay is written about announcements, “broadcast transactions will not be announced”, and says nothing about a transaction a peer asks for by hash, but Core answers nothing anyway: with fRelay false and NODE_BLOOM not offered, ProcessGetData skips every transaction item outright, and where NODE_BLOOM is offered, FindTxForGetData gates on m_last_inv_sequence, which never advances for a peer nothing is announced to. This node follows Core rather than the sentence, and the reason is what the sentence does not cover: serving the mempool by hash to a peer that declined announcements answers, for anyone willing to ask, whether a given transaction reached this node – and a peer that declined is the one with no other reason to be asking. Blocks are not affected: a peer that wants no transactions is still a peer syncing the chain. A block this node does not hold gets no notfound either: ProcessGetBlockData returns on one with no notfound of its own, vNotFound being ProcessGetData’s own local and never touched by the function it calls out to for a block item. _below_prune_threshold’s own docstring is where a pruned node’s other answer to a block item – disconnecting rather than staying silent – is argued against the same function, and _serve_getdata_block’s argues why a MSG_FILTERED_BLOCK disconnects whether or not the block is held.

The misses of a call go in one notfound, sent once the call has served what it could, as Core’s vNotFound is a per-call local.

btclib_node.p2p.callbacks.already_judged(node: Node, tx: Tx, conn: Connection) → bool[source]

Answer whether the mempool holds tx or has recently refused it.

Either way it is not verified again. Mempool is reached from Node’s thread alone (its own module docstring), as this is.

btclib_node.p2p.callbacks.block(node: Node, msg: bytes, conn: Connection) → None[source]

Store a requested block once its proof of work checks out.

A body its header does not commit to (main.is_block_mutated), on a parent this node knows, is refused first, whatever is already stored under that hash: it says nothing about the header. A body failing CheckBlock (main.passes_check_block) is refused next, requested or not, with its header left unindexed; then a body under a header marked invalid, duplicate-invalid (main.is_cached_invalid). Past that, a no-op if this block is already marked downloaded. A body failing a check is refused, and the block asked of another peer, with the index left alone except where Core marks the block failed (main.is_block_failed).

An unsolicited block whose own header this node has never indexed is not read as though getdata or headers already vouched for it: PeerManagerImpl::ProcessMessage’s own NetMsgType::BLOCK arm (net_processing.cpp, at bitcoin/bitcoin@ca7162cde5) runs every block through ChainstateManager::AcceptBlock once ProcessNewBlock’s CheckBlock has passed – which this function asks first too, in _refuse_before_indexing – and AcceptBlock calls AcceptBlockHeader (validation.cpp, same sha) on the block’s own header before the body’s remaining checks – a header already known is accepted outright, and one that is not has its own parent looked up, refused with BLOCK_MISSING_PREV where that parent is unknown too. Core punishes that refusal: MaybePunishNodeForBlock’s own switch (net_processing.cpp, same sha) calls Misbehaving for BLOCK_MISSING_PREV, unlike an unconnecting headers batch, which ProcessHeadersMessage’s own HandleUnconnectingHeaders answers by asking for more rather than by punishing – the same asymmetry this file already carries between headers below, which never discourages a batch connecting to nothing this node knows (btclib-org/btclib-node#233), and this function, which does. block_index.add_headers([block.header]) is AcceptBlockHeader’s own shape: it indexes the header where the parent is known, raises where the header itself is invalid – a MisbehavingError where Core’s MaybePunishNodeForBlock punishes, which main.handle_p2p’s own except answers by dropping and discouraging the peer, as it does for a block failing its own checks below – and, for a single header whose parent is missing, returns None rather than raising, which is headers’s own “ask again” case and not this one’s: a MisbehavingError is raised here instead, matching Misbehaving. btclib-org/btclib-node#711

A header new here whose chain is below the anti-DoS work threshold (_min_pow_checked) is not indexed, and the block is dropped with it, its peer kept: Core’s too-little-chainwork (btclib-org/btclib-node#1505).

While the stored blocks connect, the message is dropped unread (_ignored_while_reindexing).

btclib_node.p2p.callbacks.blocktxn(node: Node, msg: bytes, conn: Connection) → None[source]

Finish the block a cmpctblock from this peer left short.

Core’s BLOCKTXN handler (net_processing.cpp, at bitcoin/bitcoin@9be056a8a7, the v31.1 tag). The transactions are read unchecked, as Core’s deserializer reads them: one that is not valid leaves a block _check_block refuses.

While the stored blocks connect, the message is dropped unread (_ignored_while_reindexing).

btclib_node.p2p.callbacks.cmpctblock(node: Node, msg: bytes, conn: Connection) → None[source]

Rebuild a block from a cmpctblock, and ask for what it lacks.

Core’s CMPCTBLOCK handler (net_processing.cpp, at bitcoin/bitcoin@9be056a8a7, the v31.1 tag). Its header is taken first (_index_compact_header), and the block goes further only where it is not held, has more work than the tip, and is in flight or the tip is recent.

At most two blocks past the tip, the block is queued from this peer where it is asked of fewer than MAX_CMPCTBLOCKS_INFLIGHT_PER_BLOCK peers and this one has room, or it is queued from this peer already (_queue_compact_block). Otherwise it is rebuilt all the same, and taken where nothing is missing (_reconstruct_optimistically). Further past the tip, a block queued from this peer is asked for as a block, and one not asked of this peer is read as a header.

The message is parsed unchecked, as Core’s deserializer reads it: add_headers checks the header and _reconstruct the rest. More than 65535 transactions is refused by the parse and the peer kept, as Core’s deserializer throws “indexes overflowed 16 bits”.

A peer that never sent sendcmpct is ignored before the message is read. The v31.1 handler has no such return; bitcoin/bitcoin#32606 added it at bitcoin/bitcoin@4bacf21a13 (net_processing.cpp:4799-4802, first in v32.0rc1). This node asks for a cmpctblock only of a peer that sent sendcmpct, so the return drops nothing it asked for.

A block not asked of this peer, from a peer not marked high-bandwidth (bip152_highbandwidth_to), is ignored once its header is taken. The v31.1 handler has no such return either; bitcoin/bitcoin#32606 added it at bitcoin/bitcoin@4bacf21a13 (net_processing.cpp:4888-4891, first in v32.0rc1). A peer is marked only where this node sent it sendcmpct(1), and a block this node asked of a peer is in its download_queue, so the return drops only what neither asked for.

While the stored blocks connect, the message is dropped unread before anything else (_ignored_while_reindexing), as v31.1 does.

btclib_node.p2p.callbacks.feefilter(node: Node, msg: bytes, conn: Connection) → None[source]

Record the peer’s own BIP133 minimum feerate, ignoring an invalid one.

btclib_node.p2p.callbacks.get_cfcheckpt(node: Node, msg: bytes, conn: Connection) → None[source]

Answer a BIP157 getcfcheckpt with one filter header per checkpoint.

Disconnects for an unsupported filter type, a type not advertised under -peerblockfilters, or a stop hash _block_request_allowed refuses – _prepare_filter_request’s own docstring, matching Core (ISS 1477).

btclib_node.p2p.callbacks.get_cfheaders(node: Node, msg: bytes, conn: Connection) → None[source]

Answer a BIP157 getcfheaders with the requested range’s filter headers.

Disconnects on a request _filter_range refuses; see its own docstring and _prepare_filter_request’s.

btclib_node.p2p.callbacks.get_cfilters(node: Node, msg: bytes, conn: Connection) → None[source]

Answer a BIP157 getcfilters with one cfilter per requested block.

Disconnects on a request _filter_range refuses; see its own docstring and _prepare_filter_request’s. “sequentially in order by block height” is BIP157’s own words and the reason this is the one request answered by many messages rather than one; _filter_range already bounds how many, and advance_cfilters above pauses at the send buffer’s bound, registering what it could not finish on node.pending_cfilters for p2p.main.resume_cfilters to complete.

While conn has an entry on node.pending_cfilters, _hold_message (p2p/main.py) holds its later messages, in order, and resume_tx_checks reads them once resume_cfilters has finished the answer (btclib-org/btclib-node#1789). So an entry is never extended by a second request, and holds one range at most.

The messages held are weighed against conn.queued_recv_bytes, so reads from the connection pause past conn.recv_flood_size: that bounds what a peer can pile up behind a paused answer.

btclib_node.p2p.callbacks.getaddr(node: Node, msg: bytes, conn: Connection) → None[source]

Answer a peer’s getaddr with a sample of every known address, once.

An address conn.addr_known holds is left out, as Core leaves it out. A peer holding ADDR is answered from a draw of its own. For any other the sample is a cache, shared and redrawn only once its own lifetime and jitter expire – _cached_sample argues why – and kept one per conn.addr_cache_key rather than one for every connection. Core’s CConnman::GetAddresses (src/net.cpp, at bitcoin/bitcoin@9be056a8a7, the v31.1 tag) keys m_addr_response_caches by requestor.m_network_key, itself keyed by the connection’s network (onion for an inbound onion listener, Connection.inbound_onion) and the local bind address and port the peer reached it on (CreateNodeFromAcceptedSocket, same file and sha): “Addr responses stored in different caches per (network, local socket) prevent cross-network node identification. If a node for example is multi-homed under Tor and IPv6, a single cache (or no cache at all) would let an attacker to easily detect that it is the same node by comparing responses.” (m_addr_response_caches’s own comment, src/net.h, same sha.) conn.addr_cache_key’s own docstring (connection.py) is where the key is built; this node’s own plain tuple stands in for Core’s SipHash-keyed uint64_t, which buys unpredictability against a peer that could read the key off the wire – this key never leaves the process, so nothing here needs that property, only that two different (network, local socket) triples land on two different dict entries.

btclib_node.p2p.callbacks.getblocks(node: Node, msg: bytes, conn: Connection) → None[source]

Answer a peer’s getblocks with an inv, as Core does.

The GETBLOCKS branch of Core’s ProcessMessage (net_processing.cpp, at bitcoin/bitcoin@9be056a8a7, the v31.1 tag). A locator past MAX_LOCATOR_SZ drops the peer, undiscouraged. Any other first activates the best chain, so that a block just announced is on it, and is answered with the MSG_BLOCK hashes of the active chain after _find_fork_in_global_index’s block, up to _GETBLOCKS_LIMIT of them and up to hash_stop, which is not sent. A pruned node also stops at a block it holds no data for, or one so deep that a peer could soon find it gone: MIN_BLOCKS_TO_KEEP less an hour’s blocks behind the tip. The last block sent at the limit is the peer’s continuation_block, which _serve_getdata_block answers with an inv of the tip, for the peer’s next getblocks. Core sends the inv on its next SendMessages; here it is sent at once, nothing else being queued ahead of it.

btclib_node.p2p.callbacks.getblocktxn(node: Node, msg: bytes, conn: Connection) → None[source]

Answer the transactions of a block a peer’s cmpctblock lacked.

Core’s GETBLOCKTXN handling (net_processing.cpp, at bitcoin/bitcoin@9be056a8a7, the v31.1 tag): silence for a block not held; a blocktxn for node.most_recent_block, ahead of any lookup, or for one at most MAX_BLOCKTXN_DEPTH below the tip, an index past its last transaction being misbehaviour; and for an older one the full block, queued as a MSG_WITNESS_BLOCK item of this connection’s own getdata, whose serving pays for the disk read the request cost.

An empty indexes is dropped, undiscouraged, ahead of any lookup: Core commit 28641fd195db2a175fd43fee2e32758aef9816a6 (“p2p: reject empty getblocktxn requests”), on master and not yet in a release, at bitcoin/bitcoin@28641fd195db – “No legitimate reason to send indexes empty” – sets fDisconnect rather than calling Misbehaving, so this raises no MisbehavingError and instead drops the peer directly, matching tx’s own block-relay-only refusal above. v31.1, at bitcoin/bitcoin@9be056a8a7, answers an empty request the same as any other and keeps the peer, as this node did before this check.

btclib_node.p2p.callbacks.getdata(node: Node, msg: bytes, conn: Connection) → None[source]

Answer a peer’s request for the transactions and blocks it named.

advance_getdata above is where every item is actually served, and where this request’s own place in Core’s getdata semantics is argued; this only starts a request, and leaves on node.pending_getdata what it could not finish.

Core’s ProcessMessages (net_processing.cpp, at bitcoin/bitcoin@9be056a8a7, the v31.1 tag) returns before PollMessage whenever m_getdata_requests is non-empty or fPauseSend is set: “this maintains the order of responses and prevents m_getdata_requests to grow unbounded”. It never backlogs more than one request’s own MAX_INV_SZ items per connection, and reads nothing more from it, getdata included, until the current one has drained.

This ports the first condition (btclib-org/btclib-node#1775); the second is _hold_message’s (btclib-org/btclib-node#1796). While conn has an entry on node.pending_getdata, _hold_message (p2p/main.py) holds its later messages, in order, and resume_tx_checks reads them once resume_getdata has finished the answer. So an entry is never extended by a second request, and holds one request’s items at most.

The messages held are weighed against conn.queued_recv_bytes, so reads from the connection pause past conn.recv_flood_size: that bounds what a peer can pile up behind a paused answer.

btclib_node.p2p.callbacks.getheaders(node: Node, msg: bytes, conn: Connection) → None[source]

Answer a peer’s getheaders off the active chain, as Core does.

The GETHEADERS branch of Core’s ProcessMessage (net_processing.cpp, at bitcoin/bitcoin@9be056a8a7, the v31.1 tag). An active chain with less work than the minimum chain work is answered with an empty headers, unless the peer holds DOWNLOAD. An empty locator asks for the hash_stop header alone, answered only where it is known and _block_request_allowed, and not at all otherwise. Any other locator is answered with the active chain after _find_fork_in_global_index’s block, up to MAX_HEADERS_RESULTS headers and up to hash_stop: empty where that block is the tip. The peer’s best_header_sent becomes the last header sent, or the tip where none is.

While the stored blocks connect, NodeStatus.Reindexing, a getheaders within the locator’s bound is not answered: Core’s LoadingBlocks() return (net_processing.cpp:4405, same sha). btclib-org/btclib-node#1915

btclib_node.p2p.callbacks.has_all_desirable_services(node: Node, services: int) → bool[source]

Core’s HasAllDesirableServiceFlags, argued in version below.

btclib_node.p2p.callbacks.headers(node: Node, msg: bytes, conn: Connection) → None[source]

Index a batch of headers, ask for more, or mark header sync finished.

Core’s ProcessHeadersMessage (net_processing.cpp, at bitcoin/bitcoin@9be056a8a7, the v31.1 tag), in its order. An empty batch is the peer having nothing to give: it ends a low-work sync with it and asks for nothing more. A batch is checked for proof of work and continuity, then handed to the peer’s low-work sync where one runs (_is_continuation_of_low_work_headers_sync), which may keep it all. A batch connecting to nothing known asks again from what this node already has. A connecting batch whose chain has less work than headers_sync.anti_dos_work_threshold is not indexed: a full one starts a low-work sync, a short one is ignored (_try_low_work_headers_sync), and neither costs the peer anything. A batch past all that is indexed, asks for the next one where it was full and no sync is asking already, and ends header sync where it was short; it is then handed to DownloadManager.headers_direct_fetch.

An empty batch, or one that connects, answers the getheaders in flight to this peer, as does a batch a low-work sync takes; one connecting to nothing may be an announcement, and answers nothing.

A peer holding NO_BAN skips the work check, as in Core.

While the stored blocks connect, the message is dropped unread, its count included (_ignored_while_reindexing).

btclib_node.p2p.callbacks.inv(node: Node, msg: bytes, conn: Connection) → None[source]

Ask for headers behind an announced block, queue missing transactions.

The INV branch of Core’s ProcessMessage (net_processing.cpp, at bitcoin/bitcoin@9be056a8a7, the v31.1 tag). The last block announced that has no header here is asked for with a getheaders from the best header, whatever the sync state, where sync_headers has already asked this peer for headers; where it has not, once per peer and once per new block, so that header sync takes on one more peer for each block found. Either way maybe_send_getheaders drops the request while one to this peer is in flight, and a peer not yet syncing has its turn spent all the same, as in Core. While the stored blocks connect, NodeStatus.Reindexing, no block announced asks for headers, as Core’s LoadingBlocks() gates it (net_processing.cpp:4158, same sha; btclib-org/btclib-node#1915). Transactions are queued only out of initial block download, where Core calls AddTxAnnouncement.

A block-relay-only peer announcing a transaction is disconnected there and then, as Core’s loop does on the first such item where RejectIncomingTxs holds: what came before it is taken, and nothing after it, getheaders included. An item of the kind Core skips for the peer’s wtxidrelay is not one: MSG_TX from a peer that sent it, MSG_WTX from one that did not.

btclib_node.p2p.callbacks.maybe_send_getheaders(node: Node, conn: Connection, locator: list[bytes]) → bool[source]

Send conn a getheaders unless one to it is still in flight.

Core’s MaybeSendGetHeaders (net_processing.cpp, at bitcoin/bitcoin@9be056a8a7, the v31.1 tag), through which every getheaders this node sends goes. A request is in flight from when it is sent until headers clears it or _HEADERS_RESPONSE_TIME passes. Returns whether it was sent.

btclib_node.p2p.callbacks.not_found(node: Node, msg: bytes, conn: Connection) → None[source]

Complete the announcements of the transactions the peer could not answer.

A block item carries no such bookkeeping to complete – the comment below argues why.

btclib_node.p2p.callbacks.ping(node: Node, msg: bytes, conn: Connection) → None[source]

Answer a ping with a pong carrying the same nonce.

Unanswered at a common version of BIP0031_VERSION or below, whose ping carries no nonce and which Core does not answer either.

btclib_node.p2p.callbacks.pong(node: Node, msg: bytes, conn: Connection) → None[source]

Finish the outstanding ping a pong answers, recording the round trip.

Core’s PONG (src/net_processing.cpp, at bitcoin/bitcoin@9be056a8a7, the v31.1 tag) punishes no peer for a pong. A nonce matching no outstanding ping leaves it outstanding, mismatches being “normal when pings are overlapping”; a zero nonce, or a payload too short to hold one, finishes it with no round trip recorded; and a pong with no ping outstanding is ignored.

btclib_node.p2p.callbacks.process_orphan(node: Node, conn: Connection) → bool[source]

Take up an orphan conn is to reconsider, as far as its scripts.

Core’s ProcessOrphanTx (src/net_processing.cpp, at bitcoin/bitcoin@9be056a8a7, the v31.1 tag): the oldest is verified, and one still missing an input stays an orphan and the next is tried. Answers whether one was refused or queued for its scripts, as Core answers that it processed one.

btclib_node.p2p.callbacks.sendaddrv2(node: Node, msg: bytes, conn: Connection) → None[source]

Record that the peer wants addrv2 gossip rather than addr.

btclib_node.p2p.callbacks.sendcmpct(node: Node, msg: bytes, conn: Connection) → None[source]

Record whether the peer wants new blocks announced as cmpctblock.

Core’s SENDCMPCT handler (src/net_processing.cpp) on master, at bitcoin/bitcoin@ba8fdb9717: the announce octet is read as a uint8_t, not a bool, so a value above one is refused as “invalid sendcmpct announce field” before a version other than CMPCTBLOCKS_VERSION is ignored; otherwise the announce octet is the peer’s choice of this node as a BIP152 high-bandwidth peer, which a later sendcmpct can take back. Either way the peer is one that provides compact blocks, which cmpctblock below and DownloadManager.headers_direct_fetch read.

v31.1, at bitcoin/bitcoin@9be056a8a7, the release .github/workflows/integration-bitcoind.yml pins and the integration tests run against, still reads the octet as a plain bool and never refuses one above one: the uint8_t read and the Misbehaving call are Core commit 2d0dce0af5, on master and in v32.0rc1, not yet in a release.

btclib_node.p2p.callbacks.sendheaders(node: Node, msg: bytes, conn: Connection) → None[source]

Record that the peer wants new blocks announced as headers (BIP130).

btclib_node.p2p.callbacks.settle_tx(node: Node, check: TxCheck, refusal: Exception | None) → None[source]

Keep and announce a transaction whose scripts pass, or record why not.

On Node’s thread, once its scripts are checked: refusal is what the check raised, if anything. The chain and the mempool may have moved while the scripts ran, so every other check runs again first, against them as they are now. The scripts’ verdict still holds if they pass: a prevout is fixed by its outpoint, and interpreter.STANDARD_FLAGS reads no height.

btclib_node.p2p.callbacks.tx(node: Node, msg: bytes, conn: Connection) → None[source]

Check an unsolicited transaction, and queue its scripts to be checked.

A no-op in initial block download, if the mempool already holds this wtxid, has recently refused it, a block recently confirmed it or the orphanage keeps it, or if the transaction fails a check other than its scripts. One whose inputs are not found is kept as an orphan, and one refused for a fee floor is tried with a child the peer sent, if the peer sent one (_start_package). Otherwise its scripts are queued in node.tx_checks (p2p/tx_checks.py), and settle_tx decides it once they are checked.

A block-relay-only peer sending one is disconnected, and not discouraged, as Core’s TX handler does first of all where RejectIncomingTxs holds (net_processing.cpp, at bitcoin/bitcoin@9be056a8a7, the v31.1 tag).

btclib_node.p2p.callbacks.verack(node: Node, msg: bytes, conn: Connection) → None[source]

Complete a peer’s handshake: promote it and send the follow-up messages.

Ignores a verack ahead of version, as Core’s ProcessMessage ignores any message there (src/net_processing.cpp, at bitcoin/bitcoin@9be056a8a7, the v31.1 tag). A peer that sent no wtxidrelay ahead of it completes its handshake all the same, and has transactions relayed by txid, as in Core.

btclib_node.p2p.callbacks.version(node: Node, msg: bytes, conn: Connection) → None[source]

Handle a peer’s version: refuse an incompatible peer, else continue.

A second version ahead of this connection’s own verack is ignored outright – Core’s own guard, pfrom.nVersion != 0 (net_processing.cpp:3823, at bitcoin/bitcoin@5f45583e43), which logs and returns before doing anything else. conn.status stays Open until verack promotes it, so a repeat sent before that point reaches this callback, and unguarded would resend WtxidRelay, SendAddrV2 and Verack in answer. btclib-org/btclib-node#482

Continuing means answering verack, with wtxidrelay and sendaddrv2 ahead of it where the common version reaches WTXID_RELAY_VERSION and, to an inbound peer, this node’s own version ahead of all three; setting up address relay with a peer this node dialled, and asking it for addresses; recording a peer this node dialled as answered, block-relay-only peers and feelers included, right where Core calls AddrMan::Good – not waiting for its own verack, which may never come (#1169); and recording whether the peer asked to have transactions relayed. A feeler is then dropped once those are written, as Core’s VERSION handler ends one (net_processing.cpp, at bitcoin/bitcoin@9be056a8a7, the v31.1 tag).

btclib_node.p2p.callbacks.wtxidrelay(node: Node, msg: bytes, conn: Connection) → None[source]

Record that the peer relays transactions by wtxid (BIP339).

Ignored from a peer whose common version is below WTXID_RELAY_VERSION, as Core ignores it.

btclib_node.p2p.chain_sync module

Whether an outbound peer keeps up with this node’s chain.

ChainSyncTimeoutState is Core’s CNodeState::m_chain_sync (src/net_processing.cpp, at bitcoin/bitcoin@9be056a8a7, the v31.1 tag), and the two functions below are the two of Core’s that write it: consider_eviction is ConsiderEviction, which DownloadManager.step runs for every connected peer as Core’s SendMessages does, and protect_if_caught_up is the protection at the end of UpdatePeerStateForReceivedHeaders, which callbacks.headers runs on a batch that connects. disconnect_if_insufficient_work is the check that function makes before it, during initial block download.

Core applies them to different sets of outbound connections, which _outbound_or_block_relay and _full_outbound name after Core’s IsOutboundOrBlockRelayConn and IsFullOutboundConn: every automatic outbound connection but a feeler for the first, and for the second those of them not block-relay-only. A block is a hash here where Core holds a CBlockIndex*, as in block_availability.

class btclib_node.p2p.chain_sync.ChainSyncTimeoutState(timeout: float = 0, work_header: bytes | None = None, sent_getheaders: bool = False, protect: bool = False)[source]

Bases: object

Core’s ChainSyncTimeoutState, one per peer.

timeout is when the peer must have caught up, 0 where no timeout is set; work_header is the tip it must match the work of; sent_getheaders is whether it has been asked once; and protect exempts it from all of this for as long as it is connected.

btclib_node.p2p.chain_sync.consider_eviction(node: Node, conn: Connection, now: float, send_getheaders: Callable[[Node, Connection, list[bytes]], bool]) → None[source]

Give an outbound peer behind this node’s tip a deadline, then drop it.

Core’s ConsiderEviction: a peer whose best known block has less work than the tip gets CHAIN_SYNC_TIMEOUT, then one getheaders from the parent of the tip it was measured against and HEADERS_RESPONSE_TIME to answer, and is disconnected if it has still not caught up. A peer reaching the tip’s work clears the timeout, and one reaching only the old tip’s work gets a new one against the current tip. It applies to a peer this node has started syncing headers from and has not protected. send_getheaders is callbacks.maybe_send_getheaders, Core’s MaybeSendGetHeaders.

btclib_node.p2p.chain_sync.disconnect_if_insufficient_work(node: Node, conn: Connection) → bool[source]

Drop an outbound peer whose headers chain lacks the minimum chain work.

The initial-block-download check of Core’s UpdatePeerStateForReceivedHeaders: a peer this node drew itself, whose best known block has less work than node.config’s own minimum_chain_work, is disconnected, as it cannot serve a chain this node would download. callbacks.headers asks it only of a batch it has indexed, past the low-work gate, from a message short of a full one, the gates Core puts in front of it. Answers whether the peer was dropped.

btclib_node.p2p.chain_sync.protect_if_caught_up(node: Node, conn: Connection) → None[source]

Exempt an outbound peer with the tip’s work from consider_eviction.

The end of Core’s UpdatePeerStateForReceivedHeaders: a peer this node drew itself, still connected, whose best known block has at least the tip’s work, is protected while fewer than MAX_OUTBOUND_PEERS_TO_PROTECT_FROM_DISCONNECT are. Core counts in m_outbound_peers_with_protect_from_disconnect, which drops as a protected peer is finalized; this counts the connections held.

btclib_node.p2p.compact_block module

BIP152 compact blocks, as this node sends and receives them.

compact_block is a block as the cmpctblock this node sends of it. callbacks serves one asked for, and main’s block announcement sends one to a high-bandwidth peer. callbacks imports main, so what both need cannot live there.

block_checked is what main.update_chain calls for every block it connects, and it is where a peer that gave this node a new block is chosen as one of its high-bandwidth peers (maybe_set_peer_as_announcing_header_and_ids).

class btclib_node.p2p.compact_block.MostRecentBlock(block: Block, compact: CmpctBlock)[source]

Bases: object

The block new_pow_valid_block last kept, and its cmpctblock.

Core’s m_most_recent_block and m_most_recent_compact_block (src/net_processing.cpp, at bitcoin/bitcoin@9be056a8a7, the v31.1 tag), which m_most_recent_block_hash names. txs is Core’s m_most_recent_block_txs, built with them: every transaction of the block under its txid and under its wtxid, the two kept apart as Core’s GenTxid does.

property hash: bytes

Return the block’s hash, Core’s m_most_recent_block_hash.

btclib_node.p2p.compact_block.block_checked(node: Node, block_hash: bytes, *, valid: bool) → None[source]

Take in that a block was connected, or refused, by update_chain.

Core’s BlockChecked (src/net_processing.cpp, at bitcoin/bitcoin@9be056a8a7, the v31.1 tag), which ConnectTip calls for each block it connects or refuses. A valid block that came from a peer (DownloadManager.block_source) makes it a high-bandwidth peer, out of initial block download and where no other block is in flight, as Core’s “this is currently the best block we’re aware of”. A refused one costs the peer that sent it, unless it came through BIP152: Core’s MaybePunishNodeForBlock for BLOCK_CONSENSUS. The block’s source is then forgotten.

btclib_node.p2p.compact_block.compact_block(block: Block, nonce: int) → CmpctBlock[source]

Return block as a cmpctblock, the coinbase alone sent whole.

Core’s CBlockHeaderAndShortTxIDs constructor: the coinbase prefilled at index 0, and every other transaction by the short id of its wtxid under the key nonce and the header give.

btclib_node.p2p.compact_block.maybe_set_peer_as_announcing_header_and_ids(node: Node, conn_id: int) → None[source]

Ask a peer to announce new blocks as cmpctblock, dropping the oldest.

Core’s MaybeSetPeerAsAnnouncingHeaderAndIDs (src/net_processing.cpp, at bitcoin/bitcoin@9be056a8a7, the v31.1 tag), over DownloadManager.hb_peers, Core’s lNodesAnnouncingHeaderAndIDs. Nothing for a peer gone or one that sent no sendcmpct of version 2. A peer already chosen moves to the end. Otherwise, where _HB_PEERS are chosen, the first is sent sendcmpct(0, 2) and dropped, an outbound one being kept where it is the only outbound left and an inbound peer is the one added. The peer is sent sendcmpct(1, 2) and added at the end.

A peer id stays in the list after its peer is gone, as in Core.

btclib_node.p2p.connection module

Connection, one peer-to-peer socket and the messages framed over it.

Feeds what it reads off the wire to its Transport (p2p/transport.py, which frames the octets and bounds what any one message may claim to be) and hands each message that comes out to P2pManager, writes what Node’s own thread queues back out through the same transport, and bounds what it will buffer in either direction – recv_flood_size on how much of what this connection has already handed to P2pManager.messages or P2pManager.handshake_messages may sit there unprocessed before this connection’s own run stops reading any further, and send_buffer_max_size on how much it may owe the peer before pause_send holds its later messages, as Core’s fPauseSend does, per the comments beside each in Connection.__init__.

class btclib_node.p2p.connection.AddrKnown[source]

Bases: RollingBloomFilter

The addresses a peer sent this node or was sent, by service_key.

Core’s Peer::m_addr_known, a CRollingBloomFilter{5000, 0.001} (src/net_processing.cpp:5707, at bitcoin/bitcoin@9be056a8a7, the v31.1 tag). Like Core’s, it leaves out of a getaddr answer up to one in a thousand of the addresses the peer neither sent nor was sent.

Reached from Node’s thread, by the addr, addrv2 and getaddr callbacks and by push_address for a relayed address, and from P2pManager’s, by the self-announcement and _send_queued_addrs. Each call holds a lock, as Core’s g_msgproc_mutex guards its filter.

add(key: bytes) → None[source]

Insert key, Core’s insert.

reset(*, tweak: int | None = None) → None[source]

Forget every key, as Core’s reset does, with a new tweak.

The tweak is tweak where given, drawn at random otherwise.

The words are freed, and allocated again at the next add.

class btclib_node.p2p.connection.Connection(manager: P2pManager, client: socket.socket, address: NetworkAddressV2, connection_id: int, *, inbound: bool, use_v2transport: bool = False, allow_v1: bool = True, send_buffer_max_size: int = 1000000, recv_flood_size: int = 5000000)[source]

Bases: object

One peer-to-peer socket and everything owed to or by it.

The module docstring above is where its own three jobs – framing, writing what Node’s thread queues, and bounding what it buffers – are argued.

async async_send(payload: Payload) → None[source]

Frame payload and send it.

What run awaits for an outbound connection’s version: it runs on the loop already, and wants that on the wire before it reads anything back. Every other sender in this tree reaches send below instead.

property block_availability: BlockAvailability[source]

What this peer is known to have of the block chain.

property chain_sync: ChainSyncTimeoutState[source]

Whether this peer is behind this node’s tip, and since when.

property connected_through_network: Network

the network of the peer.

Type:

Core’s CNode::ConnectedThroughNetwork

own_version() → Version[source]

Build this node’s own version message, recording its nonce.

Sent by run as soon as an outbound connection opens, and by callbacks.version to an inbound peer whose own version it has accepted, which is where Core’s ProcessMessage calls PushNodeVersion for each (src/net_processing.cpp, at bitcoin/bitcoin@9be056a8a7, the v31.1 tag).

parse_messages(data: bytes) → None[source]

Feed data to the transport, queueing each message it completes.

A trailing partial message stays in the transport for the next read, and each complete one is routed to handshake_messages or messages. Every item carries its own weight, _recv_memusage, a fourth tuple element handle_p2p or handle_p2p_handshake (p2p/main.py), or resume_tx_checks for a message they held back, weighs back off queued_recv_bytes once it is processed (btclib-org/btclib-node#462); handshake_messages is still drained whole every pass of Node’s own loop rather than sharing messages’s own log2-scaled share, which bounds how long a backlog persists but not how large one can grow between two passes – what the weight on this queue’s own items is for, argued beside consumed below. btclib-org/btclib-node#482

A fifth element is the time it was read off the socket, for callbacks.pong (P2pManager.messages’s own comment). A handshake command goes to handshake_messages, and so does anything else read while the connection is still Open, so that no message overtakes the verack that precedes it. btclib-org/btclib-node#1657

Core’s ReceiveMsgBytes (src/net.cpp, at bitcoin/bitcoin@9be056a8a7, the v31.1 tag): the transport refusing octets raises, and the connection is dropped by run. A message it rejects is counted and the connection goes on.

push_address(address: NetworkAddressV2) → None[source]

Queue address for this peer, as Core’s PushAddress does.

An address the peer knows is left out, and so is one an addr version 1 peer cannot read. In a full queue, address replaces one entry at random. The check against addr_known only saves space: the sender checks again, for what the peer came to know meanwhile.

replace_addresses(addresses: Iterable[NetworkAddressV2]) → None[source]

Empty the queue and push addresses, in one step.

Core’s GETADDR handler does this under g_msgproc_mutex, which MaybeSendAddr takes too: a send never finds half the answer.

async run() → None[source]

Send version if outbound, then dispatch messages until stop.

An inbound connection is sent this node’s version by callbacks.version, once the peer’s own has been accepted.

Always ends in stop, whether by a graceful return, a caught exception, or the finally below catching a cancellation from outside this loop – the comment above this method argues why.

send(msg: Payload) → None[source]

Serialize and count msg here, and schedule its write onto the loop.

The synchronous entry point, safe to call from any thread: run_coroutine_threadsafe is what lets both Node’s own thread (through the p2p.callbacks handlers) and P2pManager’s own (through send_ping) reach the loop without ever awaiting directly. Only the framing and the write are scheduled: _queue runs here, on the caller’s own thread, so that a caller sending several messages in a row – advance_getdata (p2p/callbacks.py) checking pause_send before each item it serves – reads its own hand-off back rather than a count the loop has yet to make.

Serializing the payload here rather than on the loop is what that costs, and it is paid by the thread that asked for the message: for the largest of them, a block, that is the thread which has just read it out of block_db. The transport adds the header, and its checksum, on the loop.

send_ping() → None[source]

Send a ping with a fresh nonzero nonce, recording it under lock.

Called from Node’s own thread, twice over (callbacks.verack once a handshake completes, and rpc.callbacks.ping through ping_all), and from P2pManager’s own thread once (manage_connections); _ping_lock is what keeps its own two writes one step against callbacks.pong’s read and clear.

At a common version of BIP0031_VERSION or below it is a NoncelessPing, as in Core’s MaybeSendPing (src/net_processing.cpp, at bitcoin/bitcoin@9be056a8a7, the v31.1 tag): no pong answers it, so nothing is recorded as outstanding. btclib-org/btclib-node#1204

stop(*, cancel_task: bool = True) → None[source]

Close the socket and cancel task, idempotent on a repeat call.

Called from Node’s own thread and from P2pManager’s alike; the comment below is where that and its own safety are argued.

stop_when_sent() → None[source]

Stop once every message already handed to send is written.

Core sets fDisconnect on a feeler after PushMessage has already written what it sent, and a bare stop here would close the socket ahead of it. Each send schedules its write through run_coroutine_threadsafe in turn, and this call after them; callbacks run in that order, and each write queues on _write_lock ahead of this one, which the lock hands on in the order it was asked for.

take_addresses() → list[NetworkAddressV2][source]

Return the queued addresses and empty the queue.

class btclib_node.p2p.connection.KnownTxInventory[source]

Bases: RollingBloomFilter

The latest transaction hashes a peer announced to this node or was sent.

Core’s TxRelay::m_tx_inventory_known_filter, a CRollingBloomFilter{50000, 0.000001} (src/net_processing.cpp:307, at bitcoin/bitcoin@9be056a8a7, the v31.1 tag). Like Core’s, it withholds a transaction from a peer that lacks it about once in a million queries.

A txid for a peer without wtxid relay and a wtxid otherwise, as Core’s filter holds them. Reached from Node’s thread alone: the inv and tx callbacks and DownloadManager write and read it, P2pManager’s thread never does, so it needs no lock.

class btclib_node.p2p.connection.PeerStats(time_offset: int = 0, last_inv_sequence: int = 1, addr_processed: int = 0, addr_rate_limited: int = 0, bytes_sent: int = 0, bytes_recv: int = 0, bytes_sent_per_msg: Counter[str] = <factory>, bytes_recv_per_msg: Counter[str] = <factory>)[source]

Bases: object

What getpeerinfo reads of a connection and nothing else does.

time_offset is Core’s Peer::m_time_offset, the peer’s version timestamp less this node’s clock when callbacks.version read it, in whole seconds. last_inv_sequence is TxRelay::m_last_inv_sequence, Mempool.sequence as of this connection’s last trickle, which DownloadManager writes, and 1 before the first, where Core starts it. addr_processed and addr_rate_limited are Peer::m_addr_processed and m_addr_rate_limited, which callbacks.addr and callbacks.addrv2 count on Node’s thread.

The rest are Core’s nSendBytes, nRecvBytes and their per-command tables: the octets written to and read off the socket, the tables by the message the octets are for, header included: the received one per whole message, the sent one per chunk the socket takes. Each is written on this connection’s loop alone, by _deliver and run, and read from Node’s thread, which copies a table before iterating it.

btclib_node.p2p.connection.local_services(config: Config) → ServiceFlags[source]

Return the services this node offers, Core’s own g_local_services.

own_version below sends this, and rpc.callbacks.get_network_info answers getnetworkinfo’s localservices/localservicesnames from it too – one function rather than each computing its own, as ISS 1394 asks.

NODE_NETWORK_LIMITED is set unconditionally and NODE_NETWORK only where this node is not pruned, matching Core’s own g_local_services (src/init.cpp, at bitcoin/bitcoin@ca7162cde5): NODE_NETWORK_LIMITED | NODE_WITNESS from the start, gaining NODE_NETWORK only once !chainman.m_blockman.IsPruneMode() (:2026-2028). Config.pruned answers that check here, one fixed set of services for every connection rather than the per-chainstate assumeutxo case Core’s own comment there also covers – this tree has no counterpart to a background snapshot sync.

NODE_COMPACT_FILTERS is BIP157’s, and saying it promises an answer to getcfilters, getcfheaders and getcfcheckpt for every block of the chain. Config.peerblockfilters is Core’s own -peerblockfilters (src/init.cpp:992-998, at bitcoin/bitcoin@9be056a8a7, the v31.1 tag), off by default there (DEFAULT_PEERBLOCKFILTERS, src/net_processing.h) as it is here. The filter index is caught up before the node starts listening and kept up as blocks connect, so the promise holds whenever peerblockfilters is on.

NODE_P2P_V2 is set where Config.v2transport is, as Core’s -v2transport sets it (src/init.cpp:987-990, same sha): it says that a connection to this node may use BIP324, which Connection then does (use_v2transport).

btclib_node.p2p.eviction module

Which inbound peer a full P2pManager disconnects to make room.

select_node_to_evict is Core’s SelectNodeToEvict and protect_eviction_candidates_by_ratio its ProtectEvictionCandidatesByRatio (src/node/eviction.cpp), and net_group is NetGroupManager::GetGroup with no asmap loaded (src/netgroup.cpp), all read at bitcoin/bitcoin@9be056a8a7, the v31.1 tag. The selection is pure: it reads EvictionCandidate records and returns an id, and P2pManager is what builds the records from its connections and disconnects the peer chosen.

Core sorts each protection step with std::sort, which leaves the order of two equal candidates unspecified; list.sort is stable, so a tie here keeps the order the candidates arrived in. Where Core’s own tests depend on a tie, they depend on std::stable_sort over the disadvantaged networks, which list.sort reproduces.

class btclib_node.p2p.eviction.EvictionCandidate(id: int, connected: int, min_ping_time: float, last_block_time: int, last_tx_time: int, relevant_services: bool, relay_txs: bool, bloom_filter: bool, keyed_net_group: int, prefer_evict: bool, is_local: bool, network: Network, noban: bool, inbound: bool)[source]

Bases: object

Core’s NodeEvictionCandidate (src/node/eviction.h), field for field.

Times are whole seconds since the epoch, as Core’s are, and 0 where nothing has happened yet; min_ping_time is seconds and infinite until a ping is answered, Core’s microseconds::max(). inbound stands for m_conn_type == ConnectionType::INBOUND, this node having no other connection type an eviction would treat differently.

class btclib_node.p2p.eviction.Network(*values)[source]

Bases: IntEnum

Core’s enum Network (src/netaddress.h), in its own order.

btclib_node.p2p.eviction.get_network(address: NetworkAddressV2) → Network[source]

Core’s CNetAddr::GetNetwork, what m_network_conn_counts is keyed on.

Unlike net_class, an IPv6 address carrying an IPv4 one is IPv6.

btclib_node.p2p.eviction.is_internal(ip: IPv6Address) → bool[source]

Core’s CNetAddr::IsInternal: whether ip is under the internal prefix.

SetLegacyIPv6 reads an IPv6 address under INTERNAL_IN_IPV6_PREFIX (src/netaddress.h, at bitcoin/bitcoin@9be056a8a7, the v31.1 tag) as NET_INTERNAL, whatever the peer or resolver meant by it. LookupIntern’s own collection loop (src/netbase.cpp:144-168, same sha) asks exactly this, and nothing more, of each answer before counting it toward Lookup’s nMaxSolutions – is_valid below asks this and more, but only once collection is already done.

btclib_node.p2p.eviction.is_local(address: NetworkAddressV2) → bool[source]

Core’s CNetAddr::IsLocal, what m_is_local is read from.

btclib_node.p2p.eviction.is_routable(address: NetworkAddressV2) → bool[source]

Core’s CNetAddr::IsRoutable, what AddrManImpl::AddSingle asks first.

An IP address is _is_routable’s to answer rather than is_valid’s, which reads the octets of an addr v1 field: _ip reads a mapped IPv4 address as is_valid does, and the prefixes is_valid refuses ahead of _is_valid lie inside RFC4193’s range, which _is_routable refuses too. A TORv3 or an I2P address is routable, and a CJDNS one under Core’s CJDNS_PREFIX alone: that prefix is the clause of IsValid about a CJDNS address, and no range of IsRoutable reaches one. Core decodes any other network id as an address IsValid refuses (CNetAddr::UnserializeV2Stream, at bitcoin/bitcoin@9be056a8a7, the v31.1 tag), BIP155’s TORv2 id and Yggdrasil’s included. An IPv6 record embedding IPv4 or Tor v2, which Core decodes as invalid too, is left to is_embedded_ipv6, run ahead of this.

btclib_node.p2p.eviction.is_valid(ip: IPv6Address) → bool[source]

Core’s CNetAddr::IsValid of the sixteen octets of an addr v1 field.

What CNetAddr::V1 deserializes, through SetLegacyIPv6: a mapped IPv4 address read as IPv4, one under the internal prefix as NET_INTERNAL, which is invalid, and one under the Tor v2 prefix as the unspecified address, which is invalid too.

btclib_node.p2p.eviction.keyed_net_group(key: bytes, address: NetworkAddressV2) → int[source]

Core’s CConnman::CalculateKeyedNetGroup: net_group, keyed-hashed.

Core keys a SipHash with this node’s own random seeds, so a peer cannot predict which netgroups sort last and are protected; a keyed BLAKE2b under key, P2pManager’s own random draw, is the same property from what hashlib offers.

btclib_node.p2p.eviction.net_class(address: NetworkAddressV2) → Network[source]

Core’s CNetAddr::GetNetClass, what m_network is read from.

NET_INTERNAL answers for an IPv6 address under Core’s internal prefix, as it does in Core, where accepting a peer parses its address through SetLegacyIPv6.

btclib_node.p2p.eviction.net_group(address: NetworkAddressV2) → bytes[source]

Core’s NetGroupManager::GetGroup with no asmap: the peer’s netgroup.

The net class, then IPv4’s /16 (an IPv6 address carrying an IPv4 one counting as that IPv4 address), he.net’s /36 or the rest of IPv6’s /32. Every local and every other unroutable address shares the one group 00, NET_UNROUTABLE’s class alone, while an internal address is a group of its own, the ten octets after its prefix. Core buckets by autonomous system instead where -asmap is given, which this node has no counterpart to.

A Tor or I2P address is the net class and the first four bits of its octets, a CJDNS one the first twelve, the rest of the last octet set.

btclib_node.p2p.eviction.protect_eviction_candidates_by_ratio(candidates: list[EvictionCandidate]) → None[source]

Protect half of candidates by uptime, a quarter by network first.

Core’s ProtectEvictionCandidatesByRatio, removing in place what it protects. I2P and CJDNS peers never reach it from this node, which dials and listens on IPv4 and IPv6 alone, so of the four disadvantaged networks only localhost and an =onion listener’s peers ever hold one.

btclib_node.p2p.eviction.select_node_to_evict(candidates: Iterable[__annotationlib_name_1__]) → int | None[source]

Return the id of the peer to evict, None where every one is protected.

Core’s SelectNodeToEvict, step for step and with Core’s own counts.

btclib_node.p2p.headers_sync module

The low-work headers sync: a peer’s chain downloaded twice before it is kept.

HeadersSyncState is Core’s class of the same name (src/headerssync.h and src/headerssync.cpp, at bitcoin/bitcoin@9be056a8a7, the v31.1 tag), and anti_dos_work_threshold is its GetAntiDoSWorkThreshold (src/net_processing.cpp, same sha). callbacks.headers starts one per peer whose full batch of headers connects to this node’s index on a chain with less work than that threshold, and hands it every batch that peer sends until it ends: in PRESYNC the headers are counted and, every commitment_period headers from a secret offset, one salted bit of a header’s hash is kept; once the work clears the threshold, REDOWNLOAD asks for the same chain again from its start, checks each kept bit against it, and hands headers back for indexing only once redownload_buffer_size more have been checked behind them, or once the redownloaded chain clears the threshold itself. Nothing of the chain is indexed before that, so a chain that never clears it costs this node the bits and the buffer and nothing on disk.

What differs from Core is the language’s and is said where it is: the buffer, the bit queue, the randomness, the result and the end of an object, each beside the code it shapes.

Every object here is reached from Node’s thread alone – headers writes Connection.headers_sync, and getpeerinfo, which reads it, runs on the same loop – so none takes the lock Core’s m_headers_sync_mutex is: ARCHITECTURE.md’s The protocol and the RPC surface is that argument.

class btclib_node.p2p.headers_sync.ChainStart(header: BlockHeader, height: int, chainwork: int, median_time_past: int, locator: tuple[bytes, ...])[source]

Bases: object

The indexed block a low-work chain builds on: Core’s m_chain_start.

Core keeps a reference to the CBlockIndex and reads what it needs off it; this carries those same values, read off BlockIndex once by from_index: the header, its height and work, its median time past, and the locator Core rebuilds from it on every request, which is the same list each time.

classmethod from_index(block_index: BlockIndex, block_hash: bytes) → ChainStart[source]

Read the chain start block_hash names off block_index.

class btclib_node.p2p.headers_sync.HeadersSyncState(consensus: ConsensusParams, params: HeadersSyncParams, chain_start: ChainStart, minimum_required_work: int, *, now: float | None = None, commit_offset: int | None = None, salt: tuple[int, int] | None = None)[source]

Bases: object

One peer’s low-work headers sync: Core’s HeadersSyncState.

next_headers_request_locator() → list[bytes][source]

Return the locator to ask for the next batch: Core’s own.

The last header PRESYNC took, or the last one REDOWNLOAD buffered, then the chain start’s own locator. Empty for an ended sync, Core’s Assume guard, which no caller here reaches.

property presync_height: int

the height PRESYNC has reached.

Type:

Core’s GetPresyncHeight

property presync_time: int

the last PRESYNC header’s timestamp.

Type:

Core’s GetPresyncTime

property presync_work: int

the work PRESYNC has counted.

Type:

Core’s GetPresyncWork

process_next_headers(headers: Sequence[BlockHeader], *, full_headers_message: bool) → ProcessingResult[source]

Take the peer’s next batch: Core’s ProcessNextHeaders.

The caller has checked each header’s own proof of work and that the batch is continuous. full_headers_message is whether the batch held MAX_HEADERS_RESULTS headers, the peer then maybe having more. The result says whether the batch was taken, whether to ask for more with next_headers_request_locator, and which headers are ready to be indexed; the sync ends, FINAL, wherever it is not both taken and asking for more.

An empty batch, or one given to an ended sync, is refused without ending anything: Core’s Assume guards, which no caller here reaches.

class btclib_node.p2p.headers_sync.ProcessingResult(pow_validated_headers: list[BlockHeader], success: bool, request_more: bool)[source]

Bases: NamedTuple

Core’s HeadersSyncState::ProcessingResult.

Returned rather than swapped into the caller’s own list, which is what Core’s caller does with it.

pow_validated_headers: list[BlockHeader]

Alias for field number 0

request_more: bool

Alias for field number 2

success: bool

Alias for field number 1

class btclib_node.p2p.headers_sync.State(*values)[source]

Bases: Enum

Core’s HeadersSyncState::State.

PRESYNC counts the peer’s chain and keeps commitments to it, REDOWNLOAD downloads it again and checks them, and FINAL is an ended sync, whose object is dropped.

btclib_node.p2p.headers_sync.anti_dos_work_threshold(block_index: BlockIndex, minimum_chain_work: int) → int[source]

Return the work below which a chain is not indexed unseen.

Core’s GetAntiDoSWorkThreshold (src/net_processing.cpp, at bitcoin/bitcoin@9be056a8a7, the v31.1 tag): the active tip’s work less 144 blocks of the tip’s own work, and never less than minimum_chain_work, which callers pass as Config.minimum_chain_work (-minimumchainwork), Core’s MinimumChainWork. The active chain always holds genesis here, where Core allows for no tip at all.

btclib_node.p2p.main module

handle_p2p, handle_p2p_handshake and the three resume_ functions.

The first two pop one message off their own queue – P2pManager.messages or P2pManager.handshake_messages – and dispatch it through p2p.callbacks.callbacks or p2p.callbacks.handshake_callbacks depending on the connection’s own P2pConnStatus. An exception raised by a callback ends that connection’s message rather than the loop: it goes to P2pManager.maybe_discourage_and_disconnect where it is a MisbehavingError, and is logged with the peer kept otherwise: on one line under the net debug category where it is a BTClibValueError, btclib’s parse error, as Core logs what ProcessMessage throws; with its traceback where it is anything else.

Each also weighs its own queued item’s weight back off the connection it came from, queued_recv_bytes, resuming that connection’s own reads (Connection.run) once enough of what it queued is off either queue – the other end of the pacing Connection.parse_messages and Connection.recv_flood_size (p2p/connection.py) start, argued there. btclib-org/btclib-node#462, btclib-org/btclib-node#482

resume_cfilters and resume_getdata instead drain node.pending_cfilters and node.pending_getdata, the connections p2p.callbacks.get_cfilters and p2p.callbacks.getdata paused mid-answer rather than scheduling ahead of what a peer has drained – nothing queued triggers either, so both are called once every pass of run’s own loop regardless.

resume_tx_checks moves node.tx_checks (p2p/tx_checks.py) along, also once every pass.

btclib_node.p2p.main.handle_p2p(node: Node) → None[source]

Pop one queued message and dispatch it, once its handshake is done.

A message ahead of verack is ignored, as Core’s ProcessMessage ignores it (src/net_processing.cpp, at bitcoin/bitcoin@9be056a8a7, the v31.1 tag), except a sendheaders or a sendcmpct after version, which Core records there. A callback that raises is _drop’s, the comment below arguing its split.

Weighs the item’s own weight back off the connection’s queued_recv_bytes the moment it is popped, whatever happens to it next – dispatched, or ignored for want of a callback or of a completed handshake – since what recv_flood_size paces is how much of a connection’s own traffic sits unprocessed, not how that traffic was resolved. A connection paused there is resumed, via call_soon_threadsafe rather than a direct set(), from Node’s own thread onto the connection’s (Connection.__init__’s own comment on _recv_resume argues why the indirection is required). btclib-org/btclib-node#462

A message held back by _hold_message is the exception: it is weighed off when resume_tx_checks reads it, being unprocessed until then.

btclib_node.p2p.main.handle_p2p_handshake(node: Node) → None[source]

Pop one queued handshake message and dispatch it, or drop the peer.

A message of another command is here too, queued behind the handshake commands of a connection that was still Open when it was read: it is dispatched as handle_p2p would, and none overtakes the connection’s verack. btclib-org/btclib-node#1657

Once verack has promoted the connection, a second version or verack is ignored and a wtxidrelay or sendaddrv2 drops the peer undiscouraged, as Core’s ProcessMessage answers each (src/net_processing.cpp, at bitcoin/bitcoin@9be056a8a7, the v31.1 tag). A callback that raises is _drop’s.

Weighs the item’s own weight back off the connection’s queued_recv_bytes the moment it is popped, or when resume_tx_checks reads it if _hold_message held it back, as handle_p2p below does and for the same reason. btclib-org/btclib-node#482

btclib_node.p2p.main.resume_cfilters(node: Node) → bool[source]

Advance every paused getcfilters answer by what now fits.

Answers whether anything did – a connection dropped from node.pending_cfilters counts, same as one whose block hashes shrank – so this only answers False where every paused connection was tried and stayed exactly as paused as it already was. node.pending_cfilters maps a connection id to the connection itself and the block hashes advance_cfilters (p2p.callbacks) has not yet sent – entered there only when that call paused rather than finished. It is written only here and in get_cfilters, and read there and by _hold_message and _read_held, all on Node’s own thread, so nothing here needs a lock.

A connection already closed is dropped without trying it – stop can be called from P2pManager’s own thread too, but the flag it sets, P2pConnStatus.Closed, is read here the same way advance_cfilters already reads it mid-answer. An exception out of advance_cfilters is handled the same way handle_p2p’s own is above, since it is the same call raising it, just on a later turn.

btclib_node.p2p.main.resume_getdata(node: Node) → bool[source]

Advance every paused getdata answer by what now fits.

The same shape as resume_cfilters above, over node.pending_getdata and advance_getdata (p2p.callbacks) instead: answers whether anything did, a connection dropped counting the same as one whose items shrank; a connection already closed is dropped without trying it; and an exception out of advance_getdata is handled the same way handle_p2p’s own is above, being the same call raising it on a later turn.

btclib_node.p2p.main.resume_tx_checks(node: Node) → bool[source]

Settle the check in flight, read held messages, start the next.

Answers whether anything moved. Each step runs on Node’s thread:

  • a check whose verdict is in goes to p2p.callbacks.settle_tx;

  • a check past TX_CHECK_DEADLINE is dropped and logged, its worker presumed gone;

  • each peer with nothing queued and an orphan to reconsider takes one up, ahead of its held messages, as Core’s ProcessMessages takes up an orphan before the next message (p2p.callbacks.process_orphan);

  • each peer free to have one read, as _read_held says, has its oldest held message read, one per peer per pass, as Core’s message handler reads one message per peer per pass;

  • with no check in flight, the oldest candidate queued is handed to node.worker_pool, or dropped if its peer is gone or the mempool has judged it meanwhile, a copy from another peer included.

One check in flight at a time, so a block’s interpreter.check_scripts, which shares the pool, does not wait behind a queue of them; one dropped at its deadline may still be running.

An exception out of settle_tx, out of an orphan or out of a held message is handled as handle_p2p’s own is.

btclib_node.p2p.manager module

P2pManager, the thread listening for and dialing peer connections.

Runs its own asyncio loop – manage_connections accepts inbound sockets, dials outbound ones from PeerDB, and prunes an idle or handshake-stuck Connection – and hands finished messages back to Node’s own thread through messages and handshake_messages. A coroutine enters this loop only through run_coroutine_threadsafe; Node’s own thread calls this class’s plain methods, such as verack’s own promote_connection, directly.

class btclib_node.p2p.manager.P2pManager(node: Node, port: int | None, peer_db: PeerDB, ban_man: BanMan | None = None)[source]

Bases: Thread

The thread listening for and dialling peer connections.

The module docstring above is where its own loop, its two message queues and the boundary with Node’s thread are argued; connections/pending_connections and the lock that guards moving a connection between them are this class’s own state for that.

add_added_peer(node_str: str, *, use_v2transport: bool = False) → bool[source]

Add node_str to the -addnode list, Core’s own AddNode.

AddNode (src/net.cpp, at bitcoin/bitcoin@9be056a8a7, the v31.1 tag) refuses a duplicate two ways: the identical string already held, or – where both node_str and an existing entry name an address – the same LookupNumeric resolution, _numeric_endpoint above. A name only ever matches the identical string already caught by the first check, so the second check fires between two specs naming an address, an onion or I2P one included, exactly where Core’s does (btclib-org/btclib-node#1369). Returns whether node_str was added, AddNode’s own bool. use_v2transport is kept with it, as AddedNodeParams keeps it, for the dial loop.

add_pending_outbound_nonce(nonce: int) → None[source]

Record nonce as this outbound, still-unhandshaken connection’s own.

The only caller is Connection.own_version, for an outbound connection. _connections_lock (__init__) is what every access to pending_outbound_nonces goes through – this write included – so it can never land between is_self_connect_nonce below reading the set and returning.

async async_connect(address: NetworkAddressV2) → None[source]

Dial address and, if it comes up, register the connection.

Logged rather than silent where dial (p2p/address.py) comes back with nothing: unlike _maybe_dial_more_peers below, whose next pass draws another address, connect is only ever called once per already-resolved address – a caller reaching for one specific peer it already holds as a NetworkAddressV2, a test connecting two nodes among them – so a dial lost here has nothing behind it to try again, and used to vanish with nothing in debug.log naming it (issue #1020). A caller holding a host rather than a resolved address, -connect/-addnode’s own redial among them, wants async_connect_host instead (btclib-org/btclib-node#1264).

Refuses silently where network_active is false, the same OpenNetworkConnection’s own if (!fNetworkActive) { return false; } does (src/net.cpp, at bitcoin/bitcoin@9be056a8a7, the v31.1 tag) – no log line there either, only the refusal.

async async_connect_host(dest: str, default_port: int, *, addr_fetch: bool = False, automatic: bool = False, block_relay: bool = False, feeler: bool = False, use_v2transport: bool = False) → None[source]

Resolve dest and dial what it names, ConnectNode’s pszDest arm.

use_v2transport is the caller’s, as Core’s OpenNetworkConnection takes it: a name has no services to ask.

dest is Core’s own pszDest, kept whole rather than split ahead of the call: ConnectNode itself resolves Lookup(pszDest, default_port, …) from the raw destination string, not from a pre-split host and port, which is what lets a spec naming its own port – -connect=1.2.3.4:9999 – reach m_addr_name with that port still on it, and a portless one without (btclib-org/btclib-node#1493). lookup_host_port below is this tree’s own Lookup, called here rather than by any caller: a spec whose port is no port is looked up whole, as a name, and resolves to nothing (btclib-org/btclib-node#1292).

OpenNetworkConnection’s own AlreadyConnectedToHost(pszDest) (src/net.cpp, at bitcoin/bitcoin@9be056a8a7, the v31.1 tag) runs on the unresolved string first, before any resolve: compared against m_addr_name, not an address, because no address exists yet to key on. addr_name (p2p/connection.py) is this tree’s own record of that string, held only by a connection this method itself dialled – every other dial route leaves it None. Past that check, ConnectNode resolves pszDest (src/net.cpp:404-424, same sha), an internal answer dropped and the rest capped at _MAX_RESOLVED_ADDRESSES, in that order, before any of it is shuffled (btclib-org/btclib-node#1466): every answer shuffled, then validated and checked against AlreadyConnectedToAddressPort in that same, unmodified order, the whole attempt abandoned on the first answer either check refuses – never on a later one alone, however many earlier answers would have connected – and only once every answer has cleared both checks does a second pass dial each in turn, the first that connects kept (btclib-org/btclib-node#1284). addrman.Attempt, which async_connect above also calls, is called once per candidate this second pass dials, as ConnectNode’s own for loop does regardless of pszDest – a no-op where peer_db holds no entry for it, PeerDB.attempt’s own docstring.

The one caller with its own retry, _process_addr_fetch, is the only one passing addr_fetch=True; the others – -connect and -addnode’s own redial, the addnode RPC, Node.run’s startup dial – want a dial that came up with nothing logged the way async_connect logs it, since nothing else names the attempt (btclib-org/btclib-node#1264). automatic, block_relay and feeler are connect_typed’s own (addconnection’s RPC), unset by every other caller: create_connection reads all four flags straight off whichever this call was given, the same fields a drawn automatic dial (_dial_one_draw) sets directly.

Refuses silently where network_active is false, async_connect above’s own docstring giving the citation.

broadcast_raw_transaction(tx: BtclibTx, fee: int) → None[source]

Queue tx for the inv/getdata round trip, not a direct send.

The comment below is where this, and fee going unread here, are argued.

connect(address: NetworkAddressV2) → None[source]

Schedule async_connect(address) onto this manager’s own loop.

connect_host(dest: str, default_port: int, *, use_v2transport: bool = False) → None[source]

Schedule async_connect_host on this manager’s own loop.

connect_typed(dest: str, default_port: int, *, automatic: bool = False, block_relay: bool = False, feeler: bool = False, addr_fetch: bool = False, reserved: str | None = None, use_v2transport: bool = False) → None[source]

Schedule async_connect_host on this manager’s own loop.

addconnection’s dial: connect_host’s sibling, for a caller setting the flags create_connection reads off a drawn automatic dial. reserved is the connection_type the caller’s reserve_automatic_slot slot was taken as, released once the dial concludes; None where the caller reserved nothing. The release is in the finally of a coroutine wrapping the dial, since this method returns as soon as the dial is scheduled.

create_connection(client: socket, address: NetworkAddressV2, *, inbound: bool, automatic: bool = False, block_relay: bool = False, feeler: bool = False, prefer_evict: bool = False, addr_fetch: bool = False, addr_name: str | None = None, local_address: tuple[str, int] | None = None, inbound_onion: bool = False, granted: NetPermissionFlags | None = None, use_v2transport: bool = False) → None[source]

Build a Connection for client, hold it pending, and start it.

use_v2transport is Core’s own NodeOptions field: the caller decides it, as supports_v2transport below and each dial site say. A failed v2 attempt is retried with v1 by remove_connection where -v1transport allows.

Logs the id this connection is given beside the address it was accepted from or dialled to – the one point every path into a connection shares, before any wire message is parsed, and so the only point at which a handshake exception raised before callbacks.verack reaches its own pairing (p2p/callbacks.py) still leaves this id resolvable to a peer. verack’s own line is not redundant with this one despite both naming an address: that one marks the handshake completing, this one marks the connection existing, and an operator reading debug.log wants both moments where a connection dies between them. btclib-org/btclib-node#611

network_address never raises building that address here: an inbound address only ever comes from peer_address (server below), which only ever returns the two IP networks network_address accepts, and an outbound one only reaches this method once dial (p2p/address.py) has already returned a live socket for it, which dial itself never does for anything else (UnsupportedAddressTypeError) – address_sampler (p2p/address.py) filtering _maybe_dial_more_peers’s own draw to the same two networks first is belt on top of that braces, not what does the guarding.

info, matching verack’s own line: this runs once per connection actually made, dialled or accepted, never once per attempt – async_connect and _maybe_dial_more_peers below only call this once dial has already returned a socket, so a dial that goes nowhere never reaches here to begin with.

Unconditional on the address, like verack’s own line and for the same reason – argued there rather than twice here: Core’s analogous site, CNode’s own constructor (src/net.cpp, at bitcoin/bitcoin@05e49b342f), gates the address on fLogIPs.

local_address is the accepted socket’s own address, concrete where the listener is bound to every interface, None for a dialled connection – the only inbound path, server below, is the only caller that ever passes one. conn.addr_cache_key’s own docstring (connection.py) is where the key built from it is argued.

inbound_onion is Core’s own: the connection reached an =onion listener. Its peer’s address is then the Tor daemon’s, so no -whitelist entry is matched against it.

granted is what the listener the connection reached grants (-whitebind), which -whitelist adds to.

disconnect_subnet(subnet: Subnet) → bool[source]

Drop every peer subnet matches, Core’s DisconnectNode(CSubNet).

Whatever the connection’s kind, a manual one included, and answering whether any matched (src/net.cpp, at bitcoin/bitcoin@9be056a8a7, the v31.1 tag).

discourage(address: NetworkAddressV2) → None[source]

Record the host address is on as discouraged, Core’s Discourage.

maybe_discourage_and_disconnect is the caller, and decides which hosts get here. A discouraged host is not dialled by _maybe_dial_more_peers, is refused by server once the inbound slots are nearly full and accepted otherwise as the first to evict, is left out of a getaddr answer, and is not stored from an addr or addrv2.

Keyed by host_key, without the port, as Core’s BanMan::Discourage is (src/banman.cpp, at bitcoin/bitcoin@9be056a8a7, the v31.1 tag).

get_network_active() → bool[source]

Core’s own CConnman::GetNetworkActive: this manager’s own flag.

is_discouraged(address: NetworkAddressV2) → bool[source]

Whether address’s host is discouraged, Core’s IsDiscouraged.

is_reachable(address: NetworkAddressV2) → bool[source]

Whether this node reaches address’s network, g_reachable_nets.

is_self_connect_nonce(nonce: int) → bool[source]

Whether nonce is a live, unhandshaken outbound connection’s own.

The only caller is callbacks.version. Matches Core’s own live, per-connection search – CConnman::CheckIncomingNonce, net.cpp:360-376 at bitcoin/bitcoin@b91d983f66 – which walks every node still short of fSuccessfullyConnected and not IsInboundConn(), rather than a fixed-size ring: pending_outbound_nonces (__init__) reproduces that search by never holding an inbound connection’s own nonce to begin with (add_pending_outbound_nonce above), not by filtering one out of a wider set at lookup time.

That same walk also excludes a private-broadcast connection’s own nonce, one candidate among the ones it visits – the reason given there is a peer taking such a connection down must not be able to infer this node dropped it and learn its clearnet address from the disconnect. This tree has no private-broadcast connection, so nothing here excludes on that account, and nothing here depends on that exclusion existing either.

Separately, net_processing.cpp:3886 only calls that walk at all for a version arriving on an inbound connection – a second restriction, on when the search runs rather than on what it searches, and not the one the paragraph above is about. Not reproduced here: the set already holds only outbound-origin nonces, so an ordinary peer’s own draw is never found in it regardless of which side received the version, and asking unconditionally costs nothing extra.

local_snapshot() → dict[bytes, LocalService][source]

Return a copy of local_info that no other thread changes.

async manage_connections() → None[source]

Prune, maybe dump, maybe dial, sleep – forever, every 0.1s.

_prune_stale_connections pings or drops an idle peer every pass; _maybe_dump_banlist runs far less often; _disconnect_if_inactive repeats set_network_active’s own one-shot sweep every pass for as long as network_active stays false, its own docstring arguing why a one-shot call is not enough; _maybe_dial_more_peers dials one more only if this node still has room for it, and only every _AUTOMATIC_DIAL_INTERVAL – _AUTOMATIC_DIAL_INTERVAL’s own comment is where that cadence is argued against Core’s (btclib-org/btclib-node#1379), this loop’s own faster sleep below being what every other step here still runs on. -connect and -addnode peers are dialled by loops of their own, _open_connect_peers and _open_added_peers (run, below), issue #651’s own redial and #1316’s replacement of the backoff it first shipped with; _process_addr_fetch is _open_addr_fetches’ own standing loop, for the same reason (btclib-org/btclib-node#1366): an addr-fetch dial can resolve a hostname (a DNS seed subdomain or a -seednode value) before it ever reaches dial, and getaddrinfo and dial both run on this same loop, so a step here that awaited one directly would hold up every pass’ _prune_stale_connections for as long as either took.

maybe_discourage_and_disconnect(conn: Connection) → bool[source]

Drop conn for misbehaving, and discourage its host as Core would.

Core’s MaybeDiscourageAndDisconnect (src/net_processing.cpp, at bitcoin/bitcoin@9be056a8a7, the v31.1 tag), answering whether the host was discouraged. A manual peer, one -connect, -addnode or the addnode RPC dialled, is neither discouraged nor dropped, and neither is a peer holding NO_BAN. An addr-fetch peer is not a manual one. A local peer is dropped alone, since discouraging it would discourage every peer on the same local address. Otherwise the host is discouraged and every connection held with it is dropped, whatever its port and its kind, as Core’s DisconnectNode(CSubNet(addr)) does (src/net.cpp, same sha).

network_conn_counts() → Counter[Network][source]

Core’s m_network_conn_counts: the manual and full-relay peers.

Every MANUAL and OUTBOUND_FULL_RELAY connection held, pending ones included, counted under CNetAddr::GetNetwork.

ping_all() → None[source]

Send every connected peer a fresh ping, through send_ping.

A peer at BIP0031_VERSION or below is sent one with no nonce. btclib-org/btclib-node#1204

promote_connection(connection_id: int) → None[source]

Move a connection out of the handshake and into the herd.

The only caller is callbacks.verack, right after it sets P2pConnStatus.Connected – the two are one step, kept as two calls only because the status belongs to the connection and the dict it lives in belongs to the manager. _connections_lock (__init__) is what makes the pop and the write one step too, against remove_connection’s own two pops below, which this manager’s own thread also runs.

Successfully connected is exactly the state pending_outbound_nonces (__init__) has to stop answering for, so this connection’s own nonce leaves it here too, inside the same locked block – discard rather than a guarded pop, since an inbound connection’s nonce, never added there, is just as harmless to ask it to remove; the is not None guard is only for discard’s own typing, set[int] rather than set[int | None].

relay_address(originator: Connection, address: NetworkAddressV2, now: float) → None[source]

Queue address, gossiped by originator, for one or two peers.

RelayAddress (src/net_processing.cpp, at bitcoin/bitcoin@9be056a8a7, the v31.1 tag): an address on a network this node does not reach is relayed only if is_relayable. Only a peer taking part in address relay is chosen, and one that can carry address: IsAddrCompatible. Called on Node’s thread; push_address takes the lock the send on this manager’s thread shares.

release_automatic_slot(connection_type: str | None = None) → None[source]

Release a slot reserve_automatic_slot took as connection_type.

remove_added_peer(node_str: str) → bool[source]

Remove node_str from the -addnode list, Core’s RemoveAddedNode.

Matched by the exact string alone, as Core’s own loop over m_added_node_params is (src/net.cpp, same sha). Returns whether an entry was removed, RemoveAddedNode’s own bool.

remove_connection(connection_id: int) → None[source]

Drop connection_id from either table and stop it, if it was held.

_connections_lock (__init__) is what makes the two pops one step, against promote_connection’s own pop-then-write. The same connection leaving pending_connections this way is one pending_outbound_nonces (__init__) has to stop answering for too, so its own nonce is discarded inside the same locked block, the same reason promote_connection above does it there rather than after. conn.stop() stays outside the lock, as every other call into Connection from in here does, bar the one _reconnection_for makes, which __init__ argues.

Queues the retry with v1 of an outbound connection whose transport asks for one (_reconnection_for), and logs it as Core does.

reserve_automatic_slot(connection_type: str | None = None) → list[Connection] | None[source]

Check the outbound caps and reserve one slot, in one step.

Core’s CConnman::AddConnection checks the per-type cap, takes a semOutbound grant and runs OpenNetworkConnection synchronously, so its next call already counts the node the last one added (src/net.cpp, at bitcoin/bitcoin@9be056a8a7, the v31.1 tag). Here the dial runs later, on this manager’s loop, and registers only once it connects: a check of held connections alone would let two callers in a row pass a cap only one of them fits under.

So each cap counts held connections plus reservations, and the reservation is taken under the same _connections_lock acquisition as the check. The two caps, in AddConnection’s order:

  • per type: max_outbound_full_relay for outbound-full-relay and max_outbound_block_relay for block-relay-only, none for any other connection_type, as Core sets none for ADDR_FETCH or FEELER;

  • the shared pool, max_automatic_outbound, which every reservation and every automatic or addr-fetch connection counts against, each taking a semOutbound grant in Core.

connection_type is addconnection’s own. None reserves a slot of the pool alone: _maybe_dial_more_peers’ reservation, taken before its kind is chosen, and _process_addr_fetch’s.

The caller releases the slot with release_automatic_slot, of the same connection_type, once the dial concludes. A dial that connected is a held connection by then: create_connection registers it before the release runs, both on this manager’s loop with no await between them, so no check finds the dial counted as neither.

Returns the automatic connections the check counted, or None where a cap was met and nothing was reserved. _maybe_dial_more_peers splits its own counts off that list rather than reading the connections a second time (btclib-org/btclib-node#367 argues the same for two reads).

run() → None[source]

Method representing the thread’s activity.

You may override this method in a subclass. The standard run() method invokes the callable object passed to the object’s constructor as the target argument, if any, with sequential and keyword arguments taken from the args and kwargs arguments, respectively.

seen_local(host: IPv4Address | IPv6Address) → bool[source]

Raise the score of host, one of our own, as SeenLocal does.

SeenLocal (src/net.cpp, at bitcoin/bitcoin@9be056a8a7, the v31.1 tag) adds one to the score of a known address, by host alone, and answers whether it knew it. Called from Node’s thread: local_info is under _local_lock for that.

send(msg: Payload, connection_id: int) → None[source]

Send msg on connection_id, a no-op if that connection is gone.

async server(loop: AbstractEventLoop, server_socket: socket) → None[source]

Accept connections off server_socket, one create_connection each.

Reads through accepted, an asyncio.Queue a task of its own, _accept_loop, fills – rather than a bare await loop.sock_accept(server_socket) right here, which does not have the property the comment below argues for.

set_network_active(*, active: bool) → None[source]

Flip network_active, dropping every held connection on a false.

Core’s own CConnman::SetNetworkActive (src/net.cpp, at bitcoin/bitcoin@aef8a04966, past bitcoin/bitcoin#34213): only where active actually changed, drop every connection this node holds at once, _disconnect_if_inactive’s own docstring arguing why that is not the only time it runs.

On a false, the block-relay-only peers held, the first two opened, become anchors before they are dropped, so they are dialled again once the network is active and are what stop writes. Anchors not yet tried stay where no peer is held.

Reached from the setnetworkactive RPC, on Node’s own thread – the same thread disconnect_node already calls remove_connection from, _connections_lock (__init__) being what makes that safe.

start_listener() → bool[source]

Start this thread, and answer whether it came up as -listen asked.

Blocks until run has bound its listener, failed to, or skipped it under -listen=0, and answers False only for the failure: what Node.run turns into Core’s “Failed to listen on any port”, where start alone would leave the node running with neither a listener nor the dialling run schedules only after the bind. A bind_error is a failure under -listen=0 too, where run ended on an -externalip it could not read. cli refuses that ahead of any manager, as Core does before CConnman::Start, so “Failed to listen on any port” follows it only for a Config built by hand.

stop() → None[source]

Stop this manager’s own loop, then every connection and task on it.

The comment below is the whole of what makes stop_handle itself safe to cancel unconditionally, on any of the three ways run above can have left this loop by the time join returns.

stop_all() → None[source]

Stop every connection this manager holds, per the comment below.

supports_v2transport() → bool[source]

Return whether NODE_P2P_V2 is among the services this node offers.

Core’s GetLocalServices() & NODE_P2P_V2, which every site that picks a transport asks (src/net.cpp, at bitcoin/bitcoin@9be056a8a7, the v31.1 tag).

btclib_node.p2p.manager.network_error_string(error: OSError) → str[source]

Core’s NetworkErrorString of a failed socket call: text, then number.

Core’s “%s (%d)” carries SysErrorString’s errno off Windows and Win32ErrorString’s Winsock code on it (src/util/sock.cpp:426-434, src/util/syserror.cpp:17-50, at bitcoin/bitcoin@9be056a8a7). CPython keeps that code as winerror on what a socket call raises there (set_error, Modules/socketmodule.c at CPython v3.14.0) and renumbers a few of them in errno, WSAEACCES 10013 becoming 13 (PC/errmap.h), so winerror is the number read where it is set.

The text is not Core’s to the byte on Windows: CPython strips trailing whitespace and periods off FormatMessageW’s text before this sees it (Python/errors.c), where Core’s Win32ErrorString prints the buffer FormatMessageA fills without stripping it.

btclib_node.p2p.netif module

This machine’s own interface addresses, Core’s GetLocalAddresses.

local_addresses is GetLocalAddresses (src/common/netif.cpp, at bitcoin/bitcoin@9be056a8a7, the v31.1 tag): every address of an interface that is up and not a loopback one, IPv4 and IPv6 alone, as its FromSockAddr reads them. Where Core asks getifaddrs this does, and on Windows, where Core asks GetAdaptersAddresses, so does this. Both are reached through ctypes, the standard library having no binding of either.

btclib_node.p2p.netif.local_addresses() → list[IPv4Address | IPv6Address][source]

Return this machine’s interface addresses, as Core’s GetLocalAddresses.

Nothing where getifaddrs or GetAdaptersAddresses fails, as Core returns its empty vector, and nothing where the C library or iphlpapi cannot be loaded or has no such function: Core’s own call cannot fail that way, and discovery never stops its start-up.

btclib_node.p2p.permissions module

The permissions -whitelist and -whitebind grant a peer.

NetPermissionFlags is Core’s enum, Whitelist is -whitelist parsed as NetWhitelistPermissions::TryParse does (src/net_permissions.cpp) and Whitelist.flags is CConnman::AddWhitelistPermissionFlags (src/net.cpp), all read at bitcoin/bitcoin@9be056a8a7, the v31.1 tag. A value is read by lookup_subnet, the ban list’s LookupSubNet.

parse_whitebind_permissions reads the permissions of a -whitebind value as NetWhitebindPermissions::TryParse does. A peer accepted on its listener holds them in Whitelist.flags’ granted.

Each permission does here what it does in Core, wherever this node has the behaviour it changes: NO_BAN (ban, discouragement, eviction, the headers work check, the preferred download peer, the stalled headers sync, the transaction trickle, the pruned block threshold), DOWNLOAD (getheaders below the minimum chain work), ADDR (address rate limit and the getaddr cache), RELAY (the limit on announcements) and FORCE_RELAY (relay of a known transaction, no feefilter). BLOOM_FILTER and MEMPOOL are accepted and listed by getpeerinfo and change nothing: this node answers no BIP37 request and no BIP35 mempool, whoever asks. DOWNLOAD’s -maxuploadtarget and RELAY’s -blocksonly are not options of this node.

class btclib_node.p2p.permissions.NetPermissionFlags(*values)[source]

Bases: IntFlag

Core’s NetPermissionFlags, bit for bit.

A composite holds the permission it implies: NO_BAN holds DOWNLOAD and FORCE_RELAY holds RELAY. IMPLICIT marks a -whitelist or -whitebind value that named no permission, so that Whitelist.flags grants the default set.

class btclib_node.p2p.permissions.Whitelist(incoming: tuple[WhitelistEntry, ...] = (), outgoing: tuple[WhitelistEntry, ...] = (), relay: bool = True, force_relay: bool = False)[source]

Bases: object

The -whitelist values, split by the direction they apply to.

relay and force_relay are -whitelistrelay and -whitelistforcerelay, which add to the default set a value naming no permission is granted.

flags(address: NetworkAddressV2 | None, *, inbound: bool, manual: bool = False, granted: NetPermissionFlags | None = None) → NetPermissionFlags[source]

Return what a peer at address is granted.

Core’s AddWhitelistPermissionFlags, whose address is empty for a peer on an =onion listener: None matches no entry. granted is what the listener grants (-whitebind), where there is one, which the matching entries add to.

An inbound peer is matched against the incoming values and a manual outbound one against the outgoing values; no other connection is granted anything.

classmethod parse(values: Iterable[__annotationlib_name_1__], *, relay: bool = True, force_relay: bool = False) → Whitelist[source]

Read every -whitelist value, in order.

Raises ValueError with Core’s message for the first one refused.

class btclib_node.p2p.permissions.WhitelistEntry(subnet: Subnet, flags: NetPermissionFlags)[source]

Bases: object

Core’s NetWhitelistPermissions: a subnet and what it is granted.

btclib_node.p2p.permissions.parse_whitebind_permissions(text: str) → tuple[NetPermissionFlags, str][source]

Split a -whitebind value into its permissions and its address.

NetWhitebindPermissions::TryParse up to the address, which the caller resolves. A value naming no permission holds IMPLICIT. Raises ValueError with Core’s message.

btclib_node.p2p.permissions.permission_names(flags: NetPermissionFlags) → list[str][source]

Return getpeerinfo’s names, Core’s NetPermissions::ToStrings.

btclib_node.p2p.protocol_version module

The protocol versions a peer is kept at, and each feature begins at.

Core’s src/node/protocol_version.h (at bitcoin/bitcoin@9be056a8a7, the v31.1 tag), under Core’s names; PROTOCOL_VERSION itself is btclib.p2p.limits’. common_version is Core’s CNode::GetCommonVersion, which every feature gate reads.

btclib_node.p2p.protocol_version.common_version(conn: Connection) → int[source]

Return the lower of the peer’s protocol version and this node’s.

INIT_PROTO_VERSION until the peer’s version has been read, as Core starts m_greatest_common_version.

btclib_node.p2p.raw_block module

A stored block served as the octets it is stored in.

BlockDB keeps a block as its witness serialization. A getdata for MSG_WITNESS_BLOCK is answered with those octets, and one for MSG_BLOCK with the same octets less the witnesses, so neither needs the block parsed into objects and written out again.

assert_well_formed and strip_witnesses walk the octets once and refuse what Block.parse refuses with check_validity=False, with the same BTClibValueError: a block that does not parse is not served. Core serves a stored witness block unread (ReadRawBlock in ProcessGetBlockData, src/net_processing.cpp at bitcoin/bitcoin@9be056a8a7); this node checks it first.

class btclib_node.p2p.raw_block.RawBlock(data: bytes)[source]

Bases: Payload

A block message carrying octets already serialized.

serialize(*, check_validity: bool = True) → bytes[source]

Return the octets this was built with.

btclib_node.p2p.raw_block.assert_well_formed(raw: bytes) → None[source]

Raise BTClibValueError unless Block.parse reads raw.

btclib_node.p2p.raw_block.strip_witnesses(raw: bytes) → bytes[source]

Return raw as Block.serialize(include_witness=False) writes it.

btclib_node.p2p.selfannounce module

The address this node tells a peer it is reachable at, as Core’s.

reachability is CNetAddr::GetReachabilityFrom (src/netaddress.cpp) and address_for_peer is GetLocal and GetLocalAddrForPeer (src/net.cpp), both read at bitcoin/bitcoin@9be056a8a7, the v31.1 tag. Only IPv4 and IPv6 are held here, so no local address is on a privacy network, and GetLocal skips every one of them for a peer that is.

class btclib_node.p2p.selfannounce.LocalService(address: IPv4Address | IPv6Address, port: int, score: int)[source]

Bases: object

Core’s LocalServiceInfo: the port and score of one local address.

The score moves only as AddLocal moves it; Core’s SeenLocal also raises it for an address a peer reports: btclib-org/btclib-node#1646.

btclib_node.p2p.selfannounce.address_for_peer(local: dict[bytes, LocalService], peer: IPv4Address | IPv6Address, *, routable: bool, listen_port: int, seen_as: tuple[IPv4Address | IPv6Address, int | None] | None, inbound_onion: bool = False) → tuple[IPv4Address | IPv6Address, int] | None[source]

Return the address and port to tell peer, or None.

The best of local by reachability from peer, then by score; none of it where inbound_onion says peer reached an =onion listener, GetLocal keeping an address of another network from a Tor peer. Where seen_as is given – the address peer says it reaches this node at, the caller having found it routable and -discover on – it replaces that, always where nothing is held and otherwise at random, one time in two, or one in eight where the score is above LOCAL_MANUAL. Its port is that of seen_as where it has one, an outbound peer being unable to see the listening port, and otherwise the held address’s, or listen_port where none is held.

btclib_node.p2p.selfannounce.reachability(ours: IPv4Address | IPv6Address, theirs: IPv4Address | IPv6Address, *, routable: bool) → int[source]

Return how well theirs reaches ours, a routable address.

routable is whether theirs is: an address that is not, a loopback peer for one, is ranked as no network.

btclib_node.p2p.transport module

How a connection’s octets become messages and back, as Core’s Transport.

Transport is Core’s class of that name (src/net.h) and V1Transport is its V1Transport (src/net.cpp), both read at bitcoin/bitcoin@9be056a8a7, the v31.1 tag, with the names in snake case. A transport does no I/O: Connection feeds it what the socket read and writes what it hands back. V1Transport holds no lock; p2p.v2transport’s docstring says why V2Transport holds two. A BIP324 transport implements the same methods.

Threads. The receiving half is touched on the connection’s own loop alone, by Connection.parse_messages. The sending half is touched on that loop too, by Connection._drain_outbox under _write_lock, which is what makes the order of the octets on the wire the order the transport produced them in. A V2Transport’s receiving half also adds handshake octets to the sending half, on that loop, between two calls; they go out first, since the transport takes no message while it holds octets. get_info and should_reconnect_v1 read what the other methods write and may be called from another thread, V1Transport’s answers being constants.

Where this differs from Core’s shape, each for a Python reason:

  • received_bytes takes a memoryview and returns what it left, where Core chops the consumed octets off a span in place. It raises where Core returns false, so the refusal carries its reason.

  • get_received_message raises RejectedMessageError where Core sets reject_message, and takes no time: the caller reads the clock. Either way the transport can go on.

  • get_bytes_to_send returns a memoryview of the octets the transport holds, as Core returns a span, so a block is not copied to be sent.

  • There is no GetSendMemoryUsage: Connection.send_memusage weighs a message from when it is queued until it is written whole, the one the transport holds included.

class btclib_node.p2p.transport.BytesToSend(to_send: memoryview, more: bool, command: str)[source]

Bases: NamedTuple

What Transport.get_bytes_to_send returns.

more is whether more octets follow these. command is the message they are sent on behalf of, “” for octets that belong to none.

command: str

Alias for field number 2

more: bool

Alias for field number 1

to_send: memoryview

Alias for field number 0

class btclib_node.p2p.transport.NetMessage(command: str, payload: bytes, size: int)[source]

Bases: object

Core’s CNetMessage: a message taken off the wire.

size is Core’s m_raw_message_size, every octet the message took on the wire.

class btclib_node.p2p.transport.SerializedMessage(command: str, payload: bytes)[source]

Bases: object

Core’s CSerializedNetMsg: a message to send, framing not yet added.

class btclib_node.p2p.transport.Transport[source]

Bases: ABC

Core’s Transport: bytes in, messages out, and the other way round.

abstractmethod get_bytes_to_send(*, have_next_message: bool) → BytesToSend[source]

Return the octets to send, if more follow, and for which message.

Changes nothing, so it may be called again. have_next_message is the caller saying another message is ready to be set, and changes more alone.

abstractmethod get_info() → TransportInfo[source]

Return the protocol this transport speaks.

abstractmethod get_received_message() → NetMessage[source]

Return the whole message received_message_complete announced.

Raises IncompleteMessageError where there is none, and RejectedMessageError, whose size is the octets it took, for one that is invalid and is dropped without dropping its sender.

abstractmethod mark_bytes_sent(bytes_sent: int) → None[source]

Report how many octets get_bytes_to_send offered have been sent.

abstractmethod received_bytes(msg_bytes: memoryview) → memoryview[source]

Take wire octets and return those it did not take.

The caller loops until none are left, fetching each message as received_message_complete says it is whole, and does not call this while a whole one waits to be fetched.

Raises where some octets are invalid, after which the transport is no longer to be used: the connection is dropped.

abstractmethod received_message_complete() → bool[source]

Return whether get_received_message can be called.

abstractmethod set_message_to_send(msg: SerializedMessage) → bool[source]

Set the next message to send.

Returns False, and takes nothing, where the previous one is not yet sent or the transport cannot send yet. Raises BTClibValueError for a message it cannot frame.

abstractmethod should_reconnect_v1() → bool[source]

Return whether, once dropped, a reconnection with v1 is warranted.

class btclib_node.p2p.transport.TransportInfo(transport_type: TransportProtocolType, session_id: bytes | None = None)[source]

Bases: object

Core’s Transport::Info: the protocol, and the BIP324 session id.

class btclib_node.p2p.transport.TransportProtocolType(*values)[source]

Bases: StrEnum

Core’s TransportProtocolType, valued as getpeerinfo spells it.

class btclib_node.p2p.transport.V1Transport(magic: bytes)[source]

Bases: Transport

Core’s V1Transport: the 24-octet header, then the payload.

get_bytes_to_send(*, have_next_message: bool) → BytesToSend[source]

Return the octets to send, if more follow, and for which message.

Changes nothing, so it may be called again. have_next_message is the caller saying another message is ready to be set, and changes more alone.

get_info() → TransportInfo[source]

Return the protocol this transport speaks.

get_received_message() → NetMessage[source]

Return the message, and start on the next.

A checksum that does not match the payload, or a command IsMessageTypeValid refuses, is Core’s reject_message.

mark_bytes_sent(bytes_sent: int) → None[source]

Report how many octets get_bytes_to_send offered have been sent.

received_bytes(msg_bytes: memoryview) → memoryview[source]

Take the octets the current header or payload still wants.

Core’s readHeader and readData, which also stop at the end of the header, so the caller’s loop sees the header refused before any payload is taken.

received_message_complete() → bool[source]

Return whether get_received_message can be called.

set_message_to_send(msg: SerializedMessage) → bool[source]

Set the next message to send.

Returns False, and takes nothing, where the previous one is not yet sent or the transport cannot send yet. Raises BTClibValueError for a message it cannot frame.

should_reconnect_v1() → bool[source]

Return whether, once dropped, a reconnection with v1 is warranted.

btclib_node.p2p.transport.frame_message_bytes(data: bytes) → Message[source]

Return the one-argument, octet-only shape fuzz/fuzz_framing.py drives.

The first message data holds, framed by a V1Transport built with no socket: the shape of Core’s p2p_transport_serialization.cpp fuzz target (at bitcoin/bitcoin@ca7162cde5), which feeds raw octets to a V1Transport constructed with no wider node context.

RegTest’s own magic, this tree’s cheapest chain to construct, rather than a magic threaded through the entry point: the magic check is worth fuzzing on its own footing rather than fixed away.

Trailing octets are left unread, as Connection.parse_messages leaves them for the next message, so a seed exercised by tests/fuzz_corpus_test.py’s round-trip check (frame_message_bytes(seed).serialize() == seed) must carry none. Raises IncompleteMessageError for octets that end inside a message.

btclib_node.p2p.tx_checks module

The script checks of relayed transactions, run off Node’s thread.

p2p.callbacks runs every check but the scripts of a relayed transaction, of an orphan taken up again and of a parent with its child, on Node’s thread, and queues the candidate here. p2p.main.resume_tx_checks hands the scripts to Node.worker_pool, one candidate at a time, and applies the verdict back on Node’s thread, so the loop goes on serving other peers while it runs; the sending peer’s later messages wait for the verdict and for any orphan it is to reconsider.

At most one candidate per peer is queued or checked at a time. A peer’s later messages of every command wait here, in order, still weighed against its queued_recv_bytes, while p2p.main._hold_message says the peer has work before them. Candidates are checked in the order they were queued, so a peer that sends again goes to the back. Core’s message handler reads one message of each peer per pass, its peers shuffled each time (CConnman::ThreadMessageHandler, src/net.cpp, at bitcoin/bitcoin@9be056a8a7, the v31.1 tag); a queue holding each peer at most once is as fair, without the shuffle.

Everything here is read and written on Node’s thread alone, so it needs no lock. A worker reads only the transaction and its prevouts: a TxOut is frozen, and nothing writes to the Tx, which the orphanage may also hold, until the verdict is in.

sendrawtransaction and testmempoolaccept check scripts on Node’s thread, as Core’s RPC holds cs_main across the check and its message handler waits on that lock (src/node/transaction.cpp, src/rpc/mempool.cpp and PeerManagerImpl::SendMessages, same tag).

class btclib_node.p2p.tx_checks.TxCheck(conn: Connection, tx: Tx, prev_outputs: list[TxOut], parent: tuple[Tx, list[TxOut]] | None = None, first_time: bool = True, failed: int = 0, in_package: bool = False)[source]

Bases: object

A relayed transaction whose scripts are queued or being checked.

parent is set for a package: tx is then the child, and parent the transaction it is checked and kept with, and its prevouts. first_time is False for a transaction taken from the orphanage or a package, which Core’s ProcessInvalidTx does not look for a package for. failed is set by TxChecks.finish to the position of the transaction of a package whose scripts failed, parents first. in_package marks a parent a package check found passing alone, which Core accepts as a package submission: the fee estimator does not track it.

hashes() → set[bytes][source]

Return the txids and wtxids of what is being checked.

class btclib_node.p2p.tx_checks.TxChecks[source]

Bases: object

The candidates awaiting a script check, and the messages behind them.

busy(conn_id: int) → bool[source]

Answer whether a check queued or a message held holds this peer.

property checking: bool

Whether a check is on the pool.

drop_overdue() → TxCheck | None[source]

Drop the check in flight once past its deadline with no verdict.

finish() → tuple[TxCheck, Exception | None] | None[source]

Take the check off the queue once its verdict is in.

Answers the check and what its scripts raised, if anything.

pending(tx_hash: bytes) → bool[source]

Answer whether a queued candidate has this txid or wtxid.

queue(check: TxCheck) → None[source]

Queue check behind the candidates already queued.

start(node: Node, check: TxCheck) → None[source]

Hand check’s scripts to node.worker_pool.

unqueue(conn_id: int) → TxCheck[source]

Take this peer’s candidate off the queue.

btclib_node.p2p.v2transport module

BIP324’s v2 transport as a state machine that reads and writes no socket.

V2Transport is Core’s V2Transport (src/net.h and src/net.cpp, at bitcoin/bitcoin@9be056a8a7, the v31.1 tag), with Core’s receive and send states, implementing p2p.transport.Transport, whose conventions it follows. The cipher, the key schedule and the short message ids are btclib.p2p.bip324’s.

A responder that receives the first 16 bytes of a v1 version message falls back to the v1_fallback it was given, which then takes over every call. Where it was given None, the responder raises V1PeerRefusedError at that same match.

V2Transport holds a lock for each half, taken receive before send, as Core’s does: the receiving half’s key processing writes the sending half’s buffer and state.

class btclib_node.p2p.v2transport.RecvState(*values)[source]

Bases: Enum

What the receive buffer holds, as Core’s V2Transport::RecvState.

class btclib_node.p2p.v2transport.SendState(*values)[source]

Bases: Enum

What may be sent, as Core’s V2Transport::SendState.

exception btclib_node.p2p.v2transport.V1PeerRefusedError[source]

Bases: V2TransportError

A v1 peer spoke to a responder that has no v1 fallback.

class btclib_node.p2p.v2transport.V2Transport(magic: bytes, v1_fallback: Transport | None, *, initiating: bool, prv_key: int | None = None, garbage: bytes | None = None)[source]

Bases: Transport

One connection’s v2 transport.

get_bytes_to_send(*, have_next_message: bool) → BytesToSend[source]

Return the octets to send, if more follow, and for which message.

more is true when have_next_message and the handshake allows the cipher: before that no message could be set.

get_info() → TransportInfo[source]

Return the protocol, and for v2 the session id.

Neither is reported before the version packet is received and verified, which says the peer very likely holds the same keys.

get_received_message() → NetMessage[source]

Return the message, and start on the next.

Raises IncompleteMessageError where there is none, and RejectedMessageError for contents that name no message type.

mark_bytes_sent(bytes_sent: int) → None[source]

Report how many octets get_bytes_to_send offered have been sent.

received_bytes(msg_bytes: memoryview) → memoryview[source]

Take wire octets and return those it did not take.

It leaves some once a message is complete, and when it has just fallen back to v1. Invalid octets raise V2TransportError.

received_message_complete() → bool[source]

Return whether get_received_message can be called.

set_message_to_send(msg: SerializedMessage) → bool[source]

Set the next message to send, or return False if none can be now.

One message at a time is held, once the handshake allows the cipher, and only when the buffer is empty: queueing is the caller’s.

should_reconnect_v1() → bool[source]

Return whether, the connection having ended, a v1 retry is warranted.

It is when we initiated, sent enough for a v1 peer to disconnect us, and received nothing.

exception btclib_node.p2p.v2transport.V2TransportError[source]

Bases: BTClibValueError

Bytes received are invalid: the transport cannot be used anymore.

Module contents

The peer-to-peer protocol this node speaks.

Connections, the peer manager, the address book and the message handlers Node’s loop calls. manager.P2pManager is the thread; connection.Connection is one socket on it; callbacks.callbacks and callbacks.handshake_callbacks are the dispatch tables main.handle_p2p and main.handle_p2p_handshake read; address.PeerDB is the address book gossip and DNS both write to.