diff --git a/CHANGELOG.md b/CHANGELOG.md index e8daa982..c76518ce 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,7 @@ ## Unreleased +- `onchain_compose_transaction` keeps the synced watch-only wallet per extended key, script type, network and Electrum URL, so later composes for the same account run an incremental sync that reuses stored transactions instead of a full sync. Every compose still syncs before building PSBTs. Composes with and without a fingerprint share one wallet. Against the staging regtest Electrum with the Trezor emulator account, a compose drops from about 7.5 s to about 3.4 s after the first one. - Add a `wake` module for the wake push gateway: device key, secret and install id generation, a signed registration (`wake_prepare_registration`, `wake_sign_pubky_proof`, `wake_register`), decryption of legacy (v0) and v1 envelopes from any delivered push (`wake_decrypt_push`), and the device routes for acks, presence, topics and unregistering. Grants let a peer wake the device (`wake_create_grant`, `wake_list_grants`, `wake_revoke_grant`), and `wake_send_peer_wake` sends a peer wake with a grant token another device handed over. The v1 wire format is experimental until the apps adopt it. `register_device` and `test_notification` are unchanged. ## 0.5.16 - 2026-09-14 diff --git a/src/modules/onchain/compose.rs b/src/modules/onchain/compose.rs index 40174f31..ca182b9e 100644 --- a/src/modules/onchain/compose.rs +++ b/src/modules/onchain/compose.rs @@ -14,17 +14,17 @@ use bdk::wallet::Wallet; use bdk::FeeRate; use super::errors::AccountInfoError; -use super::implementation::{ - connect_electrum, create_and_sync_wallet, resolve_wallet_setup, run_account_info_blocking, -}; +use super::implementation::{resolve_wallet_setup, run_account_info_blocking, WalletSetup}; use super::types::{CoinSelection, ComposeOutput, ComposeParams, ComposeResult}; +use super::wallet_cache::synced_database_snapshot; /// Compose transactions for multiple fee rates, returning one PSBT per rate. /// -/// Creates a BDK wallet from the extended key, syncs via Electrum, then -/// builds a PSBT for each requested fee rate. The PSBTs include BIP32 -/// derivation paths (when `fingerprint` is provided) and are ready for -/// signing by any PSBT-aware signer without additional network calls. +/// Syncs a cached BDK wallet for the extended key via Electrum (a full sync +/// on first use, incremental afterwards), then builds a PSBT for each +/// requested fee rate. The PSBTs include BIP32 derivation paths (when +/// `fingerprint` is provided) and are ready for signing by any PSBT-aware +/// signer without additional network calls. pub async fn compose_transaction(params: ComposeParams) -> Vec { let num_rates = params.fee_rates.len(); if num_rates == 0 { @@ -49,6 +49,15 @@ async fn compose_inner(params: ComposeParams) -> Result, Acco params.wallet.fingerprint.as_deref(), )?; + // The cached wallet is keyed without the fingerprint, so composes with and + // without one (fee estimates vs. signing) share one synced wallet. + let sync_setup = resolve_wallet_setup( + ¶ms.wallet.extended_key, + params.wallet.network, + params.wallet.account_type, + None, + )?; + validate_outputs(¶ms.outputs, setup.network) .map_err(|e| AccountInfoError::WalletError { error_details: e })?; @@ -66,8 +75,8 @@ async fn compose_inner(params: ComposeParams) -> Result, Acco let coin_selection = params.coin_selection; run_account_info_blocking("compose transaction", move || { - let client = connect_electrum(&electrum_url)?; - let mut wallet = create_and_sync_wallet(&setup, client)?; + let database = synced_database_snapshot(&sync_setup, &electrum_url)?; + let mut wallet = wallet_from_database(&setup, database)?; let mut results = Vec::with_capacity(fee_rates.len()); for rate in &fee_rates { @@ -88,7 +97,25 @@ async fn compose_inner(params: ComposeParams) -> Result, Acco .await } -fn build_psbt( +/// Build a wallet over a synced database copy, using the descriptors that +/// carry the key origin (when a fingerprint was given) so the PSBTs include +/// BIP32 derivations. +pub(crate) fn wallet_from_database( + setup: &WalletSetup, + database: MemoryDatabase, +) -> Result, AccountInfoError> { + Wallet::new( + &setup.external_desc, + Some(&setup.internal_desc), + setup.network, + database, + ) + .map_err(|e| AccountInfoError::WalletError { + error_details: format!("Failed to create wallet: {}", e), + }) +} + +pub(crate) fn build_psbt( wallet: &mut Wallet, outputs: &[ComposeOutput], fee_rate: f32, diff --git a/src/modules/onchain/mod.rs b/src/modules/onchain/mod.rs index 6f766bae..20cba437 100644 --- a/src/modules/onchain/mod.rs +++ b/src/modules/onchain/mod.rs @@ -5,6 +5,7 @@ mod implementation; mod listener; mod psbt; mod types; +mod wallet_cache; pub use compose::compose_transaction; pub use errors::{ diff --git a/src/modules/onchain/tests.rs b/src/modules/onchain/tests.rs index ccb41211..f740a9ea 100644 --- a/src/modules/onchain/tests.rs +++ b/src/modules/onchain/tests.rs @@ -2851,4 +2851,289 @@ mod tests { assert_eq!(DEFAULT_GAP_LIMIT, 20); assert_eq!(crate::get_default_gap_limit(), DEFAULT_GAP_LIMIT); } + + mod compose_wallet_cache { + use crate::modules::onchain::compose::{build_psbt, wallet_from_database}; + use crate::modules::onchain::implementation::{create_wallet, resolve_wallet_setup}; + use crate::modules::onchain::wallet_cache::{ + cached_wallet_count, contains_key, copy_database, insert_empty_for_test, + synced_database_snapshot_with_timeout, WalletCacheKey, MAX_CACHED_WALLETS, + }; + use crate::modules::onchain::{ + compose_transaction, AccountType, ComposeOutput, ComposeParams, ComposeResult, Network, + WalletParams, + }; + use base64::{engine::general_purpose, Engine as _}; + use bdk::bitcoin::absolute::LockTime; + use bdk::bitcoin::psbt::PartiallySignedTransaction; + use bdk::bitcoin::{OutPoint, Sequence, Transaction, TxIn, TxOut, Witness}; + use bdk::database::{BatchOperations, Database, MemoryDatabase, SyncTime}; + use bdk::wallet::AddressIndex; + use bdk::{BlockTime, KeychainKind, LocalUtxo, TransactionDetails}; + + /// A server that accepts connections and never answers. Each call must + /// fail within the socket timeout and release the wallet's lock, so a + /// second call on the same wallet is not blocked behind the first. + #[test] + fn stalled_server_fails_within_timeout_and_releases_wallet() { + let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + let url = format!("tcp://{}", listener.local_addr().unwrap()); + std::thread::spawn(move || { + let mut open = Vec::new(); + for stream in listener.incoming() { + open.push(stream); + } + }); + let sync_setup = setup(None); + + let first = { + let url = url.clone(); + std::thread::spawn(move || { + synced_database_snapshot_with_timeout(&setup(None), &url, 1).map(|_| ()) + }) + }; + std::thread::sleep(std::time::Duration::from_millis(200)); + let started = std::time::Instant::now(); + let second = synced_database_snapshot_with_timeout(&sync_setup, &url, 1); + + assert!(first.join().unwrap().is_err()); + assert!(second.is_err()); + assert!( + started.elapsed() < std::time::Duration::from_secs(10), + "second call waited {:?}", + started.elapsed() + ); + } + + /// Trezor emulator `all all ... all` seed, m/84'/1'/0'. + const TREZOR_ALL_TPUB: &str = "tpubDCZB6sR48s4T5Cr8qHUYSZEFCQMMHRg8AoVKVmvcAP5bRw7ArDKeoNwKAJujV3xCPkBvXH5ejSgbgyN6kREmF7sMd41NdbuHa8n1DZNxSMg"; + const TREZOR_ALL_FINGERPRINT: &str = "5c9e228d"; + const REGTEST_ADDR: &str = "bcrt1qw508d6qejxtdg4y5r3zarvary0c5xw7kygt080"; + + fn setup( + fingerprint: Option<&str>, + ) -> crate::modules::onchain::implementation::WalletSetup { + resolve_wallet_setup( + TREZOR_ALL_TPUB, + Some(Network::Regtest), + Some(AccountType::NativeSegwit), + fingerprint, + ) + .unwrap() + } + + /// A database funded with one confirmed 100k sat UTXO at external index 0, + /// with the internal last index at 3. + fn funded_database() -> MemoryDatabase { + let deriver = create_wallet(&setup(None)).unwrap(); + let mut db = MemoryDatabase::new(); + for i in 0..10 { + let ext = deriver.get_address(AddressIndex::Peek(i)).unwrap().address; + db.set_script_pubkey(&ext.script_pubkey(), KeychainKind::External, i) + .unwrap(); + let int = deriver + .get_internal_address(AddressIndex::Peek(i)) + .unwrap() + .address; + db.set_script_pubkey(&int.script_pubkey(), KeychainKind::Internal, i) + .unwrap(); + } + let receive = deriver.get_address(AddressIndex::Peek(0)).unwrap().address; + let tx = Transaction { + version: 2, + lock_time: LockTime::ZERO, + input: vec![TxIn { + // Not a coinbase, so the output is spendable right away. + previous_output: OutPoint { + txid: "1111111111111111111111111111111111111111111111111111111111111111" + .parse() + .unwrap(), + vout: 0, + }, + script_sig: Default::default(), + sequence: Sequence::MAX, + witness: Witness::new(), + }], + output: vec![TxOut { + value: 100_000, + script_pubkey: receive.script_pubkey(), + }], + }; + let block_time = BlockTime { + height: 100, + timestamp: 1_700_000_000, + }; + db.set_tx(&TransactionDetails { + transaction: Some(tx.clone()), + txid: tx.txid(), + received: 100_000, + sent: 0, + fee: None, + confirmation_time: Some(block_time.clone()), + }) + .unwrap(); + db.set_utxo(&LocalUtxo { + outpoint: OutPoint { + txid: tx.txid(), + vout: 0, + }, + txout: tx.output[0].clone(), + keychain: KeychainKind::External, + is_spent: false, + }) + .unwrap(); + db.set_last_index(KeychainKind::External, 0).unwrap(); + db.set_last_index(KeychainKind::Internal, 3).unwrap(); + db.set_sync_time(SyncTime { block_time }).unwrap(); + db + } + + #[test] + fn copy_database_keeps_wallet_state() { + let src = funded_database(); + let copy = copy_database(&src).unwrap(); + + assert_eq!( + copy.iter_script_pubkeys(None).unwrap().len(), + src.iter_script_pubkeys(None).unwrap().len() + ); + assert_eq!(copy.iter_utxos().unwrap(), src.iter_utxos().unwrap()); + assert_eq!(copy.iter_txs(true).unwrap(), src.iter_txs(true).unwrap()); + for keychain in [KeychainKind::External, KeychainKind::Internal] { + assert_eq!( + copy.get_last_index(keychain).unwrap(), + src.get_last_index(keychain).unwrap() + ); + } + assert_eq!(copy.get_sync_time().unwrap(), src.get_sync_time().unwrap()); + } + + #[test] + fn psbt_from_copy_has_key_origin_and_leaves_source_index() { + // The cached wallet syncs with origin-less descriptors; signing needs + // PSBTs built with the fingerprinted ones over a copy of its data. + let src = funded_database(); + let mut wallet = wallet_from_database( + &setup(Some(TREZOR_ALL_FINGERPRINT)), + copy_database(&src).unwrap(), + ) + .unwrap(); + let outputs = vec![ComposeOutput::Payment { + address: REGTEST_ADDR.to_string(), + amount_sats: 10_000, + }]; + + let result = build_psbt( + &mut wallet, + &outputs, + 2.0, + bdk::bitcoin::Network::Regtest, + None, + ) + .unwrap(); + let ComposeResult::Success { psbt, fee, .. } = result else { + panic!("compose failed: {:?}", result); + }; + assert!(fee > 0); + + let bytes = general_purpose::STANDARD.decode(psbt).unwrap(); + let psbt = PartiallySignedTransaction::deserialize(&bytes).unwrap(); + let origin = psbt.inputs[0] + .bip32_derivation + .values() + .next() + .expect("input carries a BIP32 derivation"); + assert_eq!(origin.0.to_string(), TREZOR_ALL_FINGERPRINT); + assert_eq!(origin.1.to_string(), "m/84'/1'/0'/0/0"); + + // Change goes to the next internal index and is marked as ours. + let change_paths: Vec = psbt + .outputs + .iter() + .flat_map(|o| o.bip32_derivation.values()) + .map(|(_, path)| path.to_string()) + .collect(); + assert_eq!(change_paths, vec!["m/84'/1'/0'/1/4".to_string()]); + + // Building advanced the copy's change index, not the source's. + assert_eq!(src.get_last_index(KeychainKind::Internal).unwrap(), Some(3)); + } + + #[test] + fn cache_key_ignores_fingerprint_but_not_server() { + let url = "tcp://127.0.0.1:60001"; + let without = WalletCacheKey::new(&setup(None), url); + assert_eq!(without, WalletCacheKey::new(&setup(None), url)); + assert_ne!( + without, + WalletCacheKey::new(&setup(None), "tcp://127.0.0.1:60002") + ); + let other_type = resolve_wallet_setup( + TREZOR_ALL_TPUB, + Some(Network::Regtest), + Some(AccountType::Taproot), + None, + ) + .unwrap(); + assert_ne!(without, WalletCacheKey::new(&other_type, url)); + } + + #[test] + fn cache_evicts_least_recently_used() { + let keys: Vec = (0..=MAX_CACHED_WALLETS) + .map(|i| WalletCacheKey::new(&setup(None), &format!("tcp://evict-test:{}", i))) + .collect(); + for key in &keys { + insert_empty_for_test(key); + std::thread::sleep(std::time::Duration::from_millis(2)); + } + assert!(cached_wallet_count() <= MAX_CACHED_WALLETS); + assert!(!contains_key(&keys[0]), "oldest entry should be evicted"); + assert!(contains_key(&keys[MAX_CACHED_WALLETS])); + } + + /// Composes twice against a live regtest Electrum and prints both + /// timings. Set `COMPOSE_CACHE_ELECTRUM_URL` to use another server. + #[tokio::test] + #[ignore] + async fn compose_reuses_synced_wallet() { + let url = std::env::var("COMPOSE_CACHE_ELECTRUM_URL") + .unwrap_or_else(|_| "ssl://electrs.bitkit.stag0.blocktank.to:9999".to_string()); + let params = |fingerprint: Option| ComposeParams { + wallet: WalletParams { + extended_key: TREZOR_ALL_TPUB.to_string(), + electrum_url: url.clone(), + fingerprint, + network: Some(Network::Regtest), + account_type: Some(AccountType::NativeSegwit), + }, + outputs: vec![ComposeOutput::Payment { + address: REGTEST_ADDR.to_string(), + amount_sats: 10_000, + }], + fee_rates: vec![2.0], + coin_selection: None, + }; + + let mut fees = vec![]; + for (label, fingerprint) in [ + ("cold, no fingerprint", None), + ("warm, no fingerprint", None), + ( + "warm, fingerprint", + Some(TREZOR_ALL_FINGERPRINT.to_string()), + ), + ] { + let start = std::time::Instant::now(); + let results = compose_transaction(params(fingerprint)).await; + println!("compose {}: {:?}", label, start.elapsed()); + match &results[0] { + ComposeResult::Success { fee, .. } => fees.push(*fee), + ComposeResult::Error { error } => panic!("compose failed: {}", error), + } + } + assert!(fees.windows(2).all(|w| w[0] == w[1]), "fees: {:?}", fees); + assert!(contains_key(&WalletCacheKey::new(&setup(None), &url))); + } + } } diff --git a/src/modules/onchain/wallet_cache.rs b/src/modules/onchain/wallet_cache.rs new file mode 100644 index 00000000..9679b66f --- /dev/null +++ b/src/modules/onchain/wallet_cache.rs @@ -0,0 +1,221 @@ +//! Process-wide cache of synced watch-only wallets for offline transaction composition. +//! +//! A cold BDK sync fetches every script history, every wallet transaction and +//! every input's parent transaction. Keeping the synced in-memory database lets +//! the next call do an incremental sync: BDK reuses the stored transactions and +//! only fetches what changed. Every caller still syncs before reading the +//! wallet, so UTXOs are never older than the call. + +use std::collections::HashMap; +use std::sync::{Arc, Mutex as StdMutex, MutexGuard}; +use std::time::Instant; + +use bdk::electrum_client::{self, ConfigBuilder}; + +use bdk::bitcoin::Network as BdkNetwork; +use bdk::blockchain::ElectrumBlockchain; +use bdk::database::{BatchOperations, Database, MemoryDatabase}; +use bdk::wallet::Wallet; +use bdk::KeychainKind; +use once_cell::sync::OnceCell; + +use super::errors::AccountInfoError; +use super::implementation::{create_wallet, sync_wallet, WalletSetup}; + +/// Socket read and write timeout for compose connections. The per-wallet lock +/// is held while syncing, so a server that stops answering must fail the call +/// and release the lock instead of blocking every later compose for the wallet. +/// Generous enough for a slow server answering a large batch. +pub(crate) const COMPOSE_SOCKET_TIMEOUT_SECS: u8 = 30; + +/// Maximum number of wallets kept. The least recently used one is dropped +/// when a new key would exceed it. +pub(crate) const MAX_CACHED_WALLETS: usize = 8; + +/// Identifies one cached wallet. The descriptors carry the extended key and +/// script type; key origins are left out so callers with and without a +/// fingerprint share one wallet. +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub(crate) struct WalletCacheKey { + external_desc: String, + internal_desc: String, + network: BdkNetwork, + electrum_url: String, +} + +impl WalletCacheKey { + /// `sync_setup` must be resolved without a fingerprint. + pub(crate) fn new(sync_setup: &WalletSetup, electrum_url: &str) -> Self { + Self { + external_desc: sync_setup.external_desc.clone(), + internal_desc: sync_setup.internal_desc.clone(), + network: sync_setup.network, + electrum_url: electrum_url.to_string(), + } + } +} + +type Slot = Arc>>>; + +struct Entry { + slot: Slot, + last_used: Instant, +} + +static CACHE: OnceCell>> = OnceCell::new(); + +fn cache() -> &'static StdMutex> { + CACHE.get_or_init(|| StdMutex::new(HashMap::new())) +} + +fn lock_map() -> MutexGuard<'static, HashMap> { + // The map is only mutated by short, non-panicking sections; recover from + // poisoning instead of failing every later compose. + cache() + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) +} + +/// Get the slot for `key`, inserting an empty one and evicting the least +/// recently used entry if needed. +fn slot_for(key: &WalletCacheKey) -> Slot { + let mut map = lock_map(); + if let Some(entry) = map.get_mut(key) { + entry.last_used = Instant::now(); + return entry.slot.clone(); + } + while map.len() >= MAX_CACHED_WALLETS { + let oldest = map + .iter() + .min_by_key(|(_, entry)| entry.last_used) + .map(|(k, _)| k.clone()); + match oldest { + Some(k) => map.remove(&k), + None => break, + }; + } + let slot: Slot = Arc::new(StdMutex::new(None)); + map.insert( + key.clone(), + Entry { + slot: slot.clone(), + last_used: Instant::now(), + }, + ); + slot +} + +/// Sync the cached wallet for `sync_setup` (creating it on first use) and +/// return a copy of its database taken right after the sync. +/// +/// Calls for the same key are serialized on the wallet, so concurrent +/// composes never sync one wallet twice at once. The copy lets callers build +/// transactions without touching the cached wallet: building a transaction +/// advances the change index, and the cached wallet must keep the index the +/// server reports. A failed sync drops the cached wallet so the next call +/// starts cold. A new Electrum connection is opened per call, as before; +/// only the wallet data is reused. The connection has a socket timeout, so a +/// server that stops answering fails the call and releases the lock. +pub(crate) fn synced_database_snapshot( + sync_setup: &WalletSetup, + electrum_url: &str, +) -> Result { + synced_database_snapshot_with_timeout(sync_setup, electrum_url, COMPOSE_SOCKET_TIMEOUT_SECS) +} + +pub(crate) fn synced_database_snapshot_with_timeout( + sync_setup: &WalletSetup, + electrum_url: &str, + socket_timeout_secs: u8, +) -> Result { + let key = WalletCacheKey::new(sync_setup, electrum_url); + let slot = slot_for(&key); + let mut guard = slot.lock().unwrap_or_else(|poisoned| { + // A panic while syncing may have left a half-updated wallet. + let mut guard = poisoned.into_inner(); + *guard = None; + guard + }); + + // Connect before taking the wallet so a connection failure keeps it. + let blockchain = ElectrumBlockchain::from(connect_electrum_with_timeout( + electrum_url, + socket_timeout_secs, + )?); + let wallet = match guard.take() { + Some(wallet) => wallet, + None => create_wallet(sync_setup)?, + }; + sync_wallet(&wallet, &blockchain)?; + + let snapshot = copy_database(&wallet.database())?; + *guard = Some(wallet); + Ok(snapshot) +} + +fn connect_electrum_with_timeout( + electrum_url: &str, + socket_timeout_secs: u8, +) -> Result { + let config = ConfigBuilder::new() + .timeout(Some(socket_timeout_secs)) + .build(); + electrum_client::Client::from_config(electrum_url, config).map_err(|e| { + AccountInfoError::ElectrumError { + error_details: format!("Failed to connect to Electrum: {}", e), + } + }) +} + +/// Copy everything a [`Wallet`] needs to build and sign transactions: +/// cached scripts, UTXOs, transactions, last derivation indexes and the +/// sync time. Descriptor checksums are left out so the copy can back a +/// wallet whose descriptors carry key origins. +pub(crate) fn copy_database(src: &MemoryDatabase) -> Result { + let map_err = |e: bdk::Error| AccountInfoError::WalletError { + error_details: format!("Failed to copy wallet database: {}", e), + }; + let mut dst = MemoryDatabase::new(); + + for script in src.iter_script_pubkeys(None).map_err(map_err)? { + if let Some((keychain, child)) = + src.get_path_from_script_pubkey(&script).map_err(map_err)? + { + dst.set_script_pubkey(&script, keychain, child) + .map_err(map_err)?; + } + } + for utxo in src.iter_utxos().map_err(map_err)? { + dst.set_utxo(&utxo).map_err(map_err)?; + } + for tx in src.iter_raw_txs().map_err(map_err)? { + dst.set_raw_tx(&tx).map_err(map_err)?; + } + for tx in src.iter_txs(false).map_err(map_err)? { + dst.set_tx(&tx).map_err(map_err)?; + } + for keychain in [KeychainKind::External, KeychainKind::Internal] { + if let Some(index) = src.get_last_index(keychain).map_err(map_err)? { + dst.set_last_index(keychain, index).map_err(map_err)?; + } + } + if let Some(sync_time) = src.get_sync_time().map_err(map_err)? { + dst.set_sync_time(sync_time).map_err(map_err)?; + } + Ok(dst) +} + +#[cfg(test)] +pub(crate) fn cached_wallet_count() -> usize { + lock_map().len() +} + +#[cfg(test)] +pub(crate) fn contains_key(key: &WalletCacheKey) -> bool { + lock_map().contains_key(key) +} + +#[cfg(test)] +pub(crate) fn insert_empty_for_test(key: &WalletCacheKey) { + slot_for(key); +}