Skip to content

fix(wallet): avoid reissuing change address after reload - #599

Open
NaitikVerma6776 wants to merge 1 commit into
bitcoindevkit:masterfrom
NaitikVerma6776:fix/577-change-address-persist
Open

NaitikVerma6776 wants to merge 1 commit into
bitcoindevkit:masterfrom
NaitikVerma6776:fix/577-change-address-persist

Conversation

@NaitikVerma6776

Copy link
Copy Markdown

Summary

  • Fixes Change address mark_used marker is not persisted; same change address reissued after restart #577: create_tx no longer recycles unused change addresses that only have an in-memory mark_used reservation.
  • Change selection now always uses next_index, so reveal_to_target stages a monotonic last_revealed update that survives persist/reload (no new ChangeSet fields).
  • Adds a regression test that builds a change-producing tx, persists, reloads, and asserts a different change SPK is used.

Test plan

  • cargo test --test persisted_wallet change_address_should_not_be_reissued_after_reload -- --exact
  • cargo test --test wallet test_create_tx_increment_change_index -- --exact
  • CI on this PR

@vadim-anfv vadim-anfv left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

This fixes the #577 repro, but unmark_used no longer affects change selection: create_tx now always takes next_index instead of the lowest unused change index. #393 removed cancel_tx and named unmark_used as the way to release the change address of a dropped (never broadcast) tx, and the test_tx_cancellation it dropped checked that this address gets reused. Now it doesn't: master reuses index 0, this branch takes index 1.

Test (passes on master, fails here)
#[test]
fn unmark_used_change_is_reused() {
    let (mut wallet, _) = get_funded_wallet_wpkh();
    let recipient = wallet.peek_address(KeychainKind::External, 0).script_pubkey();
    let change = wallet.peek_address(KeychainKind::Internal, 0).script_pubkey();

    for i in 0..2 {
        let mut builder = wallet.build_tx();
        builder.add_recipient(recipient.clone(), Amount::from_sat(10_000));
        let psbt = builder.finish().unwrap();
        assert!(
            psbt.unsigned_tx.output.iter().any(|o| o.script_pubkey == change),
            "tx {i}: change is not at index 0"
        );
        wallet.unmark_used(KeychainKind::Internal, 0);
    }
}

@notmandatory, is unmark_used still meant to replace cancel_tx? If so, updating the existing change index to include the used address won't work with it: that index only moves forward, so it can't represent a lower address released later.

With this PR every dropped tx leaves a gap in the change indexes. After 25 of them the next change is at index 25, and a restored wallet won't find it with the default lookahead or a full_scan with stop_gap <= 25. Sparrow with its default gap limit of 20 misses it already after 20.

On the other hand, after a reload the wallet can't tell a dropped tx from one that was broadcast but not synced yet, and reusing change in the second case is exactly #577. So it's a trade-off.

create_psbt already accepts reuse and leaves marking to the caller via mark_used, which is in-memory too:

bdk_wallet/src/wallet/mod.rs

Lines 3227 to 3232 in 7f1ec9f

/// When no [`ChangeScript`] is supplied via [`PsbtParams`], the wallet automatically selects
/// the next unused internal address and reveals it so that incoming change is tracked on
/// the next sync. The change address will not be marked used, so calling this function
/// again before syncing will use the same change address. If you intend to build
/// multiple transactions without syncing between them, either provide the change script in
/// the [`PsbtParams`], or do [`Wallet::mark_used`] after each call to prevent reuse.

So I'd suggest keeping change selection in create_tx as is and noting on build_tx that the change mark isn't persisted.

@codecov

codecov Bot commented Nov 9, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 81.75%. Comparing base (7f1ec9f) to head (44f83cf).
⚠️ Report is 26 commits behind head on master.

Additional details and impacted files
@@            Coverage Diff             @@
##           master     #599      +/-   ##
==========================================
+ Coverage   81.66%   81.75%   +0.08%     
==========================================
  Files          25       25              
  Lines        6339     6329      -10     
  Branches      302      302              
==========================================
- Hits         5177     5174       -3     
+ Misses       1055     1048       -7     
  Partials      107      107              
Flag Coverage Δ
rust 81.75% <100.00%> (+0.08%) ⬆️

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.

@thunderbiscuit thunderbiscuit 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.

Overall this is the right direction for the fix. @NaitikVerma6776 please rebase on master to fix CI failures and fix the test and we should be ready to go.

@vadim-anfv my opinion in this case is that allowing the gap to grow is ok because it's fairly unlikely you'd build + drop 20ish transactions in a row, without a sync, and if so the users doing this are building very custom flows for special applications, and would then be expected IMO to use and understand the more advanced aspects of the API. In this case it's a bit clunky because you'd need to pick the specific change address you want and use the TxBuilder::drain_to method to send your change funds there, but still. As is this is kind of a limitation of the API IMO that you can't "un-reveal" addresses, but this would need fixing I think at the bdk_chain layer (sorry for the rambling!).

Small fix to the test

One thing found by my agent was that your test is failing not on the bug itself:

The current test doesn't fail on the bug itself. It predicts the change index with next_derivation_index(Internal) before building and asserts the tx contains that address. On master, after a reload, the wallet hands out the old index 0 while the prediction says 1, so the test fails at that inner assert! and the assert_ne! that describes the bug never runs.

Here is a proposed fixed test that reads the change output from the PSBT instead of predicting it. It fails on master with change address at internal index 0 was handed out again after reload and passes on this PR.

#[test]
fn change_address_should_not_be_reissued_after_reload() -> anyhow::Result<()> {
    use bdk_chain::rusqlite;
    let mut conn = rusqlite::Connection::open_in_memory()?;

    let (desc, change_desc) = get_test_tr_single_sig_xprv_and_change_desc();
    let mut wallet = Wallet::create(desc, change_desc)
        .network(Network::Signet)
        .create_wallet(&mut conn)?;

    receive_output(&mut wallet, Amount::from_sat(50_000), ReceiveTo::Mempool(0));

    // Build a change-producing tx and return the change output's derivation index, read from
    // the tx itself rather than predicted, so a reused change address shows up as equal indices.
    fn create_change_tx(wallet: &mut Wallet) -> anyhow::Result<u32> {
        let recipient = wallet.next_unused_address(KeychainKind::External).address;
        let mut builder = wallet.build_tx();
        builder.add_recipient(recipient, Amount::from_sat(10_000));
        let psbt = builder.finish()?;
        let change_indices: Vec<u32> = psbt
            .unsigned_tx
            .output
            .iter()
            .filter_map(|o| wallet.derivation_of_spk(o.script_pubkey.clone()))
            .filter(|(keychain, _)| *keychain == KeychainKind::Internal)
            .map(|(_, index)| index)
            .collect();
        assert_eq!(
            change_indices.len(),
            1,
            "expected exactly one change output"
        );
        Ok(change_indices[0])
    }

    let change1 = create_change_tx(&mut wallet)?;
    wallet.persist(&mut conn)?;

    // Reload the wallet (as after a restart) before the first tx is seen on chain.
    let mut wallet = Wallet::load()
        .load_wallet(&mut conn)?
        .expect("wallet is persisted");
    let change2 = create_change_tx(&mut wallet)?;

    assert_ne!(
        change1, change2,
        "change address at internal index {change1} was handed out again after reload"
    );
    Ok(())
}

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Status: Triage

Development

Successfully merging this pull request may close these issues.

Change address mark_used marker is not persisted; same change address reissued after restart

3 participants