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 59321b177..89e0cd2e3 100644 --- a/key-wallet-manager/src/event_tests.rs +++ b/key-wallet-manager/src/event_tests.rs @@ -11,17 +11,17 @@ use dashcore::ephemerealdata::instant_lock::InstantLock; use dashcore::hash_types::CycleHash; 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 { @@ -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()); @@ -1365,6 +1373,204 @@ 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 owner_key_hash = PubkeyHash::from_byte_array([0x70; 20]); + Transaction::dummy_provider_registration(collateral, owner_key_hash, outputs, seed) +} + +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` 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; + 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, + 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"); + 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 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(); + 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, + 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"); + 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])])); +} + +/// 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 13b6405d8..45e818bac 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: 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>, } 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..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); } 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..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 @@ -358,9 +367,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..def674e0c --- /dev/null +++ b/key-wallet/src/tests/locked_outpoints_tests.rs @@ -0,0 +1,957 @@ +//! 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_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::BLSSignature; +use dashcore::ephemerealdata::instant_lock::InstantLock; +use dashcore::hash_types::InputsHash; +use dashcore::{ + Address, BlockHash, OutPoint, PubkeyHash, ScriptBuf, Transaction, TxIn, TxOut, Txid, +}; +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, +}; +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; +#[cfg(feature = "serde")] +use crate::wallet::ManagedWalletInfo; +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, + )) +} + +/// 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") +} + +/// 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 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. +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, + .. + } + )) + ) +} + +/// 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::BranchAndBound ; "branch and bound")] +#[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"); + + assert_eq!(spent(&tx), vec![spare.expect("spare coin")]); +} + +#[tokio::test] +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, 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"); + 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()); +} + +/// 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 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 = 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 { + 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, "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"); + 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))); +} + +/// 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")] +#[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))); +} + +/// 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. +#[tokio::test] +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, TransactionContext::Mempool).await; + assert!(unconfirmed.locked_outpoints.is_empty()); + + let result = ctx.check_transaction(®istration, block(101)).await; + + assert_eq!(result.locked_outpoints, vec![collateral]); + 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; + 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))); +} + +/// 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. +#[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")]); +} + +/// 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 +/// spent. +#[test_case(true ; "locked before the spend")] +#[test_case(false ; "locked while spent")] +#[tokio::test] +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)); + } + 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 { + 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] +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()); +} + +/// 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] +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 { + 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.insert(collateral.outpoint, collateral); + account.utxos.insert(spare.outpoint, spare.clone()); + + let tx = send(&mut ctx, DASH, SelectionStrategy::LargestFirst).expect("the spare coin"); + + assert_eq!(spent(&tx), vec![spare.outpoint]); +} + +#[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(), + "127.0.0.1:19999".parse().expect("socket address"), + 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")]); +} + +/// 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. +#[tokio::test] +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 (tx, _fee, _reservation) = TransactionBuilder::new() + .set_current_height(TIP) + .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"); + + 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_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 result = TransactionBuilder::new() + .set_current_height(TIP) + .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() { + 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() { + 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/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/transaction_checking/account_checker.rs b/key-wallet/src/transaction_checking/account_checker.rs index 7b484c219..307ff8270 100644 --- a/key-wallet/src/transaction_checking/account_checker.rs +++ b/key-wallet/src/transaction_checking/account_checker.rs @@ -98,6 +98,10 @@ 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. Filled also for an otherwise irrelevant transaction. 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 +462,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..7523d82f2 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}; @@ -41,6 +42,9 @@ pub trait WalletTransactionChecker { /// /// The context parameter indicates where the transaction comes from (mempool, block, etc.) /// + /// 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, @@ -268,6 +272,64 @@ 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; + } + + 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, + ) + }); + + // 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)); + + if let Some(collateral) = locked { + 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..66d35eba1 --- /dev/null +++ b/key-wallet/src/wallet/managed_wallet_info/locked_outpoints.rs @@ -0,0 +1,235 @@ +//! 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; +use dashcore::blockdata::transaction::special_transaction::TransactionPayload; +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 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. + /// + /// 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 + /// wallet's, since spending the collateral ends the registration: + /// + /// - 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. + /// + /// 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. + /// + /// 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. + /// + /// # Lock flags + /// + /// 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 + /// another way saves the outpoints reported by + /// [`TransactionCheckResult::locked_outpoints`](crate::transaction_checking::TransactionCheckResult::locked_outpoints), + /// [`Self::lock_outpoint`] and [`Self::unlock_outpoint`], and calls + /// [`Self::lock_outpoint`] for each on load, before or after + /// [`Self::restore_utxos`]. + 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` 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; + } + if self.refresh_lock_flags([outpoint]) { + self.update_balance(); + } + true + } + + /// Unlock `outpoint` and return whether it was locked. See + /// [`Self::locked_outpoints`]. + 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 `collateral`, the collateral of the ProRegTx `tx`, when it is + /// this wallet's to keep. See [`Self::locked_outpoints`] for the rule. + /// + /// 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, + 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. 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.holds_or_keeps_aside(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. + 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 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() { + for utxo in account.utxos.values_mut() { + utxo.is_locked = locked.contains(&utxo.outpoint); + } + } + } +} + +#[cfg(test)] +mod tests { + use super::masternode_collateral; + 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 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] + 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..ceb443298 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; +pub(crate) mod locked_outpoints; pub mod managed_account_operations; pub mod managed_accounts; pub mod transaction_builder; @@ -148,6 +149,11 @@ 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; 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, } /// Serde adapter for [`ManagedWalletInfo::observed_spent_outpoints`] that @@ -255,6 +261,7 @@ impl ManagedWalletInfo { spent_claims: BTreeMap::new(), account_generation: 0, noted_chain_lock_height: None, + locked_outpoints: BTreeSet::new(), } } @@ -273,6 +280,7 @@ impl ManagedWalletInfo { spent_claims: BTreeMap::new(), account_generation: 0, noted_chain_lock_height: None, + locked_outpoints: BTreeSet::new(), } } @@ -301,6 +309,7 @@ impl ManagedWalletInfo { spent_claims: BTreeMap::new(), account_generation: 0, noted_chain_lock_height: None, + locked_outpoints: BTreeSet::new(), } } @@ -450,7 +459,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 @@ -503,12 +514,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 { @@ -525,6 +538,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_builder.rs b/key-wallet/src/wallet/managed_wallet_info/transaction_builder.rs index 7465b6bdd..40269f59d 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 `prepare`. + locked: HashSet, } impl Default for TransactionBuilder { @@ -117,6 +122,7 @@ impl TransactionBuilder { special_payload: None, payload_finalizer: None, funding: Vec::new(), + locked: HashSet::new(), } } @@ -142,7 +148,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 +185,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 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, @@ -211,6 +220,12 @@ impl TransactionBuilder { // concurrent build to select. let mut owned: HashSet = HashSet::new(); for utxo in funds_acc.utxos.values() { + // `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); + } if reserved.contains(&utxo.outpoint) { continue; } @@ -235,6 +250,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 @@ -520,6 +540,7 @@ impl TransactionBuilder { special_payload: self.special_payload.clone(), payload_finalizer: None, funding: self.funding.clone(), + locked: self.locked.clone(), } } @@ -556,17 +577,21 @@ 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 - // into the builder can spend an outpoint another in-flight build - // holds. + // 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 .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. 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 { 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();