From 606888ea326d245c17fc042bf57c2cdfa715fb4c Mon Sep 17 00:00:00 2001 From: Borja Castellano Date: Wed, 11 Nov 2026 03:37:43 -0800 Subject: [PATCH 01/22] refactor(key-wallet)!: derive pool addresses in one place `AddressPool` repeated the next-index arithmetic and the derive-and-store loop in every method that hands out or tops up addresses, and the `ManagedAccountTrait` index getters cloned every available address to read one index. `generate_addresses` is now the only path that picks indices to derive, and it, `generate_up_to` and `generate_address_at_index` return `AddressInfo`. `next_unused`, `next_unused_and_reserve`, the `next_unused_multiple*` methods, `unused_addresses_count`, `maintain_gap_limit` and `address_range` go through it. This also fixes `address_range` skipping index 0 on an empty pool, `maintain_gap_limit` deriving nothing with a gap limit of 1, and `next_unused_with_info` failing with `add_to_state` false. The unused `get_next_receive_address_index`, `get_next_change_address_index` and `get_next_address_index` trait methods are removed. The first-available-index lookup is a private `AddressPool` helper. Closes #1352. --- .../src/managed_account/address_pool.rs | 210 +++++------------- .../managed_account/managed_account_trait.rs | 98 -------- .../transaction_checking/wallet_checker.rs | 1 + 3 files changed, 59 insertions(+), 250 deletions(-) diff --git a/key-wallet/src/managed_account/address_pool.rs b/key-wallet/src/managed_account/address_pool.rs index 1c897b611..c2f0612b3 100644 --- a/key-wallet/src/managed_account/address_pool.rs +++ b/key-wallet/src/managed_account/address_pool.rs @@ -452,28 +452,38 @@ impl AddressPool { self.pool_type == AddressPoolType::External } + /// Returns the index of the first available address, or the next index to derive when none is. + fn next_unused_index(&self) -> u32 { + self.addresses + .iter() + .find(|(_, info)| info.is_available()) + .map_or_else(|| self.next_index_to_derive(), |(index, _)| *index) + } + + fn next_index_to_derive(&self) -> u32 { + self.highest_generated.map_or(0, |highest| highest + 1) + } + /// Generate addresses up to the specified count pub fn generate_addresses( &mut self, count: u32, key_source: &KeySource, add_to_state: bool, - ) -> Result> { - let mut new_addresses = Vec::new(); - let start_index = self.highest_generated.map(|h| h + 1).unwrap_or(0); - let end_index = start_index + count; - - for index in start_index..end_index { - let address = self.generate_address_at_index(index, key_source, add_to_state)?; - new_addresses.push(address); - } - - Ok(new_addresses) + ) -> Result> { + let start_index = self.next_index_to_derive(); + (start_index..start_index + count) + .map(|index| self.generate_address_at_index(index, key_source, add_to_state)) + .collect() } /// Generate every address up to and including `index` - pub fn generate_up_to(&mut self, index: u32, key_source: &KeySource) -> Result> { - let next = self.highest_generated.map_or(0, |highest| highest + 1); + pub fn generate_up_to( + &mut self, + index: u32, + key_source: &KeySource, + ) -> Result> { + let next = self.next_index_to_derive(); self.generate_addresses((index + 1).saturating_sub(next), key_source, true) } @@ -483,10 +493,10 @@ impl AddressPool { index: u32, key_source: &KeySource, add_to_state: bool, - ) -> Result
{ + ) -> Result { // Check if already generated if let Some(info) = self.addresses.get(&index) { - return Ok(info.address.clone()); + return Ok(info.clone()); } // Build the full path for record keeping @@ -565,11 +575,10 @@ impl AddressPool { }; let info = AddressInfo::new_with_public_key(address.clone(), index, full_path, public_key_type); - let script_pubkey = info.script_pubkey.clone(); if add_to_state { - self.addresses.insert(index, info); - self.address_index.insert(address.clone(), index); - self.script_pubkey_index.insert(script_pubkey, index); + self.addresses.insert(index, info.clone()); + self.address_index.insert(address, index); + self.script_pubkey_index.insert(info.script_pubkey.clone(), index); // Update highest generated if self.highest_generated.map(|h| index > h).unwrap_or(true) { @@ -577,28 +586,12 @@ impl AddressPool { } } - Ok(address) + Ok(info) } /// Get the next unused address pub fn next_unused(&mut self, key_source: &KeySource, add_to_state: bool) -> Result
{ - // First, try to find an already generated unused address - for i in 0..=self.highest_generated.unwrap_or(0) { - if let Some(info) = self.addresses.get(&i) { - if info.is_available() { - return Ok(info.address.clone()); - } - } - } - - // If NoKeySource, we can't generate new addresses - if matches!(key_source, KeySource::NoKeySource) { - return Err(Error::NoKeySource); - } - - // Generate a new address - let next_index = self.highest_generated.map(|h| h + 1).unwrap_or(0); - self.generate_address_at_index(next_index, key_source, add_to_state) + self.next_unused_with_info(key_source, add_to_state).map(|info| info.address) } /// Get the next unused address info @@ -608,12 +601,8 @@ impl AddressPool { add_to_state: bool, ) -> Result { // First, try to find an already generated unused address - for i in 0..=self.highest_generated.unwrap_or(0) { - if let Some(info) = self.addresses.get(&i) { - if info.is_available() { - return Ok(info.clone()); - } - } + if let Some(info) = self.addresses.get(&self.next_unused_index()) { + return Ok(info.clone()); } // If NoKeySource, we can't generate new addresses @@ -621,14 +610,9 @@ impl AddressPool { return Err(Error::NoKeySource); } - // Generate a new address - let next_index = self.highest_generated.map(|h| h + 1).unwrap_or(0); - self.generate_address_at_index(next_index, key_source, add_to_state)?; - - // Return the AddressInfo we just created - self.addresses.get(&next_index).cloned().ok_or_else(|| { - Error::InvalidParameter("Failed to retrieve generated address info".into()) - }) + self.generate_addresses(1, key_source, add_to_state)? + .pop() + .ok_or_else(|| Error::InvalidState("generate_addresses(1) returned nothing".into())) } /// Reserve and return the next available address. @@ -651,39 +635,15 @@ impl AddressPool { /// [`AddressPool::sweep_expired_reservations`], so callers are assumed /// trusted. Gate or cap this before exposing it to untrusted input. pub fn next_unused_and_reserve(&mut self, key_source: &KeySource, now: u64) -> Result
{ - for i in 0..=self.highest_generated.unwrap_or(0) { - if let Some(info) = self.addresses.get_mut(&i) { - if info.is_available() { - info.state = AddressState::Reserved { - at: now, - }; - return Ok(info.address.clone()); - } - } - } - - if matches!(key_source, KeySource::NoKeySource) { - return Err(Error::NoKeySource); - } - let next_index = self.highest_generated.map(|h| h + 1).unwrap_or(0); - let address = self.generate_address_at_index(next_index, key_source, true)?; - // `generate_address_at_index` with `add_to_state = true` always inserts - // at `next_index`. If `highest_generated` ever drifts out of sync with - // `addresses` a silent lookup miss would return an unreserved address, - // reintroducing the hand-out race this method exists to close, so report - // the broken invariant as an error rather than fail open. - let info = self.addresses.get_mut(&next_index).ok_or_else(|| { - Error::InvalidState(format!( - "next_unused_and_reserve: generate_address_at_index({}) succeeded but \ - the entry was not stored; pool invariant broken", - next_index - )) + let index = self.next_unused_with_info(key_source, true)?.index; + // A lookup miss would hand out an unreserved address, so fail instead. + let info = self.addresses.get_mut(&index).ok_or_else(|| { + Error::InvalidState(format!("next_unused_and_reserve: index {} not stored", index)) })?; - debug_assert!(info.is_available()); info.state = AddressState::Reserved { at: now, }; - Ok(address) + Ok(info.address.clone()) } /// Release a reservation, returning the address to the available pool. @@ -775,21 +735,9 @@ impl AddressPool { return addresses; } - // Generate new addresses to fill the remaining count - let remaining = count - addresses.len(); - let start_index = self.highest_generated.map(|h| h + 1).unwrap_or(0); - - for i in 0..remaining { - if let Ok(address) = - self.generate_address_at_index(start_index + i as u32, key_source, add_to_state) - { - addresses.push(address); - } else { - // If generation fails, return what we have so far - break; - } - } - + let remaining = (count - addresses.len()) as u32; + let generated = self.generate_addresses(remaining, key_source, add_to_state); + addresses.extend(generated.unwrap_or_default().into_iter().map(|info| info.address)); addresses } @@ -831,22 +779,11 @@ impl AddressPool { return result; } - // Generate new addresses with info to fill the remaining count - let remaining = count - result.len(); - let start_index = self.highest_generated.map(|h| h + 1).unwrap_or(0); - - for i in 0..remaining { - let index = start_index + i as u32; - if self.generate_address_at_index(index, key_source, add_to_state).is_ok() { - if let Some(info) = self.addresses.get(&index) { - result.push((info.address.clone(), info.clone())); - } - } else { - // If generation fails, return what we have so far - break; - } - } - + let remaining = (count - result.len()) as u32; + let generated = self.generate_addresses(remaining, key_source, add_to_state); + result.extend( + generated.unwrap_or_default().into_iter().map(|info| (info.address.clone(), info)), + ); result } @@ -860,9 +797,7 @@ impl AddressPool { let mut current_index = 0; // Collect existing unused addresses - while unused.len() < count as usize - && self.highest_generated.map(|h| current_index <= h).unwrap_or(false) - { + while unused.len() < count as usize && current_index < self.next_index_to_derive() { if let Some(info) = self.addresses.get(¤t_index) { if info.is_available() { unused.push(info.address.clone()); @@ -871,13 +806,9 @@ impl AddressPool { current_index += 1; } - // Generate more if needed - while unused.len() < count as usize { - let next_index = self.highest_generated.map(|h| h + 1).unwrap_or(0); - let address = self.generate_address_at_index(next_index, key_source, true)?; - unused.push(address); - } - + let remaining = count - unused.len() as u32; + let generated = self.generate_addresses(remaining, key_source, true)?; + unused.extend(generated.into_iter().map(|info| info.address)); Ok(unused) } @@ -1031,14 +962,7 @@ impl AddressPool { return Ok(Vec::new()); } - // Generate addresses up to end_index if needed - let current_highest = self.highest_generated.unwrap_or(0); - if end_index > current_highest + 1 { - // Generate from current_highest + 1 to end_index - 1 - for index in (current_highest + 1)..end_index { - self.generate_address_at_index(index, key_source, true)?; - } - } + self.generate_up_to(end_index - 1, key_source)?; // Collect addresses in the range let mut addresses = Vec::new(); @@ -1084,27 +1008,7 @@ impl AddressPool { None => self.gap_limit - 1, Some(highest) => highest + self.gap_limit, }; - - let mut new_addresses = Vec::new(); - while self.highest_generated.unwrap_or(0) < target { - let next_index = self.highest_generated.map(|h| h + 1).unwrap_or(0); - self.generate_address_at_index(next_index, key_source, true)?; - // `generate_address_at_index` with `add_to_state = true` always - // inserts at `next_index`. Surfacing a regression that breaks it - // (e.g. a refactor that hits the early-return branch on a - // re-derivation) as an error keeps the outer `while` from spinning - // into an infinite loop. - let info = self.addresses.get(&next_index).cloned().ok_or_else(|| { - Error::InvalidState(format!( - "maintain_gap_limit: generate_address_at_index({}) succeeded but \ - the entry was not stored; pool invariant broken", - next_index - )) - })?; - new_addresses.push(info); - } - - Ok(new_addresses) + self.generate_up_to(target, key_source) } /// Set a custom label for an address @@ -1402,7 +1306,7 @@ mod tests { let key_source = test_key_source(); let addresses = pool.generate_addresses(5, &key_source, true).unwrap(); - let first_addr = &addresses[0]; + let first_addr = &addresses[0].address; assert!(pool.mark_used(first_addr)); assert_eq!(pool.used_indices.len(), 1); @@ -1828,7 +1732,9 @@ mod tests { // Simulate checking for usage - mark addresses at indices 2, 5, 7 as used let check_fn = |addr: &Address| { - addresses[2] == *addr || addresses[5] == *addr || addresses[7] == *addr + addresses[2].address == *addr + || addresses[5].address == *addr + || addresses[7].address == *addr }; let found = pool.scan_for_usage(check_fn); diff --git a/key-wallet/src/managed_account/managed_account_trait.rs b/key-wallet/src/managed_account/managed_account_trait.rs index 21664883d..40b45a91a 100644 --- a/key-wallet/src/managed_account/managed_account_trait.rs +++ b/key-wallet/src/managed_account/managed_account_trait.rs @@ -99,97 +99,6 @@ pub trait ManagedAccountTrait { self.managed_account_type() } - /// Get the next unused receive address index for standard accounts - fn get_next_receive_address_index(&self) -> Option { - if let ManagedAccountType::Standard { - external_addresses, - .. - } = self.managed_account_type() - { - next_index(external_addresses) - } else { - None - } - } - - /// Get the next unused change address index for standard accounts - fn get_next_change_address_index(&self) -> Option { - if let ManagedAccountType::Standard { - internal_addresses, - .. - } = self.managed_account_type() - { - next_index(internal_addresses) - } else { - None - } - } - - /// Get the next unused address index for single-pool account types - fn get_next_address_index(&self) -> Option { - match self.managed_account_type() { - ManagedAccountType::Standard { - .. - } => self.get_next_receive_address_index(), - ManagedAccountType::CoinJoin { - external_addresses: addresses, - .. - } - | ManagedAccountType::IdentityRegistration { - addresses, - .. - } - | ManagedAccountType::IdentityTopUp { - addresses, - .. - } - | ManagedAccountType::IdentityTopUpNotBoundToIdentity { - addresses, - .. - } - | ManagedAccountType::IdentityInvitation { - addresses, - .. - } - | ManagedAccountType::AssetLockAddressTopUp { - addresses, - .. - } - | ManagedAccountType::AssetLockShieldedAddressTopUp { - addresses, - .. - } - | ManagedAccountType::ProviderVotingKeys { - addresses, - .. - } - | ManagedAccountType::ProviderOwnerKeys { - addresses, - .. - } - | ManagedAccountType::ProviderOperatorKeys { - addresses, - .. - } - | ManagedAccountType::ProviderPlatformKeys { - addresses, - .. - } - | ManagedAccountType::DashpayReceivingFunds { - addresses, - .. - } - | ManagedAccountType::DashpayExternalAccount { - addresses, - .. - } - | ManagedAccountType::PlatformPayment { - addresses, - .. - } => next_index(addresses), - } - } - /// Mark an address as used fn mark_address_used(&mut self, address: &Address) -> bool { self.managed_account_type_mut().mark_address_used(address) @@ -645,10 +554,3 @@ pub trait ManagedAccountTrait { } } } - -fn next_index(pool: &address_pool::AddressPool) -> Option { - match pool.unused_addresses().first() { - Some(addr) => pool.address_index(addr), - None => Some(pool.stats().highest_generated.map_or(0, |h| h + 1)), - } -} diff --git a/key-wallet/src/transaction_checking/wallet_checker.rs b/key-wallet/src/transaction_checking/wallet_checker.rs index bb65e7bfb..bcfdc7595 100644 --- a/key-wallet/src/transaction_checking/wallet_checker.rs +++ b/key-wallet/src/transaction_checking/wallet_checker.rs @@ -3997,6 +3997,7 @@ mod tests { external_addresses .generate_address_at_index(index, &KeySource::Public(xpub), true) .unwrap() + .address }) .collect(); let address = &addresses[0]; From 58e89b8b06b9f113f70d4ed24bb35fce8b2793d9 Mon Sep 17 00:00:00 2001 From: Borja Castellano Date: Wed, 11 Nov 2026 03:50:26 -0800 Subject: [PATCH 02/22] refactor(key-wallet)!: mark pool addresses used by address only `AddressPool` had three copies of the mark-used bookkeeping (`mark_used`, `mark_index_used` and `scan_for_usage`), and `ManagedAccountTrait` exposed `mark_first_pool_index_used` to mark by index. `mark_used(&Address)` is now the only way to mark an address used. `mark_index_used` and `mark_first_pool_index_used` are removed, `scan_for_usage` goes through `mark_used`, and `peek_next_path` returns the address instead of its index so `next_path` and the asset lock builder mark it with `mark_address_used`. --- .../src/managed_account/address_pool.rs | 76 +++++++------------ .../managed_account/managed_account_trait.rs | 28 ++----- key-wallet/src/tests/performance_tests.rs | 3 +- .../managed_wallet_info/asset_lock_builder.rs | 23 +++--- 4 files changed, 45 insertions(+), 85 deletions(-) diff --git a/key-wallet/src/managed_account/address_pool.rs b/key-wallet/src/managed_account/address_pool.rs index c2f0612b3..0ad5d0718 100644 --- a/key-wallet/src/managed_account/address_pool.rs +++ b/key-wallet/src/managed_account/address_pool.rs @@ -814,42 +814,23 @@ impl AddressPool { /// Mark an address as used pub fn mark_used(&mut self, address: &Address) -> bool { - if let Some(&index) = self.address_index.get(address) { - if let Some(info) = self.addresses.get_mut(&index) { - if !info.is_used() { - info.mark_used(); - self.used_indices.insert(index); - - // Update highest used - self.highest_used = match self.highest_used { - None => Some(index), - Some(current) => Some(current.max(index)), - }; - - return true; - } - } - } - false - } - - /// Mark an address at a specific index as used - pub fn mark_index_used(&mut self, index: u32) -> bool { - if let Some(info) = self.addresses.get_mut(&index) { - if !info.is_used() { - info.mark_used(); - self.used_indices.insert(index); + let Some(&index) = self.address_index.get(address) else { + return false; + }; - // Update highest used - self.highest_used = match self.highest_used { - None => Some(index), - Some(current) => Some(current.max(index)), - }; + let Some(info) = self.addresses.get_mut(&index) else { + return false; + }; - return true; - } + if info.is_used() { + return false; } - false + + info.mark_used(); + self.used_indices.insert(index); + self.highest_used = Some(self.highest_used.map_or(index, |highest| highest.max(index))); + + true } /// Scan addresses for usage using a check function @@ -857,20 +838,15 @@ impl AddressPool { where F: Fn(&Address) -> bool, { - let mut found = Vec::new(); + let found: Vec
= self + .addresses + .values() + .filter(|info| !info.is_used() && check_fn(&info.address)) + .map(|info| info.address.clone()) + .collect(); - for info in self.addresses.values_mut() { - if !info.is_used() && check_fn(&info.address) { - info.mark_used(); - self.used_indices.insert(info.index); - found.push(info.address.clone()); - - // Update highest used - self.highest_used = match self.highest_used { - None => Some(info.index), - Some(current) => Some(current.max(info.index)), - }; - } + for address in &found { + self.mark_used(address); } found @@ -1604,7 +1580,7 @@ mod tests { pool.generate_addresses(10, &key_source, true).unwrap(); // Mark index 0 used so keep_until = highest_used + gap_limit = 5. - pool.mark_index_used(0); + pool.mark_used(&pool.address_at_index(0).unwrap()); // Reserve indices 1..=7 (first available each time, index 0 is used). let mut reserved = Vec::new(); @@ -1655,7 +1631,7 @@ mod tests { assert_eq!(pool.addresses.len(), gap_limit as usize); // Mark address at index 0 as used - pool.mark_index_used(0); + pool.mark_used(&pool.address_at_index(0).unwrap()); assert_eq!(pool.highest_used, Some(0)); // Should generate exactly 1 address to maintain gap_limit unused after index 0 @@ -1666,8 +1642,8 @@ mod tests { assert_eq!(pool.addresses.len(), gap_limit as usize + 1); // Mark address at index 1 and 2 as used - pool.mark_index_used(1); - pool.mark_index_used(2); + pool.mark_used(&pool.address_at_index(1).unwrap()); + pool.mark_used(&pool.address_at_index(2).unwrap()); // Should generate exactly 2 more addresses let new_addresses = pool.maintain_gap_limit(&key_source).unwrap(); diff --git a/key-wallet/src/managed_account/managed_account_trait.rs b/key-wallet/src/managed_account/managed_account_trait.rs index 40b45a91a..adb4bf809 100644 --- a/key-wallet/src/managed_account/managed_account_trait.rs +++ b/key-wallet/src/managed_account/managed_account_trait.rs @@ -321,7 +321,7 @@ pub trait ManagedAccountTrait { return Err("Expected BLS public key but got different key type"); }; - addresses.mark_index_used(info.index); + addresses.mark_used(&info.address); BLSPublicKey::try_from(pub_key_bytes.as_slice()) .map_err(|_| "BLS public key was not 48 bytes")? @@ -356,7 +356,7 @@ pub trait ManagedAccountTrait { return Err("Expected EdDSA public key but got different key type"); }; - addresses.mark_index_used(info.index); + addresses.mark_used(&info.address); let verifying_key = EddsaPkBytes::from_bytes( pub_key_bytes.try_into().map_err(|_| "Invalid EdDSA public key length")?, @@ -387,7 +387,7 @@ pub trait ManagedAccountTrait { .next_unused_with_info(&address_pool::KeySource::NoKeySource, false) .map_err(|_| "No unused address available")?; - pool.mark_index_used(info.index); + pool.mark_used(&info.address); let root_ext_priv = root_xpriv.to_extended_priv_key(network); let derived_xpriv = @@ -398,8 +398,8 @@ pub trait ManagedAccountTrait { Ok(private_key) } - /// Peek at the next unused address's path and index without marking the index used. - fn peek_next_path(&mut self) -> Result<(crate::DerivationPath, u32), &'static str> { + /// Peek at the next unused address and its path without marking it used. + fn peek_next_path(&mut self) -> Result<(crate::DerivationPath, Address), &'static str> { if matches!(self.managed_account_type(), ManagedAccountType::Standard { .. }) { return Err("Standard accounts must use next_receive_address or next_change_address"); } @@ -411,25 +411,13 @@ pub trait ManagedAccountTrait { .next_unused_with_info(&address_pool::KeySource::NoKeySource, false) .map_err(|_| "No unused address available")?; - Ok((info.path, info.index)) - } - - /// Mark an index on the account's first address pool as used. - fn mark_first_pool_index_used(&mut self, index: u32) -> Result<(), &'static str> { - if matches!(self.managed_account_type(), ManagedAccountType::Standard { .. }) { - return Err("Standard accounts must use next_receive_address or next_change_address"); - } - - let mut pools = self.managed_account_type_mut().address_pools_mut(); - let pool = pools.first_mut().ok_or("Account has no address pool")?; - pool.mark_index_used(index); - Ok(()) + Ok((info.path, info.address)) } /// Consume the next unused address and return only its derivation path. fn next_path(&mut self) -> Result { - let (path, index) = self.peek_next_path()?; - self.mark_first_pool_index_used(index)?; + let (path, address) = self.peek_next_path()?; + self.mark_address_used(&address); Ok(path) } diff --git a/key-wallet/src/tests/performance_tests.rs b/key-wallet/src/tests/performance_tests.rs index e9940ddce..627ef62b6 100644 --- a/key-wallet/src/tests/performance_tests.rs +++ b/key-wallet/src/tests/performance_tests.rs @@ -288,7 +288,8 @@ fn test_gap_limit_scan_performance() { // Mark some as used (with gaps) let used_indices = vec![0, 1, 5, 10, 25, 50, 75]; for &index in &used_indices { - pool.mark_index_used(index); + let address = pool.address_at_index(index).unwrap(); + pool.mark_used(&address); } // Scan for gap limit diff --git a/key-wallet/src/wallet/managed_wallet_info/asset_lock_builder.rs b/key-wallet/src/wallet/managed_wallet_info/asset_lock_builder.rs index f637cac65..8779d1a70 100644 --- a/key-wallet/src/wallet/managed_wallet_info/asset_lock_builder.rs +++ b/key-wallet/src/wallet/managed_wallet_info/asset_lock_builder.rs @@ -590,7 +590,7 @@ impl ManagedWalletInfo { // Phase 1 (sync): peek without marking used. Borrow is scoped // to the block so we can re-resolve the account after the // signer await. - let (path, index) = { + let (path, address) = { let funding_key_account = resolve_funding_account( &mut self.accounts, funding.funding_type, @@ -602,24 +602,19 @@ impl ManagedWalletInfo { }; // Phase 2 (async): signer round-trip. If this errors, we return - // without ever calling mark_first_pool_index_used — index stays - // free for a retry. + // without marking the address used, so it stays free for a retry. let pubkey = signer .public_key(&path) .await .map_err(|e| AssetLockError::Signer(e.to_string()))?; - // Phase 3 (sync): signer succeeded, commit the index. - { - let funding_key_account = resolve_funding_account( - &mut self.accounts, - funding.funding_type, - funding.identity_index, - )?; - funding_key_account - .mark_first_pool_index_used(index) - .map_err(|e| AssetLockError::KeyDerivation(e.to_string()))?; - } + // Phase 3 (sync): signer succeeded, commit the address. + resolve_funding_account( + &mut self.accounts, + funding.funding_type, + funding.identity_index, + )? + .mark_address_used(&address); credit_output_keys.push((pubkey, path)); } From 0d935577487e784b64e390408579a6477ceeb0bf Mon Sep 17 00:00:00 2001 From: Borja Castellano Date: Wed, 11 Nov 2026 04:13:47 -0800 Subject: [PATCH 03/22] refactor(key-wallet)!: drop unused `AddressPool` API `AddressPool` carried a builder, statistics, labels, metadata, pruning, range and scan helpers and several near-duplicate getters that nothing calls, in this repository or in Dash Platform. This removes `AddressPoolBuilder`, `PoolStats` and `stats`, `set_address_type`, `next_unused_multiple_with_info`, `unused_addresses_count`, `scan_for_usage`, `used_addresses`, `info_at_index`, `script_pubkey_index`, `address_range`, `needs_more_addresses`, `set_address_label`, `add_address_metadata`, `reset_usage`, `prune_unused`, `KeySource::derive_ecdsa_at_path`, `AddressInfo::update_stats` and the account wrappers built on `stats`. Pool methods used only inside `key-wallet` become `pub(crate)` or private. --- key-wallet-manager/src/event_tests.rs | 3 +- key-wallet/src/lib.rs | 2 +- .../src/managed_account/address_pool.rs | 542 +----------------- .../managed_account/managed_account_trait.rs | 18 - .../managed_platform_account.rs | 15 - key-wallet/src/tests/address_pool_tests.rs | 80 --- 6 files changed, 17 insertions(+), 643 deletions(-) diff --git a/key-wallet-manager/src/event_tests.rs b/key-wallet-manager/src/event_tests.rs index 59321b177..b82562467 100644 --- a/key-wallet-manager/src/event_tests.rs +++ b/key-wallet-manager/src/event_tests.rs @@ -1536,7 +1536,8 @@ async fn test_mempool_tx_to_highest_external_carries_addresses_derived() { // Pin the persistence-critical payload against the wallet's // own AddressInfo for the same index. let stored = external_pool_after - .info_at_index(derived.derivation_index) + .addresses + .get(&derived.derivation_index) .unwrap_or_else(|| panic!("pool missing index {}", derived.derivation_index)); assert_eq!( derived.address, stored.address, diff --git a/key-wallet/src/lib.rs b/key-wallet/src/lib.rs index 3e049ba64..248f81530 100644 --- a/key-wallet/src/lib.rs +++ b/key-wallet/src/lib.rs @@ -48,7 +48,7 @@ pub use derivation::{DerivationPathBuilder, DerivationStrategy, KeyDerivation}; pub use dip9::{DerivationPathReference, DerivationPathType}; pub use error::{Error, Result}; pub use gap_limit::{GapLimit, GapLimitManager, GapLimitStage}; -pub use managed_account::address_pool::{AddressInfo, AddressPool, KeySource, PoolStats}; +pub use managed_account::address_pool::{AddressInfo, AddressPool, KeySource}; pub use managed_account::managed_account_type::ManagedAccountType; pub use managed_account::managed_platform_account::ManagedPlatformAccount; pub use managed_account::platform_address::PlatformP2PKHAddress; diff --git a/key-wallet/src/managed_account/address_pool.rs b/key-wallet/src/managed_account/address_pool.rs index 0ad5d0718..787d999d4 100644 --- a/key-wallet/src/managed_account/address_pool.rs +++ b/key-wallet/src/managed_account/address_pool.rs @@ -5,14 +5,12 @@ #[cfg(feature = "bincode")] use bincode_derive::{Decode, Encode}; -use core::fmt; #[cfg(feature = "serde")] use serde::{Deserialize, Serialize}; use std::collections::{BTreeMap, HashMap, HashSet}; use crate::bip32::{ChildNumber, DerivationPath, ExtendedPrivKey, ExtendedPubKey}; use crate::error::{Error, Result}; -use crate::gap_limit::DEFAULT_EXTERNAL_GAP_LIMIT; use crate::Network; use dashcore::address::Payload; #[cfg(feature = "eddsa")] @@ -132,7 +130,7 @@ pub enum DerivedKey { impl KeySource { /// Derive a child key at the given path /// Returns a DerivedKey which can be ECDSA, BLS, or EdDSA - pub fn derive_at_path(&self, path: &DerivationPath) -> Result { + fn derive_at_path(&self, path: &DerivationPath) -> Result { match self { KeySource::Private(xprv) => { let child = xprv.derive_priv(path).map_err(Error::Bip32)?; @@ -195,14 +193,6 @@ impl KeySource { } } - /// Legacy method for ECDSA-only derivation (for backward compatibility) - pub fn derive_ecdsa_at_path(&self, path: &DerivationPath) -> Result { - match self.derive_at_path(path)? { - DerivedKey::ECDSA(xpub) => Ok(xpub), - _ => Err(Error::InvalidParameter("Key source is not ECDSA".into())), - } - } - /// Check if this is a watch-only key source pub fn is_watch_only(&self) -> bool { matches!(self, KeySource::Public(_)) @@ -340,7 +330,7 @@ impl AddressInfo { } /// Whether this address is currently reserved (handed out but not yet used). - pub fn is_reserved(&self) -> bool { + fn is_reserved(&self) -> bool { matches!(self.state, AddressState::Reserved { .. }) } @@ -358,13 +348,6 @@ impl AddressInfo { _ => None, } } - - /// Update transaction statistics - pub fn update_stats(&mut self, received: u64, sent: u64) { - self.total_received += received; - self.total_sent += sent; - self.tx_count += 1; - } } /// Address pool for managing HD wallet addresses @@ -437,11 +420,6 @@ impl AddressPool { } } - /// Set the address type for new addresses - pub fn set_address_type(&mut self, address_type: AddressType) { - self.address_type = address_type; - } - /// Check if this is an internal (change) address pool pub fn is_internal(&self) -> bool { self.pool_type == AddressPoolType::Internal @@ -478,7 +456,7 @@ impl AddressPool { } /// Generate every address up to and including `index` - pub fn generate_up_to( + pub(crate) fn generate_up_to( &mut self, index: u32, key_source: &KeySource, @@ -595,7 +573,7 @@ impl AddressPool { } /// Get the next unused address info - pub fn next_unused_with_info( + pub(crate) fn next_unused_with_info( &mut self, key_source: &KeySource, add_to_state: bool, @@ -634,7 +612,11 @@ impl AddressPool { /// reclaimed only by [`AddressPool::release_reservation`] and /// [`AddressPool::sweep_expired_reservations`], so callers are assumed /// trusted. Gate or cap this before exposing it to untrusted input. - pub fn next_unused_and_reserve(&mut self, key_source: &KeySource, now: u64) -> Result
{ + pub(crate) fn next_unused_and_reserve( + &mut self, + key_source: &KeySource, + now: u64, + ) -> Result
{ let index = self.next_unused_with_info(key_source, true)?.index; // A lookup miss would hand out an unreserved address, so fail instead. let info = self.addresses.get_mut(&index).ok_or_else(|| { @@ -674,7 +656,7 @@ impl AddressPool { /// declines to judge staleness and reclaims nothing. A `ttl` of 0 means no /// expiry window, so nothing is reclaimed either. A reservation stamped with /// `at == 0` (its caller had no clock) is likewise never aged out. - pub fn sweep_expired_reservations(&mut self, now: u64, ttl: u64) -> usize { + pub(crate) fn sweep_expired_reservations(&mut self, now: u64, ttl: u64) -> usize { if now == 0 || ttl == 0 { return 0; } @@ -702,7 +684,7 @@ impl AddressPool { /// Returns the requested number of unused addresses, generating new ones if needed. /// This is more efficient than calling `next_unused` multiple times as it minimizes /// the search through existing addresses. - pub fn next_unused_multiple( + pub(crate) fn next_unused_multiple( &mut self, count: usize, key_source: &KeySource, @@ -741,77 +723,6 @@ impl AddressPool { addresses } - /// Get multiple unused addresses with their info at once - /// - /// Returns the requested number of unused addresses with their full information, - /// generating new ones if needed. This is more efficient than calling - /// `next_unused_with_info` multiple times. - pub fn next_unused_multiple_with_info( - &mut self, - count: usize, - key_source: &KeySource, - add_to_state: bool, - ) -> Vec<(Address, AddressInfo)> { - let mut result = Vec::with_capacity(count); - - // First, collect existing unused addresses with their info - let mut collected = 0; - for i in 0..=self.highest_generated.unwrap_or(0) { - if collected >= count { - break; - } - if let Some(info) = self.addresses.get(&i) { - if info.is_available() { - result.push((info.address.clone(), info.clone())); - collected += 1; - } - } - } - - // If we have enough unused addresses, return them - if result.len() >= count { - result.truncate(count); - return result; - } - - // If NoKeySource and we don't have enough addresses, return what we have - if matches!(key_source, KeySource::NoKeySource) { - return result; - } - - let remaining = (count - result.len()) as u32; - let generated = self.generate_addresses(remaining, key_source, add_to_state); - result.extend( - generated.unwrap_or_default().into_iter().map(|info| (info.address.clone(), info)), - ); - result - } - - /// Get multiple unused addresses - pub fn unused_addresses_count( - &mut self, - count: u32, - key_source: &KeySource, - ) -> Result> { - let mut unused = Vec::new(); - let mut current_index = 0; - - // Collect existing unused addresses - while unused.len() < count as usize && current_index < self.next_index_to_derive() { - if let Some(info) = self.addresses.get(¤t_index) { - if info.is_available() { - unused.push(info.address.clone()); - } - } - current_index += 1; - } - - let remaining = count - unused.len() as u32; - let generated = self.generate_addresses(remaining, key_source, true)?; - unused.extend(generated.into_iter().map(|info| info.address)); - Ok(unused) - } - /// Mark an address as used pub fn mark_used(&mut self, address: &Address) -> bool { let Some(&index) = self.address_index.get(address) else { @@ -833,44 +744,16 @@ impl AddressPool { true } - /// Scan addresses for usage using a check function - pub fn scan_for_usage(&mut self, check_fn: F) -> Vec
- where - F: Fn(&Address) -> bool, - { - let found: Vec
= self - .addresses - .values() - .filter(|info| !info.is_used() && check_fn(&info.address)) - .map(|info| info.address.clone()) - .collect(); - - for address in &found { - self.mark_used(address); - } - - found - } - /// Get all addresses in the pool pub fn all_addresses(&self) -> Vec
{ self.addresses.values().map(|info| info.address.clone()).collect() } /// Get cached scriptPubKeys for every address in the pool. - pub fn all_script_pubkeys(&self) -> Vec { + pub(crate) fn all_script_pubkeys(&self) -> Vec { self.addresses.values().map(|info| info.script_pubkey.clone()).collect() } - /// Get only used addresses - pub fn used_addresses(&self) -> Vec
{ - self.addresses - .values() - .filter(|info| info.is_used()) - .map(|info| info.address.clone()) - .collect() - } - /// Get only available addresses (neither used nor reserved) pub fn unused_addresses(&self) -> Vec
{ self.addresses @@ -899,66 +782,21 @@ impl AddressPool { } } - /// Get address info by index - pub fn info_at_index(&self, index: u32) -> Option<&AddressInfo> { - self.addresses.get(&index) - } - /// Get the index of an address pub fn address_index(&self, address: &Address) -> Option { self.address_index.get(address).copied() } - /// Get the index of an address by its script pubkey - pub fn script_pubkey_index(&self, script_pubkey: &ScriptBuf) -> Option { - self.script_pubkey_index.get(script_pubkey).copied() - } - /// Check if an address belongs to this pool pub fn contains_address(&self, address: &Address) -> bool { self.address_index.contains_key(address) } /// Check if a script pubkey belongs to this pool - pub fn contains_script_pubkey(&self, script_pubkey: &ScriptBuf) -> bool { + pub(crate) fn contains_script_pubkey(&self, script_pubkey: &ScriptBuf) -> bool { self.script_pubkey_index.contains_key(script_pubkey) } - /// Get addresses in the specified range - /// - /// Returns addresses from start_index (inclusive) to end_index (exclusive). - /// If addresses in the range haven't been generated yet, they will be generated. - pub fn address_range( - &mut self, - start_index: u32, - end_index: u32, - key_source: &KeySource, - ) -> Result> { - if end_index <= start_index { - return Ok(Vec::new()); - } - - self.generate_up_to(end_index - 1, key_source)?; - - // Collect addresses in the range - let mut addresses = Vec::new(); - for index in start_index..end_index { - if let Some(info) = self.addresses.get(&index) { - addresses.push(info.address.clone()); - } - } - - Ok(addresses) - } - - /// Check if we need to generate more addresses - pub fn needs_more_addresses(&self) -> bool { - let available_count = - self.addresses.values().filter(|info| info.is_available()).count() as u32; - - available_count < self.gap_limit - } - /// Raise the gap limit and generate the addresses the wider limit now requires. /// /// The new limit is capped at [`crate::gap_limit::MAX_GAP_LIMIT`]. Returns the freshly @@ -986,230 +824,6 @@ impl AddressPool { }; self.generate_up_to(target, key_source) } - - /// Set a custom label for an address - pub fn set_address_label(&mut self, address: &Address, label: String) -> bool { - if let Some(info) = self.address_info_mut(address) { - info.label = Some(label); - true - } else { - false - } - } - - /// Add custom metadata to an address - pub fn add_address_metadata(&mut self, address: &Address, key: String, value: String) -> bool { - if let Some(info) = self.address_info_mut(address) { - info.metadata.insert(key, value); - true - } else { - false - } - } - - /// Get pool statistics - pub fn stats(&self) -> PoolStats { - let used_count = self.used_indices.len() as u32; - let reserved_count = - self.addresses.values().filter(|info| info.is_reserved()).count() as u32; - let unused_count = self.addresses.len() as u32 - used_count - reserved_count; - - PoolStats { - total_generated: self.addresses.len() as u32, - used_count, - reserved_count, - unused_count, - highest_used: self.highest_used, - highest_generated: self.highest_generated, - gap_limit: self.gap_limit, - is_internal: self.is_internal(), - } - } - - /// Reset the pool (for rescan) - pub fn reset_usage(&mut self) { - for info in self.addresses.values_mut() { - info.state = AddressState::Available; - info.tx_count = 0; - info.total_received = 0; - info.total_sent = 0; - info.balance = 0; - } - self.used_indices.clear(); - self.highest_used = None; - } - - /// Prune unused addresses beyond the gap limit - pub fn prune_unused(&mut self) -> u32 { - let keep_until = match self.highest_used { - None => self.gap_limit - 1, // Keep indices 0 to gap_limit-1 - Some(highest) => highest + self.gap_limit, // Keep up to highest + gap_limit - }; - - let mut pruned = 0; - let indices_to_remove: Vec = self - .addresses - .iter() - .filter(|(&idx, info)| { - idx > keep_until && !self.used_indices.contains(&idx) && !info.is_reserved() - }) - .map(|(&idx, _)| idx) - .collect(); - - for idx in indices_to_remove { - if let Some(info) = self.addresses.remove(&idx) { - self.address_index.remove(&info.address); - self.script_pubkey_index.remove(&info.script_pubkey); - pruned += 1; - } - } - - if let Some(&new_highest) = self.addresses.keys().max() { - self.highest_generated = Some(new_highest); - } - - pruned - } -} - -/// Pool statistics -#[derive(Debug, Clone)] -#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] -pub struct PoolStats { - /// Total addresses generated - pub total_generated: u32, - /// Number of used addresses - pub used_count: u32, - /// Number of reserved addresses (handed out but not yet used) - pub reserved_count: u32, - /// Number of unused addresses (neither used nor reserved) - pub unused_count: u32, - /// Highest used index - pub highest_used: Option, - /// Highest generated index (None if no addresses generated) - pub highest_generated: Option, - /// Gap limit - pub gap_limit: u32, - /// Whether this is an internal pool - pub is_internal: bool, -} - -impl fmt::Display for PoolStats { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write!( - f, - "{} pool: {} addresses ({} used, {} reserved, {} unused), gap limit: {}", - if self.is_internal { - "Internal" - } else { - "External" - }, - self.total_generated, - self.used_count, - self.reserved_count, - self.unused_count, - self.gap_limit - ) - } -} - -/// Builder for AddressPool -pub struct AddressPoolBuilder { - base_path: Option, - pool_type: AddressPoolType, - gap_limit: u32, - network: Network, - address_type: AddressType, - key_source: Option, -} - -impl AddressPoolBuilder { - /// Create a new builder - pub fn new() -> Self { - Self { - base_path: None, - pool_type: AddressPoolType::External, - gap_limit: DEFAULT_EXTERNAL_GAP_LIMIT, - network: Network::Mainnet, - address_type: AddressType::P2pkh, - key_source: None, - } - } - - /// Set the base derivation path - pub fn base_path(mut self, path: DerivationPath) -> Self { - self.base_path = Some(path); - self - } - - /// Set the pool type (external, internal, or absent) - pub fn pool_type(mut self, pool_type: AddressPoolType) -> Self { - self.pool_type = pool_type; - self - } - - /// Set whether this is an internal (change) pool (compatibility method) - pub fn internal(mut self, is_internal: bool) -> Self { - self.pool_type = if is_internal { - AddressPoolType::Internal - } else { - AddressPoolType::External - }; - self - } - - /// Set the gap limit - pub fn gap_limit(mut self, limit: u32) -> Self { - self.gap_limit = limit; - self - } - - /// Set the network - pub fn network(mut self, network: Network) -> Self { - self.network = network; - self - } - - /// Set the address type - pub fn address_type(mut self, addr_type: AddressType) -> Self { - self.address_type = addr_type; - self - } - - /// Set the key source for generating addresses - pub fn key_source(mut self, key_source: KeySource) -> Self { - self.key_source = Some(key_source); - self - } - - /// Build the address pool - pub fn build(self) -> Result { - let base_path = - self.base_path.ok_or(Error::InvalidParameter("base_path required".into()))?; - - let mut pool = AddressPool::new_without_generation( - base_path, - self.pool_type, - self.gap_limit, - self.network, - ); - pool.address_type = self.address_type; - - // Generate addresses if a key source was provided - if let Some(key_source) = self.key_source { - if !matches!(key_source, KeySource::NoKeySource) { - pool.generate_addresses(self.gap_limit, &key_source, true)?; - } - } - - Ok(pool) - } -} - -impl Default for AddressPoolBuilder { - fn default() -> Self { - Self::new() - } } #[cfg(test)] @@ -1288,9 +902,7 @@ mod tests { assert_eq!(pool.used_indices.len(), 1); assert_eq!(pool.highest_used, Some(0)); - let used = pool.used_addresses(); - assert_eq!(used.len(), 1); - assert_eq!(&used[0], first_addr); + assert!(pool.address_info(first_addr).unwrap().is_used()); } #[test] @@ -1542,67 +1154,6 @@ mod tests { assert_eq!(old, reissued); } - #[test] - fn test_reset_usage_clears_reservations() { - let base_path = DerivationPath::from(vec![ChildNumber::from_normal_idx(0).unwrap()]); - let mut pool = AddressPool::new_without_generation( - base_path, - AddressPoolType::External, - 5, - Network::Testnet, - ); - let key_source = test_key_source(); - - let reserved = pool.next_unused_and_reserve(&key_source, 100).unwrap(); - let index = pool.address_index(&reserved).unwrap(); - assert!(pool.addresses.get(&index).unwrap().is_reserved()); - - // A rescan reset must drop reservations too, otherwise the address stays - // pinned forever and is never handed out again. - pool.reset_usage(); - assert!(!pool.addresses.get(&index).unwrap().is_reserved()); - - let reissued = pool.next_unused_and_reserve(&key_source, 200).unwrap(); - assert_eq!(reserved, reissued); - } - - #[test] - fn test_prune_never_drops_reserved() { - let base_path = DerivationPath::from(vec![ChildNumber::from_normal_idx(0).unwrap()]); - let gap_limit = 5; - let mut pool = AddressPool::new_without_generation( - base_path, - AddressPoolType::External, - gap_limit, - Network::Testnet, - ); - let key_source = test_key_source(); - pool.generate_addresses(10, &key_source, true).unwrap(); - - // Mark index 0 used so keep_until = highest_used + gap_limit = 5. - pool.mark_used(&pool.address_at_index(0).unwrap()); - - // Reserve indices 1..=7 (first available each time, index 0 is used). - let mut reserved = Vec::new(); - for t in 0..7 { - reserved.push(pool.next_unused_and_reserve(&key_source, 100 + t).unwrap()); - } - - // Indices 6 and 7 are reserved and beyond keep_until. Indices 8 and 9 - // are plain unused beyond keep_until and are the only prunable entries. - let pruned = pool.prune_unused(); - assert_eq!(pruned, 2); - assert!(!pool.addresses.contains_key(&8)); - assert!(!pool.addresses.contains_key(&9)); - - // Every reserved address survived the prune. - for addr in &reserved { - assert!(pool.address_index(addr).is_some()); - } - assert!(pool.addresses.get(&6).unwrap().is_reserved()); - assert!(pool.addresses.get(&7).unwrap().is_reserved()); - } - #[test] fn test_gap_limit_maintenance() { let base_path = DerivationPath::from(vec![ChildNumber::from_normal_idx(0).unwrap()]); @@ -1653,69 +1204,4 @@ mod tests { assert_eq!(pool.highest_generated, Some(gap_limit + 2)); assert_eq!(pool.addresses.len(), gap_limit as usize + 3); } - - #[test] - fn test_reserved_addresses_count_against_gap_limit() { - let base_path = DerivationPath::from(vec![ChildNumber::from_normal_idx(0).unwrap()]); - let key_source = test_key_source(); - let gap_limit = 5; - - // A pool with exactly gap_limit available addresses needs no more. - let mut pool = AddressPool::new( - base_path, - AddressPoolType::External, - gap_limit, - Network::Testnet, - &key_source, - ) - .unwrap(); - assert!(!pool.needs_more_addresses()); - - // Reserving one drops available headroom below the gap limit, so the - // pool now reports it needs more even though nothing was used. - pool.next_unused_and_reserve(&key_source, 100).unwrap(); - assert!(pool.needs_more_addresses()); - } - - #[test] - fn test_address_pool_builder() { - let pool = AddressPoolBuilder::new() - .base_path(DerivationPath::from(vec![ChildNumber::from_normal_idx(0).unwrap()])) - .internal(true) - .gap_limit(10) - .network(Network::Testnet) - .address_type(AddressType::P2pkh) - .build() - .unwrap(); - - assert!(pool.is_internal()); - assert_eq!(pool.gap_limit, 10); - assert_eq!(pool.network, Network::Testnet); - } - - #[test] - fn test_scan_for_usage() { - let base_path = DerivationPath::from(vec![ChildNumber::from_normal_idx(0).unwrap()]); - let mut pool = AddressPool::new_without_generation( - base_path, - AddressPoolType::External, - 5, - Network::Testnet, - ); - let key_source = test_key_source(); - - let addresses = pool.generate_addresses(10, &key_source, true).unwrap(); - - // Simulate checking for usage - mark addresses at indices 2, 5, 7 as used - let check_fn = |addr: &Address| { - addresses[2].address == *addr - || addresses[5].address == *addr - || addresses[7].address == *addr - }; - - let found = pool.scan_for_usage(check_fn); - assert_eq!(found.len(), 3); - assert_eq!(pool.used_indices.len(), 3); - assert_eq!(pool.highest_used, Some(7)); - } } diff --git a/key-wallet/src/managed_account/managed_account_trait.rs b/key-wallet/src/managed_account/managed_account_trait.rs index adb4bf809..60bdf97fa 100644 --- a/key-wallet/src/managed_account/managed_account_trait.rs +++ b/key-wallet/src/managed_account/managed_account_trait.rs @@ -426,24 +426,6 @@ pub trait ManagedAccountTrait { self.managed_account_type().get_address_derivation_path(address) } - /// Get total address count across all pools - fn total_address_count(&self) -> usize { - self.managed_account_type() - .address_pools() - .iter() - .map(|pool| pool.stats().total_generated as usize) - .sum() - } - - /// Get used address count across all pools - fn used_address_count(&self) -> usize { - self.managed_account_type() - .address_pools() - .iter() - .map(|pool| pool.stats().used_count as usize) - .sum() - } - /// Widen the gap limit for every address pool of this account. /// Returns every freshly generated address (across all pools) fn set_gap_limit( diff --git a/key-wallet/src/managed_account/managed_platform_account.rs b/key-wallet/src/managed_account/managed_platform_account.rs index 48c8ba93f..c8416ff3a 100644 --- a/key-wallet/src/managed_account/managed_platform_account.rs +++ b/key-wallet/src/managed_account/managed_platform_account.rs @@ -288,21 +288,6 @@ impl ManagedPlatformAccount { self.addresses.address_info(address).cloned() } - /// Get pool statistics - pub fn address_pool_stats(&self) -> super::address_pool::PoolStats { - self.addresses.stats() - } - - /// Get total address count in the pool - pub fn total_address_count(&self) -> usize { - self.addresses.stats().total_generated as usize - } - - /// Get used address count in the pool - pub fn used_address_count(&self) -> usize { - self.addresses.stats().used_count as usize - } - /// Get the gap limit for the address pool pub fn gap_limit(&self) -> u32 { self.addresses.gap_limit diff --git a/key-wallet/src/tests/address_pool_tests.rs b/key-wallet/src/tests/address_pool_tests.rs index 92a61713a..9d1dde5b4 100644 --- a/key-wallet/src/tests/address_pool_tests.rs +++ b/key-wallet/src/tests/address_pool_tests.rs @@ -65,44 +65,6 @@ fn test_next_unused_multiple() { assert_eq!(pool.highest_generated, Some(7)); // Generated 3 more } -#[test] -fn test_next_unused_multiple_with_info() { - let base_path = DerivationPath::from(vec![ChildNumber::from_normal_idx(0).unwrap()]); - let mut pool = AddressPool::new_without_generation( - base_path, - AddressPoolType::External, - 20, - Network::Testnet, - ); - let (key_source, _) = test_key_source(); - - // Test getting multiple addresses with info - let address_infos = pool.next_unused_multiple_with_info(3, &key_source, true); - assert_eq!(address_infos.len(), 3); - - // Verify the info contains correct data - for (i, (addr, info)) in address_infos.iter().enumerate() { - assert_eq!(addr, &info.address); - assert_eq!(info.index, i as u32); - assert!(!info.is_used()); - assert!(info.public_key.is_some()); - } - - // Mark first one as used - pool.mark_used(&address_infos[0].0); - - // Reserve the second one: it must be skipped alongside the used one. - let reserved = pool.next_unused_and_reserve(&key_source, 100).unwrap(); - assert_eq!(reserved, address_infos[1].0); - - // Get more with info: should skip both the used and the reserved address, - // still returning the requested count by deriving fresh addresses. - let more_infos = pool.next_unused_multiple_with_info(3, &key_source, true); - assert_eq!(more_infos.len(), 3); - assert!(!more_infos.iter().any(|(addr, _)| addr == &reserved)); - assert_eq!(more_infos[0].0, address_infos[2].0); // First available after used + reserved -} - #[test] fn test_next_unused_multiple_no_key_source() { let base_path = DerivationPath::from(vec![ChildNumber::from_normal_idx(0).unwrap()]); @@ -192,45 +154,3 @@ fn test_next_unused_multiple_mixed_usage() { assert!(!initial.contains(&next_batch[6])); assert!(!initial.contains(&next_batch[7])); } - -/// `prune_unused` must drop a pruned address from BOTH reverse indexes it -/// maintains — `address_index` and `script_pubkey_index`. A leftover -/// `script_pubkey_index` entry would let a pruned (unwatched) script still -/// resolve to an index and be treated as wallet-relevant. Regression guard for -/// the missing `script_pubkey_index.remove` in `prune_unused` -/// (dashpay/rust-dashcore#649 companion fix). -#[test] -fn prune_unused_clears_script_pubkey_index() { - let base_path = DerivationPath::from(vec![ChildNumber::from_normal_idx(0).unwrap()]); - let gap_limit = 20u32; - let mut pool = AddressPool::new_without_generation( - base_path, - AddressPoolType::External, - gap_limit, - Network::Testnet, - ); - let (key_source, _) = test_key_source(); - - // Generate well beyond the gap limit; none are marked used, so with - // `highest_used == None` everything above `gap_limit - 1` is prunable. - pool.generate_addresses(gap_limit + 10, &key_source, true).unwrap(); - - // Pick an index that will be pruned and capture its address + script. - let victim_index = gap_limit + 5; - let victim = pool.addresses.get(&victim_index).expect("victim address generated").clone(); - assert_eq!(pool.address_index.get(&victim.address), Some(&victim_index)); - assert_eq!(pool.script_pubkey_index.get(&victim.script_pubkey), Some(&victim_index)); - - let pruned = pool.prune_unused(); - assert!(pruned > 0, "addresses beyond the gap limit should be pruned"); - - assert!(!pool.addresses.contains_key(&victim_index), "pruned address removed from pool"); - assert!( - !pool.address_index.contains_key(&victim.address), - "pruned address removed from address_index" - ); - assert!( - !pool.script_pubkey_index.contains_key(&victim.script_pubkey), - "pruned address must also be removed from script_pubkey_index" - ); -} From cc41eb6d2ad40b55f860fbcfb905705c76667ce7 Mon Sep 17 00:00:00 2001 From: Borja Castellano Date: Wed, 11 Nov 2026 04:24:15 -0800 Subject: [PATCH 04/22] refactor(key-wallet)!: drop unused batch address getters `ManagedCoreFundsAccount::next_receive_addresses` and `next_change_addresses` had no callers in this repository or in Dash Platform, and they were the only users of `AddressPool::next_unused_multiple`. This removes the three methods and the tests that covered only them. --- .../src/managed_account/address_pool.rs | 44 ----- .../managed_core_funds_account.rs | 76 --------- key-wallet/src/tests/address_pool_tests.rs | 156 ------------------ key-wallet/src/tests/mod.rs | 2 - 4 files changed, 278 deletions(-) delete mode 100644 key-wallet/src/tests/address_pool_tests.rs diff --git a/key-wallet/src/managed_account/address_pool.rs b/key-wallet/src/managed_account/address_pool.rs index 787d999d4..b3e6342e8 100644 --- a/key-wallet/src/managed_account/address_pool.rs +++ b/key-wallet/src/managed_account/address_pool.rs @@ -679,50 +679,6 @@ impl AddressPool { reclaimed } - /// Get multiple unused addresses at once - /// - /// Returns the requested number of unused addresses, generating new ones if needed. - /// This is more efficient than calling `next_unused` multiple times as it minimizes - /// the search through existing addresses. - pub(crate) fn next_unused_multiple( - &mut self, - count: usize, - key_source: &KeySource, - add_to_state: bool, - ) -> Vec
{ - let mut addresses = Vec::with_capacity(count); - - // First, collect existing unused addresses - let mut collected = 0; - for i in 0..=self.highest_generated.unwrap_or(0) { - if collected >= count { - break; - } - if let Some(info) = self.addresses.get(&i) { - if info.is_available() { - addresses.push(info.address.clone()); - collected += 1; - } - } - } - - // If we have enough unused addresses, return them - if addresses.len() >= count { - addresses.truncate(count); - return addresses; - } - - // If NoKeySource and we don't have enough addresses, return what we have - if matches!(key_source, KeySource::NoKeySource) { - return addresses; - } - - let remaining = (count - addresses.len()) as u32; - let generated = self.generate_addresses(remaining, key_source, add_to_state); - addresses.extend(generated.unwrap_or_default().into_iter().map(|info| info.address)); - addresses - } - /// Mark an address as used pub fn mark_used(&mut self, address: &Address) -> bool { let Some(&index) = self.address_index.get(address) else { 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..fe49bd0d0 100644 --- a/key-wallet/src/managed_account/managed_core_funds_account.rs +++ b/key-wallet/src/managed_account/managed_core_funds_account.rs @@ -1529,82 +1529,6 @@ impl ManagedCoreFundsAccount { } } - /// Generate multiple receive addresses at once using the optionally provided extended public key. - /// Only valid for Standard accounts. - pub fn next_receive_addresses( - &mut self, - account_xpub: Option<&ExtendedPubKey>, - count: usize, - add_to_state: bool, - ) -> Result, String> { - if let ManagedAccountType::Standard { - external_addresses, - .. - } = self.keys.managed_account_type_mut() - { - let key_source = match account_xpub { - Some(xpub) => address_pool::KeySource::Public(*xpub), - None => address_pool::KeySource::NoKeySource, - }; - - let addresses = - external_addresses.next_unused_multiple(count, &key_source, add_to_state); - if addresses.is_empty() && count > 0 { - Err("Failed to generate any receive addresses".to_string()) - } else if addresses.len() < count - && matches!(key_source, address_pool::KeySource::NoKeySource) - { - Err(format!( - "Could only generate {} out of {} requested addresses (no key source)", - addresses.len(), - count - )) - } else { - Ok(addresses) - } - } else { - Err("Cannot generate receive addresses for non-standard account type".to_string()) - } - } - - /// Generate multiple change addresses at once using the optionally provided extended public key. - /// Only valid for Standard accounts. - pub fn next_change_addresses( - &mut self, - account_xpub: Option<&ExtendedPubKey>, - count: usize, - add_to_state: bool, - ) -> Result, String> { - if let ManagedAccountType::Standard { - internal_addresses, - .. - } = self.keys.managed_account_type_mut() - { - let key_source = match account_xpub { - Some(xpub) => address_pool::KeySource::Public(*xpub), - None => address_pool::KeySource::NoKeySource, - }; - - let addresses = - internal_addresses.next_unused_multiple(count, &key_source, add_to_state); - if addresses.is_empty() && count > 0 { - Err("Failed to generate any change addresses".to_string()) - } else if addresses.len() < count - && matches!(key_source, address_pool::KeySource::NoKeySource) - { - Err(format!( - "Could only generate {} out of {} requested addresses (no key source)", - addresses.len(), - count - )) - } else { - Ok(addresses) - } - } else { - Err("Cannot generate change addresses for non-standard account type".to_string()) - } - } - /// Get the external gap limit for standard accounts pub fn external_gap_limit(&self) -> Option { match self.keys.managed_account_type() { diff --git a/key-wallet/src/tests/address_pool_tests.rs b/key-wallet/src/tests/address_pool_tests.rs deleted file mode 100644 index 9d1dde5b4..000000000 --- a/key-wallet/src/tests/address_pool_tests.rs +++ /dev/null @@ -1,156 +0,0 @@ -//! Tests for address pool management -//! -//! Tests address generation, gap limit enforcement, and pool operations. - -use crate::bip32::{ChildNumber, DerivationPath, ExtendedPrivKey, ExtendedPubKey}; -use crate::managed_account::address_pool::{AddressPool, AddressPoolType, KeySource}; -use crate::mnemonic::Mnemonic; -use crate::Network; -use std::collections::HashSet; - -fn test_key_source() -> (KeySource, ExtendedPubKey) { - let mnemonic = Mnemonic::from_phrase("abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about") - .unwrap(); - let seed = mnemonic.to_seed(""); - let master = ExtendedPrivKey::new_master(Network::Testnet, &seed[..]).unwrap(); - - let path = DerivationPath::from(vec![ - ChildNumber::from_hardened_idx(44).unwrap(), - ChildNumber::from_hardened_idx(1).unwrap(), - ChildNumber::from_hardened_idx(0).unwrap(), - ]); - let account_key = master.derive_priv(&path).unwrap(); - let xpub = ExtendedPubKey::from_priv(&account_key); - - (KeySource::Private(account_key), xpub) -} - -#[test] -fn test_next_unused_multiple() { - let base_path = DerivationPath::from(vec![ChildNumber::from_normal_idx(0).unwrap()]); - let mut pool = AddressPool::new_without_generation( - base_path, - AddressPoolType::External, - 20, - Network::Testnet, - ); - let (key_source, _) = test_key_source(); - - // Test getting multiple unused addresses - let addresses = pool.next_unused_multiple(5, &key_source, true); - assert_eq!(addresses.len(), 5); - assert_eq!(pool.highest_generated, Some(4)); - - // Verify all addresses are unique - let unique_check: HashSet<_> = addresses.iter().collect(); - assert_eq!(unique_check.len(), 5); - - // Mark some as used - pool.mark_used(&addresses[0]); - pool.mark_used(&addresses[2]); - - // Reserve the first remaining unused address: it must be skipped too. - let reserved = pool.next_unused_and_reserve(&key_source, 100).unwrap(); - assert_eq!(reserved, addresses[1]); - - // Request more addresses: should skip used and reserved, returning the - // remaining generated ones plus freshly derived ones to satisfy the count. - let more_addresses = pool.next_unused_multiple(5, &key_source, true); - assert_eq!(more_addresses.len(), 5); - assert!(!more_addresses.contains(&reserved)); - assert_eq!(more_addresses[0], addresses[3]); // First available - assert_eq!(more_addresses[1], addresses[4]); // Second available - // remaining entries are newly generated - - assert_eq!(pool.highest_generated, Some(7)); // Generated 3 more -} - -#[test] -fn test_next_unused_multiple_no_key_source() { - let base_path = DerivationPath::from(vec![ChildNumber::from_normal_idx(0).unwrap()]); - let mut pool = AddressPool::new_without_generation( - base_path, - AddressPoolType::External, - 20, - Network::Testnet, - ); - - let no_key_source = KeySource::NoKeySource; - - // With NoKeySource and no pre-generated addresses, should return empty vec - let addresses = pool.next_unused_multiple(5, &no_key_source, true); - assert_eq!(addresses.len(), 0); - - // Generate some addresses first with a real key source - let (key_source, _) = test_key_source(); - pool.generate_addresses(3, &key_source, true).unwrap(); - - // Now with NoKeySource, should return existing unused addresses - let addresses = pool.next_unused_multiple(5, &no_key_source, true); - assert_eq!(addresses.len(), 3); // Only the 3 we generated - - // Mark one as used - pool.mark_used(&addresses[0]); - - // Should now return only 2 unused addresses - let addresses = pool.next_unused_multiple(5, &no_key_source, true); - assert_eq!(addresses.len(), 2); -} - -#[test] -fn test_next_unused_multiple_large_batch() { - let base_path = DerivationPath::from(vec![ChildNumber::from_normal_idx(0).unwrap()]); - let mut pool = AddressPool::new_without_generation( - base_path, - AddressPoolType::External, - 20, - Network::Testnet, - ); - let (key_source, _) = test_key_source(); - - // Test generating a large batch efficiently - let addresses = pool.next_unused_multiple(100, &key_source, true); - assert_eq!(addresses.len(), 100); - assert_eq!(pool.highest_generated, Some(99)); - - // All addresses should be unique - let unique_check: HashSet<_> = addresses.iter().collect(); - assert_eq!(unique_check.len(), 100); -} - -#[test] -fn test_next_unused_multiple_mixed_usage() { - let base_path = DerivationPath::from(vec![ChildNumber::from_normal_idx(0).unwrap()]); - let mut pool = AddressPool::new_without_generation( - base_path, - AddressPoolType::Internal, // Test with internal pool type - 20, - Network::Testnet, - ); - let (key_source, _) = test_key_source(); - - // Generate initial batch - let initial = pool.next_unused_multiple(10, &key_source, true); - assert_eq!(initial.len(), 10); - - // Mark every other address as used - for i in (0..10).step_by(2) { - pool.mark_used(&initial[i]); - } - - // Request 8 addresses - should get 5 unused + 3 new - let next_batch = pool.next_unused_multiple(8, &key_source, true); - assert_eq!(next_batch.len(), 8); - - // First 5 should be the unused ones from initial batch - assert_eq!(next_batch[0], initial[1]); - assert_eq!(next_batch[1], initial[3]); - assert_eq!(next_batch[2], initial[5]); - assert_eq!(next_batch[3], initial[7]); - assert_eq!(next_batch[4], initial[9]); - - // Last 3 should be new addresses - assert!(!initial.contains(&next_batch[5])); - assert!(!initial.contains(&next_batch[6])); - assert!(!initial.contains(&next_batch[7])); -} diff --git a/key-wallet/src/tests/mod.rs b/key-wallet/src/tests/mod.rs index 0481a7a3b..8aee85558 100644 --- a/key-wallet/src/tests/mod.rs +++ b/key-wallet/src/tests/mod.rs @@ -6,8 +6,6 @@ mod account_tests; mod balance_tests; -mod address_pool_tests; - mod address_reservation_tests; mod advanced_transaction_tests; From f5036cb858b2440826843914da6dbf5d4d3b77e1 Mon Sep 17 00:00:00 2001 From: Borja Castellano Date: Wed, 11 Nov 2026 04:28:01 -0800 Subject: [PATCH 05/22] refactor(key-wallet): drop redundant `NoKeySource` checks in `AddressPool` `next_unused_with_info` checked for `KeySource::NoKeySource` before deriving, but derivation already fails with `Error::NoKeySource`. `AddressPool::new` now uses `KeySource::can_derive` instead of matching the variant. --- key-wallet/src/managed_account/address_pool.rs | 7 +------ 1 file changed, 1 insertion(+), 6 deletions(-) diff --git a/key-wallet/src/managed_account/address_pool.rs b/key-wallet/src/managed_account/address_pool.rs index b3e6342e8..0f614e5b3 100644 --- a/key-wallet/src/managed_account/address_pool.rs +++ b/key-wallet/src/managed_account/address_pool.rs @@ -391,7 +391,7 @@ impl AddressPool { let mut pool = Self::new_without_generation(base_path, pool_type, gap_limit, network); // Generate addresses up to the gap limit if we have a key source - if !matches!(key_source, KeySource::NoKeySource) { + if key_source.can_derive() { pool.generate_addresses(gap_limit, key_source, true)?; } @@ -583,11 +583,6 @@ impl AddressPool { return Ok(info.clone()); } - // If NoKeySource, we can't generate new addresses - if matches!(key_source, KeySource::NoKeySource) { - return Err(Error::NoKeySource); - } - self.generate_addresses(1, key_source, add_to_state)? .pop() .ok_or_else(|| Error::InvalidState("generate_addresses(1) returned nothing".into())) From e493ee20f2ee85f14f6c395a32120d597c214cc7 Mon Sep 17 00:00:00 2001 From: Borja Castellano Date: Wed, 11 Nov 2026 04:29:53 -0800 Subject: [PATCH 06/22] refactor(key-wallet): simplify `AddressPool::address_info_mut` --- key-wallet/src/managed_account/address_pool.rs | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/key-wallet/src/managed_account/address_pool.rs b/key-wallet/src/managed_account/address_pool.rs index 0f614e5b3..881b2f009 100644 --- a/key-wallet/src/managed_account/address_pool.rs +++ b/key-wallet/src/managed_account/address_pool.rs @@ -726,11 +726,7 @@ impl AddressPool { /// Get mutable address info by address pub fn address_info_mut(&mut self, address: &Address) -> Option<&mut AddressInfo> { - if let Some(&index) = self.address_index.get(address) { - self.addresses.get_mut(&index) - } else { - None - } + self.address_index.get(address).and_then(|index| self.addresses.get_mut(index)) } /// Get the index of an address From 67fa80de13a8666a04d317eaf70aa6939176ba56 Mon Sep 17 00:00:00 2001 From: Borja Castellano Date: Wed, 11 Nov 2026 04:41:01 -0800 Subject: [PATCH 07/22] refactor(key-wallet): build `AddressInfo` through one constructor --- .../src/managed_account/address_pool.rs | 25 ++++--------------- 1 file changed, 5 insertions(+), 20 deletions(-) diff --git a/key-wallet/src/managed_account/address_pool.rs b/key-wallet/src/managed_account/address_pool.rs index 881b2f009..8e856c023 100644 --- a/key-wallet/src/managed_account/address_pool.rs +++ b/key-wallet/src/managed_account/address_pool.rs @@ -258,18 +258,17 @@ pub struct AddressInfo { } impl AddressInfo { - /// Create new address info with a public key - fn new_with_public_key( + fn new( address: Address, index: u32, path: DerivationPath, - public_key: PublicKeyType, + public_key: Option, ) -> Self { let script_pubkey = address.script_pubkey(); Self { address, script_pubkey, - public_key: Some(public_key), + public_key, index, path, state: AddressState::Available, @@ -298,20 +297,7 @@ impl AddressInfo { return Err(Error::InvalidAddress("Script is not P2PKH".to_string())); } - Ok(Self { - address, - script_pubkey, - public_key: None, // Public key not available from script alone - index, - path, - state: AddressState::Available, - tx_count: 0, - total_received: 0, - total_sent: 0, - balance: 0, - label: None, - metadata: BTreeMap::new(), - }) + Ok(Self::new(address, index, path, None)) } /// Mark this address as used. @@ -551,8 +537,7 @@ impl AddressPool { (address, PublicKeyType::EdDSA(public_key_bytes)) } }; - let info = - AddressInfo::new_with_public_key(address.clone(), index, full_path, public_key_type); + let info = AddressInfo::new(address.clone(), index, full_path, Some(public_key_type)); if add_to_state { self.addresses.insert(index, info.clone()); self.address_index.insert(address, index); From 83eafc1e80c76fd3397858e6caaf36f66c709a74 Mon Sep 17 00:00:00 2001 From: Borja Castellano Date: Wed, 11 Nov 2026 05:03:17 -0800 Subject: [PATCH 08/22] refactor(key-wallet)!: derive `AddressPool` high-water marks from its entries `AddressPool` stored `used_indices`, `highest_generated` and `highest_used` next to `addresses`, so every insert or state change had to update them by hand, and callers that wrote the fields directly could leave them out of sync. The three fields are removed. `highest_generated()` and `highest_used()` compute the values from `addresses`, and the used set is the entries whose state is `Used`. --- .../filters/coinjoin_gap_discovery_tests.rs | 6 +- key-wallet-manager/src/event_tests.rs | 2 +- key-wallet-manager/src/process_block.rs | 2 +- .../src/managed_account/address_pool.rs | 55 ++++++++----------- .../tests/dashpay_contact_gap_limit_tests.rs | 4 +- key-wallet/src/tests/restore_utxos_tests.rs | 4 +- .../special_transaction_matching_tests.rs | 2 +- 7 files changed, 36 insertions(+), 39 deletions(-) diff --git a/dash-spv/src/sync/filters/coinjoin_gap_discovery_tests.rs b/dash-spv/src/sync/filters/coinjoin_gap_discovery_tests.rs index ecb7ba3c4..99a0f8cfd 100644 --- a/dash-spv/src/sync/filters/coinjoin_gap_discovery_tests.rs +++ b/dash-spv/src/sync/filters/coinjoin_gap_discovery_tests.rs @@ -124,7 +124,11 @@ async fn coinjoin_pool_state( let wm = wallet.read().await; let info = wm.get_wallet_info(wallet_id).expect("wallet info present"); let pool = coinjoin_external_pool(info); - (pool.highest_used, pool.highest_generated, pool.used_indices.len()) + ( + pool.highest_used(), + pool.highest_generated(), + pool.addresses.values().filter(|info| info.is_used()).count(), + ) } /// One block at `height` whose single transaction pays every address in diff --git a/key-wallet-manager/src/event_tests.rs b/key-wallet-manager/src/event_tests.rs index b82562467..6cd066b89 100644 --- a/key-wallet-manager/src/event_tests.rs +++ b/key-wallet-manager/src/event_tests.rs @@ -1439,7 +1439,7 @@ fn pool_state( ) => internal_addresses, _ => panic!("unexpected pool type {:?}", pool_type), }; - let highest = pool.highest_generated.expect("pre-generated pool must have addresses"); + let highest = pool.highest_generated().expect("pre-generated pool must have addresses"); let gap_limit = pool.gap_limit; let addr = pool.address_at_index(highest).expect("highest index must exist"); (highest, gap_limit, addr) diff --git a/key-wallet-manager/src/process_block.rs b/key-wallet-manager/src/process_block.rs index ed6459010..3996146cb 100644 --- a/key-wallet-manager/src/process_block.rs +++ b/key-wallet-manager/src/process_block.rs @@ -1052,7 +1052,7 @@ mod tests { .address_pools() .iter() .find(|p| p.pool_type == AddressPoolType::External) - .and_then(|p| p.highest_used); + .and_then(|p| p.highest_used()); assert_eq!(pool_used, Some(gap + 8)); let txids = BTreeSet::from([early.txid(), late.txid(), both.txid()]); diff --git a/key-wallet/src/managed_account/address_pool.rs b/key-wallet/src/managed_account/address_pool.rs index 8e856c023..f2339b931 100644 --- a/key-wallet/src/managed_account/address_pool.rs +++ b/key-wallet/src/managed_account/address_pool.rs @@ -7,7 +7,7 @@ use bincode_derive::{Decode, Encode}; #[cfg(feature = "serde")] use serde::{Deserialize, Serialize}; -use std::collections::{BTreeMap, HashMap, HashSet}; +use std::collections::{BTreeMap, HashMap}; use crate::bip32::{ChildNumber, DerivationPath, ExtendedPrivKey, ExtendedPubKey}; use crate::error::{Error, Result}; @@ -355,12 +355,6 @@ pub struct AddressPool { pub address_index: HashMap, /// Reverse lookup: script pubkey -> index pub script_pubkey_index: HashMap, - /// Set of used address indices - pub used_indices: HashSet, - /// Highest generated index (None if no addresses generated yet) - pub highest_generated: Option, - /// Highest used index - pub highest_used: Option, /// Address type preference pub address_type: AddressType, } @@ -399,9 +393,6 @@ impl AddressPool { addresses: BTreeMap::new(), address_index: HashMap::new(), script_pubkey_index: HashMap::new(), - used_indices: HashSet::new(), - highest_generated: None, - highest_used: None, address_type: AddressType::P2pkh, } } @@ -424,8 +415,18 @@ impl AddressPool { .map_or_else(|| self.next_index_to_derive(), |(index, _)| *index) } + /// Returns the highest derived index, or `None` for an empty pool. + pub fn highest_generated(&self) -> Option { + self.addresses.keys().next_back().copied() + } + + /// Returns the highest used index, or `None` when no address is used. + pub fn highest_used(&self) -> Option { + self.addresses.values().rev().find(|info| info.is_used()).map(|info| info.index) + } + fn next_index_to_derive(&self) -> u32 { - self.highest_generated.map_or(0, |highest| highest + 1) + self.highest_generated().map_or(0, |highest| highest + 1) } /// Generate addresses up to the specified count @@ -542,11 +543,6 @@ impl AddressPool { self.addresses.insert(index, info.clone()); self.address_index.insert(address, index); self.script_pubkey_index.insert(info.script_pubkey.clone(), index); - - // Update highest generated - if self.highest_generated.map(|h| index > h).unwrap_or(true) { - self.highest_generated = Some(index); - } } Ok(info) @@ -674,8 +670,6 @@ impl AddressPool { } info.mark_used(); - self.used_indices.insert(index); - self.highest_used = Some(self.highest_used.map_or(index, |highest| highest.max(index))); true } @@ -750,7 +744,7 @@ impl AddressPool { /// emission seam — surface the full derivation context (index, path, /// public key) for downstream persisters without re-deriving it. pub fn maintain_gap_limit(&mut self, key_source: &KeySource) -> Result> { - let target = match self.highest_used { + let target = match self.highest_used() { None => self.gap_limit - 1, Some(highest) => highest + self.gap_limit, }; @@ -791,7 +785,7 @@ mod tests { let addresses = pool.generate_addresses(10, &key_source, true).unwrap(); assert_eq!(addresses.len(), 10); - assert_eq!(pool.highest_generated, Some(9)); + assert_eq!(pool.highest_generated(), Some(9)); assert_eq!(pool.addresses.len(), 10); } @@ -809,11 +803,11 @@ mod tests { .unwrap(); assert_eq!(pool.generate_up_to(29, &key_source).unwrap().len(), 25); - assert_eq!(pool.highest_generated, Some(29)); + assert_eq!(pool.highest_generated(), Some(29)); assert_eq!(pool.addresses.len(), 30); assert!(pool.generate_up_to(10, &key_source).unwrap().is_empty()); - assert_eq!(pool.highest_generated, Some(29)); + assert_eq!(pool.highest_generated(), Some(29)); } #[test] @@ -831,8 +825,7 @@ mod tests { let first_addr = &addresses[0].address; assert!(pool.mark_used(first_addr)); - assert_eq!(pool.used_indices.len(), 1); - assert_eq!(pool.highest_used, Some(0)); + assert_eq!(pool.highest_used(), Some(0)); assert!(pool.address_info(first_addr).unwrap().is_used()); } @@ -879,7 +872,7 @@ mod tests { assert_eq!(pool.gap_limit, 20); assert_eq!(new.len(), 15); assert_eq!(pool.addresses.len(), 20); - assert_eq!(pool.highest_generated, Some(19)); + assert_eq!(pool.highest_generated(), Some(19)); // The new limit is capped at MAX_GAP_LIMIT. pool.set_gap_limit(crate::gap_limit::MAX_GAP_LIMIT + 500, &key_source).unwrap(); @@ -1103,25 +1096,25 @@ mod tests { .unwrap(); // Verify gap_limit addresses generated, none used - assert_eq!(pool.highest_generated, Some(gap_limit - 1)); - assert_eq!(pool.highest_used, None); + assert_eq!(pool.highest_generated(), Some(gap_limit - 1)); + assert_eq!(pool.highest_used(), None); assert_eq!(pool.addresses.len(), gap_limit as usize); // Calling maintain_gap_limit should not generate any new addresses when none are used let new_addresses = pool.maintain_gap_limit(&key_source).unwrap(); assert_eq!(new_addresses.len(), 0); - assert_eq!(pool.highest_generated, Some(gap_limit - 1)); + assert_eq!(pool.highest_generated(), Some(gap_limit - 1)); assert_eq!(pool.addresses.len(), gap_limit as usize); // Mark address at index 0 as used pool.mark_used(&pool.address_at_index(0).unwrap()); - assert_eq!(pool.highest_used, Some(0)); + assert_eq!(pool.highest_used(), Some(0)); // Should generate exactly 1 address to maintain gap_limit unused after index 0 let new_addresses = pool.maintain_gap_limit(&key_source).unwrap(); assert_eq!(new_addresses.len(), 1); assert_eq!(new_addresses[0].index, gap_limit); - assert_eq!(pool.highest_generated, Some(gap_limit)); + assert_eq!(pool.highest_generated(), Some(gap_limit)); assert_eq!(pool.addresses.len(), gap_limit as usize + 1); // Mark address at index 1 and 2 as used @@ -1133,7 +1126,7 @@ mod tests { assert_eq!(new_addresses.len(), 2); assert_eq!(new_addresses[0].index, gap_limit + 1); assert_eq!(new_addresses[1].index, gap_limit + 2); - assert_eq!(pool.highest_generated, Some(gap_limit + 2)); + assert_eq!(pool.highest_generated(), Some(gap_limit + 2)); assert_eq!(pool.addresses.len(), gap_limit as usize + 3); } } diff --git a/key-wallet/src/tests/dashpay_contact_gap_limit_tests.rs b/key-wallet/src/tests/dashpay_contact_gap_limit_tests.rs index ce7245e24..62e9fa367 100644 --- a/key-wallet/src/tests/dashpay_contact_gap_limit_tests.rs +++ b/key-wallet/src/tests/dashpay_contact_gap_limit_tests.rs @@ -90,7 +90,7 @@ async fn contact_payments_extend_the_contact_pool() { "{direction}: payment to a monitored address is seen" ); assert_eq!( - contact_pool(&ctx, contact).highest_generated, + contact_pool(&ctx, contact).highest_generated(), Some(gap - 1 + gap), "{direction}: using an address must leave a full window monitored ahead of it" ); @@ -102,7 +102,7 @@ async fn contact_payments_extend_the_contact_pool() { "{direction}: the payment past the construction window must be seen too" ); assert_eq!( - contact_pool(&ctx, contact).highest_generated, + contact_pool(&ctx, contact).highest_generated(), Some(gap * 2), "{direction}: the window must keep moving, not widen once" ); diff --git a/key-wallet/src/tests/restore_utxos_tests.rs b/key-wallet/src/tests/restore_utxos_tests.rs index 9450f34e6..26589cb34 100644 --- a/key-wallet/src/tests/restore_utxos_tests.rs +++ b/key-wallet/src/tests/restore_utxos_tests.rs @@ -97,7 +97,7 @@ fn held_by_any_funds_account(ctx: &TestWalletContext, outpoint: &OutPoint) -> bo async fn a_coinjoin_utxo_past_the_stored_window_restores_into_coinjoin() { let mut ctx = TestWalletContext::new_random(); let gap = coinjoin_pool(&ctx).gap_limit; - assert_eq!(coinjoin_pool(&ctx).highest_generated, Some(gap - 1)); + assert_eq!(coinjoin_pool(&ctx).highest_generated(), Some(gap - 1)); let (_, inside) = funded(&coinjoin_address(&ctx, gap - 1), 0, 100_000); let (beyond_tx, beyond) = funded(&coinjoin_address(&ctx, 2 * gap - 1), 1, 200_000); @@ -173,7 +173,7 @@ fn a_receiving_pool_that_reaches_a_script_in_a_later_pass_claims_it() { let mut ctx = TestWalletContext::new_random(); let (receiving, reverse_external) = befriend_both_ways(&mut ctx); let pool = receiving_pool(&ctx); - let last = pool.highest_generated.expect("an initial window"); + let last = pool.highest_generated().expect("an initial window"); let far_index = last + pool.gap_limit; let mut far_pool = pool.clone(); far_pool diff --git a/key-wallet/src/tests/special_transaction_matching_tests.rs b/key-wallet/src/tests/special_transaction_matching_tests.rs index 763487274..c4680b3c2 100644 --- a/key-wallet/src/tests/special_transaction_matching_tests.rs +++ b/key-wallet/src/tests/special_transaction_matching_tests.rs @@ -481,7 +481,7 @@ async fn provider_registration_extends_operator_key_gap_limit() { match account.managed_account_type() { ManagedAccountType::ProviderOperatorKeys { addresses, - } => (addresses.highest_generated, addresses.highest_used, addresses.gap_limit), + } => (addresses.highest_generated(), addresses.highest_used(), addresses.gap_limit), _ => unreachable!("operator account holds an operator pool"), } }; From e3de00672896c94225ace654e2d6a96e2b6a2f2a Mon Sep 17 00:00:00 2001 From: Borja Castellano Date: Wed, 11 Nov 2026 05:58:17 -0800 Subject: [PATCH 09/22] refactor(key-wallet)!: drop unused `AddressPool` and `AddressInfo` fields `AddressPool::address_type` was never read, since the pool always derives P2PKH addresses. The `AddressInfo` fields `tx_count`, `total_received`, `total_sent`, `balance`, `label` and `metadata` were never written after construction. All of them are removed. --- key-wallet-manager/src/events.rs | 7 ------- .../src/managed_account/address_pool.rs | 21 ------------------- 2 files changed, 28 deletions(-) diff --git a/key-wallet-manager/src/events.rs b/key-wallet-manager/src/events.rs index 093ab0d9a..eb35954eb 100644 --- a/key-wallet-manager/src/events.rs +++ b/key-wallet-manager/src/events.rs @@ -627,7 +627,6 @@ mod project_derived_addresses_tests { use key_wallet::account::StandardAccountType; use key_wallet::bip32::{ChildNumber, DerivationPath}; use key_wallet::managed_account::address_pool::{AddressInfo, AddressState}; - use std::collections::BTreeMap; /// Compressed encoding of the secp256k1 generator point (G). const TEST_PUBKEY_G: [u8; 33] = [ @@ -681,12 +680,6 @@ mod project_derived_addresses_tests { index, path, state: AddressState::Available, - tx_count: 0, - total_received: 0, - total_sent: 0, - balance: 0, - label: None, - metadata: BTreeMap::new(), }, } } diff --git a/key-wallet/src/managed_account/address_pool.rs b/key-wallet/src/managed_account/address_pool.rs index f2339b931..5ef65e697 100644 --- a/key-wallet/src/managed_account/address_pool.rs +++ b/key-wallet/src/managed_account/address_pool.rs @@ -243,18 +243,6 @@ pub struct AddressInfo { pub path: DerivationPath, /// Lifecycle state: available, reserved, or used pub state: AddressState, - /// Transaction count for this address - pub tx_count: u32, - /// Total received amount - pub total_received: u64, - /// Total sent amount - pub total_sent: u64, - /// Current balance - pub balance: u64, - /// Custom label - pub label: Option, - /// Custom metadata - pub metadata: BTreeMap, } impl AddressInfo { @@ -272,12 +260,6 @@ impl AddressInfo { index, path, state: AddressState::Available, - tx_count: 0, - total_received: 0, - total_sent: 0, - balance: 0, - label: None, - metadata: BTreeMap::new(), } } @@ -355,8 +337,6 @@ pub struct AddressPool { pub address_index: HashMap, /// Reverse lookup: script pubkey -> index pub script_pubkey_index: HashMap, - /// Address type preference - pub address_type: AddressType, } impl AddressPool { @@ -393,7 +373,6 @@ impl AddressPool { addresses: BTreeMap::new(), address_index: HashMap::new(), script_pubkey_index: HashMap::new(), - address_type: AddressType::P2pkh, } } From d1520f3760741316fb743728d352129fb1d1ebaf Mon Sep 17 00:00:00 2001 From: Borja Castellano Date: Wed, 11 Nov 2026 06:09:18 -0800 Subject: [PATCH 10/22] refactor(key-wallet)!: always store derived pool addresses Every address getter took an `add_to_state` flag that could derive an address without storing it in the pool. Only two callers passed `false`, both with `KeySource::NoKeySource`, where nothing is derived. The flag is removed from the `AddressPool`, `ManagedAccountTrait`, `ManagedCoreFundsAccount` and `ManagedPlatformAccount` getters, and derived addresses are always stored. --- dash-spv/src/sync/mempool/sync_manager.rs | 2 +- key-wallet-manager/benches/filter_scan.rs | 2 +- key-wallet-manager/src/event_tests.rs | 4 +- .../tests/spv_integration_tests.rs | 2 +- key-wallet/benches/address_generation.rs | 2 +- .../src/managed_account/address_pool.rs | 48 +++++----- .../managed_account/managed_account_trait.rs | 16 ++-- .../managed_core_funds_account.rs | 28 +++--- .../managed_platform_account.rs | 6 +- key-wallet/src/test_utils/wallet.rs | 2 +- .../tests/observed_spent_outpoints_tests.rs | 2 +- key-wallet/src/tests/performance_tests.rs | 2 +- .../tests/provider_key_derivation_tests.rs | 2 +- .../special_transaction_matching_tests.rs | 58 ++++++------ key-wallet/src/tests/spent_outpoints_tests.rs | 2 +- .../transaction_router/tests/asset_unlock.rs | 2 +- .../transaction_router/tests/coinbase.rs | 2 +- .../tests/identity_transactions.rs | 4 +- .../transaction_router/tests/provider.rs | 40 ++++----- .../transaction_router/tests/routing.rs | 20 ++--- .../transaction_checking/wallet_checker.rs | 90 +++++++++---------- .../managed_wallet_info/asset_lock_builder.rs | 8 +- .../src/wallet/managed_wallet_info/mod.rs | 20 ++--- .../transaction_builder.rs | 6 +- .../transaction_building.rs | 8 +- 25 files changed, 176 insertions(+), 202 deletions(-) diff --git a/dash-spv/src/sync/mempool/sync_manager.rs b/dash-spv/src/sync/mempool/sync_manager.rs index 0d0978c99..4a0322d26 100644 --- a/dash-spv/src/sync/mempool/sync_manager.rs +++ b/dash-spv/src/sync/mempool/sync_manager.rs @@ -457,7 +457,7 @@ mod tests { let address = preview .bip44_managed_account_at_index_mut(1) .unwrap() - .next_receive_address(None, true) + .next_receive_address(None) .unwrap(); let mut funding = Transaction::dummy(&ctx.receive_address, 0..1, &[100_000]); funding.output.push(TxOut { diff --git a/key-wallet-manager/benches/filter_scan.rs b/key-wallet-manager/benches/filter_scan.rs index 877d39708..8690a9e0d 100644 --- a/key-wallet-manager/benches/filter_scan.rs +++ b/key-wallet-manager/benches/filter_scan.rs @@ -82,7 +82,7 @@ fn wallet_with_mixing_history(used: u32) -> (Manager, [u8; 32]) { panic!("expected CoinJoin managed account type"); }; external_addresses - .generate_addresses(used, &key_source, true) + .generate_addresses(used, &key_source) .expect("derive CoinJoin addresses"); external_addresses.all_addresses() }; diff --git a/key-wallet-manager/src/event_tests.rs b/key-wallet-manager/src/event_tests.rs index 6cd066b89..fd6b1c936 100644 --- a/key-wallet-manager/src/event_tests.rs +++ b/key-wallet-manager/src/event_tests.rs @@ -776,7 +776,7 @@ async fn test_block_with_index_less_account_tx_carries_account_type() { .expect("wallet info") .identity_registration_managed_account_mut() .expect("managed IdentityRegistration account") - .next_address(Some(&xpub), true) + .next_address(Some(&xpub)) .expect("identity registration address"); // Build a DIP-2 AssetLock transaction whose `credit_outputs` pay to the @@ -2322,7 +2322,7 @@ async fn late_funding_block_publishes_spender_correction() { .unwrap() .first_bip44_managed_account_mut() .unwrap() - .next_change_address(None, true) + .next_change_address(None) .unwrap(); let funding = create_tx_paying_to(&addr, 0xd5); let mut spender = create_tx_paying_to(&change, 0xd6); diff --git a/key-wallet-manager/tests/spv_integration_tests.rs b/key-wallet-manager/tests/spv_integration_tests.rs index 46ada40f3..734f210b3 100644 --- a/key-wallet-manager/tests/spv_integration_tests.rs +++ b/key-wallet-manager/tests/spv_integration_tests.rs @@ -138,7 +138,7 @@ async fn test_immature_balance_matures_during_block_processing() { wallet_info .first_bip44_managed_account_mut() .expect("Should have managed account") - .next_receive_address(Some(&account_xpub), true) + .next_receive_address(Some(&account_xpub)) .expect("Should get address") }; diff --git a/key-wallet/benches/address_generation.rs b/key-wallet/benches/address_generation.rs index 32f4cdd3f..9a066c39c 100644 --- a/key-wallet/benches/address_generation.rs +++ b/key-wallet/benches/address_generation.rs @@ -41,7 +41,7 @@ fn bench_address_generation(c: &mut Criterion) { group.bench_with_input(BenchmarkId::from_parameter(batch_size), &batch_size, |b, &n| { b.iter_batched( || pool.clone(), - |mut pool| black_box(pool.generate_addresses(n, &key_source, true).unwrap()), + |mut pool| black_box(pool.generate_addresses(n, &key_source).unwrap()), BatchSize::SmallInput, ); }); diff --git a/key-wallet/src/managed_account/address_pool.rs b/key-wallet/src/managed_account/address_pool.rs index 5ef65e697..1b73c0a07 100644 --- a/key-wallet/src/managed_account/address_pool.rs +++ b/key-wallet/src/managed_account/address_pool.rs @@ -352,7 +352,7 @@ impl AddressPool { // Generate addresses up to the gap limit if we have a key source if key_source.can_derive() { - pool.generate_addresses(gap_limit, key_source, true)?; + pool.generate_addresses(gap_limit, key_source)?; } Ok(pool) @@ -413,11 +413,10 @@ impl AddressPool { &mut self, count: u32, key_source: &KeySource, - add_to_state: bool, ) -> Result> { let start_index = self.next_index_to_derive(); (start_index..start_index + count) - .map(|index| self.generate_address_at_index(index, key_source, add_to_state)) + .map(|index| self.generate_address_at_index(index, key_source)) .collect() } @@ -428,7 +427,7 @@ impl AddressPool { key_source: &KeySource, ) -> Result> { let next = self.next_index_to_derive(); - self.generate_addresses((index + 1).saturating_sub(next), key_source, true) + self.generate_addresses((index + 1).saturating_sub(next), key_source) } /// Generate a specific address at an index @@ -436,7 +435,6 @@ impl AddressPool { &mut self, index: u32, key_source: &KeySource, - add_to_state: bool, ) -> Result { // Check if already generated if let Some(info) = self.addresses.get(&index) { @@ -518,32 +516,26 @@ impl AddressPool { } }; let info = AddressInfo::new(address.clone(), index, full_path, Some(public_key_type)); - if add_to_state { - self.addresses.insert(index, info.clone()); - self.address_index.insert(address, index); - self.script_pubkey_index.insert(info.script_pubkey.clone(), index); - } + self.addresses.insert(index, info.clone()); + self.address_index.insert(address, index); + self.script_pubkey_index.insert(info.script_pubkey.clone(), index); Ok(info) } /// Get the next unused address - pub fn next_unused(&mut self, key_source: &KeySource, add_to_state: bool) -> Result
{ - self.next_unused_with_info(key_source, add_to_state).map(|info| info.address) + pub fn next_unused(&mut self, key_source: &KeySource) -> Result
{ + self.next_unused_with_info(key_source).map(|info| info.address) } /// Get the next unused address info - pub(crate) fn next_unused_with_info( - &mut self, - key_source: &KeySource, - add_to_state: bool, - ) -> Result { + pub(crate) fn next_unused_with_info(&mut self, key_source: &KeySource) -> Result { // First, try to find an already generated unused address if let Some(info) = self.addresses.get(&self.next_unused_index()) { return Ok(info.clone()); } - self.generate_addresses(1, key_source, add_to_state)? + self.generate_addresses(1, key_source)? .pop() .ok_or_else(|| Error::InvalidState("generate_addresses(1) returned nothing".into())) } @@ -572,7 +564,7 @@ impl AddressPool { key_source: &KeySource, now: u64, ) -> Result
{ - let index = self.next_unused_with_info(key_source, true)?.index; + let index = self.next_unused_with_info(key_source)?.index; // A lookup miss would hand out an unreserved address, so fail instead. let info = self.addresses.get_mut(&index).ok_or_else(|| { Error::InvalidState(format!("next_unused_and_reserve: index {} not stored", index)) @@ -762,7 +754,7 @@ mod tests { ); let key_source = test_key_source(); - let addresses = pool.generate_addresses(10, &key_source, true).unwrap(); + let addresses = pool.generate_addresses(10, &key_source).unwrap(); assert_eq!(addresses.len(), 10); assert_eq!(pool.highest_generated(), Some(9)); assert_eq!(pool.addresses.len(), 10); @@ -800,7 +792,7 @@ mod tests { ); let key_source = test_key_source(); - let addresses = pool.generate_addresses(5, &key_source, true).unwrap(); + let addresses = pool.generate_addresses(5, &key_source).unwrap(); let first_addr = &addresses[0].address; assert!(pool.mark_used(first_addr)); @@ -820,12 +812,12 @@ mod tests { ); let key_source = test_key_source(); - let addr1 = pool.next_unused(&key_source, true).unwrap(); - let addr2 = pool.next_unused(&key_source, true).unwrap(); + let addr1 = pool.next_unused(&key_source).unwrap(); + let addr2 = pool.next_unused(&key_source).unwrap(); assert_eq!(addr1, addr2); // Should return same unused address pool.mark_used(&addr1); - let addr3 = pool.next_unused(&key_source, true).unwrap(); + let addr3 = pool.next_unused(&key_source).unwrap(); assert_ne!(addr1, addr3); // Should return different address after marking used } @@ -871,8 +863,8 @@ mod tests { let key_source = test_key_source(); // Without reserving, two hand-outs return the same address (the race). - let peek1 = pool.next_unused(&key_source, true).unwrap(); - let peek2 = pool.next_unused(&key_source, true).unwrap(); + let peek1 = pool.next_unused(&key_source).unwrap(); + let peek2 = pool.next_unused(&key_source).unwrap(); assert_eq!(peek1, peek2); // Reserving on hand-out makes two sequential calls return distinct @@ -882,7 +874,7 @@ mod tests { assert_ne!(addr1, addr2); // A plain peek must skip the reserved addresses too. - let peek3 = pool.next_unused(&key_source, true).unwrap(); + let peek3 = pool.next_unused(&key_source).unwrap(); assert_ne!(peek3, addr1); assert_ne!(peek3, addr2); } @@ -929,7 +921,7 @@ mod tests { assert!(pool.release_reservation(index)); assert!(!pool.release_reservation(index)); // Releasing a never-reserved index is a no-op too. - let other = pool.next_unused(&key_source, true).unwrap(); + let other = pool.next_unused(&key_source).unwrap(); let other_index = pool.address_index(&other).unwrap(); assert!(!pool.release_reservation(other_index)); // Unknown index is a no-op. diff --git a/key-wallet/src/managed_account/managed_account_trait.rs b/key-wallet/src/managed_account/managed_account_trait.rs index 60bdf97fa..e6b8ab898 100644 --- a/key-wallet/src/managed_account/managed_account_trait.rs +++ b/key-wallet/src/managed_account/managed_account_trait.rs @@ -136,7 +136,6 @@ pub trait ManagedAccountTrait { fn next_address( &mut self, account_xpub: Option<&ExtendedPubKey>, - add_to_state: bool, ) -> Result { match self.managed_account_type_mut() { ManagedAccountType::Standard { @@ -203,7 +202,7 @@ pub trait ManagedAccountTrait { None => address_pool::KeySource::NoKeySource, }; - addresses.next_unused(&key_source, add_to_state).map_err(|e| match e { + addresses.next_unused(&key_source).map_err(|e| match e { crate::error::Error::NoKeySource => { "No unused addresses available and no key source provided" } @@ -217,7 +216,6 @@ pub trait ManagedAccountTrait { fn next_address_with_info( &mut self, account_xpub: Option<&ExtendedPubKey>, - add_to_state: bool, ) -> Result { match self.managed_account_type_mut() { ManagedAccountType::Standard { @@ -286,7 +284,7 @@ pub trait ManagedAccountTrait { None => address_pool::KeySource::NoKeySource, }; - addresses.next_unused_with_info(&key_source, add_to_state).map_err(|e| match e { + addresses.next_unused_with_info(&key_source).map_err(|e| match e { crate::error::Error::NoKeySource => { "No unused addresses available and no key source provided" } @@ -301,7 +299,6 @@ pub trait ManagedAccountTrait { fn next_bls_operator_key( &mut self, account_xpub: Option, - add_to_state: bool, ) -> Result { match self.managed_account_type_mut() { ManagedAccountType::ProviderOperatorKeys { @@ -314,7 +311,7 @@ pub trait ManagedAccountTrait { }; let info = addresses - .next_unused_with_info(&key_source, add_to_state) + .next_unused_with_info(&key_source) .map_err(|_| "Failed to get next unused address")?; let Some(PublicKeyType::BLS(pub_key_bytes)) = info.public_key else { @@ -339,7 +336,6 @@ pub trait ManagedAccountTrait { fn next_eddsa_platform_key( &mut self, account_xpriv: crate::derivation_slip10::ExtendedEd25519PrivKey, - add_to_state: bool, ) -> Result<(EddsaPkBytes, AddressInfo), &'static str> { match self.managed_account_type_mut() { ManagedAccountType::ProviderPlatformKeys { @@ -349,7 +345,7 @@ pub trait ManagedAccountTrait { let key_source = address_pool::KeySource::EdDSAPrivate(account_xpriv); let info = addresses - .next_unused_with_info(&key_source, add_to_state) + .next_unused_with_info(&key_source) .map_err(|_| "Failed to get next unused address")?; let Some(PublicKeyType::EdDSA(pub_key_bytes)) = info.public_key.clone() else { @@ -384,7 +380,7 @@ pub trait ManagedAccountTrait { let pool = pools.first_mut().ok_or("Account has no address pool")?; let info = pool - .next_unused_with_info(&address_pool::KeySource::NoKeySource, false) + .next_unused_with_info(&address_pool::KeySource::NoKeySource) .map_err(|_| "No unused address available")?; pool.mark_used(&info.address); @@ -408,7 +404,7 @@ pub trait ManagedAccountTrait { let pool = pools.first_mut().ok_or("Account has no address pool")?; let info = pool - .next_unused_with_info(&address_pool::KeySource::NoKeySource, false) + .next_unused_with_info(&address_pool::KeySource::NoKeySource) .map_err(|_| "No unused address available")?; Ok((info.path, info.address)) 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 fe49bd0d0..1e5d73265 100644 --- a/key-wallet/src/managed_account/managed_core_funds_account.rs +++ b/key-wallet/src/managed_account/managed_core_funds_account.rs @@ -1385,7 +1385,6 @@ impl ManagedCoreFundsAccount { pub fn next_receive_address( &mut self, account_xpub: Option<&ExtendedPubKey>, - add_to_state: bool, ) -> Result { if let ManagedAccountType::Standard { external_addresses, @@ -1397,13 +1396,12 @@ impl ManagedCoreFundsAccount { None => address_pool::KeySource::NoKeySource, }; - let addr = - external_addresses.next_unused(&key_source, add_to_state).map_err(|e| match e { - crate::error::Error::NoKeySource => { - "No unused addresses available and no key source provided" - } - _ => "Failed to generate receive address", - })?; + let addr = external_addresses.next_unused(&key_source).map_err(|e| match e { + crate::error::Error::NoKeySource => { + "No unused addresses available and no key source provided" + } + _ => "Failed to generate receive address", + })?; self.keys.bump_monitor_revision(); Ok(addr) } else { @@ -1416,7 +1414,6 @@ impl ManagedCoreFundsAccount { pub fn next_change_address( &mut self, account_xpub: Option<&ExtendedPubKey>, - add_to_state: bool, ) -> Result { if let ManagedAccountType::Standard { internal_addresses, @@ -1428,13 +1425,12 @@ impl ManagedCoreFundsAccount { None => address_pool::KeySource::NoKeySource, }; - let addr = - internal_addresses.next_unused(&key_source, add_to_state).map_err(|e| match e { - crate::error::Error::NoKeySource => { - "No unused addresses available and no key source provided" - } - _ => "Failed to generate change address", - })?; + let addr = internal_addresses.next_unused(&key_source).map_err(|e| match e { + crate::error::Error::NoKeySource => { + "No unused addresses available and no key source provided" + } + _ => "Failed to generate change address", + })?; self.keys.bump_monitor_revision(); Ok(addr) } else { diff --git a/key-wallet/src/managed_account/managed_platform_account.rs b/key-wallet/src/managed_account/managed_platform_account.rs index c8416ff3a..401c74b7f 100644 --- a/key-wallet/src/managed_account/managed_platform_account.rs +++ b/key-wallet/src/managed_account/managed_platform_account.rs @@ -227,10 +227,9 @@ impl ManagedPlatformAccount { pub fn next_unused_address( &mut self, key_source: &super::address_pool::KeySource, - add_to_state: bool, ) -> Result
{ self.addresses - .next_unused(key_source, add_to_state) + .next_unused(key_source) .map_err(|e| Error::InvalidParameter(format!("Failed to get next address: {}", e))) } @@ -238,9 +237,8 @@ impl ManagedPlatformAccount { pub fn next_unused_platform_address( &mut self, key_source: &super::address_pool::KeySource, - add_to_state: bool, ) -> Result { - let addr = self.next_unused_address(key_source, add_to_state)?; + let addr = self.next_unused_address(key_source)?; PlatformP2PKHAddress::from_address(&addr) } diff --git a/key-wallet/src/test_utils/wallet.rs b/key-wallet/src/test_utils/wallet.rs index 7f7859a5a..f7f8377e6 100644 --- a/key-wallet/src/test_utils/wallet.rs +++ b/key-wallet/src/test_utils/wallet.rs @@ -50,7 +50,7 @@ impl TestWalletContext { let receive_address = managed_wallet .first_bip44_managed_account_mut() .expect("Should have managed account") - .next_receive_address(Some(&xpub), true) + .next_receive_address(Some(&xpub)) .expect("Should get address"); Self { diff --git a/key-wallet/src/tests/observed_spent_outpoints_tests.rs b/key-wallet/src/tests/observed_spent_outpoints_tests.rs index 216375f99..879fa9d75 100644 --- a/key-wallet/src/tests/observed_spent_outpoints_tests.rs +++ b/key-wallet/src/tests/observed_spent_outpoints_tests.rs @@ -539,7 +539,7 @@ async fn born_fully_spent_intermediate_hop_is_recorded_in_history() { .managed_wallet .first_bip44_managed_account_mut() .expect("BIP44 account") - .next_receive_address(Some(&ctx.xpub), true) + .next_receive_address(Some(&ctx.xpub)) .expect("hop address"); // C funds our first receive address (a live coin). diff --git a/key-wallet/src/tests/performance_tests.rs b/key-wallet/src/tests/performance_tests.rs index 627ef62b6..e8059eb70 100644 --- a/key-wallet/src/tests/performance_tests.rs +++ b/key-wallet/src/tests/performance_tests.rs @@ -283,7 +283,7 @@ fn test_gap_limit_scan_performance() { .unwrap(); // Generate addresses with gaps - pool.generate_addresses(100, &key_source, true).unwrap(); + pool.generate_addresses(100, &key_source).unwrap(); // Mark some as used (with gaps) let used_indices = vec![0, 1, 5, 10, 25, 50, 75]; diff --git a/key-wallet/src/tests/provider_key_derivation_tests.rs b/key-wallet/src/tests/provider_key_derivation_tests.rs index a56ad5260..fec4e9c0d 100644 --- a/key-wallet/src/tests/provider_key_derivation_tests.rs +++ b/key-wallet/src/tests/provider_key_derivation_tests.rs @@ -179,7 +179,7 @@ fn platform_pool_entries_are_keyed_by_tenderdash_node_id() { let (verifying_key, entry) = info .provider_platform_keys_managed_account_mut() .expect("platform managed account") - .next_eddsa_platform_key(account_xpriv, true) + .next_eddsa_platform_key(account_xpriv) .expect("derive platform key 0"); assert_eq!( diff --git a/key-wallet/src/tests/special_transaction_matching_tests.rs b/key-wallet/src/tests/special_transaction_matching_tests.rs index c4680b3c2..2b9ef4e2c 100644 --- a/key-wallet/src/tests/special_transaction_matching_tests.rs +++ b/key-wallet/src/tests/special_transaction_matching_tests.rs @@ -126,7 +126,7 @@ async fn asset_lock_credit_output_to_identity_registration_address_matches() { let address = info .identity_registration_managed_account_mut() .expect("identity registration managed") - .next_address(Some(&xpub), true) + .next_address(Some(&xpub)) .expect("derive address"); let tx = asset_lock_to(address.script_pubkey(), ASSET_LOCK_VALUE); @@ -177,7 +177,7 @@ async fn asset_lock_regular_output_to_identity_topup_address_matches() { let address = info .topup_managed_account_at_registration_index_mut(registration_index) .expect("identity_topup[0] managed") - .next_address(Some(&xpub), true) + .next_address(Some(&xpub)) .expect("derive address"); let mut tx = asset_lock_to(ScriptBuf::new(), ASSET_LOCK_VALUE); @@ -199,7 +199,7 @@ async fn asset_lock_credit_output_to_identity_topup_not_bound_address_matches() let address = info .identity_topup_not_bound_managed_account_mut() .expect("identity_topup_not_bound managed") - .next_address(Some(&xpub), true) + .next_address(Some(&xpub)) .expect("derive address"); let tx = asset_lock_to(address.script_pubkey(), ASSET_LOCK_VALUE); @@ -216,7 +216,7 @@ async fn asset_lock_credit_output_to_identity_invitation_address_matches() { let address = info .identity_invitation_managed_account_mut() .expect("identity_invitation managed") - .next_address(Some(&xpub), true) + .next_address(Some(&xpub)) .expect("derive address"); let tx = asset_lock_to(address.script_pubkey(), ASSET_LOCK_VALUE); @@ -236,7 +236,7 @@ async fn asset_lock_credit_output_to_asset_lock_address_topup_address_matches() .asset_lock_address_topup .as_mut() .expect("asset_lock_address_topup managed") - .next_address(Some(&xpub), true) + .next_address(Some(&xpub)) .expect("derive address"); let tx = asset_lock_to(address.script_pubkey(), ASSET_LOCK_VALUE); @@ -260,7 +260,7 @@ async fn asset_lock_credit_output_to_asset_lock_shielded_address_topup_address_m .asset_lock_shielded_address_topup .as_mut() .expect("asset_lock_shielded_address_topup managed") - .next_address(Some(&xpub), true) + .next_address(Some(&xpub)) .expect("derive address"); let tx = asset_lock_to(address.script_pubkey(), ASSET_LOCK_VALUE); @@ -344,17 +344,17 @@ async fn provider_registration_with_owner_key_hash_matches_provider_owner_keys() let owner_addr = info .provider_owner_keys_managed_account_mut() .expect("provider_owner_keys managed") - .next_address(None, true) + .next_address(None) .expect("derive owner"); let voting_addr = other_info .provider_voting_keys_managed_account_mut() .expect("other voting") - .next_address(None, true) + .next_address(None) .expect("derive voting"); let operator_pk = other_info .provider_operator_keys_managed_account_mut() .expect("other operator") - .next_bls_operator_key(None, true) + .next_bls_operator_key(None) .expect("derive operator"); let tx = prov_reg_tx( @@ -379,17 +379,17 @@ async fn provider_registration_with_voting_key_hash_matches_provider_voting_keys let owner_addr = other_info .provider_owner_keys_managed_account_mut() .expect("other owner") - .next_address(None, true) + .next_address(None) .expect("derive owner"); let voting_addr = info .provider_voting_keys_managed_account_mut() .expect("provider_voting_keys managed") - .next_address(None, true) + .next_address(None) .expect("derive voting"); let operator_pk = other_info .provider_operator_keys_managed_account_mut() .expect("other operator") - .next_bls_operator_key(None, true) + .next_bls_operator_key(None) .expect("derive operator"); let tx = prov_reg_tx( @@ -415,17 +415,17 @@ async fn provider_registration_with_operator_public_key_matches_provider_operato let owner_addr = other_info .provider_owner_keys_managed_account_mut() .expect("other owner") - .next_address(None, true) + .next_address(None) .expect("derive owner"); let voting_addr = other_info .provider_voting_keys_managed_account_mut() .expect("other voting") - .next_address(None, true) + .next_address(None) .expect("derive voting"); let operator_pk = info .provider_operator_keys_managed_account_mut() .expect("provider_operator_keys managed") - .next_bls_operator_key(None, true) + .next_bls_operator_key(None) .expect("derive operator"); let tx = prov_reg_tx( @@ -460,19 +460,19 @@ async fn provider_registration_extends_operator_key_gap_limit() { let owner_addr = other_info .provider_owner_keys_managed_account_mut() .expect("other owner") - .next_address(None, true) + .next_address(None) .expect("derive owner"); let voting_addr = other_info .provider_voting_keys_managed_account_mut() .expect("other voting") - .next_address(None, true) + .next_address(None) .expect("derive voting"); // Takes operator key 0 and marks it used, so the pool's unused window // shrinks below the gap limit. let operator_pk = info .provider_operator_keys_managed_account_mut() .expect("provider_operator_keys managed") - .next_bls_operator_key(None, true) + .next_bls_operator_key(None) .expect("derive operator"); let operator_pool_state = |info: &ManagedWalletInfo| { @@ -542,17 +542,17 @@ async fn provider_registration_with_platform_node_id_matches_provider_platform_k let owner_addr = other_info .provider_owner_keys_managed_account_mut() .expect("other owner") - .next_address(None, true) + .next_address(None) .expect("derive owner"); let voting_addr = other_info .provider_voting_keys_managed_account_mut() .expect("other voting") - .next_address(None, true) + .next_address(None) .expect("derive voting"); let operator_pk = other_info .provider_operator_keys_managed_account_mut() .expect("other operator") - .next_bls_operator_key(None, true) + .next_bls_operator_key(None) .expect("derive operator"); let root = wallet.root_extended_priv_key().expect("root extended priv key"); @@ -560,7 +560,7 @@ async fn provider_registration_with_platform_node_id_matches_provider_platform_k let (_platform_pk, platform_info) = info .provider_platform_keys_managed_account_mut() .expect("provider_platform_keys managed") - .next_eddsa_platform_key(eddsa, true) + .next_eddsa_platform_key(eddsa) .expect("derive platform"); let platform_node_id = dashcore::PlatformNodeId::from_byte_array( derive_pubkey_hash(&platform_info.address).to_byte_array(), @@ -591,7 +591,7 @@ async fn provider_update_registrar_with_voting_key_change_matches_provider_votin let voting_addr = info .provider_voting_keys_managed_account_mut() .expect("provider_voting_keys managed") - .next_address(None, true) + .next_address(None) .expect("derive voting"); // Operator key sourced from a fresh wallet so it doesn't accidentally // match this wallet's operator account. @@ -599,7 +599,7 @@ async fn provider_update_registrar_with_voting_key_change_matches_provider_votin let operator_pk = other_info .provider_operator_keys_managed_account_mut() .expect("other operator") - .next_bls_operator_key(None, true) + .next_bls_operator_key(None) .expect("derive operator"); let tx = Transaction { @@ -648,12 +648,12 @@ async fn provider_update_registrar_with_operator_key_change_matches_provider_ope let voting_addr = other_info .provider_voting_keys_managed_account_mut() .expect("other voting") - .next_address(None, true) + .next_address(None) .expect("derive voting"); let operator_pk = info .provider_operator_keys_managed_account_mut() .expect("provider_operator_keys managed") - .next_bls_operator_key(None, true) + .next_bls_operator_key(None) .expect("derive operator"); let tx = Transaction { @@ -709,7 +709,7 @@ async fn keys_account_record_is_thin_marker_internal_with_no_details() { let address = info .identity_registration_managed_account_mut() .expect("identity_registration managed") - .next_address(Some(&xpub), true) + .next_address(Some(&xpub)) .expect("derive address"); let tx = asset_lock_to(address.script_pubkey(), ASSET_LOCK_VALUE); @@ -749,7 +749,7 @@ fn next_bip44_receive_script(wallet: &Wallet, info: &mut ManagedWalletInfo) -> S let xpub = wallet.accounts.standard_bip44_accounts.get(&0).expect("bip44 account").account_xpub; info.first_bip44_managed_account_mut() .expect("bip44 managed") - .next_receive_address(Some(&xpub), true) + .next_receive_address(Some(&xpub)) .expect("derive receive address") .script_pubkey() } @@ -898,7 +898,7 @@ async fn provider_update_service_payout_to_bip44_change_address_matches() { let script = info .first_bip44_managed_account_mut() .expect("bip44 managed") - .next_change_address(Some(&xpub), true) + .next_change_address(Some(&xpub)) .expect("derive change address") .script_pubkey(); diff --git a/key-wallet/src/tests/spent_outpoints_tests.rs b/key-wallet/src/tests/spent_outpoints_tests.rs index c96eb33bd..f37853f0b 100644 --- a/key-wallet/src/tests/spent_outpoints_tests.rs +++ b/key-wallet/src/tests/spent_outpoints_tests.rs @@ -24,7 +24,7 @@ use crate::Network; fn receive_address(wallet: &Wallet, info: &mut ManagedWalletInfo, index: u32) -> dashcore::Address { let xpub = wallet.accounts.standard_bip44_accounts[&index].account_xpub; let account = info.accounts.standard_bip44_accounts.get_mut(&index).unwrap(); - account.next_receive_address(Some(&xpub), true).unwrap() + account.next_receive_address(Some(&xpub)).unwrap() } /// A wallet with `count` BIP44 accounts, and a receive address of each. diff --git a/key-wallet/src/transaction_checking/transaction_router/tests/asset_unlock.rs b/key-wallet/src/transaction_checking/transaction_router/tests/asset_unlock.rs index 7414b4d37..61402ac15 100644 --- a/key-wallet/src/transaction_checking/transaction_router/tests/asset_unlock.rs +++ b/key-wallet/src/transaction_checking/transaction_router/tests/asset_unlock.rs @@ -223,7 +223,7 @@ async fn test_asset_unlock_credits_dashpay_contact() { else { panic!("expected contact account"); }; - let address = addresses.next_unused(&KeySource::Public(xpub), true).unwrap(); + let address = addresses.next_unused(&KeySource::Public(xpub)).unwrap(); let mut tx = Transaction::dummy(&address, 0..0, &[2_000_000]); tx.version = 3; tx.special_transaction_payload = diff --git a/key-wallet/src/transaction_checking/transaction_router/tests/coinbase.rs b/key-wallet/src/transaction_checking/transaction_router/tests/coinbase.rs index 96ef9a50e..c9c5dbc5f 100644 --- a/key-wallet/src/transaction_checking/transaction_router/tests/coinbase.rs +++ b/key-wallet/src/transaction_checking/transaction_router/tests/coinbase.rs @@ -106,7 +106,7 @@ async fn test_coinbase_transaction_routing_to_bip44_change_address() { let change_address = managed_wallet_info .first_bip44_managed_account_mut() .expect("Failed to get first BIP44 managed account") - .next_change_address(Some(&xpub), true) + .next_change_address(Some(&xpub)) .expect("Failed to generate change address from BIP44 account"); // Create a coinbase transaction that pays to our change address diff --git a/key-wallet/src/transaction_checking/transaction_router/tests/identity_transactions.rs b/key-wallet/src/transaction_checking/transaction_router/tests/identity_transactions.rs index b34288c93..019a24c04 100644 --- a/key-wallet/src/transaction_checking/transaction_router/tests/identity_transactions.rs +++ b/key-wallet/src/transaction_checking/transaction_router/tests/identity_transactions.rs @@ -59,7 +59,7 @@ async fn test_identity_registration_account_routing() { .expect("Failed to get identity registration managed account"); // Use the new next_address method for identity registration account - let address = managed_account.next_address(Some(&xpub), true).expect("expected an address"); + let address = managed_account.next_address(Some(&xpub)).expect("expected an address"); // Create an Asset Lock transaction that funds identity registration use dashcore::opcodes; @@ -169,7 +169,7 @@ async fn test_normal_payment_to_identity_address_not_detected() { .expect("Failed to get identity registration managed account"); // Get an identity registration address - let address = managed_account.next_address(Some(&xpub), true).unwrap_or_else(|_| { + let address = managed_account.next_address(Some(&xpub)).unwrap_or_else(|_| { // Generate a dummy address for testing dashcore::Address::p2pkh( &dashcore::PublicKey::from_slice(&[0x03; 33]) diff --git a/key-wallet/src/transaction_checking/transaction_router/tests/provider.rs b/key-wallet/src/transaction_checking/transaction_router/tests/provider.rs index a15c64f91..3539af7d8 100644 --- a/key-wallet/src/transaction_checking/transaction_router/tests/provider.rs +++ b/key-wallet/src/transaction_checking/transaction_router/tests/provider.rs @@ -149,25 +149,25 @@ async fn test_provider_registration_transaction_routing_check_owner_only() { let managed_owner = managed_wallet_info .provider_owner_keys_managed_account_mut() .expect("Failed to get provider owner keys managed account"); - let owner_address = managed_owner.next_address(None, true).expect("expected owner address"); + let owner_address = managed_owner.next_address(None).expect("expected owner address"); let voting_address = other_managed_wallet_info .provider_voting_keys_managed_account_mut() .expect("Failed to get provider voting keys managed account") - .next_address(None, true) + .next_address(None) .expect("expected voting address"); let operator_public_key = other_managed_wallet_info .provider_operator_keys_managed_account_mut() .expect("Failed to get provider operator keys managed account") - .next_bls_operator_key(None, true) + .next_bls_operator_key(None) .expect("expected voting address"); // Payout addresses for providers are just regular addresses, not a separate account // For testing, we'll use the first standard account's address let payout_address = other_managed_wallet_info .first_bip44_managed_account_mut() - .and_then(|acc| acc.next_receive_address(None, true).ok()) + .and_then(|acc| acc.next_receive_address(None).ok()) .unwrap_or_else(|| { dashcore::Address::p2pkh( &dashcore::PublicKey::from_slice(&[0x02; 33]) @@ -286,25 +286,25 @@ async fn test_provider_registration_transaction_routing_check_voting_only() { let owner_address = other_managed_wallet_info .provider_owner_keys_managed_account_mut() .expect("Failed to get provider owner keys managed account") - .next_address(None, true) + .next_address(None) .expect("expected owner address"); let managed_voting = managed_wallet_info .provider_voting_keys_managed_account_mut() .expect("Failed to get provider voting keys managed account"); - let voting_address = managed_voting.next_address(None, true).expect("expected voting address"); + let voting_address = managed_voting.next_address(None).expect("expected voting address"); let operator_public_key = other_managed_wallet_info .provider_operator_keys_managed_account_mut() .expect("Failed to get provider operator keys managed account") - .next_bls_operator_key(None, true) + .next_bls_operator_key(None) .expect("expected operator key"); // Payout addresses for providers are just regular addresses, not a separate account // For testing, we'll use the first standard account's address let payout_address = other_managed_wallet_info .first_bip44_managed_account_mut() - .and_then(|acc| acc.next_receive_address(None, true).ok()) + .and_then(|acc| acc.next_receive_address(None).ok()) .unwrap_or_else(|| { dashcore::Address::p2pkh( &dashcore::PublicKey::from_slice(&[0x02; 33]) @@ -423,26 +423,26 @@ async fn test_provider_registration_transaction_routing_check_operator_only() { let owner_address = other_managed_wallet_info .provider_owner_keys_managed_account_mut() .expect("Failed to get provider owner keys managed account") - .next_address(None, true) + .next_address(None) .expect("expected owner address"); let voting_address = other_managed_wallet_info .provider_voting_keys_managed_account_mut() .expect("Failed to get provider voting keys managed account") - .next_address(None, true) + .next_address(None) .expect("expected voting address"); let managed_operator = managed_wallet_info .provider_operator_keys_managed_account_mut() .expect("Failed to get provider operator keys managed account"); let operator_public_key = - managed_operator.next_bls_operator_key(None, true).expect("expected operator key"); + managed_operator.next_bls_operator_key(None).expect("expected operator key"); // Payout addresses for providers are just regular addresses, not a separate account // For testing, we'll use the first standard account's address let payout_address = other_managed_wallet_info .first_bip44_managed_account_mut() - .and_then(|acc| acc.next_receive_address(None, true).ok()) + .and_then(|acc| acc.next_receive_address(None).ok()) .unwrap_or_else(|| { dashcore::Address::p2pkh( &dashcore::PublicKey::from_slice(&[0x02; 33]) @@ -612,19 +612,19 @@ async fn test_provider_registration_transaction_routing_check_platform_only() { let owner_address = other_managed_wallet_info .provider_owner_keys_managed_account_mut() .expect("Failed to get provider owner keys managed account") - .next_address(None, true) + .next_address(None) .expect("expected owner address"); let voting_address = other_managed_wallet_info .provider_voting_keys_managed_account_mut() .expect("Failed to get provider voting keys managed account") - .next_address(None, true) + .next_address(None) .expect("expected voting address"); let operator_public_key = other_managed_wallet_info .provider_operator_keys_managed_account_mut() .expect("Failed to get provider operator keys managed account") - .next_bls_operator_key(None, true) + .next_bls_operator_key(None) .expect("expected operator key"); // Get platform key from our wallet @@ -639,7 +639,7 @@ async fn test_provider_registration_transaction_routing_check_platform_only() { let eddsa_extended_key = root_key.to_eddsa_extended_priv_key(network).expect("expected EdDSA key"); let (_platform_key, info) = managed_platform - .next_eddsa_platform_key(eddsa_extended_key, true) + .next_eddsa_platform_key(eddsa_extended_key) .expect("expected platform key"); let platform_node_id = info.address; @@ -648,7 +648,7 @@ async fn test_provider_registration_transaction_routing_check_platform_only() { // For testing, we'll use the first standard account's address let payout_address = other_managed_wallet_info .first_bip44_managed_account_mut() - .and_then(|acc| acc.next_receive_address(None, true).ok()) + .and_then(|acc| acc.next_receive_address(None).ok()) .unwrap_or_else(|| { dashcore::Address::p2pkh( &dashcore::PublicKey::from_slice(&[0x02; 33]) @@ -809,14 +809,14 @@ async fn test_provider_update_registrar_with_voting_and_operator() { let voting_address = managed_wallet_info .provider_voting_keys_managed_account_mut() .expect("Failed to get provider voting keys managed account") - .next_address(None, true) + .next_address(None) .expect("expected voting address"); // Get BLS operator key let operator_public_key = managed_wallet_info .provider_operator_keys_managed_account_mut() .expect("Failed to get provider operator keys managed account") - .next_bls_operator_key(None, true) + .next_bls_operator_key(None) .expect("expected operator key"); let addr = test_addr(); @@ -892,7 +892,7 @@ async fn test_provider_revocation_classification_and_routing() { .expect("Failed to get first BIP44 managed account"); let return_address = managed_account - .next_receive_address(Some(&xpub), true) + .next_receive_address(Some(&xpub)) .expect("Failed to generate receive address"); let addr = test_addr(); diff --git a/key-wallet/src/transaction_checking/transaction_router/tests/routing.rs b/key-wallet/src/transaction_checking/transaction_router/tests/routing.rs index 65d2d487b..ccd385027 100644 --- a/key-wallet/src/transaction_checking/transaction_router/tests/routing.rs +++ b/key-wallet/src/transaction_checking/transaction_router/tests/routing.rs @@ -98,7 +98,7 @@ async fn test_transaction_routing_to_bip32_account() { .first_bip32_managed_account_mut() .expect("Failed to get first BIP32 managed account"); managed_account - .next_receive_address(Some(&xpub), true) + .next_receive_address(Some(&xpub)) .expect("Failed to generate receive address from BIP32 account") }; @@ -187,7 +187,7 @@ async fn test_transaction_routing_to_coinjoin_account() { panic!("Expected CoinJoin account type"); }; external_addresses - .next_unused(&KeySource::Public(xpub), true) + .next_unused(&KeySource::Public(xpub)) .expect("Failed to derive CoinJoin address") }; @@ -264,7 +264,7 @@ async fn test_transaction_affects_multiple_accounts() { .bip44_managed_account_at_index_mut(0) .expect("Failed to get BIP44 managed account at index 0"); let address0 = managed_account0 - .next_receive_address(Some(&xpub0), true) + .next_receive_address(Some(&xpub0)) .expect("Failed to generate receive address for account 0"); // BIP44 account 1 @@ -278,7 +278,7 @@ async fn test_transaction_affects_multiple_accounts() { .bip44_managed_account_at_index_mut(1) .expect("Failed to get BIP44 managed account at index 1"); let address1 = managed_account1 - .next_receive_address(Some(&xpub1), true) + .next_receive_address(Some(&xpub1)) .expect("Failed to generate receive address for account 1"); // BIP32 account @@ -292,7 +292,7 @@ async fn test_transaction_affects_multiple_accounts() { .first_bip32_managed_account_mut() .expect("Failed to get first BIP32 managed account"); let address2 = managed_account2 - .next_receive_address(Some(&xpub2), true) + .next_receive_address(Some(&xpub2)) .expect("Failed to generate receive address for BIP32 account"); // Create a transaction that sends to multiple accounts @@ -367,7 +367,7 @@ fn test_next_address_method_restrictions() { .first_bip44_managed_account_mut() .expect("Failed to get first BIP44 managed account"); - let result = managed_account.next_address(Some(&xpub), true); + let result = managed_account.next_address(Some(&xpub)); assert!(result.is_err(), "Standard BIP44 accounts should reject next_address"); assert_eq!( result.expect_err("Expected an error when calling next_address on BIP44 account"), @@ -375,15 +375,15 @@ fn test_next_address_method_restrictions() { ); // But next_receive_address and next_change_address should work - assert!(managed_account.next_receive_address(Some(&xpub), true).is_ok()); - assert!(managed_account.next_change_address(Some(&xpub), true).is_ok()); + assert!(managed_account.next_receive_address(Some(&xpub)).is_ok()); + assert!(managed_account.next_change_address(Some(&xpub)).is_ok()); } // Test that standard BIP32 accounts reject next_address (if present) if let Some(bip32_account) = wallet.accounts.standard_bip32_accounts.get(&0) { let xpub = bip32_account.account_xpub; if let Some(managed_account) = managed_wallet_info.first_bip32_managed_account_mut() { - let result = managed_account.next_address(Some(&xpub), true); + let result = managed_account.next_address(Some(&xpub)); assert!(result.is_err(), "Standard BIP32 accounts should reject next_address"); assert_eq!( result.expect_err("Expected an error when calling next_address on BIP44 account"), @@ -399,7 +399,7 @@ fn test_next_address_method_restrictions() { .identity_registration_managed_account_mut() .expect("Failed to get identity registration managed account"); - let result = managed_account.next_address(Some(&xpub), true); + let result = managed_account.next_address(Some(&xpub)); // This should either succeed or fail with "No unused addresses available" // but NOT with "Standard accounts must use..." if let Err(e) = result { diff --git a/key-wallet/src/transaction_checking/wallet_checker.rs b/key-wallet/src/transaction_checking/wallet_checker.rs index bcfdc7595..9c84705ca 100644 --- a/key-wallet/src/transaction_checking/wallet_checker.rs +++ b/key-wallet/src/transaction_checking/wallet_checker.rs @@ -616,7 +616,7 @@ mod tests { let xpub = bip32_account.account_xpub; if let Some(managed_account) = managed_wallet.first_bip32_managed_account_mut() { let address = managed_account - .next_receive_address(Some(&xpub), true) + .next_receive_address(Some(&xpub)) .expect("Should get BIP32 address"); (Some(xpub), Some(address)) } else { @@ -651,7 +651,7 @@ mod tests { let xpub = coinjoin_account.account_xpub; if let Some(managed_account) = managed_wallet.first_coinjoin_managed_account_mut() { let address = managed_account - .next_address(Some(&xpub), true) + .next_address(Some(&xpub)) .expect("Should get CoinJoin address"); (Some(xpub), Some(address)) } else { @@ -900,7 +900,7 @@ mod tests { } = managed_account.managed_account_type_mut() { external_addresses - .next_unused(&KeySource::Public(coinjoin_xpub), true) + .next_unused(&KeySource::Public(coinjoin_xpub)) .expect("coinjoin address") } else { panic!("Expected CoinJoin account type"); @@ -911,7 +911,7 @@ mod tests { let change_address = managed_wallet .first_bip44_managed_account_mut() .expect("managed bip44") - .next_change_address(Some(&bip44_xpub), true) + .next_change_address(Some(&bip44_xpub)) .expect("bip44 change address"); // Fund the CoinJoin address, creating a CoinJoin UTXO. @@ -1242,7 +1242,7 @@ mod tests { let change_address = managed_wallet .first_bip44_managed_account_mut() .expect("Should have managed account") - .next_change_address(Some(&xpub), true) + .next_change_address(Some(&xpub)) .expect("Should get change address"); // Create the funding transaction @@ -1490,14 +1490,14 @@ mod tests { let address0 = managed_wallet .bip44_managed_account_at_index_mut(0) .expect("managed account 0") - .next_receive_address(Some(&xpub0), true) + .next_receive_address(Some(&xpub0)) .expect("address for account 0"); let xpub1 = wallet.accounts.standard_bip44_accounts.get(&1).expect("account 1").account_xpub; let address1 = managed_wallet .bip44_managed_account_at_index_mut(1) .expect("managed account 1") - .next_receive_address(Some(&xpub1), true) + .next_receive_address(Some(&xpub1)) .expect("address for account 1"); let mut wallet_mut = wallet; @@ -1610,7 +1610,7 @@ mod tests { let address0 = managed_wallet .bip44_managed_account_at_index_mut(0) .expect("Should have managed account 0") - .next_receive_address(Some(&xpub0), true) + .next_receive_address(Some(&xpub0)) .expect("Should generate address for account 0"); let xpub1 = wallet @@ -1622,7 +1622,7 @@ mod tests { let address1 = managed_wallet .bip44_managed_account_at_index_mut(1) .expect("Should have managed account 1") - .next_receive_address(Some(&xpub1), true) + .next_receive_address(Some(&xpub1)) .expect("Should generate address for account 1"); // Build a tx with outputs to both accounts. @@ -1892,7 +1892,7 @@ mod tests { .managed_wallet .first_bip44_managed_account_mut() .expect("account") - .next_receive_address(Some(&ctx.xpub), true) + .next_receive_address(Some(&ctx.xpub)) .expect("second receive address"); let multi_tx = Transaction { @@ -1939,7 +1939,7 @@ mod tests { .managed_wallet .first_bip44_managed_account_mut() .expect("account") - .next_change_address(Some(&ctx.xpub), true) + .next_change_address(Some(&ctx.xpub)) .expect("change address"); let send_amount = 600_000u64; @@ -1995,13 +1995,13 @@ mod tests { .managed_wallet .first_bip44_managed_account_mut() .expect("account") - .next_receive_address(Some(&ctx.xpub), true) + .next_receive_address(Some(&ctx.xpub)) .expect("self address"); let change_address = ctx .managed_wallet .first_bip44_managed_account_mut() .expect("account") - .next_change_address(Some(&ctx.xpub), true) + .next_change_address(Some(&ctx.xpub)) .expect("change address"); let self_amount = 800_000u64; @@ -2088,7 +2088,7 @@ mod tests { .managed_wallet .first_bip44_managed_account_mut() .expect("account") - .next_change_address(Some(&ctx.xpub), true) + .next_change_address(Some(&ctx.xpub)) .expect("change address"); let send_amount = 400_000u64; @@ -2241,9 +2241,7 @@ mod tests { .. } = managed_account.managed_account_type_mut() { - external_addresses - .next_unused(&KeySource::Public(xpub), true) - .expect("coinjoin address") + external_addresses.next_unused(&KeySource::Public(xpub)).expect("coinjoin address") } else { panic!("Expected CoinJoin account type"); }; @@ -2338,7 +2336,7 @@ mod tests { .managed_wallet .first_bip44_managed_account_mut() .expect("account") - .next_change_address(Some(&ctx.xpub), true) + .next_change_address(Some(&ctx.xpub)) .expect("change address"); // Spend the funding UTXO: send some out, send the rest back to ourselves @@ -2430,7 +2428,7 @@ mod tests { .managed_wallet .first_bip44_managed_account_mut() .expect("account") - .next_change_address(Some(&ctx.xpub), true) + .next_change_address(Some(&ctx.xpub)) .expect("change address"); let spend = Transaction { version: 2, @@ -2512,7 +2510,7 @@ mod tests { .managed_wallet .first_bip44_managed_account_mut() .expect("account") - .next_change_address(Some(&ctx.xpub), true) + .next_change_address(Some(&ctx.xpub)) .expect("change address"); let loser = Transaction { version: 2, @@ -2600,7 +2598,7 @@ mod tests { .managed_wallet .first_bip32_managed_account_mut() .expect("BIP32 managed account") - .next_receive_address(Some(&bip32_xpub), true) + .next_receive_address(Some(&bip32_xpub)) .expect("BIP32 receive address"); let funding_tx = Transaction::dummy(&bip32_address, 0..1, &[1_000_000]); ctx.check_transaction( @@ -2645,7 +2643,7 @@ mod tests { .managed_wallet .first_bip44_managed_account_mut() .expect("account") - .next_change_address(Some(&ctx.xpub), true) + .next_change_address(Some(&ctx.xpub)) .expect("change address"); let loser = spend(&loser_change, 399_000, 600_000); ctx.check_transaction(&loser, TransactionContext::Mempool).await; @@ -2654,7 +2652,7 @@ mod tests { .managed_wallet .first_bip32_managed_account_mut() .expect("BIP32 managed account") - .next_change_address(Some(&bip32_xpub), true) + .next_change_address(Some(&bip32_xpub)) .expect("BIP32 change address"); let winner = spend(&winner_change, 299_000, 700_000); ctx.check_transaction( @@ -2732,7 +2730,7 @@ mod tests { .managed_wallet .first_bip44_managed_account_mut() .expect("account") - .next_change_address(Some(&ctx.xpub), true) + .next_change_address(Some(&ctx.xpub)) .expect("change address"); let winner = spend(&winner_change, 299_000, 700_000); ctx.check_transaction( @@ -2752,7 +2750,7 @@ mod tests { .managed_wallet .first_bip44_managed_account_mut() .expect("account") - .next_change_address(Some(&ctx.xpub), true) + .next_change_address(Some(&ctx.xpub)) .expect("change address"); let loser = spend(&loser_change, 399_000, 600_000); ctx.check_transaction(&loser, TransactionContext::Mempool).await; @@ -2814,7 +2812,7 @@ mod tests { ctx.managed_wallet .first_bip44_managed_account_mut() .expect("account") - .next_change_address(Some(&ctx.xpub), true) + .next_change_address(Some(&ctx.xpub)) .expect("change address") }; @@ -2941,7 +2939,7 @@ mod tests { .managed_wallet .first_bip44_managed_account_mut() .expect("account") - .next_change_address(Some(&ctx.xpub), true) + .next_change_address(Some(&ctx.xpub)) .expect("change address"); let loser = Transaction { version: 2, @@ -3062,7 +3060,7 @@ mod tests { .managed_wallet .first_bip44_managed_account_mut() .expect("account") - .next_change_address(Some(&ctx.xpub), true) + .next_change_address(Some(&ctx.xpub)) .expect("change address"); let identity_xpub = ctx .wallet @@ -3075,7 +3073,7 @@ mod tests { .managed_wallet .identity_registration_managed_account_mut() .expect("managed identity account") - .next_address(Some(&identity_xpub), true) + .next_address(Some(&identity_xpub)) .expect("identity address"); let mut loser = spend(vec![coin_a, coin_b], &loser_change, 99_000, 800_000); loser.version = 3; @@ -3100,7 +3098,7 @@ mod tests { .managed_wallet .first_bip44_managed_account_mut() .expect("account") - .next_change_address(Some(&ctx.xpub), true) + .next_change_address(Some(&ctx.xpub)) .expect("change address"); let winner = spend(vec![coin_a], &winner_change, 99_000, 400_000); let result = ctx @@ -3217,7 +3215,7 @@ mod tests { .managed_wallet .first_bip44_managed_account_mut() .expect("account") - .next_change_address(Some(&ctx.xpub), true) + .next_change_address(Some(&ctx.xpub)) .expect("change address"); let parent = spend(vec![coin_x], &parent_change, 99_000, 400_000); ctx.check_transaction(&parent, TransactionContext::Mempool).await; @@ -3232,7 +3230,7 @@ mod tests { .managed_wallet .first_bip44_managed_account_mut() .expect("account") - .next_change_address(Some(&ctx.xpub), true) + .next_change_address(Some(&ctx.xpub)) .expect("change address"); let child = spend(vec![parent_change_outpoint, coin_c], &child_change, 89_000, 400_000); ctx.check_transaction(&child, TransactionContext::Mempool).await; @@ -3243,7 +3241,7 @@ mod tests { .managed_wallet .first_bip44_managed_account_mut() .expect("account") - .next_change_address(Some(&ctx.xpub), true) + .next_change_address(Some(&ctx.xpub)) .expect("change address"); let winner = spend(vec![coin_x], &winner_change, 99_000, 400_000); let result = ctx @@ -3306,7 +3304,7 @@ mod tests { .managed_wallet .first_bip32_managed_account_mut() .expect("BIP32 account") - .next_receive_address(Some(&bip32_xpub), true) + .next_receive_address(Some(&bip32_xpub)) .expect("BIP32 address"); let funding_tx = Transaction::dummy(&ctx.receive_address, 0..2, &[500_000, 400_000]); @@ -3364,7 +3362,7 @@ mod tests { .managed_wallet .first_bip44_managed_account_mut() .expect("account") - .next_change_address(Some(&ctx.xpub), true) + .next_change_address(Some(&ctx.xpub)) .expect("change address"); let rival = spend(vec![coin_b], &rival_change, 50_000, 340_000); ctx.check_transaction(&rival, TransactionContext::Mempool).await; @@ -3375,7 +3373,7 @@ mod tests { .managed_wallet .first_bip44_managed_account_mut() .expect("account") - .next_change_address(Some(&ctx.xpub), true) + .next_change_address(Some(&ctx.xpub)) .expect("change address"); let winner = spend(vec![coin_a], &winner_change, 99_000, 400_000); let result = ctx @@ -3459,7 +3457,7 @@ mod tests { .managed_wallet .first_bip44_managed_account_mut() .expect("account") - .next_change_address(Some(&ctx.xpub), true) + .next_change_address(Some(&ctx.xpub)) .expect("change address"); let loser = spend_of(&loser_change, 399_000, 600_000); ctx.check_transaction(&loser, TransactionContext::Mempool).await; @@ -3468,7 +3466,7 @@ mod tests { .managed_wallet .first_bip44_managed_account_mut() .expect("account") - .next_change_address(Some(&ctx.xpub), true) + .next_change_address(Some(&ctx.xpub)) .expect("change address"); let winner = spend_of(&winner_change, 299_000, 700_000); ctx.check_transaction(&winner, TransactionContext::Mempool).await; @@ -3543,7 +3541,7 @@ mod tests { .managed_wallet .first_bip44_managed_account_mut() .expect("account") - .next_change_address(Some(&ctx.xpub), true) + .next_change_address(Some(&ctx.xpub)) .expect("change address"); // The tip pays us twice, and nothing spends it onward, so both // outputs are still live when the cascade runs — exercising the @@ -3571,7 +3569,7 @@ mod tests { .managed_wallet .first_bip44_managed_account_mut() .expect("account") - .next_change_address(Some(&ctx.xpub), true) + .next_change_address(Some(&ctx.xpub)) .expect("change address"); outputs.push(TxOut { value: change_b, @@ -3718,7 +3716,7 @@ mod tests { .managed_wallet .first_bip44_managed_account_mut() .expect("account") - .next_change_address(Some(&ctx.xpub), true) + .next_change_address(Some(&ctx.xpub)) .expect("change address"); let loser = spend_of(&first_change, 399_000, 600_000); ctx.check_transaction(&loser, TransactionContext::Mempool).await; @@ -3738,7 +3736,7 @@ mod tests { .managed_wallet .first_bip44_managed_account_mut() .expect("account") - .next_change_address(Some(&ctx.xpub), true) + .next_change_address(Some(&ctx.xpub)) .expect("change address"); let winner = spend_of(&second_change, 299_000, 700_000); ctx.check_transaction( @@ -3799,7 +3797,7 @@ mod tests { .managed_wallet .first_bip32_managed_account_mut() .expect("BIP32 managed account") - .next_receive_address(Some(&bip32_xpub), true) + .next_receive_address(Some(&bip32_xpub)) .expect("BIP32 receive address"); let funding_value = 1_000_000u64; @@ -3817,7 +3815,7 @@ mod tests { .managed_wallet .first_bip44_managed_account_mut() .expect("account") - .next_change_address(Some(&ctx.xpub), true) + .next_change_address(Some(&ctx.xpub)) .expect("change address"); let send_amount = 600_000u64; @@ -3896,7 +3894,7 @@ mod tests { .managed_wallet .first_bip44_managed_account_mut() .expect("account") - .next_change_address(Some(&ctx.xpub), true) + .next_change_address(Some(&ctx.xpub)) .expect("change address"); // Spend the still-unconfirmed funding UTXO: some out, the rest back @@ -3995,7 +3993,7 @@ mod tests { let addresses: Vec<_> = (0..=30) .map(|index| { external_addresses - .generate_address_at_index(index, &KeySource::Public(xpub), true) + .generate_address_at_index(index, &KeySource::Public(xpub)) .unwrap() .address }) diff --git a/key-wallet/src/wallet/managed_wallet_info/asset_lock_builder.rs b/key-wallet/src/wallet/managed_wallet_info/asset_lock_builder.rs index 8779d1a70..a829776a7 100644 --- a/key-wallet/src/wallet/managed_wallet_info/asset_lock_builder.rs +++ b/key-wallet/src/wallet/managed_wallet_info/asset_lock_builder.rs @@ -687,7 +687,7 @@ mod tests { ) -> OutPoint { let account_xpub = wallet.get_bip44_account(0).unwrap().account_xpub; let account = info.accounts.standard_bip44_accounts.get_mut(&0).unwrap(); - let funding_address = account.next_receive_address(Some(&account_xpub), true).unwrap(); + let funding_address = account.next_receive_address(Some(&account_xpub)).unwrap(); let outpoint = OutPoint { txid: Txid::from_byte_array([txid_byte; 32]), vout: 0, @@ -727,9 +727,7 @@ mod tests { crate::ManagedAccountType::CoinJoin { external_addresses, .. - } => external_addresses - .next_unused(&crate::KeySource::Public(account_xpub), true) - .unwrap(), + } => external_addresses.next_unused(&crate::KeySource::Public(account_xpub)).unwrap(), _ => unreachable!("coinjoin account must carry the CoinJoin managed type"), }; let outpoint = OutPoint { @@ -1294,7 +1292,7 @@ mod tests { .expect("default wallet has BIP32 account 0") .account_xpub; let account = info.accounts.standard_bip32_accounts.get_mut(&0).unwrap(); - let funding_address = account.next_receive_address(Some(&account_xpub), true).unwrap(); + let funding_address = account.next_receive_address(Some(&account_xpub)).unwrap(); let outpoint = OutPoint { txid: Txid::from_byte_array([txid_byte; 32]), vout: 0, diff --git a/key-wallet/src/wallet/managed_wallet_info/mod.rs b/key-wallet/src/wallet/managed_wallet_info/mod.rs index 523fd3e23..4db42ec4b 100644 --- a/key-wallet/src/wallet/managed_wallet_info/mod.rs +++ b/key-wallet/src/wallet/managed_wallet_info/mod.rs @@ -630,9 +630,8 @@ impl ManagedWalletInfo { let managed_account = collection.standard_bip44_accounts.get_mut(&account_index)?; let wallet_account = wallet.get_bip44_account(account_index)?; - let address = managed_account - .next_change_address(Some(&wallet_account.account_xpub), true) - .ok(); + let address = + managed_account.next_change_address(Some(&wallet_account.account_xpub)).ok(); if let (Some(address), true) = (&address, mark_as_used) { managed_account.mark_address_used(address); @@ -644,9 +643,8 @@ impl ManagedWalletInfo { let managed_account = collection.standard_bip32_accounts.get_mut(&account_index)?; let wallet_account = wallet.get_bip32_account(account_index)?; - let address = managed_account - .next_change_address(Some(&wallet_account.account_xpub), true) - .ok(); + let address = + managed_account.next_change_address(Some(&wallet_account.account_xpub)).ok(); if let (Some(address), true) = (&address, mark_as_used) { managed_account.mark_address_used(address); @@ -686,9 +684,8 @@ impl ManagedWalletInfo { let managed_account = collection.standard_bip44_accounts.get_mut(&account_index)?; let wallet_account = wallet.get_bip44_account(account_index)?; - let address = managed_account - .next_receive_address(Some(&wallet_account.account_xpub), true) - .ok(); + let address = + managed_account.next_receive_address(Some(&wallet_account.account_xpub)).ok(); if let (Some(address), true) = (&address, mark_as_used) { managed_account.mark_address_used(address); @@ -700,9 +697,8 @@ impl ManagedWalletInfo { let managed_account = collection.standard_bip32_accounts.get_mut(&account_index)?; let wallet_account = wallet.get_bip32_account(account_index)?; - let address = managed_account - .next_receive_address(Some(&wallet_account.account_xpub), true) - .ok(); + let address = + managed_account.next_receive_address(Some(&wallet_account.account_xpub)).ok(); if let (Some(address), true) = (&address, mark_as_used) { managed_account.mark_address_used(address); 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..b1acf2a36 100644 --- a/key-wallet/src/wallet/managed_wallet_info/transaction_builder.rs +++ b/key-wallet/src/wallet/managed_wallet_info/transaction_builder.rs @@ -225,7 +225,7 @@ impl TransactionBuilder { self.funding.push((funds_acc.reservations().clone(), owned)); self.inputs.extend(candidates); if self.change_addr.is_none() { - self.change_addr = funds_acc.next_change_address(Some(&acc.account_xpub), true).ok(); + self.change_addr = funds_acc.next_change_address(Some(&acc.account_xpub)).ok(); } self } @@ -1982,8 +1982,8 @@ mod tests { // Nor may it burn a pool address to derive one it then discards. let mut control = ManagedCoreFundsAccount::dummy_bip44(); assert_eq!( - funds.next_change_address(Some(&account.account_xpub), true).expect("change address"), - control.next_change_address(Some(&account.account_xpub), true).expect("change address"), + funds.next_change_address(Some(&account.account_xpub)).expect("change address"), + control.next_change_address(Some(&account.account_xpub)).expect("change address"), ); } 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..8c194b845 100644 --- a/key-wallet/src/wallet/managed_wallet_info/transaction_building.rs +++ b/key-wallet/src/wallet/managed_wallet_info/transaction_building.rs @@ -819,7 +819,7 @@ mod tests { .standard_bip44_accounts .get_mut(&0) .unwrap() - .next_receive_address(Some(&account_xpub), true) + .next_receive_address(Some(&account_xpub)) .unwrap(); let utxo = Utxo { @@ -938,7 +938,7 @@ mod tests { .standard_bip44_accounts .get_mut(&0) .unwrap() - .next_receive_address(Some(&mainnet_xpub), true) + .next_receive_address(Some(&mainnet_xpub)) .unwrap(); // Re-parse as NetworkUnchecked to hand to the builder. let mainnet_dest = @@ -998,8 +998,8 @@ mod tests { ManagedAccountType::DashpayReceivingFunds { addresses, .. - } => addresses.next_unused(&KeySource::Public(account_xpub), true).unwrap(), - _ => account.next_receive_address(Some(&account_xpub), true).unwrap(), + } => addresses.next_unused(&KeySource::Public(account_xpub)).unwrap(), + _ => account.next_receive_address(Some(&account_xpub)).unwrap(), }; let outpoint = OutPoint { From 14e85370809678694db70f6f3909ac6ef8c0bfff Mon Sep 17 00:00:00 2001 From: Borja Castellano Date: Wed, 11 Nov 2026 06:21:30 -0800 Subject: [PATCH 11/22] docs(key-wallet): drop links to crate-private pool methods The docs of `next_receive_address_and_reserve` and `sweep_expired_receive_reservations` linked to `AddressPool` methods that are now `pub(crate)`, which fails `just doc`. --- key-wallet/src/managed_account/managed_core_funds_account.rs | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/key-wallet/src/managed_account/managed_core_funds_account.rs b/key-wallet/src/managed_account/managed_core_funds_account.rs index 1e5d73265..2c9a020df 100644 --- a/key-wallet/src/managed_account/managed_core_funds_account.rs +++ b/key-wallet/src/managed_account/managed_core_funds_account.rs @@ -1448,7 +1448,7 @@ impl ManagedCoreFundsAccount { /// reservation. Only valid for Standard accounts. /// /// Derivation of fresh addresses on this path is unbounded, so callers are - /// assumed trusted. See [`address_pool::AddressPool::next_unused_and_reserve`]. + /// assumed trusted. pub fn next_receive_address_and_reserve( &mut self, account_xpub: Option<&ExtendedPubKey>, @@ -1507,8 +1507,7 @@ impl ManagedCoreFundsAccount { /// 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 - /// [`address_pool::AddressPool::sweep_expired_reservations`]. + /// monitor revision when that is non-zero. pub fn sweep_expired_receive_reservations(&mut self, now: u64, ttl: u64) -> usize { if let ManagedAccountType::Standard { external_addresses, From f92e77a40bbb9f2c1f5f1927d9166c894a7a32f8 Mon Sep 17 00:00:00 2001 From: Borja Castellano Date: Wed, 11 Nov 2026 06:21:48 -0800 Subject: [PATCH 12/22] refactor(key-wallet)!: drop unused `GapLimit` tracker `GapLimit`, `GapLimitManager`, `GapLimitStage` and their stats types were only re-exported. Nothing in this repository or in Dash Platform uses them, since `AddressPool` tracks the gap limit itself. They are removed with their tests and the README example that used them. --- key-wallet/README.md | 27 --- key-wallet/src/gap_limit.rs | 431 ------------------------------------ key-wallet/src/lib.rs | 1 - 3 files changed, 459 deletions(-) diff --git a/key-wallet/README.md b/key-wallet/README.md index 4cd5debb6..e32cb198b 100644 --- a/key-wallet/README.md +++ b/key-wallet/README.md @@ -113,33 +113,6 @@ for (index, address) in addresses.iter().enumerate() { } ``` -### Address Generation with Gap Limit - -```rust -use key_wallet::gap_limit::{GapLimit, GapLimitStage}; - -// Create gap limit manager -let gap_limit = GapLimit::new(20); // Standard gap limit of 20 - -// Track address usage -let mut stage = GapLimitStage::new(); -for i in 0..100 { - let address = account.derive_receive_address(i)?; - - // Check if address has been used (would come from blockchain scan) - let is_used = check_address_on_blockchain(&address); - - if is_used { - stage.mark_used(i); - } - - // Check if we've reached gap limit - if stage.should_stop(i, gap_limit.gap()) { - break; - } -} -``` - ### CoinJoin Account ```rust diff --git a/key-wallet/src/gap_limit.rs b/key-wallet/src/gap_limit.rs index 546f0a41a..e75e6ce1e 100644 --- a/key-wallet/src/gap_limit.rs +++ b/key-wallet/src/gap_limit.rs @@ -1,15 +1,3 @@ -//! Gap limit management for HD wallet address discovery -//! -//! Implements BIP44 gap limit tracking to determine when to stop generating -//! addresses during wallet recovery and discovery. - -#[cfg(feature = "bincode")] -use bincode_derive::{Decode, Encode}; -use core::cmp; -#[cfg(feature = "serde")] -use serde::{Deserialize, Serialize}; -use std::collections::HashSet; - /// Standard gap limit for external addresses (BIP44 recommendation) pub const DEFAULT_EXTERNAL_GAP_LIMIT: u32 = 30; @@ -53,422 +41,3 @@ pub const DIP17_GAP_LIMIT: u32 = 20; /// Maximum gap limit to prevent excessive address generation pub const MAX_GAP_LIMIT: u32 = 1000; - -/// Stages of gap limit processing -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] -#[cfg_attr(feature = "bincode", derive(Encode, Decode))] -pub enum GapLimitStage { - /// Initial address generation - Initial, - /// Extended search for more addresses - Extended, - /// Active scanning for address usage - Scanning, - /// Discovery complete - Complete, -} - -/// Gap limit tracker for a single chain (external or internal) -#[derive(Debug, Clone)] -#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] -#[cfg_attr(feature = "bincode", derive(Encode, Decode))] -pub struct GapLimit { - /// The gap limit value - pub limit: u32, - /// Current stage of processing - pub stage: GapLimitStage, - /// Count of consecutive unused addresses - pub current_unused_count: u32, - /// Highest index that has been used - pub highest_used_index: Option, - /// Highest index that has been generated - pub highest_generated_index: u32, - /// Set of all used indices - pub used_indices: HashSet, - /// Whether gap limit has been reached - pub limit_reached: bool, -} - -impl GapLimit { - /// Create a new gap limit tracker - pub fn new(limit: u32) -> Self { - let safe_limit = cmp::min(limit, MAX_GAP_LIMIT); - Self { - limit: safe_limit, - stage: GapLimitStage::Initial, - current_unused_count: 0, - highest_used_index: None, - highest_generated_index: 0, - used_indices: HashSet::new(), - limit_reached: false, - } - } - - /// Create with a specific stage - pub fn new_with_stage(limit: u32, stage: GapLimitStage) -> Self { - let mut gap = Self::new(limit); - gap.stage = stage; - gap - } - - /// Mark an address at the given index as used - pub fn mark_used(&mut self, index: u32) { - self.used_indices.insert(index); - - // Update highest used index - self.highest_used_index = match self.highest_used_index { - None => Some(index), - Some(current) => Some(cmp::max(current, index)), - }; - - // Reset unused count if this breaks a gap - if let Some(highest) = self.highest_used_index { - if index > highest { - self.current_unused_count = 0; - } else { - // Recalculate unused count from highest used - self.current_unused_count = self.calculate_current_gap(); - } - } - - // Update limit reached status - self.update_limit_reached(); - - // Update stage if we're in scanning - if self.stage == GapLimitStage::Scanning && !self.limit_reached { - self.stage = GapLimitStage::Extended; - } - } - - /// Mark an address as generated (but not necessarily used) - pub fn mark_generated(&mut self, index: u32) { - self.highest_generated_index = cmp::max(self.highest_generated_index, index); - - // Update current unused count - if !self.used_indices.contains(&index) { - if let Some(highest_used) = self.highest_used_index { - if index > highest_used { - self.current_unused_count = index - highest_used; - } - } else { - // No addresses used yet - self.current_unused_count = index + 1; - } - } - - self.update_limit_reached(); - } - - /// Calculate the current gap (consecutive unused addresses) - fn calculate_current_gap(&self) -> u32 { - match self.highest_used_index { - None => self.highest_generated_index + 1, - Some(highest_used) => { - let mut gap = 0; - for i in (highest_used + 1)..=self.highest_generated_index { - if !self.used_indices.contains(&i) { - gap += 1; - } else { - gap = 0; // Reset if we find a used address - } - } - gap - } - } - } - - /// Update whether the gap limit has been reached - fn update_limit_reached(&mut self) { - self.limit_reached = self.current_unused_count >= self.limit; - - if self.limit_reached && self.stage == GapLimitStage::Extended { - self.stage = GapLimitStage::Complete; - } - } - - /// Check if we should generate more addresses - pub fn should_generate_more(&self) -> bool { - !self.limit_reached && self.stage != GapLimitStage::Complete - } - - /// Check if extension is needed (for discovery) - pub fn needs_extension(&self) -> bool { - self.stage == GapLimitStage::Initial - && self.highest_used_index.is_some() - && !self.limit_reached - } - - /// Extend the gap limit for deeper search - pub fn extend(&mut self, new_limit: u32) { - self.limit = cmp::min(new_limit, MAX_GAP_LIMIT); - self.stage = GapLimitStage::Extended; - self.update_limit_reached(); - } - - /// Reset the unused count (used when new activity is detected) - pub fn reset_unused_count(&mut self) { - self.current_unused_count = 0; - self.limit_reached = false; - - if self.stage == GapLimitStage::Complete { - self.stage = GapLimitStage::Extended; - } - } - - /// Get the next index to generate - pub fn next_index(&self) -> u32 { - self.highest_generated_index + 1 - } - - /// Get the number of addresses that should be generated - pub fn addresses_to_generate(&self) -> u32 { - if self.limit_reached { - return 0; - } - - match self.highest_used_index { - None => { - // No addresses used yet, generate up to the limit - self.limit.saturating_sub(self.highest_generated_index) - } - Some(highest_used) => { - // Generate enough to maintain the gap limit - let target = highest_used + self.limit + 1; - target.saturating_sub(self.highest_generated_index) - } - } - } - - /// Get statistics about the gap limit - pub fn stats(&self) -> GapLimitStats { - GapLimitStats { - limit: self.limit, - stage: self.stage, - current_gap: self.current_unused_count, - highest_used: self.highest_used_index, - highest_generated: self.highest_generated_index, - used_count: self.used_indices.len() as u32, - unused_count: self.highest_generated_index + 1 - self.used_indices.len() as u32, - limit_reached: self.limit_reached, - } - } -} - -/// Statistics about gap limit state -#[derive(Debug, Clone)] -#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] -#[cfg_attr(feature = "bincode", derive(Encode, Decode))] -pub struct GapLimitStats { - pub limit: u32, - pub stage: GapLimitStage, - pub current_gap: u32, - pub highest_used: Option, - pub highest_generated: u32, - pub used_count: u32, - pub unused_count: u32, - pub limit_reached: bool, -} - -/// Manager for multiple gap limits (external, internal, CoinJoin) -#[derive(Debug, Clone)] -#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] -#[cfg_attr(feature = "bincode", derive(Encode, Decode))] -pub struct GapLimitManager { - /// External (receive) address gap limit - pub external: GapLimit, - /// Internal (change) address gap limit - pub internal: GapLimit, - /// CoinJoin address gap limit (optional) - pub coinjoin: Option, -} - -impl GapLimitManager { - /// Create a new gap limit manager with default limits - pub fn new_default() -> Self { - Self { - external: GapLimit::new(DEFAULT_EXTERNAL_GAP_LIMIT), - internal: GapLimit::new(DEFAULT_INTERNAL_GAP_LIMIT), - coinjoin: None, - } - } - - /// Create with specific limits - pub fn new(external_limit: u32, internal_limit: u32, coinjoin_limit: Option) -> Self { - Self { - external: GapLimit::new(external_limit), - internal: GapLimit::new(internal_limit), - coinjoin: coinjoin_limit.map(GapLimit::new), - } - } - - /// Enable CoinJoin gap limit tracking - pub fn enable_coinjoin(&mut self, limit: u32) { - self.coinjoin = Some(GapLimit::new(limit)); - } - - /// Check if any limits need more addresses generated - pub fn needs_generation(&self) -> bool { - self.external.should_generate_more() - || self.internal.should_generate_more() - || self.coinjoin.as_ref().is_some_and(|g| g.should_generate_more()) - } - - /// Check if discovery is complete - pub fn is_discovery_complete(&self) -> bool { - let external_complete = - self.external.stage == GapLimitStage::Complete || self.external.limit_reached; - let internal_complete = - self.internal.stage == GapLimitStage::Complete || self.internal.limit_reached; - let coinjoin_complete = self - .coinjoin - .as_ref() - .is_none_or(|g| g.stage == GapLimitStage::Complete || g.limit_reached); - - external_complete && internal_complete && coinjoin_complete - } - - /// Get combined statistics - pub fn stats(&self) -> GapLimitManagerStats { - GapLimitManagerStats { - external: self.external.stats(), - internal: self.internal.stats(), - coinjoin: self.coinjoin.as_ref().map(|g| g.stats()), - discovery_complete: self.is_discovery_complete(), - } - } - - /// Reset all gap limits (for rescan) - pub fn reset(&mut self) { - self.external.reset_unused_count(); - self.internal.reset_unused_count(); - if let Some(ref mut coinjoin) = self.coinjoin { - coinjoin.reset_unused_count(); - } - } -} - -/// Combined statistics for all gap limits -#[derive(Debug, Clone)] -#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] -#[cfg_attr(feature = "bincode", derive(Encode, Decode))] -pub struct GapLimitManagerStats { - pub external: GapLimitStats, - pub internal: GapLimitStats, - pub coinjoin: Option, - pub discovery_complete: bool, -} - -impl Default for GapLimitManager { - fn default() -> Self { - Self::new_default() - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_gap_limit_basic() { - let mut gap = GapLimit::new(20); - assert_eq!(gap.limit, 20); - assert_eq!(gap.stage, GapLimitStage::Initial); - assert!(!gap.limit_reached); - - // Mark some addresses as generated - for i in 0..20 { - gap.mark_generated(i); - } - assert_eq!(gap.current_unused_count, 20); - assert!(gap.limit_reached); - } - - #[test] - fn test_gap_limit_usage() { - let mut gap = GapLimit::new(5); - - // Generate 10 addresses - for i in 0..10 { - gap.mark_generated(i); - } - - // Mark some as used - gap.mark_used(2); - gap.mark_used(5); - gap.mark_used(7); - - assert_eq!(gap.highest_used_index, Some(7)); - assert_eq!(gap.current_unused_count, 2); // indices 8 and 9 are unused - assert!(!gap.limit_reached); - - // Generate more addresses - for i in 10..13 { - gap.mark_generated(i); - } - - assert_eq!(gap.current_unused_count, 5); // indices 8-12 are unused - assert!(gap.limit_reached); - } - - #[test] - fn test_gap_limit_extension() { - let mut gap = GapLimit::new(5); - gap.stage = GapLimitStage::Initial; - - for i in 0..5 { - gap.mark_generated(i); - } - gap.mark_used(3); - - assert!(gap.needs_extension()); - - gap.extend(10); - assert_eq!(gap.limit, 10); - assert_eq!(gap.stage, GapLimitStage::Extended); - assert!(!gap.limit_reached); - } - - #[test] - fn test_gap_limit_manager() { - let mut manager = GapLimitManager::new(20, 10, Some(5)); - - assert!(manager.needs_generation()); - assert!(!manager.is_discovery_complete()); - - // Mark external as complete - manager.external.current_unused_count = 20; - manager.external.update_limit_reached(); - - // Mark internal as complete - manager.internal.current_unused_count = 10; - manager.internal.update_limit_reached(); - - // Mark coinjoin as complete - if let Some(ref mut coinjoin) = manager.coinjoin { - coinjoin.current_unused_count = 5; - coinjoin.update_limit_reached(); - } - - assert!(manager.is_discovery_complete()); - } - - #[test] - fn test_addresses_to_generate() { - let mut gap = GapLimit::new(5); - - // Initially should generate up to limit - assert_eq!(gap.addresses_to_generate(), 5); - - // After generating 5 - for i in 0..5 { - gap.mark_generated(i); - } - assert_eq!(gap.addresses_to_generate(), 0); - - // After using one - gap.mark_used(2); - // target = 2 + 5 + 1 = 8, highest_generated = 4, so need 8 - 4 = 4 more - assert_eq!(gap.addresses_to_generate(), 4); // Need to generate 5, 6, 7, 8 to maintain gap - } -} diff --git a/key-wallet/src/lib.rs b/key-wallet/src/lib.rs index 248f81530..f52555766 100644 --- a/key-wallet/src/lib.rs +++ b/key-wallet/src/lib.rs @@ -47,7 +47,6 @@ pub use dashcore::{Address, AddressType}; pub use derivation::{DerivationPathBuilder, DerivationStrategy, KeyDerivation}; pub use dip9::{DerivationPathReference, DerivationPathType}; pub use error::{Error, Result}; -pub use gap_limit::{GapLimit, GapLimitManager, GapLimitStage}; pub use managed_account::address_pool::{AddressInfo, AddressPool, KeySource}; pub use managed_account::managed_account_type::ManagedAccountType; pub use managed_account::managed_platform_account::ManagedPlatformAccount; From 6147e3d432e0ef260018f6e91c8b3e867b676279 Mon Sep 17 00:00:00 2001 From: Borja Castellano Date: Wed, 11 Nov 2026 06:22:02 -0800 Subject: [PATCH 13/22] refactor(key-wallet)!: move gap limit constants into `address_pool` With the `GapLimit` tracker gone, `gap_limit` only held the default gap limits and `MAX_GAP_LIMIT`, which `AddressPool` uses. The constants move to `managed_account::address_pool` and the `gap_limit` module is removed. --- .../filters/coinjoin_gap_discovery_tests.rs | 2 +- .../tests/dashd_sync/tests_transaction.rs | 2 +- key-wallet-manager/src/process_block.rs | 2 +- key-wallet/AGENTS.md | 3 +- key-wallet/src/gap_limit.rs | 43 --------------- key-wallet/src/lib.rs | 1 - .../src/managed_account/address_pool.rs | 54 +++++++++++++++++-- .../managed_account_collection.rs | 2 +- .../managed_account/managed_account_type.rs | 2 +- .../transaction_checking/wallet_checker.rs | 2 +- 10 files changed, 56 insertions(+), 57 deletions(-) delete mode 100644 key-wallet/src/gap_limit.rs diff --git a/dash-spv/src/sync/filters/coinjoin_gap_discovery_tests.rs b/dash-spv/src/sync/filters/coinjoin_gap_discovery_tests.rs index 99a0f8cfd..6946d1ed1 100644 --- a/dash-spv/src/sync/filters/coinjoin_gap_discovery_tests.rs +++ b/dash-spv/src/sync/filters/coinjoin_gap_discovery_tests.rs @@ -51,7 +51,7 @@ use dashcore::{ Address, Block, BlockHash, Network, OutPoint, Transaction, TxIn, TxOut, Txid, Witness, }; use key_wallet::account::ManagedAccountTrait; -use key_wallet::gap_limit::DEFAULT_COINJOIN_GAP_LIMIT; +use key_wallet::managed_account::address_pool::DEFAULT_COINJOIN_GAP_LIMIT; use key_wallet::managed_account::address_pool::{AddressPool, AddressPoolType}; use key_wallet::wallet::initialization::WalletAccountCreationOptions; use key_wallet::wallet::managed_wallet_info::ManagedWalletInfo; diff --git a/dash-spv/tests/dashd_sync/tests_transaction.rs b/dash-spv/tests/dashd_sync/tests_transaction.rs index 4184d9c68..5f3b76794 100644 --- a/dash-spv/tests/dashd_sync/tests_transaction.rs +++ b/dash-spv/tests/dashd_sync/tests_transaction.rs @@ -14,7 +14,7 @@ use dash_spv::test_utils::{create_test_wallet, TestChain}; use dashcore::PublicKey; use key_wallet::account::ManagedAccountTrait; use key_wallet::bip32::{ChildNumber, ExtendedPrivKey}; -use key_wallet::gap_limit::DEFAULT_EXTERNAL_GAP_LIMIT; +use key_wallet::managed_account::address_pool::DEFAULT_EXTERNAL_GAP_LIMIT; use key_wallet::mnemonic::Mnemonic; use key_wallet::wallet::balance::WalletCoreBalance; use key_wallet::wallet::initialization::WalletAccountCreationOptions; diff --git a/key-wallet-manager/src/process_block.rs b/key-wallet-manager/src/process_block.rs index 3996146cb..62e84c935 100644 --- a/key-wallet-manager/src/process_block.rs +++ b/key-wallet-manager/src/process_block.rs @@ -729,8 +729,8 @@ mod tests { }; 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::managed_account::address_pool::DEFAULT_COINJOIN_GAP_LIMIT; use key_wallet::mnemonic::Language; use key_wallet::wallet::initialization::WalletAccountCreationOptions; use key_wallet::wallet::managed_wallet_info::transaction_building::AccountTypePreference; diff --git a/key-wallet/AGENTS.md b/key-wallet/AGENTS.md index ef904cc6e..3c2eb80fc 100644 --- a/key-wallet/AGENTS.md +++ b/key-wallet/AGENTS.md @@ -8,10 +8,9 @@ This crate handles key material. Correctness comes before performance, and priva - `wallet/`: `Wallet` and its construction, backup and restore. `wallet/managed_wallet_info/` holds `ManagedWalletInfo` plus coin selection, fees and transaction building. - `account/`: `Account`, `AccountType` and `AccountCollection`, with the BLS and EdDSA variants. -- `managed_account/`: the mutable account state and `AddressPool`. +- `managed_account/`: the mutable account state, and `AddressPool` with the default gap limits and `MAX_GAP_LIMIT`. - `transaction_checking/`: `TransactionRouter` and the `WalletTransactionChecker` trait that decides which transactions belong to the wallet. - `bip32.rs`, `dip9.rs`, `derivation*.rs`, `mnemonic.rs`, `seed.rs`: key derivation and the DIP-9 path constants. -- `gap_limit.rs`: the default gap limits and `MAX_GAP_LIMIT`. - `src/tests/`: crate-level tests grouped by topic. `src/test_utils/`: helpers behind the `test-utils` feature. ## Invariants diff --git a/key-wallet/src/gap_limit.rs b/key-wallet/src/gap_limit.rs deleted file mode 100644 index e75e6ce1e..000000000 --- a/key-wallet/src/gap_limit.rs +++ /dev/null @@ -1,43 +0,0 @@ -/// Standard gap limit for external addresses (BIP44 recommendation) -pub const DEFAULT_EXTERNAL_GAP_LIMIT: u32 = 30; - -/// Standard gap limit for internal (change) addresses -pub const DEFAULT_INTERNAL_GAP_LIMIT: u32 = 30; - -/// Standard gap limit for CoinJoin addresses. -/// -/// Set to match dashj's `DeterministicKeyChain` lookahead -/// (`DEFAULT_LOOKAHEAD_SIZE = 100`), which is the effective discovery window -/// dashj-core (the reference wallet, `org.dashj:dashj-core:22.x`) watches for -/// CoinJoin keychains. Address discovery here is dynamic — the pool watches -/// `highest_used + gap_limit` addresses — so this bounds the largest run of -/// UNUSED CoinJoin addresses the wallet can bridge during a filter/rescan -/// before discovery stalls. -/// -/// The previous value of 30 starved heavy mixers: DIP-9 CoinJoin mixing -/// sprays denominations across many sequential addresses, and a run wider -/// than 30 consecutive unused addresses caused the SDK to stop discovering — -/// it then missed both the txs that CREATED far-index UTXOs and the txs that -/// SPENT nearer ones, leaving a persistent balance mismatch vs dashj that -/// survived a clean re-creation + full rescan (dashpay/platform#4074, -/// dashpay/dash-wallet#1507). 100 restores parity with dashj's window so the -/// SDK discovers every CoinJoin tx dashj does. -/// -/// Cost is modest: the CoinJoin account watches two pools (external + -/// internal), so this pre-derives and filter-matches ~200 CoinJoin addresses -/// per account instead of ~60. BIP158 filter matching is a set intersection, -/// so the extra scripts add negligible per-block work; the derivation is a -/// one-time keychain expansion. -pub const DEFAULT_COINJOIN_GAP_LIMIT: u32 = 100; - -/// Standard gap limit for special purpose keys (identity, provider keys) -pub const DEFAULT_SPECIAL_GAP_LIMIT: u32 = 5; - -/// Gap limit for DashPay contact chains, as recommended by DIP-15. -pub const DEFAULT_DASHPAY_GAP_LIMIT: u32 = 10; - -/// Gap limit for DIP-17 platform payment addresses -pub const DIP17_GAP_LIMIT: u32 = 20; - -/// Maximum gap limit to prevent excessive address generation -pub const MAX_GAP_LIMIT: u32 = 1000; diff --git a/key-wallet/src/lib.rs b/key-wallet/src/lib.rs index f52555766..65639953d 100644 --- a/key-wallet/src/lib.rs +++ b/key-wallet/src/lib.rs @@ -29,7 +29,6 @@ pub mod derivation_bls_bip32; pub mod derivation_slip10; pub mod dip9; pub mod error; -pub mod gap_limit; pub mod managed_account; pub mod mnemonic; pub mod seed; diff --git a/key-wallet/src/managed_account/address_pool.rs b/key-wallet/src/managed_account/address_pool.rs index 1b73c0a07..133bf0bd2 100644 --- a/key-wallet/src/managed_account/address_pool.rs +++ b/key-wallet/src/managed_account/address_pool.rs @@ -18,6 +18,50 @@ use dashcore::eddsa::{EddsaPkBytes, EddsaPkHash}; use dashcore::hashes::hash160; use dashcore::{Address, AddressType, ScriptBuf}; +/// Standard gap limit for external addresses (BIP44 recommendation) +pub const DEFAULT_EXTERNAL_GAP_LIMIT: u32 = 30; + +/// Standard gap limit for internal (change) addresses +pub const DEFAULT_INTERNAL_GAP_LIMIT: u32 = 30; + +/// Standard gap limit for CoinJoin addresses. +/// +/// Set to match dashj's `DeterministicKeyChain` lookahead +/// (`DEFAULT_LOOKAHEAD_SIZE = 100`), which is the effective discovery window +/// dashj-core (the reference wallet, `org.dashj:dashj-core:22.x`) watches for +/// CoinJoin keychains. Address discovery here is dynamic — the pool watches +/// `highest_used + gap_limit` addresses — so this bounds the largest run of +/// UNUSED CoinJoin addresses the wallet can bridge during a filter/rescan +/// before discovery stalls. +/// +/// The previous value of 30 starved heavy mixers: DIP-9 CoinJoin mixing +/// sprays denominations across many sequential addresses, and a run wider +/// than 30 consecutive unused addresses caused the SDK to stop discovering — +/// it then missed both the txs that CREATED far-index UTXOs and the txs that +/// SPENT nearer ones, leaving a persistent balance mismatch vs dashj that +/// survived a clean re-creation + full rescan (dashpay/platform#4074, +/// dashpay/dash-wallet#1507). 100 restores parity with dashj's window so the +/// SDK discovers every CoinJoin tx dashj does. +/// +/// Cost is modest: the CoinJoin account watches two pools (external + +/// internal), so this pre-derives and filter-matches ~200 CoinJoin addresses +/// per account instead of ~60. BIP158 filter matching is a set intersection, +/// so the extra scripts add negligible per-block work; the derivation is a +/// one-time keychain expansion. +pub const DEFAULT_COINJOIN_GAP_LIMIT: u32 = 100; + +/// Standard gap limit for special purpose keys (identity, provider keys) +pub const DEFAULT_SPECIAL_GAP_LIMIT: u32 = 5; + +/// Gap limit for DashPay contact chains, as recommended by DIP-15. +pub const DEFAULT_DASHPAY_GAP_LIMIT: u32 = 10; + +/// Gap limit for DIP-17 platform payment addresses +pub const DIP17_GAP_LIMIT: u32 = 20; + +/// Maximum gap limit to prevent excessive address generation +pub const MAX_GAP_LIMIT: u32 = 1000; + /// Types of public keys used in the address pool #[derive(Debug, Clone, PartialEq, Eq)] #[cfg_attr(feature = "bincode", derive(Encode, Decode))] @@ -696,14 +740,14 @@ impl AddressPool { /// Raise the gap limit and generate the addresses the wider limit now requires. /// - /// The new limit is capped at [`crate::gap_limit::MAX_GAP_LIMIT`]. Returns the freshly + /// The new limit is capped at [`MAX_GAP_LIMIT`]. Returns the freshly /// generated [`AddressInfo`] entries pub fn set_gap_limit( &mut self, gap_limit: u32, key_source: &KeySource, ) -> Result> { - self.gap_limit = gap_limit.clamp(1, crate::gap_limit::MAX_GAP_LIMIT); + self.gap_limit = gap_limit.clamp(1, MAX_GAP_LIMIT); self.maintain_gap_limit(key_source) } @@ -846,9 +890,9 @@ mod tests { assert_eq!(pool.highest_generated(), Some(19)); // The new limit is capped at MAX_GAP_LIMIT. - pool.set_gap_limit(crate::gap_limit::MAX_GAP_LIMIT + 500, &key_source).unwrap(); - assert_eq!(pool.gap_limit, crate::gap_limit::MAX_GAP_LIMIT); - assert_eq!(pool.addresses.len(), crate::gap_limit::MAX_GAP_LIMIT as usize); + pool.set_gap_limit(MAX_GAP_LIMIT + 500, &key_source).unwrap(); + assert_eq!(pool.gap_limit, MAX_GAP_LIMIT); + assert_eq!(pool.addresses.len(), MAX_GAP_LIMIT as usize); } #[test] diff --git a/key-wallet/src/managed_account/managed_account_collection.rs b/key-wallet/src/managed_account/managed_account_collection.rs index 51742dd52..f30fabef6 100644 --- a/key-wallet/src/managed_account/managed_account_collection.rs +++ b/key-wallet/src/managed_account/managed_account_collection.rs @@ -9,8 +9,8 @@ use dashcore::blockdata::transaction::OutPoint; use dashcore::Transaction; use crate::account::account_collection::{DashpayAccountKey, PlatformPaymentAccountKey}; -use crate::gap_limit::DIP17_GAP_LIMIT; use crate::managed_account::address_pool::AddressPoolType; +use crate::managed_account::address_pool::DIP17_GAP_LIMIT; use crate::managed_account::managed_account_ref::{ ManagedAccountRef, ManagedAccountRefMut, OwnedManagedCoreAccount, }; diff --git a/key-wallet/src/managed_account/managed_account_type.rs b/key-wallet/src/managed_account/managed_account_type.rs index 81dc6ed7e..2f4a82aed 100644 --- a/key-wallet/src/managed_account/managed_account_type.rs +++ b/key-wallet/src/managed_account/managed_account_type.rs @@ -1,6 +1,6 @@ use crate::account::account_collection::{DashpayContactIdentityId, DashpayOurUserIdentityId}; use crate::account::StandardAccountType; -use crate::gap_limit::{ +use crate::managed_account::address_pool::{ DEFAULT_COINJOIN_GAP_LIMIT, DEFAULT_DASHPAY_GAP_LIMIT, DEFAULT_EXTERNAL_GAP_LIMIT, DEFAULT_INTERNAL_GAP_LIMIT, DEFAULT_SPECIAL_GAP_LIMIT, DIP17_GAP_LIMIT, }; diff --git a/key-wallet/src/transaction_checking/wallet_checker.rs b/key-wallet/src/transaction_checking/wallet_checker.rs index 9c84705ca..25a539fdd 100644 --- a/key-wallet/src/transaction_checking/wallet_checker.rs +++ b/key-wallet/src/transaction_checking/wallet_checker.rs @@ -513,7 +513,7 @@ mod tests { use super::*; use crate::account::account_type::StandardAccountType; use crate::account::{ECDSAAddressDerivation, TransactionRecord}; - use crate::gap_limit::{ + use crate::managed_account::address_pool::{ DEFAULT_COINJOIN_GAP_LIMIT, DEFAULT_EXTERNAL_GAP_LIMIT, DEFAULT_INTERNAL_GAP_LIMIT, }; use crate::managed_account::managed_account_trait::ManagedAccountTrait; From fd68794afe94e9440a52bbaad2e14da800ade393 Mon Sep 17 00:00:00 2001 From: Borja Castellano Date: Wed, 11 Nov 2026 06:22:35 -0800 Subject: [PATCH 14/22] docs(key-wallet): remove stale implementation notes `IMPLEMENTATION_SUMMARY.md` and `src/missing_tests.md` described modules and gaps that no longer exist, such as `gap_limit.rs`. --- key-wallet/IMPLEMENTATION_SUMMARY.md | 200 --------------------------- key-wallet/src/missing_tests.md | 120 ---------------- 2 files changed, 320 deletions(-) delete mode 100644 key-wallet/IMPLEMENTATION_SUMMARY.md delete mode 100644 key-wallet/src/missing_tests.md diff --git a/key-wallet/IMPLEMENTATION_SUMMARY.md b/key-wallet/IMPLEMENTATION_SUMMARY.md deleted file mode 100644 index 21db987b4..000000000 --- a/key-wallet/IMPLEMENTATION_SUMMARY.md +++ /dev/null @@ -1,200 +0,0 @@ -# Key-Wallet Implementation Summary - -## Completed Features - -### 1. Core Wallet Management (`wallet/`) - -- ✅ Complete wallet lifecycle management -- ✅ Multiple account support (BIP44) -- ✅ Mnemonic generation and recovery (BIP39) -- ✅ HD key derivation (BIP32) -- ✅ Watch-only wallet support -- ✅ Wallet metadata and configuration -- ✅ Balance tracking per account - -### 2. Account Management (`account/`) - -- ✅ Standard accounts for regular transactions -- ✅ CoinJoin accounts for privacy -- ✅ Special purpose accounts (identity, masternode, DashPay, Platform) -- ✅ Account metadata (labels, colors, tags) -- ✅ Balance tracking per account -- ✅ Address usage tracking -- ✅ Account serialization support - -### 3. Address Pool Management (`managed_account/address_pool.rs`) - -- ✅ Dynamic address generation -- ✅ Usage tracking and marking -- ✅ Address discovery scanning -- ✅ Support for external/internal chains -- ✅ Address labeling and metadata -- ✅ Performance optimizations - -### 4. Gap Limit Management (`gap_limit.rs`) - -- ✅ BIP44-compliant gap limit tracking -- ✅ Staged gap limit expansion -- ✅ Separate limits for external/internal/CoinJoin -- ✅ Address discovery optimization - -### 5. Transaction Management (`wallet/managed_wallet_info/`) - -- ✅ Transaction building from scratch -- ✅ UTXO selection strategies: - - Smallest first (minimize UTXO set) - - Largest first (minimize fees) - - Branch and bound (optimal) - - Random (privacy) - - Manual (coin control) -- ✅ Fee calculation and estimation -- ✅ Change address management -- ✅ Transaction signing (P2PKH) -- ✅ UTXO tracking and management -- ✅ Asset lock/unlock transactions (Dash-specific) - -### 6. Address Support - -- ✅ P2PKH address generation -- ✅ P2SH address support -- ✅ Network-specific encoding -- ✅ Script pubkey generation -- ✅ Base58check encoding/decoding - -### 7. Mnemonic Support (`mnemonic.rs`) - -- ✅ Multi-language support (10 languages) -- ✅ 12/15/18/21/24 word phrases -- ✅ Passphrase support -- ✅ Seed generation -- ✅ Entropy validation - -## Architecture Highlights - -### Modular Design - -- Each component is self-contained -- Clear separation of concerns -- Minimal dependencies between modules - -### No-std Support - -- Core functionality works without std library -- Suitable for embedded systems -- Optional std features for convenience - -### Security Features - -- Private keys never exposed in Debug output -- Secure random number generation -- Memory-safe implementations - -### Extensibility - -- Trait-based design for key derivation -- Pluggable UTXO selection strategies (`CoinSelector`, `SelectionStrategy`) -- Extensible address types - -## Testing Coverage - -### Unit Tests - -- ✅ Account creation and management -- ✅ Address generation and usage -- ✅ Gap limit tracking -- ✅ Mnemonic generation -- ✅ UTXO selection -- ✅ Fee calculation -- ✅ Transaction creation - -### Integration Points - -- Compatible with `dashcore_hashes` -- Uses secp256k1 for cryptography -- Integrates with bip39 crate - -## Future Enhancements - -### High Priority - -1. **Advanced UTXO Management** - - UTXO rollback for reorgs - - Coin control UI support - -2. **Persistence Layer** - - Database integration - - Encrypted storage - -### Medium Priority - -1. **Performance Optimizations** - - Batch address generation - - Parallel derivation - - Address caching - -2. **Additional Tests** - - Property-based testing - - Fuzzing - - Benchmark tests - -3. **Documentation** - - API documentation - - Usage examples - - Integration guides - -### Low Priority - -1. **Extended Features** - - Hardware wallet integration - - Multi-party computation - - Threshold signatures - -## Usage Example - -```rust -use key_wallet::{Wallet, Network}; -use key_wallet::mnemonic::{Mnemonic, Language}; -use key_wallet::account::{AccountType, StandardAccountType}; - -// Create a new wallet from mnemonic -let mnemonic = Mnemonic::generate(24, Language::English)?; -let wallet = Wallet::from_mnemonic(mnemonic, None, Network::Testnet)?; - -// Create a standard BIP44 account -let account = wallet.create_account( - Network::Testnet, - AccountType::Standard { - index: 0, - standard_account_type: StandardAccountType::BIP44Account, - }, -)?; - -// Wrap in a managed account for mutable operations -let mut managed = ManagedCoreFundsAccount::from_account(&account); - -// Get a receive address -let address = managed.next_receive_address(Some(&account.account_xpub), true)?; -``` - -## Dependencies - -### Required - -- `dashcore_hashes` - Cryptographic hashes -- `secp256k1` - Elliptic curve cryptography -- `bip39` - Mnemonic phrase support -- `base58ck` - Base58check encoding - -### Optional - -- `serde` - Serialization support -- `bincode` - Binary encoding -- `getrandom` - Random number generation - -## License - -This implementation follows Dash Core licensing (CC0-1.0). - -## Status - -The key-wallet library is feature-complete for HD wallet functionality with comprehensive account management, address generation, gap limit tracking, and transaction creation. All modules compile successfully and include unit tests. diff --git a/key-wallet/src/missing_tests.md b/key-wallet/src/missing_tests.md deleted file mode 100644 index 4db77754d..000000000 --- a/key-wallet/src/missing_tests.md +++ /dev/null @@ -1,120 +0,0 @@ -# Missing Tests in key-wallet (Low-Level Components) - -## 1. Wallet Module Tests (`wallet.rs`) - -### Core Wallet Operations -- ✓ `test_wallet_creation_from_mnemonic` - Create wallet from mnemonic -- ✓ `test_wallet_creation_empty` - Create empty wallet -- ✓ `test_wallet_recovery_from_seed` - Full wallet recovery process -- `test_wallet_import_export` - Import/export wallet data -- `test_wallet_encryption` - Encrypt/decrypt wallet data -- `test_wallet_backup_restore` - Complete backup/restore cycle -- `test_wallet_migration` - Migrate wallet versions - -### Single Wallet Account Management -- ✓ `test_account_creation` - Create individual accounts -- ✓ `test_account_retrieval` - Get accounts by index -- ✓ `test_account_metadata` - Account metadata management - -## 2. Account Module Tests (`account.rs`) - -### Gap Limit Scenarios -- `test_gap_limit_with_sparse_usage` - Addresses used with gaps -- `test_gap_limit_recovery` - Recovery with various gap patterns -- `test_gap_limit_edge_cases` - Boundary conditions -- `test_dynamic_gap_limit_adjustment` - Adjust gap limit on the fly - -### Address Management -- `test_address_labeling` - Add/update address labels -- `test_address_metadata` - Custom metadata management -- `test_address_sorting_bip69` - BIP69 deterministic sorting -- `test_address_reuse_detection` - Detect address reuse -- `test_change_address_optimization` - Optimize change address selection - -### CoinJoin/PrivateSend -- `test_coinjoin_rounds` - Track CoinJoin rounds -- `test_coinjoin_denomination` - Denomination management -- `test_coinjoin_balance_tracking` - Separate CoinJoin balance -- `test_coinjoin_address_isolation` - Address pool isolation - -## 3. Address Pool Module Tests (`address_pool.rs`) - -### Performance Tests -- `test_large_pool_generation` - Generate 10000+ addresses -- `test_pool_pruning` - Prune unused addresses -- `test_concurrent_address_generation` - Thread-safe generation -- `test_address_caching` - Cache performance - -### Edge Cases -- `test_pool_reset` - Reset pool state -- `test_pool_migration` - Migrate pool format -- `test_corrupted_pool_recovery` - Recover from corruption - -## 4. BIP32/BIP39 Tests (`bip32.rs`, `mnemonic.rs`) - -### Language Support -- ✓ `test_mnemonic_japanese` - Japanese wordlist -- ✓ `test_mnemonic_french` - French wordlist -- ✓ `test_mnemonic_spanish` - Spanish wordlist -- ✓ `test_mnemonic_italian` - Italian wordlist -- ✓ `test_mnemonic_korean` - Korean wordlist -- ✓ `test_mnemonic_czech` - Czech wordlist -- ✓ `test_mnemonic_portuguese` - Portuguese wordlist -- ✓ `test_mnemonic_chinese_simplified` - Chinese simplified -- ✓ `test_mnemonic_chinese_traditional` - Chinese traditional - -### Mnemonic Recovery -- `test_mnemonic_missing_word_recovery` - Find missing word -- `test_mnemonic_typo_correction` - Correct typos -- `test_mnemonic_similar_words` - Handle similar words -- `test_partial_mnemonic_recovery` - Recover from partial phrase - -### Special Derivation Paths -- ✓ `test_identity_authentication_derivation` - Identity auth keys -- ✓ `test_identity_registration_derivation` - Identity registration -- ✓ `test_identity_topup_derivation` - Identity top-up -- ✓ `test_provider_voting_derivation` - Provider voting keys -- ✓ `test_provider_operator_derivation` - Provider operator keys -- ✓ `test_dashpay_derivation` - DashPay contact keys - -## 5. Key Management Tests (`derivation.rs`) - -### Key Operations -- ✓ `test_key_signing_deterministic` - Deterministic signatures -- `test_key_signing_compact` - Compact signatures -- ✓ `test_key_verification` - Signature verification -- ✓ `test_key_recovery_from_signature` - Recover pubkey from sig - -## 6. Low-Level Cryptographic Tests - -### Key Operations (stays in key-wallet) -- ✓ `test_key_signing_deterministic` - Deterministic signatures (already implemented above) -- `test_key_signing_compact` - Compact signatures -- ✓ `test_key_verification` - Signature verification (already implemented above) -- ✓ `test_key_recovery_from_signature` - Recover pubkey from sig (already implemented above) - -### Address Generation -- `test_address_generation_accuracy` - Verify address generation -- `test_address_network_validation` - Network-specific addresses - -## Files to Add Tests To (key-wallet only): - -1. **wallet.rs** - Add 8-10 core wallet operation tests -2. **account.rs** - Add 10-12 account management tests -3. **address_pool.rs** - Add 5-7 pool optimization tests -4. **gap_limit.rs** - Add 3-4 edge case tests -5. **mnemonic.rs** - Add 9 language tests + 4 recovery tests -6. **derivation.rs** - Add 8-10 key operation tests - -## Test Data Requirements - -- Test vectors from BIP32/BIP39/BIP44 specifications -- DashSync test vectors for compatibility -- Language-specific mnemonic test cases -- Key derivation test vectors - -## Priority Order - -1. **High Priority**: Mnemonic handling, key derivation, address generation -2. **Medium Priority**: Multi-language mnemonics, gap limit edge cases -3. **Low Priority**: Performance tests, CoinJoin, migration tests From 17f1b9cce175662bb853c855c416307a73207385 Mon Sep 17 00:00:00 2001 From: Borja Castellano Date: Wed, 11 Nov 2026 06:28:20 -0800 Subject: [PATCH 15/22] refactor(key-wallet): derive serde for `PublicKeyType` The hand-written `Serialize` and `Deserialize` impls went through a mirror enum with the same variants, which is what the derive generates. The JSON output is unchanged. --- .../src/managed_account/address_pool.rs | 47 +------------------ 1 file changed, 2 insertions(+), 45 deletions(-) diff --git a/key-wallet/src/managed_account/address_pool.rs b/key-wallet/src/managed_account/address_pool.rs index 133bf0bd2..d490cc2d3 100644 --- a/key-wallet/src/managed_account/address_pool.rs +++ b/key-wallet/src/managed_account/address_pool.rs @@ -64,10 +64,11 @@ pub const MAX_GAP_LIMIT: u32 = 1000; /// Types of public keys used in the address pool #[derive(Debug, Clone, PartialEq, Eq)] +#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] #[cfg_attr(feature = "bincode", derive(Encode, Decode))] #[allow(clippy::upper_case_acronyms)] pub enum PublicKeyType { - /// ECDSA public key (standard Bitcoin/Dash addresses) - stored as `Vec` for serialization + /// ECDSA public key (standard Bitcoin/Dash addresses) ECDSA(Vec), /// EdDSA public key (Ed25519, used in some Platform operations) EdDSA(Vec), @@ -90,50 +91,6 @@ pub enum AddressPoolType { AbsentHardened, } -#[cfg(feature = "serde")] -impl Serialize for PublicKeyType { - fn serialize(&self, serializer: S) -> core::result::Result - where - S: serde::Serializer, - { - #[derive(Serialize)] - #[allow(clippy::upper_case_acronyms)] - enum PublicKeyTypeSer<'a> { - ECDSA(&'a Vec), - EdDSA(&'a Vec), - BLS(&'a Vec), - } - - match self { - PublicKeyType::ECDSA(bytes) => PublicKeyTypeSer::ECDSA(bytes).serialize(serializer), - PublicKeyType::EdDSA(bytes) => PublicKeyTypeSer::EdDSA(bytes).serialize(serializer), - PublicKeyType::BLS(bytes) => PublicKeyTypeSer::BLS(bytes).serialize(serializer), - } - } -} - -#[cfg(feature = "serde")] -impl<'de> Deserialize<'de> for PublicKeyType { - fn deserialize(deserializer: D) -> core::result::Result - where - D: serde::Deserializer<'de>, - { - #[derive(Deserialize)] - #[allow(clippy::upper_case_acronyms)] - enum PublicKeyTypeDe { - ECDSA(Vec), - EdDSA(Vec), - BLS(Vec), - } - - match PublicKeyTypeDe::deserialize(deserializer)? { - PublicKeyTypeDe::ECDSA(bytes) => Ok(PublicKeyType::ECDSA(bytes)), - PublicKeyTypeDe::EdDSA(bytes) => Ok(PublicKeyType::EdDSA(bytes)), - PublicKeyTypeDe::BLS(bytes) => Ok(PublicKeyType::BLS(bytes)), - } - } -} - /// Key source for address derivation #[derive(Debug, Clone)] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] From 7ea1be5dfd64b6cab4117e1811815b692299d6c7 Mon Sep 17 00:00:00 2001 From: Borja Castellano Date: Wed, 11 Nov 2026 07:01:40 -0800 Subject: [PATCH 16/22] fix(key-wallet): clamp pool gap limit and saturate derive counts `AddressPool::new_without_generation` accepted any gap limit, and a gap limit of 0 underflowed in `maintain_gap_limit`. The constructors now clamp it to `1..=MAX_GAP_LIMIT` like `set_gap_limit` does. `generate_addresses` and `generate_up_to` saturate the caller-supplied count and index, so an out-of-range request fails derivation instead of overflowing. --- key-wallet/src/managed_account/address_pool.rs | 10 +++++----- key-wallet/src/tests/edge_case_tests.rs | 7 +++---- 2 files changed, 8 insertions(+), 9 deletions(-) diff --git a/key-wallet/src/managed_account/address_pool.rs b/key-wallet/src/managed_account/address_pool.rs index d490cc2d3..44557c81c 100644 --- a/key-wallet/src/managed_account/address_pool.rs +++ b/key-wallet/src/managed_account/address_pool.rs @@ -353,13 +353,13 @@ impl AddressPool { // Generate addresses up to the gap limit if we have a key source if key_source.can_derive() { - pool.generate_addresses(gap_limit, key_source)?; + pool.generate_addresses(pool.gap_limit, key_source)?; } Ok(pool) } - /// Create a new address pool without generating any addresses + /// Create a new address pool without generating any addresses. The gap limit is clamped to `1..=MAX_GAP_LIMIT`. pub fn new_without_generation( base_path: DerivationPath, pool_type: AddressPoolType, @@ -369,7 +369,7 @@ impl AddressPool { Self { base_path, pool_type, - gap_limit, + gap_limit: gap_limit.clamp(1, MAX_GAP_LIMIT), network, addresses: BTreeMap::new(), address_index: HashMap::new(), @@ -416,7 +416,7 @@ impl AddressPool { key_source: &KeySource, ) -> Result> { let start_index = self.next_index_to_derive(); - (start_index..start_index + count) + (start_index..start_index.saturating_add(count)) .map(|index| self.generate_address_at_index(index, key_source)) .collect() } @@ -428,7 +428,7 @@ impl AddressPool { key_source: &KeySource, ) -> Result> { let next = self.next_index_to_derive(); - self.generate_addresses((index + 1).saturating_sub(next), key_source) + self.generate_addresses(index.saturating_add(1).saturating_sub(next), key_source) } /// Generate a specific address at an index diff --git a/key-wallet/src/tests/edge_case_tests.rs b/key-wallet/src/tests/edge_case_tests.rs index 52dc497bc..b0118d6de 100644 --- a/key-wallet/src/tests/edge_case_tests.rs +++ b/key-wallet/src/tests/edge_case_tests.rs @@ -155,7 +155,7 @@ fn test_duplicate_account_handling() { #[test] fn test_extreme_gap_limit() { use crate::bip32::DerivationPath; - use crate::managed_account::address_pool::{AddressPool, AddressPoolType}; + use crate::managed_account::address_pool::{AddressPool, AddressPoolType, MAX_GAP_LIMIT}; // Test with extremely large gap limit let base_path = DerivationPath::from(vec![ChildNumber::from(0)]); @@ -166,8 +166,7 @@ fn test_extreme_gap_limit() { Network::Testnet, ); - // Should handle large gap limits without issues - assert_eq!(pool.gap_limit, 10000); + assert_eq!(pool.gap_limit, MAX_GAP_LIMIT); // Test with zero gap limit let zero_gap_pool = AddressPool::new_without_generation( @@ -176,7 +175,7 @@ fn test_extreme_gap_limit() { 0, Network::Testnet, ); - assert_eq!(zero_gap_pool.gap_limit, 0); + assert_eq!(zero_gap_pool.gap_limit, 1); } #[test] From 0458fdd0f3d7941d04e0a3c55f5b5d63f909bd28 Mon Sep 17 00:00:00 2001 From: Borja Castellano Date: Wed, 11 Nov 2026 07:23:50 -0800 Subject: [PATCH 17/22] refactor(key-wallet)!: make `AddressPool` fields private Callers wrote the pool maps and fields directly to restore entries, unmark addresses and reserve a chosen address, which could leave `addresses` and its lookup maps out of sync. The fields are private. `base_path`, `pool_type`, `gap_limit`, `network` and `addresses` are read through getters, and `insert`, `unmark_used` and `reserve` cover the writes callers made by hand. `insert` rejects indexes outside the BIP32 normal range. Closes #1252. --- .../filters/coinjoin_gap_discovery_tests.rs | 4 +- key-wallet-manager/src/event_tests.rs | 4 +- key-wallet-manager/src/process_block.rs | 2 +- key-wallet-manager/src/test_utils/coinjoin.rs | 4 +- .../src/managed_account/address_pool.rs | 93 +++++++++--- .../managed_account/managed_account_trait.rs | 2 +- .../managed_core_funds_account.rs | 4 +- .../managed_platform_account.rs | 4 +- .../tests/dashpay_contact_gap_limit_tests.rs | 2 +- key-wallet/src/tests/edge_case_tests.rs | 4 +- key-wallet/src/tests/restore_utxos_tests.rs | 8 +- .../special_transaction_matching_tests.rs | 2 +- .../transaction_checking/account_checker.rs | 141 ++++++++---------- .../transaction_checking/wallet_checker.rs | 2 +- 14 files changed, 159 insertions(+), 117 deletions(-) diff --git a/dash-spv/src/sync/filters/coinjoin_gap_discovery_tests.rs b/dash-spv/src/sync/filters/coinjoin_gap_discovery_tests.rs index 6946d1ed1..d2be7a0e9 100644 --- a/dash-spv/src/sync/filters/coinjoin_gap_discovery_tests.rs +++ b/dash-spv/src/sync/filters/coinjoin_gap_discovery_tests.rs @@ -111,7 +111,7 @@ fn coinjoin_external_pool(info: &ManagedWalletInfo) -> &AddressPool { .managed_account_type() .address_pools() .into_iter() - .find(|p| p.pool_type == AddressPoolType::External) + .find(|p| p.pool_type() == AddressPoolType::External) .expect("CoinJoin External pool") } @@ -127,7 +127,7 @@ async fn coinjoin_pool_state( ( pool.highest_used(), pool.highest_generated(), - pool.addresses.values().filter(|info| info.is_used()).count(), + pool.addresses().values().filter(|info| info.is_used()).count(), ) } diff --git a/key-wallet-manager/src/event_tests.rs b/key-wallet-manager/src/event_tests.rs index fd6b1c936..9029ee38c 100644 --- a/key-wallet-manager/src/event_tests.rs +++ b/key-wallet-manager/src/event_tests.rs @@ -1440,7 +1440,7 @@ fn pool_state( _ => panic!("unexpected pool type {:?}", pool_type), }; let highest = pool.highest_generated().expect("pre-generated pool must have addresses"); - let gap_limit = pool.gap_limit; + let gap_limit = pool.gap_limit(); let addr = pool.address_at_index(highest).expect("highest index must exist"); (highest, gap_limit, addr) } @@ -1536,7 +1536,7 @@ async fn test_mempool_tx_to_highest_external_carries_addresses_derived() { // Pin the persistence-critical payload against the wallet's // own AddressInfo for the same index. let stored = external_pool_after - .addresses + .addresses() .get(&derived.derivation_index) .unwrap_or_else(|| panic!("pool missing index {}", derived.derivation_index)); assert_eq!( diff --git a/key-wallet-manager/src/process_block.rs b/key-wallet-manager/src/process_block.rs index 62e84c935..665f7d275 100644 --- a/key-wallet-manager/src/process_block.rs +++ b/key-wallet-manager/src/process_block.rs @@ -1051,7 +1051,7 @@ mod tests { .managed_account_type() .address_pools() .iter() - .find(|p| p.pool_type == AddressPoolType::External) + .find(|p| p.pool_type() == AddressPoolType::External) .and_then(|p| p.highest_used()); assert_eq!(pool_used, Some(gap + 8)); diff --git a/key-wallet-manager/src/test_utils/coinjoin.rs b/key-wallet-manager/src/test_utils/coinjoin.rs index 474ce5eb2..9b98bdc55 100644 --- a/key-wallet-manager/src/test_utils/coinjoin.rs +++ b/key-wallet-manager/src/test_utils/coinjoin.rs @@ -19,10 +19,10 @@ pub fn coinjoin_external_addresses( let pools = account.managed_account_type().address_pools(); let live = pools .iter() - .find(|p| p.pool_type == AddressPoolType::External) + .find(|p| p.pool_type() == AddressPoolType::External) .expect("CoinJoin External pool"); let pool = AddressPool::new( - live.base_path.clone(), + live.base_path().clone(), AddressPoolType::External, count, wallet.network, diff --git a/key-wallet/src/managed_account/address_pool.rs b/key-wallet/src/managed_account/address_pool.rs index 44557c81c..d49573f09 100644 --- a/key-wallet/src/managed_account/address_pool.rs +++ b/key-wallet/src/managed_account/address_pool.rs @@ -325,19 +325,19 @@ impl AddressInfo { #[cfg_attr(feature = "bincode", derive(Encode, Decode))] pub struct AddressPool { /// Base derivation path for this pool - pub base_path: DerivationPath, + base_path: DerivationPath, /// Type of address pool (external, internal, or absent) - pub pool_type: AddressPoolType, + pool_type: AddressPoolType, /// Gap limit for this pool - pub gap_limit: u32, + gap_limit: u32, /// Network for address generation - pub network: Network, + network: Network, /// All addresses in the pool - pub addresses: BTreeMap, + addresses: BTreeMap, /// Reverse lookup: address -> index - pub address_index: HashMap, + address_index: HashMap, /// Reverse lookup: script pubkey -> index - pub script_pubkey_index: HashMap, + script_pubkey_index: HashMap, } impl AddressPool { @@ -377,6 +377,27 @@ impl AddressPool { } } + pub fn base_path(&self) -> &DerivationPath { + &self.base_path + } + + pub fn pool_type(&self) -> AddressPoolType { + self.pool_type + } + + pub fn gap_limit(&self) -> u32 { + self.gap_limit + } + + pub fn network(&self) -> Network { + self.network + } + + /// Returns every address in the pool, keyed by derivation index. + pub fn addresses(&self) -> &BTreeMap { + &self.addresses + } + /// Check if this is an internal (change) address pool pub fn is_internal(&self) -> bool { self.pool_type == AddressPoolType::Internal @@ -517,13 +538,25 @@ impl AddressPool { } }; let info = AddressInfo::new(address.clone(), index, full_path, Some(public_key_type)); - self.addresses.insert(index, info.clone()); - self.address_index.insert(address, index); - self.script_pubkey_index.insert(info.script_pubkey.clone(), index); - + self.insert(info.clone())?; Ok(info) } + /// Stores `info` at its index, replacing any entry already there. + /// + /// Use it to restore persisted entries or keys that cannot be derived from the key source. + pub fn insert(&mut self, info: AddressInfo) -> Result<()> { + ChildNumber::from_normal_idx(info.index).map_err(Error::Bip32)?; + if let Some(old) = self.addresses.remove(&info.index) { + self.address_index.remove(&old.address); + self.script_pubkey_index.remove(&old.script_pubkey); + } + self.address_index.insert(info.address.clone(), info.index); + self.script_pubkey_index.insert(info.script_pubkey.clone(), info.index); + self.addresses.insert(info.index, info); + Ok(()) + } + /// Get the next unused address pub fn next_unused(&mut self, key_source: &KeySource) -> Result
{ self.next_unused_with_info(key_source).map(|info| info.address) @@ -565,15 +598,29 @@ impl AddressPool { key_source: &KeySource, now: u64, ) -> Result
{ - let index = self.next_unused_with_info(key_source)?.index; - // A lookup miss would hand out an unreserved address, so fail instead. - let info = self.addresses.get_mut(&index).ok_or_else(|| { - Error::InvalidState(format!("next_unused_and_reserve: index {} not stored", index)) - })?; + let address = self.next_unused_with_info(key_source)?.address; + // A failed reservation would hand out an unreserved address, so fail instead. + if !self.reserve(&address, now) { + return Err(Error::InvalidState(format!( + "next_unused_and_reserve: {} not reservable", + address + ))); + } + Ok(address) + } + + /// Reserves `address` with timestamp `now` if it is available. Returns whether it did. + pub fn reserve(&mut self, address: &Address, now: u64) -> bool { + let Some(info) = self.address_info_mut(address) else { + return false; + }; + if !info.is_available() { + return false; + } info.state = AddressState::Reserved { at: now, }; - Ok(info.address.clone()) + true } /// Release a reservation, returning the address to the available pool. @@ -646,6 +693,18 @@ impl AddressPool { true } + /// Returns a used address to the available state. Returns whether it was used. + pub fn unmark_used(&mut self, address: &Address) -> bool { + let Some(info) = self.address_info_mut(address) else { + return false; + }; + if !info.is_used() { + return false; + } + info.state = AddressState::Available; + true + } + /// Get all addresses in the pool pub fn all_addresses(&self) -> Vec
{ self.addresses.values().map(|info| info.address.clone()).collect() diff --git a/key-wallet/src/managed_account/managed_account_trait.rs b/key-wallet/src/managed_account/managed_account_trait.rs index e6b8ab898..26292713f 100644 --- a/key-wallet/src/managed_account/managed_account_trait.rs +++ b/key-wallet/src/managed_account/managed_account_trait.rs @@ -516,7 +516,7 @@ pub trait ManagedAccountTrait { | ManagedAccountType::PlatformPayment { addresses, .. - } => Some(addresses.gap_limit), + } => Some(addresses.gap_limit()), } } } 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 2c9a020df..103974c45 100644 --- a/key-wallet/src/managed_account/managed_core_funds_account.rs +++ b/key-wallet/src/managed_account/managed_core_funds_account.rs @@ -1530,7 +1530,7 @@ impl ManagedCoreFundsAccount { ManagedAccountType::Standard { external_addresses, .. - } => Some(external_addresses.gap_limit), + } => Some(external_addresses.gap_limit()), _ => None, } } @@ -1541,7 +1541,7 @@ impl ManagedCoreFundsAccount { ManagedAccountType::Standard { internal_addresses, .. - } => Some(internal_addresses.gap_limit), + } => Some(internal_addresses.gap_limit()), _ => None, } } diff --git a/key-wallet/src/managed_account/managed_platform_account.rs b/key-wallet/src/managed_account/managed_platform_account.rs index 401c74b7f..fd06c6a2d 100644 --- a/key-wallet/src/managed_account/managed_platform_account.rs +++ b/key-wallet/src/managed_account/managed_platform_account.rs @@ -56,7 +56,7 @@ impl ManagedPlatformAccount { /// /// The network is derived from the AddressPool to ensure consistency. pub fn new(account: u32, key_class: u32, addresses: AddressPool, is_watch_only: bool) -> Self { - let network = addresses.network; + let network = addresses.network(); Self { account, key_class, @@ -288,7 +288,7 @@ impl ManagedPlatformAccount { /// Get the gap limit for the address pool pub fn gap_limit(&self) -> u32 { - self.addresses.gap_limit + self.addresses.gap_limit() } } diff --git a/key-wallet/src/tests/dashpay_contact_gap_limit_tests.rs b/key-wallet/src/tests/dashpay_contact_gap_limit_tests.rs index 62e9fa367..4c87148fc 100644 --- a/key-wallet/src/tests/dashpay_contact_gap_limit_tests.rs +++ b/key-wallet/src/tests/dashpay_contact_gap_limit_tests.rs @@ -78,7 +78,7 @@ async fn contact_payments_extend_the_contact_pool() { "external" }; let pool = contact_pool(&ctx, contact); - let gap = pool.gap_limit; + let gap = pool.gap_limit(); let last_built = pool.address_at_index(gap - 1).expect("construction fills the window"); assert!( pool.address_at_index(gap).is_none(), diff --git a/key-wallet/src/tests/edge_case_tests.rs b/key-wallet/src/tests/edge_case_tests.rs index b0118d6de..b01cc893a 100644 --- a/key-wallet/src/tests/edge_case_tests.rs +++ b/key-wallet/src/tests/edge_case_tests.rs @@ -166,7 +166,7 @@ fn test_extreme_gap_limit() { Network::Testnet, ); - assert_eq!(pool.gap_limit, MAX_GAP_LIMIT); + assert_eq!(pool.gap_limit(), MAX_GAP_LIMIT); // Test with zero gap limit let zero_gap_pool = AddressPool::new_without_generation( @@ -175,7 +175,7 @@ fn test_extreme_gap_limit() { 0, Network::Testnet, ); - assert_eq!(zero_gap_pool.gap_limit, 1); + assert_eq!(zero_gap_pool.gap_limit(), 1); } #[test] diff --git a/key-wallet/src/tests/restore_utxos_tests.rs b/key-wallet/src/tests/restore_utxos_tests.rs index 26589cb34..8aaa43ec3 100644 --- a/key-wallet/src/tests/restore_utxos_tests.rs +++ b/key-wallet/src/tests/restore_utxos_tests.rs @@ -96,7 +96,7 @@ fn held_by_any_funds_account(ctx: &TestWalletContext, outpoint: &OutPoint) -> bo #[tokio::test] async fn a_coinjoin_utxo_past_the_stored_window_restores_into_coinjoin() { let mut ctx = TestWalletContext::new_random(); - let gap = coinjoin_pool(&ctx).gap_limit; + let gap = coinjoin_pool(&ctx).gap_limit(); assert_eq!(coinjoin_pool(&ctx).highest_generated(), Some(gap - 1)); let (_, inside) = funded(&coinjoin_address(&ctx, gap - 1), 0, 100_000); let (beyond_tx, beyond) = funded(&coinjoin_address(&ctx, 2 * gap - 1), 1, 200_000); @@ -129,7 +129,7 @@ async fn a_coinjoin_utxo_past_the_stored_window_restores_into_coinjoin() { fn a_utxo_matching_no_account_comes_back(ours_but_unreachable: bool) { let mut ctx = TestWalletContext::new_random(); let address = if ours_but_unreachable { - let gap = coinjoin_pool(&ctx).gap_limit; + let gap = coinjoin_pool(&ctx).gap_limit(); coinjoin_address(&ctx, 2 * gap) } else { TestWalletContext::new_random().receive_address @@ -174,7 +174,7 @@ fn a_receiving_pool_that_reaches_a_script_in_a_later_pass_claims_it() { let (receiving, reverse_external) = befriend_both_ways(&mut ctx); let pool = receiving_pool(&ctx); let last = pool.highest_generated().expect("an initial window"); - let far_index = last + pool.gap_limit; + let far_index = last + pool.gap_limit(); let mut far_pool = pool.clone(); far_pool .generate_up_to(far_index, &ctx.wallet.key_source_for_account(receiving)) @@ -208,7 +208,7 @@ fn a_receiving_pool_that_reaches_a_script_in_a_later_pass_claims_it() { #[test] fn a_pool_restored_as_used_is_extended_before_matching() { let mut ctx = TestWalletContext::new_random(); - let gap = coinjoin_pool(&ctx).gap_limit; + let gap = coinjoin_pool(&ctx).gap_limit(); let used = coinjoin_address(&ctx, gap - 1); ctx.managed_wallet.accounts.coinjoin_accounts.get_mut(&0).unwrap().mark_address_used(&used); let (_, utxo) = funded(&coinjoin_address(&ctx, 2 * gap - 1), 0, 100_000); diff --git a/key-wallet/src/tests/special_transaction_matching_tests.rs b/key-wallet/src/tests/special_transaction_matching_tests.rs index 2b9ef4e2c..632b08dc0 100644 --- a/key-wallet/src/tests/special_transaction_matching_tests.rs +++ b/key-wallet/src/tests/special_transaction_matching_tests.rs @@ -481,7 +481,7 @@ async fn provider_registration_extends_operator_key_gap_limit() { match account.managed_account_type() { ManagedAccountType::ProviderOperatorKeys { addresses, - } => (addresses.highest_generated(), addresses.highest_used(), addresses.gap_limit), + } => (addresses.highest_generated(), addresses.highest_used(), addresses.gap_limit()), _ => unreachable!("operator account holds an operator pool"), } }; diff --git a/key-wallet/src/transaction_checking/account_checker.rs b/key-wallet/src/transaction_checking/account_checker.rs index 7b484c219..34be21d06 100644 --- a/key-wallet/src/transaction_checking/account_checker.rs +++ b/key-wallet/src/transaction_checking/account_checker.rs @@ -991,20 +991,17 @@ impl ManagedCoreFundsAccount { }; // Check if voting_key_hash matches any of our address hashes - for (address, &addr_index) in &addresses.address_index { - if let Payload::PubkeyHash(addr_hash) = address.payload() { + for address_info in addresses.addresses().values() { + if let Payload::PubkeyHash(addr_hash) = address_info.address.payload() { if addr_hash == voting_key_hash { - // Get the address info - if let Some(address_info) = addresses.addresses.get(&addr_index) { - return Some(AccountMatch { - account_type_match: CoreAccountTypeMatch::ProviderVotingKeys { - involved_addresses: vec![address_info.clone()], - }, - received: 0, - sent: 0, - received_for_credit_conversion: 0, - }); - } + return Some(AccountMatch { + account_type_match: CoreAccountTypeMatch::ProviderVotingKeys { + involved_addresses: vec![address_info.clone()], + }, + received: 0, + sent: 0, + received_for_credit_conversion: 0, + }); } } } @@ -1031,20 +1028,17 @@ impl ManagedCoreFundsAccount { }; // Check if owner_key_hash matches any of our address hashes - for (address, &addr_index) in &addresses.address_index { - if let Payload::PubkeyHash(addr_hash) = address.payload() { + for address_info in addresses.addresses().values() { + if let Payload::PubkeyHash(addr_hash) = address_info.address.payload() { if addr_hash == owner_key_hash { - // Get the address info - if let Some(address_info) = addresses.addresses.get(&addr_index) { - return Some(AccountMatch { - account_type_match: CoreAccountTypeMatch::ProviderOwnerKeys { - involved_addresses: vec![address_info.clone()], - }, - received: 0, - sent: 0, - received_for_credit_conversion: 0, - }); - } + return Some(AccountMatch { + account_type_match: CoreAccountTypeMatch::ProviderOwnerKeys { + involved_addresses: vec![address_info.clone()], + }, + received: 0, + sent: 0, + received_for_credit_conversion: 0, + }); } } } @@ -1076,7 +1070,7 @@ impl ManagedCoreFundsAccount { }; // Check if operator_public_key matches any of our BLS public keys - for address_info in addresses.addresses.values() { + for address_info in addresses.addresses().values() { if let Some(PublicKeyType::BLS(bls_key)) = &address_info.public_key { let operator_key_bytes: &[u8; 48] = operator_public_key.as_ref(); if bls_key.len() == 48 && bls_key.as_slice() == operator_key_bytes { @@ -1119,21 +1113,17 @@ impl ManagedCoreFundsAccount { _ => return None, }; - for (address, &addr_index) in &addresses.address_index { - if let Payload::PubkeyHash(addr_hash) = address.payload() { + for address_info in addresses.addresses().values() { + if let Payload::PubkeyHash(addr_hash) = address_info.address.payload() { if *addr_hash.as_byte_array() == platform_node_id.to_byte_array() { - // Get the address info - if let Some(address_info) = addresses.addresses.get(&addr_index) { - return Some(AccountMatch { - account_type_match: - CoreAccountTypeMatch::ProviderPlatformKeys { - involved_addresses: vec![address_info.clone()], - }, - received: 0, - sent: 0, - received_for_credit_conversion: 0, - }); - } + return Some(AccountMatch { + account_type_match: CoreAccountTypeMatch::ProviderPlatformKeys { + involved_addresses: vec![address_info.clone()], + }, + received: 0, + sent: 0, + received_for_credit_conversion: 0, + }); } } } @@ -1453,19 +1443,17 @@ impl crate::managed_account::ManagedCoreKeysAccount { _ => return None, }; - for (address, &addr_index) in &addresses.address_index { - if let Payload::PubkeyHash(addr_hash) = address.payload() { + for address_info in addresses.addresses().values() { + if let Payload::PubkeyHash(addr_hash) = address_info.address.payload() { if addr_hash == voting_key_hash { - if let Some(address_info) = addresses.addresses.get(&addr_index) { - return Some(AccountMatch { - account_type_match: CoreAccountTypeMatch::ProviderVotingKeys { - involved_addresses: vec![address_info.clone()], - }, - received: 0, - sent: 0, - received_for_credit_conversion: 0, - }); - } + return Some(AccountMatch { + account_type_match: CoreAccountTypeMatch::ProviderVotingKeys { + involved_addresses: vec![address_info.clone()], + }, + received: 0, + sent: 0, + received_for_credit_conversion: 0, + }); } } } @@ -1489,19 +1477,17 @@ impl crate::managed_account::ManagedCoreKeysAccount { _ => return None, }; - for (address, &addr_index) in &addresses.address_index { - if let Payload::PubkeyHash(addr_hash) = address.payload() { + for address_info in addresses.addresses().values() { + if let Payload::PubkeyHash(addr_hash) = address_info.address.payload() { if addr_hash == owner_key_hash { - if let Some(address_info) = addresses.addresses.get(&addr_index) { - return Some(AccountMatch { - account_type_match: CoreAccountTypeMatch::ProviderOwnerKeys { - involved_addresses: vec![address_info.clone()], - }, - received: 0, - sent: 0, - received_for_credit_conversion: 0, - }); - } + return Some(AccountMatch { + account_type_match: CoreAccountTypeMatch::ProviderOwnerKeys { + involved_addresses: vec![address_info.clone()], + }, + received: 0, + sent: 0, + received_for_credit_conversion: 0, + }); } } } @@ -1531,7 +1517,7 @@ impl crate::managed_account::ManagedCoreKeysAccount { _ => return None, }; - for address_info in addresses.addresses.values() { + for address_info in addresses.addresses().values() { if let Some(PublicKeyType::BLS(bls_key)) = &address_info.public_key { let operator_key_bytes: &[u8; 48] = operator_public_key.as_ref(); if bls_key.len() == 48 && bls_key.as_slice() == operator_key_bytes { @@ -1574,20 +1560,17 @@ impl crate::managed_account::ManagedCoreKeysAccount { _ => return None, }; - for (address, &addr_index) in &addresses.address_index { - if let Payload::PubkeyHash(addr_hash) = address.payload() { + for address_info in addresses.addresses().values() { + if let Payload::PubkeyHash(addr_hash) = address_info.address.payload() { if *addr_hash.as_byte_array() == platform_node_id.to_byte_array() { - if let Some(address_info) = addresses.addresses.get(&addr_index) { - return Some(AccountMatch { - account_type_match: - CoreAccountTypeMatch::ProviderPlatformKeys { - involved_addresses: vec![address_info.clone()], - }, - received: 0, - sent: 0, - received_for_credit_conversion: 0, - }); - } + return Some(AccountMatch { + account_type_match: CoreAccountTypeMatch::ProviderPlatformKeys { + involved_addresses: vec![address_info.clone()], + }, + received: 0, + sent: 0, + received_for_credit_conversion: 0, + }); } } } diff --git a/key-wallet/src/transaction_checking/wallet_checker.rs b/key-wallet/src/transaction_checking/wallet_checker.rs index 25a539fdd..63add8787 100644 --- a/key-wallet/src/transaction_checking/wallet_checker.rs +++ b/key-wallet/src/transaction_checking/wallet_checker.rs @@ -166,7 +166,7 @@ impl ManagedWalletInfo { } let rev_before = new_addresses.len(); for pool in account.managed_account_type_mut().address_pools_mut() { - let pool_type = pool.pool_type; + let pool_type = pool.pool_type(); match pool.maintain_gap_limit(&key_source) { Ok(infos) => { new_addresses.extend(infos.into_iter().map(|info| DerivedAddressInfo { From 0b1dfb6b53b841b9f20bbf3fe5bac19be898924c Mon Sep 17 00:00:00 2001 From: Borja Castellano Date: Wed, 11 Nov 2026 09:10:48 -0800 Subject: [PATCH 18/22] test(key-wallet): drop vacuous change address assertion The assertion compared two `next_change_address` calls, which return the same address whether or not `add_funding` derived one, so it could never fail. --- .../src/wallet/managed_wallet_info/transaction_builder.rs | 6 ------ 1 file changed, 6 deletions(-) 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 b1acf2a36..c3ed1ed2c 100644 --- a/key-wallet/src/wallet/managed_wallet_info/transaction_builder.rs +++ b/key-wallet/src/wallet/managed_wallet_info/transaction_builder.rs @@ -1979,12 +1979,6 @@ mod tests { Some(&explicit), "funding must not override a change address the caller chose" ); - // Nor may it burn a pool address to derive one it then discards. - let mut control = ManagedCoreFundsAccount::dummy_bip44(); - assert_eq!( - funds.next_change_address(Some(&account.account_xpub)).expect("change address"), - control.next_change_address(Some(&account.account_xpub)).expect("change address"), - ); } #[test] From a4c8be89af14f3fc7d680447e5e3a46a95719297 Mon Sep 17 00:00:00 2001 From: Borja Castellano Date: Wed, 11 Nov 2026 09:10:49 -0800 Subject: [PATCH 19/22] fix(key-wallet): reject duplicates in `AddressPool::insert` `insert` accepted an address or script already stored at another index, which left the reverse maps pointing at one entry while the pool held two. It now returns an error, and `address_info_mut` is private so callers cannot rewrite entry identity. Adds tests for `insert`, `reserve` refusals and `unmark_used`, and trims the `DEFAULT_COINJOIN_GAP_LIMIT` doc. --- .../src/managed_account/address_pool.rs | 96 ++++++++++++++----- 1 file changed, 72 insertions(+), 24 deletions(-) diff --git a/key-wallet/src/managed_account/address_pool.rs b/key-wallet/src/managed_account/address_pool.rs index d49573f09..410e737f0 100644 --- a/key-wallet/src/managed_account/address_pool.rs +++ b/key-wallet/src/managed_account/address_pool.rs @@ -26,28 +26,8 @@ pub const DEFAULT_INTERNAL_GAP_LIMIT: u32 = 30; /// Standard gap limit for CoinJoin addresses. /// -/// Set to match dashj's `DeterministicKeyChain` lookahead -/// (`DEFAULT_LOOKAHEAD_SIZE = 100`), which is the effective discovery window -/// dashj-core (the reference wallet, `org.dashj:dashj-core:22.x`) watches for -/// CoinJoin keychains. Address discovery here is dynamic — the pool watches -/// `highest_used + gap_limit` addresses — so this bounds the largest run of -/// UNUSED CoinJoin addresses the wallet can bridge during a filter/rescan -/// before discovery stalls. -/// -/// The previous value of 30 starved heavy mixers: DIP-9 CoinJoin mixing -/// sprays denominations across many sequential addresses, and a run wider -/// than 30 consecutive unused addresses caused the SDK to stop discovering — -/// it then missed both the txs that CREATED far-index UTXOs and the txs that -/// SPENT nearer ones, leaving a persistent balance mismatch vs dashj that -/// survived a clean re-creation + full rescan (dashpay/platform#4074, -/// dashpay/dash-wallet#1507). 100 restores parity with dashj's window so the -/// SDK discovers every CoinJoin tx dashj does. -/// -/// Cost is modest: the CoinJoin account watches two pools (external + -/// internal), so this pre-derives and filter-matches ~200 CoinJoin addresses -/// per account instead of ~60. BIP158 filter matching is a set intersection, -/// so the extra scripts add negligible per-block work; the derivation is a -/// one-time keychain expansion. +/// Matches dashj's `DEFAULT_LOOKAHEAD_SIZE` of 100, so discovery bridges the long runs of unused +/// addresses that CoinJoin mixing leaves. pub const DEFAULT_COINJOIN_GAP_LIMIT: u32 = 100; /// Standard gap limit for special purpose keys (identity, provider keys) @@ -545,8 +525,18 @@ impl AddressPool { /// Stores `info` at its index, replacing any entry already there. /// /// Use it to restore persisted entries or keys that cannot be derived from the key source. + /// Fails if the address or script is already stored at another index. pub fn insert(&mut self, info: AddressInfo) -> Result<()> { ChildNumber::from_normal_idx(info.index).map_err(Error::Bip32)?; + let elsewhere = |index: Option<&u32>| index.is_some_and(|&i| i != info.index); + if elsewhere(self.address_index.get(&info.address)) + || elsewhere(self.script_pubkey_index.get(&info.script_pubkey)) + { + return Err(Error::InvalidParameter(format!( + "{} is already stored at another index", + info.address + ))); + } if let Some(old) = self.addresses.remove(&info.index) { self.address_index.remove(&old.address); self.script_pubkey_index.remove(&old.script_pubkey); @@ -734,8 +724,7 @@ impl AddressPool { self.address_index.get(address).and_then(|&index| self.addresses.get(&index)) } - /// Get mutable address info by address - pub fn address_info_mut(&mut self, address: &Address) -> Option<&mut AddressInfo> { + fn address_info_mut(&mut self, address: &Address) -> Option<&mut AddressInfo> { self.address_index.get(address).and_then(|index| self.addresses.get_mut(index)) } @@ -859,6 +848,65 @@ mod tests { assert_eq!(pool.highest_used(), Some(0)); assert!(pool.address_info(first_addr).unwrap().is_used()); + + assert!(pool.unmark_used(first_addr)); + assert!(!pool.unmark_used(first_addr)); + assert_eq!(pool.highest_used(), None); + assert!(pool.address_info(first_addr).unwrap().is_available()); + } + + #[test] + fn test_reserve_refuses_unavailable_addresses() { + let base_path = DerivationPath::from(vec![ChildNumber::from_normal_idx(0).unwrap()]); + let key_source = test_key_source(); + let mut pool = AddressPool::new( + base_path, + AddressPoolType::External, + 5, + Network::Testnet, + &key_source, + ) + .unwrap(); + let addresses = pool.all_addresses(); + + assert!(pool.reserve(&addresses[0], 100)); + assert!(!pool.reserve(&addresses[0], 100)); + assert_eq!(pool.address_info(&addresses[0]).unwrap().reserved_at(), Some(100)); + + pool.mark_used(&addresses[1]); + assert!(!pool.reserve(&addresses[1], 100)); + + assert!(!pool.reserve(&Address::dummy(Network::Testnet, 99), 100)); + } + + #[test] + fn test_insert_replaces_index_and_rejects_duplicates() { + let base_path = DerivationPath::from(vec![ChildNumber::from_normal_idx(0).unwrap()]); + let key_source = test_key_source(); + let mut pool = AddressPool::new( + base_path, + AddressPoolType::External, + 5, + Network::Testnet, + &key_source, + ) + .unwrap(); + let first = pool.address_info(&pool.address_at_index(0).unwrap()).unwrap().clone(); + let mut second = pool.address_info(&pool.address_at_index(1).unwrap()).unwrap().clone(); + + let mut moved = first.clone(); + moved.index = 1; + assert!(pool.insert(moved).is_err()); + assert_eq!(pool.address_index(&first.address), Some(0)); + + let replaced = second.address.clone(); + let replacement = Address::dummy(Network::Testnet, 99); + second.script_pubkey = replacement.script_pubkey(); + second.address = replacement.clone(); + pool.insert(second).unwrap(); + assert_eq!(pool.address_index(&replacement), Some(1)); + assert!(!pool.contains_address(&replaced)); + assert_eq!(pool.all_addresses().len(), 5); } #[test] From 749029c5d6adf8335041a6bd93c855be533ede15 Mon Sep 17 00:00:00 2001 From: Borja Castellano Date: Thu, 12 Nov 2026 03:03:04 -0800 Subject: [PATCH 20/22] refactor(key-wallet)!: drop `script_pubkey` from `AddressInfo` The field duplicated `address.script_pubkey()`, and `AddressPool::insert` accepted an entry whose script did not match its address, so the address and script lookups could disagree. The pool now computes the script from the address. --- key-wallet-manager/src/events.rs | 2 -- key-wallet-manager/src/process_block.rs | 2 +- key-wallet/src/managed_account/address_pool.rs | 18 +++++++----------- 3 files changed, 8 insertions(+), 14 deletions(-) diff --git a/key-wallet-manager/src/events.rs b/key-wallet-manager/src/events.rs index eb35954eb..1ed983d09 100644 --- a/key-wallet-manager/src/events.rs +++ b/key-wallet-manager/src/events.rs @@ -660,7 +660,6 @@ mod project_derived_addresses_tests { let pubkey = dashcore::PublicKey::from_slice(&TEST_PUBKEY_G).expect("generator point is valid"); let address = dashcore::Address::p2pkh(&pubkey, key_wallet::Network::Testnet); - let script_pubkey = address.script_pubkey(); let path = DerivationPath::from(vec![ ChildNumber::from_normal_idx(0).unwrap(), ChildNumber::from_normal_idx(index).unwrap(), @@ -675,7 +674,6 @@ mod project_derived_addresses_tests { pool_type, info: AddressInfo { address, - script_pubkey, public_key: Some(PublicKeyType::ECDSA(pubkey_bytes)), index, path, diff --git a/key-wallet-manager/src/process_block.rs b/key-wallet-manager/src/process_block.rs index 665f7d275..6865b9d6a 100644 --- a/key-wallet-manager/src/process_block.rs +++ b/key-wallet-manager/src/process_block.rs @@ -101,7 +101,7 @@ impl WalletInterface for WalletM for (wallet_id, derived) in check_result.new_addresses { derived_wallets.insert(wallet_id); let scripts = - derived.iter().map(|d| d.info.script_pubkey.clone()).collect::>(); + derived.iter().map(|d| d.info.address.script_pubkey()).collect::>(); result.new_scripts.entry(wallet_id).or_default().extend(scripts); per_wallet_derived.entry(wallet_id).or_default().extend(derived); } diff --git a/key-wallet/src/managed_account/address_pool.rs b/key-wallet/src/managed_account/address_pool.rs index 410e737f0..f40071c79 100644 --- a/key-wallet/src/managed_account/address_pool.rs +++ b/key-wallet/src/managed_account/address_pool.rs @@ -214,8 +214,6 @@ pub enum AddressState { pub struct AddressInfo { /// The address pub address: Address, - /// The script pubkey for this address - pub script_pubkey: ScriptBuf, /// The public key used to derive this address pub public_key: Option, /// Derivation index @@ -233,10 +231,8 @@ impl AddressInfo { path: DerivationPath, public_key: Option, ) -> Self { - let script_pubkey = address.script_pubkey(); Self { address, - script_pubkey, public_key, index, path, @@ -525,12 +521,13 @@ impl AddressPool { /// Stores `info` at its index, replacing any entry already there. /// /// Use it to restore persisted entries or keys that cannot be derived from the key source. - /// Fails if the address or script is already stored at another index. + /// Fails if the address is already stored at another index. pub fn insert(&mut self, info: AddressInfo) -> Result<()> { ChildNumber::from_normal_idx(info.index).map_err(Error::Bip32)?; + let script_pubkey = info.address.script_pubkey(); let elsewhere = |index: Option<&u32>| index.is_some_and(|&i| i != info.index); if elsewhere(self.address_index.get(&info.address)) - || elsewhere(self.script_pubkey_index.get(&info.script_pubkey)) + || elsewhere(self.script_pubkey_index.get(&script_pubkey)) { return Err(Error::InvalidParameter(format!( "{} is already stored at another index", @@ -539,10 +536,10 @@ impl AddressPool { } if let Some(old) = self.addresses.remove(&info.index) { self.address_index.remove(&old.address); - self.script_pubkey_index.remove(&old.script_pubkey); + self.script_pubkey_index.remove(&old.address.script_pubkey()); } self.address_index.insert(info.address.clone(), info.index); - self.script_pubkey_index.insert(info.script_pubkey.clone(), info.index); + self.script_pubkey_index.insert(script_pubkey, info.index); self.addresses.insert(info.index, info); Ok(()) } @@ -700,9 +697,9 @@ impl AddressPool { self.addresses.values().map(|info| info.address.clone()).collect() } - /// Get cached scriptPubKeys for every address in the pool. + /// Get the scriptPubKeys of every address in the pool. pub(crate) fn all_script_pubkeys(&self) -> Vec { - self.addresses.values().map(|info| info.script_pubkey.clone()).collect() + self.addresses.values().map(|info| info.address.script_pubkey()).collect() } /// Get only available addresses (neither used nor reserved) @@ -901,7 +898,6 @@ mod tests { let replaced = second.address.clone(); let replacement = Address::dummy(Network::Testnet, 99); - second.script_pubkey = replacement.script_pubkey(); second.address = replacement.clone(); pool.insert(second).unwrap(); assert_eq!(pool.address_index(&replacement), Some(1)); From 108e52cdf90d82e40198a4f368300cbafcf79b76 Mon Sep 17 00:00:00 2001 From: Borja Castellano Date: Thu, 12 Nov 2026 03:03:07 -0800 Subject: [PATCH 21/22] docs(key-wallet): fix the `add_funding` change-address note `next_change_address` returns the first available change address without marking or reserving it, so it does not burn a pool address. --- .../src/wallet/managed_wallet_info/transaction_builder.rs | 2 -- 1 file changed, 2 deletions(-) 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 c3ed1ed2c..dbc4f790f 100644 --- a/key-wallet/src/wallet/managed_wallet_info/transaction_builder.rs +++ b/key-wallet/src/wallet/managed_wallet_info/transaction_builder.rs @@ -158,8 +158,6 @@ impl TransactionBuilder { /// /// A change address already set by [`set_change_address`](Self::set_change_address) /// wins: the funding account is only asked for one when the builder has none. - /// Deriving unconditionally would both discard the caller's choice and burn a - /// pool address, since `next_change_address` advances the pool state. pub fn add_funding(self, funds_acc: &mut ManagedCoreFundsAccount, acc: &Account) -> Self { self.fund_from(funds_acc, acc, true) } From 850431fe011a428417fe9a9bea21f942a56568ca Mon Sep 17 00:00:00 2001 From: Borja Castellano Date: Thu, 12 Nov 2026 03:15:56 -0800 Subject: [PATCH 22/22] fix(key-wallet): reject index gaps in `AddressPool::insert` A pool derives new addresses from its highest stored index, so an entry inserted past the next index to derive left the indices in between never derived or watched. `insert` now rejects such an index, except in `AbsentHardened` pools, whose hardened keys cannot be derived from the account xpub and are inserted at any index. --- key-wallet/src/managed_account/address_pool.rs | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/key-wallet/src/managed_account/address_pool.rs b/key-wallet/src/managed_account/address_pool.rs index f40071c79..a6a8d5107 100644 --- a/key-wallet/src/managed_account/address_pool.rs +++ b/key-wallet/src/managed_account/address_pool.rs @@ -521,9 +521,21 @@ impl AddressPool { /// Stores `info` at its index, replacing any entry already there. /// /// Use it to restore persisted entries or keys that cannot be derived from the key source. - /// Fails if the address is already stored at another index. + /// Fails if the address is already stored at another index, or if the index would leave a + /// gap in a pool derived from the account xpub. Such a gap would never be derived or watched. pub fn insert(&mut self, info: AddressInfo) -> Result<()> { ChildNumber::from_normal_idx(info.index).map_err(Error::Bip32)?; + + if self.pool_type != AddressPoolType::AbsentHardened + && info.index > self.next_index_to_derive() + { + return Err(Error::InvalidParameter(format!( + "index {} leaves a gap, the next index to derive is {}", + info.index, + self.next_index_to_derive() + ))); + } + let script_pubkey = info.address.script_pubkey(); let elsewhere = |index: Option<&u32>| index.is_some_and(|&i| i != info.index); if elsewhere(self.address_index.get(&info.address))