-
Notifications
You must be signed in to change notification settings - Fork 412
Introduce block-by-block API to bdk::Wallet and add RPC wallet example
#1172
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
evanlinjin
merged 8 commits into
bitcoindevkit:master
from
vladimirfomene:implement_rpc_wallet
Jan 19, 2024
Merged
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
2b61a12
feat(chain): add `CheckPoint::from_block_ids` convenience method
evanlinjin d3e5095
feat(chain): add `apply_header..` methods to `LocalChain`
evanlinjin 9467cad
feat(wallet): introduce block-by-block api
vladimirfomene 8f2d4d9
test(chain): `LocalChain` test for update that is shorter than original
evanlinjin e0512ac
feat(bitcoind_rpc)!: emissions include checkpoint and connected_to data
evanlinjin a7d01dc
feat(chain)!: make `IndexedTxGraph::apply_block_relevant` more efficient
evanlinjin 8ec65f0
feat(example): add RPC wallet example
vladimirfomene a4f28c0
chore: improve LocalChain::apply_header_connected_to doc
LLFourn File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -23,16 +23,18 @@ pub use bdk_chain::keychain::Balance; | |
| use bdk_chain::{ | ||
| indexed_tx_graph, | ||
| keychain::{self, KeychainTxOutIndex}, | ||
| local_chain::{self, CannotConnectError, CheckPoint, CheckPointIter, LocalChain}, | ||
| local_chain::{ | ||
| self, ApplyHeaderError, CannotConnectError, CheckPoint, CheckPointIter, LocalChain, | ||
| }, | ||
| tx_graph::{CanonicalTx, TxGraph}, | ||
| Append, BlockId, ChainPosition, ConfirmationTime, ConfirmationTimeHeightAnchor, FullTxOut, | ||
| IndexedTxGraph, Persist, PersistBackend, | ||
| }; | ||
| use bitcoin::secp256k1::{All, Secp256k1}; | ||
| use bitcoin::sighash::{EcdsaSighashType, TapSighashType}; | ||
| use bitcoin::{ | ||
| absolute, Address, Network, OutPoint, Script, ScriptBuf, Sequence, Transaction, TxOut, Txid, | ||
| Weight, Witness, | ||
| absolute, Address, Block, Network, OutPoint, Script, ScriptBuf, Sequence, Transaction, TxOut, | ||
| Txid, Weight, Witness, | ||
| }; | ||
| use bitcoin::{consensus::encode::serialize, BlockHash}; | ||
| use bitcoin::{constants::genesis_block, psbt}; | ||
|
|
@@ -428,6 +430,55 @@ pub enum InsertTxError { | |
| }, | ||
| } | ||
|
|
||
| impl fmt::Display for InsertTxError { | ||
| fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { | ||
| match self { | ||
| InsertTxError::ConfirmationHeightCannotBeGreaterThanTip { | ||
| tip_height, | ||
| tx_height, | ||
| } => { | ||
| write!(f, "cannot insert tx with confirmation height ({}) higher than internal tip height ({})", tx_height, tip_height) | ||
| } | ||
| } | ||
| } | ||
| } | ||
|
|
||
| #[cfg(feature = "std")] | ||
| impl std::error::Error for InsertTxError {} | ||
|
|
||
| /// An error that may occur when applying a block to [`Wallet`]. | ||
| #[derive(Debug)] | ||
| pub enum ApplyBlockError { | ||
| /// Occurs when the update chain cannot connect with original chain. | ||
| CannotConnect(CannotConnectError), | ||
| /// Occurs when the `connected_to` hash does not match the hash derived from `block`. | ||
| UnexpectedConnectedToHash { | ||
| /// Block hash of `connected_to`. | ||
| connected_to_hash: BlockHash, | ||
| /// Expected block hash of `connected_to`, as derived from `block`. | ||
| expected_hash: BlockHash, | ||
| }, | ||
| } | ||
|
|
||
| impl fmt::Display for ApplyBlockError { | ||
| fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { | ||
| match self { | ||
| ApplyBlockError::CannotConnect(err) => err.fmt(f), | ||
| ApplyBlockError::UnexpectedConnectedToHash { | ||
| expected_hash: block_hash, | ||
| connected_to_hash: checkpoint_hash, | ||
| } => write!( | ||
| f, | ||
| "`connected_to` hash {} differs from the expected hash {} (which is derived from `block`)", | ||
| checkpoint_hash, block_hash | ||
| ), | ||
| } | ||
| } | ||
| } | ||
|
|
||
| #[cfg(feature = "std")] | ||
| impl std::error::Error for ApplyBlockError {} | ||
|
|
||
| impl<D> Wallet<D> { | ||
| /// Initialize an empty [`Wallet`]. | ||
| pub fn new<E: IntoWalletDescriptor>( | ||
|
|
@@ -2302,7 +2353,7 @@ impl<D> Wallet<D> { | |
| self.persist.commit().map(|c| c.is_some()) | ||
| } | ||
|
|
||
| /// Returns the changes that will be staged with the next call to [`commit`]. | ||
| /// Returns the changes that will be committed with the next call to [`commit`]. | ||
| /// | ||
| /// [`commit`]: Self::commit | ||
| pub fn staged(&self) -> &ChangeSet | ||
|
|
@@ -2326,6 +2377,86 @@ impl<D> Wallet<D> { | |
| pub fn local_chain(&self) -> &LocalChain { | ||
| &self.chain | ||
| } | ||
|
|
||
| /// Introduces a `block` of `height` to the wallet, and tries to connect it to the | ||
| /// `prev_blockhash` of the block's header. | ||
| /// | ||
| /// This is a convenience method that is equivalent to calling [`apply_block_connected_to`] | ||
| /// with `prev_blockhash` and `height-1` as the `connected_to` parameter. | ||
| /// | ||
| /// [`apply_block_connected_to`]: Self::apply_block_connected_to | ||
| pub fn apply_block(&mut self, block: &Block, height: u32) -> Result<(), CannotConnectError> | ||
| where | ||
| D: PersistBackend<ChangeSet>, | ||
| { | ||
| let connected_to = match height.checked_sub(1) { | ||
| Some(prev_height) => BlockId { | ||
| height: prev_height, | ||
| hash: block.header.prev_blockhash, | ||
| }, | ||
| None => BlockId { | ||
| height, | ||
| hash: block.block_hash(), | ||
| }, | ||
| }; | ||
| self.apply_block_connected_to(block, height, connected_to) | ||
| .map_err(|err| match err { | ||
| ApplyHeaderError::InconsistentBlocks => { | ||
| unreachable!("connected_to is derived from the block so must be consistent") | ||
| } | ||
| ApplyHeaderError::CannotConnect(err) => err, | ||
| }) | ||
| } | ||
vladimirfomene marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| /// Applies relevant transactions from `block` of `height` to the wallet, and connects the | ||
| /// block to the internal chain. | ||
| /// | ||
| /// The `connected_to` parameter informs the wallet how this block connects to the internal | ||
| /// [`LocalChain`]. Relevant transactions are filtered from the `block` and inserted into the | ||
| /// internal [`TxGraph`]. | ||
| pub fn apply_block_connected_to( | ||
| &mut self, | ||
| block: &Block, | ||
| height: u32, | ||
| connected_to: BlockId, | ||
| ) -> Result<(), ApplyHeaderError> | ||
| where | ||
| D: PersistBackend<ChangeSet>, | ||
evanlinjin marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| { | ||
| let mut changeset = ChangeSet::default(); | ||
| changeset.append( | ||
| self.chain | ||
| .apply_header_connected_to(&block.header, height, connected_to)? | ||
| .into(), | ||
| ); | ||
| changeset.append( | ||
| self.indexed_graph | ||
| .apply_block_relevant(block, height) | ||
| .into(), | ||
| ); | ||
| self.persist.stage(changeset); | ||
| Ok(()) | ||
| } | ||
|
|
||
| /// Apply relevant unconfirmed transactions to the wallet. | ||
| /// | ||
| /// Transactions that are not relevant are filtered out. | ||
| /// | ||
| /// This method takes in an iterator of `(tx, last_seen)` where `last_seen` is the timestamp of | ||
| /// when the transaction was last seen in the mempool. This is used for conflict resolution | ||
| /// when there is conflicting unconfirmed transactions. The transaction with the later | ||
| /// `last_seen` is prioritied. | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. typo: prioritied |
||
| pub fn apply_unconfirmed_txs<'t>( | ||
| &mut self, | ||
| unconfirmed_txs: impl IntoIterator<Item = (&'t Transaction, u64)>, | ||
| ) where | ||
| D: PersistBackend<ChangeSet>, | ||
| { | ||
| let indexed_graph_changeset = self | ||
| .indexed_graph | ||
| .batch_insert_relevant_unconfirmed(unconfirmed_txs); | ||
| self.persist.stage(ChangeSet::from(indexed_graph_changeset)); | ||
| } | ||
| } | ||
|
|
||
| impl<D> AsRef<bdk_chain::tx_graph::TxGraph<ConfirmationTimeHeightAnchor>> for Wallet<D> { | ||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Did you intend to use this for either
apply_blockorapply_block_connected_to?