diff --git a/bdk-android/lib/src/androidTest/kotlin/org/bitcoindevkit/ElectrumClientTest.kt b/bdk-android/lib/src/androidTest/kotlin/org/bitcoindevkit/ElectrumClientTest.kt new file mode 100644 index 00000000..9a82eeae --- /dev/null +++ b/bdk-android/lib/src/androidTest/kotlin/org/bitcoindevkit/ElectrumClientTest.kt @@ -0,0 +1,77 @@ +package org.bitcoindevkit + +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertTrue +import androidx.test.ext.junit.runners.AndroidJUnit4 +import kotlinx.coroutines.delay +import kotlinx.coroutines.runBlocking +import org.junit.runner.RunWith +import org.kotlinbitcointools.regtesttoolbox.regenv.RegEnv +import kotlin.time.Duration.Companion.milliseconds + +@RunWith(AndroidJUnit4::class) +class ElectrumClientTest { + private val conn: Persister = Persister.newInMemory() + + @Test + fun populateAnchorCacheFromWalletTransactions() { + runBlocking { + val regtestEnv = RegEnv.connectTo( + host = "10.0.2.2", + walletName = "faucet", + username = "regtest", + password = "password", + ) + + // A freshly generated key on every run, so the wallet has no history from earlier runs. + val secretKey = DescriptorSecretKey(NetworkKind.TEST, Mnemonic(WordCount.WORDS12), null) + val wallet: Wallet = Wallet.createSingle( + descriptor = Descriptor.newBip86(secretKey, KeychainKind.EXTERNAL, NetworkKind.TEST), + network = Network.REGTEST, + persister = conn + ) + val address = wallet.revealNextAddress(KeychainKind.EXTERNAL).address + val txid = Txid.fromString(regtestEnv.send(address.toString(), 0.12345678, 2.0)) + regtestEnv.mine(1) + + // Full scan until the Electrum server has indexed our transaction as confirmed. + val electrumClient = ElectrumClient(ELECTRUM_REGTEST_URL) + for (i in 0..99) { + val request = wallet.startFullScan().build() + wallet.applyUpdate(electrumClient.fullScan(request, 10uL, 10uL, false)) + if (wallet.getTx(txid)?.chainPosition is ChainPosition.Confirmed) break + delay(200.milliseconds) + } + + // Build one TxAnchor per directly confirmed wallet transaction. Transactions confirmed + // only `transitively` (through a confirmed descendant) are skipped, since their + // ConfirmationBlockTime belongs to the descendant, not to them. + val anchors: List = wallet.transactions().mapNotNull { canonicalTx -> + val position = canonicalTx.chainPosition + if (position is ChainPosition.Confirmed && position.transitively == null) { + TxAnchor( + txid = canonicalTx.transaction.computeTxid(), + anchor = position.confirmationBlockTime, + ) + } else { + null + } + } + assertEquals(1, anchors.size, "The funding transaction should produce one anchor") + assertEquals(txid, anchors.single().txid) + + // A fresh client seeded with the wallet's transactions and anchors does not need to + // re-download those transactions or re-fetch their Merkle proofs during the next sync. + val freshClient = ElectrumClient(ELECTRUM_REGTEST_URL) + freshClient.populateTxCache(wallet.transactions().map { it.transaction }) + freshClient.populateAnchorCache(anchors) + + val syncRequest = wallet.startSyncWithRevealedSpks().build() + wallet.applyUpdate(freshClient.sync(syncRequest, 10uL, false)) + + assertEquals(12_345_678uL, wallet.balance().confirmed.toSat()) + assertTrue(wallet.getTx(txid)?.chainPosition is ChainPosition.Confirmed) + } + } +} diff --git a/bdk-ffi/src/electrum.rs b/bdk-ffi/src/electrum.rs index da4844d5..c6b50bbd 100644 --- a/bdk-ffi/src/electrum.rs +++ b/bdk-ffi/src/electrum.rs @@ -1,6 +1,7 @@ use crate::bitcoin::{BlockHash, Header, Transaction, Txid}; use crate::error::ElectrumError; use crate::types::KeychainKind; +use crate::types::TxAnchor; use crate::types::Update; use crate::types::{FullScanRequest, SyncRequest}; @@ -12,6 +13,7 @@ use bdk_wallet::chain::spk_client::FullScanRequest as BdkFullScanRequest; use bdk_wallet::chain::spk_client::FullScanResponse as BdkFullScanResponse; use bdk_wallet::chain::spk_client::SyncRequest as BdkSyncRequest; use bdk_wallet::chain::spk_client::SyncResponse as BdkSyncResponse; +use bdk_wallet::chain::ConfirmationBlockTime as BdkConfirmationBlockTime; use bdk_wallet::Update as BdkUpdate; use bdk_electrum::electrum_client::ElectrumApi; @@ -60,6 +62,25 @@ impl ElectrumClient { Ok(Self(client)) } + /// Insert confirmation anchors into the client's anchor cache so that later syncs and full + /// scans do not request their Merkle proofs again. + /// + /// Anchors are keyed by block hash: when the client resolves a different block at that height + /// (for example after a reorg), the proof is fetched and validated as usual. + /// + /// Only pass direct confirmation anchors already verified by the wallet. When building them + /// from `Wallet.transactions()`, select `ChainPosition::Confirmed { transitively: None, .. }`. + /// A transitive anchor belongs to a confirmed descendant, not to the transaction whose id is + /// passed. + pub fn populate_anchor_cache(&self, anchors: Vec) { + self.0.populate_anchor_cache(anchors.into_iter().map(|a| { + ( + a.txid.0, + std::iter::once(BdkConfirmationBlockTime::from(a.anchor)), + ) + })); + } + /// Full scan the keychain scripts specified with the blockchain (via an Electrum client) and /// returns updates for bdk_chain data structures. /// diff --git a/bdk-ffi/src/types.rs b/bdk-ffi/src/types.rs index 0cfe874c..68642fe7 100644 --- a/bdk-ffi/src/types.rs +++ b/bdk-ffi/src/types.rs @@ -134,6 +134,18 @@ impl From for BdkConfirmationBlockTime { } } +// Replaces the Rust `(Txid, impl IntoIterator)` pair, since UniFFI +// cannot expose tuples or generics. Pass multiple records for a transaction with multiple anchors. +/// A transaction id with one of its confirmation anchors, used to prefill an Electrum client's +/// anchor cache (see `ElectrumClient::populate_anchor_cache`). +#[derive(Clone, uniffi::Record)] +pub struct TxAnchor { + /// The id of the anchored transaction. + pub txid: Arc, + /// A direct confirmation anchor for this transaction, not one inherited from a descendant. + pub anchor: ConfirmationBlockTime, +} + /// A reference to a block in the canonical chain. #[derive(Debug, Clone, PartialEq, Eq, std::hash::Hash, uniffi::Record)] pub struct BlockId {