diff --git a/dash-spv/src/client/lifecycle.rs b/dash-spv/src/client/lifecycle.rs index 50abaf180..beb59d118 100644 --- a/dash-spv/src/client/lifecycle.rs +++ b/dash-spv/src/client/lifecycle.rs @@ -179,12 +179,12 @@ impl DashSpvClient { // Build mempool manager if tracking is enabled if config.enable_mempool_tracking { - let initial_revision = wallet.read().await.monitor_revision(); + let initial_hash = wallet.read().await.monitor_hash(); managers.mempool = Some(MempoolManager::new( wallet.clone(), config.mempool_strategy, config.max_mempool_transactions, - initial_revision, + initial_hash, config.broadcast_config(), )); } diff --git a/dash-spv/src/sync/mempool/manager.rs b/dash-spv/src/sync/mempool/manager.rs index 26ce50d72..69d667cec 100644 --- a/dash-spv/src/sync/mempool/manager.rs +++ b/dash-spv/src/sync/mempool/manager.rs @@ -59,7 +59,7 @@ pub(crate) struct MempoolManager { /// Self-broadcast transactions and their network-acceptance state. pub(super) broadcasts: HashMap, broadcast_config: BroadcastConfig, - strategy: MempoolStrategy, + pub(super) strategy: MempoolStrategy, max_transactions: usize, /// Txids we have requested via getdata but not yet received, with request time. pending_requests: HashMap, @@ -71,9 +71,9 @@ pub(crate) struct MempoolManager { /// Prevents duplicate downloads when multiple peers announce the same transactions. /// Entries expire after `SEEN_TXID_EXPIRY`. seen_txids: HashMap, - /// Wallet monitor revision at the time of the last filter build. + /// Wallet monitor hash at the time of the last filter build. /// Compared on each tick to detect when the wallet's monitored set has changed. - pub(super) last_monitor_revision: u64, + pub(super) last_monitor_hash: u64, } impl MempoolManager { @@ -83,7 +83,7 @@ impl MempoolManager { wallet: Arc>, strategy: MempoolStrategy, max_transactions: usize, - initial_monitor_revision: u64, + initial_monitor_hash: u64, broadcast_config: BroadcastConfig, ) -> Self { Self { @@ -98,7 +98,7 @@ impl MempoolManager { peers: HashMap::new(), pending_is_locks: HashMap::new(), seen_txids: HashMap::new(), - last_monitor_revision: initial_monitor_revision, + last_monitor_hash: initial_monitor_hash, } } @@ -136,6 +136,7 @@ impl MempoolManager { &mut self, network: &Arc, ) -> SyncResult<()> { + self.last_monitor_hash = self.wallet.read().await.monitor_hash(); let inactive: Vec = self.peers.iter().filter(|(_, v)| v.is_none()).map(|(k, _)| *k).collect(); for peer in inactive { diff --git a/dash-spv/src/sync/mempool/sync_manager.rs b/dash-spv/src/sync/mempool/sync_manager.rs index 0d0978c99..2ad7ce33e 100644 --- a/dash-spv/src/sync/mempool/sync_manager.rs +++ b/dash-spv/src/sync/mempool/sync_manager.rs @@ -1,4 +1,5 @@ use super::manager::MEMPOOL_TX_EXPIRY; +use crate::client::config::MempoolStrategy; use crate::error::SyncResult; use crate::network::{InboundMessage, MessageType, NetworkEvent, NetworkManager}; use crate::sync::{ @@ -123,7 +124,7 @@ impl SyncManager for MempoolManager { .. } => { // Remove confirmed transactions from mempool. - // Bloom filter rebuild is handled by the tick's revision check. + // Bloom filter rebuild is handled by the tick's monitor hash check. if !confirmed_txids.is_empty() { return Ok(self.remove_confirmed(confirmed_txids)); } @@ -158,19 +159,15 @@ impl SyncManager for MempoolManager { // Rebuild bloom filter if the wallet's monitored set has changed. // - // We poll the revision counter rather than using push-based wallet events - // for simplicity: the revision lives on `ManagedCoreFundsAccount` and auto-bumps - // on address generation and UTXO mutations, giving us a single source of - // truth without needing event emission after every wallet operation. - // Adding a push-based approach would require a new `select!` branch in the - // shared `SyncManager::run` loop or a `WalletEvent` bridge — complexity - // that isn't justified given the 100ms tick latency is negligible for bloom - // filter rebuilds and the read lock is non-contending. - let current_revision = self.wallet.read().await.monitor_revision(); - if current_revision != self.last_monitor_revision { - tracing::info!("Wallet monitor revision changed, rebuilding bloom filter"); - self.rebuild_filter(network).await?; - self.last_monitor_revision = current_revision; + // The hash covers exactly what the filter is built from, so polling it + // catches every change without the wallet having to signal one. + if self.strategy == MempoolStrategy::BloomFilter { + let current_hash = self.wallet.read().await.monitor_hash(); + if current_hash != self.last_monitor_hash { + tracing::info!("Wallet monitored set changed, rebuilding bloom filter"); + self.rebuild_filter(network).await?; + self.last_monitor_hash = current_hash; + } } Ok(events) @@ -184,7 +181,6 @@ impl SyncManager for MempoolManager { #[cfg(test)] mod tests { use super::*; - use crate::client::config::MempoolStrategy; use crate::sync::BroadcastConfig; use crate::test_utils::{test_socket_address, MockNetworkManager}; use key_wallet_manager::test_utils::MockWallet; @@ -762,7 +758,7 @@ mod tests { network_mock.clear_sent().await; // BlockProcessed does not eagerly rebuild — the tick handles it via - // the revision check. Verify no FilterLoad is sent from the event handler. + // the monitor hash check. Verify no FilterLoad is sent from the event handler. let event = SyncEvent::BlockProcessed { block_hash: dashcore::BlockHash::all_zeros(), height: 1001, @@ -803,7 +799,7 @@ mod tests { } #[tokio::test] - async fn test_tick_rebuilds_filter_when_monitor_revision_changes() { + async fn test_tick_rebuilds_filter_when_monitor_hash_changes() { let addr = { let script = dashcore::ScriptBuf::from_bytes(vec![ 0x76, 0xa9, 0x14, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab, @@ -814,7 +810,7 @@ mod tests { let mut mock = MockWallet::new(); mock.set_addresses(vec![addr.clone()]); - let initial_revision = mock.monitor_revision(); + let initial_hash = mock.monitor_hash(); let wallet = Arc::new(RwLock::new(mock)); let network_mock = Arc::new(MockNetworkManager::new()); let network: Arc = network_mock.clone(); @@ -823,14 +819,27 @@ mod tests { wallet.clone(), MempoolStrategy::BloomFilter, 1000, - initial_revision, + initial_hash, BroadcastConfig::default(), ); let peer = test_socket_address(1); manager.handle_peer_connected(peer); - // Activate — this snapshots the monitor revision + // Sync discovers addresses before the filters complete + { + let sync_addr = dashcore::Address::from_script( + &dashcore::ScriptBuf::from_bytes(vec![ + 0x76, 0xa9, 0x14, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, + 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0x88, 0xac, + ]), + dashcore::Network::Testnet, + ) + .unwrap(); + wallet.write().await.set_addresses(vec![addr.clone(), sync_addr]); + } + + // Activate — this snapshots the monitor hash let sync = SyncEvent::FiltersSyncComplete { tip_height: 1000, }; @@ -840,14 +849,14 @@ mod tests { // Drain activation messages network_mock.clear_sent().await; - // tick with unchanged revision should not rebuild + // tick with unchanged hash should not rebuild manager.tick(&network).await.unwrap(); assert!( network_mock.sent_to_messages().await.is_empty(), - "no messages expected when revision unchanged" + "no messages expected when hash unchanged" ); - // Simulate wallet adding new addresses (bumps revision) + // Simulate wallet adding new addresses (changes the monitor hash) { let mut w = wallet.write().await; let addr2 = dashcore::Address::from_script( @@ -870,14 +879,14 @@ mod tests { found_filter_load = true; } } - assert!(found_filter_load, "expected FilterLoad after monitor revision change"); + assert!(found_filter_load, "expected FilterLoad after monitor hash change"); - // Subsequent tick should not rebuild again (revision was snapshotted) + // Subsequent tick should not rebuild again (hash was snapshotted) network_mock.clear_sent().await; manager.tick(&network).await.unwrap(); assert!( network_mock.sent_to_messages().await.is_empty(), - "no messages expected after revision re-snapshot" + "no messages expected after hash re-snapshot" ); } @@ -904,7 +913,7 @@ mod tests { manager.handle_sync_event(&sync, &network).await.unwrap(); network_mock.clear_sent().await; - // Bump revision + // Change the monitored set { let mut w = wallet.write().await; w.set_addresses(vec![dashcore::Address::dummy(dashcore::Network::Testnet, 0)]); @@ -918,7 +927,7 @@ mod tests { found_filter = true; } } - assert!(!found_filter, "FetchAll should not send filter messages on revision change"); + assert!(!found_filter, "FetchAll should not send filter messages on monitor hash change"); } #[tokio::test] @@ -933,7 +942,7 @@ mod tests { let mut mock = MockWallet::new(); mock.set_addresses(vec![addr]); - let initial_revision = mock.monitor_revision(); + let initial_hash = mock.monitor_hash(); let wallet = Arc::new(RwLock::new(mock)); let network_mock = Arc::new(MockNetworkManager::new()); let network: Arc = network_mock.clone(); @@ -942,7 +951,7 @@ mod tests { wallet.clone(), MempoolStrategy::BloomFilter, 1000, - initial_revision, + initial_hash, BroadcastConfig::default(), ); @@ -964,7 +973,7 @@ mod tests { }]); } - // tick should detect the revision change and rebuild + // tick should detect the monitor hash change and rebuild manager.tick(&network).await.unwrap(); let found_filter_load = network_mock @@ -985,7 +994,7 @@ mod tests { ]); let addr = dashcore::Address::from_script(&script, dashcore::Network::Testnet).unwrap(); mock.set_addresses(vec![addr]); - let initial_revision = mock.monitor_revision(); + let initial_hash = mock.monitor_hash(); let wallet = Arc::new(RwLock::new(mock)); let network_mock = Arc::new(MockNetworkManager::new()); let network: Arc = network_mock.clone(); @@ -994,7 +1003,7 @@ mod tests { wallet.clone(), MempoolStrategy::BloomFilter, 1000, - initial_revision, + initial_hash, BroadcastConfig::default(), ); @@ -1024,8 +1033,7 @@ mod tests { .any(|(_, msg)| matches!(msg, NetworkMessage::FilterLoad(_))); assert!(!has_filter_load, "handle_tx should not eagerly rebuild filter"); - // But the next tick should catch it if the wallet revision changed - // (MockWallet bumps revision when set_mempool_relevant triggers processing) + // But the next tick should catch it if the monitored set changed { let mut w = wallet.write().await; w.set_addresses(vec![dashcore::Address::dummy(dashcore::Network::Testnet, 0)]); @@ -1037,6 +1045,6 @@ mod tests { .await .into_iter() .any(|(_, msg)| matches!(msg, NetworkMessage::FilterLoad(_))); - assert!(found_filter_load, "tick should rebuild after revision change"); + assert!(found_filter_load, "tick should rebuild after the monitored set changed"); } } diff --git a/key-wallet-manager/src/accessors.rs b/key-wallet-manager/src/accessors.rs index a35c10acc..a2a076834 100644 --- a/key-wallet-manager/src/accessors.rs +++ b/key-wallet-manager/src/accessors.rs @@ -59,7 +59,7 @@ impl WalletManager { /// Insert a pre-built wallet and info pair. /// /// Errors with [`WalletError::WalletExists`] if a wallet with the same ID is - /// already registered. On success bumps the structural revision. + /// already registered. pub fn insert_wallet(&mut self, wallet: Wallet, info: T) -> Result { let wallet_id = wallet.compute_wallet_id(); if self.wallets.contains_key(&wallet_id) { @@ -67,7 +67,6 @@ impl WalletManager { } self.wallets.insert(wallet_id, wallet); self.wallet_infos.insert(wallet_id, info); - self.bump_structural_revision(); Ok(wallet_id) } @@ -77,9 +76,6 @@ impl WalletManager { self.wallets.remove(wallet_id).ok_or(WalletError::WalletNotFound(*wallet_id))?; let info = self.wallet_infos.remove(wallet_id).ok_or(WalletError::WalletNotFound(*wallet_id))?; - // Absorb the removed wallet's account-level revision so the total - // stays monotonically increasing even though we lost a contributor. - self.structural_revision += info.monitor_revision() + 1; Ok((wallet, info)) } @@ -246,12 +242,6 @@ impl WalletManager { Some(receiver) } - /// Return the total monitor revision (structural + per-wallet account revisions). - pub fn monitor_revision(&self) -> u64 { - self.structural_revision - + self.wallet_infos.values().map(|w| w.monitor_revision()).sum::() - } - /// Snapshot the current balance of every managed wallet. pub(crate) fn snapshot_balances(&self) -> BTreeMap { self.wallet_infos.iter().map(|(id, info)| (*id, info.balance())).collect() diff --git a/key-wallet-manager/src/lib.rs b/key-wallet-manager/src/lib.rs index 45e818bac..491ab08f5 100644 --- a/key-wallet-manager/src/lib.rs +++ b/key-wallet-manager/src/lib.rs @@ -149,10 +149,6 @@ pub struct WalletManager, /// Mutable wallet info indexed by wallet ID wallet_infos: BTreeMap, - /// Structural revision counter incremented when wallets or accounts are - /// added/removed. Combined with per-wallet account-level revisions to - /// produce the total monitor revision. - structural_revision: u64, /// Event sender for wallet events. /// /// This is a *bounded, lossy* fan-out (capacity @@ -221,7 +217,6 @@ impl WalletManager { network, wallets: BTreeMap::new(), wallet_infos: BTreeMap::new(), - structural_revision: 0, event_sender: broadcast::Sender::new(DEFAULT_WALLET_EVENT_CAPACITY), // Persistence delivery is opt-in; the channel is created lazily when // a consumer calls `take_persistence_receiver`. See that field's docs. @@ -274,11 +269,6 @@ impl WalletManager { let _ = self.event_sender.send(event); } - /// Increment the structural revision for wallet/account additions or removals. - fn bump_structural_revision(&mut self) { - self.structural_revision += 1; - } - /// Create a new wallet from mnemonic and add it to the manager. /// The mnemonic may be in any supported BIP-39 language (detected /// automatically). Returns the computed wallet ID. @@ -315,7 +305,6 @@ impl WalletManager { self.wallets.insert(wallet_id, wallet_mut); self.wallet_infos.insert(wallet_id, managed_info); - self.bump_structural_revision(); Ok(wallet_id) } @@ -398,7 +387,6 @@ impl WalletManager { self.wallets.insert(wallet_id, final_wallet); self.wallet_infos.insert(wallet_id, managed_info); - self.bump_structural_revision(); Ok((serialized_bytes, wallet_id)) } @@ -431,7 +419,6 @@ impl WalletManager { self.wallets.insert(wallet_id, wallet); self.wallet_infos.insert(wallet_id, managed_info); - self.bump_structural_revision(); Ok(wallet_id) } @@ -472,7 +459,6 @@ impl WalletManager { self.wallets.insert(wallet_id, wallet); self.wallet_infos.insert(wallet_id, managed_info); - self.bump_structural_revision(); Ok(wallet_id) } @@ -520,7 +506,6 @@ impl WalletManager { self.wallets.insert(wallet_id, wallet); self.wallet_infos.insert(wallet_id, managed_info); - self.bump_structural_revision(); Ok(wallet_id) } @@ -568,7 +553,6 @@ impl WalletManager { self.wallets.insert(wallet_id, wallet); self.wallet_infos.insert(wallet_id, managed_info); - self.bump_structural_revision(); Ok(wallet_id) } @@ -709,7 +693,6 @@ impl WalletManager { .add_account(account_type, account_xpub) .map_err(|e| WalletError::AccountCreation(e.to_string()))?; - self.bump_structural_revision(); Ok(()) } } diff --git a/key-wallet-manager/src/process_block.rs b/key-wallet-manager/src/process_block.rs index f0c48c288..dd54d5ec2 100644 --- a/key-wallet-manager/src/process_block.rs +++ b/key-wallet-manager/src/process_block.rs @@ -398,10 +398,6 @@ impl WalletInterface for WalletM self.watched_outpoints() } - fn monitor_revision(&self) -> u64 { - self.monitor_revision() - } - async fn earliest_required_height(&self) -> CoreBlockHeight { self.wallet_infos.values().map(|info| info.birth_height()).min().unwrap_or(0) } @@ -742,12 +738,10 @@ mod tests { BlockHash, Network, OutPoint, ScriptBuf, TxIn, TxMerkleNode, TxOut, Txid, Witness, }; use key_wallet::account::ManagedAccountTrait as _; - use key_wallet::account::StandardAccountType; use key_wallet::gap_limit::DEFAULT_COINJOIN_GAP_LIMIT; use key_wallet::managed_account::address_pool::AddressPoolType; use key_wallet::mnemonic::Language; use key_wallet::wallet::initialization::WalletAccountCreationOptions; - use key_wallet::wallet::managed_wallet_info::transaction_building::AccountTypePreference; use key_wallet::wallet::managed_wallet_info::ManagedWalletInfo; use key_wallet::{AccountType, Mnemonic}; use std::collections::HashMap; @@ -1240,103 +1234,55 @@ mod tests { } #[tokio::test] - async fn test_monitor_revision_bumps_and_stability() { + async fn test_monitor_hash_follows_the_filter_contents() { let mut manager: WalletManager = WalletManager::new(Network::Testnet); - let mut expected_rev = 0u64; - assert_eq!(manager.monitor_revision(), expected_rev); + let empty = manager.monitor_hash(); - // create_wallet_from_mnemonic bumps let wallet_id = manager .create_wallet_from_mnemonic(TEST_MNEMONIC, 0, WalletAccountCreationOptions::Default) .unwrap(); - expected_rev += 1; - assert_eq!(manager.monitor_revision(), expected_rev, "after create_wallet_from_mnemonic"); + let after_wallet = manager.monitor_hash(); + assert_ne!(after_wallet, empty, "after create_wallet_from_mnemonic"); - // create_account bumps - manager - .create_account( - &wallet_id, - AccountType::Standard { - index: 1, - standard_account_type: StandardAccountType::BIP44Account, - }, - None, - ) - .unwrap(); - expected_rev += 1; - assert_eq!(manager.monitor_revision(), expected_rev, "after create_account"); - - // get_receive_address bumps (when address is generated) - let address = - manager.next_receive_address(&wallet_id, 0, AccountTypePreference::BIP44, true); - if address.is_some() { - expected_rev += 1; - assert_eq!(manager.monitor_revision(), expected_rev, "after get_receive_address"); - } - - // get_change_address bumps (when address is generated) - let address = - manager.next_change_address(&wallet_id, 0, AccountTypePreference::BIP44, true); - if address.is_some() { - expected_rev += 1; - assert_eq!(manager.monitor_revision(), expected_rev, "after get_change_address"); - } - - // `update_wallet_last_processed_height` does not bump the monitor revision. manager.update_wallet_last_processed_height(&wallet_id, 1000); assert_eq!( - manager.monitor_revision(), - expected_rev, + manager.monitor_hash(), + after_wallet, "after update_wallet_last_processed_height" ); - // process_mempool_transaction bumps from UTXO changes and possibly - // new addresses generated via gap limit maintenance - let rev_before_mempool = manager.monitor_revision(); + let (wallet, info) = manager.get_wallet_and_info_mut(&wallet_id).unwrap(); + let account = info.first_bip44_managed_account_mut().unwrap(); + let key_source = + wallet.key_source_for_account(account.managed_account_type().to_account_type()); + let gap_limit = account.external_gap_limit().unwrap(); + let generated = account.set_gap_limit(gap_limit + 1, &key_source).unwrap(); + assert!(!generated.is_empty()); + let after_generation = manager.monitor_hash(); + assert_ne!(after_generation, after_wallet, "generating addresses changes the hash"); + let addr = manager.monitored_addresses()[0].clone(); let tx = create_tx_paying_to(&addr, 0xd0); let _result = manager.process_mempool_transaction(&tx, None).await; - assert!( - manager.monitor_revision() > rev_before_mempool, - "mempool tx paying to our address should bump revision (UTXO added)" - ); - let rev_after_mempool = manager.monitor_revision(); + let after_mempool = manager.monitor_hash(); + assert_ne!(after_mempool, after_generation, "mempool tx paying to our address adds a UTXO"); - // process_instant_send_lock does NOT bump (no outpoint set change) manager.process_instant_send_lock(dummy_instant_lock(tx.txid())); - assert_eq!( - manager.monitor_revision(), - rev_after_mempool, - "after process_instant_send_lock" - ); + assert_eq!(manager.monitor_hash(), after_mempool, "after process_instant_send_lock"); - // process_block_for_wallets bumps from UTXO changes and possibly new addresses - let rev_before_block = manager.monitor_revision(); let tx2 = create_tx_paying_to(&addr, 0xd1); let block = make_block(vec![tx2]); let block_wallets = BTreeSet::from([wallet_id]); let _result = manager .process_block_for_wallets(&block, block.block_hash(), 100, &block_wallets) .await; - assert!( - manager.monitor_revision() > rev_before_block, - "block with tx paying to our address should bump revision (UTXO added)" + let after_block = manager.monitor_hash(); + assert_ne!( + after_block, after_mempool, + "block paying to an already used address adds a UTXO" ); - // remove_wallet absorbs the wallet's account-level revision + 1 - let rev_before_remove = manager.monitor_revision(); manager.remove_wallet(&wallet_id).unwrap(); - assert!( - manager.monitor_revision() > rev_before_remove, - "remove_wallet should bump revision" - ); - - // create_wallet_with_random_mnemonic bumps structural revision - let rev_before = manager.monitor_revision(); - manager.create_wallet_with_random_mnemonic(WalletAccountCreationOptions::Default).unwrap(); - assert!( - manager.monitor_revision() > rev_before, - "create_wallet_with_random_mnemonic should bump revision" - ); + assert_eq!(manager.monitor_hash(), empty, "after remove_wallet"); } } diff --git a/key-wallet-manager/src/test_utils/mock_wallet.rs b/key-wallet-manager/src/test_utils/mock_wallet.rs index 93cafe34c..7480aef29 100644 --- a/key-wallet-manager/src/test_utils/mock_wallet.rs +++ b/key-wallet-manager/src/test_utils/mock_wallet.rs @@ -42,8 +42,6 @@ pub struct MockWallet { /// Captured `InstantLock` payloads from both `process_mempool_transaction` and /// `process_instant_send_lock`, for test assertions. pub processed_instant_locks: InstantLockCaptures, - /// Monitor revision counter for staleness detection. - monitor_revision: u64, reapply_heights: BTreeMap>, /// Addresses the wallet derives the first time it processes each height. derived_addresses: BTreeMap>, @@ -73,7 +71,6 @@ impl MockWallet { mempool_new_addresses: Vec::new(), status_changes: Arc::new(Mutex::new(Vec::new())), processed_instant_locks: Arc::new(Mutex::new(Vec::new())), - monitor_revision: 0, reapply_heights: BTreeMap::new(), derived_addresses: BTreeMap::new(), } @@ -102,13 +99,11 @@ impl MockWallet { /// Set the addresses returned by monitored_addresses. pub fn set_addresses(&mut self, addresses: Vec
) { self.addresses = addresses; - self.monitor_revision += 1; } /// Set the outpoints returned by watched_outpoints. pub fn set_outpoints(&mut self, outpoints: Vec) { self.outpoints = outpoints; - self.monitor_revision += 1; } /// Set the net amount returned by process_mempool_transaction. @@ -161,7 +156,6 @@ impl WalletInterface for MockWallet { .collect(); let mut new_scripts = BTreeMap::new(); if !derived.is_empty() { - self.monitor_revision += 1; new_scripts .insert(self.wallet_id, derived.iter().map(Address::script_pubkey).collect()); self.addresses.extend(derived); @@ -274,10 +268,6 @@ impl WalletInterface for MockWallet { } } - fn monitor_revision(&self) -> u64 { - self.monitor_revision - } - fn subscribe_events(&self) -> broadcast::Receiver { self.event_sender.subscribe() } diff --git a/key-wallet-manager/src/wallet_interface.rs b/key-wallet-manager/src/wallet_interface.rs index 7941a2cc3..f2d60498b 100644 --- a/key-wallet-manager/src/wallet_interface.rs +++ b/key-wallet-manager/src/wallet_interface.rs @@ -8,7 +8,9 @@ use dashcore::ephemerealdata::chain_lock::ChainLock; use dashcore::ephemerealdata::instant_lock::InstantLock; use dashcore::prelude::CoreBlockHeight; use dashcore::{Address, Block, BlockHash, OutPoint, ScriptBuf, Transaction, Txid}; +use std::collections::hash_map::DefaultHasher; use std::collections::{BTreeMap, BTreeSet}; +use std::hash::{Hash, Hasher}; use tokio::sync::broadcast; /// Result of processing a block through the wallet @@ -191,11 +193,14 @@ pub trait WalletInterface: Send + Sync + 'static { height: CoreBlockHeight, ); - /// Return a revision counter that increments whenever the set of monitored - /// addresses or watched outpoints changes. The mempool manager uses this to - /// detect when its bloom filter is stale without requiring an external signal. - fn monitor_revision(&self) -> u64 { - 0 + /// Hash of the monitored addresses and watched outpoints. It changes when + /// either set changes, so the mempool manager can tell when its bloom + /// filter is stale. + fn monitor_hash(&self) -> u64 { + let mut hasher = DefaultHasher::new(); + self.monitored_addresses().hash(&mut hasher); + self.watched_outpoints().hash(&mut hasher); + hasher.finish() } /// Reclaim expired receive-address reservations across every managed diff --git a/key-wallet-manager/tests/integration_test.rs b/key-wallet-manager/tests/integration_test.rs index c0ac7a35c..09232b782 100644 --- a/key-wallet-manager/tests/integration_test.rs +++ b/key-wallet-manager/tests/integration_test.rs @@ -19,7 +19,6 @@ fn test_wallet_manager_creation() { // WalletManager::new returns Self, not Result assert_eq!(manager.last_processed_height(), 0); assert_eq!(manager.wallet_count(), 0); // No wallets created yet - assert_eq!(manager.monitor_revision(), 0); } #[test] @@ -27,7 +26,6 @@ fn test_wallet_manager_from_mnemonic() { // Create from a test mnemonic let mnemonic = Mnemonic::generate(12, Language::English).unwrap(); let mut manager = WalletManager::::new(Network::Testnet); - assert_eq!(manager.monitor_revision(), 0); // Create a wallet from mnemonic let wallet_result = manager.create_wallet_from_mnemonic( @@ -37,7 +35,6 @@ fn test_wallet_manager_from_mnemonic() { ); assert!(wallet_result.is_ok(), "Failed to create wallet: {:?}", wallet_result); assert_eq!(manager.wallet_count(), 1); - assert_eq!(manager.monitor_revision(), 1); } #[test] @@ -71,7 +68,6 @@ fn test_account_management() { manager.create_wallet_with_random_mnemonic(WalletAccountCreationOptions::Default); assert!(wallet_result.is_ok(), "Failed to create wallet: {:?}", wallet_result); let wallet_id = wallet_result.unwrap(); - assert_eq!(manager.monitor_revision(), 1); // Add accounts to the wallet // Note: Index 0 already exists from wallet creation, so use index 1 @@ -84,7 +80,6 @@ fn test_account_management() { None, ); assert!(result.is_ok()); - assert_eq!(manager.monitor_revision(), 2); // Get accounts from wallet - Default creates 11 accounts (including PlatformPayment), plus the one we added let accounts = manager.get_accounts(&wallet_id); diff --git a/key-wallet/src/managed_account/managed_account_ref.rs b/key-wallet/src/managed_account/managed_account_ref.rs index 6e079e2a9..eb79a95e4 100644 --- a/key-wallet/src/managed_account/managed_account_ref.rs +++ b/key-wallet/src/managed_account/managed_account_ref.rs @@ -126,14 +126,6 @@ impl<'a> ManagedAccountRef<'a> { } } - /// Return the current monitor revision. - pub fn monitor_revision(self) -> u64 { - match self { - ManagedAccountRef::Funds(a) => a.monitor_revision(), - ManagedAccountRef::Keys(a) => a.monitor_revision(), - } - } - /// Whether `address` belongs to this account. pub fn contains_address(self, address: &Address) -> bool { match self { @@ -282,23 +274,6 @@ impl<'a> ManagedAccountRefMut<'a> { } } - /// Bump the monitor revision counter — call this when the monitored - /// address set changes (e.g. new addresses generated). - pub fn bump_monitor_revision(&mut self) { - match self { - ManagedAccountRefMut::Funds(a) => a.bump_monitor_revision(), - ManagedAccountRefMut::Keys(a) => a.bump_monitor_revision(), - } - } - - /// Return the current monitor revision. - pub fn monitor_revision(&self) -> u64 { - match self { - ManagedAccountRefMut::Funds(a) => a.monitor_revision(), - ManagedAccountRefMut::Keys(a) => a.monitor_revision(), - } - } - /// Record a new transaction for this account. /// /// Funds variants update UTXO state and balance; keys variants update diff --git a/key-wallet/src/managed_account/managed_account_trait.rs b/key-wallet/src/managed_account/managed_account_trait.rs index 21664883d..35fcccc91 100644 --- a/key-wallet/src/managed_account/managed_account_trait.rs +++ b/key-wallet/src/managed_account/managed_account_trait.rs @@ -73,15 +73,6 @@ pub trait ManagedAccountTrait { /// the full record under the default feature configuration. fn transaction_is_finalized(&self, txid: &Txid) -> bool; - /// Return the current monitor revision. - /// - /// Bumped whenever the monitored address set changes (e.g. new addresses - /// generated). Used to detect bloom-filter staleness. - fn monitor_revision(&self) -> u64; - - /// Increment the monitor revision to signal that the monitored address set changed. - fn bump_monitor_revision(&mut self); - // ----- Provided: defaults built on the primitives above ----- /// Get the account index @@ -567,12 +558,6 @@ pub trait ManagedAccountTrait { } } - // Bump the monitor revision if any pool actually generated addresses, even when a later - // pool failed — otherwise the revision would stay stale despite changed monitored state. - if !generated.is_empty() { - self.bump_monitor_revision(); - } - if let Some(e) = first_error { return Err(e); } 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 af5b7d72e..573dc0ab1 100644 --- a/key-wallet/src/managed_account/managed_core_funds_account.rs +++ b/key-wallet/src/managed_account/managed_core_funds_account.rs @@ -1,7 +1,7 @@ //! Managed core funds account: keys-account state plus balance, UTXOs, and spent outpoints. //! //! Composed of an inner [`ManagedCoreKeysAccount`] (which carries the address -//! pools, transactions, network, and monitor revision) plus the funds-specific +//! pools, transactions and network) plus the funds-specific //! bookkeeping needed for accounts that hold and spend Dash directly //! (Standard, CoinJoin, DashPay). //! @@ -52,8 +52,7 @@ use std::collections::{BTreeSet, HashMap, HashSet, VecDeque}; #[derive(Debug, Clone)] #[cfg_attr(feature = "serde", derive(Serialize))] pub struct ManagedCoreFundsAccount { - /// Shared keys-account state (address pools, transactions, network, - /// monitor revision). + /// Shared keys-account state (address pools, transactions, network). keys: ManagedCoreKeysAccount, /// Account balance information pub balance: WalletCoreBalance, @@ -455,7 +454,6 @@ impl ManagedCoreFundsAccount { }); let txid = tx.txid(); - let mut utxos_changed = false; // A transaction whose input a *block* already spent can never // confirm — unless this arrival is that block delivery itself. @@ -507,7 +505,7 @@ impl ManagedCoreFundsAccount { context.block_info().map_or(0, |info| info.height), tx.is_coin_base(), ); - utxos_changed |= self.take_in_output( + self.take_in_output( received, Vec::new(), observed_spent, @@ -546,16 +544,11 @@ impl ManagedCoreFundsAccount { "Removed spent UTXO" ); self.unsettled_spends.entry(txid).or_default().push(spent); - utxos_changed = true; } } if context.is_chain_locked() { self.unsettled_spends.remove(&txid); } - - if utxos_changed { - self.keys.bump_monitor_revision(); - } } _ => {} } @@ -643,9 +636,6 @@ impl ManagedCoreFundsAccount { self.release_spent_marks(&freed); } - if utxos > 0 { - self.keys.bump_monitor_revision(); - } AbandonRemoval { utxos, records, @@ -726,9 +716,6 @@ impl ManagedCoreFundsAccount { for outpoint in spent_claims.keys() { self.keep_recorded_output_for_claim(outpoint); } - if !restored.is_empty() { - self.keys.bump_monitor_revision(); - } Truncation { txids: dropped.into_iter().collect(), unconfirmed_txids: unconfirmed.into_iter().collect(), @@ -874,13 +861,11 @@ impl ManagedCoreFundsAccount { } let mut freed: HashSet = HashSet::new(); - let mut changed = false; for loser in &losers { let removed: Vec = self.utxos.keys().filter(|outpoint| outpoint.txid == *loser).copied().collect(); for outpoint in removed { self.utxos.remove(&outpoint); - changed = true; } self.spent_before_funded.retain(|outpoint, _| outpoint.txid != *loser); self.claim_guarded_outputs.retain(|outpoint, _| outpoint.txid != *loser); @@ -904,9 +889,6 @@ impl ManagedCoreFundsAccount { // Only the loser's *extra* inputs are genuinely released. freed.retain(|outpoint| !spent.contains(outpoint)); let released = self.release_spent_marks(&freed); - if changed { - self.keys.bump_monitor_revision(); - } // Report only coins that outlive this sweep. The descendant closure // above removes transactions that spent a loser's *own* change, so @@ -1160,9 +1142,6 @@ impl ManagedCoreFundsAccount { observed_spent, spent_claims, ); - if coins_changed { - self.keys.bump_monitor_revision(); - } Confirmation { record, coins_changed, @@ -1413,7 +1392,6 @@ impl ManagedCoreFundsAccount { } _ => "Failed to generate receive address", })?; - self.keys.bump_monitor_revision(); Ok(addr) } else { Err("Cannot generate receive address for non-standard account type") @@ -1444,7 +1422,6 @@ impl ManagedCoreFundsAccount { } _ => "Failed to generate change address", })?; - self.keys.bump_monitor_revision(); Ok(addr) } else { Err("Cannot generate change address for non-standard account type") @@ -1485,7 +1462,6 @@ impl ManagedCoreFundsAccount { _ => "Failed to generate receive address", }, )?; - self.keys.bump_monitor_revision(); Ok(addr) } else { Err("Cannot generate receive address for non-standard account type") @@ -1495,8 +1471,7 @@ impl ManagedCoreFundsAccount { /// Release a previously reserved receive address back to the available pool. /// /// Idempotent: returns `false` if the address is unknown to the external - /// pool or is not currently reserved. Bumps the monitor revision only when - /// a reservation is actually cleared. + /// pool or is not currently reserved. pub fn release_receive_reservation(&mut self, address: &Address) -> bool { if let ManagedAccountType::Standard { external_addresses, @@ -1504,10 +1479,7 @@ impl ManagedCoreFundsAccount { } = self.keys.managed_account_type_mut() { if let Some(index) = external_addresses.address_index(address) { - if external_addresses.release_reservation(index) { - self.keys.bump_monitor_revision(); - return true; - } + return external_addresses.release_reservation(index); } } false @@ -1519,8 +1491,7 @@ impl ManagedCoreFundsAccount { /// Backstop for reservations handed out but never funded and never /// explicitly released, which would otherwise pin gap-limit headroom /// forever. `now` and `ttl` are caller-supplied (seconds); the wallet keeps - /// no clock. Returns the number of reservations reclaimed and bumps the - /// monitor revision when that is non-zero. See + /// no clock. Returns the number of reservations reclaimed. See /// [`address_pool::AddressPool::sweep_expired_reservations`]. pub fn sweep_expired_receive_reservations(&mut self, now: u64, ttl: u64) -> usize { if let ManagedAccountType::Standard { @@ -1528,11 +1499,7 @@ impl ManagedCoreFundsAccount { .. } = self.keys.managed_account_type_mut() { - let reclaimed = external_addresses.sweep_expired_reservations(now, ttl); - if reclaimed > 0 { - self.keys.bump_monitor_revision(); - } - reclaimed + external_addresses.sweep_expired_reservations(now, ttl) } else { 0 } @@ -1669,14 +1636,6 @@ impl ManagedAccountTrait for ManagedCoreFundsAccount { fn transaction_is_finalized(&self, txid: &Txid) -> bool { self.keys.transaction_is_finalized(txid) } - - fn monitor_revision(&self) -> u64 { - self.keys.monitor_revision() - } - - fn bump_monitor_revision(&mut self) { - self.keys.bump_monitor_revision() - } } /// Rebuild the account-local `spent_outpoints` set from recorded transactions. diff --git a/key-wallet/src/managed_account/managed_core_keys_account.rs b/key-wallet/src/managed_account/managed_core_keys_account.rs index f3e7aea37..ec1d0e848 100644 --- a/key-wallet/src/managed_account/managed_core_keys_account.rs +++ b/key-wallet/src/managed_account/managed_core_keys_account.rs @@ -80,10 +80,6 @@ pub struct ManagedCoreKeysAccount { #[cfg(not(feature = "keep-finalized-transactions"))] #[cfg_attr(feature = "serde", serde(default))] finalized_summaries: HashMap, - /// Revision counter incremented when the monitored address set changes - /// (e.g. new addresses generated). Used to detect bloom filter staleness. - #[cfg_attr(feature = "serde", serde(skip))] - monitor_revision: u64, } impl ManagedCoreKeysAccount { @@ -97,7 +93,6 @@ impl ManagedCoreKeysAccount { finalized_txids: HashSet::new(), #[cfg(not(feature = "keep-finalized-transactions"))] finalized_summaries: HashMap::new(), - monitor_revision: 0, } } @@ -471,12 +466,4 @@ impl ManagedAccountTrait for ManagedCoreKeysAccount { fn transaction_is_finalized(&self, txid: &Txid) -> bool { self.finalized_txids.contains(txid) } - - fn monitor_revision(&self) -> u64 { - self.monitor_revision - } - - fn bump_monitor_revision(&mut self) { - self.monitor_revision += 1; - } } diff --git a/key-wallet/src/tests/address_reservation_tests.rs b/key-wallet/src/tests/address_reservation_tests.rs index a1cfa038c..5c4b9cef6 100644 --- a/key-wallet/src/tests/address_reservation_tests.rs +++ b/key-wallet/src/tests/address_reservation_tests.rs @@ -5,7 +5,6 @@ use crate::account::{Account, AccountType, ManagedCoreFundsAccount}; use crate::managed_account::address_pool::KeySource; -use crate::managed_account::managed_account_trait::ManagedAccountTrait; use crate::managed_account::managed_account_type::ManagedAccountType; use crate::mnemonic::Mnemonic; use crate::test_utils::TestWalletContext; @@ -20,12 +19,6 @@ async fn test_reserved_receive_address_promotes_on_funding() { let mut ctx = TestWalletContext::new_random(); let xpub = ctx.xpub; - let revision_before = ctx - .managed_wallet - .first_bip44_managed_account_mut() - .expect("managed account") - .monitor_revision(); - let a = ctx .managed_wallet .first_bip44_managed_account_mut() @@ -39,15 +32,6 @@ async fn test_reserved_receive_address_promotes_on_funding() { .next_receive_address_and_reserve(Some(&xpub), 1_000) .expect("reserve b"); - // Each reservation must bump the monitor revision so observers re-read the - // address set. - let revision_after_reserve = ctx - .managed_wallet - .first_bip44_managed_account_mut() - .expect("managed account") - .monitor_revision(); - assert!(revision_after_reserve > revision_before); - // Two sequential receive hand-outs return distinct addresses: reserving the // first removes it from the available pool seen by the second. assert_ne!(a, b); @@ -62,10 +46,7 @@ async fn test_reserved_receive_address_promotes_on_funding() { // `a` is used now, so its reservation is already gone: releasing is a no-op. assert!(!acc.release_receive_reservation(&a)); // `b` is still reserved, so releasing it returns it to the available pool - // and bumps the monitor revision again. - let revision_before_release = acc.monitor_revision(); assert!(acc.release_receive_reservation(&b)); - assert!(acc.monitor_revision() > revision_before_release); // Releasing an address the pool has never seen is a no-op. let stray = Address::from_str("yTb47qEBpNmgXvYYsHEN4nh8yJwa5iC4Cs") @@ -122,17 +103,13 @@ fn test_sweep_expired_receive_reservations_reclaims_through_account() { let acc = ctx.managed_wallet.first_bip44_managed_account_mut().expect("managed account"); let reserved = acc.next_receive_address_and_reserve(Some(&xpub), 1_000).expect("reserve"); - let revision_after_reserve = acc.monitor_revision(); - // A sweep before the ttl elapses leaves the reservation intact and does not - // bump the monitor revision. + // A sweep before the ttl elapses leaves the reservation intact. assert_eq!(acc.sweep_expired_receive_reservations(1_000, 500), 0); - assert_eq!(acc.monitor_revision(), revision_after_reserve); - // Once the reservation is older than the ttl it is reclaimed, the revision - // bumps, and releasing the now-available address is a no-op. + // Once the reservation is older than the ttl it is reclaimed, and releasing + // the now-available address is a no-op. assert_eq!(acc.sweep_expired_receive_reservations(2_000, 500), 1); - assert!(acc.monitor_revision() > revision_after_reserve); assert!(!acc.release_receive_reservation(&reserved)); } diff --git a/key-wallet/src/tests/restore_utxos_tests.rs b/key-wallet/src/tests/restore_utxos_tests.rs index 2b52f202e..84897b5f6 100644 --- a/key-wallet/src/tests/restore_utxos_tests.rs +++ b/key-wallet/src/tests/restore_utxos_tests.rs @@ -229,7 +229,6 @@ fn a_copy_another_account_holds_is_taken_out_on_restore() { let (_, utxo) = funded(&coinjoin_address(&ctx, 0), 0, 100_000); let bip44 = ctx.managed_wallet.accounts.standard_bip44_accounts.get_mut(&0).unwrap(); bip44.utxos.insert(utxo.outpoint, utxo.clone()); - let bip44_revision = bip44.monitor_revision(); let unmatched = ctx.managed_wallet.restore_utxos(&ctx.wallet, [utxo.clone()]).expect("restores"); @@ -238,7 +237,6 @@ fn a_copy_another_account_holds_is_taken_out_on_restore() { let accounts = &ctx.managed_wallet.accounts; assert!(accounts.coinjoin_accounts[&0].utxos.contains_key(&utxo.outpoint)); assert!(!accounts.standard_bip44_accounts[&0].utxos.contains_key(&utxo.outpoint)); - assert!(accounts.standard_bip44_accounts[&0].monitor_revision() > bip44_revision); ctx.managed_wallet.update_balance(); assert_eq!(ctx.managed_wallet.balance.total(), 100_000); } diff --git a/key-wallet/src/transaction_checking/wallet_checker.rs b/key-wallet/src/transaction_checking/wallet_checker.rs index 7523d82f2..07b64e2bb 100644 --- a/key-wallet/src/transaction_checking/wallet_checker.rs +++ b/key-wallet/src/transaction_checking/wallet_checker.rs @@ -123,15 +123,13 @@ impl ManagedWalletInfo { let adopted_indices = &TransactionRecord::owned_indices(&record.output_details) - &before; let adopted = outputs.iter().filter(|d| adopted_indices.contains(&d.index)); - if funds.take_in_mined_outputs( + funds.take_in_mined_outputs( &record.transaction, &record.context, adopted, &self.observed_spent_outpoints, &self.spent_claims, - ) { - funds.bump_monitor_revision(); - } + ); } result .updated_records @@ -168,7 +166,6 @@ impl ManagedWalletInfo { if matches!(key_source, KeySource::NoKeySource) { continue; } - let rev_before = new_addresses.len(); for pool in account.managed_account_type_mut().address_pools_mut() { let pool_type = pool.pool_type; match pool.maintain_gap_limit(&key_source) { @@ -189,9 +186,6 @@ impl ManagedWalletInfo { } } } - if new_addresses.len() > rev_before { - account.bump_monitor_revision(); - } } new_addresses.len() > derived_before } diff --git a/key-wallet/src/wallet/managed_wallet_info/mod.rs b/key-wallet/src/wallet/managed_wallet_info/mod.rs index ceb443298..0019c6b8a 100644 --- a/key-wallet/src/wallet/managed_wallet_info/mod.rs +++ b/key-wallet/src/wallet/managed_wallet_info/mod.rs @@ -470,10 +470,6 @@ impl ManagedWalletInfo { /// spent-output claim does not hold a restored UTXO back; a credited /// UTXO is no longer kept aside for one. /// - /// Each account whose pools grow, or that is credited a UTXO or loses one, - /// gets its monitor revision bumped, so a running client rebuilds its - /// filters. - /// /// Every pool is extended before any UTXO is inserted, so an `Err` from /// address derivation leaves the UTXO sets as they were; the addresses /// derived and marked used by then stay. The balance is not recomputed: @@ -527,16 +523,11 @@ impl ManagedWalletInfo { if index != owner { if let Some(copy) = account.utxos.remove(&outpoint) { copies.push(copy); - account.bump_monitor_revision(); } } } let account = &mut accounts[owner]; - let credited = - account.take_in_output(utxo, copies, &self.observed_spent_outpoints, None, |_| {}); - if credited { - account.bump_monitor_revision(); - } + account.take_in_output(utxo, copies, &self.observed_spent_outpoints, None, |_| {}); } self.refresh_lock_flags(matched); Ok(unmatched) @@ -760,8 +751,6 @@ impl ManagedWalletInfo { for pool in account.managed_account_type_mut().address_pools_mut() { pool.generate_up_to(last_index, &key_source)?; } - - account.bump_monitor_revision(); } Ok(()) @@ -769,8 +758,7 @@ impl ManagedWalletInfo { } /// Extend every pool of `accounts` that has a public key source to its gap -/// limit, bumping the monitor revision of each account that grew. Returns -/// whether any pool grew. +/// limit. Returns whether any pool grew. fn extend_pools( wallet: &Wallet, accounts: &mut [&mut crate::managed_account::ManagedCoreFundsAccount], @@ -782,13 +770,8 @@ fn extend_pools( if matches!(key_source, crate::KeySource::NoKeySource) { continue; } - let mut grew = false; for pool in account.managed_account_type_mut().address_pools_mut() { - grew |= !pool.maintain_gap_limit(&key_source)?.is_empty(); - } - if grew { - account.bump_monitor_revision(); - any_grew = true; + any_grew |= !pool.maintain_gap_limit(&key_source)?.is_empty(); } } Ok(any_grew) 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 1af236928..fbf624075 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 @@ -305,12 +305,6 @@ pub trait WalletInfoInterface: Sized + WalletTransactionChecker + ManagedAccount fn mark_instant_send_utxos(&mut self, txid: &Txid, lock: &InstantLock) -> bool; fn unrecorded_spend_heights(&self, tx: &Transaction) -> BTreeSet; - - /// Return the aggregated monitor revision across all accounts. - /// Increments whenever the monitored address set changes. - fn monitor_revision(&self) -> u64 { - 0 - } } /// Default implementation for ManagedWalletInfo @@ -698,10 +692,6 @@ impl WalletInfoInterface for ManagedWalletInfo { any_changed || swept } - fn monitor_revision(&self) -> u64 { - self.accounts.all_accounts().iter().map(|a| a.monitor_revision()).sum() - } - fn unrecorded_spend_heights(&self, tx: &Transaction) -> BTreeSet { let txid = tx.txid(); (0..tx.output.len() as u32)