Merge pull request #1493 from ValuedMammal/refactor/keychain-balance

[chain] Create module `indexer`
This commit is contained in:
Lloyd Fournier 2024-07-06 22:37:02 +10:00 committed by GitHub
commit db8fbd729d
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
25 changed files with 133 additions and 136 deletions

View File

@ -3,9 +3,8 @@ use std::collections::{BTreeMap, BTreeSet};
use bdk_bitcoind_rpc::Emitter; use bdk_bitcoind_rpc::Emitter;
use bdk_chain::{ use bdk_chain::{
bitcoin::{Address, Amount, Txid}, bitcoin::{Address, Amount, Txid},
keychain::Balance,
local_chain::{CheckPoint, LocalChain}, local_chain::{CheckPoint, LocalChain},
Append, BlockId, IndexedTxGraph, SpkTxOutIndex, Append, Balance, BlockId, IndexedTxGraph, SpkTxOutIndex,
}; };
use bdk_testenv::{anyhow, TestEnv}; use bdk_testenv::{anyhow, TestEnv};
use bitcoin::{hashes::Hash, Block, OutPoint, ScriptBuf, WScriptHash}; use bitcoin::{hashes::Hash, Block, OutPoint, ScriptBuf, WScriptHash};

View File

@ -1,20 +1,4 @@
//! Module for keychain related structures. use bitcoin::Amount;
//!
//! A keychain here is a set of application-defined indexes for a miniscript descriptor where we can
//! derive script pubkeys at a particular derivation index. The application's index is simply
//! anything that implements `Ord`.
//!
//! [`KeychainTxOutIndex`] indexes script pubkeys of keychains and scans in relevant outpoints (that
//! has a `txout` containing an indexed script pubkey). Internally, this uses [`SpkTxOutIndex`], but
//! also maintains "revealed" and "lookahead" index counts per keychain.
//!
//! [`SpkTxOutIndex`]: crate::SpkTxOutIndex
#[cfg(feature = "miniscript")]
mod txout_index;
use bitcoin::{Amount, ScriptBuf};
#[cfg(feature = "miniscript")]
pub use txout_index::*;
/// Balance, differentiated into various categories. /// Balance, differentiated into various categories.
#[derive(Debug, PartialEq, Eq, Clone, Default)] #[derive(Debug, PartialEq, Eq, Clone, Default)]
@ -49,11 +33,6 @@ impl Balance {
} }
} }
/// A tuple of keychain index and `T` representing the indexed value.
pub type Indexed<T> = (u32, T);
/// A tuple of keychain `K`, derivation index (`u32`) and a `T` associated with them.
pub type KeychainIndexed<K, T> = ((K, u32), T);
impl core::fmt::Display for Balance { impl core::fmt::Display for Balance {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
write!( write!(

View File

@ -16,7 +16,8 @@ pub struct CombinedChangeSet<K, A> {
/// Changes to the [`LocalChain`](crate::local_chain::LocalChain). /// Changes to the [`LocalChain`](crate::local_chain::LocalChain).
pub chain: crate::local_chain::ChangeSet, pub chain: crate::local_chain::ChangeSet,
/// Changes to [`IndexedTxGraph`](crate::indexed_tx_graph::IndexedTxGraph). /// Changes to [`IndexedTxGraph`](crate::indexed_tx_graph::IndexedTxGraph).
pub indexed_tx_graph: crate::indexed_tx_graph::ChangeSet<A, crate::keychain::ChangeSet<K>>, pub indexed_tx_graph:
crate::indexed_tx_graph::ChangeSet<A, crate::indexer::keychain_txout::ChangeSet<K>>,
/// Stores the network type of the transaction data. /// Stores the network type of the transaction data.
pub network: Option<bitcoin::Network>, pub network: Option<bitcoin::Network>,
} }
@ -62,11 +63,14 @@ impl<K, A> From<crate::local_chain::ChangeSet> for CombinedChangeSet<K, A> {
} }
#[cfg(feature = "miniscript")] #[cfg(feature = "miniscript")]
impl<K, A> From<crate::indexed_tx_graph::ChangeSet<A, crate::keychain::ChangeSet<K>>> impl<K, A> From<crate::indexed_tx_graph::ChangeSet<A, crate::indexer::keychain_txout::ChangeSet<K>>>
for CombinedChangeSet<K, A> for CombinedChangeSet<K, A>
{ {
fn from( fn from(
indexed_tx_graph: crate::indexed_tx_graph::ChangeSet<A, crate::keychain::ChangeSet<K>>, indexed_tx_graph: crate::indexed_tx_graph::ChangeSet<
A,
crate::indexer::keychain_txout::ChangeSet<K>,
>,
) -> Self { ) -> Self {
Self { Self {
indexed_tx_graph, indexed_tx_graph,
@ -76,8 +80,8 @@ impl<K, A> From<crate::indexed_tx_graph::ChangeSet<A, crate::keychain::ChangeSet
} }
#[cfg(feature = "miniscript")] #[cfg(feature = "miniscript")]
impl<K, A> From<crate::keychain::ChangeSet<K>> for CombinedChangeSet<K, A> { impl<K, A> From<crate::indexer::keychain_txout::ChangeSet<K>> for CombinedChangeSet<K, A> {
fn from(indexer: crate::keychain::ChangeSet<K>) -> Self { fn from(indexer: crate::indexer::keychain_txout::ChangeSet<K>) -> Self {
Self { Self {
indexed_tx_graph: crate::indexed_tx_graph::ChangeSet { indexed_tx_graph: crate::indexed_tx_graph::ChangeSet {
indexer, indexer,

View File

@ -5,7 +5,7 @@ use bitcoin::{Block, OutPoint, Transaction, TxOut, Txid};
use crate::{ use crate::{
tx_graph::{self, TxGraph}, tx_graph::{self, TxGraph},
Anchor, AnchorFromBlockPosition, Append, BlockId, Anchor, AnchorFromBlockPosition, Append, BlockId, Indexer,
}; };
/// The [`IndexedTxGraph`] combines a [`TxGraph`] and an [`Indexer`] implementation. /// The [`IndexedTxGraph`] combines a [`TxGraph`] and an [`Indexer`] implementation.
@ -320,8 +320,10 @@ impl<A, IA: Default> From<tx_graph::ChangeSet<A>> for ChangeSet<A, IA> {
} }
#[cfg(feature = "miniscript")] #[cfg(feature = "miniscript")]
impl<A, K> From<crate::keychain::ChangeSet<K>> for ChangeSet<A, crate::keychain::ChangeSet<K>> { impl<A, K> From<crate::indexer::keychain_txout::ChangeSet<K>>
fn from(indexer: crate::keychain::ChangeSet<K>) -> Self { for ChangeSet<A, crate::indexer::keychain_txout::ChangeSet<K>>
{
fn from(indexer: crate::indexer::keychain_txout::ChangeSet<K>) -> Self {
Self { Self {
graph: Default::default(), graph: Default::default(),
indexer, indexer,
@ -329,30 +331,6 @@ impl<A, K> From<crate::keychain::ChangeSet<K>> for ChangeSet<A, crate::keychain:
} }
} }
/// Utilities for indexing transaction data.
///
/// Types which implement this trait can be used to construct an [`IndexedTxGraph`].
/// This trait's methods should rarely be called directly.
pub trait Indexer {
/// The resultant "changeset" when new transaction data is indexed.
type ChangeSet;
/// Scan and index the given `outpoint` and `txout`.
fn index_txout(&mut self, outpoint: OutPoint, txout: &TxOut) -> Self::ChangeSet;
/// Scans a transaction for relevant outpoints, which are stored and indexed internally.
fn index_tx(&mut self, tx: &Transaction) -> Self::ChangeSet;
/// Apply changeset to itself.
fn apply_changeset(&mut self, changeset: Self::ChangeSet);
/// Determines the [`ChangeSet`] between `self` and an empty [`Indexer`].
fn initial_changeset(&self) -> Self::ChangeSet;
/// Determines whether the transaction should be included in the index.
fn is_tx_relevant(&self, tx: &Transaction) -> bool;
}
impl<A, I> AsRef<TxGraph<A>> for IndexedTxGraph<A, I> { impl<A, I> AsRef<TxGraph<A>> for IndexedTxGraph<A, I> {
fn as_ref(&self) -> &TxGraph<A> { fn as_ref(&self) -> &TxGraph<A> {
&self.graph &self.graph

View File

@ -0,0 +1,33 @@
//! [`Indexer`] provides utilities for indexing transaction data.
use bitcoin::{OutPoint, Transaction, TxOut};
#[cfg(feature = "miniscript")]
pub mod keychain_txout;
pub mod spk_txout;
/// Utilities for indexing transaction data.
///
/// Types which implement this trait can be used to construct an [`IndexedTxGraph`].
/// This trait's methods should rarely be called directly.
///
/// [`IndexedTxGraph`]: crate::IndexedTxGraph
pub trait Indexer {
/// The resultant "changeset" when new transaction data is indexed.
type ChangeSet;
/// Scan and index the given `outpoint` and `txout`.
fn index_txout(&mut self, outpoint: OutPoint, txout: &TxOut) -> Self::ChangeSet;
/// Scans a transaction for relevant outpoints, which are stored and indexed internally.
fn index_tx(&mut self, tx: &Transaction) -> Self::ChangeSet;
/// Apply changeset to itself.
fn apply_changeset(&mut self, changeset: Self::ChangeSet);
/// Determines the [`ChangeSet`](Indexer::ChangeSet) between `self` and an empty [`Indexer`].
fn initial_changeset(&self) -> Self::ChangeSet;
/// Determines whether the transaction should be included in the index.
fn is_tx_relevant(&self, tx: &Transaction) -> bool;
}

View File

@ -1,18 +1,19 @@
//! [`KeychainTxOutIndex`] controls how script pubkeys are revealed for multiple keychains and
//! indexes [`TxOut`]s with them.
use crate::{ use crate::{
collections::*, collections::*,
indexed_tx_graph::Indexer,
miniscript::{Descriptor, DescriptorPublicKey}, miniscript::{Descriptor, DescriptorPublicKey},
spk_iter::BIP32_MAX_INDEX, spk_iter::BIP32_MAX_INDEX,
DescriptorExt, DescriptorId, SpkIterator, SpkTxOutIndex, DescriptorExt, DescriptorId, Indexed, Indexer, KeychainIndexed, SpkIterator, SpkTxOutIndex,
}; };
use alloc::{borrow::ToOwned, vec::Vec}; use alloc::{borrow::ToOwned, vec::Vec};
use bitcoin::{Amount, OutPoint, Script, SignedAmount, Transaction, TxOut, Txid}; use bitcoin::{Amount, OutPoint, Script, ScriptBuf, SignedAmount, Transaction, TxOut, Txid};
use core::{ use core::{
fmt::Debug, fmt::Debug,
ops::{Bound, RangeBounds}, ops::{Bound, RangeBounds},
}; };
use super::*;
use crate::Append; use crate::Append;
/// The default lookahead for a [`KeychainTxOutIndex`] /// The default lookahead for a [`KeychainTxOutIndex`]
@ -73,7 +74,7 @@ pub const DEFAULT_LOOKAHEAD: u32 = 25;
/// ## Synopsis /// ## Synopsis
/// ///
/// ``` /// ```
/// use bdk_chain::keychain::KeychainTxOutIndex; /// use bdk_chain::indexer::keychain_txout::KeychainTxOutIndex;
/// # use bdk_chain::{ miniscript::{Descriptor, DescriptorPublicKey} }; /// # use bdk_chain::{ miniscript::{Descriptor, DescriptorPublicKey} };
/// # use core::str::FromStr; /// # use core::str::FromStr;
/// ///
@ -98,7 +99,7 @@ pub const DEFAULT_LOOKAHEAD: u32 = 25;
/// let _ = txout_index.insert_descriptor(MyKeychain::MyAppUser { user_id: 42 }, descriptor_42)?; /// let _ = txout_index.insert_descriptor(MyKeychain::MyAppUser { user_id: 42 }, descriptor_42)?;
/// ///
/// let new_spk_for_user = txout_index.reveal_next_spk(&MyKeychain::MyAppUser{ user_id: 42 }); /// let new_spk_for_user = txout_index.reveal_next_spk(&MyKeychain::MyAppUser{ user_id: 42 });
/// # Ok::<_, bdk_chain::keychain::InsertDescriptorError<_>>(()) /// # Ok::<_, bdk_chain::indexer::keychain_txout::InsertDescriptorError<_>>(())
/// ``` /// ```
/// ///
/// [`Ord`]: core::cmp::Ord /// [`Ord`]: core::cmp::Ord
@ -859,8 +860,7 @@ impl<K: core::fmt::Debug> std::error::Error for InsertDescriptorError<K> {}
/// `keychains_added` is *not* monotone, once it is set any attempt to change it is subject to the /// `keychains_added` is *not* monotone, once it is set any attempt to change it is subject to the
/// same *one-to-one* keychain <-> descriptor mapping invariant as [`KeychainTxOutIndex`] itself. /// same *one-to-one* keychain <-> descriptor mapping invariant as [`KeychainTxOutIndex`] itself.
/// ///
/// [`KeychainTxOutIndex`]: crate::keychain::KeychainTxOutIndex /// [`apply_changeset`]: KeychainTxOutIndex::apply_changeset
/// [`apply_changeset`]: crate::keychain::KeychainTxOutIndex::apply_changeset
/// [`append`]: Self::append /// [`append`]: Self::append
#[derive(Clone, Debug, PartialEq)] #[derive(Clone, Debug, PartialEq)]
#[cfg_attr( #[cfg_attr(

View File

@ -1,8 +1,10 @@
//! [`SpkTxOutIndex`] is an index storing [`TxOut`]s that have a script pubkey that matches those in a list.
use core::ops::RangeBounds; use core::ops::RangeBounds;
use crate::{ use crate::{
collections::{hash_map::Entry, BTreeMap, BTreeSet, HashMap}, collections::{hash_map::Entry, BTreeMap, BTreeSet, HashMap},
indexed_tx_graph::Indexer, Indexer,
}; };
use bitcoin::{Amount, OutPoint, Script, ScriptBuf, SignedAmount, Transaction, TxOut, Txid}; use bitcoin::{Amount, OutPoint, Script, ScriptBuf, SignedAmount, Transaction, TxOut, Txid};

View File

@ -21,14 +21,15 @@
#![warn(missing_docs)] #![warn(missing_docs)]
pub use bitcoin; pub use bitcoin;
mod spk_txout_index; mod balance;
pub use spk_txout_index::*; pub use balance::*;
mod chain_data; mod chain_data;
pub use chain_data::*; pub use chain_data::*;
pub mod indexed_tx_graph; pub mod indexed_tx_graph;
pub use indexed_tx_graph::IndexedTxGraph; pub use indexed_tx_graph::IndexedTxGraph;
pub mod keychain; pub mod indexer;
pub use keychain::{Indexed, KeychainIndexed}; pub use indexer::spk_txout::*;
pub use indexer::Indexer;
pub mod local_chain; pub mod local_chain;
mod tx_data_traits; mod tx_data_traits;
pub mod tx_graph; pub mod tx_graph;
@ -98,3 +99,8 @@ pub mod collections {
/// How many confirmations are needed f or a coinbase output to be spent. /// How many confirmations are needed f or a coinbase output to be spent.
pub const COINBASE_MATURITY: u32 = 100; pub const COINBASE_MATURITY: u32 = 100;
/// A tuple of keychain index and `T` representing the indexed value.
pub type Indexed<T> = (u32, T);
/// A tuple of keychain `K`, derivation index (`u32`) and a `T` associated with them.
pub type KeychainIndexed<K, T> = ((K, u32), T);

View File

@ -1,8 +1,7 @@
//! Helper types for spk-based blockchain clients. //! Helper types for spk-based blockchain clients.
use crate::{ use crate::{
collections::BTreeMap, keychain::Indexed, local_chain::CheckPoint, collections::BTreeMap, local_chain::CheckPoint, ConfirmationTimeHeightAnchor, Indexed, TxGraph,
ConfirmationTimeHeightAnchor, TxGraph,
}; };
use alloc::boxed::Box; use alloc::boxed::Box;
use bitcoin::{OutPoint, Script, ScriptBuf, Txid}; use bitcoin::{OutPoint, Script, ScriptBuf, Txid};
@ -160,7 +159,7 @@ impl SyncRequest {
#[must_use] #[must_use]
pub fn populate_with_revealed_spks<K: Clone + Ord + core::fmt::Debug + Send + Sync>( pub fn populate_with_revealed_spks<K: Clone + Ord + core::fmt::Debug + Send + Sync>(
self, self,
index: &crate::keychain::KeychainTxOutIndex<K>, index: &crate::indexer::keychain_txout::KeychainTxOutIndex<K>,
spk_range: impl core::ops::RangeBounds<K>, spk_range: impl core::ops::RangeBounds<K>,
) -> Self { ) -> Self {
use alloc::borrow::ToOwned; use alloc::borrow::ToOwned;
@ -216,12 +215,12 @@ impl<K: Ord + Clone> FullScanRequest<K> {
/// [`KeychainTxOutIndex::all_unbounded_spk_iters`] and is used to populate the /// [`KeychainTxOutIndex::all_unbounded_spk_iters`] and is used to populate the
/// [`FullScanRequest`]. /// [`FullScanRequest`].
/// ///
/// [`KeychainTxOutIndex::all_unbounded_spk_iters`]: crate::keychain::KeychainTxOutIndex::all_unbounded_spk_iters /// [`KeychainTxOutIndex::all_unbounded_spk_iters`]: crate::indexer::keychain_txout::KeychainTxOutIndex::all_unbounded_spk_iters
#[cfg(feature = "miniscript")] #[cfg(feature = "miniscript")]
#[must_use] #[must_use]
pub fn from_keychain_txout_index( pub fn from_keychain_txout_index(
chain_tip: CheckPoint, chain_tip: CheckPoint,
index: &crate::keychain::KeychainTxOutIndex<K>, index: &crate::indexer::keychain_txout::KeychainTxOutIndex<K>,
) -> Self ) -> Self
where where
K: core::fmt::Debug, K: core::fmt::Debug,

View File

@ -1,7 +1,7 @@
use crate::{ use crate::{
bitcoin::{secp256k1::Secp256k1, ScriptBuf}, bitcoin::{secp256k1::Secp256k1, ScriptBuf},
keychain::Indexed,
miniscript::{Descriptor, DescriptorPublicKey}, miniscript::{Descriptor, DescriptorPublicKey},
Indexed,
}; };
use core::{borrow::Borrow, ops::Bound, ops::RangeBounds}; use core::{borrow::Borrow, ops::Bound, ops::RangeBounds};
@ -137,7 +137,7 @@ where
mod test { mod test {
use crate::{ use crate::{
bitcoin::secp256k1::Secp256k1, bitcoin::secp256k1::Secp256k1,
keychain::KeychainTxOutIndex, indexer::keychain_txout::KeychainTxOutIndex,
miniscript::{Descriptor, DescriptorPublicKey}, miniscript::{Descriptor, DescriptorPublicKey},
spk_iter::{SpkIterator, BIP32_MAX_INDEX}, spk_iter::{SpkIterator, BIP32_MAX_INDEX},
}; };

View File

@ -89,8 +89,7 @@
//! [`insert_txout`]: TxGraph::insert_txout //! [`insert_txout`]: TxGraph::insert_txout
use crate::{ use crate::{
collections::*, keychain::Balance, Anchor, Append, BlockId, ChainOracle, ChainPosition, collections::*, Anchor, Append, Balance, BlockId, ChainOracle, ChainPosition, FullTxOut,
FullTxOut,
}; };
use alloc::collections::vec_deque::VecDeque; use alloc::collections::vec_deque::VecDeque;
use alloc::sync::Arc; use alloc::sync::Arc;

View File

@ -8,9 +8,9 @@ use std::{collections::BTreeSet, sync::Arc};
use crate::common::DESCRIPTORS; use crate::common::DESCRIPTORS;
use bdk_chain::{ use bdk_chain::{
indexed_tx_graph::{self, IndexedTxGraph}, indexed_tx_graph::{self, IndexedTxGraph},
keychain::{self, Balance, KeychainTxOutIndex}, indexer::keychain_txout::KeychainTxOutIndex,
local_chain::LocalChain, local_chain::LocalChain,
tx_graph, Append, ChainPosition, ConfirmationHeightAnchor, DescriptorExt, tx_graph, Append, Balance, ChainPosition, ConfirmationHeightAnchor, DescriptorExt,
}; };
use bitcoin::{ use bitcoin::{
secp256k1::Secp256k1, Amount, OutPoint, Script, ScriptBuf, Transaction, TxIn, TxOut, secp256k1::Secp256k1, Amount, OutPoint, Script, ScriptBuf, Transaction, TxIn, TxOut,
@ -26,6 +26,7 @@ use miniscript::Descriptor;
/// agnostic. /// agnostic.
#[test] #[test]
fn insert_relevant_txs() { fn insert_relevant_txs() {
use bdk_chain::indexer::keychain_txout;
let (descriptor, _) = Descriptor::parse_descriptor(&Secp256k1::signing_only(), DESCRIPTORS[0]) let (descriptor, _) = Descriptor::parse_descriptor(&Secp256k1::signing_only(), DESCRIPTORS[0])
.expect("must be valid"); .expect("must be valid");
let spk_0 = descriptor.at_derivation_index(0).unwrap().script_pubkey(); let spk_0 = descriptor.at_derivation_index(0).unwrap().script_pubkey();
@ -76,7 +77,7 @@ fn insert_relevant_txs() {
txs: txs.iter().cloned().map(Arc::new).collect(), txs: txs.iter().cloned().map(Arc::new).collect(),
..Default::default() ..Default::default()
}, },
indexer: keychain::ChangeSet { indexer: keychain_txout::ChangeSet {
last_revealed: [(descriptor.descriptor_id(), 9_u32)].into(), last_revealed: [(descriptor.descriptor_id(), 9_u32)].into(),
keychains_added: [].into(), keychains_added: [].into(),
}, },
@ -90,7 +91,7 @@ fn insert_relevant_txs() {
// The initial changeset will also contain info about the keychain we added // The initial changeset will also contain info about the keychain we added
let initial_changeset = indexed_tx_graph::ChangeSet { let initial_changeset = indexed_tx_graph::ChangeSet {
graph: changeset.graph, graph: changeset.graph,
indexer: keychain::ChangeSet { indexer: keychain_txout::ChangeSet {
last_revealed: changeset.indexer.last_revealed, last_revealed: changeset.indexer.last_revealed,
keychains_added: [((), descriptor)].into(), keychains_added: [((), descriptor)].into(),
}, },

View File

@ -4,9 +4,8 @@
mod common; mod common;
use bdk_chain::{ use bdk_chain::{
collections::BTreeMap, collections::BTreeMap,
indexed_tx_graph::Indexer, indexer::keychain_txout::{ChangeSet, KeychainTxOutIndex},
keychain::{self, ChangeSet, KeychainTxOutIndex}, Append, DescriptorExt, DescriptorId, Indexer,
Append, DescriptorExt, DescriptorId,
}; };
use bitcoin::{secp256k1::Secp256k1, Amount, OutPoint, ScriptBuf, Transaction, TxOut}; use bitcoin::{secp256k1::Secp256k1, Amount, OutPoint, ScriptBuf, Transaction, TxOut};
@ -31,8 +30,8 @@ fn init_txout_index(
external_descriptor: Descriptor<DescriptorPublicKey>, external_descriptor: Descriptor<DescriptorPublicKey>,
internal_descriptor: Descriptor<DescriptorPublicKey>, internal_descriptor: Descriptor<DescriptorPublicKey>,
lookahead: u32, lookahead: u32,
) -> bdk_chain::keychain::KeychainTxOutIndex<TestKeychain> { ) -> KeychainTxOutIndex<TestKeychain> {
let mut txout_index = bdk_chain::keychain::KeychainTxOutIndex::<TestKeychain>::new(lookahead); let mut txout_index = KeychainTxOutIndex::<TestKeychain>::new(lookahead);
let _ = txout_index let _ = txout_index
.insert_descriptor(TestKeychain::External, external_descriptor) .insert_descriptor(TestKeychain::External, external_descriptor)
@ -146,8 +145,6 @@ fn when_apply_contradictory_changesets_they_are_ignored() {
#[test] #[test]
fn test_set_all_derivation_indices() { fn test_set_all_derivation_indices() {
use bdk_chain::indexed_tx_graph::Indexer;
let external_descriptor = parse_descriptor(DESCRIPTORS[0]); let external_descriptor = parse_descriptor(DESCRIPTORS[0]);
let internal_descriptor = parse_descriptor(DESCRIPTORS[1]); let internal_descriptor = parse_descriptor(DESCRIPTORS[1]);
let mut txout_index = let mut txout_index =
@ -169,7 +166,7 @@ fn test_set_all_derivation_indices() {
assert_eq!(txout_index.last_revealed_indices(), derive_to); assert_eq!(txout_index.last_revealed_indices(), derive_to);
assert_eq!( assert_eq!(
txout_index.reveal_to_target_multi(&derive_to), txout_index.reveal_to_target_multi(&derive_to),
keychain::ChangeSet::default(), ChangeSet::default(),
"no changes if we set to the same thing" "no changes if we set to the same thing"
); );
assert_eq!(txout_index.initial_changeset().last_revealed, last_revealed); assert_eq!(txout_index.initial_changeset().last_revealed, last_revealed);
@ -304,7 +301,7 @@ fn test_lookahead() {
], ],
..common::new_tx(external_index) ..common::new_tx(external_index)
}; };
assert_eq!(txout_index.index_tx(&tx), keychain::ChangeSet::default()); assert_eq!(txout_index.index_tx(&tx), ChangeSet::default());
assert_eq!( assert_eq!(
txout_index.last_revealed_index(&TestKeychain::External), txout_index.last_revealed_index(&TestKeychain::External),
Some(last_external_index) Some(last_external_index)
@ -643,14 +640,14 @@ fn insert_descriptor_no_change() {
let mut txout_index = KeychainTxOutIndex::<()>::default(); let mut txout_index = KeychainTxOutIndex::<()>::default();
assert_eq!( assert_eq!(
txout_index.insert_descriptor((), desc.clone()), txout_index.insert_descriptor((), desc.clone()),
Ok(keychain::ChangeSet { Ok(ChangeSet {
keychains_added: [((), desc.clone())].into(), keychains_added: [((), desc.clone())].into(),
last_revealed: Default::default() last_revealed: Default::default()
}), }),
); );
assert_eq!( assert_eq!(
txout_index.insert_descriptor((), desc.clone()), txout_index.insert_descriptor((), desc.clone()),
Ok(keychain::ChangeSet::default()), Ok(ChangeSet::default()),
"inserting the same descriptor for keychain should return an empty changeset", "inserting the same descriptor for keychain should return an empty changeset",
); );
} }

View File

@ -1,4 +1,4 @@
use bdk_chain::{indexed_tx_graph::Indexer, SpkTxOutIndex}; use bdk_chain::{Indexer, SpkTxOutIndex};
use bitcoin::{ use bitcoin::{
absolute, transaction, Amount, OutPoint, ScriptBuf, SignedAmount, Transaction, TxIn, TxOut, absolute, transaction, Amount, OutPoint, ScriptBuf, SignedAmount, Transaction, TxIn, TxOut,
}; };

View File

@ -5,7 +5,7 @@ mod common;
use std::collections::{BTreeSet, HashSet}; use std::collections::{BTreeSet, HashSet};
use bdk_chain::{keychain::Balance, BlockId}; use bdk_chain::{Balance, BlockId};
use bitcoin::{Amount, OutPoint, Script}; use bitcoin::{Amount, OutPoint, Script};
use common::*; use common::*;

View File

@ -1,9 +1,8 @@
use bdk_chain::{ use bdk_chain::{
bitcoin::{hashes::Hash, Address, Amount, ScriptBuf, WScriptHash}, bitcoin::{hashes::Hash, Address, Amount, ScriptBuf, WScriptHash},
keychain::Balance,
local_chain::LocalChain, local_chain::LocalChain,
spk_client::SyncRequest, spk_client::SyncRequest,
ConfirmationTimeHeightAnchor, IndexedTxGraph, SpkTxOutIndex, Balance, ConfirmationTimeHeightAnchor, IndexedTxGraph, SpkTxOutIndex,
}; };
use bdk_electrum::BdkElectrumClient; use bdk_electrum::BdkElectrumClient;
use bdk_testenv::{anyhow, bitcoincore_rpc::RpcApi, TestEnv}; use bdk_testenv::{anyhow, bitcoincore_rpc::RpcApi, TestEnv};

View File

@ -231,7 +231,7 @@ async fn chain_update<A: Anchor>(
} }
/// This performs a full scan to get an update for the [`TxGraph`] and /// This performs a full scan to get an update for the [`TxGraph`] and
/// [`KeychainTxOutIndex`](bdk_chain::keychain::KeychainTxOutIndex). /// [`KeychainTxOutIndex`](bdk_chain::indexer::keychain_txout::KeychainTxOutIndex).
async fn full_scan_for_index_and_graph<K: Ord + Clone + Send>( async fn full_scan_for_index_and_graph<K: Ord + Clone + Send>(
client: &esplora_client::AsyncClient, client: &esplora_client::AsyncClient,
keychain_spks: BTreeMap< keychain_spks: BTreeMap<

View File

@ -213,7 +213,7 @@ fn chain_update<A: Anchor>(
} }
/// This performs a full scan to get an update for the [`TxGraph`] and /// This performs a full scan to get an update for the [`TxGraph`] and
/// [`KeychainTxOutIndex`](bdk_chain::keychain::KeychainTxOutIndex). /// [`KeychainTxOutIndex`](bdk_chain::indexer::keychain_txout::KeychainTxOutIndex).
fn full_scan_for_index_and_graph_blocking<K: Ord + Clone>( fn full_scan_for_index_and_graph_blocking<K: Ord + Clone>(
client: &esplora_client::BlockingClient, client: &esplora_client::BlockingClient,
keychain_spks: BTreeMap<K, impl IntoIterator<Item = Indexed<ScriptBuf>>>, keychain_spks: BTreeMap<K, impl IntoIterator<Item = Indexed<ScriptBuf>>>,

View File

@ -14,7 +14,8 @@ use std::sync::{Arc, Mutex};
use crate::Error; use crate::Error;
use bdk_chain::CombinedChangeSet; use bdk_chain::CombinedChangeSet;
use bdk_chain::{ use bdk_chain::{
indexed_tx_graph, keychain, local_chain, tx_graph, Anchor, Append, DescriptorExt, DescriptorId, indexed_tx_graph, indexer::keychain_txout, local_chain, tx_graph, Anchor, Append,
DescriptorExt, DescriptorId,
}; };
/// Persists data in to a relational schema based [SQLite] database file. /// Persists data in to a relational schema based [SQLite] database file.
@ -187,7 +188,7 @@ where
/// If keychain exists only update last active index. /// If keychain exists only update last active index.
fn insert_keychains( fn insert_keychains(
db_transaction: &rusqlite::Transaction, db_transaction: &rusqlite::Transaction,
tx_graph_changeset: &indexed_tx_graph::ChangeSet<A, keychain::ChangeSet<K>>, tx_graph_changeset: &indexed_tx_graph::ChangeSet<A, keychain_txout::ChangeSet<K>>,
) -> Result<(), Error> { ) -> Result<(), Error> {
let keychain_changeset = &tx_graph_changeset.indexer; let keychain_changeset = &tx_graph_changeset.indexer;
for (keychain, descriptor) in keychain_changeset.keychains_added.iter() { for (keychain, descriptor) in keychain_changeset.keychains_added.iter() {
@ -206,7 +207,7 @@ where
/// Update descriptor last revealed index. /// Update descriptor last revealed index.
fn update_last_revealed( fn update_last_revealed(
db_transaction: &rusqlite::Transaction, db_transaction: &rusqlite::Transaction,
tx_graph_changeset: &indexed_tx_graph::ChangeSet<A, keychain::ChangeSet<K>>, tx_graph_changeset: &indexed_tx_graph::ChangeSet<A, keychain_txout::ChangeSet<K>>,
) -> Result<(), Error> { ) -> Result<(), Error> {
let keychain_changeset = &tx_graph_changeset.indexer; let keychain_changeset = &tx_graph_changeset.indexer;
for (descriptor_id, last_revealed) in keychain_changeset.last_revealed.iter() { for (descriptor_id, last_revealed) in keychain_changeset.last_revealed.iter() {
@ -279,7 +280,7 @@ impl<K, A> Store<K, A> {
/// Error if trying to insert existing txid. /// Error if trying to insert existing txid.
fn insert_txs( fn insert_txs(
db_transaction: &rusqlite::Transaction, db_transaction: &rusqlite::Transaction,
tx_graph_changeset: &indexed_tx_graph::ChangeSet<A, keychain::ChangeSet<K>>, tx_graph_changeset: &indexed_tx_graph::ChangeSet<A, keychain_txout::ChangeSet<K>>,
) -> Result<(), Error> { ) -> Result<(), Error> {
for tx in tx_graph_changeset.graph.txs.iter() { for tx in tx_graph_changeset.graph.txs.iter() {
let insert_tx_stmt = &mut db_transaction let insert_tx_stmt = &mut db_transaction
@ -343,7 +344,7 @@ impl<K, A> Store<K, A> {
/// Error if trying to insert existing outpoint. /// Error if trying to insert existing outpoint.
fn insert_txouts( fn insert_txouts(
db_transaction: &rusqlite::Transaction, db_transaction: &rusqlite::Transaction,
tx_graph_changeset: &indexed_tx_graph::ChangeSet<A, keychain::ChangeSet<K>>, tx_graph_changeset: &indexed_tx_graph::ChangeSet<A, keychain_txout::ChangeSet<K>>,
) -> Result<(), Error> { ) -> Result<(), Error> {
for txout in tx_graph_changeset.graph.txouts.iter() { for txout in tx_graph_changeset.graph.txouts.iter() {
let insert_txout_stmt = &mut db_transaction let insert_txout_stmt = &mut db_transaction
@ -393,7 +394,7 @@ impl<K, A> Store<K, A> {
/// Update transaction last seen times. /// Update transaction last seen times.
fn update_last_seen( fn update_last_seen(
db_transaction: &rusqlite::Transaction, db_transaction: &rusqlite::Transaction,
tx_graph_changeset: &indexed_tx_graph::ChangeSet<A, keychain::ChangeSet<K>>, tx_graph_changeset: &indexed_tx_graph::ChangeSet<A, keychain_txout::ChangeSet<K>>,
) -> Result<(), Error> { ) -> Result<(), Error> {
for tx_last_seen in tx_graph_changeset.graph.last_seen.iter() { for tx_last_seen in tx_graph_changeset.graph.last_seen.iter() {
let insert_or_update_tx_stmt = &mut db_transaction let insert_or_update_tx_stmt = &mut db_transaction
@ -418,7 +419,7 @@ where
/// Insert anchors. /// Insert anchors.
fn insert_anchors( fn insert_anchors(
db_transaction: &rusqlite::Transaction, db_transaction: &rusqlite::Transaction,
tx_graph_changeset: &indexed_tx_graph::ChangeSet<A, keychain::ChangeSet<K>>, tx_graph_changeset: &indexed_tx_graph::ChangeSet<A, keychain_txout::ChangeSet<K>>,
) -> Result<(), Error> { ) -> Result<(), Error> {
// serde_json::to_string // serde_json::to_string
for anchor in tx_graph_changeset.graph.anchors.iter() { for anchor in tx_graph_changeset.graph.anchors.iter() {
@ -514,12 +515,12 @@ where
last_seen, last_seen,
}; };
let indexer: keychain::ChangeSet<K> = keychain::ChangeSet { let indexer = keychain_txout::ChangeSet {
keychains_added, keychains_added,
last_revealed, last_revealed,
}; };
let indexed_tx_graph: indexed_tx_graph::ChangeSet<A, keychain::ChangeSet<K>> = let indexed_tx_graph: indexed_tx_graph::ChangeSet<A, keychain_txout::ChangeSet<K>> =
indexed_tx_graph::ChangeSet { graph, indexer }; indexed_tx_graph::ChangeSet { graph, indexer };
if network.is_none() && chain.is_empty() && indexed_tx_graph.is_empty() { if network.is_none() && chain.is_empty() && indexed_tx_graph.is_empty() {
@ -547,7 +548,7 @@ mod test {
use bdk_chain::miniscript::Descriptor; use bdk_chain::miniscript::Descriptor;
use bdk_chain::CombinedChangeSet; use bdk_chain::CombinedChangeSet;
use bdk_chain::{ use bdk_chain::{
indexed_tx_graph, keychain, tx_graph, BlockId, ConfirmationHeightAnchor, indexed_tx_graph, tx_graph, BlockId, ConfirmationHeightAnchor,
ConfirmationTimeHeightAnchor, DescriptorExt, ConfirmationTimeHeightAnchor, DescriptorExt,
}; };
use std::str::FromStr; use std::str::FromStr;
@ -684,12 +685,12 @@ mod test {
.into(), .into(),
}; };
let keychain_changeset = keychain::ChangeSet { let keychain_changeset = keychain_txout::ChangeSet {
keychains_added: [(ext_keychain, ext_desc), (int_keychain, int_desc)].into(), keychains_added: [(ext_keychain, ext_desc), (int_keychain, int_desc)].into(),
last_revealed: [(ext_desc_id, 124), (int_desc_id, 421)].into(), last_revealed: [(ext_desc_id, 124), (int_desc_id, 421)].into(),
}; };
let graph_changeset: indexed_tx_graph::ChangeSet<A, keychain::ChangeSet<Keychain>> = let graph_changeset: indexed_tx_graph::ChangeSet<A, keychain_txout::ChangeSet<Keychain>> =
indexed_tx_graph::ChangeSet { indexed_tx_graph::ChangeSet {
graph: tx_graph_changeset, graph: tx_graph_changeset,
indexer: keychain_changeset, indexer: keychain_changeset,
@ -712,10 +713,10 @@ mod test {
last_seen: [(tx2.compute_txid(), 1708919121)].into(), last_seen: [(tx2.compute_txid(), 1708919121)].into(),
}; };
let graph_changeset2: indexed_tx_graph::ChangeSet<A, keychain::ChangeSet<Keychain>> = let graph_changeset2: indexed_tx_graph::ChangeSet<A, keychain_txout::ChangeSet<Keychain>> =
indexed_tx_graph::ChangeSet { indexed_tx_graph::ChangeSet {
graph: tx_graph_changeset2, graph: tx_graph_changeset2,
indexer: keychain::ChangeSet::default(), indexer: keychain_txout::ChangeSet::default(),
}; };
changesets.push(CombinedChangeSet { changesets.push(CombinedChangeSet {
@ -732,10 +733,10 @@ mod test {
last_seen: BTreeMap::default(), last_seen: BTreeMap::default(),
}; };
let graph_changeset3: indexed_tx_graph::ChangeSet<A, keychain::ChangeSet<Keychain>> = let graph_changeset3: indexed_tx_graph::ChangeSet<A, keychain_txout::ChangeSet<Keychain>> =
indexed_tx_graph::ChangeSet { indexed_tx_graph::ChangeSet {
graph: tx_graph_changeset3, graph: tx_graph_changeset3,
indexer: keychain::ChangeSet::default(), indexer: keychain_txout::ChangeSet::default(),
}; };
changesets.push(CombinedChangeSet { changesets.push(CombinedChangeSet {

View File

@ -19,10 +19,10 @@ use alloc::{
sync::Arc, sync::Arc,
vec::Vec, vec::Vec,
}; };
pub use bdk_chain::keychain::Balance; pub use bdk_chain::Balance;
use bdk_chain::{ use bdk_chain::{
indexed_tx_graph, indexed_tx_graph,
keychain::KeychainTxOutIndex, indexer::keychain_txout::KeychainTxOutIndex,
local_chain::{ local_chain::{
self, ApplyHeaderError, CannotConnectError, CheckPoint, CheckPointIter, LocalChain, self, ApplyHeaderError, CannotConnectError, CheckPoint, CheckPointIter, LocalChain,
}, },
@ -112,7 +112,7 @@ pub struct Wallet {
/// An update to [`Wallet`]. /// An update to [`Wallet`].
/// ///
/// It updates [`bdk_chain::keychain::KeychainTxOutIndex`], [`bdk_chain::TxGraph`] and [`local_chain::LocalChain`] atomically. /// It updates [`KeychainTxOutIndex`], [`bdk_chain::TxGraph`] and [`local_chain::LocalChain`] atomically.
#[derive(Debug, Clone, Default)] #[derive(Debug, Clone, Default)]
pub struct Update { pub struct Update {
/// Contains the last active derivation indices per keychain (`K`), which is used to update the /// Contains the last active derivation indices per keychain (`K`), which is used to update the
@ -2451,7 +2451,7 @@ fn create_signers<E: IntoWalletDescriptor>(
let _ = index let _ = index
.insert_descriptor(KeychainKind::Internal, descriptor) .insert_descriptor(KeychainKind::Internal, descriptor)
.map_err(|e| { .map_err(|e| {
use bdk_chain::keychain::InsertDescriptorError; use bdk_chain::indexer::keychain_txout::InsertDescriptorError;
match e { match e {
InsertDescriptorError::DescriptorAlreadyAssigned { .. } => { InsertDescriptorError::DescriptorAlreadyAssigned { .. } => {
crate::descriptor::error::Error::ExternalAndInternalAreTheSame crate::descriptor::error::Error::ExternalAndInternalAreTheSame

View File

@ -1,13 +1,12 @@
#![allow(unused)] #![allow(unused)]
use bdk_chain::indexed_tx_graph::Indexer;
use bdk_chain::{BlockId, ConfirmationTime, ConfirmationTimeHeightAnchor, TxGraph}; use bdk_chain::{BlockId, ConfirmationTime, ConfirmationTimeHeightAnchor, TxGraph};
use bdk_wallet::wallet::Update; use bdk_wallet::{
use bdk_wallet::{KeychainKind, LocalOutput, Wallet}; wallet::{Update, Wallet},
use bitcoin::hashes::Hash; KeychainKind, LocalOutput,
};
use bitcoin::{ use bitcoin::{
transaction, Address, Amount, BlockHash, FeeRate, Network, OutPoint, Transaction, TxIn, TxOut, hashes::Hash, transaction, Address, Amount, BlockHash, FeeRate, Network, OutPoint, Transaction,
Txid, TxIn, TxOut, Txid,
}; };
use std::str::FromStr; use std::str::FromStr;

View File

@ -13,7 +13,8 @@ use bdk_bitcoind_rpc::{
}; };
use bdk_chain::{ use bdk_chain::{
bitcoin::{constants::genesis_block, Block, Transaction}, bitcoin::{constants::genesis_block, Block, Transaction},
indexed_tx_graph, keychain, indexed_tx_graph,
indexer::keychain_txout,
local_chain::{self, LocalChain}, local_chain::{self, LocalChain},
Append, ConfirmationTimeHeightAnchor, IndexedTxGraph, Append, ConfirmationTimeHeightAnchor, IndexedTxGraph,
}; };
@ -37,7 +38,7 @@ const DB_COMMIT_DELAY: Duration = Duration::from_secs(60);
type ChangeSet = ( type ChangeSet = (
local_chain::ChangeSet, local_chain::ChangeSet,
indexed_tx_graph::ChangeSet<ConfirmationTimeHeightAnchor, keychain::ChangeSet<Keychain>>, indexed_tx_graph::ChangeSet<ConfirmationTimeHeightAnchor, keychain_txout::ChangeSet<Keychain>>,
); );
#[derive(Debug)] #[derive(Debug)]

View File

@ -14,7 +14,7 @@ use bdk_chain::{
transaction, Address, Amount, Network, Sequence, Transaction, TxIn, TxOut, transaction, Address, Amount, Network, Sequence, Transaction, TxIn, TxOut,
}, },
indexed_tx_graph::{self, IndexedTxGraph}, indexed_tx_graph::{self, IndexedTxGraph},
keychain::{self, KeychainTxOutIndex}, indexer::keychain_txout::{self, KeychainTxOutIndex},
local_chain, local_chain,
miniscript::{ miniscript::{
descriptor::{DescriptorSecretKey, KeyMap}, descriptor::{DescriptorSecretKey, KeyMap},
@ -30,7 +30,7 @@ use clap::{Parser, Subcommand};
pub type KeychainTxGraph<A> = IndexedTxGraph<A, KeychainTxOutIndex<Keychain>>; pub type KeychainTxGraph<A> = IndexedTxGraph<A, KeychainTxOutIndex<Keychain>>;
pub type KeychainChangeSet<A> = ( pub type KeychainChangeSet<A> = (
local_chain::ChangeSet, local_chain::ChangeSet,
indexed_tx_graph::ChangeSet<A, keychain::ChangeSet<Keychain>>, indexed_tx_graph::ChangeSet<A, keychain_txout::ChangeSet<Keychain>>,
); );
#[derive(Parser)] #[derive(Parser)]
@ -191,7 +191,7 @@ impl core::fmt::Display for Keychain {
} }
pub struct CreateTxChange { pub struct CreateTxChange {
pub index_changeset: keychain::ChangeSet<Keychain>, pub index_changeset: keychain_txout::ChangeSet<Keychain>,
pub change_keychain: Keychain, pub change_keychain: Keychain,
pub index: u32, pub index: u32,
} }
@ -207,7 +207,7 @@ pub fn create_tx<A: Anchor, O: ChainOracle>(
where where
O::Error: std::error::Error + Send + Sync + 'static, O::Error: std::error::Error + Send + Sync + 'static,
{ {
let mut changeset = keychain::ChangeSet::default(); let mut changeset = keychain_txout::ChangeSet::default();
let assets = bdk_tmp_plan::Assets { let assets = bdk_tmp_plan::Assets {
keys: keymap.iter().map(|(pk, _)| pk.clone()).collect(), keys: keymap.iter().map(|(pk, _)| pk.clone()).collect(),

View File

@ -7,7 +7,7 @@ use bdk_chain::{
bitcoin::{constants::genesis_block, Address, Network, Txid}, bitcoin::{constants::genesis_block, Address, Network, Txid},
collections::BTreeSet, collections::BTreeSet,
indexed_tx_graph::{self, IndexedTxGraph}, indexed_tx_graph::{self, IndexedTxGraph},
keychain, indexer::keychain_txout,
local_chain::{self, LocalChain}, local_chain::{self, LocalChain},
spk_client::{FullScanRequest, SyncRequest}, spk_client::{FullScanRequest, SyncRequest},
Append, ConfirmationHeightAnchor, Append, ConfirmationHeightAnchor,
@ -100,7 +100,7 @@ pub struct ScanOptions {
type ChangeSet = ( type ChangeSet = (
local_chain::ChangeSet, local_chain::ChangeSet,
indexed_tx_graph::ChangeSet<ConfirmationHeightAnchor, keychain::ChangeSet<Keychain>>, indexed_tx_graph::ChangeSet<ConfirmationHeightAnchor, keychain_txout::ChangeSet<Keychain>>,
); );
fn main() -> anyhow::Result<()> { fn main() -> anyhow::Result<()> {

View File

@ -7,7 +7,7 @@ use std::{
use bdk_chain::{ use bdk_chain::{
bitcoin::{constants::genesis_block, Address, Network, Txid}, bitcoin::{constants::genesis_block, Address, Network, Txid},
indexed_tx_graph::{self, IndexedTxGraph}, indexed_tx_graph::{self, IndexedTxGraph},
keychain, indexer::keychain_txout,
local_chain::{self, LocalChain}, local_chain::{self, LocalChain},
spk_client::{FullScanRequest, SyncRequest}, spk_client::{FullScanRequest, SyncRequest},
Append, ConfirmationTimeHeightAnchor, Append, ConfirmationTimeHeightAnchor,
@ -26,7 +26,7 @@ const DB_PATH: &str = ".bdk_esplora_example.db";
type ChangeSet = ( type ChangeSet = (
local_chain::ChangeSet, local_chain::ChangeSet,
indexed_tx_graph::ChangeSet<ConfirmationTimeHeightAnchor, keychain::ChangeSet<Keychain>>, indexed_tx_graph::ChangeSet<ConfirmationTimeHeightAnchor, keychain_txout::ChangeSet<Keychain>>,
); );
#[derive(Subcommand, Debug, Clone)] #[derive(Subcommand, Debug, Clone)]