Repository navigation
fix(wallet): avoid reissuing change address after reload - #599
NaitikVerma6776 wants to merge 1 commit into
Conversation
vadim-anfv
left a comment
There was a problem hiding this comment.
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:
Lines 3227 to 3232 in 7f1ec9f
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 Report✅ All modified and coverable lines are covered by tests. 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
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:
|
thunderbiscuit
left a comment
There was a problem hiding this comment.
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 innerassert!and theassert_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(())
}
Summary
mark_usedmarker is not persisted; same change address reissued after restart #577:create_txno longer recyclesunusedchange addresses that only have an in-memorymark_usedreservation.next_index, soreveal_to_targetstages a monotoniclast_revealedupdate that survives persist/reload (no new ChangeSet fields).Test plan
cargo test --test persisted_wallet change_address_should_not_be_reissued_after_reload -- --exactcargo test --test wallet test_create_tx_increment_change_index -- --exact