From 7bd074c32b357744bb1bae1230898b61abf19278 Mon Sep 17 00:00:00 2001 From: Quantum Explorer Date: Mon, 28 Sep 2026 11:46:56 +0700 Subject: [PATCH 01/13] feat(key-wallet)!: lock masternode collateral out of coin selection A wallet now locks the outputs it owns that back a registered masternode, so ordinary sends never spend them; an explicit unlock is available. Spending the collateral would end the registration. The wallet keeps one set of locked outpoints, `ManagedWalletInfo::locked_outpoints`, like Dash Core's `setLockedCoins`. Every ProRegTx the wallet processes adds its collateral: the outpoint it names, or its own output at `collateralIndex` when the collateral txid is null. The collateral may arrive before or after the ProRegTx. `lock_outpoint` and `unlock_outpoint` lock and unlock by hand, and only an unlock removes an entry. A ProUpRevTx or a replacing ProRegTx leaves the collateral locked; spending it removes the coin and leaves an entry with nothing to act on. Coin selection sees only `Utxo`s, so the wallet keeps each held coin's `is_locked` equal to membership in the set: when the coin arrives, on lock and unlock, and on every balance refresh. `is_spendable`, every selection strategy including the `All` drain, the spendable balance and the asset-lock builder follow from that, and `fund_from` also drops a seeded copy of a coin the account holds locked. The set is serialized with the wallet (`serde(default)`), and each check lists the outpoints it locked in `TransactionCheckResult::locked_outpoints` for stores that persist wallet state their own way. Co-Authored-By: Claude Opus 5.5 (cherry picked from commit 183d07fa818e5b6d69a63f87ae5c10d459c48f02) --- .../managed_core_funds_account.rs | 6 +- key-wallet/src/tests/balance_tests.rs | 9 +- .../src/tests/locked_outpoints_tests.rs | 582 ++++++++++++++++++ key-wallet/src/tests/mod.rs | 2 + .../transaction_checking/account_checker.rs | 11 + .../transaction_checking/wallet_checker.rs | 53 ++ key-wallet/src/utxo.rs | 20 +- key-wallet/src/wallet/balance.rs | 3 +- .../managed_wallet_info/locked_outpoints.rs | 255 ++++++++ .../src/wallet/managed_wallet_info/mod.rs | 14 + .../transaction_builder.rs | 21 +- .../wallet_info_interface.rs | 7 +- 12 files changed, 970 insertions(+), 13 deletions(-) create mode 100644 key-wallet/src/tests/locked_outpoints_tests.rs create mode 100644 key-wallet/src/wallet/managed_wallet_info/locked_outpoints.rs diff --git a/key-wallet/src/managed_account/managed_core_funds_account.rs b/key-wallet/src/managed_account/managed_core_funds_account.rs index 7eb199933..f8a1cc91b 100644 --- a/key-wallet/src/managed_account/managed_core_funds_account.rs +++ b/key-wallet/src/managed_account/managed_core_funds_account.rs @@ -358,9 +358,9 @@ impl ManagedCoreFundsAccount { // scratch, so carry forward flags that must not regress. An // InstantSend lock is permanent for a txid (DIP-0010) and // trust only ever settles, so both latch monotonically. A - // coin reservation is orthogonal to chain context and is kept - // as-is. `is_confirmed` stays freshly derived so a reorg can - // still downgrade it. + // coin lock follows the wallet's lock set, not chain context, + // and is kept as-is. `is_confirmed` stays freshly derived so a + // reorg can still downgrade it. copies.extend(self.utxos.get(&outpoint).cloned()); if !copies.is_empty() { output.is_instantlocked |= copies.iter().any(|copy| copy.is_instantlocked); diff --git a/key-wallet/src/tests/balance_tests.rs b/key-wallet/src/tests/balance_tests.rs index ecb1f1481..d0cd4cb83 100644 --- a/key-wallet/src/tests/balance_tests.rs +++ b/key-wallet/src/tests/balance_tests.rs @@ -54,13 +54,18 @@ fn test_locked_utxos_in_locked_balance() { let mut wallet_info = ManagedWalletInfo::dummy(3); let mut account = ManagedCoreFundsAccount::dummy_bip44(); - let mut utxo = Utxo::dummy(1, 100_000, 1000, false, true); - utxo.is_locked = true; + let utxo = Utxo::dummy(1, 100_000, 1000, false, true); + let outpoint = utxo.outpoint; account.utxos.insert(utxo.outpoint, utxo); wallet_info.accounts.insert(account).unwrap(); assert_eq!(wallet_info.balance, WalletCoreBalance::default()); wallet_info.update_last_processed_height(1100); + assert_eq!(wallet_info.balance, WalletCoreBalance::new(100_000, 0, 0, 0)); + + // A held coin is locked through the wallet's lock set, which moves its + // value to the locked bucket. + assert!(wallet_info.lock_outpoint(outpoint)); let expected = WalletCoreBalance::new(0, 0, 0, 100_000); assert_eq!(wallet_info.balance, expected); } diff --git a/key-wallet/src/tests/locked_outpoints_tests.rs b/key-wallet/src/tests/locked_outpoints_tests.rs new file mode 100644 index 000000000..4bd2d294c --- /dev/null +++ b/key-wallet/src/tests/locked_outpoints_tests.rs @@ -0,0 +1,582 @@ +//! A wallet locks the coins it owns that back a registered masternode, so +//! ordinary sends never spend them, and anything else locked by hand. See +//! [`ManagedWalletInfo::locked_outpoints`](crate::wallet::ManagedWalletInfo::locked_outpoints). + +use std::str::FromStr; + +use dashcore::address::NetworkUnchecked; +use dashcore::blockdata::transaction::special_transaction::provider_registration::{ + ProviderMasternodeType, ProviderRegistrationPayload, +}; +use dashcore::blockdata::transaction::special_transaction::provider_update_revocation::ProviderUpdateRevocationPayload; +use dashcore::blockdata::transaction::special_transaction::provider_update_service::ProviderUpdateServicePayload; +use dashcore::blockdata::transaction::special_transaction::TransactionPayload; +use dashcore::bls_sig_utils::{BLSPublicKey, BLSSignature}; +use dashcore::hash_types::InputsHash; +use dashcore::hashes::Hash; +use dashcore::{ + Address, BlockHash, OutPoint, PubkeyHash, ScriptBuf, Transaction, TxIn, TxOut, Txid, +}; +use test_case::test_case; + +use crate::test_utils::TestWalletContext; +use crate::transaction_checking::{BlockInfo, TransactionContext, WalletTransactionChecker}; +use crate::wallet::managed_wallet_info::asset_lock_builder::{ + AssetLockError, AssetLockFundingType, CreditOutputFunding, +}; +use crate::wallet::managed_wallet_info::coin_selection::{SelectionError, SelectionStrategy}; +use crate::wallet::managed_wallet_info::fee::FeeRate; +use crate::wallet::managed_wallet_info::transaction_builder::{BuilderError, TransactionBuilder}; +use crate::wallet::managed_wallet_info::transaction_building::AccountTypePreference; +use crate::wallet::managed_wallet_info::wallet_info_interface::WalletInfoInterface; +use crate::Utxo; + +const DASH: u64 = 100_000_000; +const COLLATERAL: u64 = 1_000 * DASH; +const SPARE: u64 = 5 * DASH; +const TIP: u32 = 200; + +fn block(height: u32) -> TransactionContext { + TransactionContext::InBlock(BlockInfo::new( + height, + BlockHash::from_byte_array([height as u8; 32]), + 1_700_000_000 + height, + )) +} + +/// An address that is not the wallet's. +fn elsewhere() -> Address { + Address::from_str("yTb47qEBpNmgXvYYsHEN4nh8yJwa5iC4Cs").expect("testnet address") +} + +/// A ProRegTx registering `collateral`, paying `outputs`. Everything else, +/// its fee input and keys included, belongs to no one this wallet knows, so +/// the collateral is its only link to the wallet. `seed` varies the txid. +fn registration(collateral: OutPoint, outputs: Vec, seed: u8) -> Transaction { + let key_hash = PubkeyHash::from_byte_array([0x70; 20]); + Transaction { + version: 3, + lock_time: 0, + input: vec![TxIn { + previous_output: OutPoint::new(Txid::from_byte_array([seed; 32]), 0), + ..Default::default() + }], + output: outputs, + special_transaction_payload: Some(TransactionPayload::ProviderRegistrationPayloadType( + ProviderRegistrationPayload { + version: 1, + masternode_type: ProviderMasternodeType::Regular, + masternode_mode: 0, + collateral_outpoint: collateral, + service_address: "127.0.0.1:19999".parse().expect("socket address"), + owner_key_hash: key_hash, + operator_public_key: BLSPublicKey::from([0x11; 48]), + voting_key_hash: key_hash, + operator_reward: 0, + script_payout: ScriptBuf::new(), + inputs_hash: InputsHash::all_zeros(), + signature: vec![0x33; 65], + platform_node_id: None, + platform_p2p_port: None, + platform_http_port: None, + }, + )), + } +} + +/// Pay `value` to the wallet in a block at `height`; `seed` varies the txid. +async fn receive(ctx: &mut TestWalletContext, value: u64, seed: u8, height: u32) -> OutPoint { + let tx = Transaction::dummy(&ctx.receive_address, seed..seed + 1, &[value]); + assert!(ctx.check_transaction(&tx, block(height)).await.is_relevant); + OutPoint::new(tx.txid(), 0) +} + +/// A wallet holding a 1,000 DASH coin registered as masternode collateral by +/// a ProRegTx it has seen, and a spare coin of `spare` duffs, if any. +async fn registered_wallet(spare: Option) -> (TestWalletContext, OutPoint, Option) { + let mut ctx = TestWalletContext::new_random(); + let collateral = receive(&mut ctx, COLLATERAL, 0x01, 100).await; + let spare = match spare { + Some(value) => Some(receive(&mut ctx, value, 0x02, 100).await), + None => None, + }; + let registration = registration(collateral, vec![], 0xEE); + let registered = ctx.check_transaction(®istration, block(101)).await; + assert_eq!(registered.locked_outpoints, vec![collateral]); + ctx.managed_wallet.update_last_processed_height(TIP); + (ctx, collateral, spare) +} + +/// Build a send of `amount` from BIP44 account 0 without signing it. The +/// build's reservation is handed back, so the next build sees every coin. +fn send( + ctx: &mut TestWalletContext, + amount: u64, + strategy: SelectionStrategy, +) -> Result { + let (tx, _fee) = ctx.managed_wallet.build_unsigned_transaction( + &ctx.wallet, + &[AccountTypePreference::BIP44], + 0, + vec![(elsewhere(), amount)], + FeeRate::normal(), + strategy, + )?; + ctx.bip44_account().release_reservation(&tx); + Ok(tx) +} + +fn spent(tx: &Transaction) -> Vec { + tx.input.iter().map(|input| input.previous_output).collect() +} + +fn is_out_of_coins(result: Result) -> bool { + matches!( + result, + Err(BuilderError::CoinSelection( + SelectionError::NoUtxosAvailable + | SelectionError::InsufficientFunds { + available: 0, + .. + } + )) + ) +} + +#[test_case(SelectionStrategy::SmallestFirst ; "smallest first")] +#[test_case(SelectionStrategy::LargestFirst ; "largest first")] +#[test_case(SelectionStrategy::SmallestFirstTill(1) ; "smallest first till one")] +#[test_case(SelectionStrategy::BranchAndBound ; "branch and bound")] +#[test_case(SelectionStrategy::OptimalConsolidation ; "optimal consolidation")] +#[test_case(SelectionStrategy::Random ; "random")] +#[test_case(SelectionStrategy::All ; "drain")] +#[tokio::test] +async fn a_send_spends_the_spare_coin_and_never_the_collateral(strategy: SelectionStrategy) { + let (mut ctx, _collateral, spare) = registered_wallet(Some(SPARE)).await; + + let tx = send(&mut ctx, DASH, strategy).expect("the spare 5 DASH covers a 1 DASH send"); + + // A drain takes every spendable coin: still only the spare one. + assert_eq!(spent(&tx), vec![spare.expect("spare coin")]); +} + +#[test_case(SelectionStrategy::SmallestFirst ; "smallest first")] +#[test_case(SelectionStrategy::LargestFirst ; "largest first")] +#[test_case(SelectionStrategy::SmallestFirstTill(1) ; "smallest first till one")] +#[test_case(SelectionStrategy::BranchAndBound ; "branch and bound")] +#[test_case(SelectionStrategy::OptimalConsolidation ; "optimal consolidation")] +#[test_case(SelectionStrategy::Random ; "random")] +#[test_case(SelectionStrategy::All ; "drain")] +#[tokio::test] +async fn a_wallet_holding_only_its_collateral_has_nothing_to_send(strategy: SelectionStrategy) { + let (mut ctx, _collateral, _) = registered_wallet(None).await; + + assert!(is_out_of_coins(send(&mut ctx, DASH, strategy))); + assert!(ctx.managed_wallet.get_spendable_utxos().is_empty()); + let balance = ctx.managed_wallet.balance(); + assert_eq!(balance.spendable(), 0, "the collateral is not spendable balance"); + assert_eq!(balance.locked(), COLLATERAL); + assert_eq!(balance.total(), COLLATERAL, "the collateral still counts toward the total"); +} + +/// The lock comes from the registration, not the amount: the same 1,000 DASH +/// coin is an ordinary coin until a ProRegTx names it. +#[tokio::test] +async fn a_collateral_sized_coin_nobody_registered_is_spendable() { + let mut ctx = TestWalletContext::new_random(); + let big = receive(&mut ctx, COLLATERAL, 0x01, 100).await; + receive(&mut ctx, SPARE, 0x02, 100).await; + ctx.managed_wallet.update_last_processed_height(TIP); + + let tx = send(&mut ctx, DASH, SelectionStrategy::LargestFirst).expect("funded"); + + assert_eq!(spent(&tx), vec![big]); + assert!(ctx.managed_wallet.locked_outpoints().is_empty()); +} + +#[test_case(true ; "collateral first")] +#[test_case(false ; "registration first")] +#[tokio::test] +async fn a_registration_locks_its_external_collateral_whichever_arrives_first( + collateral_first: bool, +) { + let mut ctx = TestWalletContext::new_random(); + let collateral_tx = Transaction::dummy(&ctx.receive_address, 0x01..0x02, &[COLLATERAL]); + let collateral = OutPoint::new(collateral_tx.txid(), 0); + let registration = registration(collateral, vec![], 0xEE); + + let registered = if collateral_first { + ctx.check_transaction(&collateral_tx, block(100)).await; + ctx.check_transaction(®istration, block(101)).await + } else { + // A rescan can hand over the later block first. + let registered = ctx.check_transaction(®istration, block(101)).await; + assert!(ctx.managed_wallet.is_outpoint_locked(&collateral), "locked before it arrives"); + ctx.check_transaction(&collateral_tx, block(100)).await; + registered + }; + + // No separate balance refresh: the checks leave the balance right. + assert!(!registered.is_relevant, "nothing but the collateral ties it to this wallet"); + assert_eq!(registered.locked_outpoints, vec![collateral]); + assert!(registered.state_modified, "the lock set is persisted state"); + assert!(ctx.bip44_account().utxos[&collateral].is_locked); + assert_eq!(ctx.managed_wallet.balance().locked(), COLLATERAL); + assert!(is_out_of_coins(send(&mut ctx, DASH, SelectionStrategy::LargestFirst))); +} + +#[test_case(&[TransactionContext::Mempool, block(101)] ; "seen in the mempool, then mined")] +#[test_case(&[block(101)] ; "first seen mined")] +#[tokio::test] +async fn a_registration_locks_the_collateral_it_creates(sightings: &[TransactionContext]) { + let mut ctx = TestWalletContext::new_random(); + let to_wallet = TxOut { + value: COLLATERAL, + script_pubkey: ctx.receive_address.script_pubkey(), + }; + let to_elsewhere = TxOut { + value: DASH, + script_pubkey: elsewhere().assume_checked().script_pubkey(), + }; + // A null collateral txid: the collateral is this ProRegTx's output 1. + let registration = + registration(OutPoint::new(Txid::all_zeros(), 1), vec![to_elsewhere, to_wallet], 0xEE); + let collateral = OutPoint::new(registration.txid(), 1); + + let mut reported = Vec::new(); + for context in sightings { + let result = ctx.check_transaction(®istration, context.clone()).await; + assert!(result.is_relevant, "the collateral pays this wallet"); + reported.extend(result.locked_outpoints); + assert!( + ctx.bip44_account().utxos[&collateral].is_locked, + "the coin is locked from its first sighting, in {context}" + ); + } + ctx.managed_wallet.update_last_processed_height(TIP); + + assert_eq!(reported, vec![collateral], "reported once, when first locked"); + assert_eq!(ctx.managed_wallet.balance().locked(), COLLATERAL); + assert!(is_out_of_coins(send(&mut ctx, DASH, SelectionStrategy::LargestFirst))); +} + +#[tokio::test] +async fn unlocking_lets_a_send_spend_the_collateral_and_relocking_stops_it_again() { + let (mut ctx, collateral, _) = registered_wallet(None).await; + assert!(is_out_of_coins(send(&mut ctx, DASH, SelectionStrategy::LargestFirst))); + + assert!(ctx.managed_wallet.unlock_outpoint(&collateral)); + assert!(!ctx.managed_wallet.unlock_outpoint(&collateral), "already unlocked"); + assert_eq!(ctx.managed_wallet.balance().spendable(), COLLATERAL); + assert_eq!(ctx.managed_wallet.balance().locked(), 0); + let tx = send(&mut ctx, DASH, SelectionStrategy::LargestFirst).expect("unlocked"); + assert_eq!(spent(&tx), vec![collateral]); + + assert!(ctx.managed_wallet.lock_outpoint(collateral)); + assert!(!ctx.managed_wallet.lock_outpoint(collateral), "already locked"); + assert_eq!(ctx.managed_wallet.balance().locked(), COLLATERAL); + assert!(is_out_of_coins(send(&mut ctx, DASH, SelectionStrategy::LargestFirst))); +} + +/// Core ties the lock to the masternode list, which only spending the +/// collateral leaves: a revocation keeps the masternode registered, and a new +/// ProRegTx naming the same collateral replaces the registration. +#[tokio::test] +async fn a_revocation_or_a_replacing_registration_keeps_the_collateral_locked() { + let (mut ctx, collateral, spare) = registered_wallet(Some(SPARE)).await; + let original = registration(collateral, vec![], 0xEE); + + let revocation = Transaction { + version: 3, + lock_time: 0, + input: vec![TxIn { + previous_output: OutPoint::new(Txid::from_byte_array([0xEF; 32]), 0), + ..Default::default() + }], + output: Vec::new(), + special_transaction_payload: Some(TransactionPayload::ProviderUpdateRevocationPayloadType( + ProviderUpdateRevocationPayload { + version: 1, + pro_tx_hash: original.txid(), + reason: 0, + inputs_hash: InputsHash::all_zeros(), + payload_sig: BLSSignature::from([0; 96]), + }, + )), + }; + assert!(ctx.check_transaction(&revocation, block(102)).await.locked_outpoints.is_empty()); + assert!(ctx.managed_wallet.is_outpoint_locked(&collateral)); + + let replacement = registration(collateral, vec![], 0xF0); + let replaced = ctx.check_transaction(&replacement, block(103)).await; + assert!(replaced.locked_outpoints.is_empty(), "already locked, nothing new to report"); + assert!(ctx.managed_wallet.is_outpoint_locked(&collateral)); + + ctx.managed_wallet.update_last_processed_height(TIP); + let tx = send(&mut ctx, DASH, SelectionStrategy::LargestFirst).expect("the spare coin"); + assert_eq!(spent(&tx), vec![spare.expect("spare coin")]); +} + +/// Only spending the collateral ends a registration. The coin leaves; its +/// entry stays and has nothing to act on, so a spend that is reorged out or +/// swept brings the coin back locked. +#[tokio::test] +async fn spending_the_collateral_removes_the_coin_but_not_its_lock() { + let (mut ctx, collateral, _) = registered_wallet(None).await; + let spend = Transaction { + version: 1, + lock_time: 0, + input: vec![TxIn { + previous_output: collateral, + ..Default::default() + }], + output: vec![TxOut { + value: COLLATERAL - 1_000, + script_pubkey: elsewhere().assume_checked().script_pubkey(), + }], + special_transaction_payload: None, + }; + + assert!(ctx.check_transaction(&spend, block(150)).await.is_relevant); + + assert!(!ctx.bip44_account().utxos.contains_key(&collateral)); + assert!(ctx.managed_wallet.is_outpoint_locked(&collateral)); + assert_eq!(ctx.managed_wallet.balance().total(), 0); +} + +#[tokio::test] +async fn a_preview_check_locks_nothing() { + let mut ctx = TestWalletContext::new_random(); + let collateral = receive(&mut ctx, COLLATERAL, 0x01, 100).await; + + let preview = ctx + .managed_wallet + .check_core_transaction( + ®istration(collateral, vec![], 0xEE), + block(101), + &mut ctx.wallet, + false, + false, + ) + .await; + + assert!(preview.locked_outpoints.is_empty()); + assert!(!ctx.managed_wallet.is_outpoint_locked(&collateral)); + assert!(!ctx.bip44_account().utxos[&collateral].is_locked); +} + +/// Block processing checks each transaction with `update_balance = false` and +/// refreshes the balance once per block. The coin must be locked in between, +/// not only after that refresh. +#[tokio::test] +async fn a_collateral_is_locked_even_before_the_next_balance_refresh() { + let mut ctx = TestWalletContext::new_random(); + let collateral = receive(&mut ctx, COLLATERAL, 0x01, 100).await; + + let result = ctx + .managed_wallet + .check_core_transaction( + ®istration(collateral, vec![], 0xEE), + block(101), + &mut ctx.wallet, + true, + false, + ) + .await; + + assert_eq!(result.locked_outpoints, vec![collateral]); + assert!(ctx.bip44_account().utxos[&collateral].is_locked); + assert!(ctx.managed_wallet.get_spendable_utxos().is_empty()); +} + +/// The lock set is the source of truth: a flag written on a held coin by hand +/// is set back from the set on the next balance refresh. +#[tokio::test] +async fn a_held_coins_lock_flag_follows_the_lock_set() { + let (mut ctx, collateral, spare) = registered_wallet(Some(SPARE)).await; + let spare = spare.expect("spare coin"); + let account = ctx.managed_wallet.first_bip44_managed_account_mut().expect("BIP44 account"); + account.utxos.get_mut(&collateral).expect("collateral").is_locked = false; + account.utxos.get_mut(&spare).expect("spare").is_locked = true; + + ctx.managed_wallet.update_balance(); + + assert!(ctx.bip44_account().utxos[&collateral].is_locked); + assert!(!ctx.bip44_account().utxos[&spare].is_locked); + assert_eq!(ctx.managed_wallet.balance().locked(), COLLATERAL); + assert_eq!(ctx.managed_wallet.balance().spendable(), SPARE); +} + +#[test_case(false ; "a set amount")] +#[test_case(true ; "a drain")] +#[tokio::test] +async fn the_asset_lock_builder_skips_the_collateral(drain: bool) { + let (mut ctx, _collateral, spare) = registered_wallet(Some(SPARE)).await; + let credit = CreditOutputFunding { + output: TxOut { + value: DASH, + script_pubkey: elsewhere().assume_checked().script_pubkey(), + }, + funding_type: AssetLockFundingType::AssetLockAddressTopUp, + identity_index: 0, + }; + + let built = ctx + .managed_wallet + .build_asset_lock( + &ctx.wallet, + &[AccountTypePreference::BIP44], + 0, + vec![credit], + 1000, + drain, + ) + .await + .expect("the spare coin funds the asset lock"); + + assert_eq!(spent(&built.transaction), vec![spare.expect("spare coin")]); +} + +#[tokio::test] +async fn the_asset_lock_builder_has_nothing_to_lock_from_the_collateral_alone() { + let (mut ctx, _collateral, _) = registered_wallet(None).await; + let credit = CreditOutputFunding { + output: TxOut { + value: DASH, + script_pubkey: elsewhere().assume_checked().script_pubkey(), + }, + funding_type: AssetLockFundingType::AssetLockAddressTopUp, + identity_index: 0, + }; + + let built = ctx + .managed_wallet + .build_asset_lock(&ctx.wallet, &[AccountTypePreference::BIP44], 0, vec![credit], 1000, true) + .await; + + assert!( + matches!( + built, + Err(AssetLockError::Builder(BuilderError::CoinSelection( + SelectionError::NoUtxosAvailable + ))) + ), + "only the collateral is left, and it is locked" + ); +} + +/// A ProUpServTx placeholder: special transactions such as provider updates +/// fund their fee through `add_funding`. +fn provider_update_service() -> TransactionPayload { + TransactionPayload::ProviderUpdateServicePayloadType(ProviderUpdateServicePayload::new( + Some(0), + Txid::all_zeros(), + 0x00000000000000000000ffff7f000001, // 127.0.0.1 mapped + 19999, + ScriptBuf::new(), + InputsHash::all_zeros(), + None, + None, + None, + BLSSignature::from([0; 96]), + )) +} + +/// A copy of the collateral cloned before it was locked, or built by the +/// caller, still carries an unlocked flag. +fn stale_copy(ctx: &TestWalletContext, collateral: OutPoint) -> Utxo { + let mut stale = ctx.bip44_account().utxos[&collateral].clone(); + stale.is_locked = false; + stale +} + +#[tokio::test] +async fn special_transaction_funding_skips_the_collateral_even_when_seeded() { + let (mut ctx, collateral, spare) = registered_wallet(Some(SPARE)).await; + let stale = stale_copy(&ctx, collateral); + let account = ctx.wallet.accounts.standard_bip44_accounts.get(&0).expect("BIP44").clone(); + let funds = ctx.managed_wallet.accounts.standard_bip44_accounts.get_mut(&0).expect("BIP44"); + + let (tx, _fee, _reservation) = TransactionBuilder::new() + .set_current_height(TIP) + .set_fee_rate(FeeRate::normal()) + .add_inputs([stale]) + .add_funding(funds, &account) + .set_special_payload(provider_update_service()) + .build_unsigned_reserved() + .expect("the spare coin pays the fee"); + + assert_eq!(spent(&tx), vec![spare.expect("spare coin")]); +} + +/// The chunked drain path offers only what the caller seeds; a seeded copy of +/// a coin the account holds locked is dropped all the same. +#[tokio::test] +async fn reservation_only_funding_drops_a_seeded_collateral() { + let (mut ctx, collateral, _) = registered_wallet(None).await; + let stale = stale_copy(&ctx, collateral); + let account = ctx.wallet.accounts.standard_bip44_accounts.get(&0).expect("BIP44").clone(); + let funds = ctx.managed_wallet.accounts.standard_bip44_accounts.get_mut(&0).expect("BIP44"); + + let result = TransactionBuilder::new() + .set_current_height(TIP) + .set_selection_strategy(SelectionStrategy::All) + .add_inputs([stale]) + .add_funding_reservation_only(funds, &account) + .add_output(&elsewhere().assume_checked(), DASH) + .build_unsigned_reserved(); + + assert!(matches!(result, Err(BuilderError::CoinSelection(SelectionError::NoUtxosAvailable)))); +} + +#[cfg(feature = "serde")] +#[test] +fn locks_survive_a_serialization_round_trip() { + use crate::managed_account::ManagedCoreFundsAccount; + use crate::wallet::ManagedWalletInfo; + + let mut info = ManagedWalletInfo::dummy(1); + let mut account = ManagedCoreFundsAccount::dummy_bip44(); + let collateral = Utxo::dummy(1, COLLATERAL, 100, false, true); + let spare = Utxo::dummy(2, SPARE, 100, false, true); + account.utxos.insert(collateral.outpoint, collateral.clone()); + account.utxos.insert(spare.outpoint, spare.clone()); + info.accounts.insert(account).expect("account"); + // Locked before the coin arrives, as when a registration is seen first. + let arriving = Utxo::dummy(3, COLLATERAL, 100, false, true); + info.lock_outpoint(collateral.outpoint); + info.lock_outpoint(arriving.outpoint); + + let json = serde_json::to_string(&info).expect("serialize"); + let mut restored: ManagedWalletInfo = serde_json::from_str(&json).expect("deserialize"); + + assert_eq!(restored.locked_outpoints(), info.locked_outpoints()); + restored.update_last_processed_height(TIP); + let spendable: Vec = + restored.get_spendable_utxos().into_iter().map(|utxo| utxo.outpoint).collect(); + assert_eq!(spendable, vec![spare.outpoint]); + assert_eq!(restored.balance().locked(), COLLATERAL); + + // The lock taken before the coin arrived still applies after the reload. + let account = restored.first_bip44_managed_account_mut().expect("BIP44 account"); + account.utxos.insert(arriving.outpoint, arriving.clone()); + restored.update_balance(); + assert_eq!(restored.balance().locked(), 2 * COLLATERAL); + assert_eq!(restored.balance().spendable(), SPARE); +} + +/// A snapshot written before the lock set existed loads with no locks. +#[cfg(feature = "serde")] +#[test] +fn a_snapshot_without_locks_loads_with_none() { + use crate::wallet::ManagedWalletInfo; + + let mut info = ManagedWalletInfo::dummy(2); + info.lock_outpoint(OutPoint::new(Txid::from_byte_array([0x42; 32]), 0)); + let mut json = serde_json::to_value(&info).expect("serialize"); + json.as_object_mut().expect("object").remove("locked_outpoints").expect("the field"); + + let restored: ManagedWalletInfo = serde_json::from_value(json).expect("deserialize"); + + assert!(restored.locked_outpoints().is_empty()); +} diff --git a/key-wallet/src/tests/mod.rs b/key-wallet/src/tests/mod.rs index 0481a7a3b..ae12794d9 100644 --- a/key-wallet/src/tests/mod.rs +++ b/key-wallet/src/tests/mod.rs @@ -22,6 +22,8 @@ mod integration_tests; mod keep_finalized_transactions_tests; +mod locked_outpoints_tests; + mod managed_account_collection_tests; mod observed_spent_outpoints_tests; diff --git a/key-wallet/src/transaction_checking/account_checker.rs b/key-wallet/src/transaction_checking/account_checker.rs index 7b484c219..3ed845a16 100644 --- a/key-wallet/src/transaction_checking/account_checker.rs +++ b/key-wallet/src/transaction_checking/account_checker.rs @@ -98,6 +98,16 @@ pub struct TransactionCheckResult { /// [`WalletConflictSweep::released_outpoints`]: /// crate::wallet::managed_wallet_info::helpers::WalletConflictSweep::released_outpoints pub released_outpoints: Vec, + /// Outpoints this check added to the wallet's lock set: the collateral of + /// a ProRegTx, which coin selection now skips. Only new entries are + /// listed, so a ProRegTx seen again reports nothing. + /// + /// Filled whether or not the transaction is otherwise relevant: the + /// registration may involve nothing of this wallet's but the collateral, + /// or the collateral may not have arrived yet. A store that persists + /// wallet state records these; see + /// [`ManagedWalletInfo::locked_outpoints`](crate::wallet::ManagedWalletInfo::locked_outpoints). + pub locked_outpoints: Vec, } /// Enum representing the type of Core account that matched with embedded data @@ -458,6 +468,7 @@ impl ManagedAccountCollection { updated_records: Vec::new(), swept_transactions: Vec::new(), released_outpoints: Vec::new(), + locked_outpoints: Vec::new(), }; for account_type in account_types { diff --git a/key-wallet/src/transaction_checking/wallet_checker.rs b/key-wallet/src/transaction_checking/wallet_checker.rs index bb65e7bfb..a5f9d0ef7 100644 --- a/key-wallet/src/transaction_checking/wallet_checker.rs +++ b/key-wallet/src/transaction_checking/wallet_checker.rs @@ -41,6 +41,10 @@ pub trait WalletTransactionChecker { /// /// The context parameter indicates where the transaction comes from (mempool, block, etc.) /// + /// With `update_state`, a ProRegTx also locks the collateral it + /// registers, relevant or not, so coin selection skips it; new locks are + /// listed in [`TransactionCheckResult::locked_outpoints`]. See + /// [`ManagedWalletInfo::locked_outpoints`]. async fn check_core_transaction( &mut self, tx: &Transaction, @@ -268,6 +272,55 @@ impl WalletTransactionChecker for ManagedWalletInfo { wallet: &mut Wallet, update_state: bool, update_balance: bool, + ) -> TransactionCheckResult { + if !update_state { + return self + .check_core_transaction_inner(tx, context, wallet, update_state, update_balance) + .await; + } + + // Before the accounts record `tx`, so a collateral the ProRegTx + // creates itself is locked from the moment it becomes a coin. + let collateral = self.lock_masternode_collateral(tx); + + let mut result = self + .check_core_transaction_inner(tx, context, wallet, update_state, update_balance) + .await; + + // Bring the lock flags of the coins involved in line with the lock + // set: the coins `tx` pays this wallet, and a collateral the wallet + // already held. The balance refresh inside the check does this when it + // runs, but not every path reaches one: an otherwise irrelevant + // ProRegTx returns early, and block processing passes + // `update_balance = false` and refreshes once per block. + let txid = tx.txid(); + let outputs = (0..tx.output.len() as u32).map(|vout| OutPoint::new(txid, vout)); + let flags_changed = self.refresh_lock_flags(outputs.chain(collateral)); + + if let Some(collateral) = collateral { + result.locked_outpoints.push(collateral); + // The lock set is persisted wallet state. + result.state_modified = true; + } + if flags_changed && update_balance { + self.update_balance(); + } + + result + } +} + +impl ManagedWalletInfo { + /// Everything [`WalletTransactionChecker::check_core_transaction`] does + /// except keeping coin locks: the caller locks a ProRegTx's collateral and + /// refreshes the lock flags around it. + async fn check_core_transaction_inner( + &mut self, + tx: &Transaction, + context: TransactionContext, + wallet: &mut Wallet, + update_state: bool, + update_balance: bool, ) -> TransactionCheckResult { // Classify the transaction let tx_type = TransactionRouter::classify_transaction(tx); diff --git a/key-wallet/src/utxo.rs b/key-wallet/src/utxo.rs index 879813d08..14bc3876b 100644 --- a/key-wallet/src/utxo.rs +++ b/key-wallet/src/utxo.rs @@ -30,7 +30,12 @@ pub struct Utxo { pub is_confirmed: bool, /// Whether this UTXO has an InstantLock pub is_instantlocked: bool, - /// Whether this UTXO is locked (not available for spending) + /// Whether this UTXO is locked: coin selection skips it and its value + /// counts as locked balance. + /// + /// For a coin a wallet holds, the wallet sets this from its lock set, + /// [`ManagedWalletInfo::locked_outpoints`](crate::wallet::ManagedWalletInfo::locked_outpoints), + /// which is where such a coin is locked and unlocked. pub is_locked: bool, /// Whether this UTXO comes from a "trusted" mempool transaction — one we /// created ourselves, recognised because it spends at least one of our @@ -108,12 +113,21 @@ impl Utxo { } } - /// Lock this UTXO to prevent it from being selected + /// Lock this UTXO to prevent it from being selected. + /// + /// For a coin outside a wallet, such as one handed to a transaction + /// builder. A wallet overwrites the flag of a coin it holds from its lock + /// set: lock that coin with + /// [`ManagedWalletInfo::lock_outpoint`](crate::wallet::ManagedWalletInfo::lock_outpoint). pub fn lock(&mut self) { self.is_locked = true; } - /// Unlock this UTXO to allow it to be selected + /// Unlock this UTXO to allow it to be selected. + /// + /// For a coin outside a wallet, as with [`Self::lock`]. Unlock a coin a + /// wallet holds with + /// [`ManagedWalletInfo::unlock_outpoint`](crate::wallet::ManagedWalletInfo::unlock_outpoint). pub fn unlock(&mut self) { self.is_locked = false; } diff --git a/key-wallet/src/wallet/balance.rs b/key-wallet/src/wallet/balance.rs index 063700bfa..761daf1bf 100644 --- a/key-wallet/src/wallet/balance.rs +++ b/key-wallet/src/wallet/balance.rs @@ -23,7 +23,8 @@ pub struct WalletCoreBalance { unconfirmed: u64, /// Immature balance (UTXOs without enough confirmations for maturity, e.g. 100 for coinbase). immature: u64, - /// Locked balance (UTXOs reserved for specific purposes like CoinJoin). + /// Locked balance: coins the wallet will not spend, such as masternode + /// collateral (see `ManagedWalletInfo::locked_outpoints`). locked: u64, } diff --git a/key-wallet/src/wallet/managed_wallet_info/locked_outpoints.rs b/key-wallet/src/wallet/managed_wallet_info/locked_outpoints.rs new file mode 100644 index 000000000..8a5da617b --- /dev/null +++ b/key-wallet/src/wallet/managed_wallet_info/locked_outpoints.rs @@ -0,0 +1,255 @@ +//! Outpoints the wallet will not spend. +//! +//! The wallet keeps one set of locked outpoints, like Dash Core's +//! `setLockedCoins`, and coin selection never spends a coin in it. A ProRegTx +//! locks the collateral it registers; [`ManagedWalletInfo::lock_outpoint`] and +//! [`ManagedWalletInfo::unlock_outpoint`] lock and unlock anything by hand. See +//! [`ManagedWalletInfo::locked_outpoints`] for the full rules. + +use super::ManagedWalletInfo; +use crate::wallet::managed_wallet_info::wallet_info_interface::WalletInfoInterface; +use dashcore::blockdata::transaction::special_transaction::TransactionPayload; +use dashcore::hashes::Hash; +use dashcore::{OutPoint, Transaction, Txid}; +use std::collections::BTreeSet; + +/// The collateral `tx` registers when it is a ProRegTx, `None` otherwise. +/// +/// A null collateral txid means the ProRegTx creates its collateral itself, as +/// its own output at `collateralIndex`. An index past its outputs names no coin +/// (Core rejects such a registration), so it yields `None`. +pub(crate) fn masternode_collateral(tx: &Transaction) -> Option { + let Some(TransactionPayload::ProviderRegistrationPayloadType(registration)) = + &tx.special_transaction_payload + else { + return None; + }; + let named = registration.collateral_outpoint; + if named.txid != Txid::all_zeros() { + return Some(named); + } + ((named.vout as usize) < tx.output.len()).then(|| OutPoint::new(tx.txid(), named.vout)) +} + +impl ManagedWalletInfo { + /// The outpoints this wallet will not spend. + /// + /// Coin selection never picks a coin whose outpoint is in this set, for any + /// [`SelectionStrategy`](crate::wallet::managed_wallet_info::coin_selection::SelectionStrategy), + /// the `All` drain included, and such a coin counts toward + /// [`WalletCoreBalance::locked`](crate::WalletCoreBalance::locked) rather + /// than the spendable balance. + /// + /// # What locks an outpoint + /// + /// - A ProRegTx. The wallet locks the collateral of every masternode + /// registration it processes, so an ordinary send never spends it: + /// spending the collateral would end the registration. The collateral is + /// the ProRegTx's `collateralOutpoint`, or, when that names a null txid, + /// the ProRegTx's own output at `collateralIndex`. + /// - [`Self::lock_outpoint`]. + /// + /// Only [`Self::unlock_outpoint`] removes an outpoint. A coin's amount is + /// never a reason to lock it. + /// + /// # Order does not matter + /// + /// An entry does not need a coin behind it. A collateral seen after its + /// ProRegTx, or a coin locked before it arrives, arrives locked. A ProRegTx + /// naming a coin that is not this wallet's leaves an entry that never + /// matches anything. + /// + /// # How long a lock lasts + /// + /// Until [`Self::unlock_outpoint`]. Dash Core ties the collateral lock to + /// its masternode list: a ProUpRevTx leaves the masternode registered, so + /// the collateral stays locked; a later ProRegTx naming the same collateral + /// replaces the registration and keeps it locked; only spending the + /// collateral ends the registration. Core then drops the lock along with + /// the coin, and re-derives it from its masternode list whenever the coin + /// could come back (on load, and when the spend is abandoned). An SPV + /// wallet has no masternode list, so it keeps the entry instead: once the + /// coin is spent the entry has nothing to act on, and a coin whose spend is + /// reorged out or swept comes back locked. + /// + /// Processing a ProRegTx again (the block that confirms it, a rescan) locks + /// its collateral again, as Core does on load. + /// + /// # The set is the source of truth + /// + /// Coin selection works on [`Utxo`](crate::Utxo)s and skips a locked one + /// through [`Utxo::is_spendable`](crate::Utxo::is_spendable). The wallet + /// keeps the `is_locked` flag of every coin it holds equal to membership in + /// this set: when the coin arrives, when its outpoint is locked or + /// unlocked, and on every balance refresh. A flag written on a held coin + /// directly is overwritten by the next refresh. + /// + /// # Persistence + /// + /// The set is serialized with the wallet. A store that keeps wallet state + /// some other way persists this set instead: the outpoints a transaction + /// check locks arrive on + /// [`TransactionCheckResult::locked_outpoints`](crate::transaction_checking::TransactionCheckResult::locked_outpoints), + /// [`Self::lock_outpoint`] and [`Self::unlock_outpoint`] report their own + /// changes, and on load the store calls [`Self::lock_outpoint`] for each + /// persisted outpoint, before or after restoring the coins. + pub fn locked_outpoints(&self) -> &BTreeSet { + &self.locked_outpoints + } + + /// Whether `outpoint` is locked. See [`Self::locked_outpoints`]. + pub fn is_outpoint_locked(&self, outpoint: &OutPoint) -> bool { + self.locked_outpoints.contains(outpoint) + } + + /// Lock `outpoint`, so coin selection does not spend it until + /// [`Self::unlock_outpoint`]. See [`Self::locked_outpoints`]. + /// + /// The wallet does not need to hold the coin yet: it arrives locked. + /// Returns `true` when the outpoint was not locked before. When the wallet + /// holds the coin, its value moves to the locked balance. + pub fn lock_outpoint(&mut self, outpoint: OutPoint) -> bool { + if !self.locked_outpoints.insert(outpoint) { + return false; + } + if self.refresh_lock_flags([outpoint]) { + self.update_balance(); + } + true + } + + /// Unlock `outpoint`, so coin selection may spend it again. See + /// [`Self::locked_outpoints`]. + /// + /// Unlocking is never automatic, and a masternode collateral is unlocked + /// only here. Returns `true` when the outpoint was locked. When the wallet + /// holds the coin, its value moves back to the spendable balance. + pub fn unlock_outpoint(&mut self, outpoint: &OutPoint) -> bool { + if !self.locked_outpoints.remove(outpoint) { + return false; + } + if self.refresh_lock_flags([*outpoint]) { + self.update_balance(); + } + true + } + + /// Lock the collateral `tx` registers when it is a ProRegTx. + /// + /// Returns the collateral when it was not locked before. Only updates the + /// set: the caller refreshes the flags of the coins involved. + pub(crate) fn lock_masternode_collateral(&mut self, tx: &Transaction) -> Option { + let collateral = masternode_collateral(tx)?; + self.locked_outpoints.insert(collateral).then_some(collateral) + } + + /// Set the lock flag of each coin this wallet holds among `outpoints` to + /// its membership in the lock set. Returns whether any flag changed, which + /// means the balance buckets are stale. + pub(crate) fn refresh_lock_flags( + &mut self, + outpoints: impl IntoIterator, + ) -> bool { + let locked = &self.locked_outpoints; + let mut accounts = self.accounts.all_funding_accounts_mut(); + let mut changed = false; + for outpoint in outpoints { + let is_locked = locked.contains(&outpoint); + for account in accounts.iter_mut() { + if let Some(utxo) = account.utxos.get_mut(&outpoint) { + changed |= utxo.is_locked != is_locked; + utxo.is_locked = is_locked; + } + } + } + changed + } + + /// Set the lock flag of every coin this wallet holds to its membership in + /// the lock set. + /// + /// Run before every balance refresh, so coins inserted without going + /// through transaction checking (a store restoring its coins, say) pick up + /// their locks too. + pub(crate) fn refresh_all_lock_flags(&mut self) { + let locked = &self.locked_outpoints; + for account in self.accounts.all_funding_accounts_mut() { + for utxo in account.utxos.values_mut() { + utxo.is_locked = locked.contains(&utxo.outpoint); + } + } + } +} + +#[cfg(test)] +mod tests { + use super::masternode_collateral; + use dashcore::blockdata::transaction::special_transaction::provider_registration::{ + ProviderMasternodeType, ProviderRegistrationPayload, + }; + use dashcore::blockdata::transaction::special_transaction::TransactionPayload; + use dashcore::bls_sig_utils::BLSPublicKey; + use dashcore::hash_types::InputsHash; + use dashcore::hashes::Hash; + use dashcore::{Address, Network, OutPoint, PubkeyHash, ScriptBuf, Transaction, TxOut, Txid}; + + /// A ProRegTx naming `collateral`, with `outputs` outputs of its own. + fn registration(collateral: OutPoint, outputs: usize) -> Transaction { + let key_hash = PubkeyHash::from_byte_array([0x70; 20]); + Transaction { + version: 3, + lock_time: 0, + input: Vec::new(), + output: vec![ + TxOut { + value: 1_000, + script_pubkey: Address::dummy(Network::Testnet, 1).script_pubkey(), + }; + outputs + ], + special_transaction_payload: Some(TransactionPayload::ProviderRegistrationPayloadType( + ProviderRegistrationPayload { + version: 1, + masternode_type: ProviderMasternodeType::Regular, + masternode_mode: 0, + collateral_outpoint: collateral, + service_address: "127.0.0.1:19999".parse().expect("socket address"), + owner_key_hash: key_hash, + operator_public_key: BLSPublicKey::from([0x11; 48]), + voting_key_hash: key_hash, + operator_reward: 0, + script_payout: ScriptBuf::new(), + inputs_hash: InputsHash::all_zeros(), + signature: vec![0x33; 65], + platform_node_id: None, + platform_p2p_port: None, + platform_http_port: None, + }, + )), + } + } + + #[test] + fn an_external_collateral_is_the_outpoint_the_registration_names() { + let named = OutPoint::new(Txid::from_byte_array([0x19; 32]), 3); + assert_eq!(masternode_collateral(®istration(named, 1)), Some(named)); + } + + #[test] + fn a_null_collateral_txid_names_the_registrations_own_output() { + let tx = registration(OutPoint::new(Txid::all_zeros(), 1), 2); + assert_eq!(masternode_collateral(&tx), Some(OutPoint::new(tx.txid(), 1))); + } + + #[test] + fn an_own_output_index_past_the_outputs_names_no_coin() { + let tx = registration(OutPoint::new(Txid::all_zeros(), 2), 2); + assert_eq!(masternode_collateral(&tx), None); + } + + #[test] + fn only_a_registration_has_a_collateral() { + let address = Address::dummy(Network::Testnet, 1); + assert_eq!(masternode_collateral(&Transaction::dummy(&address, 0..1, &[1_000])), None); + } +} diff --git a/key-wallet/src/wallet/managed_wallet_info/mod.rs b/key-wallet/src/wallet/managed_wallet_info/mod.rs index 523fd3e23..2fe34f986 100644 --- a/key-wallet/src/wallet/managed_wallet_info/mod.rs +++ b/key-wallet/src/wallet/managed_wallet_info/mod.rs @@ -8,6 +8,7 @@ pub mod coin_selection; pub mod fee; pub mod helpers; pub use helpers::AbandonOutcome; +mod locked_outpoints; pub mod managed_account_operations; pub mod managed_accounts; pub mod transaction_builder; @@ -148,6 +149,16 @@ pub struct ManagedWalletInfo { pub(crate) account_generation: u64, #[cfg_attr(feature = "serde", serde(skip))] pub(crate) noted_chain_lock_height: Option, + /// Outpoints the wallet will not spend: masternode collateral, and + /// anything locked by hand. The source of truth for coin locks; see + /// [`Self::locked_outpoints`] for the rules. + /// + /// `#[serde(default)]` loads a snapshot written before this field existed + /// with no locks, in self-describing formats (e.g. JSON). As with + /// `observed_spent_outpoints`, non-self-describing serde formats cannot + /// default a missing field. + #[cfg_attr(feature = "serde", serde(default))] + pub(crate) locked_outpoints: BTreeSet, } /// Serde adapter for [`ManagedWalletInfo::observed_spent_outpoints`] that @@ -255,6 +266,7 @@ impl ManagedWalletInfo { spent_claims: BTreeMap::new(), account_generation: 0, noted_chain_lock_height: None, + locked_outpoints: BTreeSet::new(), } } @@ -273,6 +285,7 @@ impl ManagedWalletInfo { spent_claims: BTreeMap::new(), account_generation: 0, noted_chain_lock_height: None, + locked_outpoints: BTreeSet::new(), } } @@ -301,6 +314,7 @@ impl ManagedWalletInfo { spent_claims: BTreeMap::new(), account_generation: 0, noted_chain_lock_height: None, + locked_outpoints: BTreeSet::new(), } } diff --git a/key-wallet/src/wallet/managed_wallet_info/transaction_builder.rs b/key-wallet/src/wallet/managed_wallet_info/transaction_builder.rs index 7465b6bdd..56743924f 100644 --- a/key-wallet/src/wallet/managed_wallet_info/transaction_builder.rs +++ b/key-wallet/src/wallet/managed_wallet_info/transaction_builder.rs @@ -142,7 +142,9 @@ impl TransactionBuilder { } /// Add a funding account's spendable UTXOs to the candidate input set, - /// skipping any already reserved by another in-flight build. + /// skipping any already reserved by another in-flight build and any the + /// wallet has locked (see + /// [`ManagedWalletInfo::locked_outpoints`](crate::wallet::ManagedWalletInfo::locked_outpoints)). /// /// Call it once per funding account: coin selection then draws from the /// union of their UTXOs, and the first account supplies the change @@ -177,8 +179,9 @@ impl TransactionBuilder { /// does. /// /// Reservation bookkeeping is unchanged: `owned` still covers every - /// unreserved UTXO of the account, so whichever seeded outpoints selection - /// picks are reserved by the account that holds them. + /// unreserved, unlocked UTXO of the account, so whichever seeded outpoints + /// selection picks are reserved by the account that holds them. A seeded + /// outpoint the account holds locked is dropped, as with `add_funding`. pub fn add_funding_reservation_only( self, funds_acc: &mut ManagedCoreFundsAccount, @@ -210,10 +213,19 @@ impl TransactionBuilder { // here would leave a pre-seeded input unreserved and free for a // concurrent build to select. let mut owned: HashSet = HashSet::new(); + // Coins the wallet has locked, such as masternode collateral. Never a + // candidate, and a copy seeded by `add_inputs` is dropped below: a + // caller-built `Utxo` carries whatever lock flag it was cloned with, + // while this account's own coin carries the current one. + let mut locked: HashSet = HashSet::new(); for utxo in funds_acc.utxos.values() { if reserved.contains(&utxo.outpoint) { continue; } + if utxo.is_locked { + locked.insert(utxo.outpoint); + continue; + } owned.insert(utxo.outpoint); if present.contains(&utxo.outpoint) { continue; @@ -223,6 +235,9 @@ impl TransactionBuilder { } } self.funding.push((funds_acc.reservations().clone(), owned)); + if !locked.is_empty() { + self.inputs.retain(|utxo| !locked.contains(&utxo.outpoint)); + } self.inputs.extend(candidates); if self.change_addr.is_none() { self.change_addr = funds_acc.next_change_address(Some(&acc.account_xpub), true).ok(); diff --git a/key-wallet/src/wallet/managed_wallet_info/wallet_info_interface.rs b/key-wallet/src/wallet/managed_wallet_info/wallet_info_interface.rs index b2a92648c..1af236928 100644 --- a/key-wallet/src/wallet/managed_wallet_info/wallet_info_interface.rs +++ b/key-wallet/src/wallet/managed_wallet_info/wallet_info_interface.rs @@ -131,7 +131,8 @@ pub trait WalletInfoInterface: Sized + WalletTransactionChecker + ManagedAccount /// Get all UTXOs for the wallet fn utxos(&self) -> BTreeSet<&Utxo>; - /// Get spendable UTXOs (confirmed and not locked) + /// Get spendable UTXOs: mature and not locked (see + /// [`ManagedWalletInfo::locked_outpoints`]). fn get_spendable_utxos(&self) -> BTreeSet<&Utxo>; /// Get the wallet balance @@ -506,6 +507,10 @@ impl WalletInfoInterface for ManagedWalletInfo { } fn update_balance(&mut self) { + // The locked bucket is read from each coin's lock flag, which follows + // the wallet's lock set; bring every flag up to date first. + self.refresh_all_lock_flags(); + // Only funds-bearing accounts contribute to the wallet balance. let mut balance = WalletCoreBalance::default(); let last_processed_height = self.last_processed_height(); From da7a162f35ed086045e911318f737a7652ab171d Mon Sep 17 00:00:00 2001 From: Quantum Explorer Date: Tue, 29 Sep 2026 01:50:42 +0700 Subject: [PATCH 02/13] fix(key-wallet): lock external collateral only from a block External collateral is locked only once its ProRegTx is in a block (InBlock or InChainLockedBlock). Until then the ProRegTx is not a registration: the network may never accept it, and the wallet does not check its payload itself. An InstantSend context counts as unconfirmed, since the wallet does not verify InstantSend locks and cannot tell whether its caller did. A ProRegTx first seen in the mempool locks the collateral it names at the block that confirms it, and the collateral may still arrive before or after that block. Dash Core likewise locks such a collateral once a block adds the registration to its masternode list. A collateral the ProRegTx creates itself (a null collateral txid) is still locked from any sighting, mempool included, as the coin arrives: it is the ProRegTx's own output. An unconfirmed sighting does not lock that output again once the wallet holds it; a block does. A lock refreshes the balance. `CheckTransactionsResult` lists each wallet's new locks in `per_wallet_locked_outpoints`, relevant or not, and the mempool path refreshes those wallets' balances as well as the affected ones. Off-chain, a lock can only land on a coin arriving with the ProRegTx, so `TransactionDetected` carries it in the locked balance; in a block, `BlockProcessed` carries it. Co-Authored-By: Claude Opus 5.5 (cherry picked from commit 16c1795f1049a163b01dfe7fea90fde6e7a7be8a) --- key-wallet-manager/src/event_tests.rs | 193 +++++++++++++++++- key-wallet-manager/src/lib.rs | 17 ++ key-wallet-manager/src/process_block.rs | 14 +- .../src/tests/locked_outpoints_tests.rs | 106 ++++++++++ .../transaction_checking/account_checker.rs | 10 +- .../transaction_checking/wallet_checker.rs | 11 +- .../managed_wallet_info/locked_outpoints.rs | 69 ++++++- 7 files changed, 395 insertions(+), 25 deletions(-) diff --git a/key-wallet-manager/src/event_tests.rs b/key-wallet-manager/src/event_tests.rs index 59321b177..fd89a58e9 100644 --- a/key-wallet-manager/src/event_tests.rs +++ b/key-wallet-manager/src/event_tests.rs @@ -4,24 +4,28 @@ use crate::wallet_interface::WalletInterface; use dashcore::block::{Block, Header, Version}; use dashcore::blockdata::script::Builder; use dashcore::blockdata::transaction::special_transaction::asset_lock::AssetLockPayload; +use dashcore::blockdata::transaction::special_transaction::provider_registration::{ + ProviderMasternodeType, ProviderRegistrationPayload, +}; use dashcore::blockdata::transaction::special_transaction::TransactionPayload; -use dashcore::bls_sig_utils::BLSSignature; +use dashcore::bls_sig_utils::{BLSPublicKey, BLSSignature}; use dashcore::ephemerealdata::chain_lock::ChainLock; use dashcore::ephemerealdata::instant_lock::InstantLock; -use dashcore::hash_types::CycleHash; +use dashcore::hash_types::{CycleHash, InputsHash}; +use dashcore::hashes::Hash; use dashcore::opcodes; use dashcore::{ - BlockHash, CompactTarget, OutPoint, PublicKey, ScriptBuf, TxIn, TxMerkleNode, TxOut, Txid, - Witness, + BlockHash, CompactTarget, OutPoint, PubkeyHash, PublicKey, ScriptBuf, TxIn, TxMerkleNode, + TxOut, Txid, Witness, }; use key_wallet::account::StandardAccountType; use key_wallet::managed_account::address_pool::{AddressPoolType, PublicKeyType}; use key_wallet::managed_account::managed_account_trait::ManagedAccountTrait; use key_wallet::managed_account::managed_account_type::ManagedAccountType; -use key_wallet::transaction_checking::{TransactionRouter, TransactionType}; +use key_wallet::transaction_checking::{BlockInfo, TransactionRouter, TransactionType}; use key_wallet::wallet::managed_wallet_info::transaction_building::AccountTypePreference; use key_wallet::AccountType; -use std::collections::BTreeSet; +use std::collections::{BTreeMap, BTreeSet}; fn make_block(txdata: Vec, seed: u8, time: u32) -> Block { Block { @@ -1365,6 +1369,183 @@ async fn test_update_wallet_synced_height_does_not_re_emit_when_unchanged() { ); } +// --------------------------------------------------------------------------- +// Masternode collateral locks +// --------------------------------------------------------------------------- + +/// A ProRegTx registering `collateral` and paying `outputs`. Its fee input and +/// keys belong to no one the test wallet knows; `seed` varies the txid. +fn masternode_registration(collateral: OutPoint, outputs: Vec, seed: u8) -> Transaction { + let key_hash = PubkeyHash::from_byte_array([0x70; 20]); + Transaction { + version: 3, + lock_time: 0, + input: vec![TxIn { + previous_output: OutPoint::new(Txid::from_byte_array([seed; 32]), 0), + ..Default::default() + }], + output: outputs, + special_transaction_payload: Some(TransactionPayload::ProviderRegistrationPayloadType( + ProviderRegistrationPayload { + version: 1, + masternode_type: ProviderMasternodeType::Regular, + masternode_mode: 0, + collateral_outpoint: collateral, + service_address: "127.0.0.1:19999".parse().expect("socket address"), + owner_key_hash: key_hash, + operator_public_key: BLSPublicKey::from([0x11; 48]), + voting_key_hash: key_hash, + operator_reward: 0, + script_payout: ScriptBuf::new(), + inputs_hash: InputsHash::all_zeros(), + signature: vec![0x33; 65], + platform_node_id: None, + platform_p2p_port: None, + platform_http_port: None, + }, + )), + } +} + +fn bip44_account_0() -> AccountType { + AccountType::Standard { + index: 0, + standard_account_type: StandardAccountType::BIP44Account, + } +} + +/// A wallet holding one coin of `TX_AMOUNT`, mined at height 100. +async fn manager_holding_a_coin() -> (WalletManager, WalletId, OutPoint) { + let (mut manager, wallet_id, addr) = setup_manager_with_wallet(); + let funding = create_tx_paying_to(&addr, 0xc0); + let block = make_block(vec![funding.clone()], 0xc0, 1_000); + manager + .process_block_for_wallets(&block, block.block_hash(), 100, &BTreeSet::from([wallet_id])) + .await; + (manager, wallet_id, OutPoint::new(funding.txid(), 0)) +} + +/// A ProRegTx locks a collateral it names at the block that holds it, not +/// from the mempool. The mempool sighting changes nothing and emits nothing; +/// the block's `BlockProcessed` carries the coin in the locked balance. +#[tokio::test] +async fn test_registration_locks_a_named_collateral_at_its_block_not_from_the_mempool() { + let (mut manager, wallet_id, collateral) = manager_holding_a_coin().await; + let registration = masternode_registration(collateral, vec![], 0xc1); + let mut rx = manager.subscribe_events(); + + let result = manager.process_mempool_transaction(®istration, None).await; + + assert!(!result.is_relevant); + assert_no_events(&mut rx); + let info = manager.get_wallet_info(&wallet_id).expect("wallet info"); + assert!(!info.is_outpoint_locked(&collateral)); + assert_eq!(info.balance().spendable(), TX_AMOUNT); + assert_eq!(info.balance().locked(), 0); + + let block = make_block(vec![registration], 0xc1, 1_001); + manager + .process_block_for_wallets(&block, block.block_hash(), 101, &BTreeSet::from([wallet_id])) + .await; + + assert!(manager + .get_wallet_info(&wallet_id) + .expect("wallet info") + .is_outpoint_locked(&collateral)); + let events = drain_events(&mut rx); + assert_eq!(events.len(), 1, "one BlockProcessed expected, got {:?}", events); + match &events[0] { + WalletEvent::BlockProcessed { + inserted, + updated, + balance, + account_balances, + .. + } => { + assert!(inserted.is_empty() && updated.is_empty(), "the ProRegTx records nothing"); + assert_eq!(balance.locked(), TX_AMOUNT); + assert_eq!(balance.spendable(), 0); + let account = account_balances.get(&bip44_account_0()).expect("the coin's account"); + assert_eq!(account.locked(), TX_AMOUNT); + } + other => panic!("expected BlockProcessed, got {:?}", other), + } +} + +/// An InstantSend lock does not make a ProRegTx a registration: the coin it +/// names stays spendable until a block holds the ProRegTx. +#[tokio::test] +async fn test_instant_locked_registration_locks_no_collateral_it_names() { + let (mut manager, wallet_id, collateral) = manager_holding_a_coin().await; + let registration = masternode_registration(collateral, vec![], 0xc2); + let mut rx = manager.subscribe_events(); + + manager + .process_mempool_transaction(®istration, Some(dummy_instant_lock(registration.txid()))) + .await; + + assert_no_events(&mut rx); + let info = manager.get_wallet_info(&wallet_id).expect("wallet info"); + assert!(!info.is_outpoint_locked(&collateral)); + assert_eq!(info.balance().spendable(), TX_AMOUNT); + assert_eq!(info.balance().locked(), 0); +} + +/// A ProRegTx that creates its collateral locks it from the mempool, and the +/// `TransactionDetected` for the coin carries it in the locked balance. +#[tokio::test] +async fn test_mempool_registration_creating_its_collateral_emits_the_locked_balance() { + let (mut manager, wallet_id, addr) = setup_manager_with_wallet(); + let to_wallet = TxOut { + value: TX_AMOUNT, + script_pubkey: addr.script_pubkey(), + }; + // A null collateral txid: the collateral is this ProRegTx's output 0. + let registration = + masternode_registration(OutPoint::new(Txid::all_zeros(), 0), vec![to_wallet], 0xc3); + let collateral = OutPoint::new(registration.txid(), 0); + let mut rx = manager.subscribe_events(); + + let result = manager.process_mempool_transaction(®istration, None).await; + + assert!(result.is_relevant); + let events = drain_events(&mut rx); + assert_eq!(events.len(), 1, "one TransactionDetected expected, got {:?}", events); + match &events[0] { + WalletEvent::TransactionDetected { + record, + balance, + account_balances, + .. + } => { + assert_eq!(record.txid, registration.txid()); + assert_eq!(balance.locked(), TX_AMOUNT); + assert_eq!(balance.spendable(), 0, "the collateral is not spendable balance"); + let account = account_balances.get(&bip44_account_0()).expect("the coin's account"); + assert_eq!(account.locked(), TX_AMOUNT); + } + other => panic!("expected TransactionDetected, got {:?}", other), + } + let info = manager.get_wallet_info(&wallet_id).expect("wallet info"); + assert!(info.is_outpoint_locked(&collateral)); + assert_eq!(info.balance().locked(), TX_AMOUNT); +} + +/// A check reports the locks it took per wallet, including for a wallet the +/// transaction is otherwise irrelevant to, so a caller that checks with +/// `update_balance = false` knows which balances to refresh. +#[tokio::test] +async fn test_check_transaction_reports_a_lock_for_a_wallet_it_is_otherwise_irrelevant_to() { + let (mut manager, wallet_id, collateral) = manager_holding_a_coin().await; + let registration = masternode_registration(collateral, vec![], 0xc4); + let mined = TransactionContext::InBlock(BlockInfo::new(101, BlockHash::all_zeros(), 1_001)); + + let result = manager.check_transaction_in_all_wallets(®istration, mined, true, false).await; + + assert!(result.affected_wallets.is_empty()); + assert_eq!(result.per_wallet_locked_outpoints, BTreeMap::from([(wallet_id, vec![collateral])])); +} + // --------------------------------------------------------------------------- // Dry run and irrelevant paths // --------------------------------------------------------------------------- diff --git a/key-wallet-manager/src/lib.rs b/key-wallet-manager/src/lib.rs index 13b6405d8..43c96186d 100644 --- a/key-wallet-manager/src/lib.rs +++ b/key-wallet-manager/src/lib.rs @@ -111,6 +111,15 @@ pub struct CheckTransactionsResult { /// see [`crate::events::WalletEvent::TransactionsSwept`] for why a /// consumer needs this set named explicitly instead of re-deriving it. pub per_wallet_released_outpoints: BTreeMap>, + /// Outpoints this check added to each wallet's lock set, grouped by + /// wallet: the collateral of a ProRegTx (see + /// [`ManagedWalletInfo::locked_outpoints`]). Gathered whether or not the + /// transaction is relevant to the wallet, since a ProRegTx in a block + /// locks a coin the wallet holds even when nothing else ties it to the + /// wallet. A lock moves that coin from the spendable to the locked + /// balance, so a caller that checked with `update_balance = false` + /// refreshes these wallets as well as the affected ones. + pub per_wallet_locked_outpoints: BTreeMap>, } impl CheckTransactionsResult { @@ -664,6 +673,14 @@ impl WalletManager { .extend(check_result.released_outpoints); } + if !check_result.locked_outpoints.is_empty() { + result + .per_wallet_locked_outpoints + .entry(*wallet_id) + .or_default() + .extend(check_result.locked_outpoints); + } + if !check_result.new_addresses.is_empty() { result .new_addresses diff --git a/key-wallet-manager/src/process_block.rs b/key-wallet-manager/src/process_block.rs index ed6459010..4e0cdc924 100644 --- a/key-wallet-manager/src/process_block.rs +++ b/key-wallet-manager/src/process_block.rs @@ -221,11 +221,23 @@ impl WalletInterface for WalletM // changed. The cached `.balance` field is stale until // `update_balance()` runs, so the pre-snapshot taken here captures // the pre-transaction state. + // + // A wallet whose lock set this check grew is refreshed too, relevant + // or not, since a lock moves a held coin to the locked balance. + // Off-chain only a ProRegTx's own output locks, and only as that coin + // arrives, so the lock rides the `TransactionDetected` of the wallet + // the ProRegTx pays. + let refreshed: BTreeSet = check_result + .affected_wallets + .iter() + .chain(check_result.per_wallet_locked_outpoints.keys()) + .copied() + .collect(); let mut per_wallet_account_diff: BTreeMap< WalletId, BTreeMap, > = BTreeMap::new(); - for wallet_id in &check_result.affected_wallets { + for wallet_id in &refreshed { if let Some(info) = self.wallet_infos.get_mut(wallet_id) { let prior = info.account_balances(); info.update_balance(); diff --git a/key-wallet/src/tests/locked_outpoints_tests.rs b/key-wallet/src/tests/locked_outpoints_tests.rs index 4bd2d294c..53cca5cee 100644 --- a/key-wallet/src/tests/locked_outpoints_tests.rs +++ b/key-wallet/src/tests/locked_outpoints_tests.rs @@ -12,6 +12,7 @@ use dashcore::blockdata::transaction::special_transaction::provider_update_revoc use dashcore::blockdata::transaction::special_transaction::provider_update_service::ProviderUpdateServicePayload; use dashcore::blockdata::transaction::special_transaction::TransactionPayload; use dashcore::bls_sig_utils::{BLSPublicKey, BLSSignature}; +use dashcore::ephemerealdata::instant_lock::InstantLock; use dashcore::hash_types::InputsHash; use dashcore::hashes::Hash; use dashcore::{ @@ -44,6 +45,27 @@ fn block(height: u32) -> TransactionContext { )) } +fn chain_locked_block(height: u32) -> TransactionContext { + TransactionContext::InChainLockedBlock(BlockInfo::new( + height, + BlockHash::from_byte_array([height as u8; 32]), + 1_700_000_000 + height, + )) +} + +/// Seen in the mempool, without an InstantSend lock. +fn in_mempool(_tx: &Transaction) -> TransactionContext { + TransactionContext::Mempool +} + +/// Seen in the mempool with an InstantSend lock. +fn instant_locked(tx: &Transaction) -> TransactionContext { + TransactionContext::InstantSend(InstantLock { + txid: tx.txid(), + ..InstantLock::default() + }) +} + /// An address that is not the wallet's. fn elsewhere() -> Address { Address::from_str("yTb47qEBpNmgXvYYsHEN4nh8yJwa5iC4Cs").expect("testnet address") @@ -226,6 +248,8 @@ async fn a_registration_locks_its_external_collateral_whichever_arrives_first( } #[test_case(&[TransactionContext::Mempool, block(101)] ; "seen in the mempool, then mined")] +#[test_case(&[TransactionContext::Mempool] ; "seen only in the mempool")] +#[test_case(&[TransactionContext::InstantSend(InstantLock::default())] ; "seen instant send locked")] #[test_case(&[block(101)] ; "first seen mined")] #[tokio::test] async fn a_registration_locks_the_collateral_it_creates(sightings: &[TransactionContext]) { @@ -260,6 +284,88 @@ async fn a_registration_locks_the_collateral_it_creates(sightings: &[Transaction assert!(is_out_of_coins(send(&mut ctx, DASH, SelectionStrategy::LargestFirst))); } +/// A ProRegTx that is not in a block is not a registration yet, so the coin +/// it names stays spendable. An InstantSend lock does not change that. +#[test_case(in_mempool ; "in the mempool")] +#[test_case(instant_locked ; "instant send locked")] +#[tokio::test] +async fn an_unconfirmed_registration_leaves_the_collateral_it_names_unlocked( + sighting: fn(&Transaction) -> TransactionContext, +) { + let mut ctx = TestWalletContext::new_random(); + let collateral = receive(&mut ctx, COLLATERAL, 0x01, 100).await; + ctx.managed_wallet.update_last_processed_height(TIP); + let registration = registration(collateral, vec![], 0xEE); + + let result = ctx.check_transaction(®istration, sighting(®istration)).await; + + assert!(result.locked_outpoints.is_empty()); + assert!(!result.state_modified, "nothing changed"); + assert!(!ctx.managed_wallet.is_outpoint_locked(&collateral)); + assert!(!ctx.bip44_account().utxos[&collateral].is_locked); + assert_eq!(ctx.managed_wallet.balance().spendable(), COLLATERAL); + assert_eq!(ctx.managed_wallet.balance().locked(), 0); + let tx = send(&mut ctx, DASH, SelectionStrategy::LargestFirst).expect("the coin is spendable"); + assert_eq!(spent(&tx), vec![collateral]); +} + +/// The block that confirms a ProRegTx first seen unconfirmed locks the +/// collateral it names. +#[test_case(in_mempool, block(101) ; "mempool, then a block")] +#[test_case(in_mempool, chain_locked_block(101) ; "mempool, then a chainlocked block")] +#[test_case(instant_locked, block(101) ; "instant send, then a block")] +#[tokio::test] +async fn the_block_holding_a_registration_first_seen_unconfirmed_locks_its_collateral( + first: fn(&Transaction) -> TransactionContext, + mined: TransactionContext, +) { + let mut ctx = TestWalletContext::new_random(); + let collateral = receive(&mut ctx, COLLATERAL, 0x01, 100).await; + let registration = registration(collateral, vec![], 0xEE); + let unconfirmed = ctx.check_transaction(®istration, first(®istration)).await; + assert!(unconfirmed.locked_outpoints.is_empty()); + + let result = ctx.check_transaction(®istration, mined).await; + + assert_eq!(result.locked_outpoints, vec![collateral]); + assert!(result.state_modified, "the lock set is persisted state"); + assert!(ctx.bip44_account().utxos[&collateral].is_locked); + assert_eq!(ctx.managed_wallet.balance().locked(), COLLATERAL); + ctx.managed_wallet.update_last_processed_height(TIP); + assert!(is_out_of_coins(send(&mut ctx, DASH, SelectionStrategy::LargestFirst))); +} + +/// An unconfirmed sighting locks the collateral a ProRegTx creates as that +/// coin arrives, not again once the wallet holds it: an unlock stays until a +/// block holding the ProRegTx locks the coin again. +#[test_case(in_mempool ; "in the mempool")] +#[test_case(instant_locked ; "instant send locked")] +#[tokio::test] +async fn an_unconfirmed_sighting_does_not_relock_a_created_collateral_after_an_unlock( + sighting: fn(&Transaction) -> TransactionContext, +) { + let mut ctx = TestWalletContext::new_random(); + let to_wallet = TxOut { + value: COLLATERAL, + script_pubkey: ctx.receive_address.script_pubkey(), + }; + let registration = registration(OutPoint::new(Txid::all_zeros(), 0), vec![to_wallet], 0xEE); + let collateral = OutPoint::new(registration.txid(), 0); + let first = ctx.check_transaction(®istration, TransactionContext::Mempool).await; + assert_eq!(first.locked_outpoints, vec![collateral]); + assert!(ctx.managed_wallet.unlock_outpoint(&collateral)); + + let again = ctx.check_transaction(®istration, sighting(®istration)).await; + + assert!(again.locked_outpoints.is_empty()); + assert!(!ctx.managed_wallet.is_outpoint_locked(&collateral)); + assert_eq!(ctx.managed_wallet.balance().locked(), 0); + + let mined = ctx.check_transaction(®istration, block(101)).await; + assert_eq!(mined.locked_outpoints, vec![collateral]); + assert_eq!(ctx.managed_wallet.balance().locked(), COLLATERAL); +} + #[tokio::test] async fn unlocking_lets_a_send_spend_the_collateral_and_relocking_stops_it_again() { let (mut ctx, collateral, _) = registered_wallet(None).await; diff --git a/key-wallet/src/transaction_checking/account_checker.rs b/key-wallet/src/transaction_checking/account_checker.rs index 3ed845a16..3427c5975 100644 --- a/key-wallet/src/transaction_checking/account_checker.rs +++ b/key-wallet/src/transaction_checking/account_checker.rs @@ -100,13 +100,17 @@ pub struct TransactionCheckResult { pub released_outpoints: Vec, /// Outpoints this check added to the wallet's lock set: the collateral of /// a ProRegTx, which coin selection now skips. Only new entries are - /// listed, so a ProRegTx seen again reports nothing. + /// listed, so a ProRegTx seen again reports nothing. A collateral the + /// ProRegTx names is locked only in a block context; see + /// [`ManagedWalletInfo::locked_outpoints`](crate::wallet::ManagedWalletInfo::locked_outpoints). /// /// Filled whether or not the transaction is otherwise relevant: the /// registration may involve nothing of this wallet's but the collateral, /// or the collateral may not have arrived yet. A store that persists - /// wallet state records these; see - /// [`ManagedWalletInfo::locked_outpoints`](crate::wallet::ManagedWalletInfo::locked_outpoints). + /// wallet state records these. A lock moves a coin the wallet holds from + /// the spendable to the locked balance, so a caller that checked with + /// `update_balance = false` refreshes the balance of a wallet whose check + /// lists any, as it does for a relevant transaction. pub locked_outpoints: Vec, } diff --git a/key-wallet/src/transaction_checking/wallet_checker.rs b/key-wallet/src/transaction_checking/wallet_checker.rs index a5f9d0ef7..c2c2aa08b 100644 --- a/key-wallet/src/transaction_checking/wallet_checker.rs +++ b/key-wallet/src/transaction_checking/wallet_checker.rs @@ -42,9 +42,12 @@ pub trait WalletTransactionChecker { /// The context parameter indicates where the transaction comes from (mempool, block, etc.) /// /// With `update_state`, a ProRegTx also locks the collateral it - /// registers, relevant or not, so coin selection skips it; new locks are - /// listed in [`TransactionCheckResult::locked_outpoints`]. See - /// [`ManagedWalletInfo::locked_outpoints`]. + /// registers, relevant or not, so coin selection skips it: a collateral it + /// names once the ProRegTx is in a block, its own output from any context. + /// New locks are listed in [`TransactionCheckResult::locked_outpoints`]; + /// with `update_balance = false`, refresh the balance of a wallet whose + /// check lists any, since a lock moves a held coin to the locked balance. + /// See [`ManagedWalletInfo::locked_outpoints`]. async fn check_core_transaction( &mut self, tx: &Transaction, @@ -281,7 +284,7 @@ impl WalletTransactionChecker for ManagedWalletInfo { // Before the accounts record `tx`, so a collateral the ProRegTx // creates itself is locked from the moment it becomes a coin. - let collateral = self.lock_masternode_collateral(tx); + let collateral = self.lock_masternode_collateral(tx, &context); let mut result = self .check_core_transaction_inner(tx, context, wallet, update_state, update_balance) diff --git a/key-wallet/src/wallet/managed_wallet_info/locked_outpoints.rs b/key-wallet/src/wallet/managed_wallet_info/locked_outpoints.rs index 8a5da617b..9f5eda217 100644 --- a/key-wallet/src/wallet/managed_wallet_info/locked_outpoints.rs +++ b/key-wallet/src/wallet/managed_wallet_info/locked_outpoints.rs @@ -7,6 +7,7 @@ //! [`ManagedWalletInfo::locked_outpoints`] for the full rules. use super::ManagedWalletInfo; +use crate::transaction_checking::TransactionContext; use crate::wallet::managed_wallet_info::wallet_info_interface::WalletInfoInterface; use dashcore::blockdata::transaction::special_transaction::TransactionPayload; use dashcore::hashes::Hash; @@ -42,11 +43,26 @@ impl ManagedWalletInfo { /// /// # What locks an outpoint /// - /// - A ProRegTx. The wallet locks the collateral of every masternode - /// registration it processes, so an ordinary send never spends it: + /// - A ProRegTx. The wallet locks the collateral of the masternode + /// registrations it processes, so an ordinary send never spends it: /// spending the collateral would end the registration. The collateral is /// the ProRegTx's `collateralOutpoint`, or, when that names a null txid, - /// the ProRegTx's own output at `collateralIndex`. + /// the ProRegTx's own output at `collateralIndex`. When it is locked + /// depends on which: + /// - A collateral the ProRegTx names is locked once the ProRegTx is in a + /// block ([`TransactionContext::InBlock`] or + /// [`TransactionContext::InChainLockedBlock`]). Until then it is not a + /// registration: the network may never accept it, and the wallet does + /// not check a ProRegTx's payload itself. Dash Core likewise locks such + /// a collateral once a block adds the registration to its masternode + /// list. An [`TransactionContext::InstantSend`] context counts as + /// unconfirmed here: the wallet does not verify InstantSend locks, and + /// cannot tell whether its caller did. + /// - A collateral the ProRegTx creates is locked from its first + /// sighting, mempool included, as the coin arrives: it is the + /// ProRegTx's own output, so the lock can hold no other coin. An + /// unconfirmed sighting does not lock that output again once the + /// wallet holds it; a block does. /// - [`Self::lock_outpoint`]. /// /// Only [`Self::unlock_outpoint`] removes an outpoint. A coin's amount is @@ -54,10 +70,10 @@ impl ManagedWalletInfo { /// /// # Order does not matter /// - /// An entry does not need a coin behind it. A collateral seen after its - /// ProRegTx, or a coin locked before it arrives, arrives locked. A ProRegTx - /// naming a coin that is not this wallet's leaves an entry that never - /// matches anything. + /// An entry does not need a coin behind it. A collateral seen after the + /// block holding its ProRegTx, or a coin locked before it arrives, arrives + /// locked. A ProRegTx naming a coin that is not this wallet's leaves an + /// entry that never matches anything. /// /// # How long a lock lasts /// @@ -72,8 +88,9 @@ impl ManagedWalletInfo { /// coin is spent the entry has nothing to act on, and a coin whose spend is /// reorged out or swept comes back locked. /// - /// Processing a ProRegTx again (the block that confirms it, a rescan) locks - /// its collateral again, as Core does on load. + /// Processing a ProRegTx in a block again (a rescan, or the block that + /// confirms a ProRegTx first seen in the mempool) locks its collateral + /// again, as Core does on load. /// /// # The set is the source of truth /// @@ -84,6 +101,13 @@ impl ManagedWalletInfo { /// unlocked, and on every balance refresh. A flag written on a held coin /// directly is overwritten by the next refresh. /// + /// A lock or an unlock moves a held coin between the spendable and the + /// locked balance. [`Self::lock_outpoint`], [`Self::unlock_outpoint`] and a + /// transaction check with `update_balance` refresh the balance themselves; + /// a check without it leaves the refresh to its caller, which refreshes + /// every wallet whose check lists a lock in + /// [`TransactionCheckResult::locked_outpoints`](crate::transaction_checking::TransactionCheckResult::locked_outpoints). + /// /// # Persistence /// /// The set is serialized with the wallet. A store that keeps wallet state @@ -134,15 +158,38 @@ impl ManagedWalletInfo { true } - /// Lock the collateral `tx` registers when it is a ProRegTx. + /// Lock the collateral `tx` registers when it is a ProRegTx that locks it + /// in `context`: a collateral it names only in a block, its own output in + /// a block or, unconfirmed, as that coin arrives. See + /// [`Self::locked_outpoints`]. /// /// Returns the collateral when it was not locked before. Only updates the /// set: the caller refreshes the flags of the coins involved. - pub(crate) fn lock_masternode_collateral(&mut self, tx: &Transaction) -> Option { + pub(crate) fn lock_masternode_collateral( + &mut self, + tx: &Transaction, + context: &TransactionContext, + ) -> Option { let collateral = masternode_collateral(tx)?; + if !context.confirmed() { + // Only a null collateral txid yields the ProRegTx's own txid: no + // transaction can name itself. + let creates_it = collateral.txid == tx.txid(); + if !creates_it || self.holds_coin(&collateral) { + return None; + } + } self.locked_outpoints.insert(collateral).then_some(collateral) } + /// Whether a funds account of this wallet holds `outpoint` as a coin. + fn holds_coin(&self, outpoint: &OutPoint) -> bool { + self.accounts + .all_funding_accounts() + .iter() + .any(|account| account.utxos.contains_key(outpoint)) + } + /// Set the lock flag of each coin this wallet holds among `outpoints` to /// its membership in the lock set. Returns whether any flag changed, which /// means the balance buckets are stale. From 4381c6f4183d0440499519dc124840b748029408 Mon Sep 17 00:00:00 2001 From: Quantum Explorer Date: Tue, 29 Sep 2026 03:46:10 +0700 Subject: [PATCH 03/13] fix(key-wallet): drop a locked input seeded after funding `add_funding` dropped the account's locked coins only from the inputs the builder held at that moment, so a stale copy of a locked coin (one cloned with `is_locked == false`) passed to `add_inputs` after the funding call reached coin selection and could be spent, masternode collateral included. Funding now records the outpoints the account holds locked on the builder, and `assemble_unsigned` drops them from the candidates just before coin selection, next to the reservation recheck. As with a reserved outpoint, a locked one is dropped silently rather than refused, whichever call came first. Inputs the accounts hold unlocked are kept as before. Co-Authored-By: Claude Opus 5.5 (cherry picked from commit 44a9a010500fbd44aba09111b4c53a28b88e8073) --- .../src/tests/locked_outpoints_tests.rs | 49 ++++++++++++++++--- .../transaction_builder.rs | 45 +++++++++++------ 2 files changed, 70 insertions(+), 24 deletions(-) diff --git a/key-wallet/src/tests/locked_outpoints_tests.rs b/key-wallet/src/tests/locked_outpoints_tests.rs index 53cca5cee..f71d9c17f 100644 --- a/key-wallet/src/tests/locked_outpoints_tests.rs +++ b/key-wallet/src/tests/locked_outpoints_tests.rs @@ -615,22 +615,55 @@ async fn special_transaction_funding_skips_the_collateral_even_when_seeded() { assert_eq!(spent(&tx), vec![spare.expect("spare coin")]); } +/// Funding records the coins the account holds locked, and the build drops +/// them just before coin selection, so a copy seeded after the funding call is +/// dropped too. `LargestFirst` would take the 1,000 DASH collateral first. +#[test_case(false ; "seeded before funding")] +#[test_case(true ; "seeded after funding")] +#[tokio::test] +async fn funding_drops_a_seeded_collateral(seeded_after_funding: bool) { + let (mut ctx, collateral, spare) = registered_wallet(Some(SPARE)).await; + let stale = stale_copy(&ctx, collateral); + let account = ctx.wallet.accounts.standard_bip44_accounts.get(&0).expect("BIP44").clone(); + let funds = ctx.managed_wallet.accounts.standard_bip44_accounts.get_mut(&0).expect("BIP44"); + + let builder = TransactionBuilder::new() + .set_current_height(TIP) + .set_selection_strategy(SelectionStrategy::LargestFirst); + let builder = if seeded_after_funding { + builder.add_funding(funds, &account).add_inputs([stale]) + } else { + builder.add_inputs([stale]).add_funding(funds, &account) + }; + let (tx, _fee, _reservation) = builder + .add_output(&elsewhere().assume_checked(), DASH) + .build_unsigned_reserved() + .expect("the spare coin funds the payment"); + + assert_eq!(spent(&tx), vec![spare.expect("spare coin")]); +} + /// The chunked drain path offers only what the caller seeds; a seeded copy of -/// a coin the account holds locked is dropped all the same. +/// a coin the account holds locked is dropped all the same, whichever call +/// comes first. +#[test_case(false ; "seeded before funding")] +#[test_case(true ; "seeded after funding")] #[tokio::test] -async fn reservation_only_funding_drops_a_seeded_collateral() { +async fn reservation_only_funding_drops_a_seeded_collateral(seeded_after_funding: bool) { let (mut ctx, collateral, _) = registered_wallet(None).await; let stale = stale_copy(&ctx, collateral); let account = ctx.wallet.accounts.standard_bip44_accounts.get(&0).expect("BIP44").clone(); let funds = ctx.managed_wallet.accounts.standard_bip44_accounts.get_mut(&0).expect("BIP44"); - let result = TransactionBuilder::new() + let builder = TransactionBuilder::new() .set_current_height(TIP) - .set_selection_strategy(SelectionStrategy::All) - .add_inputs([stale]) - .add_funding_reservation_only(funds, &account) - .add_output(&elsewhere().assume_checked(), DASH) - .build_unsigned_reserved(); + .set_selection_strategy(SelectionStrategy::All); + let builder = if seeded_after_funding { + builder.add_funding_reservation_only(funds, &account).add_inputs([stale]) + } else { + builder.add_inputs([stale]).add_funding_reservation_only(funds, &account) + }; + let result = builder.add_output(&elsewhere().assume_checked(), DASH).build_unsigned_reserved(); assert!(matches!(result, Err(BuilderError::CoinSelection(SelectionError::NoUtxosAvailable)))); } diff --git a/key-wallet/src/wallet/managed_wallet_info/transaction_builder.rs b/key-wallet/src/wallet/managed_wallet_info/transaction_builder.rs index 56743924f..28a40312f 100644 --- a/key-wallet/src/wallet/managed_wallet_info/transaction_builder.rs +++ b/key-wallet/src/wallet/managed_wallet_info/transaction_builder.rs @@ -93,6 +93,11 @@ pub struct TransactionBuilder { /// account that holds the UTXO, so each account reserves its own share of /// the chosen inputs — all under the one token this build is stamped with. funding: Vec<(ReservationSet, HashSet)>, + /// Outpoints a funding account holds locked, such as masternode + /// collateral, captured by `add_funding`. Coin selection never sees them, + /// whether the account offered them or `add_inputs` seeded them, before + /// the funding call or after it: see `assemble_unsigned`. + locked: HashSet, } impl Default for TransactionBuilder { @@ -117,6 +122,7 @@ impl TransactionBuilder { special_payload: None, payload_finalizer: None, funding: Vec::new(), + locked: HashSet::new(), } } @@ -213,17 +219,17 @@ impl TransactionBuilder { // here would leave a pre-seeded input unreserved and free for a // concurrent build to select. let mut owned: HashSet = HashSet::new(); - // Coins the wallet has locked, such as masternode collateral. Never a - // candidate, and a copy seeded by `add_inputs` is dropped below: a - // caller-built `Utxo` carries whatever lock flag it was cloned with, - // while this account's own coin carries the current one. - let mut locked: HashSet = HashSet::new(); for utxo in funds_acc.utxos.values() { - if reserved.contains(&utxo.outpoint) { + // A coin the wallet has locked, such as masternode collateral, is + // never a candidate. Record it so `assemble_unsigned` also drops a + // copy seeded by `add_inputs`, before this call or after it: a + // caller-built `Utxo` carries whatever lock flag it was cloned + // with, while this account's own coin carries the current one. + if utxo.is_locked { + self.locked.insert(utxo.outpoint); continue; } - if utxo.is_locked { - locked.insert(utxo.outpoint); + if reserved.contains(&utxo.outpoint) { continue; } owned.insert(utxo.outpoint); @@ -235,9 +241,6 @@ impl TransactionBuilder { } } self.funding.push((funds_acc.reservations().clone(), owned)); - if !locked.is_empty() { - self.inputs.retain(|utxo| !locked.contains(&utxo.outpoint)); - } self.inputs.extend(candidates); if self.change_addr.is_none() { self.change_addr = funds_acc.next_change_address(Some(&acc.account_xpub), true).ok(); @@ -250,6 +253,11 @@ impl TransactionBuilder { self } + /// Add `inputs` to the candidate input set. + /// + /// In a funded build, an input that a funding account holds reserved or + /// locked is dropped just before coin selection, whether it was added + /// before the funding call or after it. pub fn add_inputs(mut self, inputs: impl IntoIterator) -> Self { self.inputs.extend(inputs); self @@ -570,18 +578,23 @@ impl TransactionBuilder { } if !self.funding.is_empty() { - // Every UTXO a funding account offers is unreserved, but a seeded - // one need not be: `add_inputs` does not consult a reservation set, - // and may run after the funding call. Drop those here so no path + // Every UTXO a funding account offers is unreserved and unlocked, + // but a seeded one need not be: `add_inputs` consults neither the + // reservation sets nor the accounts' locks, and may run after the + // funding call. Drop those here, just before selection, so no path // into the builder can spend an outpoint another in-flight build - // holds. + // holds or one the wallet has locked, such as masternode + // collateral. let height = self.current_height; let reserved: HashSet = self .funding .iter() .flat_map(|(reservations, _)| reservations.reserved(height)) .collect(); - self.inputs.retain(|utxo| !reserved.contains(&utxo.outpoint)); + let locked = &self.locked; + self.inputs.retain(|utxo| { + !reserved.contains(&utxo.outpoint) && !locked.contains(&utxo.outpoint) + }); } // Must match `calculate_base_size`, including the conservative VIN0 routing-script size. From 035db5c1bf756ad5324b161ee45a241d929681a9 Mon Sep 17 00:00:00 2001 From: Bartosz Rozwarski Date: Wed, 11 Nov 2026 14:27:44 +0100 Subject: [PATCH 04/13] fix(key-wallet): port the collateral lock to current `dev` `TransactionBuilder::with_waiting_coins` copies the builder field by field, so it now carries `locked` too. Without it the trial build that tells whether coins awaiting finality would fund a send would not compile. The test fixtures follow the ProRegTx version 3 payload (`payouts`, `shared_collateral`, a `MasternodeNetInfo` service address) and the `ProviderUpdateServicePayload::new` signature, and the `Hash` imports that `bitcoin_hashes` 1.x made unused are gone. Co-Authored-By: Claude Fable 5.2 --- key-wallet-manager/src/event_tests.rs | 8 ++++++-- key-wallet/src/tests/locked_outpoints_tests.rs | 11 +++++++---- .../wallet/managed_wallet_info/locked_outpoints.rs | 9 ++++++--- .../wallet/managed_wallet_info/transaction_builder.rs | 1 + 4 files changed, 20 insertions(+), 9 deletions(-) diff --git a/key-wallet-manager/src/event_tests.rs b/key-wallet-manager/src/event_tests.rs index fd89a58e9..de205745d 100644 --- a/key-wallet-manager/src/event_tests.rs +++ b/key-wallet-manager/src/event_tests.rs @@ -12,8 +12,8 @@ use dashcore::bls_sig_utils::{BLSPublicKey, BLSSignature}; use dashcore::ephemerealdata::chain_lock::ChainLock; use dashcore::ephemerealdata::instant_lock::InstantLock; use dashcore::hash_types::{CycleHash, InputsHash}; -use dashcore::hashes::Hash; use dashcore::opcodes; +use dashcore::sml::masternode_list_entry::MasternodeNetInfo; use dashcore::{ BlockHash, CompactTarget, OutPoint, PubkeyHash, PublicKey, ScriptBuf, TxIn, TxMerkleNode, TxOut, Txid, Witness, @@ -1391,7 +1391,9 @@ fn masternode_registration(collateral: OutPoint, outputs: Vec, seed: u8) masternode_type: ProviderMasternodeType::Regular, masternode_mode: 0, collateral_outpoint: collateral, - service_address: "127.0.0.1:19999".parse().expect("socket address"), + service_address: MasternodeNetInfo::Legacy( + "127.0.0.1:19999".parse().expect("socket address"), + ), owner_key_hash: key_hash, operator_public_key: BLSPublicKey::from([0x11; 48]), voting_key_hash: key_hash, @@ -1402,6 +1404,8 @@ fn masternode_registration(collateral: OutPoint, outputs: Vec, seed: u8) platform_node_id: None, platform_p2p_port: None, platform_http_port: None, + payouts: None, + shared_collateral: None, }, )), } diff --git a/key-wallet/src/tests/locked_outpoints_tests.rs b/key-wallet/src/tests/locked_outpoints_tests.rs index f71d9c17f..896dd0162 100644 --- a/key-wallet/src/tests/locked_outpoints_tests.rs +++ b/key-wallet/src/tests/locked_outpoints_tests.rs @@ -14,7 +14,7 @@ use dashcore::blockdata::transaction::special_transaction::TransactionPayload; use dashcore::bls_sig_utils::{BLSPublicKey, BLSSignature}; use dashcore::ephemerealdata::instant_lock::InstantLock; use dashcore::hash_types::InputsHash; -use dashcore::hashes::Hash; +use dashcore::sml::masternode_list_entry::MasternodeNetInfo; use dashcore::{ Address, BlockHash, OutPoint, PubkeyHash, ScriptBuf, Transaction, TxIn, TxOut, Txid, }; @@ -90,7 +90,9 @@ fn registration(collateral: OutPoint, outputs: Vec, seed: u8) -> Transact masternode_type: ProviderMasternodeType::Regular, masternode_mode: 0, collateral_outpoint: collateral, - service_address: "127.0.0.1:19999".parse().expect("socket address"), + service_address: MasternodeNetInfo::Legacy( + "127.0.0.1:19999".parse().expect("socket address"), + ), owner_key_hash: key_hash, operator_public_key: BLSPublicKey::from([0x11; 48]), voting_key_hash: key_hash, @@ -101,6 +103,8 @@ fn registration(collateral: OutPoint, outputs: Vec, seed: u8) -> Transact platform_node_id: None, platform_p2p_port: None, platform_http_port: None, + payouts: None, + shared_collateral: None, }, )), } @@ -577,8 +581,7 @@ fn provider_update_service() -> TransactionPayload { TransactionPayload::ProviderUpdateServicePayloadType(ProviderUpdateServicePayload::new( Some(0), Txid::all_zeros(), - 0x00000000000000000000ffff7f000001, // 127.0.0.1 mapped - 19999, + "127.0.0.1:19999".parse().expect("socket address"), ScriptBuf::new(), InputsHash::all_zeros(), None, diff --git a/key-wallet/src/wallet/managed_wallet_info/locked_outpoints.rs b/key-wallet/src/wallet/managed_wallet_info/locked_outpoints.rs index 9f5eda217..355c2650a 100644 --- a/key-wallet/src/wallet/managed_wallet_info/locked_outpoints.rs +++ b/key-wallet/src/wallet/managed_wallet_info/locked_outpoints.rs @@ -10,7 +10,6 @@ use super::ManagedWalletInfo; use crate::transaction_checking::TransactionContext; use crate::wallet::managed_wallet_info::wallet_info_interface::WalletInfoInterface; use dashcore::blockdata::transaction::special_transaction::TransactionPayload; -use dashcore::hashes::Hash; use dashcore::{OutPoint, Transaction, Txid}; use std::collections::BTreeSet; @@ -237,7 +236,7 @@ mod tests { use dashcore::blockdata::transaction::special_transaction::TransactionPayload; use dashcore::bls_sig_utils::BLSPublicKey; use dashcore::hash_types::InputsHash; - use dashcore::hashes::Hash; + use dashcore::sml::masternode_list_entry::MasternodeNetInfo; use dashcore::{Address, Network, OutPoint, PubkeyHash, ScriptBuf, Transaction, TxOut, Txid}; /// A ProRegTx naming `collateral`, with `outputs` outputs of its own. @@ -260,7 +259,9 @@ mod tests { masternode_type: ProviderMasternodeType::Regular, masternode_mode: 0, collateral_outpoint: collateral, - service_address: "127.0.0.1:19999".parse().expect("socket address"), + service_address: MasternodeNetInfo::Legacy( + "127.0.0.1:19999".parse().expect("socket address"), + ), owner_key_hash: key_hash, operator_public_key: BLSPublicKey::from([0x11; 48]), voting_key_hash: key_hash, @@ -271,6 +272,8 @@ mod tests { platform_node_id: None, platform_p2p_port: None, platform_http_port: None, + payouts: None, + shared_collateral: None, }, )), } diff --git a/key-wallet/src/wallet/managed_wallet_info/transaction_builder.rs b/key-wallet/src/wallet/managed_wallet_info/transaction_builder.rs index 28a40312f..e106791d4 100644 --- a/key-wallet/src/wallet/managed_wallet_info/transaction_builder.rs +++ b/key-wallet/src/wallet/managed_wallet_info/transaction_builder.rs @@ -543,6 +543,7 @@ impl TransactionBuilder { special_payload: self.special_payload.clone(), payload_finalizer: None, funding: self.funding.clone(), + locked: self.locked.clone(), } } From aabf94cdf9266d40f719dd4c77db523895e07a46 Mon Sep 17 00:00:00 2001 From: Bartosz Rozwarski Date: Wed, 11 Nov 2026 14:33:35 +0100 Subject: [PATCH 05/13] fix(key-wallet)!: lock only collateral tied to the wallet Every ProRegTx the wallet checked added its collateral to the lock set, whether or not the coin or the registration had anything to do with the wallet. The set is persisted and nothing removes an entry, so it grew with the registrations of other masternodes, including unvalidated ones relayed through the mempool. A ProRegTx now locks its collateral only when the coin is the wallet's. A collateral it creates is locked when that output pays the wallet. A collateral it names is locked in a block when the wallet holds the coin, or when the ProRegTx is relevant to the wallet, so a collateral that arrives after its own registration (a rescan can hand over the later block first) still arrives locked. A named collateral that arrives after a registration involving nothing else of the wallet's is no longer locked. The three copies of the ProRegTx test fixture become `Transaction::dummy_provider_registration`. Co-Authored-By: Claude Fable 5.2 --- dash/src/test_utils/transaction.rs | 53 ++++++- key-wallet-manager/src/event_tests.rs | 43 +---- .../src/tests/locked_outpoints_tests.rs | 138 +++++++++++----- .../transaction_checking/account_checker.rs | 6 +- .../transaction_checking/wallet_checker.rs | 44 +++-- .../managed_wallet_info/locked_outpoints.rs | 150 ++++++++---------- .../src/wallet/managed_wallet_info/mod.rs | 2 +- 7 files changed, 249 insertions(+), 187 deletions(-) diff --git a/dash/src/test_utils/transaction.rs b/dash/src/test_utils/transaction.rs index d10833ef6..dc370e22c 100644 --- a/dash/src/test_utils/transaction.rs +++ b/dash/src/test_utils/transaction.rs @@ -1,11 +1,17 @@ use std::ops::Range; -use crate::bls_sig_utils::BLSSignature; +use crate::bls_sig_utils::{BLSPublicKey, BLSSignature}; use crate::consensus::serialize; -use crate::hash_types::{MerkleRootAssetUnlocks, MerkleRootMasternodeList, MerkleRootQuorums}; +use crate::hash_types::{ + InputsHash, MerkleRootAssetUnlocks, MerkleRootMasternodeList, MerkleRootQuorums, +}; +use crate::sml::masternode_list_entry::MasternodeNetInfo; use crate::transaction::special_transaction::coinbase::CoinbasePayload; +use crate::transaction::special_transaction::provider_registration::{ + ProviderMasternodeType, ProviderRegistrationPayload, +}; use crate::transaction::special_transaction::{TransactionPayload, TransactionType}; -use crate::{Address, OutPoint, ScriptBuf, Transaction, TxIn, TxOut, Txid, Witness}; +use crate::{Address, OutPoint, PubkeyHash, ScriptBuf, Transaction, TxIn, TxOut, Txid, Witness}; /// A special transaction type no Dash Core version assigns pub const UNASSIGNED_SPECIAL_TX_TYPE: u16 = 0xffff; @@ -59,6 +65,47 @@ impl Transaction { } } + /// Creates a ProRegTx registering `collateral`, with `owner_key_hash` as + /// its owner and voting key, paying `outputs`. `input_id` sets its one + /// input and so varies the txid. + pub fn dummy_provider_registration( + collateral: OutPoint, + owner_key_hash: PubkeyHash, + outputs: Vec, + input_id: u8, + ) -> Transaction { + Transaction { + version: 3, + lock_time: 0, + input: vec![TxIn { + previous_output: OutPoint::new(Txid::from([input_id; 32]), 0), + ..Default::default() + }], + output: outputs, + special_transaction_payload: Some(TransactionPayload::ProviderRegistrationPayloadType( + ProviderRegistrationPayload { + version: 1, + masternode_type: ProviderMasternodeType::Regular, + masternode_mode: 0, + collateral_outpoint: collateral, + service_address: MasternodeNetInfo::Legacy(([127, 0, 0, 1], 19999).into()), + owner_key_hash, + operator_public_key: BLSPublicKey::from([0x11; 48]), + voting_key_hash: owner_key_hash, + operator_reward: 0, + script_payout: ScriptBuf::new(), + inputs_hash: InputsHash::all_zeros(), + signature: vec![0x33; 65], + platform_node_id: None, + platform_p2p_port: None, + platform_http_port: None, + payouts: None, + shared_collateral: None, + }, + )), + } + } + pub fn dummy_coinbase(address: &Address, value: u64) -> Transaction { let inputs = vec![TxIn { previous_output: OutPoint::null(), diff --git a/key-wallet-manager/src/event_tests.rs b/key-wallet-manager/src/event_tests.rs index de205745d..8599a99d9 100644 --- a/key-wallet-manager/src/event_tests.rs +++ b/key-wallet-manager/src/event_tests.rs @@ -4,16 +4,12 @@ use crate::wallet_interface::WalletInterface; use dashcore::block::{Block, Header, Version}; use dashcore::blockdata::script::Builder; use dashcore::blockdata::transaction::special_transaction::asset_lock::AssetLockPayload; -use dashcore::blockdata::transaction::special_transaction::provider_registration::{ - ProviderMasternodeType, ProviderRegistrationPayload, -}; use dashcore::blockdata::transaction::special_transaction::TransactionPayload; -use dashcore::bls_sig_utils::{BLSPublicKey, BLSSignature}; +use dashcore::bls_sig_utils::BLSSignature; use dashcore::ephemerealdata::chain_lock::ChainLock; use dashcore::ephemerealdata::instant_lock::InstantLock; -use dashcore::hash_types::{CycleHash, InputsHash}; +use dashcore::hash_types::CycleHash; use dashcore::opcodes; -use dashcore::sml::masternode_list_entry::MasternodeNetInfo; use dashcore::{ BlockHash, CompactTarget, OutPoint, PubkeyHash, PublicKey, ScriptBuf, TxIn, TxMerkleNode, TxOut, Txid, Witness, @@ -1376,39 +1372,8 @@ async fn test_update_wallet_synced_height_does_not_re_emit_when_unchanged() { /// A ProRegTx registering `collateral` and paying `outputs`. Its fee input and /// keys belong to no one the test wallet knows; `seed` varies the txid. fn masternode_registration(collateral: OutPoint, outputs: Vec, seed: u8) -> Transaction { - let key_hash = PubkeyHash::from_byte_array([0x70; 20]); - Transaction { - version: 3, - lock_time: 0, - input: vec![TxIn { - previous_output: OutPoint::new(Txid::from_byte_array([seed; 32]), 0), - ..Default::default() - }], - output: outputs, - special_transaction_payload: Some(TransactionPayload::ProviderRegistrationPayloadType( - ProviderRegistrationPayload { - version: 1, - masternode_type: ProviderMasternodeType::Regular, - masternode_mode: 0, - collateral_outpoint: collateral, - service_address: MasternodeNetInfo::Legacy( - "127.0.0.1:19999".parse().expect("socket address"), - ), - owner_key_hash: key_hash, - operator_public_key: BLSPublicKey::from([0x11; 48]), - voting_key_hash: key_hash, - operator_reward: 0, - script_payout: ScriptBuf::new(), - inputs_hash: InputsHash::all_zeros(), - signature: vec![0x33; 65], - platform_node_id: None, - platform_p2p_port: None, - platform_http_port: None, - payouts: None, - shared_collateral: None, - }, - )), - } + let owner_key_hash = PubkeyHash::from_byte_array([0x70; 20]); + Transaction::dummy_provider_registration(collateral, owner_key_hash, outputs, seed) } fn bip44_account_0() -> AccountType { diff --git a/key-wallet/src/tests/locked_outpoints_tests.rs b/key-wallet/src/tests/locked_outpoints_tests.rs index 896dd0162..6b8872b92 100644 --- a/key-wallet/src/tests/locked_outpoints_tests.rs +++ b/key-wallet/src/tests/locked_outpoints_tests.rs @@ -5,21 +5,18 @@ use std::str::FromStr; use dashcore::address::NetworkUnchecked; -use dashcore::blockdata::transaction::special_transaction::provider_registration::{ - ProviderMasternodeType, ProviderRegistrationPayload, -}; use dashcore::blockdata::transaction::special_transaction::provider_update_revocation::ProviderUpdateRevocationPayload; use dashcore::blockdata::transaction::special_transaction::provider_update_service::ProviderUpdateServicePayload; use dashcore::blockdata::transaction::special_transaction::TransactionPayload; -use dashcore::bls_sig_utils::{BLSPublicKey, BLSSignature}; +use dashcore::bls_sig_utils::BLSSignature; use dashcore::ephemerealdata::instant_lock::InstantLock; use dashcore::hash_types::InputsHash; -use dashcore::sml::masternode_list_entry::MasternodeNetInfo; use dashcore::{ Address, BlockHash, OutPoint, PubkeyHash, ScriptBuf, Transaction, TxIn, TxOut, Txid, }; use test_case::test_case; +use crate::managed_account::managed_account_trait::ManagedAccountTrait; use crate::test_utils::TestWalletContext; use crate::transaction_checking::{BlockInfo, TransactionContext, WalletTransactionChecker}; use crate::wallet::managed_wallet_info::asset_lock_builder::{ @@ -71,43 +68,26 @@ fn elsewhere() -> Address { Address::from_str("yTb47qEBpNmgXvYYsHEN4nh8yJwa5iC4Cs").expect("testnet address") } -/// A ProRegTx registering `collateral`, paying `outputs`. Everything else, -/// its fee input and keys included, belongs to no one this wallet knows, so -/// the collateral is its only link to the wallet. `seed` varies the txid. +/// The ProRegTx of someone else's masternode registering `collateral`, paying +/// `outputs`. Its fee input and keys belong to no one this wallet knows, so +/// the collateral is its only possible link to the wallet. `seed` varies the +/// txid. fn registration(collateral: OutPoint, outputs: Vec, seed: u8) -> Transaction { - let key_hash = PubkeyHash::from_byte_array([0x70; 20]); - Transaction { - version: 3, - lock_time: 0, - input: vec![TxIn { - previous_output: OutPoint::new(Txid::from_byte_array([seed; 32]), 0), - ..Default::default() - }], - output: outputs, - special_transaction_payload: Some(TransactionPayload::ProviderRegistrationPayloadType( - ProviderRegistrationPayload { - version: 1, - masternode_type: ProviderMasternodeType::Regular, - masternode_mode: 0, - collateral_outpoint: collateral, - service_address: MasternodeNetInfo::Legacy( - "127.0.0.1:19999".parse().expect("socket address"), - ), - owner_key_hash: key_hash, - operator_public_key: BLSPublicKey::from([0x11; 48]), - voting_key_hash: key_hash, - operator_reward: 0, - script_payout: ScriptBuf::new(), - inputs_hash: InputsHash::all_zeros(), - signature: vec![0x33; 65], - platform_node_id: None, - platform_p2p_port: None, - platform_http_port: None, - payouts: None, - shared_collateral: None, - }, - )), - } + let owner_key_hash = PubkeyHash::from_byte_array([0x70; 20]); + Transaction::dummy_provider_registration(collateral, owner_key_hash, outputs, seed) +} + +/// A ProRegTx registering `collateral` under an owner key of the wallet, so +/// the wallet finds it relevant. `seed` varies the txid. +fn own_registration(ctx: &mut TestWalletContext, collateral: OutPoint, seed: u8) -> Transaction { + let owner = ctx + .managed_wallet + .provider_owner_keys_managed_account_mut() + .expect("provider owner keys account") + .next_address(None, true) + .expect("owner address"); + let owner_key_hash = *owner.payload().as_pubkey_hash().expect("P2PKH owner address"); + Transaction::dummy_provider_registration(collateral, owner_key_hash, Vec::new(), seed) } /// Pay `value` to the wallet in a block at `height`; `seed` varies the txid. @@ -220,22 +200,25 @@ async fn a_collateral_sized_coin_nobody_registered_is_spendable() { assert!(ctx.managed_wallet.locked_outpoints().is_empty()); } +/// The wallet holds the owner key, so the ProRegTx is relevant, and the +/// collateral is one of its coins. A rescan can hand over the later block +/// first: the collateral then arrives locked. #[test_case(true ; "collateral first")] #[test_case(false ; "registration first")] #[tokio::test] -async fn a_registration_locks_its_external_collateral_whichever_arrives_first( +async fn the_wallets_own_registration_locks_its_collateral_whichever_arrives_first( collateral_first: bool, ) { let mut ctx = TestWalletContext::new_random(); + let spare = receive(&mut ctx, SPARE, 0x02, 100).await; let collateral_tx = Transaction::dummy(&ctx.receive_address, 0x01..0x02, &[COLLATERAL]); let collateral = OutPoint::new(collateral_tx.txid(), 0); - let registration = registration(collateral, vec![], 0xEE); + let registration = own_registration(&mut ctx, collateral, 0xEE); let registered = if collateral_first { ctx.check_transaction(&collateral_tx, block(100)).await; ctx.check_transaction(®istration, block(101)).await } else { - // A rescan can hand over the later block first. let registered = ctx.check_transaction(®istration, block(101)).await; assert!(ctx.managed_wallet.is_outpoint_locked(&collateral), "locked before it arrives"); ctx.check_transaction(&collateral_tx, block(100)).await; @@ -243,6 +226,27 @@ async fn a_registration_locks_its_external_collateral_whichever_arrives_first( }; // No separate balance refresh: the checks leave the balance right. + assert!(registered.is_relevant, "the owner key is the wallet's"); + assert_eq!(registered.locked_outpoints, vec![collateral]); + assert!(ctx.bip44_account().utxos[&collateral].is_locked); + assert_eq!(ctx.managed_wallet.balance().locked(), COLLATERAL); + assert_eq!(ctx.managed_wallet.balance().spendable(), SPARE); + ctx.managed_wallet.update_last_processed_height(TIP); + let tx = send(&mut ctx, DASH, SelectionStrategy::LargestFirst).expect("the spare coin"); + assert_eq!(spent(&tx), vec![spare]); +} + +/// Holding the collateral is enough: the registration may use keys and fee +/// coins kept elsewhere. +#[tokio::test] +async fn a_registration_in_a_block_locks_a_collateral_the_wallet_holds() { + let mut ctx = TestWalletContext::new_random(); + let collateral = receive(&mut ctx, COLLATERAL, 0x01, 100).await; + + let registered = + ctx.check_transaction(®istration(collateral, vec![], 0xEE), block(101)).await; + + // No separate balance refresh: the check leaves the balance right. assert!(!registered.is_relevant, "nothing but the collateral ties it to this wallet"); assert_eq!(registered.locked_outpoints, vec![collateral]); assert!(registered.state_modified, "the lock set is persisted state"); @@ -251,6 +255,52 @@ async fn a_registration_locks_its_external_collateral_whichever_arrives_first( assert!(is_out_of_coins(send(&mut ctx, DASH, SelectionStrategy::LargestFirst))); } +/// The registration of a masternode that is not this wallet's leaves no +/// entry, so the lock set does not grow with the network's registrations. +#[test_case(false, block(101) ; "naming a coin, in a block")] +#[test_case(true, TransactionContext::Mempool ; "creating its collateral, in the mempool")] +#[test_case(true, block(101) ; "creating its collateral, in a block")] +#[tokio::test] +async fn a_registration_of_another_masternode_locks_nothing( + creates_collateral: bool, + context: TransactionContext, +) { + let mut ctx = TestWalletContext::new_random(); + let held = receive(&mut ctx, COLLATERAL, 0x01, 100).await; + let registration = if creates_collateral { + let to_elsewhere = TxOut { + value: COLLATERAL, + script_pubkey: elsewhere().assume_checked().script_pubkey(), + }; + registration(OutPoint::new(Txid::all_zeros(), 0), vec![to_elsewhere], 0xEE) + } else { + registration(OutPoint::new(Txid::from_byte_array([0x19; 32]), 0), vec![], 0xEE) + }; + + let result = ctx.check_transaction(®istration, context).await; + + assert!(!result.is_relevant); + assert!(result.locked_outpoints.is_empty()); + assert!(ctx.managed_wallet.locked_outpoints().is_empty()); + assert!(!ctx.bip44_account().utxos[&held].is_locked); +} + +/// A named collateral that arrives after a registration involving nothing +/// else of the wallet's is an ordinary coin: nothing said it would be the +/// wallet's. +#[tokio::test] +async fn a_collateral_arriving_after_a_foreign_registration_is_not_locked() { + let mut ctx = TestWalletContext::new_random(); + let collateral_tx = Transaction::dummy(&ctx.receive_address, 0x01..0x02, &[COLLATERAL]); + let collateral = OutPoint::new(collateral_tx.txid(), 0); + + ctx.check_transaction(®istration(collateral, vec![], 0xEE), block(101)).await; + ctx.check_transaction(&collateral_tx, block(100)).await; + + assert!(!ctx.managed_wallet.is_outpoint_locked(&collateral)); + assert_eq!(ctx.managed_wallet.balance().spendable(), COLLATERAL); +} + #[test_case(&[TransactionContext::Mempool, block(101)] ; "seen in the mempool, then mined")] #[test_case(&[TransactionContext::Mempool] ; "seen only in the mempool")] #[test_case(&[TransactionContext::InstantSend(InstantLock::default())] ; "seen instant send locked")] diff --git a/key-wallet/src/transaction_checking/account_checker.rs b/key-wallet/src/transaction_checking/account_checker.rs index 3427c5975..ab803ee07 100644 --- a/key-wallet/src/transaction_checking/account_checker.rs +++ b/key-wallet/src/transaction_checking/account_checker.rs @@ -104,9 +104,9 @@ pub struct TransactionCheckResult { /// ProRegTx names is locked only in a block context; see /// [`ManagedWalletInfo::locked_outpoints`](crate::wallet::ManagedWalletInfo::locked_outpoints). /// - /// Filled whether or not the transaction is otherwise relevant: the - /// registration may involve nothing of this wallet's but the collateral, - /// or the collateral may not have arrived yet. A store that persists + /// Filled whether or not the transaction is otherwise relevant: a + /// registration in a block may involve nothing of this wallet's but a + /// collateral it holds. A store that persists /// wallet state records these. A lock moves a coin the wallet holds from /// the spendable to the locked balance, so a caller that checked with /// `update_balance = false` refreshes the balance of a wallet whose check diff --git a/key-wallet/src/transaction_checking/wallet_checker.rs b/key-wallet/src/transaction_checking/wallet_checker.rs index c2c2aa08b..2b5676e6c 100644 --- a/key-wallet/src/transaction_checking/wallet_checker.rs +++ b/key-wallet/src/transaction_checking/wallet_checker.rs @@ -9,6 +9,7 @@ use super::transaction_context::TransactionContext; use super::transaction_router::{AccountTypeToCheck, TransactionRouter}; use crate::managed_account::managed_account_trait::ManagedAccountTrait; use crate::managed_account::transaction_record::{InputDetail, TransactionRecord}; +use crate::wallet::managed_wallet_info::locked_outpoints::masternode_collateral; use crate::wallet::managed_wallet_info::wallet_info_interface::WalletInfoInterface; use crate::wallet::managed_wallet_info::ManagedWalletInfo; use crate::{KeySource, Wallet}; @@ -42,12 +43,14 @@ pub trait WalletTransactionChecker { /// The context parameter indicates where the transaction comes from (mempool, block, etc.) /// /// With `update_state`, a ProRegTx also locks the collateral it - /// registers, relevant or not, so coin selection skips it: a collateral it - /// names once the ProRegTx is in a block, its own output from any context. - /// New locks are listed in [`TransactionCheckResult::locked_outpoints`]; - /// with `update_balance = false`, refresh the balance of a wallet whose - /// check lists any, since a lock moves a held coin to the locked balance. - /// See [`ManagedWalletInfo::locked_outpoints`]. + /// registers when that coin is this wallet's, so coin selection skips it: + /// a collateral it names once the ProRegTx is in a block, its own output + /// from any context. The ProRegTx need not be relevant for that: holding + /// the collateral is enough. New locks are listed in + /// [`TransactionCheckResult::locked_outpoints`]; with + /// `update_balance = false`, refresh the balance of a wallet whose check + /// lists any, since a lock moves a held coin to the locked balance. See + /// [`ManagedWalletInfo::locked_outpoints`]. async fn check_core_transaction( &mut self, tx: &Transaction, @@ -282,25 +285,36 @@ impl WalletTransactionChecker for ManagedWalletInfo { .await; } - // Before the accounts record `tx`, so a collateral the ProRegTx - // creates itself is locked from the moment it becomes a coin. - let collateral = self.lock_masternode_collateral(tx, &context); + let collateral = masternode_collateral(tx); + let held_before = collateral.is_some_and(|collateral| self.holds_coin(&collateral)); + let confirmed = context.confirmed(); let mut result = self .check_core_transaction_inner(tx, context, wallet, update_state, update_balance) .await; + // After the accounts recorded `tx`: whether its collateral is this + // wallet's depends on what the check found. + let locked = collateral.filter(|collateral| { + self.lock_masternode_collateral( + tx, + *collateral, + confirmed, + held_before, + result.is_relevant, + ) + }); + // Bring the lock flags of the coins involved in line with the lock - // set: the coins `tx` pays this wallet, and a collateral the wallet - // already held. The balance refresh inside the check does this when it - // runs, but not every path reaches one: an otherwise irrelevant - // ProRegTx returns early, and block processing passes + // set: the coins `tx` pays this wallet, and a collateral it locked. + // A balance refresh does this too, but the one inside the check ran + // before the lock, and block processing passes // `update_balance = false` and refreshes once per block. let txid = tx.txid(); let outputs = (0..tx.output.len() as u32).map(|vout| OutPoint::new(txid, vout)); - let flags_changed = self.refresh_lock_flags(outputs.chain(collateral)); + let flags_changed = self.refresh_lock_flags(outputs.chain(locked)); - if let Some(collateral) = collateral { + if let Some(collateral) = locked { result.locked_outpoints.push(collateral); // The lock set is persisted wallet state. result.state_modified = true; diff --git a/key-wallet/src/wallet/managed_wallet_info/locked_outpoints.rs b/key-wallet/src/wallet/managed_wallet_info/locked_outpoints.rs index 355c2650a..a08dcbcd0 100644 --- a/key-wallet/src/wallet/managed_wallet_info/locked_outpoints.rs +++ b/key-wallet/src/wallet/managed_wallet_info/locked_outpoints.rs @@ -2,12 +2,12 @@ //! //! The wallet keeps one set of locked outpoints, like Dash Core's //! `setLockedCoins`, and coin selection never spends a coin in it. A ProRegTx -//! locks the collateral it registers; [`ManagedWalletInfo::lock_outpoint`] and +//! locks the collateral it registers when that coin is this wallet's; +//! [`ManagedWalletInfo::lock_outpoint`] and //! [`ManagedWalletInfo::unlock_outpoint`] lock and unlock anything by hand. See //! [`ManagedWalletInfo::locked_outpoints`] for the full rules. use super::ManagedWalletInfo; -use crate::transaction_checking::TransactionContext; use crate::wallet::managed_wallet_info::wallet_info_interface::WalletInfoInterface; use dashcore::blockdata::transaction::special_transaction::TransactionPayload; use dashcore::{OutPoint, Transaction, Txid}; @@ -42,37 +42,47 @@ impl ManagedWalletInfo { /// /// # What locks an outpoint /// - /// - A ProRegTx. The wallet locks the collateral of the masternode - /// registrations it processes, so an ordinary send never spends it: - /// spending the collateral would end the registration. The collateral is - /// the ProRegTx's `collateralOutpoint`, or, when that names a null txid, - /// the ProRegTx's own output at `collateralIndex`. When it is locked + /// - A ProRegTx whose collateral is this wallet's. The wallet locks that + /// coin so an ordinary send never spends it: spending the collateral + /// would end the registration. The collateral is the ProRegTx's + /// `collateralOutpoint`, or, when that names a null txid, the ProRegTx's + /// own output at `collateralIndex`. Whether and when it is locked /// depends on which: /// - A collateral the ProRegTx names is locked once the ProRegTx is in a /// block ([`TransactionContext::InBlock`] or - /// [`TransactionContext::InChainLockedBlock`]). Until then it is not a + /// [`TransactionContext::InChainLockedBlock`]), when the wallet holds + /// the coin or the ProRegTx is relevant to the wallet: it uses the + /// wallet's keys, pays it or spends its coins. Until then it is not a /// registration: the network may never accept it, and the wallet does /// not check a ProRegTx's payload itself. Dash Core likewise locks such /// a collateral once a block adds the registration to its masternode /// list. An [`TransactionContext::InstantSend`] context counts as /// unconfirmed here: the wallet does not verify InstantSend locks, and /// cannot tell whether its caller did. - /// - A collateral the ProRegTx creates is locked from its first - /// sighting, mempool included, as the coin arrives: it is the - /// ProRegTx's own output, so the lock can hold no other coin. An - /// unconfirmed sighting does not lock that output again once the - /// wallet holds it; a block does. + /// - A collateral the ProRegTx creates is locked when that output pays + /// this wallet, from its first sighting, mempool included, as the coin + /// arrives: it is the ProRegTx's own output, so the lock can hold no + /// other coin. An unconfirmed sighting does not lock that output again + /// once the wallet holds it; a block does. /// - [`Self::lock_outpoint`]. /// - /// Only [`Self::unlock_outpoint`] removes an outpoint. A coin's amount is - /// never a reason to lock it. + /// A ProRegTx that involves nothing of this wallet's locks nothing, so the + /// registrations of other masternodes do not grow the set. Only + /// [`Self::unlock_outpoint`] removes an outpoint. A coin's amount is never + /// a reason to lock it. /// - /// # Order does not matter + /// # A lock can come before its coin /// - /// An entry does not need a coin behind it. A collateral seen after the - /// block holding its ProRegTx, or a coin locked before it arrives, arrives - /// locked. A ProRegTx naming a coin that is not this wallet's leaves an - /// entry that never matches anything. + /// An entry does not need a coin behind it. A coin locked with + /// [`Self::lock_outpoint`] before it arrives, arrives locked. So does a + /// collateral seen after the block holding its ProRegTx (a rescan can hand + /// over the later block first), when that ProRegTx is relevant to the + /// wallet. A relevant ProRegTx naming a coin that is not this wallet's + /// leaves an entry that never matches anything. + /// + /// A named collateral that arrives after a ProRegTx involving nothing else + /// of this wallet's is not locked: nothing told the wallet the coin would + /// be its own. Lock it with [`Self::lock_outpoint`]. /// /// # How long a lock lasts /// @@ -157,32 +167,40 @@ impl ManagedWalletInfo { true } - /// Lock the collateral `tx` registers when it is a ProRegTx that locks it - /// in `context`: a collateral it names only in a block, its own output in - /// a block or, unconfirmed, as that coin arrives. See - /// [`Self::locked_outpoints`]. + /// Lock `collateral`, the collateral of the ProRegTx `tx`, when it is + /// this wallet's to keep. See [`Self::locked_outpoints`] for the rule. /// - /// Returns the collateral when it was not locked before. Only updates the + /// Call it once the accounts recorded `tx`, with the sighting that was + /// checked: whether it was in a block (`confirmed`), whether the wallet + /// held `collateral` before the check (`held_before`) and whether the + /// check found `tx` relevant. + /// + /// Returns whether the collateral was not locked before. Only updates the /// set: the caller refreshes the flags of the coins involved. pub(crate) fn lock_masternode_collateral( &mut self, tx: &Transaction, - context: &TransactionContext, - ) -> Option { - let collateral = masternode_collateral(tx)?; - if !context.confirmed() { - // Only a null collateral txid yields the ProRegTx's own txid: no - // transaction can name itself. - let creates_it = collateral.txid == tx.txid(); - if !creates_it || self.holds_coin(&collateral) { - return None; - } - } - self.locked_outpoints.insert(collateral).then_some(collateral) + collateral: OutPoint, + confirmed: bool, + held_before: bool, + is_relevant: bool, + ) -> bool { + let holds = self.holds_coin(&collateral); + // Only a null collateral txid yields the ProRegTx's own txid: no + // transaction can name itself. + let creates_it = collateral.txid == tx.txid(); + let locks = if creates_it { + holds && (confirmed || !held_before) + } else { + // A named coin can arrive after its registration, so a relevant + // registration locks it ahead. + confirmed && (holds || is_relevant) + }; + locks && self.locked_outpoints.insert(collateral) } /// Whether a funds account of this wallet holds `outpoint` as a coin. - fn holds_coin(&self, outpoint: &OutPoint) -> bool { + pub(crate) fn holds_coin(&self, outpoint: &OutPoint) -> bool { self.accounts .all_funding_accounts() .iter() @@ -230,53 +248,21 @@ impl ManagedWalletInfo { #[cfg(test)] mod tests { use super::masternode_collateral; - use dashcore::blockdata::transaction::special_transaction::provider_registration::{ - ProviderMasternodeType, ProviderRegistrationPayload, - }; - use dashcore::blockdata::transaction::special_transaction::TransactionPayload; - use dashcore::bls_sig_utils::BLSPublicKey; - use dashcore::hash_types::InputsHash; - use dashcore::sml::masternode_list_entry::MasternodeNetInfo; - use dashcore::{Address, Network, OutPoint, PubkeyHash, ScriptBuf, Transaction, TxOut, Txid}; + use dashcore::{Address, Network, OutPoint, PubkeyHash, Transaction, TxOut, Txid}; /// A ProRegTx naming `collateral`, with `outputs` outputs of its own. fn registration(collateral: OutPoint, outputs: usize) -> Transaction { - let key_hash = PubkeyHash::from_byte_array([0x70; 20]); - Transaction { - version: 3, - lock_time: 0, - input: Vec::new(), - output: vec![ - TxOut { - value: 1_000, - script_pubkey: Address::dummy(Network::Testnet, 1).script_pubkey(), - }; - outputs - ], - special_transaction_payload: Some(TransactionPayload::ProviderRegistrationPayloadType( - ProviderRegistrationPayload { - version: 1, - masternode_type: ProviderMasternodeType::Regular, - masternode_mode: 0, - collateral_outpoint: collateral, - service_address: MasternodeNetInfo::Legacy( - "127.0.0.1:19999".parse().expect("socket address"), - ), - owner_key_hash: key_hash, - operator_public_key: BLSPublicKey::from([0x11; 48]), - voting_key_hash: key_hash, - operator_reward: 0, - script_payout: ScriptBuf::new(), - inputs_hash: InputsHash::all_zeros(), - signature: vec![0x33; 65], - platform_node_id: None, - platform_p2p_port: None, - platform_http_port: None, - payouts: None, - shared_collateral: None, - }, - )), - } + let output = TxOut { + value: 1_000, + script_pubkey: Address::dummy(Network::Testnet, 1).script_pubkey(), + }; + let owner_key_hash = PubkeyHash::from_byte_array([0x70; 20]); + Transaction::dummy_provider_registration( + collateral, + owner_key_hash, + vec![output; outputs], + 0, + ) } #[test] diff --git a/key-wallet/src/wallet/managed_wallet_info/mod.rs b/key-wallet/src/wallet/managed_wallet_info/mod.rs index 2fe34f986..0bcdafc84 100644 --- a/key-wallet/src/wallet/managed_wallet_info/mod.rs +++ b/key-wallet/src/wallet/managed_wallet_info/mod.rs @@ -8,7 +8,7 @@ pub mod coin_selection; pub mod fee; pub mod helpers; pub use helpers::AbandonOutcome; -mod locked_outpoints; +pub(crate) mod locked_outpoints; pub mod managed_account_operations; pub mod managed_accounts; pub mod transaction_builder; From 547940723d7dbfac18f76d9e33377aafdfa461e3 Mon Sep 17 00:00:00 2001 From: Bartosz Rozwarski Date: Wed, 11 Nov 2026 14:37:26 +0100 Subject: [PATCH 06/13] fix(key-wallet): apply coin locks to restored UTXOs A store that restored a lock before its coin left that coin spendable. Coin selection reads the `is_locked` flag of each UTXO, and a coin that entered an account after `lock_outpoint` kept the flag it came with until the next balance refresh, so a send in between could spend a locked collateral. `restore_utxos` now sets the flag of every UTXO it restores from the lock set, and the wallet sets all flags before it funds a transaction, which also covers a coin a store puts into an account's `utxos` directly. A restored UTXO's own flag, and that of a copy it replaces, no longer decides its coin lock. Co-Authored-By: Claude Fable 5.2 --- .../src/tests/locked_outpoints_tests.rs | 65 +++++++++++++++---- key-wallet/src/tests/restore_utxos_tests.rs | 26 ++++---- .../managed_wallet_info/locked_outpoints.rs | 23 +++++-- .../src/wallet/managed_wallet_info/mod.rs | 7 +- .../transaction_building.rs | 4 ++ 5 files changed, 89 insertions(+), 36 deletions(-) diff --git a/key-wallet/src/tests/locked_outpoints_tests.rs b/key-wallet/src/tests/locked_outpoints_tests.rs index 6b8872b92..23c1bf497 100644 --- a/key-wallet/src/tests/locked_outpoints_tests.rs +++ b/key-wallet/src/tests/locked_outpoints_tests.rs @@ -549,22 +549,61 @@ async fn a_collateral_is_locked_even_before_the_next_balance_refresh() { assert!(ctx.managed_wallet.get_spendable_utxos().is_empty()); } -/// The lock set is the source of truth: a flag written on a held coin by hand -/// is set back from the set on the next balance refresh. -#[tokio::test] -async fn a_held_coins_lock_flag_follows_the_lock_set() { - let (mut ctx, collateral, spare) = registered_wallet(Some(SPARE)).await; - let spare = spare.expect("spare coin"); +/// A confirmed coin paying `value` to the wallet, as a store hands it back on +/// load; `seed` varies the outpoint. +fn stored_coin(ctx: &TestWalletContext, value: u64, seed: u8) -> Utxo { + let tx = Transaction::dummy(&ctx.receive_address, seed..seed + 1, &[value]); + let mut utxo = Utxo::new( + OutPoint::new(tx.txid(), 0), + tx.output[0].clone(), + ctx.receive_address.clone(), + 100, + false, + ); + utxo.is_confirmed = true; + utxo +} + +/// A store restores its locks and its coins in either order. With no balance +/// refresh in between, the collateral is already out of reach. +#[test_case(true ; "locks first")] +#[test_case(false ; "coins first")] +fn a_restored_lock_holds_whichever_is_restored_first(locks_first: bool) { + let mut ctx = TestWalletContext::new_random(); + let collateral = stored_coin(&ctx, COLLATERAL, 0x01); + let spare = stored_coin(&ctx, SPARE, 0x02); + let coins = [collateral.clone(), spare.clone()]; + if locks_first { + ctx.managed_wallet.lock_outpoint(collateral.outpoint); + ctx.managed_wallet.restore_utxos(&ctx.wallet, coins).expect("restores"); + } else { + ctx.managed_wallet.restore_utxos(&ctx.wallet, coins).expect("restores"); + ctx.managed_wallet.lock_outpoint(collateral.outpoint); + } + + let spendable: Vec = + ctx.managed_wallet.get_spendable_utxos().into_iter().map(|utxo| utxo.outpoint).collect(); + assert_eq!(spendable, vec![spare.outpoint]); + let tx = send(&mut ctx, DASH, SelectionStrategy::LargestFirst).expect("the spare coin"); + assert_eq!(spent(&tx), vec![spare.outpoint]); +} + +/// A store that puts a coin into an account itself, after locking its +/// outpoint, passes every point where the wallet sets the coin's flag. A send +/// reads the lock set all the same. +#[test] +fn a_send_skips_a_locked_coin_put_into_an_account_directly() { + let mut ctx = TestWalletContext::new_random(); + let collateral = stored_coin(&ctx, COLLATERAL, 0x01); + let spare = stored_coin(&ctx, SPARE, 0x02); + ctx.managed_wallet.lock_outpoint(collateral.outpoint); let account = ctx.managed_wallet.first_bip44_managed_account_mut().expect("BIP44 account"); - account.utxos.get_mut(&collateral).expect("collateral").is_locked = false; - account.utxos.get_mut(&spare).expect("spare").is_locked = true; + account.utxos.insert(collateral.outpoint, collateral); + account.utxos.insert(spare.outpoint, spare.clone()); - ctx.managed_wallet.update_balance(); + let tx = send(&mut ctx, DASH, SelectionStrategy::LargestFirst).expect("the spare coin"); - assert!(ctx.bip44_account().utxos[&collateral].is_locked); - assert!(!ctx.bip44_account().utxos[&spare].is_locked); - assert_eq!(ctx.managed_wallet.balance().locked(), COLLATERAL); - assert_eq!(ctx.managed_wallet.balance().spendable(), SPARE); + assert_eq!(spent(&tx), vec![spare.outpoint]); } #[test_case(false ; "a set amount")] diff --git a/key-wallet/src/tests/restore_utxos_tests.rs b/key-wallet/src/tests/restore_utxos_tests.rs index 9450f34e6..2b52f202e 100644 --- a/key-wallet/src/tests/restore_utxos_tests.rs +++ b/key-wallet/src/tests/restore_utxos_tests.rs @@ -244,34 +244,30 @@ fn a_copy_another_account_holds_is_taken_out_on_restore() { } /// The restored UTXO keeps the InstantSend lock and trust of the copy it -/// takes out of BIP44, and takes the coin lock of the copies it replaces in -/// place of its own: locked if either the copy CoinJoin held or the one taken -/// out of BIP44 is locked. -#[test_case(true, true, true; "a held lock stays")] -#[test_case(false, false, false; "a held unlock stays")] -#[test_case(false, true, true; "a lock on the misplaced copy stays")] -fn a_restored_utxo_keeps_the_flags_of_the_copies_it_replaces( - held_locked: bool, - misplaced_locked: bool, - expected_locked: bool, -) { +/// takes out of BIP44. Its coin lock follows the wallet's lock set, whatever +/// flag it or the copies it replaces carry. +#[test_case(true; "a locked outpoint restores locked")] +#[test_case(false; "an unlocked outpoint restores unlocked")] +fn a_restored_utxo_keeps_the_flags_of_the_copies_it_replaces(locked: bool) { let mut ctx = TestWalletContext::new_random(); let (_, mut utxo) = funded(&coinjoin_address(&ctx, 0), 0, 100_000); + if locked { + ctx.managed_wallet.lock_outpoint(utxo.outpoint); + } let accounts = &mut ctx.managed_wallet.accounts; let mut held = utxo.clone(); - held.is_locked = held_locked; + held.is_locked = !locked; accounts.coinjoin_accounts.get_mut(&0).unwrap().utxos.insert(utxo.outpoint, held); let mut misplaced = utxo.clone(); misplaced.is_instantlocked = true; misplaced.is_trusted = true; - misplaced.is_locked = misplaced_locked; accounts.standard_bip44_accounts.get_mut(&0).unwrap().utxos.insert(utxo.outpoint, misplaced); - utxo.is_locked = !(held_locked || misplaced_locked); + utxo.is_locked = !locked; ctx.managed_wallet.restore_utxos(&ctx.wallet, [utxo.clone()]).expect("restores"); let restored = &ctx.managed_wallet.accounts.coinjoin_accounts[&0].utxos[&utxo.outpoint]; - assert_eq!(restored.is_locked, expected_locked); + assert_eq!(restored.is_locked, locked); assert!(restored.is_instantlocked); assert!(restored.is_trusted); } diff --git a/key-wallet/src/wallet/managed_wallet_info/locked_outpoints.rs b/key-wallet/src/wallet/managed_wallet_info/locked_outpoints.rs index a08dcbcd0..6b2b156f5 100644 --- a/key-wallet/src/wallet/managed_wallet_info/locked_outpoints.rs +++ b/key-wallet/src/wallet/managed_wallet_info/locked_outpoints.rs @@ -106,9 +106,10 @@ impl ManagedWalletInfo { /// Coin selection works on [`Utxo`](crate::Utxo)s and skips a locked one /// through [`Utxo::is_spendable`](crate::Utxo::is_spendable). The wallet /// keeps the `is_locked` flag of every coin it holds equal to membership in - /// this set: when the coin arrives, when its outpoint is locked or - /// unlocked, and on every balance refresh. A flag written on a held coin - /// directly is overwritten by the next refresh. + /// this set: when the coin arrives or is restored, when its outpoint is + /// locked or unlocked, on every balance refresh and before the wallet + /// funds a transaction. A flag written on a held coin directly is + /// overwritten by the next refresh. /// /// A lock or an unlock moves a held coin between the spendable and the /// locked balance. [`Self::lock_outpoint`], [`Self::unlock_outpoint`] and a @@ -125,7 +126,15 @@ impl ManagedWalletInfo { /// [`TransactionCheckResult::locked_outpoints`](crate::transaction_checking::TransactionCheckResult::locked_outpoints), /// [`Self::lock_outpoint`] and [`Self::unlock_outpoint`] report their own /// changes, and on load the store calls [`Self::lock_outpoint`] for each - /// persisted outpoint, before or after restoring the coins. + /// persisted outpoint, before or after restoring the coins with + /// [`Self::restore_utxos`]. + /// + /// [`TransactionContext::InBlock`]: + /// crate::transaction_checking::TransactionContext::InBlock + /// [`TransactionContext::InChainLockedBlock`]: + /// crate::transaction_checking::TransactionContext::InChainLockedBlock + /// [`TransactionContext::InstantSend`]: + /// crate::transaction_checking::TransactionContext::InstantSend pub fn locked_outpoints(&self) -> &BTreeSet { &self.locked_outpoints } @@ -232,9 +241,9 @@ impl ManagedWalletInfo { /// Set the lock flag of every coin this wallet holds to its membership in /// the lock set. /// - /// Run before every balance refresh, so coins inserted without going - /// through transaction checking (a store restoring its coins, say) pick up - /// their locks too. + /// Run before every balance refresh and before funding a transaction, so + /// a coin that entered an account some other way than transaction + /// checking or [`Self::restore_utxos`] picks up its lock too. pub(crate) fn refresh_all_lock_flags(&mut self) { let locked = &self.locked_outpoints; for account in self.accounts.all_funding_accounts_mut() { diff --git a/key-wallet/src/wallet/managed_wallet_info/mod.rs b/key-wallet/src/wallet/managed_wallet_info/mod.rs index 0bcdafc84..77a4f1dad 100644 --- a/key-wallet/src/wallet/managed_wallet_info/mod.rs +++ b/key-wallet/src/wallet/managed_wallet_info/mod.rs @@ -464,7 +464,9 @@ impl ManagedWalletInfo { /// way as when it processes the funding transaction, except that claims /// are not consulted. The restored UTXO /// keeps the InstantSend lock and trust of any copy it replaces or takes - /// out, and their coin lock replaces its own. A matched outpoint the + /// out. Its coin lock follows the wallet's lock set + /// ([`locked_outpoints`](Self::locked_outpoints)), whatever flag it or + /// those copies carry. A matched outpoint the /// wallet already saw spent is neither credited nor returned: one the /// owning account recorded spending is held under that spend, so a fork /// dropping the spend gives it back, and one spent in a processed block @@ -517,12 +519,14 @@ impl ManagedWalletInfo { } }; let mut unmatched = Vec::new(); + let mut matched = Vec::new(); for (utxo, owner) in utxos.into_iter().zip(owners) { let Some(owner) = owner else { unmatched.push(utxo); continue; }; let outpoint = utxo.outpoint; + matched.push(outpoint); let mut copies = Vec::new(); for (index, account) in accounts.iter_mut().enumerate() { if index != owner { @@ -539,6 +543,7 @@ impl ManagedWalletInfo { account.bump_monitor_revision(); } } + self.refresh_lock_flags(matched); Ok(unmatched) } diff --git a/key-wallet/src/wallet/managed_wallet_info/transaction_building.rs b/key-wallet/src/wallet/managed_wallet_info/transaction_building.rs index c5e6b43d3..54fe46af1 100644 --- a/key-wallet/src/wallet/managed_wallet_info/transaction_building.rs +++ b/key-wallet/src/wallet/managed_wallet_info/transaction_building.rs @@ -278,6 +278,10 @@ impl ManagedWalletInfo { source_index: u32, mut builder: TransactionBuilder, ) -> Result { + // Coin selection reads each coin's lock flag, and a coin can enter an + // account without one: set every flag from the lock set first. + self.refresh_all_lock_flags(); + let preferences = if sources.is_empty() { &AccountTypePreference::DEFAULT[..] } else { From d857952e765731c662573dd33e6eff212342ceaf Mon Sep 17 00:00:00 2001 From: Bartosz Rozwarski Date: Wed, 11 Nov 2026 14:39:55 +0100 Subject: [PATCH 07/13] refactor(key-wallet): drop redundant lock handling The mempool path chained `per_wallet_locked_outpoints` into the wallets it refreshes. Off-chain a lock only lands on a ProRegTx output that pays the wallet, so that wallet is already among the affected ones and the chain added nothing. `fund_from` skipped a locked coin with a `continue`, while `prepare` drops every outpoint recorded as locked just before coin selection. The record stays, the skip goes. Co-Authored-By: Claude Fable 5.2 --- key-wallet-manager/src/process_block.rs | 14 +--------- .../transaction_builder.rs | 26 ++++++++----------- 2 files changed, 12 insertions(+), 28 deletions(-) diff --git a/key-wallet-manager/src/process_block.rs b/key-wallet-manager/src/process_block.rs index 4e0cdc924..ed6459010 100644 --- a/key-wallet-manager/src/process_block.rs +++ b/key-wallet-manager/src/process_block.rs @@ -221,23 +221,11 @@ impl WalletInterface for WalletM // changed. The cached `.balance` field is stale until // `update_balance()` runs, so the pre-snapshot taken here captures // the pre-transaction state. - // - // A wallet whose lock set this check grew is refreshed too, relevant - // or not, since a lock moves a held coin to the locked balance. - // Off-chain only a ProRegTx's own output locks, and only as that coin - // arrives, so the lock rides the `TransactionDetected` of the wallet - // the ProRegTx pays. - let refreshed: BTreeSet = check_result - .affected_wallets - .iter() - .chain(check_result.per_wallet_locked_outpoints.keys()) - .copied() - .collect(); let mut per_wallet_account_diff: BTreeMap< WalletId, BTreeMap, > = BTreeMap::new(); - for wallet_id in &refreshed { + for wallet_id in &check_result.affected_wallets { if let Some(info) = self.wallet_infos.get_mut(wallet_id) { let prior = info.account_balances(); info.update_balance(); diff --git a/key-wallet/src/wallet/managed_wallet_info/transaction_builder.rs b/key-wallet/src/wallet/managed_wallet_info/transaction_builder.rs index e106791d4..40269f59d 100644 --- a/key-wallet/src/wallet/managed_wallet_info/transaction_builder.rs +++ b/key-wallet/src/wallet/managed_wallet_info/transaction_builder.rs @@ -96,7 +96,7 @@ pub struct TransactionBuilder { /// Outpoints a funding account holds locked, such as masternode /// collateral, captured by `add_funding`. Coin selection never sees them, /// whether the account offered them or `add_inputs` seeded them, before - /// the funding call or after it: see `assemble_unsigned`. + /// the funding call or after it: see `prepare`. locked: HashSet, } @@ -185,7 +185,7 @@ impl TransactionBuilder { /// does. /// /// Reservation bookkeeping is unchanged: `owned` still covers every - /// unreserved, unlocked UTXO of the account, so whichever seeded outpoints + /// unreserved UTXO of the account, so whichever seeded outpoints /// selection picks are reserved by the account that holds them. A seeded /// outpoint the account holds locked is dropped, as with `add_funding`. pub fn add_funding_reservation_only( @@ -220,14 +220,11 @@ impl TransactionBuilder { // concurrent build to select. let mut owned: HashSet = HashSet::new(); for utxo in funds_acc.utxos.values() { - // A coin the wallet has locked, such as masternode collateral, is - // never a candidate. Record it so `assemble_unsigned` also drops a - // copy seeded by `add_inputs`, before this call or after it: a - // caller-built `Utxo` carries whatever lock flag it was cloned - // with, while this account's own coin carries the current one. + // `prepare` drops every outpoint recorded here, so a locked coin + // is not spent through a copy seeded by `add_inputs` either: such + // a copy carries whatever lock flag it was cloned with. if utxo.is_locked { self.locked.insert(utxo.outpoint); - continue; } if reserved.contains(&utxo.outpoint) { continue; @@ -579,13 +576,12 @@ impl TransactionBuilder { } if !self.funding.is_empty() { - // Every UTXO a funding account offers is unreserved and unlocked, - // but a seeded one need not be: `add_inputs` consults neither the - // reservation sets nor the accounts' locks, and may run after the - // funding call. Drop those here, just before selection, so no path - // into the builder can spend an outpoint another in-flight build - // holds or one the wallet has locked, such as masternode - // collateral. + // Every UTXO a funding account offers is unreserved, but a seeded + // one need not be: `add_inputs` consults neither the reservation + // sets nor the accounts' locks, and may run after the funding + // call. Drop those here, just before selection, so no path into + // the builder can spend an outpoint another in-flight build holds + // or one the wallet has locked, such as masternode collateral. let height = self.current_height; let reserved: HashSet = self .funding From db3b389981fff0ca5b9133c9d5ff7b72333c0eef Mon Sep 17 00:00:00 2001 From: Bartosz Rozwarski Date: Wed, 11 Nov 2026 14:42:00 +0100 Subject: [PATCH 08/13] test(key-wallet): cover lock gaps and trim redundant cases Removing any of these left every test passing: `state_modified` after a lock, the lock flag refresh of a transaction's own outputs, the lock flag refresh inside `update_balance`, the coin lock carried over when an account rebuilds a UTXO, and the locked outpoints the finality trial build copies. Each now has a test that fails without it: a rescan of the registration block after an unlock, a coin locked ahead arriving with no balance refresh, a coin locked while spent coming back when the spend is reorged out, a confirmation driven on one account, and a build limited to final coins. The strategy matrices keep the strategies that would take the collateral first and the drain, the sighting matrix for a registration first seen unconfirmed keeps one case, and the seeded-input tests keep the copy seeded after funding, which the removed cases did not add to. Co-Authored-By: Claude Fable 5.2 --- .../src/tests/locked_outpoints_tests.rs | 203 ++++++++++++------ 1 file changed, 133 insertions(+), 70 deletions(-) diff --git a/key-wallet/src/tests/locked_outpoints_tests.rs b/key-wallet/src/tests/locked_outpoints_tests.rs index 23c1bf497..1133cc22e 100644 --- a/key-wallet/src/tests/locked_outpoints_tests.rs +++ b/key-wallet/src/tests/locked_outpoints_tests.rs @@ -17,7 +17,10 @@ use dashcore::{ use test_case::test_case; use crate::managed_account::managed_account_trait::ManagedAccountTrait; +#[cfg(feature = "serde")] +use crate::managed_account::ManagedCoreFundsAccount; use crate::test_utils::TestWalletContext; +use crate::transaction_checking::transaction_router::TransactionRouter; use crate::transaction_checking::{BlockInfo, TransactionContext, WalletTransactionChecker}; use crate::wallet::managed_wallet_info::asset_lock_builder::{ AssetLockError, AssetLockFundingType, CreditOutputFunding, @@ -27,6 +30,8 @@ use crate::wallet::managed_wallet_info::fee::FeeRate; use crate::wallet::managed_wallet_info::transaction_builder::{BuilderError, TransactionBuilder}; use crate::wallet::managed_wallet_info::transaction_building::AccountTypePreference; use crate::wallet::managed_wallet_info::wallet_info_interface::WalletInfoInterface; +#[cfg(feature = "serde")] +use crate::wallet::ManagedWalletInfo; use crate::Utxo; const DASH: u64 = 100_000_000; @@ -42,14 +47,6 @@ fn block(height: u32) -> TransactionContext { )) } -fn chain_locked_block(height: u32) -> TransactionContext { - TransactionContext::InChainLockedBlock(BlockInfo::new( - height, - BlockHash::from_byte_array([height as u8; 32]), - 1_700_000_000 + height, - )) -} - /// Seen in the mempool, without an InstantSend lock. fn in_mempool(_tx: &Transaction) -> TransactionContext { TransactionContext::Mempool @@ -149,12 +146,10 @@ fn is_out_of_coins(result: Result) -> bool { ) } -#[test_case(SelectionStrategy::SmallestFirst ; "smallest first")] +/// Largest first and branch and bound, which falls back to it here, would +/// take the collateral first; a drain takes every coin it is offered. #[test_case(SelectionStrategy::LargestFirst ; "largest first")] -#[test_case(SelectionStrategy::SmallestFirstTill(1) ; "smallest first till one")] #[test_case(SelectionStrategy::BranchAndBound ; "branch and bound")] -#[test_case(SelectionStrategy::OptimalConsolidation ; "optimal consolidation")] -#[test_case(SelectionStrategy::Random ; "random")] #[test_case(SelectionStrategy::All ; "drain")] #[tokio::test] async fn a_send_spends_the_spare_coin_and_never_the_collateral(strategy: SelectionStrategy) { @@ -162,22 +157,14 @@ async fn a_send_spends_the_spare_coin_and_never_the_collateral(strategy: Selecti let tx = send(&mut ctx, DASH, strategy).expect("the spare 5 DASH covers a 1 DASH send"); - // A drain takes every spendable coin: still only the spare one. assert_eq!(spent(&tx), vec![spare.expect("spare coin")]); } -#[test_case(SelectionStrategy::SmallestFirst ; "smallest first")] -#[test_case(SelectionStrategy::LargestFirst ; "largest first")] -#[test_case(SelectionStrategy::SmallestFirstTill(1) ; "smallest first till one")] -#[test_case(SelectionStrategy::BranchAndBound ; "branch and bound")] -#[test_case(SelectionStrategy::OptimalConsolidation ; "optimal consolidation")] -#[test_case(SelectionStrategy::Random ; "random")] -#[test_case(SelectionStrategy::All ; "drain")] #[tokio::test] -async fn a_wallet_holding_only_its_collateral_has_nothing_to_send(strategy: SelectionStrategy) { +async fn a_wallet_holding_only_its_collateral_has_nothing_to_send() { let (mut ctx, _collateral, _) = registered_wallet(None).await; - assert!(is_out_of_coins(send(&mut ctx, DASH, strategy))); + assert!(is_out_of_coins(send(&mut ctx, DASH, SelectionStrategy::LargestFirst))); assert!(ctx.managed_wallet.get_spendable_utxos().is_empty()); let balance = ctx.managed_wallet.balance(); assert_eq!(balance.spendable(), 0, "the collateral is not spendable balance"); @@ -365,24 +352,17 @@ async fn an_unconfirmed_registration_leaves_the_collateral_it_names_unlocked( /// The block that confirms a ProRegTx first seen unconfirmed locks the /// collateral it names. -#[test_case(in_mempool, block(101) ; "mempool, then a block")] -#[test_case(in_mempool, chain_locked_block(101) ; "mempool, then a chainlocked block")] -#[test_case(instant_locked, block(101) ; "instant send, then a block")] #[tokio::test] -async fn the_block_holding_a_registration_first_seen_unconfirmed_locks_its_collateral( - first: fn(&Transaction) -> TransactionContext, - mined: TransactionContext, -) { +async fn the_block_holding_a_registration_first_seen_unconfirmed_locks_its_collateral() { let mut ctx = TestWalletContext::new_random(); let collateral = receive(&mut ctx, COLLATERAL, 0x01, 100).await; let registration = registration(collateral, vec![], 0xEE); - let unconfirmed = ctx.check_transaction(®istration, first(®istration)).await; + let unconfirmed = ctx.check_transaction(®istration, TransactionContext::Mempool).await; assert!(unconfirmed.locked_outpoints.is_empty()); - let result = ctx.check_transaction(®istration, mined).await; + let result = ctx.check_transaction(®istration, block(101)).await; assert_eq!(result.locked_outpoints, vec![collateral]); - assert!(result.state_modified, "the lock set is persisted state"); assert!(ctx.bip44_account().utxos[&collateral].is_locked); assert_eq!(ctx.managed_wallet.balance().locked(), COLLATERAL); ctx.managed_wallet.update_last_processed_height(TIP); @@ -438,6 +418,23 @@ async fn unlocking_lets_a_send_spend_the_collateral_and_relocking_stops_it_again assert!(is_out_of_coins(send(&mut ctx, DASH, SelectionStrategy::LargestFirst))); } +/// Processing the block of a registration again locks its collateral again, +/// also after an `unlock_outpoint`, as Dash Core locks collaterals again when +/// it loads a wallet. Nothing else of the wallet changes on that pass, so the +/// lock alone marks the state modified. +#[tokio::test] +async fn a_rescan_of_the_registration_block_locks_an_unlocked_collateral_again() { + let (mut ctx, collateral, _) = registered_wallet(None).await; + assert!(ctx.managed_wallet.unlock_outpoint(&collateral)); + + let rescanned = + ctx.check_transaction(®istration(collateral, vec![], 0xEE), block(101)).await; + + assert_eq!(rescanned.locked_outpoints, vec![collateral]); + assert!(rescanned.state_modified, "the lock set is persisted state"); + assert_eq!(ctx.managed_wallet.balance().locked(), COLLATERAL); +} + /// Core ties the lock to the masternode list, which only spending the /// collateral leaves: a revocation keeps the masternode registered, and a new /// ProRegTx naming the same collateral replaces the registration. @@ -478,16 +475,23 @@ async fn a_revocation_or_a_replacing_registration_keeps_the_collateral_locked() } /// Only spending the collateral ends a registration. The coin leaves; its -/// entry stays and has nothing to act on, so a spend that is reorged out or -/// swept brings the coin back locked. +/// entry stays and has nothing to act on, so a spend that is reorged out +/// brings the coin back locked. So does a lock taken while the coin was +/// spent. +#[test_case(true ; "locked before the spend")] +#[test_case(false ; "locked while spent")] #[tokio::test] -async fn spending_the_collateral_removes_the_coin_but_not_its_lock() { - let (mut ctx, collateral, _) = registered_wallet(None).await; +async fn a_spent_coin_comes_back_locked_when_its_spend_is_reorged_out(locked_before: bool) { + let mut ctx = TestWalletContext::new_random(); + let coin = receive(&mut ctx, COLLATERAL, 0x01, 100).await; + if locked_before { + assert!(ctx.managed_wallet.lock_outpoint(coin)); + } let spend = Transaction { version: 1, lock_time: 0, input: vec![TxIn { - previous_output: collateral, + previous_output: coin, ..Default::default() }], output: vec![TxOut { @@ -496,12 +500,20 @@ async fn spending_the_collateral_removes_the_coin_but_not_its_lock() { }], special_transaction_payload: None, }; - assert!(ctx.check_transaction(&spend, block(150)).await.is_relevant); - - assert!(!ctx.bip44_account().utxos.contains_key(&collateral)); - assert!(ctx.managed_wallet.is_outpoint_locked(&collateral)); + assert!(!ctx.bip44_account().utxos.contains_key(&coin)); assert_eq!(ctx.managed_wallet.balance().total(), 0); + if locked_before { + assert!(ctx.managed_wallet.is_outpoint_locked(&coin), "the entry outlives the coin"); + } else { + assert!(ctx.managed_wallet.lock_outpoint(coin)); + } + + ctx.managed_wallet.truncate_above(149).expect("no chainlock above the cut"); + + assert!(ctx.bip44_account().utxos[&coin].is_locked); + assert_eq!(ctx.managed_wallet.balance().locked(), COLLATERAL); + assert_eq!(ctx.managed_wallet.balance().spendable(), 0); } #[tokio::test] @@ -549,6 +561,51 @@ async fn a_collateral_is_locked_even_before_the_next_balance_refresh() { assert!(ctx.managed_wallet.get_spendable_utxos().is_empty()); } +/// A coin locked before it arrives is locked on arrival, also when the check +/// leaves the balance refresh to its caller, as block processing does. +#[tokio::test] +async fn a_coin_locked_ahead_arrives_locked_without_a_balance_refresh() { + let mut ctx = TestWalletContext::new_random(); + let funding = Transaction::dummy(&ctx.receive_address, 0x01..0x02, &[COLLATERAL]); + let coin = OutPoint::new(funding.txid(), 0); + assert!(ctx.managed_wallet.lock_outpoint(coin)); + + ctx.managed_wallet + .check_core_transaction(&funding, block(100), &mut ctx.wallet, true, false) + .await; + + assert!(ctx.bip44_account().utxos[&coin].is_locked); + assert!(ctx.managed_wallet.get_spendable_utxos().is_empty()); +} + +/// A caller driving one account directly rebuilds the coin without the +/// wallet's lock set at hand: the coin keeps the lock flag it had. +#[tokio::test] +async fn confirming_a_transaction_on_one_account_keeps_the_coin_lock() { + let mut ctx = TestWalletContext::new_random(); + let funding = Transaction::dummy(&ctx.receive_address, 0x01..0x02, &[COLLATERAL]); + let coin = OutPoint::new(funding.txid(), 0); + let seen = ctx.check_transaction(&funding, TransactionContext::Mempool).await; + let account_match = seen.affected_accounts[0].clone(); + assert!(ctx.managed_wallet.lock_outpoint(coin)); + + let mut account = ctx + .managed_wallet + .accounts + .get_by_account_type_match_mut(&account_match.account_type_match) + .expect("BIP44 account"); + account.confirm_transaction( + &funding, + &account_match, + block(100), + TransactionRouter::classify_transaction(&funding), + ); + + let utxo = &ctx.bip44_account().utxos[&coin]; + assert!(utxo.is_confirmed, "rebuilt from the block"); + assert!(utxo.is_locked); +} + /// A confirmed coin paying `value` to the wallet, as a store hands it back on /// load; `seed` varies the outpoint. fn stored_coin(ctx: &TestWalletContext, value: u64, seed: u8) -> Utxo { @@ -710,24 +767,18 @@ async fn special_transaction_funding_skips_the_collateral_even_when_seeded() { /// Funding records the coins the account holds locked, and the build drops /// them just before coin selection, so a copy seeded after the funding call is /// dropped too. `LargestFirst` would take the 1,000 DASH collateral first. -#[test_case(false ; "seeded before funding")] -#[test_case(true ; "seeded after funding")] #[tokio::test] -async fn funding_drops_a_seeded_collateral(seeded_after_funding: bool) { +async fn funding_drops_a_collateral_seeded_after_it() { let (mut ctx, collateral, spare) = registered_wallet(Some(SPARE)).await; let stale = stale_copy(&ctx, collateral); let account = ctx.wallet.accounts.standard_bip44_accounts.get(&0).expect("BIP44").clone(); let funds = ctx.managed_wallet.accounts.standard_bip44_accounts.get_mut(&0).expect("BIP44"); - let builder = TransactionBuilder::new() + let (tx, _fee, _reservation) = TransactionBuilder::new() .set_current_height(TIP) - .set_selection_strategy(SelectionStrategy::LargestFirst); - let builder = if seeded_after_funding { - builder.add_funding(funds, &account).add_inputs([stale]) - } else { - builder.add_inputs([stale]).add_funding(funds, &account) - }; - let (tx, _fee, _reservation) = builder + .set_selection_strategy(SelectionStrategy::LargestFirst) + .add_funding(funds, &account) + .add_inputs([stale]) .add_output(&elsewhere().assume_checked(), DASH) .build_unsigned_reserved() .expect("the spare coin funds the payment"); @@ -736,36 +787,50 @@ async fn funding_drops_a_seeded_collateral(seeded_after_funding: bool) { } /// The chunked drain path offers only what the caller seeds; a seeded copy of -/// a coin the account holds locked is dropped all the same, whichever call -/// comes first. -#[test_case(false ; "seeded before funding")] -#[test_case(true ; "seeded after funding")] +/// a coin the account holds locked is dropped all the same. #[tokio::test] -async fn reservation_only_funding_drops_a_seeded_collateral(seeded_after_funding: bool) { +async fn reservation_only_funding_drops_a_collateral_seeded_after_it() { let (mut ctx, collateral, _) = registered_wallet(None).await; let stale = stale_copy(&ctx, collateral); let account = ctx.wallet.accounts.standard_bip44_accounts.get(&0).expect("BIP44").clone(); let funds = ctx.managed_wallet.accounts.standard_bip44_accounts.get_mut(&0).expect("BIP44"); - let builder = TransactionBuilder::new() + let result = TransactionBuilder::new() .set_current_height(TIP) - .set_selection_strategy(SelectionStrategy::All); - let builder = if seeded_after_funding { - builder.add_funding_reservation_only(funds, &account).add_inputs([stale]) - } else { - builder.add_inputs([stale]).add_funding_reservation_only(funds, &account) - }; - let result = builder.add_output(&elsewhere().assume_checked(), DASH).build_unsigned_reserved(); + .set_selection_strategy(SelectionStrategy::All) + .add_funding_reservation_only(funds, &account) + .add_inputs([stale]) + .add_output(&elsewhere().assume_checked(), DASH) + .build_unsigned_reserved(); assert!(matches!(result, Err(BuilderError::CoinSelection(SelectionError::NoUtxosAvailable)))); } +/// A build that takes only final coins says when coins awaiting finality +/// would fund it. A copy of the locked collateral that is not final yet is no +/// such coin. +#[tokio::test] +async fn a_locked_coin_is_not_reported_as_awaiting_finality() { + let (mut ctx, collateral, _) = registered_wallet(None).await; + let mut stale = stale_copy(&ctx, collateral); + stale.is_confirmed = false; + let account = ctx.wallet.accounts.standard_bip44_accounts.get(&0).expect("BIP44").clone(); + let funds = ctx.managed_wallet.accounts.standard_bip44_accounts.get_mut(&0).expect("BIP44"); + + let result = TransactionBuilder::new() + .set_current_height(TIP) + .add_funding(funds, &account) + .add_inputs([stale]) + .add_output(&elsewhere().assume_checked(), DASH) + .require_final_inputs() + .build_unsigned_reserved(); + + assert!(matches!(result, Err(BuilderError::CoinSelection(_))), "got {result:?}"); +} + #[cfg(feature = "serde")] #[test] fn locks_survive_a_serialization_round_trip() { - use crate::managed_account::ManagedCoreFundsAccount; - use crate::wallet::ManagedWalletInfo; - let mut info = ManagedWalletInfo::dummy(1); let mut account = ManagedCoreFundsAccount::dummy_bip44(); let collateral = Utxo::dummy(1, COLLATERAL, 100, false, true); @@ -800,8 +865,6 @@ fn locks_survive_a_serialization_round_trip() { #[cfg(feature = "serde")] #[test] fn a_snapshot_without_locks_loads_with_none() { - use crate::wallet::ManagedWalletInfo; - let mut info = ManagedWalletInfo::dummy(2); info.lock_outpoint(OutPoint::new(Txid::from_byte_array([0x42; 32]), 0)); let mut json = serde_json::to_value(&info).expect("serialize"); From d8ab1e3bad23ea517365e53e25efe227bf117a8c Mon Sep 17 00:00:00 2001 From: Bartosz Rozwarski Date: Wed, 11 Nov 2026 15:32:33 +0100 Subject: [PATCH 09/13] docs(key-wallet): say which registrations reach a wallet A ProRegTx that only names one of the wallet's coins is found by a compact-filter client through the outpoints `monitored_filter_elements` watches, and those are watched only for a wallet with provider accounts. The lock rules now say that a wallet without them is not handed such a ProRegTx and has to lock the collateral by hand. Co-Authored-By: Claude Fable 5.2 --- .../src/wallet/managed_wallet_info/locked_outpoints.rs | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/key-wallet/src/wallet/managed_wallet_info/locked_outpoints.rs b/key-wallet/src/wallet/managed_wallet_info/locked_outpoints.rs index 6b2b156f5..8d327f95e 100644 --- a/key-wallet/src/wallet/managed_wallet_info/locked_outpoints.rs +++ b/key-wallet/src/wallet/managed_wallet_info/locked_outpoints.rs @@ -71,6 +71,14 @@ impl ManagedWalletInfo { /// [`Self::unlock_outpoint`] removes an outpoint. A coin's amount is never /// a reason to lock it. /// + /// The wallet locks from the registrations it is handed. A client that + /// fetches blocks by compact filter finds a ProRegTx that only names one + /// of the wallet's coins through + /// [`WalletInfoInterface::monitored_filter_elements`], which watches held + /// outpoints only for a wallet with provider accounts. A wallet without + /// them is not handed such a ProRegTx: lock its collateral with + /// [`Self::lock_outpoint`]. + /// /// # A lock can come before its coin /// /// An entry does not need a coin behind it. A coin locked with From 418e40fb574edc10865543a17d1884ec60f6af6b Mon Sep 17 00:00:00 2001 From: Bartosz Rozwarski Date: Wed, 11 Nov 2026 16:04:08 +0100 Subject: [PATCH 10/13] feat(key-wallet-manager)!: name locked outpoints in wallet events Block and mempool processing collected the outpoints a ProRegTx locked but handed them to no one. `BlockProcessed` and `TransactionDetected` reported the balance the lock moved, not the outpoint, so a store that persists wallet state from events could not save the lock, and after a restart the collateral was spendable again. Both events gain `locked_outpoints`. `BlockProcessed` is now also emitted for a wallet whose only change in the block is a lock, such as a rescan locking again a collateral that has not arrived. Co-Authored-By: Claude Fable 5.2 --- key-wallet-manager/src/event_tests.rs | 60 ++++++++++++++++++++++++- key-wallet-manager/src/events.rs | 17 ++++++- key-wallet-manager/src/lib.rs | 10 ++--- key-wallet-manager/src/process_block.rs | 18 +++++++- 4 files changed, 94 insertions(+), 11 deletions(-) diff --git a/key-wallet-manager/src/event_tests.rs b/key-wallet-manager/src/event_tests.rs index 8599a99d9..89e0cd2e3 100644 --- a/key-wallet-manager/src/event_tests.rs +++ b/key-wallet-manager/src/event_tests.rs @@ -79,7 +79,9 @@ async fn test_mempool_tx_emits_single_event_with_balance() { balance, account_balances, addresses_derived: _, + locked_outpoints, } => { + assert!(locked_outpoints.is_empty(), "an ordinary payment locks nothing"); assert_eq!(*wid, wallet_id); assert_eq!(record.txid, tx.txid()); assert_eq!(record.context, TransactionContext::Mempool); @@ -132,7 +134,9 @@ async fn test_mempool_tx_with_instant_lock_emits_detected_event_with_locked_bala balance, account_balances, addresses_derived: _, + locked_outpoints, } => { + assert!(locked_outpoints.is_empty(), "an ordinary payment locks nothing"); assert_eq!(*wid, wallet_id); assert!(matches!(record.context, TransactionContext::InstantSend(_))); assert_eq!(balance.confirmed(), TX_AMOUNT); @@ -348,7 +352,9 @@ async fn test_block_with_new_tx_emits_inserted_record() { account_balances, addresses_derived: _, chain_lock: _, + locked_outpoints, } => { + assert!(locked_outpoints.is_empty(), "an ordinary payment locks nothing"); assert_eq!(*wid, wallet_id); assert_eq!(*height, 100); assert_eq!(inserted.len(), 1); @@ -414,7 +420,9 @@ async fn test_block_confirming_known_mempool_tx_emits_updated_record() { account_balances, addresses_derived: _, chain_lock: _, + locked_outpoints, } => { + assert!(locked_outpoints.is_empty(), "an ordinary payment locks nothing"); assert_eq!(*wid, wallet_id); assert_eq!(*height, 200); assert!(inserted.is_empty()); @@ -1396,7 +1404,8 @@ async fn manager_holding_a_coin() -> (WalletManager, WalletId, OutPoint) { /// A ProRegTx locks a collateral it names at the block that holds it, not /// from the mempool. The mempool sighting changes nothing and emits nothing; -/// the block's `BlockProcessed` carries the coin in the locked balance. +/// the block's `BlockProcessed` names the locked outpoint and carries the coin +/// in the locked balance. #[tokio::test] async fn test_registration_locks_a_named_collateral_at_its_block_not_from_the_mempool() { let (mut manager, wallet_id, collateral) = manager_holding_a_coin().await; @@ -1429,9 +1438,11 @@ async fn test_registration_locks_a_named_collateral_at_its_block_not_from_the_me updated, balance, account_balances, + locked_outpoints, .. } => { assert!(inserted.is_empty() && updated.is_empty(), "the ProRegTx records nothing"); + assert_eq!(locked_outpoints, &vec![collateral]); assert_eq!(balance.locked(), TX_AMOUNT); assert_eq!(balance.spendable(), 0); let account = account_balances.get(&bip44_account_0()).expect("the coin's account"); @@ -1461,7 +1472,8 @@ async fn test_instant_locked_registration_locks_no_collateral_it_names() { } /// A ProRegTx that creates its collateral locks it from the mempool, and the -/// `TransactionDetected` for the coin carries it in the locked balance. +/// `TransactionDetected` for the coin names the locked outpoint and carries +/// the coin in the locked balance. #[tokio::test] async fn test_mempool_registration_creating_its_collateral_emits_the_locked_balance() { let (mut manager, wallet_id, addr) = setup_manager_with_wallet(); @@ -1485,9 +1497,11 @@ async fn test_mempool_registration_creating_its_collateral_emits_the_locked_bala record, balance, account_balances, + locked_outpoints, .. } => { assert_eq!(record.txid, registration.txid()); + assert_eq!(locked_outpoints, &vec![collateral]); assert_eq!(balance.locked(), TX_AMOUNT); assert_eq!(balance.spendable(), 0, "the collateral is not spendable balance"); let account = account_balances.get(&bip44_account_0()).expect("the coin's account"); @@ -1515,6 +1529,48 @@ async fn test_check_transaction_reports_a_lock_for_a_wallet_it_is_otherwise_irre assert_eq!(result.per_wallet_locked_outpoints, BTreeMap::from([(wallet_id, vec![collateral])])); } +/// A lock that moves no balance and adds no record still reaches a persister. +/// Here a rescan locks again the collateral of the wallet's own registration, +/// a coin that has not arrived. +#[tokio::test] +async fn test_block_processed_names_a_lock_that_changes_nothing_else() { + let (mut manager, wallet_id, _addr) = setup_manager_with_wallet(); + let owner = manager + .get_wallet_info_mut(&wallet_id) + .expect("wallet info") + .provider_owner_keys_managed_account_mut() + .expect("provider owner keys account") + .next_address(None, true) + .expect("owner address"); + let owner_key_hash = *owner.payload().as_pubkey_hash().expect("P2PKH owner address"); + let collateral = OutPoint::new(Txid::from_byte_array([0xc5; 32]), 0); + let registration = + Transaction::dummy_provider_registration(collateral, owner_key_hash, Vec::new(), 0xc5); + let block = make_block(vec![registration], 0xc5, 1_001); + let wallets = BTreeSet::from([wallet_id]); + manager.process_block_for_wallets(&block, block.block_hash(), 101, &wallets).await; + let info = manager.get_wallet_info_mut(&wallet_id).expect("wallet info"); + assert!(info.unlock_outpoint(&collateral)); + let mut rx = manager.subscribe_events(); + + manager.process_block_for_wallets(&block, block.block_hash(), 101, &wallets).await; + + let events = drain_events(&mut rx); + assert_eq!(events.len(), 1, "one BlockProcessed expected, got {:?}", events); + match &events[0] { + WalletEvent::BlockProcessed { + inserted, + updated, + locked_outpoints, + .. + } => { + assert!(inserted.is_empty() && updated.is_empty(), "already recorded"); + assert_eq!(locked_outpoints, &vec![collateral]); + } + other => panic!("expected BlockProcessed, got {:?}", other), + } +} + // --------------------------------------------------------------------------- // Dry run and irrelevant paths // --------------------------------------------------------------------------- diff --git a/key-wallet-manager/src/events.rs b/key-wallet-manager/src/events.rs index 093ab0d9a..64413a1f7 100644 --- a/key-wallet-manager/src/events.rs +++ b/key-wallet-manager/src/events.rs @@ -205,6 +205,10 @@ pub enum WalletEvent { /// these rows transactionally with `record` so UTXOs landing on /// them retain a parent address row. addresses_derived: Vec, + /// Outpoints this transaction added to the wallet's lock set: the + /// collateral of a ProRegTx. A persister stores them and hands them + /// back with `ManagedWalletInfo::lock_outpoint` on load. + locked_outpoints: Vec, }, /// An InstantSend lock was applied to a previously-seen off-chain /// wallet-relevant transaction. @@ -374,6 +378,11 @@ pub enum WalletEvent { /// transactionally with the inserted/updated records so UTXOs /// landing on them retain a parent address row. addresses_derived: Vec, + /// Outpoints this block added to the wallet's lock set: the + /// collateral of each ProRegTx that locked one. A persister stores + /// them and hands them back with `ManagedWalletInfo::lock_outpoint` + /// on load. + locked_outpoints: Vec, }, /// The wallet's scan cursor advanced because the filter pipeline /// committed a batch covering blocks up to `height`. No records or @@ -478,15 +487,17 @@ impl fmt::Display for WalletEvent { balance, account_balances, addresses_derived, + locked_outpoints, .. } => write!( f, - "TransactionDetected(txid={}, context={}, balance={}, account_balances={}, derived={})", + "TransactionDetected(txid={}, context={}, balance={}, account_balances={}, derived={}, locked={})", record.txid, record.context, balance, format_account_balances(account_balances), addresses_derived.len(), + locked_outpoints.len(), ), WalletEvent::TransactionInstantLocked { txid, @@ -545,10 +556,11 @@ impl fmt::Display for WalletEvent { balance, account_balances, addresses_derived, + locked_outpoints, .. } => write!( f, - "BlockProcessed(height={}, chainlocked={}, inserted={}, updated={}, matured={}, balance={}, account_balances={}, derived={})", + "BlockProcessed(height={}, chainlocked={}, inserted={}, updated={}, matured={}, balance={}, account_balances={}, derived={}, locked={})", height, chain_lock.is_some(), inserted.len(), @@ -557,6 +569,7 @@ impl fmt::Display for WalletEvent { balance, format_account_balances(account_balances), addresses_derived.len(), + locked_outpoints.len(), ), WalletEvent::SyncHeightAdvanced { height, diff --git a/key-wallet-manager/src/lib.rs b/key-wallet-manager/src/lib.rs index 43c96186d..45e818bac 100644 --- a/key-wallet-manager/src/lib.rs +++ b/key-wallet-manager/src/lib.rs @@ -114,11 +114,11 @@ pub struct CheckTransactionsResult { /// Outpoints this check added to each wallet's lock set, grouped by /// wallet: the collateral of a ProRegTx (see /// [`ManagedWalletInfo::locked_outpoints`]). Gathered whether or not the - /// transaction is relevant to the wallet, since a ProRegTx in a block - /// locks a coin the wallet holds even when nothing else ties it to the - /// wallet. A lock moves that coin from the spendable to the locked - /// balance, so a caller that checked with `update_balance = false` - /// refreshes these wallets as well as the affected ones. + /// transaction is relevant to the wallet: a ProRegTx in a block locks a + /// coin the wallet holds even when nothing else ties it to the wallet. + /// Block and mempool processing forward them on + /// [`crate::events::WalletEvent::BlockProcessed`] and + /// [`crate::events::WalletEvent::TransactionDetected`]. pub per_wallet_locked_outpoints: BTreeMap>, } diff --git a/key-wallet-manager/src/process_block.rs b/key-wallet-manager/src/process_block.rs index ed6459010..f0c48c288 100644 --- a/key-wallet-manager/src/process_block.rs +++ b/key-wallet-manager/src/process_block.rs @@ -5,7 +5,7 @@ use async_trait::async_trait; use dashcore::ephemerealdata::chain_lock::ChainLock; use dashcore::ephemerealdata::instant_lock::InstantLock; use dashcore::prelude::CoreBlockHeight; -use dashcore::{Address, Block, BlockHash, ScriptBuf, Transaction, Txid}; +use dashcore::{Address, Block, BlockHash, OutPoint, ScriptBuf, Transaction, Txid}; use hex_conservative::DisplayHex; use key_wallet::account::AccountType; use key_wallet::managed_account::transaction_record::TransactionRecord; @@ -63,6 +63,7 @@ impl WalletInterface for WalletM let mut per_wallet_inserted: BTreeMap> = BTreeMap::new(); let mut per_wallet_updated: BTreeMap> = BTreeMap::new(); let mut per_wallet_derived: BTreeMap> = BTreeMap::new(); + let mut per_wallet_locked: BTreeMap> = BTreeMap::new(); let mut relevant_positions: BTreeMap> = BTreeMap::new(); let mut listed_txids: HashSet = HashSet::new(); @@ -105,6 +106,9 @@ impl WalletInterface for WalletM result.new_scripts.entry(wallet_id).or_default().extend(scripts); per_wallet_derived.entry(wallet_id).or_default().extend(derived); } + for (wallet_id, locked) in check_result.per_wallet_locked_outpoints { + per_wallet_locked.entry(wallet_id).or_default().extend(locked); + } for (wallet_id, records) in check_result.per_wallet_new_records { let inserted = per_wallet_inserted.entry(wallet_id).or_default(); for record in records { @@ -184,6 +188,7 @@ impl WalletInterface for WalletM per_wallet_inserted, per_wallet_updated, per_wallet_derived, + per_wallet_locked, ); result @@ -238,6 +243,7 @@ impl WalletInterface for WalletM let per_wallet_updated_records = std::mem::take(&mut check_result.per_wallet_updated_records); let mut per_wallet_derived = std::mem::take(&mut check_result.new_addresses); + let mut per_wallet_locked = std::mem::take(&mut check_result.per_wallet_locked_outpoints); for (wallet_id, records) in per_wallet_new_records { let Some(info) = self.wallet_infos.get(&wallet_id) else { @@ -265,6 +271,8 @@ impl WalletInterface for WalletM balance, account_balances: account_balances.clone(), addresses_derived: project_derived_addresses(for_record), + // Once per wallet, on its first record. + locked_outpoints: per_wallet_locked.remove(&wallet_id).unwrap_or_default(), }; self.emit_event(event); } @@ -336,6 +344,7 @@ impl WalletInterface for WalletM balance, account_balances: account_balances.clone(), addresses_derived: Vec::new(), + locked_outpoints: Vec::new(), }); } if let Some(lock) = @@ -385,7 +394,7 @@ impl WalletInterface for WalletM .unwrap_or_default() } - fn watched_outpoints(&self) -> Vec { + fn watched_outpoints(&self) -> Vec { self.watched_outpoints() } @@ -488,6 +497,7 @@ impl WalletInterface for WalletM BTreeMap::new(), BTreeMap::new(), BTreeMap::new(), + BTreeMap::new(), ); } @@ -625,6 +635,7 @@ impl WalletManager { mut per_wallet_inserted: BTreeMap>, mut per_wallet_updated: BTreeMap>, mut per_wallet_derived: BTreeMap>, + mut per_wallet_locked: BTreeMap>, ) { if wallets.is_empty() { return; @@ -691,11 +702,13 @@ impl WalletManager { project_derived_addresses(derived_for_wallet); let chain_lock = info.last_applied_chain_lock().filter(|cl| height <= cl.block_height).cloned(); + let locked_outpoints = per_wallet_locked.remove(wallet_id).unwrap_or_default(); if !inserted.is_empty() || !updated.is_empty() || !matured.is_empty() || !addresses_derived.is_empty() + || !locked_outpoints.is_empty() || balance_changed { let event = WalletEvent::BlockProcessed { @@ -708,6 +721,7 @@ impl WalletManager { balance: new_balance, account_balances, addresses_derived, + locked_outpoints, }; self.emit_event(event); } From 2b6bd7d78b2e146d411253956b25765506e4c020 Mon Sep 17 00:00:00 2001 From: Bartosz Rozwarski Date: Wed, 11 Nov 2026 16:07:31 +0100 Subject: [PATCH 11/13] fix(key-wallet): lock a collateral the wallet keeps aside as spent A rescan can hand over the block that spends a collateral before the block that funds or registers it. The wallet then keeps the coin aside as spent instead of holding it as a UTXO, so the registration found no coin to lock, and a fork that dropped the spend brought the collateral back spendable. A coin the wallet keeps aside, as spent before funded, under a recorded spend or behind a spent-output claim, now counts as held when a ProRegTx is checked. Co-Authored-By: Claude Fable 5.2 --- .../managed_core_funds_account.rs | 9 ++ .../src/tests/locked_outpoints_tests.rs | 109 +++++++++++++++--- .../managed_wallet_info/locked_outpoints.rs | 6 +- 3 files changed, 108 insertions(+), 16 deletions(-) diff --git a/key-wallet/src/managed_account/managed_core_funds_account.rs b/key-wallet/src/managed_account/managed_core_funds_account.rs index f8a1cc91b..af5b7d72e 100644 --- a/key-wallet/src/managed_account/managed_core_funds_account.rs +++ b/key-wallet/src/managed_account/managed_core_funds_account.rs @@ -219,6 +219,15 @@ impl ManagedCoreFundsAccount { self.spent_outpoints.contains(outpoint) } + /// Whether the account holds `outpoint` as a UTXO or keeps it aside as + /// spent or claimed, to take it back if that spend or claim goes away. + pub(crate) fn holds_or_keeps_aside(&self, outpoint: &OutPoint) -> bool { + self.utxos.contains_key(outpoint) + || self.spent_before_funded.contains_key(outpoint) + || self.claim_guarded_outputs.contains_key(outpoint) + || self.unsettled_spends.values().flatten().any(|utxo| utxo.outpoint == *outpoint) + } + /// Fill `claim_guarded_outputs` for a claim restored after its funding: /// the account holds the funding transaction's full record, the output /// pays one of its addresses, and the outpoint is neither in `utxos` nor diff --git a/key-wallet/src/tests/locked_outpoints_tests.rs b/key-wallet/src/tests/locked_outpoints_tests.rs index 1133cc22e..def674e0c 100644 --- a/key-wallet/src/tests/locked_outpoints_tests.rs +++ b/key-wallet/src/tests/locked_outpoints_tests.rs @@ -474,6 +474,23 @@ async fn a_revocation_or_a_replacing_registration_keeps_the_collateral_locked() assert_eq!(spent(&tx), vec![spare.expect("spare coin")]); } +/// A transaction spending `coin` to an address that is not the wallet's. +fn spend_of(coin: OutPoint) -> Transaction { + Transaction { + version: 1, + lock_time: 0, + input: vec![TxIn { + previous_output: coin, + ..Default::default() + }], + output: vec![TxOut { + value: COLLATERAL - 1_000, + script_pubkey: elsewhere().assume_checked().script_pubkey(), + }], + special_transaction_payload: None, + } +} + /// Only spending the collateral ends a registration. The coin leaves; its /// entry stays and has nothing to act on, so a spend that is reorged out /// brings the coin back locked. So does a lock taken while the coin was @@ -487,20 +504,7 @@ async fn a_spent_coin_comes_back_locked_when_its_spend_is_reorged_out(locked_bef if locked_before { assert!(ctx.managed_wallet.lock_outpoint(coin)); } - let spend = Transaction { - version: 1, - lock_time: 0, - input: vec![TxIn { - previous_output: coin, - ..Default::default() - }], - output: vec![TxOut { - value: COLLATERAL - 1_000, - script_pubkey: elsewhere().assume_checked().script_pubkey(), - }], - special_transaction_payload: None, - }; - assert!(ctx.check_transaction(&spend, block(150)).await.is_relevant); + assert!(ctx.check_transaction(&spend_of(coin), block(150)).await.is_relevant); assert!(!ctx.bip44_account().utxos.contains_key(&coin)); assert_eq!(ctx.managed_wallet.balance().total(), 0); if locked_before { @@ -561,6 +565,83 @@ async fn a_collateral_is_locked_even_before_the_next_balance_refresh() { assert!(ctx.managed_wallet.get_spendable_utxos().is_empty()); } +/// A rescan can hand over the block spending a collateral before the block +/// that funds or registers it. The wallet then keeps the coin aside as spent, +/// and the registration still locks it: a fork that drops the spend brings it +/// back locked. +#[test_case(true ; "a collateral the registration creates")] +#[test_case(false ; "a collateral the registration names")] +#[tokio::test] +async fn a_collateral_seen_spent_first_is_locked_and_comes_back_locked(creates_collateral: bool) { + let mut ctx = TestWalletContext::new_random(); + let to_wallet = TxOut { + value: COLLATERAL, + script_pubkey: ctx.receive_address.script_pubkey(), + }; + let (collateral, earlier_blocks) = if creates_collateral { + let registration = registration(OutPoint::new(Txid::all_zeros(), 0), vec![to_wallet], 0xEE); + (OutPoint::new(registration.txid(), 0), vec![(registration, 100)]) + } else { + let funding = Transaction::dummy(&ctx.receive_address, 0x01..0x02, &[COLLATERAL]); + let collateral = OutPoint::new(funding.txid(), 0); + (collateral, vec![(funding, 100), (registration(collateral, vec![], 0xEE), 101)]) + }; + ctx.check_transaction(&spend_of(collateral), block(150)).await; + + let mut reported = Vec::new(); + for (tx, height) in &earlier_blocks { + reported.extend(ctx.check_transaction(tx, block(*height)).await.locked_outpoints); + } + + assert_eq!(reported, vec![collateral]); + assert!(!ctx.bip44_account().utxos.contains_key(&collateral), "seen spent already"); + ctx.managed_wallet.truncate_above(149).expect("no chainlock above the cut"); + assert!(ctx.bip44_account().utxos[&collateral].is_locked); + assert_eq!(ctx.managed_wallet.balance().locked(), COLLATERAL); +} + +/// A coin kept aside under a spend the wallet recorded counts as held: a +/// registration processed after that spend locks it, and it comes back +/// locked when a fork drops the spend. +#[tokio::test] +async fn a_collateral_under_a_recorded_spend_is_locked_and_comes_back_locked() { + let mut ctx = TestWalletContext::new_random(); + let collateral = receive(&mut ctx, COLLATERAL, 0x01, 100).await; + assert!(ctx.check_transaction(&spend_of(collateral), block(150)).await.is_relevant); + assert!(!ctx.bip44_account().utxos.contains_key(&collateral)); + + let registered = + ctx.check_transaction(®istration(collateral, vec![], 0xEE), block(101)).await; + + assert_eq!(registered.locked_outpoints, vec![collateral]); + ctx.managed_wallet.truncate_above(149).expect("no chainlock above the cut"); + assert!(ctx.bip44_account().utxos[&collateral].is_locked); + assert_eq!(ctx.managed_wallet.balance().locked(), COLLATERAL); +} + +/// A coin a restored spent-output claim holds back counts as held too: once +/// the claim is released and the funding is processed again, the coin arrives +/// locked. +#[tokio::test] +async fn a_collateral_held_back_by_a_spent_claim_is_locked() { + let mut ctx = TestWalletContext::new_random(); + let funding = Transaction::dummy(&ctx.receive_address, 0x01..0x02, &[COLLATERAL]); + let collateral = OutPoint::new(funding.txid(), 0); + let claimant = Txid::from_byte_array([0x5c; 32]); + ctx.managed_wallet.restore_spent_outpoints(&[(collateral, Some(claimant))]); + ctx.check_transaction(&funding, block(100)).await; + assert!(!ctx.bip44_account().utxos.contains_key(&collateral)); + + let registered = + ctx.check_transaction(®istration(collateral, vec![], 0xEE), block(101)).await; + + assert_eq!(registered.locked_outpoints, vec![collateral]); + ctx.managed_wallet.abandon_transaction(claimant); + ctx.check_transaction(&funding, block(100)).await; + assert!(ctx.bip44_account().utxos[&collateral].is_locked); + assert_eq!(ctx.managed_wallet.balance().locked(), COLLATERAL); +} + /// A coin locked before it arrives is locked on arrival, also when the check /// leaves the balance refresh to its caller, as block processing does. #[tokio::test] diff --git a/key-wallet/src/wallet/managed_wallet_info/locked_outpoints.rs b/key-wallet/src/wallet/managed_wallet_info/locked_outpoints.rs index 8d327f95e..69cad70cb 100644 --- a/key-wallet/src/wallet/managed_wallet_info/locked_outpoints.rs +++ b/key-wallet/src/wallet/managed_wallet_info/locked_outpoints.rs @@ -216,12 +216,14 @@ impl ManagedWalletInfo { locks && self.locked_outpoints.insert(collateral) } - /// Whether a funds account of this wallet holds `outpoint` as a coin. + /// Whether a funds account of this wallet holds `outpoint` as a coin. A + /// coin it keeps aside as spent counts: a fork that drops the spend gives + /// it back. pub(crate) fn holds_coin(&self, outpoint: &OutPoint) -> bool { self.accounts .all_funding_accounts() .iter() - .any(|account| account.utxos.contains_key(outpoint)) + .any(|account| account.holds_or_keeps_aside(outpoint)) } /// Set the lock flag of each coin this wallet holds among `outpoints` to From 4ab7ce087aba859b9aaf966b9a244074287bf182 Mon Sep 17 00:00:00 2001 From: Bartosz Rozwarski Date: Wed, 11 Nov 2026 16:08:54 +0100 Subject: [PATCH 12/13] docs(key-wallet): cut the lock docs down to the rules The `locked_outpoints` doc ran to about a hundred lines, narrated how Dash Core ties the lock to its masternode list and repeated points made on the module, the field and the lock and unlock methods. It now states what locks an outpoint, how the lock flags follow the set and how a store persists it. The comments in `check_core_transaction` keep to three lines. Co-Authored-By: Claude Fable 5.2 --- .../transaction_checking/account_checker.rs | 12 +- .../transaction_checking/wallet_checker.rs | 20 +-- .../managed_wallet_info/locked_outpoints.rs | 149 ++++-------------- .../src/wallet/managed_wallet_info/mod.rs | 11 +- 4 files changed, 45 insertions(+), 147 deletions(-) diff --git a/key-wallet/src/transaction_checking/account_checker.rs b/key-wallet/src/transaction_checking/account_checker.rs index ab803ee07..307ff8270 100644 --- a/key-wallet/src/transaction_checking/account_checker.rs +++ b/key-wallet/src/transaction_checking/account_checker.rs @@ -99,18 +99,8 @@ pub struct TransactionCheckResult { /// crate::wallet::managed_wallet_info::helpers::WalletConflictSweep::released_outpoints pub released_outpoints: Vec, /// Outpoints this check added to the wallet's lock set: the collateral of - /// a ProRegTx, which coin selection now skips. Only new entries are - /// listed, so a ProRegTx seen again reports nothing. A collateral the - /// ProRegTx names is locked only in a block context; see + /// a ProRegTx. Filled also for an otherwise irrelevant transaction. See /// [`ManagedWalletInfo::locked_outpoints`](crate::wallet::ManagedWalletInfo::locked_outpoints). - /// - /// Filled whether or not the transaction is otherwise relevant: a - /// registration in a block may involve nothing of this wallet's but a - /// collateral it holds. A store that persists - /// wallet state records these. A lock moves a coin the wallet holds from - /// the spendable to the locked balance, so a caller that checked with - /// `update_balance = false` refreshes the balance of a wallet whose check - /// lists any, as it does for a relevant transaction. pub locked_outpoints: Vec, } diff --git a/key-wallet/src/transaction_checking/wallet_checker.rs b/key-wallet/src/transaction_checking/wallet_checker.rs index 2b5676e6c..7523d82f2 100644 --- a/key-wallet/src/transaction_checking/wallet_checker.rs +++ b/key-wallet/src/transaction_checking/wallet_checker.rs @@ -42,15 +42,9 @@ pub trait WalletTransactionChecker { /// /// The context parameter indicates where the transaction comes from (mempool, block, etc.) /// - /// With `update_state`, a ProRegTx also locks the collateral it - /// registers when that coin is this wallet's, so coin selection skips it: - /// a collateral it names once the ProRegTx is in a block, its own output - /// from any context. The ProRegTx need not be relevant for that: holding - /// the collateral is enough. New locks are listed in - /// [`TransactionCheckResult::locked_outpoints`]; with - /// `update_balance = false`, refresh the balance of a wallet whose check - /// lists any, since a lock moves a held coin to the locked balance. See - /// [`ManagedWalletInfo::locked_outpoints`]. + /// With `update_state`, a ProRegTx also locks its collateral when that + /// coin is this wallet's, and [`TransactionCheckResult::locked_outpoints`] + /// lists the new locks. See [`ManagedWalletInfo::locked_outpoints`]. async fn check_core_transaction( &mut self, tx: &Transaction, @@ -305,11 +299,9 @@ impl WalletTransactionChecker for ManagedWalletInfo { ) }); - // Bring the lock flags of the coins involved in line with the lock - // set: the coins `tx` pays this wallet, and a collateral it locked. - // A balance refresh does this too, but the one inside the check ran - // before the lock, and block processing passes - // `update_balance = false` and refreshes once per block. + // The balance refresh inside the check ran before the lock, and block + // processing passes `update_balance = false`: set the lock flags of + // the coins `tx` pays this wallet and of the collateral here. let txid = tx.txid(); let outputs = (0..tx.output.len() as u32).map(|vout| OutPoint::new(txid, vout)); let flags_changed = self.refresh_lock_flags(outputs.chain(locked)); diff --git a/key-wallet/src/wallet/managed_wallet_info/locked_outpoints.rs b/key-wallet/src/wallet/managed_wallet_info/locked_outpoints.rs index 69cad70cb..d4fba5c39 100644 --- a/key-wallet/src/wallet/managed_wallet_info/locked_outpoints.rs +++ b/key-wallet/src/wallet/managed_wallet_info/locked_outpoints.rs @@ -1,11 +1,5 @@ -//! Outpoints the wallet will not spend. -//! -//! The wallet keeps one set of locked outpoints, like Dash Core's -//! `setLockedCoins`, and coin selection never spends a coin in it. A ProRegTx -//! locks the collateral it registers when that coin is this wallet's; -//! [`ManagedWalletInfo::lock_outpoint`] and -//! [`ManagedWalletInfo::unlock_outpoint`] lock and unlock anything by hand. See -//! [`ManagedWalletInfo::locked_outpoints`] for the full rules. +//! Outpoints the wallet will not spend, like Dash Core's `setLockedCoins`. +//! See [`ManagedWalletInfo::locked_outpoints`] for the rules. use super::ManagedWalletInfo; use crate::wallet::managed_wallet_info::wallet_info_interface::WalletInfoInterface; @@ -34,115 +28,50 @@ pub(crate) fn masternode_collateral(tx: &Transaction) -> Option { impl ManagedWalletInfo { /// The outpoints this wallet will not spend. /// - /// Coin selection never picks a coin whose outpoint is in this set, for any - /// [`SelectionStrategy`](crate::wallet::managed_wallet_info::coin_selection::SelectionStrategy), - /// the `All` drain included, and such a coin counts toward - /// [`WalletCoreBalance::locked`](crate::WalletCoreBalance::locked) rather - /// than the spendable balance. + /// Coin selection skips a coin in this set whatever the strategy, and its + /// value counts as [`WalletCoreBalance::locked`](crate::WalletCoreBalance::locked). + /// Only [`Self::unlock_outpoint`] removes an outpoint. /// /// # What locks an outpoint /// - /// - A ProRegTx whose collateral is this wallet's. The wallet locks that - /// coin so an ordinary send never spends it: spending the collateral - /// would end the registration. The collateral is the ProRegTx's - /// `collateralOutpoint`, or, when that names a null txid, the ProRegTx's - /// own output at `collateralIndex`. Whether and when it is locked - /// depends on which: - /// - A collateral the ProRegTx names is locked once the ProRegTx is in a - /// block ([`TransactionContext::InBlock`] or - /// [`TransactionContext::InChainLockedBlock`]), when the wallet holds - /// the coin or the ProRegTx is relevant to the wallet: it uses the - /// wallet's keys, pays it or spends its coins. Until then it is not a - /// registration: the network may never accept it, and the wallet does - /// not check a ProRegTx's payload itself. Dash Core likewise locks such - /// a collateral once a block adds the registration to its masternode - /// list. An [`TransactionContext::InstantSend`] context counts as - /// unconfirmed here: the wallet does not verify InstantSend locks, and - /// cannot tell whether its caller did. - /// - A collateral the ProRegTx creates is locked when that output pays - /// this wallet, from its first sighting, mempool included, as the coin - /// arrives: it is the ProRegTx's own output, so the lock can hold no - /// other coin. An unconfirmed sighting does not lock that output again - /// once the wallet holds it; a block does. - /// - [`Self::lock_outpoint`]. + /// [`Self::lock_outpoint`], and a ProRegTx whose collateral is this + /// wallet's, since spending the collateral ends the registration: /// - /// A ProRegTx that involves nothing of this wallet's locks nothing, so the - /// registrations of other masternodes do not grow the set. Only - /// [`Self::unlock_outpoint`] removes an outpoint. A coin's amount is never - /// a reason to lock it. + /// - A collateral the ProRegTx creates (a null collateral txid names its + /// own output) is locked when that output pays the wallet, from the + /// first sighting, mempool included. An unconfirmed sighting does not + /// lock it again once the wallet holds it; a block does. + /// - A collateral the ProRegTx names is locked only once the ProRegTx is + /// in a block, when the wallet holds the coin or the ProRegTx is + /// relevant to the wallet. An InstantSend context counts as + /// unconfirmed: the wallet does not verify InstantSend locks. /// - /// The wallet locks from the registrations it is handed. A client that - /// fetches blocks by compact filter finds a ProRegTx that only names one - /// of the wallet's coins through - /// [`WalletInfoInterface::monitored_filter_elements`], which watches held - /// outpoints only for a wallet with provider accounts. A wallet without - /// them is not handed such a ProRegTx: lock its collateral with - /// [`Self::lock_outpoint`]. + /// Processing the block of a ProRegTx again locks its collateral again, + /// also after an unlock. A ProRegTx that involves nothing of the wallet's + /// locks nothing, so a named collateral that arrives after such a + /// ProRegTx is not locked. /// - /// # A lock can come before its coin + /// The wallet locks from the registrations it is handed. A wallet without + /// provider accounts does not watch its outpoints + /// ([`WalletInfoInterface::monitored_filter_elements`]), so a + /// compact-filter client never hands it a ProRegTx that only names one of + /// its coins. /// - /// An entry does not need a coin behind it. A coin locked with - /// [`Self::lock_outpoint`] before it arrives, arrives locked. So does a - /// collateral seen after the block holding its ProRegTx (a rescan can hand - /// over the later block first), when that ProRegTx is relevant to the - /// wallet. A relevant ProRegTx naming a coin that is not this wallet's - /// leaves an entry that never matches anything. + /// # Lock flags /// - /// A named collateral that arrives after a ProRegTx involving nothing else - /// of this wallet's is not locked: nothing told the wallet the coin would - /// be its own. Lock it with [`Self::lock_outpoint`]. - /// - /// # How long a lock lasts - /// - /// Until [`Self::unlock_outpoint`]. Dash Core ties the collateral lock to - /// its masternode list: a ProUpRevTx leaves the masternode registered, so - /// the collateral stays locked; a later ProRegTx naming the same collateral - /// replaces the registration and keeps it locked; only spending the - /// collateral ends the registration. Core then drops the lock along with - /// the coin, and re-derives it from its masternode list whenever the coin - /// could come back (on load, and when the spend is abandoned). An SPV - /// wallet has no masternode list, so it keeps the entry instead: once the - /// coin is spent the entry has nothing to act on, and a coin whose spend is - /// reorged out or swept comes back locked. - /// - /// Processing a ProRegTx in a block again (a rescan, or the block that - /// confirms a ProRegTx first seen in the mempool) locks its collateral - /// again, as Core does on load. - /// - /// # The set is the source of truth - /// - /// Coin selection works on [`Utxo`](crate::Utxo)s and skips a locked one - /// through [`Utxo::is_spendable`](crate::Utxo::is_spendable). The wallet - /// keeps the `is_locked` flag of every coin it holds equal to membership in - /// this set: when the coin arrives or is restored, when its outpoint is - /// locked or unlocked, on every balance refresh and before the wallet - /// funds a transaction. A flag written on a held coin directly is - /// overwritten by the next refresh. - /// - /// A lock or an unlock moves a held coin between the spendable and the - /// locked balance. [`Self::lock_outpoint`], [`Self::unlock_outpoint`] and a - /// transaction check with `update_balance` refresh the balance themselves; - /// a check without it leaves the refresh to its caller, which refreshes - /// every wallet whose check lists a lock in - /// [`TransactionCheckResult::locked_outpoints`](crate::transaction_checking::TransactionCheckResult::locked_outpoints). + /// An entry needs no coin behind it: a coin locked before it arrives, + /// arrives locked. The wallet sets [`Utxo::is_locked`](crate::Utxo::is_locked) + /// of every coin it holds from this set, so a flag written directly is + /// overwritten. /// /// # Persistence /// /// The set is serialized with the wallet. A store that keeps wallet state - /// some other way persists this set instead: the outpoints a transaction - /// check locks arrive on + /// another way saves the outpoints reported by /// [`TransactionCheckResult::locked_outpoints`](crate::transaction_checking::TransactionCheckResult::locked_outpoints), - /// [`Self::lock_outpoint`] and [`Self::unlock_outpoint`] report their own - /// changes, and on load the store calls [`Self::lock_outpoint`] for each - /// persisted outpoint, before or after restoring the coins with + /// [`Self::lock_outpoint`] and [`Self::unlock_outpoint`], and calls + /// [`Self::lock_outpoint`] for each on load, before or after /// [`Self::restore_utxos`]. - /// - /// [`TransactionContext::InBlock`]: - /// crate::transaction_checking::TransactionContext::InBlock - /// [`TransactionContext::InChainLockedBlock`]: - /// crate::transaction_checking::TransactionContext::InChainLockedBlock - /// [`TransactionContext::InstantSend`]: - /// crate::transaction_checking::TransactionContext::InstantSend pub fn locked_outpoints(&self) -> &BTreeSet { &self.locked_outpoints } @@ -152,12 +81,8 @@ impl ManagedWalletInfo { self.locked_outpoints.contains(outpoint) } - /// Lock `outpoint`, so coin selection does not spend it until - /// [`Self::unlock_outpoint`]. See [`Self::locked_outpoints`]. - /// - /// The wallet does not need to hold the coin yet: it arrives locked. - /// Returns `true` when the outpoint was not locked before. When the wallet - /// holds the coin, its value moves to the locked balance. + /// Lock `outpoint` and return whether it was not locked before. The + /// wallet need not hold the coin yet. See [`Self::locked_outpoints`]. pub fn lock_outpoint(&mut self, outpoint: OutPoint) -> bool { if !self.locked_outpoints.insert(outpoint) { return false; @@ -168,12 +93,8 @@ impl ManagedWalletInfo { true } - /// Unlock `outpoint`, so coin selection may spend it again. See + /// Unlock `outpoint` and return whether it was locked. See /// [`Self::locked_outpoints`]. - /// - /// Unlocking is never automatic, and a masternode collateral is unlocked - /// only here. Returns `true` when the outpoint was locked. When the wallet - /// holds the coin, its value moves back to the spendable balance. pub fn unlock_outpoint(&mut self, outpoint: &OutPoint) -> bool { if !self.locked_outpoints.remove(outpoint) { return false; diff --git a/key-wallet/src/wallet/managed_wallet_info/mod.rs b/key-wallet/src/wallet/managed_wallet_info/mod.rs index 77a4f1dad..ceb443298 100644 --- a/key-wallet/src/wallet/managed_wallet_info/mod.rs +++ b/key-wallet/src/wallet/managed_wallet_info/mod.rs @@ -149,14 +149,9 @@ pub struct ManagedWalletInfo { pub(crate) account_generation: u64, #[cfg_attr(feature = "serde", serde(skip))] pub(crate) noted_chain_lock_height: Option, - /// Outpoints the wallet will not spend: masternode collateral, and - /// anything locked by hand. The source of truth for coin locks; see - /// [`Self::locked_outpoints`] for the rules. - /// - /// `#[serde(default)]` loads a snapshot written before this field existed - /// with no locks, in self-describing formats (e.g. JSON). As with - /// `observed_spent_outpoints`, non-self-describing serde formats cannot - /// default a missing field. + /// Outpoints the wallet will not spend; see [`Self::locked_outpoints`]. + /// `serde(default)` loads a snapshot written before the field existed + /// with no locks, in self-describing formats only. #[cfg_attr(feature = "serde", serde(default))] pub(crate) locked_outpoints: BTreeSet, } From 2cdb0d6f6bc3a402a9fee475bccd59a05b8ddd8e Mon Sep 17 00:00:00 2001 From: Bartosz Rozwarski Date: Wed, 11 Nov 2026 16:19:32 +0100 Subject: [PATCH 13/13] docs(key-wallet): say a spent coin keeps its lock entry The lock docs compared the set to Dash Core's `setLockedCoins` without saying where it differs. Dash Core drops the lock when the coin is spent and derives it again from its masternode list. This wallet has no such list, so the entry stays and is what locks the coin again when a fork drops the spend. Co-Authored-By: Claude Fable 5.2 --- .../src/wallet/managed_wallet_info/locked_outpoints.rs | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/key-wallet/src/wallet/managed_wallet_info/locked_outpoints.rs b/key-wallet/src/wallet/managed_wallet_info/locked_outpoints.rs index d4fba5c39..66d35eba1 100644 --- a/key-wallet/src/wallet/managed_wallet_info/locked_outpoints.rs +++ b/key-wallet/src/wallet/managed_wallet_info/locked_outpoints.rs @@ -1,5 +1,5 @@ -//! Outpoints the wallet will not spend, like Dash Core's `setLockedCoins`. -//! See [`ManagedWalletInfo::locked_outpoints`] for the rules. +//! Outpoints the wallet will not spend. See +//! [`ManagedWalletInfo::locked_outpoints`] for the rules. use super::ManagedWalletInfo; use crate::wallet::managed_wallet_info::wallet_info_interface::WalletInfoInterface; @@ -32,6 +32,10 @@ impl ManagedWalletInfo { /// value counts as [`WalletCoreBalance::locked`](crate::WalletCoreBalance::locked). /// Only [`Self::unlock_outpoint`] removes an outpoint. /// + /// A spent coin keeps its entry, so it comes back locked when a fork + /// drops the spend. Dash Core drops the lock with the coin and derives it + /// again from its masternode list, which this wallet does not have. + /// /// # What locks an outpoint /// /// [`Self::lock_outpoint`], and a ProRegTx whose collateral is this