Write more docs
This commit is contained in:
@@ -22,6 +22,58 @@
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
// SOFTWARE.
|
||||
|
||||
//! Address validation callbacks
|
||||
//!
|
||||
//! The typical usage of those callbacks is for displaying the newly-generated address on a
|
||||
//! hardware wallet, so that the user can cross-check its correctness.
|
||||
//!
|
||||
//! More generally speaking though, these callbacks can also be used to "do something" every time
|
||||
//! an address is generated, without necessarily checking or validating it.
|
||||
//!
|
||||
//! An address validator can be attached to a [`Wallet`](super::Wallet) by using the
|
||||
//! [`Wallet::add_address_validator`](super::Wallet::add_address_validator) method, and
|
||||
//! whenever a new address is generated (either explicitly by the user with
|
||||
//! [`Wallet::get_new_address`](super::Wallet::get_new_address) or internally to create a change
|
||||
//! address) all the attached validators will be polled, in sequence. All of them must complete
|
||||
//! successfully to continue.
|
||||
//!
|
||||
//! ## Example
|
||||
//!
|
||||
//! ```
|
||||
//! # use std::sync::Arc;
|
||||
//! # use bitcoin::*;
|
||||
//! # use magical_bitcoin_wallet::address_validator::*;
|
||||
//! # use magical_bitcoin_wallet::database::*;
|
||||
//! # use magical_bitcoin_wallet::*;
|
||||
//! struct PrintAddressAndContinue;
|
||||
//!
|
||||
//! impl AddressValidator for PrintAddressAndContinue {
|
||||
//! fn validate(
|
||||
//! &self,
|
||||
//! script_type: ScriptType,
|
||||
//! hd_keypaths: &HDKeyPaths,
|
||||
//! script: &Script
|
||||
//! ) -> Result<(), AddressValidatorError> {
|
||||
//! let address = Address::from_script(script, Network::Testnet)
|
||||
//! .as_ref()
|
||||
//! .map(Address::to_string)
|
||||
//! .unwrap_or(script.to_string());
|
||||
//! println!("New address of type {:?}: {}", script_type, address);
|
||||
//! println!("HD keypaths: {:#?}", hd_keypaths);
|
||||
//!
|
||||
//! Ok(())
|
||||
//! }
|
||||
//! }
|
||||
//!
|
||||
//! let descriptor = "wpkh(tpubD6NzVbkrYhZ4Xferm7Pz4VnjdcDPFyjVu5K4iZXQ4pVN8Cks4pHVowTBXBKRhX64pkRyJZJN5xAKj4UDNnLPb5p2sSKXhewoYx5GbTdUFWq/*)";
|
||||
//! let mut wallet: OfflineWallet<_> = Wallet::new_offline(descriptor, None, Network::Testnet, MemoryDatabase::default())?;
|
||||
//! wallet.add_address_validator(Arc::new(Box::new(PrintAddressAndContinue)));
|
||||
//!
|
||||
//! let address = wallet.get_new_address()?;
|
||||
//! println!("Address: {}", address);
|
||||
//! # Ok::<(), magical_bitcoin_wallet::Error>(())
|
||||
//! ```
|
||||
|
||||
use std::fmt;
|
||||
|
||||
use bitcoin::Script;
|
||||
@@ -29,12 +81,14 @@ use bitcoin::Script;
|
||||
use crate::descriptor::HDKeyPaths;
|
||||
use crate::types::ScriptType;
|
||||
|
||||
/// Errors that can be returned to fail the validation of an address
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum AddressValidatorError {
|
||||
UserRejected,
|
||||
ConnectionError,
|
||||
TimeoutError,
|
||||
InvalidScript,
|
||||
Message(String),
|
||||
}
|
||||
|
||||
impl fmt::Display for AddressValidatorError {
|
||||
@@ -45,7 +99,15 @@ impl fmt::Display for AddressValidatorError {
|
||||
|
||||
impl std::error::Error for AddressValidatorError {}
|
||||
|
||||
/// Trait to build address validators
|
||||
///
|
||||
/// All the address validators attached to a wallet with [`Wallet::add_address_validator`](super::Wallet::add_address_validator) will be polled
|
||||
/// every time an address (external or internal) is generated by the wallet. Errors returned in the
|
||||
/// validator will be propagated up to the original caller that triggered the address generation.
|
||||
///
|
||||
/// For a usage example see [this module](crate::address_validator)'s documentation.
|
||||
pub trait AddressValidator {
|
||||
/// Validate or inspect an address
|
||||
fn validate(
|
||||
&self,
|
||||
script_type: ScriptType,
|
||||
|
||||
@@ -22,22 +22,122 @@
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
// SOFTWARE.
|
||||
|
||||
//! Coin selection
|
||||
//!
|
||||
//! This module provides the trait [`CoinSelectionAlgorithm`] that can be implemented to
|
||||
//! define custom coin selection algorithms.
|
||||
//!
|
||||
//! The coin selection algorithm is not globally part of a [`Wallet`](super::Wallet), instead it
|
||||
//! is selected whenever a [`Wallet::create_tx`](super::Wallet::create_tx) call is made, through
|
||||
//! the use of the [`TxBuilder`] structure, specifically with
|
||||
//! [`TxBuilder::coin_selection`](super::tx_builder::TxBuilder::coin_selection) method.
|
||||
//!
|
||||
//! The [`DefaultCoinSelectionAlgorithm`] selects the default coin selection algorithm that
|
||||
//! [`TxBuilder`] uses, if it's not explicitly overridden.
|
||||
//!
|
||||
//! [`TxBuilder`]: super::tx_builder::TxBuilder
|
||||
//!
|
||||
//! ## Example
|
||||
//!
|
||||
//! ```no_run
|
||||
//! # use std::str::FromStr;
|
||||
//! # use bitcoin::*;
|
||||
//! # use bitcoin::consensus::serialize;
|
||||
//! # use magical_bitcoin_wallet::wallet::coin_selection::*;
|
||||
//! # use magical_bitcoin_wallet::*;
|
||||
//! #[derive(Debug)]
|
||||
//! struct AlwaysSpendEverything;
|
||||
//!
|
||||
//! impl CoinSelectionAlgorithm for AlwaysSpendEverything {
|
||||
//! fn coin_select(
|
||||
//! &self,
|
||||
//! utxos: Vec<UTXO>,
|
||||
//! _use_all_utxos: bool,
|
||||
//! fee_rate: FeeRate,
|
||||
//! amount_needed: u64,
|
||||
//! input_witness_weight: usize,
|
||||
//! fee_amount: f32,
|
||||
//! ) -> Result<CoinSelectionResult, magical_bitcoin_wallet::Error> {
|
||||
//! let selected_amount = utxos.iter().fold(0, |acc, utxo| acc + utxo.txout.value);
|
||||
//! let all_utxos_selected = utxos
|
||||
//! .into_iter()
|
||||
//! .map(|utxo| {
|
||||
//! (
|
||||
//! TxIn {
|
||||
//! previous_output: utxo.outpoint,
|
||||
//! ..Default::default()
|
||||
//! },
|
||||
//! utxo.txout.script_pubkey,
|
||||
//! )
|
||||
//! })
|
||||
//! .collect::<Vec<_>>();
|
||||
//! let additional_weight = all_utxos_selected.iter().fold(0, |acc, (txin, _)| {
|
||||
//! acc + serialize(txin).len() * 4 + input_witness_weight
|
||||
//! });
|
||||
//! let additional_fees = additional_weight as f32 * fee_rate.as_sat_vb() / 4.0;
|
||||
//!
|
||||
//! if (fee_amount + additional_fees).ceil() as u64 + amount_needed > selected_amount {
|
||||
//! return Err(magical_bitcoin_wallet::Error::InsufficientFunds);
|
||||
//! }
|
||||
//!
|
||||
//! Ok(CoinSelectionResult {
|
||||
//! txin: all_utxos_selected,
|
||||
//! selected_amount,
|
||||
//! fee_amount: fee_amount + additional_fees,
|
||||
//! })
|
||||
//! }
|
||||
//! }
|
||||
//!
|
||||
//! # let wallet: OfflineWallet<_> = Wallet::new_offline("", None, Network::Testnet, magical_bitcoin_wallet::database::MemoryDatabase::default())?;
|
||||
//! // create wallet, sync, ...
|
||||
//!
|
||||
//! let to_address = Address::from_str("2N4eQYCbKUHCCTUjBJeHcJp9ok6J2GZsTDt").unwrap();
|
||||
//! let (psbt, details) = wallet.create_tx(
|
||||
//! TxBuilder::with_recipients(vec![(to_address, 50_000)])
|
||||
//! .coin_selection(AlwaysSpendEverything),
|
||||
//! )?;
|
||||
//!
|
||||
//! // inspect, sign, broadcast, ...
|
||||
//!
|
||||
//! # Ok::<(), magical_bitcoin_wallet::Error>(())
|
||||
//! ```
|
||||
|
||||
use bitcoin::consensus::encode::serialize;
|
||||
use bitcoin::{Script, TxIn};
|
||||
|
||||
use crate::error::Error;
|
||||
use crate::types::{FeeRate, UTXO};
|
||||
|
||||
/// Default coin selection algorithm used by [`TxBuilder`](super::tx_builder::TxBuilder) if not
|
||||
/// overridden
|
||||
pub type DefaultCoinSelectionAlgorithm = DumbCoinSelection;
|
||||
|
||||
/// Result of a successful coin selection
|
||||
#[derive(Debug)]
|
||||
pub struct CoinSelectionResult {
|
||||
/// List of inputs to use, with the respective previous script_pubkey
|
||||
pub txin: Vec<(TxIn, Script)>,
|
||||
/// Sum of the selected inputs' value
|
||||
pub selected_amount: u64,
|
||||
/// Total fee amount in satoshi
|
||||
pub fee_amount: f32,
|
||||
}
|
||||
|
||||
/// Trait for generalized coin selection algorithms
|
||||
///
|
||||
/// This trait can be implemented to make the [`Wallet`](super::Wallet) use a customized coin
|
||||
/// selection algorithm when it creates transactions.
|
||||
///
|
||||
/// For an example see [this module](crate::wallet::coin_selection)'s documentation.
|
||||
pub trait CoinSelectionAlgorithm: std::fmt::Debug {
|
||||
/// Perform the coin selection
|
||||
///
|
||||
/// - `utxos`: the list of spendable UTXOs
|
||||
/// - `use_all_utxos`: if true all utxos should be spent unconditionally
|
||||
/// - `fee_rate`: fee rate to use
|
||||
/// - `amount_needed`: the amount in satoshi to select
|
||||
/// - `input_witness_weight`: the weight of an input's witness to keep into account for the fees
|
||||
/// - `fee_amount`: the amount of fees in satoshi already accumulated from adding outputs
|
||||
fn coin_select(
|
||||
&self,
|
||||
utxos: Vec<UTXO>,
|
||||
@@ -49,6 +149,10 @@ pub trait CoinSelectionAlgorithm: std::fmt::Debug {
|
||||
) -> Result<CoinSelectionResult, Error>;
|
||||
}
|
||||
|
||||
/// Simple and dumb coin selection
|
||||
///
|
||||
/// This coin selection algorithm sorts the available UTXOs by value and then picks them starting
|
||||
/// from the largest ones until the required amount is reached.
|
||||
#[derive(Debug, Default)]
|
||||
pub struct DumbCoinSelection;
|
||||
|
||||
|
||||
@@ -200,7 +200,7 @@ where
|
||||
return Err(Error::SpendingPolicyRequired);
|
||||
}
|
||||
let requirements =
|
||||
policy.get_requirements(builder.policy_path.as_ref().unwrap_or(&BTreeMap::new()))?;
|
||||
policy.get_condition(builder.policy_path.as_ref().unwrap_or(&BTreeMap::new()))?;
|
||||
debug!("requirements: {:?}", requirements);
|
||||
|
||||
let version = match builder.version {
|
||||
|
||||
Reference in New Issue
Block a user