Skip to content

feat(chain)!: classify timelocked outputs as Immature - #2321

Merged
evanlinjin merged 2 commits into
bitcoindevkit:masterfrom
Dmenec:feat/eligibility-locked
Oct 19, 2026
Merged

evanlinjin merged 2 commits into
bitcoindevkit:masterfrom
Dmenec:feat/eligibility-locked

Conversation

@Dmenec

@Dmenec Dmenec commented Sep 21, 2026 •

Copy link
Copy Markdown
Contributor

Description

Classifies outputs whose timelock hasn't matured yet as Eligibility::Immature, so they aren't counted as spendable balance. classify_outpoints and balance take a new is_locked predicate, evaluated on every output.

Notes to the reviewers

The timelock lives in the output's descriptor, so CanonicalView can't evaluate it from chain data alone. The caller passes is_locked instead, the same way it passes does_taint. The wallet side will follow in a separate bdk_wallet PR.

Timelocked (CSV, CLTV) outputs share Immature with immature coinbase outputs, since neither is spendable by consensus. Callers that need to tell them apart can check is_on_coinbase. Other locked coins that aren't enforced by consensus, like frozen or reserved coins, shouldn't use is_locked and are expected to be handled in the wallet.

Changelog notice

Breaking: CanonicalView::classify_outpoints and balance take a new is_locked predicate which classifies outputs with unmet timelocks as Immature.

Checklists

All Submissions:

New Features:

  • I've added tests for the new feature
  • I've added docs for the new feature

Bugfixes:

  • This pull request breaks the existing API
  • I've added tests to reproduce the issue which are now passing
  • I'm linking the issue being fixed by this PR

@codecov

codecov Bot commented Sep 21, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 80.00000% with 1 line in your changes missing coverage. Please review.
✅ Project coverage is 80.26%. Comparing base (1fedce6) to head (ba702bd).
⚠️ Report is 33 commits behind head on master.

Files with missing lines Patch % Lines
crates/chain/src/canonical.rs 80.00% 1 Missing ⚠️
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     
Flag Coverage Δ
rust 80.26% <80.00%> (+1.15%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@nymius nymius left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

cACK cf0edd7

This is a valuable feature. Implementation is missing more complex mainnet like tests.
Try to keep coverage percentage positive, i.e., >0%.

Comment thread crates/chain/src/canonical.rs Resolved
@Dmenec
Dmenec force-pushed the feat/eligibility-locked branch 4 times, most recently from 833100b to 698d67a Compare October 1, 2026 08:16

@evanlinjin evanlinjin left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ConceptACK

Comment thread crates/chain/src/canonical.rs Resolved
Comment thread crates/chain/src/canonical.rs Resolved
Comment thread crates/chain/src/canonical.rs Resolved
@Dmenec

Dmenec commented Oct 15, 2026 •

Copy link
Copy Markdown
Contributor Author

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 is_locked docs, because I think it's better not to handle this in bdk. Callers can check ChainPosition::Confirmed::transitively in their is_locked and, if they want to handle these cases, fetch the parent's anchor from their chain source.

@Dmenec Dmenec changed the title feat(chain)!: add Locked eligibility for timelocked outputs feat(chain)!: classify timelocked outputs as Immature Oct 15, 2026
@Dmenec
Dmenec force-pushed the feat/eligibility-locked branch from c8ba866 to 626b4d2 Compare October 15, 2026 16:55
@kallal79

This comment has been minimized.

Comment thread crates/chain/src/canonical.rs Resolved
Comment thread crates/chain/src/balance.rs Resolved
@evanlinjin

Copy link
Copy Markdown
Contributor

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 is_locked docs, because I think it's better not to handle this in bdk. Callers can check ChainPosition::Confirmed::transitively in their is_locked and, if they want to handle these cases, fetch the parent's anchor from their chain source.

@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`.
@Dmenec
Dmenec force-pushed the feat/eligibility-locked branch from 626b4d2 to ba702bd Compare October 19, 2026 06:24

@evanlinjin evanlinjin left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ACK ba702bd

Just a final nit for the test.

Comment on lines +1123 to +1311
/// 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
);
}
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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}");
    }
}

@evanlinjin
evanlinjin merged commit 634b42c into bitcoindevkit:master Oct 19, 2026
19 checks passed
@Dmenec
Dmenec deleted the feat/eligibility-locked branch October 19, 2026 17:11
IndigoNakamoto added a commit to LitecoinDevKit/bdk that referenced this pull request Oct 24, 2026
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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

4 participants