Repository navigation
feat(chain)!: classify timelocked outputs as Immature - #2321
Conversation
Codecov Report❌ Patch coverage is
Additional details and impacted files@@ Coverage Diff @@
## master #2321 +/- ##
==========================================
+ Coverage 79.11% 80.26% +1.15%
==========================================
Files 31 31
Lines 6061 6168 +107
Branches 289 292 +3
==========================================
+ Hits 4795 4951 +156
+ Misses 1187 1147 -40
+ Partials 79 70 -9
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
833100b to
698d67a
Compare
698d67a to
c8ba866
Compare
|
While reviewing #2299 I saw that transitive confirmations can also affect timelocks. If an output is only confirmed through a descendant's anchor, its confirmation height is an upper bound, so a relative timelock can look unmet when it's already met. I left it as a note in the |
Locked eligibility for timelocked outputsImmature
c8ba866 to
626b4d2
Compare
This comment has been minimized.
This comment has been minimized.
@Dmenec this is fine and expected. Wallet data is sparse so if we have missing data, we may get false-positives for whether something is locked. This is the right direction. False-negatives would be a problem. |
Add an `is_locked` predicate on `classify_outpoints`/`balance` so the caller marks outputs whose timelock has not matured yet. They are classified as `Immature`.
626b4d2 to
ba702bd
Compare
evanlinjin
left a comment
There was a problem hiding this comment.
ACK ba702bd
Just a final nit for the test.
| /// An output behind OP_CSV or OP_CLTV is `Immature` while unconfirmed. Once confirmed, the CSV one | ||
| /// stays `Immature` until it has enough confirmations, and the CLTV one until the tip reaches its | ||
| /// lock height. | ||
| #[test] | ||
| fn test_classify_locked_script_timelocks() { | ||
| enum Timelock { | ||
| Relative(u32), | ||
| Absolute(u32), | ||
| } | ||
|
|
||
| /// Reads the first `<n> OP_CSV` or `<n> OP_CLTV` pair in `script`. | ||
| fn read_timelock(script: &Script) -> Option<Timelock> { | ||
| let instructions = script.instructions().collect::<Result<Vec<_>, _>>().ok()?; | ||
| instructions.windows(2).find_map(|pair| { | ||
| let n = u32::try_from(pair[0].script_num()?).ok()?; | ||
| match &pair[1] { | ||
| Instruction::Op(op) if *op == OP_CSV => Some(Timelock::Relative(n)), | ||
| Instruction::Op(op) if *op == OP_CLTV => Some(Timelock::Absolute(n)), | ||
| _ => None, | ||
| } | ||
| }) | ||
| } | ||
|
|
||
| /// Returns true if the UTXO is still locked by its timelock. | ||
| fn is_locked( | ||
| wallet: &HashMap<ScriptBuf, ScriptBuf>, | ||
| tip: u32, | ||
| utxo: &CanonicalTxOut<ChainPosition<ConfirmationBlockTime>>, | ||
| ) -> bool { | ||
| let spk = &utxo.txout.script_pubkey; | ||
| let Some(script) = wallet.get(spk) else { | ||
| return false; | ||
| }; | ||
| let Some(timelock) = read_timelock(script) else { | ||
| return false; | ||
| }; | ||
| match timelock { | ||
| Timelock::Relative(n) => utxo.pos.confirmations_lower_bound(tip) < n, | ||
| Timelock::Absolute(h) => tip < h, | ||
| } | ||
| } | ||
|
|
||
| let key = "tprv8ZgxMBicQKsPd3krDUsBAmtnRsK3rb8u5yi1zhQgMhF1tR8MW7xfE4rnrbbsrbPR52e7rKapu6ztw1jXveJSCGHEriUGZV7mCe88duLp5pj/0/*"; | ||
| let desc_csv = format!("wsh(and_v(v:pk({key}),older(100)))"); | ||
| let desc_cltv = format!("wsh(and_v(v:pk({key}),after(200)))"); | ||
|
|
||
| let secp = Secp256k1::signing_only(); | ||
|
|
||
| let (desc_csv, _) = Descriptor::parse_descriptor(&secp, &desc_csv).unwrap(); | ||
| let (desc_cltv, _) = Descriptor::parse_descriptor(&secp, &desc_cltv).unwrap(); | ||
|
|
||
| let desc_csv = desc_csv.at_derivation_index(0).unwrap(); | ||
| let desc_cltv = desc_cltv.at_derivation_index(0).unwrap(); | ||
|
|
||
| let wallet = HashMap::from([ | ||
| ( | ||
| desc_csv.script_pubkey(), | ||
| desc_csv.explicit_script().unwrap(), | ||
| ), | ||
| ( | ||
| desc_cltv.script_pubkey(), | ||
| desc_cltv.explicit_script().unwrap(), | ||
| ), | ||
| ]); | ||
|
|
||
| let blocks: BTreeMap<u32, BlockHash> = [ | ||
| (0, hash!("genesis")), | ||
| (50, hash!("50")), | ||
| (100, hash!("100")), | ||
| ] | ||
| .into_iter() | ||
| .collect(); | ||
| let mut chain = LocalChain::from_blocks(blocks).unwrap(); | ||
| let mut tx_graph = TxGraph::<ConfirmationBlockTime>::default(); | ||
|
|
||
| let parent = Transaction { | ||
| input: vec![TxIn { | ||
| previous_output: OutPoint::new(hash!("ext"), 0), | ||
| ..Default::default() | ||
| }], | ||
| output: vec![TxOut { | ||
| value: Amount::from_sat(40_000), | ||
| script_pubkey: ScriptBuf::new(), | ||
| }], | ||
| ..new_tx(0) | ||
| }; | ||
| let parent_txid = parent.compute_txid(); | ||
| let _ = tx_graph.insert_tx(parent); | ||
| let _ = tx_graph.insert_anchor( | ||
| parent_txid, | ||
| ConfirmationBlockTime { | ||
| block_id: chain.get(50).unwrap().block_id(), | ||
| confirmation_time: 50, | ||
| }, | ||
| ); | ||
|
|
||
| let tx = Transaction { | ||
| input: vec![TxIn { | ||
| previous_output: OutPoint::new(parent_txid, 0), | ||
| ..Default::default() | ||
| }], | ||
| output: vec![ | ||
| TxOut { | ||
| value: Amount::from_sat(10_000), | ||
| script_pubkey: desc_csv.script_pubkey(), | ||
| }, | ||
| TxOut { | ||
| value: Amount::from_sat(20_000), | ||
| script_pubkey: desc_cltv.script_pubkey(), | ||
| }, | ||
| ], | ||
| ..new_tx(0) | ||
| }; | ||
|
|
||
| let txid: bitcoin::Txid = tx.compute_txid(); | ||
| let csv_op = OutPoint::new(txid, 0); | ||
| let cltv_op = OutPoint::new(txid, 1); | ||
|
|
||
| let _ = tx_graph.insert_tx(tx); | ||
| let _ = tx_graph.insert_seen_at(txid, 100); | ||
| let view = chain.canonical_view(&tx_graph, chain.tip().block_id(), Default::default()); | ||
| let tip = view.tip().height; | ||
| let unconfirmed = view | ||
| .classify_outpoints( | ||
| [csv_op, cltv_op], | ||
| |_| false, | ||
| |pos| pos.is_confirmed(), | ||
| |txout: &CanonicalTxOut<_>| is_locked(&wallet, tip, txout), | ||
| ) | ||
| .map(|(_, eligibility)| eligibility) | ||
| .collect::<Vec<_>>(); | ||
| assert_eq!(unconfirmed, [Eligibility::Immature, Eligibility::Immature]); | ||
|
|
||
| let _ = tx_graph.insert_anchor( | ||
| txid, | ||
| ConfirmationBlockTime { | ||
| block_id: chain.get(100).unwrap().block_id(), | ||
| confirmation_time: 100, | ||
| }, | ||
| ); | ||
|
|
||
| chain.insert_block(101, hash!("101")).unwrap(); | ||
|
|
||
| let test_cases = [ | ||
| (198, true, true), // tip 198 -> CSV Immature, CLTV Immature | ||
| (199, false, true), // tip 199 -> CSV Settled, CLTV Immature | ||
| (200, false, false), // tip 200 -> CSV Settled, CLTV Settled | ||
| ]; | ||
|
|
||
| for (tip_height, expect_csv_locked, expect_cltv_locked) in test_cases { | ||
| chain.insert_block(tip_height, hash!("tip")).unwrap(); | ||
| let view = chain.canonical_view(&tx_graph, chain.tip().block_id(), Default::default()); | ||
| let tip = view.tip().height; | ||
|
|
||
| let (_, csv) = view | ||
| .classify_outpoints( | ||
| [csv_op], | ||
| |_| true, | ||
| |pos| pos.is_confirmed(), | ||
| |txout: &CanonicalTxOut<_>| is_locked(&wallet, tip, txout), | ||
| ) | ||
| .next() | ||
| .unwrap(); | ||
|
|
||
| let (_, cltv) = view | ||
| .classify_outpoints( | ||
| [cltv_op], | ||
| |_| true, | ||
| |pos| pos.is_confirmed(), | ||
| |txout: &CanonicalTxOut<_>| is_locked(&wallet, tip, txout), | ||
| ) | ||
| .next() | ||
| .unwrap(); | ||
|
|
||
| let csv_is_locked = csv == Eligibility::Immature; | ||
| let cltv_is_locked = cltv == Eligibility::Immature; | ||
|
|
||
| assert_eq!( | ||
| csv_is_locked, expect_csv_locked, | ||
| "csv at tip {tip} expected: {}", | ||
| expect_csv_locked | ||
| ); | ||
| assert_eq!( | ||
| cltv_is_locked, expect_cltv_locked, | ||
| "cltv at tip {tip} expected: {}", | ||
| expect_cltv_locked | ||
| ); | ||
| } | ||
| } |
There was a problem hiding this comment.
nit: Simpler version of this test (~65 lines instead of ~190). It keeps what nymius asked for (real older/after descriptors, and an is_locked that evaluates them from the spk and position it receives) and drops what only tests the test: the <n> OP_CSV parser (the two locks are known, so is_locked can name them), the confirmed parent and block 50 (the ancestry walk never reaches them), insert_block(101), and the two classify_outpoints calls per tip. With does_taint = |_| true it also pins the untrusted, unconfirmed, locked case. Tested: passes against this PR's head, no new clippy warnings.
/// `is_locked` gets what a wallet needs to evaluate its descriptors' timelocks: the spk, and the
/// position to count confirmations. Both outputs are `Immature` while unconfirmed (here also
/// untrusted). Once confirmed, the `older(100)` one is `Immature` until its 100th confirmation,
/// and the `after(200)` one until the tip reaches 200.
#[test]
fn test_classify_locked_script_timelocks() {
let key = "tprv8ZgxMBicQKsPd3krDUsBAmtnRsK3rb8u5yi1zhQgMhF1tR8MW7xfE4rnrbbsrbPR52e7rKapu6ztw1jXveJSCGHEriUGZV7mCe88duLp5pj/0/*";
let spk = |lock: &str| {
let desc = format!("wsh(and_v(v:pk({key}),{lock}))");
let (desc, _) = Descriptor::parse_descriptor(&Secp256k1::signing_only(), &desc).unwrap();
desc.at_derivation_index(0).unwrap().script_pubkey()
};
let (csv_spk, cltv_spk) = (spk("older(100)"), spk("after(200)"));
let is_locked = |tip: u32, txout: &CanonicalTxOut<ChainPosition<ConfirmationBlockTime>>| {
let spk = &txout.txout.script_pubkey;
(*spk == csv_spk && txout.pos.confirmations_lower_bound(tip) < 100)
|| (*spk == cltv_spk && tip < 200)
};
let mut chain =
LocalChain::from_blocks([(0, hash!("genesis")), (100, hash!("100"))].into()).unwrap();
let mut tx_graph = TxGraph::<ConfirmationBlockTime>::default();
let tx = Transaction {
input: vec![TxIn {
previous_output: OutPoint::new(hash!("ext"), 0),
..Default::default()
}],
output: vec![
TxOut {
value: Amount::from_sat(10_000),
script_pubkey: csv_spk.clone(),
},
TxOut {
value: Amount::from_sat(20_000),
script_pubkey: cltv_spk.clone(),
},
],
..new_tx(0)
};
let txid = tx.compute_txid();
let _ = tx_graph.insert_tx(tx);
let _ = tx_graph.insert_seen_at(txid, 100);
let classify = |chain: &LocalChain, tx_graph: &TxGraph<ConfirmationBlockTime>| {
let view = chain.canonical_view(tx_graph, chain.tip().block_id(), Default::default());
let tip = view.tip().height;
let ops = [OutPoint::new(txid, 0), OutPoint::new(txid, 1)];
view.classify_outpoints(ops, |_| true, |pos| pos.is_confirmed(), |o| is_locked(tip, o))
.map(|(_, eligibility)| eligibility)
.collect::<Vec<_>>()
};
assert_eq!(classify(&chain, &tx_graph), [Eligibility::Immature; 2]);
let anchor = ConfirmationBlockTime {
block_id: chain.get(100).unwrap().block_id(),
confirmation_time: 100,
};
let _ = tx_graph.insert_anchor(txid, anchor);
for (tip, expected) in [
(198, [Eligibility::Immature, Eligibility::Immature]),
(199, [Eligibility::Settled, Eligibility::Immature]),
(200, [Eligibility::Settled, Eligibility::Settled]),
] {
chain.insert_block(tip, hash!("tip")).unwrap();
assert_eq!(classify(&chain, &tx_graph), expected, "tip {tip}");
}
}Brings in 102 upstream commits (2026-07-24..2026-10-22): taint-aware `CanonicalView::balance` (bitcoindevkit#2246), `Anchor::confirmation_height_upper_bound` removal (bitcoindevkit#2299), timelocked outputs as `Immature` (bitcoindevkit#2321), genesis-safe `LocalChain::apply_changeset` / `insert_block` errors (bitcoindevkit#2380), `Indexer::rescan` (bitcoindevkit#2262), electrum/esplora hardening, and the MSRV job narrowing to `--lib`. Resolution notes (alias-only; no `.rs` logic diverged): - Manifests keep the `litecoin` alias, miniscript 12.x fork pin, vendored `bitcoincore-rpc`, and esplora-client fork; take upstream's `serde` `default-features = false` and tokio `time`. - Workflows keep SHA-pinned actions; `actions/checkout` moves to the v7 SHA everywhere, `Swatinem/rust-cache` to v2.9.2. - `crates/testenv/src/daemon.rs` regenerated from upstream `lib.rs` (same three deltas as before). `LitecoinTestEnv` mirrors the new `wait_until_electrum_sees_block(height, Option<hash>, timeout)` and `wait_until_electrum_tip_syncs_with_bitcoind`. - `examples/ltc-scan` ported to the new `balance` signature. - Parked `*.upstream` bitcoind_rpc tests received upstream's edits via rename detection and stay parked. Co-authored-by: Cursor <[email protected]>
Description
Classifies outputs whose timelock hasn't matured yet as
Eligibility::Immature, so they aren't counted as spendable balance.classify_outpointsandbalancetake a newis_lockedpredicate, evaluated on every output.Notes to the reviewers
The timelock lives in the output's descriptor, so
CanonicalViewcan't evaluate it from chain data alone. The caller passesis_lockedinstead, the same way it passesdoes_taint. The wallet side will follow in a separatebdk_walletPR.Timelocked (CSV, CLTV) outputs share
Immaturewith immature coinbase outputs, since neither is spendable by consensus. Callers that need to tell them apart can checkis_on_coinbase. Other locked coins that aren't enforced by consensus, like frozen or reserved coins, shouldn't useis_lockedand are expected to be handled in the wallet.Changelog notice
Breaking:
CanonicalView::classify_outpointsandbalancetake a newis_lockedpredicate which classifies outputs with unmet timelocks asImmature.Checklists
All Submissions:
New Features:
Bugfixes: