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..d2be7a0e9 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; @@ -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") } @@ -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/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/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/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 59321b177..9029ee38c 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 @@ -1439,8 +1439,8 @@ fn pool_state( ) => internal_addresses, _ => 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 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) } @@ -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, @@ -2321,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/src/events.rs b/key-wallet-manager/src/events.rs index 093ab0d9a..1ed983d09 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] = [ @@ -661,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(), @@ -676,17 +674,10 @@ mod project_derived_addresses_tests { pool_type, info: AddressInfo { address, - script_pubkey, public_key: Some(PublicKeyType::ECDSA(pubkey_bytes)), 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-manager/src/process_block.rs b/key-wallet-manager/src/process_block.rs index ed6459010..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); } @@ -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; @@ -1051,8 +1051,8 @@ mod tests { .managed_account_type() .address_pools() .iter() - .find(|p| p.pool_type == AddressPoolType::External) - .and_then(|p| p.highest_used); + .find(|p| p.pool_type() == AddressPoolType::External) + .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-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-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/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/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/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/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/gap_limit.rs b/key-wallet/src/gap_limit.rs deleted file mode 100644 index 546f0a41a..000000000 --- a/key-wallet/src/gap_limit.rs +++ /dev/null @@ -1,474 +0,0 @@ -//! 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; - -/// 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; - -/// 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 3e049ba64..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; @@ -47,8 +46,7 @@ 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, 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 1c897b611..a6a8d5107 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 std::collections::{BTreeMap, HashMap}; 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")] @@ -20,12 +18,37 @@ 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. +/// +/// 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) +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 = "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), @@ -48,50 +71,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))] @@ -132,7 +111,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 +174,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(_)) @@ -243,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 @@ -253,42 +222,21 @@ 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 { - /// 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, - tx_count: 0, - total_received: 0, - total_sent: 0, - balance: 0, - label: None, - metadata: BTreeMap::new(), } } @@ -308,20 +256,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. @@ -340,7 +275,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 +293,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 @@ -373,27 +301,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, - /// 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, + script_pubkey_index: HashMap, } impl AddressPool { @@ -408,14 +328,14 @@ 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) { - pool.generate_addresses(gap_limit, key_source, true)?; + if key_source.can_derive() { + 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, @@ -425,21 +345,33 @@ 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(), script_pubkey_index: HashMap::new(), - used_indices: HashSet::new(), - highest_generated: None, - highest_used: None, - address_type: AddressType::P2pkh, } } - /// Set the address type for new addresses - pub fn set_address_type(&mut self, address_type: AddressType) { - self.address_type = address_type; + 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 @@ -452,29 +384,48 @@ 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) + } + + /// 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) + } + /// 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.saturating_add(count)) + .map(|index| self.generate_address_at_index(index, key_source)) + .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); - self.generate_addresses((index + 1).saturating_sub(next), key_source, true) + pub(crate) fn generate_up_to( + &mut self, + index: u32, + key_source: &KeySource, + ) -> Result> { + let next = self.next_index_to_derive(); + self.generate_addresses(index.saturating_add(1).saturating_sub(next), key_source) } /// Generate a specific address at an index @@ -482,11 +433,10 @@ impl AddressPool { &mut self, 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 @@ -563,72 +513,64 @@ impl AddressPool { (address, PublicKeyType::EdDSA(public_key_bytes)) } }; - 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); - - // Update highest generated - if self.highest_generated.map(|h| index > h).unwrap_or(true) { - self.highest_generated = Some(index); - } - } - - Ok(address) + let info = AddressInfo::new(address.clone(), index, full_path, Some(public_key_type)); + self.insert(info.clone())?; + 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()); - } - } + /// 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, 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() + ))); } - // If NoKeySource, we can't generate new addresses - if matches!(key_source, KeySource::NoKeySource) { - return Err(Error::NoKeySource); + 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(&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.address.script_pubkey()); } + self.address_index.insert(info.address.clone(), info.index); + self.script_pubkey_index.insert(script_pubkey, info.index); + self.addresses.insert(info.index, info); + Ok(()) + } - // 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) + /// 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) } /// Get the next unused address info - pub 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 - 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 - 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)?; - - // 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)? + .pop() + .ok_or_else(|| Error::InvalidState("generate_addresses(1) returned nothing".into())) } /// Reserve and return the next available address. @@ -650,40 +592,34 @@ 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
{ - 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()); - } - } + pub(crate) fn next_unused_and_reserve( + &mut self, + key_source: &KeySource, + now: u64, + ) -> Result
{ + 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) + } - if matches!(key_source, KeySource::NoKeySource) { - return Err(Error::NoKeySource); + /// 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; } - 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 - )) - })?; - debug_assert!(info.is_available()); info.state = AddressState::Reserved { at: now, }; - Ok(address) + true } /// Release a reservation, returning the address to the available pool. @@ -714,7 +650,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; } @@ -737,212 +673,35 @@ 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 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; - } - - // 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; - } - } - - 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; - } - - // 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; - } - } - - 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 - && self.highest_generated.map(|h| current_index <= h).unwrap_or(false) - { - if let Some(info) = self.addresses.get(¤t_index) { - if info.is_available() { - unused.push(info.address.clone()); - } - } - 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); - } - - Ok(unused) - } - /// 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 - } - /// 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 mut found = Vec::new(); + info.mark_used(); - 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)), - }; - } - } + true + } - found + /// 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 @@ -950,18 +709,9 @@ impl AddressPool { 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 { - 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 the scriptPubKeys of every address in the pool. + pub(crate) fn all_script_pubkeys(&self) -> Vec { + self.addresses.values().map(|info| info.address.script_pubkey()).collect() } /// Get only available addresses (neither used nor reserved) @@ -983,18 +733,8 @@ 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> { - if let Some(&index) = self.address_index.get(address) { - self.addresses.get_mut(&index) - } else { - None - } - } - - /// Get address info by index - pub fn info_at_index(&self, index: u32) -> Option<&AddressInfo> { - self.addresses.get(&index) + fn address_info_mut(&mut self, address: &Address) -> Option<&mut AddressInfo> { + self.address_index.get(address).and_then(|index| self.addresses.get_mut(index)) } /// Get the index of an address @@ -1002,73 +742,26 @@ impl AddressPool { 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()); - } - - // 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)?; - } - } - - // 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 + /// 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) } @@ -1080,255 +773,11 @@ 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, }; - - 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) - } - - /// 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() + self.generate_up_to(target, key_source) } } @@ -1363,9 +812,9 @@ 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.highest_generated(), Some(9)); assert_eq!(pool.addresses.len(), 10); } @@ -1383,11 +832,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] @@ -1401,16 +850,71 @@ mod tests { ); let key_source = test_key_source(); - let addresses = pool.generate_addresses(5, &key_source, true).unwrap(); - let first_addr = &addresses[0]; + let addresses = pool.generate_addresses(5, &key_source).unwrap(); + 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()); + + 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 used = pool.used_addresses(); - assert_eq!(used.len(), 1); - assert_eq!(&used[0], first_addr); + let replaced = second.address.clone(); + let replacement = Address::dummy(Network::Testnet, 99); + 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] @@ -1424,12 +928,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 } @@ -1455,12 +959,12 @@ 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(); - 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] @@ -1475,8 +979,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 @@ -1486,7 +990,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); } @@ -1533,7 +1037,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. @@ -1662,67 +1166,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_index_used(0); - - // 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()]); @@ -1740,100 +1183,37 @@ 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_index_used(0); - assert_eq!(pool.highest_used, Some(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 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 - 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(); 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); } - - #[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] == *addr || addresses[5] == *addr || addresses[7] == *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_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_trait.rs b/key-wallet/src/managed_account/managed_account_trait.rs index 21664883d..26292713f 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) @@ -227,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 { @@ -294,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" } @@ -308,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 { @@ -377,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" } @@ -392,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 { @@ -405,14 +311,14 @@ 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 { 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")? @@ -430,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 { @@ -440,14 +345,14 @@ 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 { 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")?, @@ -475,10 +380,10 @@ 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_index_used(info.index); + pool.mark_used(&info.address); let root_ext_priv = root_xpriv.to_extended_priv_key(network); let derived_xpriv = @@ -489,8 +394,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"); } @@ -499,28 +404,16 @@ 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.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) } @@ -529,24 +422,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( @@ -641,14 +516,7 @@ pub trait ManagedAccountTrait { | ManagedAccountType::PlatformPayment { addresses, .. - } => Some(addresses.gap_limit), + } => Some(addresses.gap_limit()), } } } - -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/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/managed_account/managed_core_funds_account.rs b/key-wallet/src/managed_account/managed_core_funds_account.rs index 7eb199933..103974c45 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 { @@ -1452,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>, @@ -1511,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, @@ -1529,89 +1524,13 @@ 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() { ManagedAccountType::Standard { external_addresses, .. - } => Some(external_addresses.gap_limit), + } => Some(external_addresses.gap_limit()), _ => None, } } @@ -1622,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 48c8ba93f..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, @@ -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) } @@ -288,24 +286,9 @@ 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 + self.addresses.gap_limit() } } 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 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/address_pool_tests.rs b/key-wallet/src/tests/address_pool_tests.rs deleted file mode 100644 index 92a61713a..000000000 --- a/key-wallet/src/tests/address_pool_tests.rs +++ /dev/null @@ -1,236 +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_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()]); - 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])); -} - -/// `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" - ); -} 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..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(), @@ -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/edge_case_tests.rs b/key-wallet/src/tests/edge_case_tests.rs index 52dc497bc..b01cc893a 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] 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; 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 e9940ddce..e8059eb70 100644 --- a/key-wallet/src/tests/performance_tests.rs +++ b/key-wallet/src/tests/performance_tests.rs @@ -283,12 +283,13 @@ 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]; 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/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/restore_utxos_tests.rs b/key-wallet/src/tests/restore_utxos_tests.rs index 9450f34e6..8aaa43ec3 100644 --- a/key-wallet/src/tests/restore_utxos_tests.rs +++ b/key-wallet/src/tests/restore_utxos_tests.rs @@ -96,8 +96,8 @@ 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; - assert_eq!(coinjoin_pool(&ctx).highest_generated, Some(gap - 1)); + 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 @@ -173,8 +173,8 @@ 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 far_index = last + pool.gap_limit; + let last = pool.highest_generated().expect("an initial window"); + 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 763487274..632b08dc0 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| { @@ -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"), } }; @@ -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/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/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 bb65e7bfb..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 { @@ -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; @@ -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,8 +3993,9 @@ 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 }) .collect(); let address = &addresses[0]; 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..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 @@ -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)); } @@ -692,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, @@ -732,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 { @@ -1299,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..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) } @@ -225,7 +223,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 } @@ -1979,12 +1977,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), true).expect("change address"), - control.next_change_address(Some(&account.account_xpub), true).expect("change address"), - ); } #[test] 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 {