btclib_node.chainstate package¶
Submodules¶
btclib_node.chainstate.block_index module¶
BlockIndex, every header this node has seen and which chain is active.
BlockStatus tracks a header from valid_header up through however far its block has been validated. invalidate is what a failed contextual check calls, through main.update_header_index, to drop a header and everything built on it. stage_status and finalize are set_status split into its two halves – the in-memory move and the disk write – so that main._finalize_fork can hold the second half back across more than one block; db.py’s own docstring is where that staging, shared with UtxoIndex, is argued.
set_downloaded and set_status both check pending before writing through, and for the same reason: either can be asked to change a hash pending already holds, unflushed, and a write-through there would only be undone the next time finalize writes that pending entry’s own stale snapshot back over it.
For set_status this is reached because invalidate’s own caller can name a hash that already connected once. update_chain sets failed_hash to a block across utxo_index.add_block, _validate_block, block_db.add_rev_block and filter_index.add_connected_block alike, so a fault in either of the last two – an I/O failure, nothing to do with the block’s own content – invalidates a block exactly as an actual validation failure would. Reached during a chain-tip flip-flop – a hash stage_status staged, disconnected by a later trial that re-stages it there, then offered again – that is a hash pending still holds, unflushed. set_status therefore checks pending itself: a hash already staged there is updated in pending, exactly as stage_status would leave it, rather than written straight through, so the next finalize writes the invalidation instead of clobbering it with the stale entry write-through would otherwise race against. btclib-org/btclib-node#586.
For set_downloaded no caller reaches this today: main.prune_up_to_height flushes the chainstate first, which empties pending, and p2p.callbacks.block sets the flag only on a hash not yet downloaded. The check stays so that a caller that does not flush first cannot have its write undone by the next finalize.
- class btclib_node.chainstate.block_index.BlockIndex(parent_db: KeyValueStore, chain: Chain, logger: Logger)[source]¶
Bases:
objectEvery header this node has seen, and which chain among them is active.
header_dict maps a hash to its BlockInfo; chainwork holds each one’s cumulative work, kept apart from the record itself since it is derived rather than stored (issue #201). active_chain is the current best chain by hash; block_candidates is every other header that might still beat it once downloaded; header_index is the best known header chain, tracked separately since a header being known does not make its own block downloaded, let alone valid. header_index_pos is header_index’s own hash -> position, kept beside it the same way chainwork is kept beside header_dict (issue #439), and skip is each header’s skip pointer, Core’s pskip, which get_ancestor and last_common_ancestor follow.
- add_headers(headers: Iterable[__annotationlib_name_1__], *, punish_cached_invalid: bool = False, min_pow_checked: bool = True) bytes | None[source]¶
Validate headers as one batch, then index each in turn.
Returns the highest header this batch carried that is indexed now (new or already known), or None if the batch connects to nothing this index knows at all. punish_cached_invalid is whether a header already marked invalid is a MisbehavingError, as Core has it for an outbound peer, rather than a BTClibValueError. min_pow_checked is whether the caller has checked the chain’s work against p2p.headers_sync’s anti-DoS threshold, a LowWorkHeaderError being what a new header gets where it has not. True by default: p2p.callbacks.headers checks before calling, and Core’s RPCs pass true, which leaves p2p.callbacks.block the one caller that can pass false.
- add_to_active_chain(block_hash: bytes) None[source]¶
Append block_hash to active_chain, with no check it connects.
- calculate_chainwork() None[source]¶
Compute every header’s cumulative work into chainwork.
Backfills children along the way, one entry per header visited, and best_invalid the same way Core’s own LoadBlockIndex scan does (src/validation.cpp:4964-4965, at bitcoin/bitcoin@9be056a8a7, the v31.1 tag): a block already marked invalid when this index was last written beats whatever best_invalid already holds if its chainwork is greater.
- finalize(wb: KeyValueStore | None = None) None[source]¶
Write every status stage_status staged, into wb if there is one.
Mirrors FilterIndex.finalize: a write_batch of its own when no wb is given, one write inside a caller’s own batch otherwise.
- generate_active_chain() None[source]¶
Rebuild active_chain from every header marked in_active_chain.
- generate_block_candidates() None[source]¶
Rebuild block_candidates over every valid_header/valid entry.
init_from_db calls this once at start-up, over every header the store holds; reconsider above and main.invalidate_chain call it again once disconnecting or reconnecting has moved the active chain’s own tip work, since a candidate get_first_candidate already evicted as stale against the old tip is gone from the deque for good once popped – reachable again only by rebuilding from header_dict whole, the way this does. Sorts header_dict itself rather than reading sorted_header_dict, the start-up-only list init_from_db frees right after this call returns there, so that a later caller finds the same list this one would have. Always starts from an empty deque rather than appending onto whatever is there, which only matters past start-up: block_candidates is empty already the one time init_from_db calls this.
precious calls this too, once it has renumbered a block that may now outrank the tip.
valid is offered alongside valid_header so that a branch a reorg has since displaced (_finalize_fork’s own to_remove loop sets it) becomes a candidate again once whatever displaced it is itself invalidated, and so that a block leave_active_chain took off the chain connects again. Core’s own InvalidateBlock (src/validation.cpp:3663-3684, at bitcoin/bitcoin@9be056a8a7, the v31.1 tag) re-inserts such an out-of-chain header into setBlockIndexCandidates only where candidate->IsValid(BLOCK_VALID_TRANSACTIONS) && candidate->HaveNumChainTxs() both hold (:3674-3677) – so a valid block this index still holds the data for is offered, matched here by requiring downloaded as well as the status, and one a completed prune has since cleared downloaded on (main.prune_up_to_height) is not, matching Core rather than the un-downloaded valid_header candidates this deque already carries for a different reason: a valid_header was never BLOCK_VALID_TRANSACTIONS in the first place, so it is not this same reinsertion Core’s source is arguing, and changing that pre-existing, separately-argued divergence is out of scope here. btclib-org/btclib-node#1561
A block is offered where it outranks the active tip (_outranks), so one of the tip’s own work is offered where its sequence_id is the lower.
- get_ancestor(block_hash: bytes, height: int) bytes | None[source]¶
Return block_hash’s ancestor at height: Core’s GetAncestor.
Core’s is in src/chain.cpp, at bitcoin/bitcoin@9be056a8a7, the v31.1 tag.
The block itself at its own height, and None for a height above it or below zero, where Core answers nullptr. Follows skip pointers, so the cost grows with the logarithm of the distance rather than with the distance.
- get_block_locator_hashes(start: bytes | None = None) list[bytes][source]¶
Return a block locator over header_index, its own best known chain.
locator_entries from start, a header of header_index, or from its tip where none is given.
- get_first_candidate() BlockInfo | None[source]¶
Return the first downloaded candidate outranking the active tip.
Pops every stale entry (work below the active chain’s own) off the front of block_candidates, then scans up to the 100 left: among those that outrank the tip (_outranks), the first whose whole branch is downloaded is returned, or the very first of them if none is, or None if none outranks the tip. A later downloaded entry of the same work replaces it where it outranks it, which is Core’s tie-break; one of more work does not, where Core’s FindMostWorkChain takes the most-work candidate.
- get_fork_details(header_hash: bytes, chain: list[bytes] | None = None) tuple[list[bytes], list[bytes]][source]¶
Split chain at its common ancestor with header_hash.
chain defaults to active_chain. Returns the branch from that ancestor up to header_hash (ancestor excluded, oldest first) and the tail of chain that branch would replace.
- init_from_db() None[source]¶
Load every stored header into header_dict, then derive the rest.
Stops at the first key that is not a blkinfo- record: the shared store’s own key order (db.py’s docstring) sorts this index’s own keys ahead of the filter and UTXO indexes sharing the same store.
- invalidate(block_hash: bytes) None[source]¶
Mark block_hash invalid, and everything indexed on top of it.
Walks children rather than header_dict, so the cost is the size of the bad lineage rather than of the whole index. Every invalidated hash is dropped from block_candidates; header_index is rebuilt from active_chain only if it held one of them.
Compares block_hash alone against best_invalid, as Core’s own InvalidChainFound does (src/validation.cpp:1971-1974, at bitcoin/bitcoin@9be056a8a7, the v31.1 tag): its SetBlockFailureFlags marks the descendants without touching m_best_invalid. calculate_chainwork is the load-time path, which weighs every invalid block, descendants included.
- last_common_ancestor(first: bytes, second: bytes) bytes[source]¶
Return the fork point of two blocks: Core’s LastCommonAncestor.
Core’s is in src/chain.cpp, at bitcoin/bitcoin@9be056a8a7, the v31.1 tag.
Both are brought to the lower one’s height, then walked back through their skip pointers while those differ, and one parent at a time where they agree.
- static leave_active_chain(db: KeyValueStore, genesis_hash: bytes) None[source]¶
Mark every block of the active chain but genesis valid.
Chainstate’s module docstring says when. valid is a block whose content passed once and that is off the active chain, so generate_block_candidates offers it again while its data is held, and main.update_chain connects it again.
- locator_entries(block_hash: bytes) list[bytes][source]¶
Return a block locator from block_hash: locator_entries’s.
- precious(block_hash: bytes) bool[source]¶
Treat block_hash as received before its rivals: PreciousBlock.
Chainstate::PreciousBlock (src/validation.cpp, at bitcoin/bitcoin@9be056a8a7, the v31.1 tag). Nothing for a block with less work than the tip, and False. Otherwise the block takes the next negative number, counting down from -1 again wherever the tip gained work since the last call, block_candidates is rebuilt so that it is offered where it now outranks the tip, and True.
A block whose data, or an ancestor’s, is missing keeps no number: Core gives it one that its data’s arrival overwrites before anything compares it. Core stops counting down at the int32_t minimum, against overflow, which a Python int does not have.
- reconsider(block_hash: bytes) None[source]¶
Undo invalidate’s mark on block_hash’s own lineage, then rebuild.
Core’s own Chainstate::ResetBlockFailureFlags (src/validation .cpp, at bitcoin/bitcoin@9be056a8a7, the v31.1 tag): every header this index holds that is block_hash itself, one of its ancestors, or one of its descendants, and that invalidate above marked, has that mark cleared – not only block_hash itself, since an ancestor invalidate reached through block_hash and a descendant built on it are both still wrongly invalid once block_hash no longer is. block_candidates and header_index are rebuilt whole afterward rather than patched: a header this clears may now be the best known header chain, or a legitimate candidate get_first_candidate already evicted as permanently stale against a tip the clearing has not yet moved.
best_invalid is reset to None where it names a header this clears, as Core’s own loop resets m_best_invalid to nullptr (:3772-3775), without looking for the next-best invalid header.
- remove_from_active_chain(block_hash: bytes) None[source]¶
Pop active_chain’s tip if it is block_hash, else raise.
ChainstateInconsistencyError, since a caller removing anything else is reorganizing the chain out of order.
- set_downloaded(block_hash: bytes, *, downloaded: bool = True) None[source]¶
Set block_hash’s downloaded flag, replacing its BlockInfo.
Checks pending first, the same shape set_status above already does; the module docstring’s last paragraph says why, and that no caller reaches it today.
A block whose data arrives here is numbered by _link.
- set_status(block_hash: bytes, status: BlockStatus, wb: KeyValueStore | None = None) None[source]¶
Set block_hash’s own status, replacing its stored BlockInfo.
Writes straight through to the store (or to a caller’s own wb) unless pending already holds this hash – in which case the change is folded into that pending entry instead, exactly as stage_status below would leave it, and wb goes unused: the write is deferred to finalize’s own flush rather than happening now at all, since a write-through here would only be undone the next time finalize writes that pending entry’s stale value over it. The module docstring argues why this happens – invalidate’s own caller, update_chain.
- stage_status(block_hash: bytes, status: BlockStatus) None[source]¶
Set block_hash’s status now, its write staged for finalize.
set_status above writes through to the store (or to a caller’s own wb) the moment it is called, unless pending already holds the hash; this stages the write into pending unconditionally, for finalize to write out whenever it next runs – _finalize_fork’s own to_add/to_remove loop is the one caller, once per block a fork connects or disconnects, so that a block’s own status reaches disk only together with the UTXO cache’s flush rather than one write_batch per block. A later call for the same hash before that flush – a reorg undoing a connection this process staged and never wrote – simply replaces the pending entry, which is correct: only the state finalize is about to write ever needs to reach disk at all.
- stored_branch_outranks_tip() bool[source]¶
Answer whether main.update_chain has stored blocks to connect.
That is, whether get_first_candidate picks a candidate whose whole branch is stored: the test main._ready_fork makes before it connects, and whose failure ends NodeStatus.Reindexing there. Its 100-candidate window is therefore the same at start as on every pass after it.
- weigh_invalid(block_hash: bytes) None[source]¶
Make block_hash the best_invalid if it carries more work.
Core’s own comparison wherever it writes m_best_invalid (src/validation.cpp:1971-1973, at bitcoin/bitcoin@9be056a8a7, the v31.1 tag): strictly greater, so a tie keeps the first.
- class btclib_node.chainstate.block_index.BlockInfo(header: BlockHeader, index: int, status: BlockStatus = BlockStatus.valid_header, downloaded: bool = False)[source]¶
Bases:
objectOne header this index has indexed: its height, status and download state.
header is the parsed header; index is its height; status and downloaded are this index’s own bookkeeping about it. chainwork is deliberately not a field here – the comment above argues why.
- classmethod deserialize(data: bytes, *, check_validity: bool = True) BlockInfo[source]¶
Parse a BlockInfo from the bytes serialize produced.
- serialize() bytes[source]¶
Serialize this record to the bytes stored under blkinfo-<hash>.
The header checked here now. It used to be serialized unchecked: a header of a version zero or below is Core’s to take below BIP34’s height, and btclib’s BlockHeader.assert_valid refused it on its own – fixed at btclib 2026.9.29 (btclib-org/btclib@bbb1ad71, closing btclib-org/btclib#2309; btclib-org/btclib-node#1511). A header reaches a BlockInfo only past add_headers’s own height-gated bad-version check (_assert_valid_in_context), so nothing assert_valid still checks can refuse one that got here honestly.
- class btclib_node.chainstate.block_index.BlockStatus(*values)[source]¶
Bases:
IntEnumWhere a block stands relative to the active chain.
valid_header is a header on its own, content not yet checked; in_active_chain is on the active chain now; valid is a block whose content passed validation but that is off the active chain, set by _finalize_fork’s own to_remove loop after a reorg and by -reindex-chainstate’s wipe (leave_active_chain). invalid is set on a block itself or on any block built on one already marked invalid – not terminal, since reconsider below is exactly what clears it again.
- btclib_node.chainstate.block_index.block_time(header: BlockHeader) int[source]¶
Return the second the header’s four timestamp bytes hold.
Core’s CBlockHeader::GetBlockTime. BlockHeader.serialize writes int(time.timestamp()), so that is the value the rules here compare: a header is weighed as it goes on the wire and not as it was built. main.py and rpc.callbacks read it from here rather than from a module of their own, chainstate being the lowest layer both already depend on.
- btclib_node.chainstate.block_index.calculate_work(header: BlockHeader) int[source]¶
Return the work header’s own target represents.
- btclib_node.chainstate.block_index.check_headers_pow(headers: Sequence[__annotationlib_name_1__], pow_limit_bits: bytes) None[source]¶
Core’s CheckHeadersPoW: each header’s proof of work, then continuity.
Both are Misbehaving in Core (src/net_processing.cpp, at bitcoin/bitcoin@9be056a8a7, the v31.1 tag), so both refusals are a MisbehavingError. BlockIndex.add_headers asks it too, of every batch it is given.
- btclib_node.chainstate.block_index.locator_entries(block_index: BlockIndex, block_hash: bytes) list[bytes][source]¶
Return a block locator from block_hash: Core’s LocatorEntries.
Core’s is in src/chain.cpp, at bitcoin/bitcoin@9be056a8a7, the v31.1 tag: block_hash and its ancestors, one height apart for the first ten and twice as far apart for each one after, down to genesis. This is the tree’s one copy of it (btclib-org/btclib-node#1530): BlockIndex.locator_entries, BlockIndex.get_block_locator_hashes and p2p.chain_sync’s own are its callers.
Core reaches each ancestor with GetAncestor. Where block_hash is on header_index, which holds the best header chain by height, the ancestor at a height is that entry of it, read in constant time; a block anywhere else is walked back through get_ancestor’s skip pointers, the same blocks at a cost logarithmic in the distance.
btclib_node.chainstate.filter_index module¶
The BIP158 filter of every connected block, and its filter header.
What a node holds that btclib.block.block_filter does not: the arithmetic over one block is btclib’s, and this is the index over the chain – one filter per block, and the header chaining it onto its parent’s.
A filter is keyed by block hash and so is its header, both being functions of the block and of its ancestry: a header is filter_header(this filter’s hash, the parent’s header) and the parent is fixed by previous_block_hash, not by which chain is active. So a block stepped over in a reorg keeps the filter and the header it had, and coming back costs nothing – which is why there is no counterpart here to UtxoIndex.apply_rev_block.
Writes are held until finalize, the way UtxoIndex holds them: a block connects in the same write batch as the chainstate it advances, and until that batch is written the parent of the block being indexed is not in the database yet.
BIP157 asks for exactly this: “Nodes SHOULD NOT generate filters dynamically on request, as malicious peers may be able to perform DoS attacks by requesting small filters derived from large blocks.”
- class btclib_node.chainstate.filter_index.FilterIndex(parent_db: KeyValueStore, chain: Chain, logger: Logger)[source]¶
Bases:
objectThe BIP157/BIP158 filter and header for every connected block.
The module docstring above is where the keying, the write-batch discipline and the lack of a reorg-time undo are all argued.
pending now survives more than one trial of main.update_chain, the same way UtxoIndex’s own staging does, so rollback cannot stay a blanket wipe either: add_block only ever adds a hash that was not already a key (its own guard, checking get_filter first), so _trial_log needs to remember only which hashes a trial added, not what they replace – UtxoIndex’s own _undo_log carries a prior value for exactly the mutations here that never happen.
- add_block(block: Block, prevout_scripts: list[bytes]) None[source]¶
Index the filter of a block whose parent is already indexed.
- add_connected_block(block: Block, rev_block: RevBlock) None[source]¶
Index a block from the reverse patch its connection produced.
RevBlock.to_add is the output every input of the block spent, which is what a filter needs and a block does not carry – prevout_scripts_from_utxos wants a bare TxOut per outpoint, one step short of what RevBlock.to_add now carries alongside it (Coin’s own docstring, block_db/__init__.py), so it is unwrapped here rather than asking that function to know about a type outside its own package.
- catch_up(active_chain: list[bytes], block_db: BlockDB) int[source]¶
Index every block of the active chain that has no filter yet.
A datadir synced before this index existed has the blocks and the reverse patches and none of the filters, and a node that answers getcfilters for some of its chain is worse than one that does not answer at all – BIP157’s service bit is a promise about the whole of it. Walked from the bottom so that each block’s parent is indexed before it is.
Returns how many it built, which is zero on every start but the first after the index appears.
- finalize(wb: KeyValueStore | None = None) None[source]¶
Write what is held, into wb if there is one and atomically.
The header before the filter, and the pair in one write. Both skip guards ask get_filter, so a filter written without its header is the state nothing repairs: the block is skipped for ever and its child cannot be indexed at all, which leaves the datadir unopenable. The other half of the pair is harmless – a header with no filter is simply rebuilt.
- get_filter(block_hash: bytes) bytes | None[source]¶
Return the serialized filter of a block, or None.
- get_filter_hash(block_hash: bytes) bytes | None[source]¶
Return the filter hash of a block, in display order, or None.
- rollback(mark: int = 0) None[source]¶
Discard whatever pending gained since mark.
mark defaults to the very start, which is every direct test of this method: a fresh index, nothing pending before its own trial. UtxoIndex.rollback’s own docstring is where a caller with something to protect gets a real one from.
- trial_mark() int[source]¶
Return a point in the trial log a failed trial can be rolled back to.
UtxoIndex.trial_mark’s own docstring is where the reason this exists at all – pending surviving more than one trial – is argued; main.update_chain is the one caller.
- static wipe(db: KeyValueStore) None[source]¶
Remove every stored filter and filter header.
Chainstate’s module docstring says when, and why the filters go with the coins.
btclib_node.chainstate.muhash module¶
CoinStats: this store’s own on-disk shape for the UTXO commitment.
btclib.coinstats.CoinStats – this tree’s equivalent of Core’s incrementally-maintained CoinStatsIndex (src/index/coinstatsindex.cpp) – is the accumulator, the three running counters beside it, the bytes a coin is committed to as (tx_out_ser) and the gate on what is committed to at all (btclib.script.spendability.is_unspendable). [btclib#1623](https://github.com/btclib-org/btclib/issues/1623) is where moving them out of this module was decided, and btclib.coinstats’s own module docstring is where the construction, the counters and the gate are all argued, insert/remove being each other’s exact inverses on the same bytes included. UtxoIndex.rollback relies on that inverse property to undo a staged insert with a remove and vice versa, without recording what the accumulator’s own state was before either.
What stays here is what btclib’s own class carries no opinion on: a serialize/deserialize pair for this store’s on-disk layout – the same seam btclib.tx.coin.Coin already draws for the same reason, and why block_db.Coin is the wire-format subclass on that side of it, this CoinStats subclass being the other – and is_bip30_unspendable with the two-block pair it checks, which is [btclib#1695](https://github.com/btclib-org/btclib/issues/1695)’s own follow-up and not btclib’s.
## The serialization this store chose, and the one a coin is committed to as
btclib.coinstats’s own module docstring already argues why packing tx_out_ser’s (height << 1) | coinbase field differently from its own fixed 4-byte little-endian uint32 produces a different digest for the same coin. This store’s choice is Coin.serialize (block_db/__init__.py): a var_int ahead of the output, for storage density. CoinStats.insert/.remove, inherited from btclib, build tx_out_ser’s own encoding fresh from coin.height and coin.is_coinbase every time, never from Coin.serialize’s bytes, so the two encodings never have to agree.
## What is inserted, and what is not
is_unspendable gates CoinStats.insert/.remove independently of what UtxoIndex’s own store keeps, so the two accumulators agree on a block carrying an OP_RETURN output regardless of whether the store also refuses to hold one (btclib-org/btclib-node#667). UtxoIndex.add_block also skips storing such an output under a utxo- key at all, matching CCoinsViewCache::AddCoin’s own refusal directly rather than only agreeing with it through CoinStats’s own independent gate (utxo_index.py’s own _stage_creation is where that gate, and apply_rev_block’s own consequence – an output never stored is never restored – are argued); gettxoutsetinfo’s txouts and bogosize (rpc/callbacks.py) are always CoinStats’s own count, never a scan of the utxo- namespace.
## The two blocks history exempts
IsBIP30Unspendable (validation.cpp:6224-6228, at bitcoin/bitcoin@ca7162cde5) names two mainnet blocks, 91722 and 91812, each mined before BIP34 gave a coinbase’s own outpoint a height it could never collide with, whose coinbase transaction was later duplicated verbatim by a different block (91842, 91880 – IsBIP30Repeat, the pair btclib.consensus’s own Chain.consensus.bip30_exceptions names, which is what _check_bip30 on the second occurrence is waived against, not this one). CoinStatsIndex::CustomAppend skips a duplicated coinbase’s own outputs entirely – never inserted, so never later removed either – on whichever of the two connects first carrying that flag: the first occurrence is never hashed, so the second occurrence’s own ordinary insertion is the only one the accumulator ever carries, and the outpoint’s later spend correctly cancels exactly that one. Reproduced here as _BIP30_UNSPENDABLE_ORIGINALS, checked once per connecting block’s own coinbase in UtxoIndex.add_block – chains.py is other work’s own region for this branch, so the pair is local rather than a new Chain attribute. Both blocks are ninety-odd thousand mainnet blocks deep and neither height nor hash is reachable on any chain this tree’s own test suite runs (Chain.consensus.bip30_exceptions is empty on every chain but mainnet), so this exclusion is matched against Core’s source rather than against a live run of it.
- class btclib_node.chainstate.muhash.CoinStats(muhash: MuHash3072 = <factory>, transaction_output_count: int = 0, total_amount: int = 0, bogo_size: int = 0)[source]¶
Bases:
CoinStatsbtclib.coinstats.CoinStats, plus this store’s own on-disk shape.
The accumulator and the three counters beside it, insert, remove and digest included, are all btclib.coinstats.CoinStats’s own; the module docstring above is where the seam between what lives there and what lives here is argued. serialize and deserialize below are this store’s own decision: the muhash state, then each of the three counters as 8 bytes, signed, big-endian. KeyValueStore’s own meta column family is where UtxoIndex.finalize writes this, in the same write_batch as the coins it commits to (db.py’s docstring argues why).
- btclib_node.chainstate.muhash.is_bip30_unspendable(height: int, block_hash: bytes) bool[source]¶
Report whether block_hash/height is one CoinStatsIndex skips.
The module docstring’s own “The two blocks history exempts” argues why, and btclib.consensus’s own Chain.consensus.bip30_exceptions is the different pair this is not.
- btclib_node.chainstate.muhash.is_unspendable(script_pub_key: bytes | str | bytearray | memoryview) bool[source]¶
Answer whether no transaction can ever spend such an output.
Sliced and not indexed, so that an empty script is a script with no leading OP_RETURN rather than an IndexError; and the length is compared with >, so a script of exactly MAX_SCRIPT_SIZE bytes is spendable, as it is to a node.
- btclib_node.chainstate.muhash.tx_out_ser(out_point_bytes: bytes | str | bytearray | memoryview, coin: Coin) bytes[source]¶
Return the bytes a coin is committed to as – Core’s TxOutSer.
TxOutSer (kernel/coinstats.cpp:46-52) writes the outpoint, then (height << 1) | coinbase as a fixed 4-byte little-endian uint32, then the output. The fixed width is the whole of what a caller cannot guess: an outpoint, that packed number and an output are also what a UTXO store keeps, and a store is free to write the packed number as a var_int for density – the same number, a different encoding, and a different digest.
out_point_bytes rather than an OutPoint, because a caller with a UTXO set already holds the outpoint in exactly this form – it is what keys the set – and OutPoint.serialize is what writes it.
btclib_node.chainstate.utxo_index module¶
UtxoIndex, the set of transaction outputs a spend may still reference.
add_block applies one block’s own spends and creations, returning the prevouts each transaction consumed – what main._validate_block validates against – and the block_db.RevBlock a reorg away from this block would need to undo it.
- class btclib_node.chainstate.utxo_index.UtxoIndex(parent_db: KeyValueStore, logger: Logger)[source]¶
Bases:
objectThe set of spendable outputs, staged in memory until finalize.
removed_utxos and updated_utxo_set hold what a batch of add_block/apply_rev_block calls has changed since the last finalize; the module docstring above is where add_block’s own return value is argued. The staging now survives more than one block – should_flush is what tells a caller it is time to stop piling more of it on and write, and db.py’s docstring is where what a crash before that costs is decided.
That survival is what makes rollback unable to stay a blanket wipe: a trial main.update_chain rolls back may run against staging several earlier, already-succeeded blocks left behind, unflushed, and wiping the two dicts to empty would discard those too – state a failed trial never touched and has no claim over. _undo_log is what tells the two apart: every mutation add_block and apply_rev_block make is recorded there as it happens, and rollback(mark) undoes only what was recorded since mark (trial_mark’s own reading, taken before the trial that might fail began), in reverse, leaving anything recorded before it standing.
coin_stats is the running commitment to the same set – chainstate/muhash.py’s own CoinStats, restored from parent_db’s meta column family here and staged the same way the two dicts above are: every _hash_insert/_hash_remove this class makes is logged into the same _undo_log, CoinStats.insert and .remove being each other’s exact undo regardless of order (muhash.py’s own docstring argues why), so rollback needs no prior accumulator state recorded, only that the opposite call replays.
- add_block(block: Block, height: int, *, check_bip30: bool = True) tuple[list[tuple[list[Coin], Tx]], RevBlock][source]¶
Apply block’s own spends and creations, staged rather than written.
height is this block’s own height, on whichever branch it is being tried – what every output it creates is stamped with, coin and coinbase alike, and never the height a later reorg disconnects or reconnects it at: apply_rev_block below restores a Coin exactly as this call staged it for removal, height and coinbase bit included, rather than recomputing either.
check_bip30 refuses a block that “overwrites” an output still unspent from anywhere earlier on the chain – Core’s own bad-txns-BIP30 (ConnectBlock, src/validation.cpp:2401-2431, at bitcoin/bitcoin@204256c73f), CVE-2012-1909’s shape: without it, a coinbase sharing an already-mined, still-unspent txid overwrites that output in place, and a reorg away from the second block deletes an output the first block’s own branch still carries. Checked over every transaction the block carries, coinbase included, matching Core’s own loop – and before either of the two loops below stages a single write, since Core’s own check runs against the view exactly as it stood before this block, coinbase and ordinary spends alike. False only for the two 2010 blocks Chain.consensus.bip30_exceptions names, which predate BIP34 (btclib-org/btclib-node#571) and so predate the property that makes a new violation of this kind unreachable once BIP34 binds: a block’s own coinbase commits to its own real height, which two different heights can never share, so the outpoint a block’s own coinbase creates cannot already belong to an earlier block’s coinbase – and UtxoIndex.add_block un-stages an entire block atomically on any raise, this one included, so a refused duplicate never reaches the two loops below that would otherwise stage a write over it.
Both loops below call _unmark_removed on an outpoint’s own bytes before every _put of it, the same order apply_rev_block’s own to_add loop uses to restore one: a key this call creates can coincide with one removed_utxos still carries only when the two share a txid, check_bip30 above being what refuses that for every case but the two historical exceptions – so the unmark is a no-op everywhere else, and is what keeps removed_utxos and updated_utxo_set disjoint rather than leaving a recreated outpoint staged in both at once (_bip30_violation’s own docstring is where that invariant is used, and btclib-org/btclib-node#586 is where staging it in both broke a later apply_rev_block on a coin that was legitimately unspent).
Returns each non-coinbase transaction paired with the prevouts its own inputs consumed – what main._validate_block validates against – and the RevBlock that undoes this call.
Every output this stages and every prevout it spends also moves coin_stats, the running commitment to the set – inserted for a creation, removed for a spend, Coin.parse’s own two raises above unaffected since they run before either ever touches it. The coinbase creation loop’s own _hash_insert is skipped for the two mainnet blocks is_bip30_unspendable names, matching CoinStatsIndex::CustomAppend – muhash.py’s own “The two blocks history exempts” argues why, and why this is a different pair from check_bip30’s own exception above.
Neither creation loop stages a provably unspendable output at all – _stage_creation’s own docstring is where that gate, and why it is what keeps added (and so RevBlock.to_remove) from ever naming an outpoint this call never wrote, is argued (btclib-org/btclib-node#667). A block’s own spend loop below needs no matching gate: no valid witness satisfies a provably unspendable output’s own script, so no block this method is ever asked to connect legitimately spends one, and one that tried would find it absent – “prevout not found”, the same answer Core’s own ConnectBlock reaches through Consensus::CheckTxInputs/HaveInputs for an output its own AddCoin never added either.
- apply_rev_block(rev_block: RevBlock) None[source]¶
Undo add_block for the block rev_block was returned for.
Removes every outpoint it created and restores every prevout it spent, staged the same way add_block stages its own changes.
to_add runs before to_remove, not the reverse order add_block itself builds the two lists in, because an ordinary chained transaction – one spending an output another transaction earlier in the same block created – puts that output’s outpoint in both: to_remove from being created, to_add from being spent before this block ever finalized it to disk. Popping it in to_remove first would look it up while it is in neither updated_utxo_set nor the database – its net effect on the persisted set is nothing, both before this block and after it – and raise “output not found” on a block that did nothing wrong. Restoring it in to_add first stages it back into updated_utxo_set, where to_remove’s own _pop then finds and removes it, netting to the same nothing add_block itself computed. Every other entry is unaffected by the order: to_add’s outpoints predate this block and never collide with to_remove’s own, which this block alone created, a valid block spending a given outpoint at most once. Core’s DisconnectBlock (src/validation.cpp, at bitcoin/bitcoin@05e49b342f) reaches the same result walking one transaction at a time in reverse block order – spend its own outputs, then restore its own inputs – rather than in the two flat passes here (btclib-org/btclib-node#634).
A restored prevout is unmarked from removed_utxos before it is put back, not merely put back: add_block staged that spend with _mark_removed whenever the prevout was already durable (found in self.db rather than in updated_utxo_set), and leaving that flag set here would put the same outpoint bytes in both removed_utxos and updated_utxo_set at once – still “removed” as far as a later add_block call’s own guard is concerned, even though this call just made it spendable again. Staging now survives across trials (this outpoint can sit restored for up to _FLUSH_BOUND entries’ worth of blocks before finalize clears both dicts), so a stale flag here is no longer erased by the next trial boundary the way the old, per-trial finalize used to erase it – it stays wrong until a legitimate later spend of the same output hits add_block’s “prevout already spent in this batch” guard and gets rejected as a double spend, invalidating that block and, through update_header_index -> BlockIndex.invalidate, everything built on it. Independently of that, the same stale flag hides a genuine BIP30 duplicate too: _bip30_violation reads removed_utxos first and answers “no violation” on a hit, so a block recreating the restored outpoint – still unspent once this call has put it back – would connect instead of being refused bad-txns-BIP30 (btclib-org/btclib-node#586).
coin_stats moves the opposite way add_block moved it for the same coin: to_add restores a prevout that block spent, so it is inserted back into the commitment; to_remove drops an output that block created, so it is removed from it – both skipped for a coin that is both coin.is_coinbase and named by is_bip30_unspendable, matching add_block’s own gate, which withholds only the coinbase creation loop (skip_coinbase_hash, add_block’s own docstring) and never an ordinary transaction sharing the same block. is_coinbase alone is what is_bip30_unspendable cannot answer for: it checks only the coin’s own height and the block’s hash, so without this condition every non-coinbase output of the exempt block itself – stamped with the same height by add_block – would be wrongly withheld here on undo despite having been correctly hashed in on the way in, leaving coin_stats permanently off after a reorg through that block. Matches CoinStatsIndex::CustomAppend’s own is_coinbase && IsBIP30Unspendable(…) (src/index/coinstatsindex.cpp:129, at bitcoin/bitcoin@ca7162cde5), which gates on exactly the same conjunction rather than the hash/height pair alone. to_remove parses the stored Coin for this alone where the rest of this loop only ever needed to know the record existed. A parse failure here raises ChainstateInconsistencyError, unlike the identical fault reached through _stored_prevout (add_block’s own prevout resolution, get_coin), which answers None instead (btclib-org/btclib-node#650, _stored_prevout’s own docstring). The two share only the attribution – that the fault is this node’s own corrupted record, never a caller’s content (btclib-org/btclib-node#620, btclib-org/btclib-node#631, btclib-org/btclib-node#636) – not the outcome: undoing a block this node already connected has no legitimate “not found” reading the way an ordinary prevout lookup does, this loop’s own “output not found” raise immediately above already treating absence itself as this node’s own bookkeeping fault rather than a candidate’s.
- static by_txid(cursor: Iterator[__annotationlib_name_1__]) Iterator[__annotationlib_name_2__][source]¶
Yield each txid’s (n, out_point_bytes, value) rows, n ascending.
The store sorts utxo- keys by txid and then by the bytes of a little-endian output index, which is not n for an index of 256 or more, so each txid’s rows are sorted again here. Core’s ComputeUTXOStats collects one txid’s outputs into a std::map<uint32_t, Coin> for the same reason (src/kernel/coinstats.cpp, at bitcoin/bitcoin@9be056a8a7, the v31.1 tag), and the txid bytes order the same in both stores.
- cursor() Iterator[__annotationlib_name_1__][source]¶
Return a cursor over the stored utxo- records, as they are now.
Core’s CCoinsViewDB::Cursor: the view is fixed when this returns, so a block connected or a flush made while the cursor is walked, on any thread, does not reach it (KeyValueStore.scan_prefix). It sees what is written, not what is staged, so a caller flushes first, as Core’s gettxoutsetinfo does (ForceFlushStateToDisk).
- finalize(wb: KeyValueStore | None = None) None[source]¶
Write every staged change into wb, or into self.db if none.
Everything staged is durable after this, so nothing recorded before it can ever be rolled back to: _undo_log is cleared along with the two dicts it was tracking. coin_stats is written alongside them, into the same store’s meta column family (db.py’s own put_meta) – inside wb’s own batch when a caller passes one, which is what keeps the commitment and the coins it commits to landing together or not at all (db.py’s docstring argues why).
- get_coin(prevout_bytes: bytes) Coin | None[source]¶
Return the Coin a serialized outpoint still resolves to, or None.
Checks updated_utxo_set and removed_utxos first, the same order add_block and apply_rev_block already read staged state in, before falling to the store: a coin several blocks’ own worth of staging have created or already taken is real regardless of whether finalize has written it out yet, and a caller reading self.db directly – main.verify_mempool_acceptance used to – would miss exactly what staying staged across more than one block (btclib-org/btclib-node#586) makes ordinary.
- rollback(mark: int = 0) None[source]¶
Undo every mutation recorded since mark, in reverse.
mark defaults to the very start – a caller with nothing staged before its own trial began, which is every direct test of this method – and trial_mark’s own docstring is where a caller with something to protect gets a real one from.
- static serialized_hash(cursor: Iterator[__annotationlib_name_1__], interruption_point: Callable[[], None] = <function UtxoIndex.<lambda>>) bytes | None[source]¶
Return Core’s hash_serialized_3 over cursor’s coins, or None.
SHA256d over tx_out_ser of every coin, in by_txid’s order: ApplyHash over ComputeUTXOStats’ cursor (src/kernel/coinstats.cpp, at bitcoin/bitcoin@9be056a8a7, the v31.1 tag). The digest is HashWriter::GetHash’s own byte order, reversed for the hex uint256::GetHex prints.
interruption_point is called once per coin, and what it raises ends the walk, as Core’s node.rpc_interruption_point does. None is a stored record that does not parse, where Core’s cursor fails to read the value and ComputeUTXOStats returns no stats.
- should_flush() bool[source]¶
Whether the staged size has reached _FLUSH_BOUND.
main._finalize_fork is the one caller, and it is not asking this alone: Chainstate.flush writes BlockIndex and FilterIndex in the same batch this triggers, which is what keeps the three in step (db.py’s own docstring argues why).
- trial_mark() int[source]¶
Return a point in the undo log a failed trial can be rolled back to.
Taken before add_block/apply_rev_block are ever called for that trial; rollback undoes back to exactly this point, main.update_chain and main.try_connect_block being its callers.
- static wipe(db: KeyValueStore) None[source]¶
Remove every stored coin, and reset the commitment to them.
Chainstate’s module docstring says when: before an index is built on the store, so nothing is staged to lose.
Module contents¶
Chainstate: the block index, the UTXO set and the compact filter index.
All three share the one db.KeyValueStore Chainstate opens, told apart by each’s own key prefix – db.py’s own docstring is where that shared store’s key order is argued. block_index.BlockIndex tracks headers and which chain is active, checking a header’s own height- and time-dependent rules over btclib’s block.next_bits_required and median_time_past before it is indexed; utxo_index.UtxoIndex is the spendable outputs on it, and filter_index.FilterIndex the BIP157/BIP158 filters served over p2p.
flush is what writes all three indexes’ own staged changes in one batch, and close calls it before closing the store – db.py’s docstring is where the crash this is the other half of is argued.
wipe is -reindex-chainstate, Core’s InitCoinsDB with should_wipe (src/validation.cpp, src/node/chainstate.cpp, at bitcoin/bitcoin@9be056a8a7, the v31.1 tag). It removes the coins, their running commitment and the filters, and takes every block of the active chain but genesis off it, all in one batch. The headers stay, and so do the blocks block_db holds: main.update_chain then connects them again from genesis, as Core’s ImportBlocks does through ActivateBestChains. A stop part-way leaves what the last flush wrote, a shorter active chain and its coins, so the next start carries on from there with no marker, as Core’s own coins database does.
Wiping the filters departs from Core, which keeps its block filter index, a database of its own, and wipes it only on -reindex: SECURITY.md’s Where this node departs from Bitcoin Core records it. Here the filters share the store the rebuild is recovering, and the reconnect builds each one again from the block and the undo data it computes anyway. FilterIndex.add_block and catch_up skip a block that already has a filter, so without the wipe a corrupt filter in the shared store would survive the rebuild, and there is no way here to rebuild the filters alone. The departure lasts until btclib-org/btclib-node#1940 gives the filters a store of their own, after which -reindex-chainstate keeps them as Core does.
- class btclib_node.chainstate.Chainstate(data_dir: Path, chain: Chain, logger: Logger, *, wipe: bool = False)[source]¶
Bases:
objectThe block index, the UTXO set and the compact filter index, together.
The module docstring above is where the three, and the one KeyValueStore they share, are argued.
- close() None[source]¶
Flush every staged index, then close the shared store.
A clean close loses nothing staged – the crash this store has to survive is one that never reaches this method at all, and db.py’s docstring is where what that crash costs is decided. Safe to call twice: flush needs the connection open, so a second call skips it and reaches only KeyValueStore.close’s own no-op on an already-closed store.
- flush() None[source]¶
Write every index’s own staged changes, in one atomic batch.
main._finalize_fork stages a connected or disconnected block’s own status (BlockIndex.stage_status) and its filter (FilterIndex.add_connected_block) the same way UtxoIndex already staged its spends and creations, across more than one block; writing the three together here – one write_batch, one commit – is what keeps a status or a filter from ever landing on disk ahead of the UTXO set it was validated against. db.py’s own docstring argues why that has to hold.