From cad0d90afb6a5c1959f6dcb3a26c41f4ccae53e7 Mon Sep 17 00:00:00 2001 From: Vladimir Fomene Date: Mon, 23 Oct 2023 20:47:11 +0300 Subject: [PATCH 1/2] feat: get keychain that derived a script --- crates/bdk/src/wallet/mod.rs | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/crates/bdk/src/wallet/mod.rs b/crates/bdk/src/wallet/mod.rs index 659da90a2..1c95d826f 100644 --- a/crates/bdk/src/wallet/mod.rs +++ b/crates/bdk/src/wallet/mod.rs @@ -1986,6 +1986,14 @@ impl Wallet { pub fn local_chain(&self) -> &LocalChain { &self.chain } + + /// Get the [`KeychainKind`] and derivation index for a given [`Script`]. + /// + /// This will return `None` if the script is not in the wallet. + // TODO: Generalize this implementation once we make the wallet generic over K + pub fn which_keychain_derived(&self, spk: &Script) -> Option<&(KeychainKind, u32)> { + self.indexed_graph.index.index_of_spk(spk) + } } impl AsRef> for Wallet { From e2ec6ff56fe9461f4ac93a2d5c0e7beabec98c85 Mon Sep 17 00:00:00 2001 From: Vladimir Fomene Date: Thu, 9 Nov 2023 10:19:59 +0300 Subject: [PATCH 2/2] test: test getting keychain for a script --- crates/bdk/tests/wallet.rs | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/crates/bdk/tests/wallet.rs b/crates/bdk/tests/wallet.rs index aad8c2db2..8990b21ea 100644 --- a/crates/bdk/tests/wallet.rs +++ b/crates/bdk/tests/wallet.rs @@ -60,6 +60,21 @@ fn receive_output_in_latest_block(wallet: &mut Wallet, value: u64) -> OutPoint { // OP_PUSH. const P2WPKH_FAKE_WITNESS_SIZE: usize = 106; +#[test] +fn test_which_keychain_derived_script() { + let (mut segwit_wallet, _) = get_funded_wallet(get_test_wpkh()); + let addr = segwit_wallet.get_address(New); + let script = addr.script_pubkey(); + let keychain = segwit_wallet.which_keychain_derived(&script).unwrap(); + assert_eq!(keychain.0, KeychainKind::External); + + let (mut taproot_wallet, _) = get_funded_wallet(get_test_tr_single_sig()); + let addr = taproot_wallet.get_address(New); + let script = addr.script_pubkey(); + let keychain = segwit_wallet.which_keychain_derived(&script); + assert!(keychain.is_none()); +} + #[test] fn test_descriptor_checksum() { let (wallet, _) = get_funded_wallet(get_test_wpkh());