Merge commit 'refs/pull/228/head' of github.com:bitcoindevkit/bdk

This commit is contained in:
Alekos Filini 2020-12-15 14:33:59 +01:00
commit 6d9472793c
No known key found for this signature in database
GPG Key ID: 5E8AFC3034FDFA4F
19 changed files with 334 additions and 345 deletions

View File

@ -16,6 +16,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
#### Changed #### Changed
- Rename the library to `bdk` - Rename the library to `bdk`
- Rename `ScriptType` to `KeychainKind`
- Prettify README examples on github - Prettify README examples on github
- Change CI to github actions - Change CI to github actions
- Bump rust-bitcoin to 0.25, fix Cargo dependencies - Bump rust-bitcoin to 0.25, fix Cargo dependencies

View File

@ -28,7 +28,7 @@ use bdk::bitcoin;
use bdk::database::MemoryDatabase; use bdk::database::MemoryDatabase;
use bdk::descriptor::HDKeyPaths; use bdk::descriptor::HDKeyPaths;
use bdk::wallet::address_validator::{AddressValidator, AddressValidatorError}; use bdk::wallet::address_validator::{AddressValidator, AddressValidatorError};
use bdk::ScriptType; use bdk::KeychainKind;
use bdk::{OfflineWallet, Wallet}; use bdk::{OfflineWallet, Wallet};
use bitcoin::hashes::hex::FromHex; use bitcoin::hashes::hex::FromHex;
@ -39,7 +39,7 @@ struct DummyValidator;
impl AddressValidator for DummyValidator { impl AddressValidator for DummyValidator {
fn validate( fn validate(
&self, &self,
script_type: ScriptType, keychain: KeychainKind,
hd_keypaths: &HDKeyPaths, hd_keypaths: &HDKeyPaths,
script: &Script, script: &Script,
) -> Result<(), AddressValidatorError> { ) -> Result<(), AddressValidatorError> {
@ -50,7 +50,7 @@ impl AddressValidator for DummyValidator {
println!( println!(
"Validating `{:?}` {} address, script: {}", "Validating `{:?}` {} address, script: {}",
script_type, path, script keychain, path, script
); );
Ok(()) Ok(())

View File

@ -40,7 +40,7 @@ use miniscript::policy::Concrete;
use miniscript::Descriptor; use miniscript::Descriptor;
use bdk::database::memory::MemoryDatabase; use bdk::database::memory::MemoryDatabase;
use bdk::{OfflineWallet, ScriptType, Wallet}; use bdk::{KeychainKind, OfflineWallet, Wallet};
fn main() { fn main() {
env_logger::init_from_env( env_logger::init_from_env(
@ -104,7 +104,7 @@ fn main() {
info!("... First address: {}", wallet.get_new_address().unwrap()); info!("... First address: {}", wallet.get_new_address().unwrap());
if matches.is_present("parsed_policy") { if matches.is_present("parsed_policy") {
let spending_policy = wallet.policies(ScriptType::External).unwrap(); let spending_policy = wallet.policies(KeychainKind::External).unwrap();
info!( info!(
"... Spending policy:\n{}", "... Spending policy:\n{}",
serde_json::to_string_pretty(&spending_policy).unwrap() serde_json::to_string_pretty(&spending_policy).unwrap()

View File

@ -81,7 +81,7 @@ mod sync;
use super::{Blockchain, Capability, ConfigurableBlockchain, Progress}; use super::{Blockchain, Capability, ConfigurableBlockchain, Progress};
use crate::database::{BatchDatabase, BatchOperations, DatabaseUtils}; use crate::database::{BatchDatabase, BatchOperations, DatabaseUtils};
use crate::error::Error; use crate::error::Error;
use crate::types::{ScriptType, TransactionDetails, UTXO}; use crate::types::{KeychainKind, TransactionDetails, UTXO};
use crate::FeeRate; use crate::FeeRate;
use peer::*; use peer::*;
@ -188,22 +188,22 @@ impl CompactFiltersBlockchain {
outputs_sum += output.value; outputs_sum += output.value;
// this output is ours, we have a path to derive it // this output is ours, we have a path to derive it
if let Some((script_type, child)) = if let Some((keychain, child)) =
database.get_path_from_script_pubkey(&output.script_pubkey)? database.get_path_from_script_pubkey(&output.script_pubkey)?
{ {
debug!("{} output #{} is mine, adding utxo", tx.txid(), i); debug!("{} output #{} is mine, adding utxo", tx.txid(), i);
updates.set_utxo(&UTXO { updates.set_utxo(&UTXO {
outpoint: OutPoint::new(tx.txid(), i as u32), outpoint: OutPoint::new(tx.txid(), i as u32),
txout: output.clone(), txout: output.clone(),
script_type, keychain,
})?; })?;
incoming += output.value; incoming += output.value;
if script_type == ScriptType::Internal if keychain == KeychainKind::Internal
&& (internal_max_deriv.is_none() || child > internal_max_deriv.unwrap_or(0)) && (internal_max_deriv.is_none() || child > internal_max_deriv.unwrap_or(0))
{ {
*internal_max_deriv = Some(child); *internal_max_deriv = Some(child);
} else if script_type == ScriptType::External } else if keychain == KeychainKind::External
&& (external_max_deriv.is_none() || child > external_max_deriv.unwrap_or(0)) && (external_max_deriv.is_none() || child > external_max_deriv.unwrap_or(0))
{ {
*external_max_deriv = Some(child); *external_max_deriv = Some(child);
@ -415,18 +415,22 @@ impl Blockchain for CompactFiltersBlockchain {
)?; )?;
} }
let current_ext = database.get_last_index(ScriptType::External)?.unwrap_or(0); let current_ext = database
.get_last_index(KeychainKind::External)?
.unwrap_or(0);
let first_ext_new = external_max_deriv.map(|x| x + 1).unwrap_or(0); let first_ext_new = external_max_deriv.map(|x| x + 1).unwrap_or(0);
if first_ext_new > current_ext { if first_ext_new > current_ext {
info!("Setting external index to {}", first_ext_new); info!("Setting external index to {}", first_ext_new);
database.set_last_index(ScriptType::External, first_ext_new)?; database.set_last_index(KeychainKind::External, first_ext_new)?;
} }
let current_int = database.get_last_index(ScriptType::Internal)?.unwrap_or(0); let current_int = database
.get_last_index(KeychainKind::Internal)?
.unwrap_or(0);
let first_int_new = internal_max_deriv.map(|x| x + 1).unwrap_or(0); let first_int_new = internal_max_deriv.map(|x| x + 1).unwrap_or(0);
if first_int_new > current_int { if first_int_new > current_int {
info!("Setting internal index to {}", first_int_new); info!("Setting internal index to {}", first_int_new);
database.set_last_index(ScriptType::Internal, first_int_new)?; database.set_last_index(KeychainKind::Internal, first_int_new)?;
} }
info!("Dropping blocks until {}", buried_height); info!("Dropping blocks until {}", buried_height);

View File

@ -34,7 +34,7 @@ use bitcoin::{BlockHeader, OutPoint, Script, Transaction, Txid};
use super::*; use super::*;
use crate::database::{BatchDatabase, BatchOperations, DatabaseUtils}; use crate::database::{BatchDatabase, BatchOperations, DatabaseUtils};
use crate::error::Error; use crate::error::Error;
use crate::types::{ScriptType, TransactionDetails, UTXO}; use crate::types::{KeychainKind, TransactionDetails, UTXO};
use crate::wallet::time::Instant; use crate::wallet::time::Instant;
use crate::wallet::utils::ChunksIterator; use crate::wallet::utils::ChunksIterator;
@ -81,12 +81,12 @@ pub trait ElectrumLikeSync {
let mut txid_height = HashMap::new(); let mut txid_height = HashMap::new();
let mut max_indexes = HashMap::new(); let mut max_indexes = HashMap::new();
let mut wallet_chains = vec![ScriptType::Internal, ScriptType::External]; let mut wallet_chains = vec![KeychainKind::Internal, KeychainKind::External];
// shuffling improve privacy, the server doesn't know my first request is from my internal or external addresses // shuffling improve privacy, the server doesn't know my first request is from my internal or external addresses
wallet_chains.shuffle(&mut thread_rng()); wallet_chains.shuffle(&mut thread_rng());
// download history of our internal and external script_pubkeys // download history of our internal and external script_pubkeys
for script_type in wallet_chains.iter() { for keychain in wallet_chains.iter() {
let script_iter = db.iter_script_pubkeys(Some(*script_type))?.into_iter(); let script_iter = db.iter_script_pubkeys(Some(*keychain))?.into_iter();
for (i, chunk) in ChunksIterator::new(script_iter, stop_gap).enumerate() { for (i, chunk) in ChunksIterator::new(script_iter, stop_gap).enumerate() {
// TODO if i == last, should create another chunk of addresses in db // TODO if i == last, should create another chunk of addresses in db
@ -98,10 +98,10 @@ pub trait ElectrumLikeSync {
.filter_map(|(i, v)| v.first().map(|_| i as u32)) .filter_map(|(i, v)| v.first().map(|_| i as u32))
.max(); .max();
if let Some(max) = max_index { if let Some(max) = max_index {
max_indexes.insert(script_type, max + (i * chunk_size) as u32); max_indexes.insert(keychain, max + (i * chunk_size) as u32);
} }
let flattened: Vec<ELSGetHistoryRes> = call_result.into_iter().flatten().collect(); let flattened: Vec<ELSGetHistoryRes> = call_result.into_iter().flatten().collect();
debug!("#{} of {:?} results:{}", i, script_type, flattened.len()); debug!("#{} of {:?} results:{}", i, keychain, flattened.len());
if flattened.is_empty() { if flattened.is_empty() {
// Didn't find anything in the last `stop_gap` script_pubkeys, breaking // Didn't find anything in the last `stop_gap` script_pubkeys, breaking
break; break;
@ -123,9 +123,9 @@ pub trait ElectrumLikeSync {
// saving max indexes // saving max indexes
info!("max indexes are: {:?}", max_indexes); info!("max indexes are: {:?}", max_indexes);
for script_type in wallet_chains.iter() { for keychain in wallet_chains.iter() {
if let Some(index) = max_indexes.get(script_type) { if let Some(index) = max_indexes.get(keychain) {
db.set_last_index(*script_type, *index)?; db.set_last_index(*keychain, *index)?;
} }
} }
@ -351,14 +351,12 @@ fn save_transaction_details_and_utxos<D: BatchDatabase>(
outputs_sum += output.value; outputs_sum += output.value;
// this output is ours, we have a path to derive it // this output is ours, we have a path to derive it
if let Some((script_type, _child)) = if let Some((keychain, _child)) = db.get_path_from_script_pubkey(&output.script_pubkey)? {
db.get_path_from_script_pubkey(&output.script_pubkey)?
{
debug!("{} output #{} is mine, adding utxo", txid, i); debug!("{} output #{} is mine, adding utxo", txid, i);
updates.set_utxo(&UTXO { updates.set_utxo(&UTXO {
outpoint: OutPoint::new(tx.txid(), i as u32), outpoint: OutPoint::new(tx.txid(), i as u32),
txout: output.clone(), txout: output.clone(),
script_type, keychain,
})?; })?;
incoming += output.value; incoming += output.value;

View File

@ -104,7 +104,7 @@ use bitcoin::{Address, OutPoint, Script, Txid};
use crate::blockchain::log_progress; use crate::blockchain::log_progress;
use crate::error::Error; use crate::error::Error;
use crate::types::ScriptType; use crate::types::KeychainKind;
use crate::{FeeRate, TxBuilder, Wallet}; use crate::{FeeRate, TxBuilder, Wallet};
/// Wallet global options and sub-command /// Wallet global options and sub-command
@ -479,14 +479,14 @@ where
} }
let policies = vec![ let policies = vec![
external_policy.map(|p| (p, ScriptType::External)), external_policy.map(|p| (p, KeychainKind::External)),
internal_policy.map(|p| (p, ScriptType::Internal)), internal_policy.map(|p| (p, KeychainKind::Internal)),
]; ];
for (policy, script_type) in policies.into_iter().filter_map(|x| x) { for (policy, keychain) in policies.into_iter().filter_map(|x| x) {
let policy = serde_json::from_str::<BTreeMap<String, Vec<usize>>>(&policy) let policy = serde_json::from_str::<BTreeMap<String, Vec<usize>>>(&policy)
.map_err(|s| Error::Generic(s.to_string()))?; .map_err(|s| Error::Generic(s.to_string()))?;
tx_builder = tx_builder.policy_path(policy, script_type); tx_builder = tx_builder.policy_path(policy, keychain);
} }
let (psbt, details) = wallet.create_tx(tx_builder)?; let (psbt, details) = wallet.create_tx(tx_builder)?;
@ -526,12 +526,12 @@ where
Ok(json!({"psbt": base64::encode(&serialize(&psbt)),"details": details,})) Ok(json!({"psbt": base64::encode(&serialize(&psbt)),"details": details,}))
} }
WalletSubCommand::Policies => Ok(json!({ WalletSubCommand::Policies => Ok(json!({
"external": wallet.policies(ScriptType::External)?, "external": wallet.policies(KeychainKind::External)?,
"internal": wallet.policies(ScriptType::Internal)?, "internal": wallet.policies(KeychainKind::Internal)?,
})), })),
WalletSubCommand::PublicDescriptor => Ok(json!({ WalletSubCommand::PublicDescriptor => Ok(json!({
"external": wallet.public_descriptor(ScriptType::External)?.map(|d| d.to_string()), "external": wallet.public_descriptor(KeychainKind::External)?.map(|d| d.to_string()),
"internal": wallet.public_descriptor(ScriptType::Internal)?.map(|d| d.to_string()), "internal": wallet.public_descriptor(KeychainKind::Internal)?.map(|d| d.to_string()),
})), })),
WalletSubCommand::Sign { WalletSubCommand::Sign {
psbt, psbt,

View File

@ -121,7 +121,7 @@ impl BatchOperations for AnyDatabase {
fn set_script_pubkey( fn set_script_pubkey(
&mut self, &mut self,
script: &Script, script: &Script,
script_type: ScriptType, keychain: KeychainKind,
child: u32, child: u32,
) -> Result<(), Error> { ) -> Result<(), Error> {
impl_inner_method!( impl_inner_method!(
@ -129,7 +129,7 @@ impl BatchOperations for AnyDatabase {
self, self,
set_script_pubkey, set_script_pubkey,
script, script,
script_type, keychain,
child child
) )
} }
@ -142,27 +142,27 @@ impl BatchOperations for AnyDatabase {
fn set_tx(&mut self, transaction: &TransactionDetails) -> Result<(), Error> { fn set_tx(&mut self, transaction: &TransactionDetails) -> Result<(), Error> {
impl_inner_method!(AnyDatabase, self, set_tx, transaction) impl_inner_method!(AnyDatabase, self, set_tx, transaction)
} }
fn set_last_index(&mut self, script_type: ScriptType, value: u32) -> Result<(), Error> { fn set_last_index(&mut self, keychain: KeychainKind, value: u32) -> Result<(), Error> {
impl_inner_method!(AnyDatabase, self, set_last_index, script_type, value) impl_inner_method!(AnyDatabase, self, set_last_index, keychain, value)
} }
fn del_script_pubkey_from_path( fn del_script_pubkey_from_path(
&mut self, &mut self,
script_type: ScriptType, keychain: KeychainKind,
child: u32, child: u32,
) -> Result<Option<Script>, Error> { ) -> Result<Option<Script>, Error> {
impl_inner_method!( impl_inner_method!(
AnyDatabase, AnyDatabase,
self, self,
del_script_pubkey_from_path, del_script_pubkey_from_path,
script_type, keychain,
child child
) )
} }
fn del_path_from_script_pubkey( fn del_path_from_script_pubkey(
&mut self, &mut self,
script: &Script, script: &Script,
) -> Result<Option<(ScriptType, u32)>, Error> { ) -> Result<Option<(KeychainKind, u32)>, Error> {
impl_inner_method!(AnyDatabase, self, del_path_from_script_pubkey, script) impl_inner_method!(AnyDatabase, self, del_path_from_script_pubkey, script)
} }
fn del_utxo(&mut self, outpoint: &OutPoint) -> Result<Option<UTXO>, Error> { fn del_utxo(&mut self, outpoint: &OutPoint) -> Result<Option<UTXO>, Error> {
@ -178,28 +178,28 @@ impl BatchOperations for AnyDatabase {
) -> Result<Option<TransactionDetails>, Error> { ) -> Result<Option<TransactionDetails>, Error> {
impl_inner_method!(AnyDatabase, self, del_tx, txid, include_raw) impl_inner_method!(AnyDatabase, self, del_tx, txid, include_raw)
} }
fn del_last_index(&mut self, script_type: ScriptType) -> Result<Option<u32>, Error> { fn del_last_index(&mut self, keychain: KeychainKind) -> Result<Option<u32>, Error> {
impl_inner_method!(AnyDatabase, self, del_last_index, script_type) impl_inner_method!(AnyDatabase, self, del_last_index, keychain)
} }
} }
impl Database for AnyDatabase { impl Database for AnyDatabase {
fn check_descriptor_checksum<B: AsRef<[u8]>>( fn check_descriptor_checksum<B: AsRef<[u8]>>(
&mut self, &mut self,
script_type: ScriptType, keychain: KeychainKind,
bytes: B, bytes: B,
) -> Result<(), Error> { ) -> Result<(), Error> {
impl_inner_method!( impl_inner_method!(
AnyDatabase, AnyDatabase,
self, self,
check_descriptor_checksum, check_descriptor_checksum,
script_type, keychain,
bytes bytes
) )
} }
fn iter_script_pubkeys(&self, script_type: Option<ScriptType>) -> Result<Vec<Script>, Error> { fn iter_script_pubkeys(&self, keychain: Option<KeychainKind>) -> Result<Vec<Script>, Error> {
impl_inner_method!(AnyDatabase, self, iter_script_pubkeys, script_type) impl_inner_method!(AnyDatabase, self, iter_script_pubkeys, keychain)
} }
fn iter_utxos(&self) -> Result<Vec<UTXO>, Error> { fn iter_utxos(&self) -> Result<Vec<UTXO>, Error> {
impl_inner_method!(AnyDatabase, self, iter_utxos) impl_inner_method!(AnyDatabase, self, iter_utxos)
@ -213,21 +213,21 @@ impl Database for AnyDatabase {
fn get_script_pubkey_from_path( fn get_script_pubkey_from_path(
&self, &self,
script_type: ScriptType, keychain: KeychainKind,
child: u32, child: u32,
) -> Result<Option<Script>, Error> { ) -> Result<Option<Script>, Error> {
impl_inner_method!( impl_inner_method!(
AnyDatabase, AnyDatabase,
self, self,
get_script_pubkey_from_path, get_script_pubkey_from_path,
script_type, keychain,
child child
) )
} }
fn get_path_from_script_pubkey( fn get_path_from_script_pubkey(
&self, &self,
script: &Script, script: &Script,
) -> Result<Option<(ScriptType, u32)>, Error> { ) -> Result<Option<(KeychainKind, u32)>, Error> {
impl_inner_method!(AnyDatabase, self, get_path_from_script_pubkey, script) impl_inner_method!(AnyDatabase, self, get_path_from_script_pubkey, script)
} }
fn get_utxo(&self, outpoint: &OutPoint) -> Result<Option<UTXO>, Error> { fn get_utxo(&self, outpoint: &OutPoint) -> Result<Option<UTXO>, Error> {
@ -239,12 +239,12 @@ impl Database for AnyDatabase {
fn get_tx(&self, txid: &Txid, include_raw: bool) -> Result<Option<TransactionDetails>, Error> { fn get_tx(&self, txid: &Txid, include_raw: bool) -> Result<Option<TransactionDetails>, Error> {
impl_inner_method!(AnyDatabase, self, get_tx, txid, include_raw) impl_inner_method!(AnyDatabase, self, get_tx, txid, include_raw)
} }
fn get_last_index(&self, script_type: ScriptType) -> Result<Option<u32>, Error> { fn get_last_index(&self, keychain: KeychainKind) -> Result<Option<u32>, Error> {
impl_inner_method!(AnyDatabase, self, get_last_index, script_type) impl_inner_method!(AnyDatabase, self, get_last_index, keychain)
} }
fn increment_last_index(&mut self, script_type: ScriptType) -> Result<u32, Error> { fn increment_last_index(&mut self, keychain: KeychainKind) -> Result<u32, Error> {
impl_inner_method!(AnyDatabase, self, increment_last_index, script_type) impl_inner_method!(AnyDatabase, self, increment_last_index, keychain)
} }
} }
@ -252,17 +252,10 @@ impl BatchOperations for AnyBatch {
fn set_script_pubkey( fn set_script_pubkey(
&mut self, &mut self,
script: &Script, script: &Script,
script_type: ScriptType, keychain: KeychainKind,
child: u32, child: u32,
) -> Result<(), Error> { ) -> Result<(), Error> {
impl_inner_method!( impl_inner_method!(AnyBatch, self, set_script_pubkey, script, keychain, child)
AnyBatch,
self,
set_script_pubkey,
script,
script_type,
child
)
} }
fn set_utxo(&mut self, utxo: &UTXO) -> Result<(), Error> { fn set_utxo(&mut self, utxo: &UTXO) -> Result<(), Error> {
impl_inner_method!(AnyBatch, self, set_utxo, utxo) impl_inner_method!(AnyBatch, self, set_utxo, utxo)
@ -273,27 +266,21 @@ impl BatchOperations for AnyBatch {
fn set_tx(&mut self, transaction: &TransactionDetails) -> Result<(), Error> { fn set_tx(&mut self, transaction: &TransactionDetails) -> Result<(), Error> {
impl_inner_method!(AnyBatch, self, set_tx, transaction) impl_inner_method!(AnyBatch, self, set_tx, transaction)
} }
fn set_last_index(&mut self, script_type: ScriptType, value: u32) -> Result<(), Error> { fn set_last_index(&mut self, keychain: KeychainKind, value: u32) -> Result<(), Error> {
impl_inner_method!(AnyBatch, self, set_last_index, script_type, value) impl_inner_method!(AnyBatch, self, set_last_index, keychain, value)
} }
fn del_script_pubkey_from_path( fn del_script_pubkey_from_path(
&mut self, &mut self,
script_type: ScriptType, keychain: KeychainKind,
child: u32, child: u32,
) -> Result<Option<Script>, Error> { ) -> Result<Option<Script>, Error> {
impl_inner_method!( impl_inner_method!(AnyBatch, self, del_script_pubkey_from_path, keychain, child)
AnyBatch,
self,
del_script_pubkey_from_path,
script_type,
child
)
} }
fn del_path_from_script_pubkey( fn del_path_from_script_pubkey(
&mut self, &mut self,
script: &Script, script: &Script,
) -> Result<Option<(ScriptType, u32)>, Error> { ) -> Result<Option<(KeychainKind, u32)>, Error> {
impl_inner_method!(AnyBatch, self, del_path_from_script_pubkey, script) impl_inner_method!(AnyBatch, self, del_path_from_script_pubkey, script)
} }
fn del_utxo(&mut self, outpoint: &OutPoint) -> Result<Option<UTXO>, Error> { fn del_utxo(&mut self, outpoint: &OutPoint) -> Result<Option<UTXO>, Error> {
@ -309,8 +296,8 @@ impl BatchOperations for AnyBatch {
) -> Result<Option<TransactionDetails>, Error> { ) -> Result<Option<TransactionDetails>, Error> {
impl_inner_method!(AnyBatch, self, del_tx, txid, include_raw) impl_inner_method!(AnyBatch, self, del_tx, txid, include_raw)
} }
fn del_last_index(&mut self, script_type: ScriptType) -> Result<Option<u32>, Error> { fn del_last_index(&mut self, keychain: KeychainKind) -> Result<Option<u32>, Error> {
impl_inner_method!(AnyBatch, self, del_last_index, script_type) impl_inner_method!(AnyBatch, self, del_last_index, keychain)
} }
} }

View File

@ -37,13 +37,13 @@ use crate::types::*;
macro_rules! impl_batch_operations { macro_rules! impl_batch_operations {
( { $($after_insert:tt)* }, $process_delete:ident ) => { ( { $($after_insert:tt)* }, $process_delete:ident ) => {
fn set_script_pubkey(&mut self, script: &Script, script_type: ScriptType, path: u32) -> Result<(), Error> { fn set_script_pubkey(&mut self, script: &Script, keychain: KeychainKind, path: u32) -> Result<(), Error> {
let key = MapKey::Path((Some(script_type), Some(path))).as_map_key(); let key = MapKey::Path((Some(keychain), Some(path))).as_map_key();
self.insert(key, serialize(script))$($after_insert)*; self.insert(key, serialize(script))$($after_insert)*;
let key = MapKey::Script(Some(script)).as_map_key(); let key = MapKey::Script(Some(script)).as_map_key();
let value = json!({ let value = json!({
"t": script_type, "t": keychain,
"p": path, "p": path,
}); });
self.insert(key, serde_json::to_vec(&value)?)$($after_insert)*; self.insert(key, serde_json::to_vec(&value)?)$($after_insert)*;
@ -55,7 +55,7 @@ macro_rules! impl_batch_operations {
let key = MapKey::UTXO(Some(&utxo.outpoint)).as_map_key(); let key = MapKey::UTXO(Some(&utxo.outpoint)).as_map_key();
let value = json!({ let value = json!({
"t": utxo.txout, "t": utxo.txout,
"i": utxo.script_type, "i": utxo.keychain,
}); });
self.insert(key, serde_json::to_vec(&value)?)$($after_insert)*; self.insert(key, serde_json::to_vec(&value)?)$($after_insert)*;
@ -88,22 +88,22 @@ macro_rules! impl_batch_operations {
Ok(()) Ok(())
} }
fn set_last_index(&mut self, script_type: ScriptType, value: u32) -> Result<(), Error> { fn set_last_index(&mut self, keychain: KeychainKind, value: u32) -> Result<(), Error> {
let key = MapKey::LastIndex(script_type).as_map_key(); let key = MapKey::LastIndex(keychain).as_map_key();
self.insert(key, &value.to_be_bytes())$($after_insert)*; self.insert(key, &value.to_be_bytes())$($after_insert)*;
Ok(()) Ok(())
} }
fn del_script_pubkey_from_path(&mut self, script_type: ScriptType, path: u32) -> Result<Option<Script>, Error> { fn del_script_pubkey_from_path(&mut self, keychain: KeychainKind, path: u32) -> Result<Option<Script>, Error> {
let key = MapKey::Path((Some(script_type), Some(path))).as_map_key(); let key = MapKey::Path((Some(keychain), Some(path))).as_map_key();
let res = self.remove(key); let res = self.remove(key);
let res = $process_delete!(res); let res = $process_delete!(res);
Ok(res.map_or(Ok(None), |x| Some(deserialize(&x)).transpose())?) Ok(res.map_or(Ok(None), |x| Some(deserialize(&x)).transpose())?)
} }
fn del_path_from_script_pubkey(&mut self, script: &Script) -> Result<Option<(ScriptType, u32)>, Error> { fn del_path_from_script_pubkey(&mut self, script: &Script) -> Result<Option<(KeychainKind, u32)>, Error> {
let key = MapKey::Script(Some(script)).as_map_key(); let key = MapKey::Script(Some(script)).as_map_key();
let res = self.remove(key); let res = self.remove(key);
let res = $process_delete!(res); let res = $process_delete!(res);
@ -130,9 +130,9 @@ macro_rules! impl_batch_operations {
Some(b) => { Some(b) => {
let mut val: serde_json::Value = serde_json::from_slice(&b)?; let mut val: serde_json::Value = serde_json::from_slice(&b)?;
let txout = serde_json::from_value(val["t"].take())?; let txout = serde_json::from_value(val["t"].take())?;
let script_type = serde_json::from_value(val["i"].take())?; let keychain = serde_json::from_value(val["i"].take())?;
Ok(Some(UTXO { outpoint: outpoint.clone(), txout, script_type })) Ok(Some(UTXO { outpoint: outpoint.clone(), txout, keychain }))
} }
} }
} }
@ -167,8 +167,8 @@ macro_rules! impl_batch_operations {
} }
} }
fn del_last_index(&mut self, script_type: ScriptType) -> Result<Option<u32>, Error> { fn del_last_index(&mut self, keychain: KeychainKind) -> Result<Option<u32>, Error> {
let key = MapKey::LastIndex(script_type).as_map_key(); let key = MapKey::LastIndex(keychain).as_map_key();
let res = self.remove(key); let res = self.remove(key);
let res = $process_delete!(res); let res = $process_delete!(res);
@ -206,10 +206,10 @@ impl BatchOperations for Batch {
impl Database for Tree { impl Database for Tree {
fn check_descriptor_checksum<B: AsRef<[u8]>>( fn check_descriptor_checksum<B: AsRef<[u8]>>(
&mut self, &mut self,
script_type: ScriptType, keychain: KeychainKind,
bytes: B, bytes: B,
) -> Result<(), Error> { ) -> Result<(), Error> {
let key = MapKey::DescriptorChecksum(script_type).as_map_key(); let key = MapKey::DescriptorChecksum(keychain).as_map_key();
let prev = self.get(&key)?.map(|x| x.to_vec()); let prev = self.get(&key)?.map(|x| x.to_vec());
if let Some(val) = prev { if let Some(val) = prev {
@ -224,8 +224,8 @@ impl Database for Tree {
} }
} }
fn iter_script_pubkeys(&self, script_type: Option<ScriptType>) -> Result<Vec<Script>, Error> { fn iter_script_pubkeys(&self, keychain: Option<KeychainKind>) -> Result<Vec<Script>, Error> {
let key = MapKey::Path((script_type, None)).as_map_key(); let key = MapKey::Path((keychain, None)).as_map_key();
self.scan_prefix(key) self.scan_prefix(key)
.map(|x| -> Result<_, Error> { .map(|x| -> Result<_, Error> {
let (_, v) = x?; let (_, v) = x?;
@ -243,12 +243,12 @@ impl Database for Tree {
let mut val: serde_json::Value = serde_json::from_slice(&v)?; let mut val: serde_json::Value = serde_json::from_slice(&v)?;
let txout = serde_json::from_value(val["t"].take())?; let txout = serde_json::from_value(val["t"].take())?;
let script_type = serde_json::from_value(val["i"].take())?; let keychain = serde_json::from_value(val["i"].take())?;
Ok(UTXO { Ok(UTXO {
outpoint, outpoint,
txout, txout,
script_type, keychain,
}) })
}) })
.collect() .collect()
@ -282,17 +282,17 @@ impl Database for Tree {
fn get_script_pubkey_from_path( fn get_script_pubkey_from_path(
&self, &self,
script_type: ScriptType, keychain: KeychainKind,
path: u32, path: u32,
) -> Result<Option<Script>, Error> { ) -> Result<Option<Script>, Error> {
let key = MapKey::Path((Some(script_type), Some(path))).as_map_key(); let key = MapKey::Path((Some(keychain), Some(path))).as_map_key();
Ok(self.get(key)?.map(|b| deserialize(&b)).transpose()?) Ok(self.get(key)?.map(|b| deserialize(&b)).transpose()?)
} }
fn get_path_from_script_pubkey( fn get_path_from_script_pubkey(
&self, &self,
script: &Script, script: &Script,
) -> Result<Option<(ScriptType, u32)>, Error> { ) -> Result<Option<(KeychainKind, u32)>, Error> {
let key = MapKey::Script(Some(script)).as_map_key(); let key = MapKey::Script(Some(script)).as_map_key();
self.get(key)? self.get(key)?
.map(|b| -> Result<_, Error> { .map(|b| -> Result<_, Error> {
@ -311,12 +311,12 @@ impl Database for Tree {
.map(|b| -> Result<_, Error> { .map(|b| -> Result<_, Error> {
let mut val: serde_json::Value = serde_json::from_slice(&b)?; let mut val: serde_json::Value = serde_json::from_slice(&b)?;
let txout = serde_json::from_value(val["t"].take())?; let txout = serde_json::from_value(val["t"].take())?;
let script_type = serde_json::from_value(val["i"].take())?; let keychain = serde_json::from_value(val["i"].take())?;
Ok(UTXO { Ok(UTXO {
outpoint: *outpoint, outpoint: *outpoint,
txout, txout,
script_type, keychain,
}) })
}) })
.transpose() .transpose()
@ -341,8 +341,8 @@ impl Database for Tree {
.transpose() .transpose()
} }
fn get_last_index(&self, script_type: ScriptType) -> Result<Option<u32>, Error> { fn get_last_index(&self, keychain: KeychainKind) -> Result<Option<u32>, Error> {
let key = MapKey::LastIndex(script_type).as_map_key(); let key = MapKey::LastIndex(keychain).as_map_key();
self.get(key)? self.get(key)?
.map(|b| -> Result<_, Error> { .map(|b| -> Result<_, Error> {
let array: [u8; 4] = b let array: [u8; 4] = b
@ -356,8 +356,8 @@ impl Database for Tree {
} }
// inserts 0 if not present // inserts 0 if not present
fn increment_last_index(&mut self, script_type: ScriptType) -> Result<u32, Error> { fn increment_last_index(&mut self, keychain: KeychainKind) -> Result<u32, Error> {
let key = MapKey::LastIndex(script_type).as_map_key(); let key = MapKey::LastIndex(keychain).as_map_key();
self.update_and_fetch(key, |prev| { self.update_and_fetch(key, |prev| {
let new = match prev { let new = match prev {
Some(b) => { Some(b) => {

View File

@ -47,13 +47,13 @@ use crate::types::*;
// descriptor checksum d{i,e} -> vec<u8> // descriptor checksum d{i,e} -> vec<u8>
pub(crate) enum MapKey<'a> { pub(crate) enum MapKey<'a> {
Path((Option<ScriptType>, Option<u32>)), Path((Option<KeychainKind>, Option<u32>)),
Script(Option<&'a Script>), Script(Option<&'a Script>),
UTXO(Option<&'a OutPoint>), UTXO(Option<&'a OutPoint>),
RawTx(Option<&'a Txid>), RawTx(Option<&'a Txid>),
Transaction(Option<&'a Txid>), Transaction(Option<&'a Txid>),
LastIndex(ScriptType), LastIndex(KeychainKind),
DescriptorChecksum(ScriptType), DescriptorChecksum(KeychainKind),
} }
impl MapKey<'_> { impl MapKey<'_> {
@ -141,15 +141,15 @@ impl BatchOperations for MemoryDatabase {
fn set_script_pubkey( fn set_script_pubkey(
&mut self, &mut self,
script: &Script, script: &Script,
script_type: ScriptType, keychain: KeychainKind,
path: u32, path: u32,
) -> Result<(), Error> { ) -> Result<(), Error> {
let key = MapKey::Path((Some(script_type), Some(path))).as_map_key(); let key = MapKey::Path((Some(keychain), Some(path))).as_map_key();
self.map.insert(key, Box::new(script.clone())); self.map.insert(key, Box::new(script.clone()));
let key = MapKey::Script(Some(script)).as_map_key(); let key = MapKey::Script(Some(script)).as_map_key();
let value = json!({ let value = json!({
"t": script_type, "t": keychain,
"p": path, "p": path,
}); });
self.map.insert(key, Box::new(value)); self.map.insert(key, Box::new(value));
@ -160,7 +160,7 @@ impl BatchOperations for MemoryDatabase {
fn set_utxo(&mut self, utxo: &UTXO) -> Result<(), Error> { fn set_utxo(&mut self, utxo: &UTXO) -> Result<(), Error> {
let key = MapKey::UTXO(Some(&utxo.outpoint)).as_map_key(); let key = MapKey::UTXO(Some(&utxo.outpoint)).as_map_key();
self.map self.map
.insert(key, Box::new((utxo.txout.clone(), utxo.script_type))); .insert(key, Box::new((utxo.txout.clone(), utxo.keychain)));
Ok(()) Ok(())
} }
@ -186,8 +186,8 @@ impl BatchOperations for MemoryDatabase {
Ok(()) Ok(())
} }
fn set_last_index(&mut self, script_type: ScriptType, value: u32) -> Result<(), Error> { fn set_last_index(&mut self, keychain: KeychainKind, value: u32) -> Result<(), Error> {
let key = MapKey::LastIndex(script_type).as_map_key(); let key = MapKey::LastIndex(keychain).as_map_key();
self.map.insert(key, Box::new(value)); self.map.insert(key, Box::new(value));
Ok(()) Ok(())
@ -195,10 +195,10 @@ impl BatchOperations for MemoryDatabase {
fn del_script_pubkey_from_path( fn del_script_pubkey_from_path(
&mut self, &mut self,
script_type: ScriptType, keychain: KeychainKind,
path: u32, path: u32,
) -> Result<Option<Script>, Error> { ) -> Result<Option<Script>, Error> {
let key = MapKey::Path((Some(script_type), Some(path))).as_map_key(); let key = MapKey::Path((Some(keychain), Some(path))).as_map_key();
let res = self.map.remove(&key); let res = self.map.remove(&key);
self.deleted_keys.push(key); self.deleted_keys.push(key);
@ -207,7 +207,7 @@ impl BatchOperations for MemoryDatabase {
fn del_path_from_script_pubkey( fn del_path_from_script_pubkey(
&mut self, &mut self,
script: &Script, script: &Script,
) -> Result<Option<(ScriptType, u32)>, Error> { ) -> Result<Option<(KeychainKind, u32)>, Error> {
let key = MapKey::Script(Some(script)).as_map_key(); let key = MapKey::Script(Some(script)).as_map_key();
let res = self.map.remove(&key); let res = self.map.remove(&key);
self.deleted_keys.push(key); self.deleted_keys.push(key);
@ -231,11 +231,11 @@ impl BatchOperations for MemoryDatabase {
match res { match res {
None => Ok(None), None => Ok(None),
Some(b) => { Some(b) => {
let (txout, script_type) = b.downcast_ref().cloned().unwrap(); let (txout, keychain) = b.downcast_ref().cloned().unwrap();
Ok(Some(UTXO { Ok(Some(UTXO {
outpoint: *outpoint, outpoint: *outpoint,
txout, txout,
script_type, keychain,
})) }))
} }
} }
@ -272,8 +272,8 @@ impl BatchOperations for MemoryDatabase {
} }
} }
} }
fn del_last_index(&mut self, script_type: ScriptType) -> Result<Option<u32>, Error> { fn del_last_index(&mut self, keychain: KeychainKind) -> Result<Option<u32>, Error> {
let key = MapKey::LastIndex(script_type).as_map_key(); let key = MapKey::LastIndex(keychain).as_map_key();
let res = self.map.remove(&key); let res = self.map.remove(&key);
self.deleted_keys.push(key); self.deleted_keys.push(key);
@ -287,10 +287,10 @@ impl BatchOperations for MemoryDatabase {
impl Database for MemoryDatabase { impl Database for MemoryDatabase {
fn check_descriptor_checksum<B: AsRef<[u8]>>( fn check_descriptor_checksum<B: AsRef<[u8]>>(
&mut self, &mut self,
script_type: ScriptType, keychain: KeychainKind,
bytes: B, bytes: B,
) -> Result<(), Error> { ) -> Result<(), Error> {
let key = MapKey::DescriptorChecksum(script_type).as_map_key(); let key = MapKey::DescriptorChecksum(keychain).as_map_key();
let prev = self let prev = self
.map .map
@ -308,8 +308,8 @@ impl Database for MemoryDatabase {
} }
} }
fn iter_script_pubkeys(&self, script_type: Option<ScriptType>) -> Result<Vec<Script>, Error> { fn iter_script_pubkeys(&self, keychain: Option<KeychainKind>) -> Result<Vec<Script>, Error> {
let key = MapKey::Path((script_type, None)).as_map_key(); let key = MapKey::Path((keychain, None)).as_map_key();
self.map self.map
.range::<Vec<u8>, _>((Included(&key), Excluded(&after(&key)))) .range::<Vec<u8>, _>((Included(&key), Excluded(&after(&key))))
.map(|(_, v)| Ok(v.downcast_ref().cloned().unwrap())) .map(|(_, v)| Ok(v.downcast_ref().cloned().unwrap()))
@ -322,11 +322,11 @@ impl Database for MemoryDatabase {
.range::<Vec<u8>, _>((Included(&key), Excluded(&after(&key)))) .range::<Vec<u8>, _>((Included(&key), Excluded(&after(&key))))
.map(|(k, v)| { .map(|(k, v)| {
let outpoint = deserialize(&k[1..]).unwrap(); let outpoint = deserialize(&k[1..]).unwrap();
let (txout, script_type) = v.downcast_ref().cloned().unwrap(); let (txout, keychain) = v.downcast_ref().cloned().unwrap();
Ok(UTXO { Ok(UTXO {
outpoint, outpoint,
txout, txout,
script_type, keychain,
}) })
}) })
.collect() .collect()
@ -358,10 +358,10 @@ impl Database for MemoryDatabase {
fn get_script_pubkey_from_path( fn get_script_pubkey_from_path(
&self, &self,
script_type: ScriptType, keychain: KeychainKind,
path: u32, path: u32,
) -> Result<Option<Script>, Error> { ) -> Result<Option<Script>, Error> {
let key = MapKey::Path((Some(script_type), Some(path))).as_map_key(); let key = MapKey::Path((Some(keychain), Some(path))).as_map_key();
Ok(self Ok(self
.map .map
.get(&key) .get(&key)
@ -371,7 +371,7 @@ impl Database for MemoryDatabase {
fn get_path_from_script_pubkey( fn get_path_from_script_pubkey(
&self, &self,
script: &Script, script: &Script,
) -> Result<Option<(ScriptType, u32)>, Error> { ) -> Result<Option<(KeychainKind, u32)>, Error> {
let key = MapKey::Script(Some(script)).as_map_key(); let key = MapKey::Script(Some(script)).as_map_key();
Ok(self.map.get(&key).map(|b| { Ok(self.map.get(&key).map(|b| {
let mut val: serde_json::Value = b.downcast_ref().cloned().unwrap(); let mut val: serde_json::Value = b.downcast_ref().cloned().unwrap();
@ -385,11 +385,11 @@ impl Database for MemoryDatabase {
fn get_utxo(&self, outpoint: &OutPoint) -> Result<Option<UTXO>, Error> { fn get_utxo(&self, outpoint: &OutPoint) -> Result<Option<UTXO>, Error> {
let key = MapKey::UTXO(Some(outpoint)).as_map_key(); let key = MapKey::UTXO(Some(outpoint)).as_map_key();
Ok(self.map.get(&key).map(|b| { Ok(self.map.get(&key).map(|b| {
let (txout, script_type) = b.downcast_ref().cloned().unwrap(); let (txout, keychain) = b.downcast_ref().cloned().unwrap();
UTXO { UTXO {
outpoint: *outpoint, outpoint: *outpoint,
txout, txout,
script_type, keychain,
} }
})) }))
} }
@ -414,14 +414,14 @@ impl Database for MemoryDatabase {
})) }))
} }
fn get_last_index(&self, script_type: ScriptType) -> Result<Option<u32>, Error> { fn get_last_index(&self, keychain: KeychainKind) -> Result<Option<u32>, Error> {
let key = MapKey::LastIndex(script_type).as_map_key(); let key = MapKey::LastIndex(keychain).as_map_key();
Ok(self.map.get(&key).map(|b| *b.downcast_ref().unwrap())) Ok(self.map.get(&key).map(|b| *b.downcast_ref().unwrap()))
} }
// inserts 0 if not present // inserts 0 if not present
fn increment_last_index(&mut self, script_type: ScriptType) -> Result<u32, Error> { fn increment_last_index(&mut self, keychain: KeychainKind) -> Result<u32, Error> {
let key = MapKey::LastIndex(script_type).as_map_key(); let key = MapKey::LastIndex(keychain).as_map_key();
let value = self let value = self
.map .map
.entry(key) .entry(key)
@ -507,7 +507,7 @@ impl MemoryDatabase {
txid, txid,
vout: vout as u32, vout: vout as u32,
}, },
script_type: ScriptType::External, keychain: KeychainKind::External,
}) })
.unwrap(); .unwrap();
} }

View File

@ -57,11 +57,11 @@ pub use memory::MemoryDatabase;
/// This trait defines the list of operations that must be implemented on the [`Database`] type and /// This trait defines the list of operations that must be implemented on the [`Database`] type and
/// the [`BatchDatabase::Batch`] type. /// the [`BatchDatabase::Batch`] type.
pub trait BatchOperations { pub trait BatchOperations {
/// Store a script_pubkey along with its script type and child number /// Store a script_pubkey along with its keychain and child number.
fn set_script_pubkey( fn set_script_pubkey(
&mut self, &mut self,
script: &Script, script: &Script,
script_type: ScriptType, keychain: KeychainKind,
child: u32, child: u32,
) -> Result<(), Error>; ) -> Result<(), Error>;
/// Store a [`UTXO`] /// Store a [`UTXO`]
@ -70,21 +70,21 @@ pub trait BatchOperations {
fn set_raw_tx(&mut self, transaction: &Transaction) -> Result<(), Error>; fn set_raw_tx(&mut self, transaction: &Transaction) -> Result<(), Error>;
/// Store the metadata of a transaction /// Store the metadata of a transaction
fn set_tx(&mut self, transaction: &TransactionDetails) -> Result<(), Error>; fn set_tx(&mut self, transaction: &TransactionDetails) -> Result<(), Error>;
/// Store the last derivation index for a given script type /// Store the last derivation index for a given keychain.
fn set_last_index(&mut self, script_type: ScriptType, value: u32) -> Result<(), Error>; fn set_last_index(&mut self, keychain: KeychainKind, value: u32) -> Result<(), Error>;
/// Delete a script_pubkey given the script type and its child number /// Delete a script_pubkey given the keychain and its child number.
fn del_script_pubkey_from_path( fn del_script_pubkey_from_path(
&mut self, &mut self,
script_type: ScriptType, keychain: KeychainKind,
child: u32, child: u32,
) -> Result<Option<Script>, Error>; ) -> Result<Option<Script>, Error>;
/// Delete the data related to a specific script_pubkey, meaning the script type and the child /// Delete the data related to a specific script_pubkey, meaning the keychain and the child
/// number /// number.
fn del_path_from_script_pubkey( fn del_path_from_script_pubkey(
&mut self, &mut self,
script: &Script, script: &Script,
) -> Result<Option<(ScriptType, u32)>, Error>; ) -> Result<Option<(KeychainKind, u32)>, Error>;
/// Delete a [`UTXO`] given its [`OutPoint`] /// Delete a [`UTXO`] given its [`OutPoint`]
fn del_utxo(&mut self, outpoint: &OutPoint) -> Result<Option<UTXO>, Error>; fn del_utxo(&mut self, outpoint: &OutPoint) -> Result<Option<UTXO>, Error>;
/// Delete a raw transaction given its [`Txid`] /// Delete a raw transaction given its [`Txid`]
@ -95,27 +95,27 @@ pub trait BatchOperations {
txid: &Txid, txid: &Txid,
include_raw: bool, include_raw: bool,
) -> Result<Option<TransactionDetails>, Error>; ) -> Result<Option<TransactionDetails>, Error>;
/// Delete the last derivation index for a script type /// Delete the last derivation index for a keychain.
fn del_last_index(&mut self, script_type: ScriptType) -> Result<Option<u32>, Error>; fn del_last_index(&mut self, keychain: KeychainKind) -> Result<Option<u32>, Error>;
} }
/// Trait for reading data from a database /// Trait for reading data from a database
/// ///
/// This traits defines the operations that can be used to read data out of a database /// This traits defines the operations that can be used to read data out of a database
pub trait Database: BatchOperations { pub trait Database: BatchOperations {
/// Read and checks the descriptor checksum for a given script type /// Read and checks the descriptor checksum for a given keychain.
/// ///
/// Should return [`Error::ChecksumMismatch`](crate::error::Error::ChecksumMismatch) if the /// Should return [`Error::ChecksumMismatch`](crate::error::Error::ChecksumMismatch) if the
/// checksum doesn't match. If there's no checksum in the database, simply store it for the /// checksum doesn't match. If there's no checksum in the database, simply store it for the
/// next time. /// next time.
fn check_descriptor_checksum<B: AsRef<[u8]>>( fn check_descriptor_checksum<B: AsRef<[u8]>>(
&mut self, &mut self,
script_type: ScriptType, keychain: KeychainKind,
bytes: B, bytes: B,
) -> Result<(), Error>; ) -> Result<(), Error>;
/// Return the list of script_pubkeys /// Return the list of script_pubkeys
fn iter_script_pubkeys(&self, script_type: Option<ScriptType>) -> Result<Vec<Script>, Error>; fn iter_script_pubkeys(&self, keychain: Option<KeychainKind>) -> Result<Vec<Script>, Error>;
/// Return the list of [`UTXO`]s /// Return the list of [`UTXO`]s
fn iter_utxos(&self) -> Result<Vec<UTXO>, Error>; fn iter_utxos(&self) -> Result<Vec<UTXO>, Error>;
/// Return the list of raw transactions /// Return the list of raw transactions
@ -123,30 +123,30 @@ pub trait Database: BatchOperations {
/// Return the list of transactions metadata /// Return the list of transactions metadata
fn iter_txs(&self, include_raw: bool) -> Result<Vec<TransactionDetails>, Error>; fn iter_txs(&self, include_raw: bool) -> Result<Vec<TransactionDetails>, Error>;
/// Fetch a script_pubkey given the script type and child number /// Fetch a script_pubkey given the child number of a keychain.
fn get_script_pubkey_from_path( fn get_script_pubkey_from_path(
&self, &self,
script_type: ScriptType, keychain: KeychainKind,
child: u32, child: u32,
) -> Result<Option<Script>, Error>; ) -> Result<Option<Script>, Error>;
/// Fetch the script type and child number of a given script_pubkey /// Fetch the keychain and child number of a given script_pubkey
fn get_path_from_script_pubkey( fn get_path_from_script_pubkey(
&self, &self,
script: &Script, script: &Script,
) -> Result<Option<(ScriptType, u32)>, Error>; ) -> Result<Option<(KeychainKind, u32)>, Error>;
/// Fetch a [`UTXO`] given its [`OutPoint`] /// Fetch a [`UTXO`] given its [`OutPoint`]
fn get_utxo(&self, outpoint: &OutPoint) -> Result<Option<UTXO>, Error>; fn get_utxo(&self, outpoint: &OutPoint) -> Result<Option<UTXO>, Error>;
/// Fetch a raw transaction given its [`Txid`] /// Fetch a raw transaction given its [`Txid`]
fn get_raw_tx(&self, txid: &Txid) -> Result<Option<Transaction>, Error>; fn get_raw_tx(&self, txid: &Txid) -> Result<Option<Transaction>, Error>;
/// Fetch the transaction metadata and optionally also the raw transaction /// Fetch the transaction metadata and optionally also the raw transaction
fn get_tx(&self, txid: &Txid, include_raw: bool) -> Result<Option<TransactionDetails>, Error>; fn get_tx(&self, txid: &Txid, include_raw: bool) -> Result<Option<TransactionDetails>, Error>;
/// Return the last defivation index for a script type /// Return the last defivation index for a keychain.
fn get_last_index(&self, script_type: ScriptType) -> Result<Option<u32>, Error>; fn get_last_index(&self, keychain: KeychainKind) -> Result<Option<u32>, Error>;
/// Increment the last derivation index for a script type and returns it /// Increment the last derivation index for a keychain and return it
/// ///
/// It should insert and return `0` if not present in the database /// It should insert and return `0` if not present in the database
fn increment_last_index(&mut self, script_type: ScriptType) -> Result<u32, Error>; fn increment_last_index(&mut self, keychain: KeychainKind) -> Result<u32, Error>;
} }
/// Trait for a database that supports batch operations /// Trait for a database that supports batch operations
@ -217,17 +217,17 @@ pub mod test {
Vec::<u8>::from_hex("76a91402306a7c23f3e8010de41e9e591348bb83f11daa88ac").unwrap(), Vec::<u8>::from_hex("76a91402306a7c23f3e8010de41e9e591348bb83f11daa88ac").unwrap(),
); );
let path = 42; let path = 42;
let script_type = ScriptType::External; let keychain = KeychainKind::External;
tree.set_script_pubkey(&script, script_type, path).unwrap(); tree.set_script_pubkey(&script, keychain, path).unwrap();
assert_eq!( assert_eq!(
tree.get_script_pubkey_from_path(script_type, path).unwrap(), tree.get_script_pubkey_from_path(keychain, path).unwrap(),
Some(script.clone()) Some(script.clone())
); );
assert_eq!( assert_eq!(
tree.get_path_from_script_pubkey(&script).unwrap(), tree.get_path_from_script_pubkey(&script).unwrap(),
Some((script_type, path.clone())) Some((keychain, path.clone()))
); );
} }
@ -238,12 +238,12 @@ pub mod test {
Vec::<u8>::from_hex("76a91402306a7c23f3e8010de41e9e591348bb83f11daa88ac").unwrap(), Vec::<u8>::from_hex("76a91402306a7c23f3e8010de41e9e591348bb83f11daa88ac").unwrap(),
); );
let path = 42; let path = 42;
let script_type = ScriptType::External; let keychain = KeychainKind::External;
batch.set_script_pubkey(&script, script_type, path).unwrap(); batch.set_script_pubkey(&script, keychain, path).unwrap();
assert_eq!( assert_eq!(
tree.get_script_pubkey_from_path(script_type, path).unwrap(), tree.get_script_pubkey_from_path(keychain, path).unwrap(),
None None
); );
assert_eq!(tree.get_path_from_script_pubkey(&script).unwrap(), None); assert_eq!(tree.get_path_from_script_pubkey(&script).unwrap(), None);
@ -251,12 +251,12 @@ pub mod test {
tree.commit_batch(batch).unwrap(); tree.commit_batch(batch).unwrap();
assert_eq!( assert_eq!(
tree.get_script_pubkey_from_path(script_type, path).unwrap(), tree.get_script_pubkey_from_path(keychain, path).unwrap(),
Some(script.clone()) Some(script.clone())
); );
assert_eq!( assert_eq!(
tree.get_path_from_script_pubkey(&script).unwrap(), tree.get_path_from_script_pubkey(&script).unwrap(),
Some((script_type, path.clone())) Some((keychain, path.clone()))
); );
} }
@ -265,9 +265,9 @@ pub mod test {
Vec::<u8>::from_hex("76a91402306a7c23f3e8010de41e9e591348bb83f11daa88ac").unwrap(), Vec::<u8>::from_hex("76a91402306a7c23f3e8010de41e9e591348bb83f11daa88ac").unwrap(),
); );
let path = 42; let path = 42;
let script_type = ScriptType::External; let keychain = KeychainKind::External;
tree.set_script_pubkey(&script, script_type, path).unwrap(); tree.set_script_pubkey(&script, keychain, path).unwrap();
assert_eq!(tree.iter_script_pubkeys(None).unwrap().len(), 1); assert_eq!(tree.iter_script_pubkeys(None).unwrap().len(), 1);
} }
@ -277,12 +277,12 @@ pub mod test {
Vec::<u8>::from_hex("76a91402306a7c23f3e8010de41e9e591348bb83f11daa88ac").unwrap(), Vec::<u8>::from_hex("76a91402306a7c23f3e8010de41e9e591348bb83f11daa88ac").unwrap(),
); );
let path = 42; let path = 42;
let script_type = ScriptType::External; let keychain = KeychainKind::External;
tree.set_script_pubkey(&script, script_type, path).unwrap(); tree.set_script_pubkey(&script, keychain, path).unwrap();
assert_eq!(tree.iter_script_pubkeys(None).unwrap().len(), 1); assert_eq!(tree.iter_script_pubkeys(None).unwrap().len(), 1);
tree.del_script_pubkey_from_path(script_type, path).unwrap(); tree.del_script_pubkey_from_path(keychain, path).unwrap();
assert_eq!(tree.iter_script_pubkeys(None).unwrap().len(), 0); assert_eq!(tree.iter_script_pubkeys(None).unwrap().len(), 0);
} }
@ -301,7 +301,7 @@ pub mod test {
let utxo = UTXO { let utxo = UTXO {
txout, txout,
outpoint, outpoint,
script_type: ScriptType::External, keychain: KeychainKind::External,
}; };
tree.set_utxo(&utxo).unwrap(); tree.set_utxo(&utxo).unwrap();
@ -356,24 +356,27 @@ pub mod test {
} }
pub fn test_last_index<D: Database>(mut tree: D) { pub fn test_last_index<D: Database>(mut tree: D) {
tree.set_last_index(ScriptType::External, 1337).unwrap(); tree.set_last_index(KeychainKind::External, 1337).unwrap();
assert_eq!( assert_eq!(
tree.get_last_index(ScriptType::External).unwrap(), tree.get_last_index(KeychainKind::External).unwrap(),
Some(1337) Some(1337)
); );
assert_eq!(tree.get_last_index(ScriptType::Internal).unwrap(), None); assert_eq!(tree.get_last_index(KeychainKind::Internal).unwrap(), None);
let res = tree.increment_last_index(ScriptType::External).unwrap(); let res = tree.increment_last_index(KeychainKind::External).unwrap();
assert_eq!(res, 1338); assert_eq!(res, 1338);
let res = tree.increment_last_index(ScriptType::Internal).unwrap(); let res = tree.increment_last_index(KeychainKind::Internal).unwrap();
assert_eq!(res, 0); assert_eq!(res, 0);
assert_eq!( assert_eq!(
tree.get_last_index(ScriptType::External).unwrap(), tree.get_last_index(KeychainKind::External).unwrap(),
Some(1338) Some(1338)
); );
assert_eq!(tree.get_last_index(ScriptType::Internal).unwrap(), Some(0)); assert_eq!(
tree.get_last_index(KeychainKind::Internal).unwrap(),
Some(0)
);
} }
// TODO: more tests... // TODO: more tests...

View File

@ -34,7 +34,7 @@ use miniscript::{Legacy, Segwitv0};
use super::{ExtendedDescriptor, KeyMap, ToWalletDescriptor}; use super::{ExtendedDescriptor, KeyMap, ToWalletDescriptor};
use crate::keys::{DerivableKey, KeyError, ToDescriptorKey, ValidNetworks}; use crate::keys::{DerivableKey, KeyError, ToDescriptorKey, ValidNetworks};
use crate::{descriptor, ScriptType}; use crate::{descriptor, KeychainKind};
/// Type alias for the return type of [`DescriptorTemplate`], [`descriptor!`](crate::descriptor!) and others /// Type alias for the return type of [`DescriptorTemplate`], [`descriptor!`](crate::descriptor!) and others
pub type DescriptorTemplateOut = (ExtendedDescriptor, KeyMap, ValidNetworks); pub type DescriptorTemplateOut = (ExtendedDescriptor, KeyMap, ValidNetworks);
@ -159,23 +159,23 @@ impl<K: ToDescriptorKey<Segwitv0>> DescriptorTemplate for P2WPKH<K> {
/// ``` /// ```
/// # use std::str::FromStr; /// # use std::str::FromStr;
/// # use bdk::bitcoin::{PrivateKey, Network}; /// # use bdk::bitcoin::{PrivateKey, Network};
/// # use bdk::{Wallet, OfflineWallet, ScriptType}; /// # use bdk::{Wallet, OfflineWallet, KeychainKind};
/// # use bdk::database::MemoryDatabase; /// # use bdk::database::MemoryDatabase;
/// use bdk::template::BIP44; /// use bdk::template::BIP44;
/// ///
/// let key = bitcoin::util::bip32::ExtendedPrivKey::from_str("tprv8ZgxMBicQKsPeZRHk4rTG6orPS2CRNFX3njhUXx5vj9qGog5ZMH4uGReDWN5kCkY3jmWEtWause41CDvBRXD1shKknAMKxT99o9qUTRVC6m")?; /// let key = bitcoin::util::bip32::ExtendedPrivKey::from_str("tprv8ZgxMBicQKsPeZRHk4rTG6orPS2CRNFX3njhUXx5vj9qGog5ZMH4uGReDWN5kCkY3jmWEtWause41CDvBRXD1shKknAMKxT99o9qUTRVC6m")?;
/// let wallet: OfflineWallet<_> = Wallet::new_offline( /// let wallet: OfflineWallet<_> = Wallet::new_offline(
/// BIP44(key.clone(), ScriptType::External), /// BIP44(key.clone(), KeychainKind::External),
/// Some(BIP44(key, ScriptType::Internal)), /// Some(BIP44(key, KeychainKind::Internal)),
/// Network::Testnet, /// Network::Testnet,
/// MemoryDatabase::default() /// MemoryDatabase::default()
/// )?; /// )?;
/// ///
/// assert_eq!(wallet.get_new_address()?.to_string(), "miNG7dJTzJqNbFS19svRdTCisC65dsubtR"); /// assert_eq!(wallet.get_new_address()?.to_string(), "miNG7dJTzJqNbFS19svRdTCisC65dsubtR");
/// assert_eq!(wallet.public_descriptor(ScriptType::External)?.unwrap().to_string(), "pkh([c55b303f/44'/0'/0']tpubDDDzQ31JkZB7VxUr9bjvBivDdqoFLrDPyLWtLapArAi51ftfmCb2DPxwLQzX65iNcXz1DGaVvyvo6JQ6rTU73r2gqdEo8uov9QKRb7nKCSU/0/*)"); /// assert_eq!(wallet.public_descriptor(KeychainKind::External)?.unwrap().to_string(), "pkh([c55b303f/44'/0'/0']tpubDDDzQ31JkZB7VxUr9bjvBivDdqoFLrDPyLWtLapArAi51ftfmCb2DPxwLQzX65iNcXz1DGaVvyvo6JQ6rTU73r2gqdEo8uov9QKRb7nKCSU/0/*)");
/// # Ok::<_, Box<dyn std::error::Error>>(()) /// # Ok::<_, Box<dyn std::error::Error>>(())
/// ``` /// ```
pub struct BIP44<K: DerivableKey<Legacy>>(pub K, pub ScriptType); pub struct BIP44<K: DerivableKey<Legacy>>(pub K, pub KeychainKind);
impl<K: DerivableKey<Legacy>> DescriptorTemplate for BIP44<K> { impl<K: DerivableKey<Legacy>> DescriptorTemplate for BIP44<K> {
fn build(self) -> Result<DescriptorTemplateOut, KeyError> { fn build(self) -> Result<DescriptorTemplateOut, KeyError> {
@ -197,24 +197,24 @@ impl<K: DerivableKey<Legacy>> DescriptorTemplate for BIP44<K> {
/// ``` /// ```
/// # use std::str::FromStr; /// # use std::str::FromStr;
/// # use bdk::bitcoin::{PrivateKey, Network}; /// # use bdk::bitcoin::{PrivateKey, Network};
/// # use bdk::{Wallet, OfflineWallet, ScriptType}; /// # use bdk::{Wallet, OfflineWallet, KeychainKind};
/// # use bdk::database::MemoryDatabase; /// # use bdk::database::MemoryDatabase;
/// use bdk::template::BIP44Public; /// use bdk::template::BIP44Public;
/// ///
/// let key = bitcoin::util::bip32::ExtendedPubKey::from_str("tpubDDDzQ31JkZB7VxUr9bjvBivDdqoFLrDPyLWtLapArAi51ftfmCb2DPxwLQzX65iNcXz1DGaVvyvo6JQ6rTU73r2gqdEo8uov9QKRb7nKCSU")?; /// let key = bitcoin::util::bip32::ExtendedPubKey::from_str("tpubDDDzQ31JkZB7VxUr9bjvBivDdqoFLrDPyLWtLapArAi51ftfmCb2DPxwLQzX65iNcXz1DGaVvyvo6JQ6rTU73r2gqdEo8uov9QKRb7nKCSU")?;
/// let fingerprint = bitcoin::util::bip32::Fingerprint::from_str("c55b303f")?; /// let fingerprint = bitcoin::util::bip32::Fingerprint::from_str("c55b303f")?;
/// let wallet: OfflineWallet<_> = Wallet::new_offline( /// let wallet: OfflineWallet<_> = Wallet::new_offline(
/// BIP44Public(key.clone(), fingerprint, ScriptType::External), /// BIP44Public(key.clone(), fingerprint, KeychainKind::External),
/// Some(BIP44Public(key, fingerprint, ScriptType::Internal)), /// Some(BIP44Public(key, fingerprint, KeychainKind::Internal)),
/// Network::Testnet, /// Network::Testnet,
/// MemoryDatabase::default() /// MemoryDatabase::default()
/// )?; /// )?;
/// ///
/// assert_eq!(wallet.get_new_address()?.to_string(), "miNG7dJTzJqNbFS19svRdTCisC65dsubtR"); /// assert_eq!(wallet.get_new_address()?.to_string(), "miNG7dJTzJqNbFS19svRdTCisC65dsubtR");
/// assert_eq!(wallet.public_descriptor(ScriptType::External)?.unwrap().to_string(), "pkh([c55b303f/44'/0'/0']tpubDDDzQ31JkZB7VxUr9bjvBivDdqoFLrDPyLWtLapArAi51ftfmCb2DPxwLQzX65iNcXz1DGaVvyvo6JQ6rTU73r2gqdEo8uov9QKRb7nKCSU/0/*)"); /// assert_eq!(wallet.public_descriptor(KeychainKind::External)?.unwrap().to_string(), "pkh([c55b303f/44'/0'/0']tpubDDDzQ31JkZB7VxUr9bjvBivDdqoFLrDPyLWtLapArAi51ftfmCb2DPxwLQzX65iNcXz1DGaVvyvo6JQ6rTU73r2gqdEo8uov9QKRb7nKCSU/0/*)");
/// # Ok::<_, Box<dyn std::error::Error>>(()) /// # Ok::<_, Box<dyn std::error::Error>>(())
/// ``` /// ```
pub struct BIP44Public<K: DerivableKey<Legacy>>(pub K, pub bip32::Fingerprint, pub ScriptType); pub struct BIP44Public<K: DerivableKey<Legacy>>(pub K, pub bip32::Fingerprint, pub KeychainKind);
impl<K: DerivableKey<Legacy>> DescriptorTemplate for BIP44Public<K> { impl<K: DerivableKey<Legacy>> DescriptorTemplate for BIP44Public<K> {
fn build(self) -> Result<DescriptorTemplateOut, KeyError> { fn build(self) -> Result<DescriptorTemplateOut, KeyError> {
@ -233,23 +233,23 @@ impl<K: DerivableKey<Legacy>> DescriptorTemplate for BIP44Public<K> {
/// ``` /// ```
/// # use std::str::FromStr; /// # use std::str::FromStr;
/// # use bdk::bitcoin::{PrivateKey, Network}; /// # use bdk::bitcoin::{PrivateKey, Network};
/// # use bdk::{Wallet, OfflineWallet, ScriptType}; /// # use bdk::{Wallet, OfflineWallet, KeychainKind};
/// # use bdk::database::MemoryDatabase; /// # use bdk::database::MemoryDatabase;
/// use bdk::template::BIP49; /// use bdk::template::BIP49;
/// ///
/// let key = bitcoin::util::bip32::ExtendedPrivKey::from_str("tprv8ZgxMBicQKsPeZRHk4rTG6orPS2CRNFX3njhUXx5vj9qGog5ZMH4uGReDWN5kCkY3jmWEtWause41CDvBRXD1shKknAMKxT99o9qUTRVC6m")?; /// let key = bitcoin::util::bip32::ExtendedPrivKey::from_str("tprv8ZgxMBicQKsPeZRHk4rTG6orPS2CRNFX3njhUXx5vj9qGog5ZMH4uGReDWN5kCkY3jmWEtWause41CDvBRXD1shKknAMKxT99o9qUTRVC6m")?;
/// let wallet: OfflineWallet<_> = Wallet::new_offline( /// let wallet: OfflineWallet<_> = Wallet::new_offline(
/// BIP49(key.clone(), ScriptType::External), /// BIP49(key.clone(), KeychainKind::External),
/// Some(BIP49(key, ScriptType::Internal)), /// Some(BIP49(key, KeychainKind::Internal)),
/// Network::Testnet, /// Network::Testnet,
/// MemoryDatabase::default() /// MemoryDatabase::default()
/// )?; /// )?;
/// ///
/// assert_eq!(wallet.get_new_address()?.to_string(), "2N3K4xbVAHoiTQSwxkZjWDfKoNC27pLkYnt"); /// assert_eq!(wallet.get_new_address()?.to_string(), "2N3K4xbVAHoiTQSwxkZjWDfKoNC27pLkYnt");
/// assert_eq!(wallet.public_descriptor(ScriptType::External)?.unwrap().to_string(), "sh(wpkh([c55b303f/49\'/0\'/0\']tpubDC49r947KGK52X5rBWS4BLs5m9SRY3pYHnvRrm7HcybZ3BfdEsGFyzCMzayi1u58eT82ZeyFZwH7DD6Q83E3fM9CpfMtmnTygnLfP59jL9L/0/*))"); /// assert_eq!(wallet.public_descriptor(KeychainKind::External)?.unwrap().to_string(), "sh(wpkh([c55b303f/49\'/0\'/0\']tpubDC49r947KGK52X5rBWS4BLs5m9SRY3pYHnvRrm7HcybZ3BfdEsGFyzCMzayi1u58eT82ZeyFZwH7DD6Q83E3fM9CpfMtmnTygnLfP59jL9L/0/*))");
/// # Ok::<_, Box<dyn std::error::Error>>(()) /// # Ok::<_, Box<dyn std::error::Error>>(())
/// ``` /// ```
pub struct BIP49<K: DerivableKey<Segwitv0>>(pub K, pub ScriptType); pub struct BIP49<K: DerivableKey<Segwitv0>>(pub K, pub KeychainKind);
impl<K: DerivableKey<Segwitv0>> DescriptorTemplate for BIP49<K> { impl<K: DerivableKey<Segwitv0>> DescriptorTemplate for BIP49<K> {
fn build(self) -> Result<DescriptorTemplateOut, KeyError> { fn build(self) -> Result<DescriptorTemplateOut, KeyError> {
@ -271,24 +271,24 @@ impl<K: DerivableKey<Segwitv0>> DescriptorTemplate for BIP49<K> {
/// ``` /// ```
/// # use std::str::FromStr; /// # use std::str::FromStr;
/// # use bdk::bitcoin::{PrivateKey, Network}; /// # use bdk::bitcoin::{PrivateKey, Network};
/// # use bdk::{Wallet, OfflineWallet, ScriptType}; /// # use bdk::{Wallet, OfflineWallet, KeychainKind};
/// # use bdk::database::MemoryDatabase; /// # use bdk::database::MemoryDatabase;
/// use bdk::template::BIP49Public; /// use bdk::template::BIP49Public;
/// ///
/// let key = bitcoin::util::bip32::ExtendedPubKey::from_str("tpubDC49r947KGK52X5rBWS4BLs5m9SRY3pYHnvRrm7HcybZ3BfdEsGFyzCMzayi1u58eT82ZeyFZwH7DD6Q83E3fM9CpfMtmnTygnLfP59jL9L")?; /// let key = bitcoin::util::bip32::ExtendedPubKey::from_str("tpubDC49r947KGK52X5rBWS4BLs5m9SRY3pYHnvRrm7HcybZ3BfdEsGFyzCMzayi1u58eT82ZeyFZwH7DD6Q83E3fM9CpfMtmnTygnLfP59jL9L")?;
/// let fingerprint = bitcoin::util::bip32::Fingerprint::from_str("c55b303f")?; /// let fingerprint = bitcoin::util::bip32::Fingerprint::from_str("c55b303f")?;
/// let wallet: OfflineWallet<_> = Wallet::new_offline( /// let wallet: OfflineWallet<_> = Wallet::new_offline(
/// BIP49Public(key.clone(), fingerprint, ScriptType::External), /// BIP49Public(key.clone(), fingerprint, KeychainKind::External),
/// Some(BIP49Public(key, fingerprint, ScriptType::Internal)), /// Some(BIP49Public(key, fingerprint, KeychainKind::Internal)),
/// Network::Testnet, /// Network::Testnet,
/// MemoryDatabase::default() /// MemoryDatabase::default()
/// )?; /// )?;
/// ///
/// assert_eq!(wallet.get_new_address()?.to_string(), "2N3K4xbVAHoiTQSwxkZjWDfKoNC27pLkYnt"); /// assert_eq!(wallet.get_new_address()?.to_string(), "2N3K4xbVAHoiTQSwxkZjWDfKoNC27pLkYnt");
/// assert_eq!(wallet.public_descriptor(ScriptType::External)?.unwrap().to_string(), "sh(wpkh([c55b303f/49\'/0\'/0\']tpubDC49r947KGK52X5rBWS4BLs5m9SRY3pYHnvRrm7HcybZ3BfdEsGFyzCMzayi1u58eT82ZeyFZwH7DD6Q83E3fM9CpfMtmnTygnLfP59jL9L/0/*))"); /// assert_eq!(wallet.public_descriptor(KeychainKind::External)?.unwrap().to_string(), "sh(wpkh([c55b303f/49\'/0\'/0\']tpubDC49r947KGK52X5rBWS4BLs5m9SRY3pYHnvRrm7HcybZ3BfdEsGFyzCMzayi1u58eT82ZeyFZwH7DD6Q83E3fM9CpfMtmnTygnLfP59jL9L/0/*))");
/// # Ok::<_, Box<dyn std::error::Error>>(()) /// # Ok::<_, Box<dyn std::error::Error>>(())
/// ``` /// ```
pub struct BIP49Public<K: DerivableKey<Segwitv0>>(pub K, pub bip32::Fingerprint, pub ScriptType); pub struct BIP49Public<K: DerivableKey<Segwitv0>>(pub K, pub bip32::Fingerprint, pub KeychainKind);
impl<K: DerivableKey<Segwitv0>> DescriptorTemplate for BIP49Public<K> { impl<K: DerivableKey<Segwitv0>> DescriptorTemplate for BIP49Public<K> {
fn build(self) -> Result<DescriptorTemplateOut, KeyError> { fn build(self) -> Result<DescriptorTemplateOut, KeyError> {
@ -307,23 +307,23 @@ impl<K: DerivableKey<Segwitv0>> DescriptorTemplate for BIP49Public<K> {
/// ``` /// ```
/// # use std::str::FromStr; /// # use std::str::FromStr;
/// # use bdk::bitcoin::{PrivateKey, Network}; /// # use bdk::bitcoin::{PrivateKey, Network};
/// # use bdk::{Wallet, OfflineWallet, ScriptType}; /// # use bdk::{Wallet, OfflineWallet, KeychainKind};
/// # use bdk::database::MemoryDatabase; /// # use bdk::database::MemoryDatabase;
/// use bdk::template::BIP84; /// use bdk::template::BIP84;
/// ///
/// let key = bitcoin::util::bip32::ExtendedPrivKey::from_str("tprv8ZgxMBicQKsPeZRHk4rTG6orPS2CRNFX3njhUXx5vj9qGog5ZMH4uGReDWN5kCkY3jmWEtWause41CDvBRXD1shKknAMKxT99o9qUTRVC6m")?; /// let key = bitcoin::util::bip32::ExtendedPrivKey::from_str("tprv8ZgxMBicQKsPeZRHk4rTG6orPS2CRNFX3njhUXx5vj9qGog5ZMH4uGReDWN5kCkY3jmWEtWause41CDvBRXD1shKknAMKxT99o9qUTRVC6m")?;
/// let wallet: OfflineWallet<_> = Wallet::new_offline( /// let wallet: OfflineWallet<_> = Wallet::new_offline(
/// BIP84(key.clone(), ScriptType::External), /// BIP84(key.clone(), KeychainKind::External),
/// Some(BIP84(key, ScriptType::Internal)), /// Some(BIP84(key, KeychainKind::Internal)),
/// Network::Testnet, /// Network::Testnet,
/// MemoryDatabase::default() /// MemoryDatabase::default()
/// )?; /// )?;
/// ///
/// assert_eq!(wallet.get_new_address()?.to_string(), "tb1qedg9fdlf8cnnqfd5mks6uz5w4kgpk2pr6y4qc7"); /// assert_eq!(wallet.get_new_address()?.to_string(), "tb1qedg9fdlf8cnnqfd5mks6uz5w4kgpk2pr6y4qc7");
/// assert_eq!(wallet.public_descriptor(ScriptType::External)?.unwrap().to_string(), "wpkh([c55b303f/84\'/0\'/0\']tpubDC2Qwo2TFsaNC4ju8nrUJ9mqVT3eSgdmy1yPqhgkjwmke3PRXutNGRYAUo6RCHTcVQaDR3ohNU9we59brGHuEKPvH1ags2nevW5opEE9Z5Q/0/*)"); /// assert_eq!(wallet.public_descriptor(KeychainKind::External)?.unwrap().to_string(), "wpkh([c55b303f/84\'/0\'/0\']tpubDC2Qwo2TFsaNC4ju8nrUJ9mqVT3eSgdmy1yPqhgkjwmke3PRXutNGRYAUo6RCHTcVQaDR3ohNU9we59brGHuEKPvH1ags2nevW5opEE9Z5Q/0/*)");
/// # Ok::<_, Box<dyn std::error::Error>>(()) /// # Ok::<_, Box<dyn std::error::Error>>(())
/// ``` /// ```
pub struct BIP84<K: DerivableKey<Segwitv0>>(pub K, pub ScriptType); pub struct BIP84<K: DerivableKey<Segwitv0>>(pub K, pub KeychainKind);
impl<K: DerivableKey<Segwitv0>> DescriptorTemplate for BIP84<K> { impl<K: DerivableKey<Segwitv0>> DescriptorTemplate for BIP84<K> {
fn build(self) -> Result<DescriptorTemplateOut, KeyError> { fn build(self) -> Result<DescriptorTemplateOut, KeyError> {
@ -345,24 +345,24 @@ impl<K: DerivableKey<Segwitv0>> DescriptorTemplate for BIP84<K> {
/// ``` /// ```
/// # use std::str::FromStr; /// # use std::str::FromStr;
/// # use bdk::bitcoin::{PrivateKey, Network}; /// # use bdk::bitcoin::{PrivateKey, Network};
/// # use bdk::{Wallet, OfflineWallet, ScriptType}; /// # use bdk::{Wallet, OfflineWallet, KeychainKind};
/// # use bdk::database::MemoryDatabase; /// # use bdk::database::MemoryDatabase;
/// use bdk::template::BIP84Public; /// use bdk::template::BIP84Public;
/// ///
/// let key = bitcoin::util::bip32::ExtendedPubKey::from_str("tpubDC2Qwo2TFsaNC4ju8nrUJ9mqVT3eSgdmy1yPqhgkjwmke3PRXutNGRYAUo6RCHTcVQaDR3ohNU9we59brGHuEKPvH1ags2nevW5opEE9Z5Q")?; /// let key = bitcoin::util::bip32::ExtendedPubKey::from_str("tpubDC2Qwo2TFsaNC4ju8nrUJ9mqVT3eSgdmy1yPqhgkjwmke3PRXutNGRYAUo6RCHTcVQaDR3ohNU9we59brGHuEKPvH1ags2nevW5opEE9Z5Q")?;
/// let fingerprint = bitcoin::util::bip32::Fingerprint::from_str("c55b303f")?; /// let fingerprint = bitcoin::util::bip32::Fingerprint::from_str("c55b303f")?;
/// let wallet: OfflineWallet<_> = Wallet::new_offline( /// let wallet: OfflineWallet<_> = Wallet::new_offline(
/// BIP84Public(key.clone(), fingerprint, ScriptType::External), /// BIP84Public(key.clone(), fingerprint, KeychainKind::External),
/// Some(BIP84Public(key, fingerprint, ScriptType::Internal)), /// Some(BIP84Public(key, fingerprint, KeychainKind::Internal)),
/// Network::Testnet, /// Network::Testnet,
/// MemoryDatabase::default() /// MemoryDatabase::default()
/// )?; /// )?;
/// ///
/// assert_eq!(wallet.get_new_address()?.to_string(), "tb1qedg9fdlf8cnnqfd5mks6uz5w4kgpk2pr6y4qc7"); /// assert_eq!(wallet.get_new_address()?.to_string(), "tb1qedg9fdlf8cnnqfd5mks6uz5w4kgpk2pr6y4qc7");
/// assert_eq!(wallet.public_descriptor(ScriptType::External)?.unwrap().to_string(), "wpkh([c55b303f/84\'/0\'/0\']tpubDC2Qwo2TFsaNC4ju8nrUJ9mqVT3eSgdmy1yPqhgkjwmke3PRXutNGRYAUo6RCHTcVQaDR3ohNU9we59brGHuEKPvH1ags2nevW5opEE9Z5Q/0/*)"); /// assert_eq!(wallet.public_descriptor(KeychainKind::External)?.unwrap().to_string(), "wpkh([c55b303f/84\'/0\'/0\']tpubDC2Qwo2TFsaNC4ju8nrUJ9mqVT3eSgdmy1yPqhgkjwmke3PRXutNGRYAUo6RCHTcVQaDR3ohNU9we59brGHuEKPvH1ags2nevW5opEE9Z5Q/0/*)");
/// # Ok::<_, Box<dyn std::error::Error>>(()) /// # Ok::<_, Box<dyn std::error::Error>>(())
/// ``` /// ```
pub struct BIP84Public<K: DerivableKey<Segwitv0>>(pub K, pub bip32::Fingerprint, pub ScriptType); pub struct BIP84Public<K: DerivableKey<Segwitv0>>(pub K, pub bip32::Fingerprint, pub KeychainKind);
impl<K: DerivableKey<Segwitv0>> DescriptorTemplate for BIP84Public<K> { impl<K: DerivableKey<Segwitv0>> DescriptorTemplate for BIP84Public<K> {
fn build(self) -> Result<DescriptorTemplateOut, KeyError> { fn build(self) -> Result<DescriptorTemplateOut, KeyError> {
@ -378,18 +378,18 @@ macro_rules! expand_make_bipxx {
pub(super) fn make_bipxx_private<K: DerivableKey<$ctx>>( pub(super) fn make_bipxx_private<K: DerivableKey<$ctx>>(
bip: u32, bip: u32,
key: K, key: K,
script_type: ScriptType, keychain: KeychainKind,
) -> Result<impl ToDescriptorKey<$ctx>, KeyError> { ) -> Result<impl ToDescriptorKey<$ctx>, KeyError> {
let mut derivation_path = Vec::with_capacity(4); let mut derivation_path = Vec::with_capacity(4);
derivation_path.push(bip32::ChildNumber::from_hardened_idx(bip)?); derivation_path.push(bip32::ChildNumber::from_hardened_idx(bip)?);
derivation_path.push(bip32::ChildNumber::from_hardened_idx(0)?); derivation_path.push(bip32::ChildNumber::from_hardened_idx(0)?);
derivation_path.push(bip32::ChildNumber::from_hardened_idx(0)?); derivation_path.push(bip32::ChildNumber::from_hardened_idx(0)?);
match script_type { match keychain {
ScriptType::External => { KeychainKind::External => {
derivation_path.push(bip32::ChildNumber::from_normal_idx(0)?) derivation_path.push(bip32::ChildNumber::from_normal_idx(0)?)
} }
ScriptType::Internal => { KeychainKind::Internal => {
derivation_path.push(bip32::ChildNumber::from_normal_idx(1)?) derivation_path.push(bip32::ChildNumber::from_normal_idx(1)?)
} }
}; };
@ -402,11 +402,11 @@ macro_rules! expand_make_bipxx {
bip: u32, bip: u32,
key: K, key: K,
parent_fingerprint: bip32::Fingerprint, parent_fingerprint: bip32::Fingerprint,
script_type: ScriptType, keychain: KeychainKind,
) -> Result<impl ToDescriptorKey<$ctx>, KeyError> { ) -> Result<impl ToDescriptorKey<$ctx>, KeyError> {
let derivation_path: bip32::DerivationPath = match script_type { let derivation_path: bip32::DerivationPath = match keychain {
ScriptType::External => vec![bip32::ChildNumber::from_normal_idx(0)?].into(), KeychainKind::External => vec![bip32::ChildNumber::from_normal_idx(0)?].into(),
ScriptType::Internal => vec![bip32::ChildNumber::from_normal_idx(1)?].into(), KeychainKind::Internal => vec![bip32::ChildNumber::from_normal_idx(1)?].into(),
}; };
let mut source_path = Vec::with_capacity(3); let mut source_path = Vec::with_capacity(3);
@ -544,7 +544,7 @@ mod test {
fn test_bip44_template() { fn test_bip44_template() {
let prvkey = bitcoin::util::bip32::ExtendedPrivKey::from_str("tprv8ZgxMBicQKsPcx5nBGsR63Pe8KnRUqmbJNENAfGftF3yuXoMMoVJJcYeUw5eVkm9WBPjWYt6HMWYJNesB5HaNVBaFc1M6dRjWSYnmewUMYy").unwrap(); let prvkey = bitcoin::util::bip32::ExtendedPrivKey::from_str("tprv8ZgxMBicQKsPcx5nBGsR63Pe8KnRUqmbJNENAfGftF3yuXoMMoVJJcYeUw5eVkm9WBPjWYt6HMWYJNesB5HaNVBaFc1M6dRjWSYnmewUMYy").unwrap();
check( check(
BIP44(prvkey, ScriptType::External).build(), BIP44(prvkey, KeychainKind::External).build(),
false, false,
false, false,
&[ &[
@ -554,7 +554,7 @@ mod test {
], ],
); );
check( check(
BIP44(prvkey, ScriptType::Internal).build(), BIP44(prvkey, KeychainKind::Internal).build(),
false, false,
false, false,
&[ &[
@ -571,7 +571,7 @@ mod test {
let pubkey = bitcoin::util::bip32::ExtendedPubKey::from_str("tpubDDDzQ31JkZB7VxUr9bjvBivDdqoFLrDPyLWtLapArAi51ftfmCb2DPxwLQzX65iNcXz1DGaVvyvo6JQ6rTU73r2gqdEo8uov9QKRb7nKCSU").unwrap(); let pubkey = bitcoin::util::bip32::ExtendedPubKey::from_str("tpubDDDzQ31JkZB7VxUr9bjvBivDdqoFLrDPyLWtLapArAi51ftfmCb2DPxwLQzX65iNcXz1DGaVvyvo6JQ6rTU73r2gqdEo8uov9QKRb7nKCSU").unwrap();
let fingerprint = bitcoin::util::bip32::Fingerprint::from_str("c55b303f").unwrap(); let fingerprint = bitcoin::util::bip32::Fingerprint::from_str("c55b303f").unwrap();
check( check(
BIP44Public(pubkey, fingerprint, ScriptType::External).build(), BIP44Public(pubkey, fingerprint, KeychainKind::External).build(),
false, false,
false, false,
&[ &[
@ -581,7 +581,7 @@ mod test {
], ],
); );
check( check(
BIP44Public(pubkey, fingerprint, ScriptType::Internal).build(), BIP44Public(pubkey, fingerprint, KeychainKind::Internal).build(),
false, false,
false, false,
&[ &[
@ -597,7 +597,7 @@ mod test {
fn test_bip49_template() { fn test_bip49_template() {
let prvkey = bitcoin::util::bip32::ExtendedPrivKey::from_str("tprv8ZgxMBicQKsPcx5nBGsR63Pe8KnRUqmbJNENAfGftF3yuXoMMoVJJcYeUw5eVkm9WBPjWYt6HMWYJNesB5HaNVBaFc1M6dRjWSYnmewUMYy").unwrap(); let prvkey = bitcoin::util::bip32::ExtendedPrivKey::from_str("tprv8ZgxMBicQKsPcx5nBGsR63Pe8KnRUqmbJNENAfGftF3yuXoMMoVJJcYeUw5eVkm9WBPjWYt6HMWYJNesB5HaNVBaFc1M6dRjWSYnmewUMYy").unwrap();
check( check(
BIP49(prvkey, ScriptType::External).build(), BIP49(prvkey, KeychainKind::External).build(),
true, true,
false, false,
&[ &[
@ -607,7 +607,7 @@ mod test {
], ],
); );
check( check(
BIP49(prvkey, ScriptType::Internal).build(), BIP49(prvkey, KeychainKind::Internal).build(),
true, true,
false, false,
&[ &[
@ -624,7 +624,7 @@ mod test {
let pubkey = bitcoin::util::bip32::ExtendedPubKey::from_str("tpubDC49r947KGK52X5rBWS4BLs5m9SRY3pYHnvRrm7HcybZ3BfdEsGFyzCMzayi1u58eT82ZeyFZwH7DD6Q83E3fM9CpfMtmnTygnLfP59jL9L").unwrap(); let pubkey = bitcoin::util::bip32::ExtendedPubKey::from_str("tpubDC49r947KGK52X5rBWS4BLs5m9SRY3pYHnvRrm7HcybZ3BfdEsGFyzCMzayi1u58eT82ZeyFZwH7DD6Q83E3fM9CpfMtmnTygnLfP59jL9L").unwrap();
let fingerprint = bitcoin::util::bip32::Fingerprint::from_str("c55b303f").unwrap(); let fingerprint = bitcoin::util::bip32::Fingerprint::from_str("c55b303f").unwrap();
check( check(
BIP49Public(pubkey, fingerprint, ScriptType::External).build(), BIP49Public(pubkey, fingerprint, KeychainKind::External).build(),
true, true,
false, false,
&[ &[
@ -634,7 +634,7 @@ mod test {
], ],
); );
check( check(
BIP49Public(pubkey, fingerprint, ScriptType::Internal).build(), BIP49Public(pubkey, fingerprint, KeychainKind::Internal).build(),
true, true,
false, false,
&[ &[
@ -650,7 +650,7 @@ mod test {
fn test_bip84_template() { fn test_bip84_template() {
let prvkey = bitcoin::util::bip32::ExtendedPrivKey::from_str("tprv8ZgxMBicQKsPcx5nBGsR63Pe8KnRUqmbJNENAfGftF3yuXoMMoVJJcYeUw5eVkm9WBPjWYt6HMWYJNesB5HaNVBaFc1M6dRjWSYnmewUMYy").unwrap(); let prvkey = bitcoin::util::bip32::ExtendedPrivKey::from_str("tprv8ZgxMBicQKsPcx5nBGsR63Pe8KnRUqmbJNENAfGftF3yuXoMMoVJJcYeUw5eVkm9WBPjWYt6HMWYJNesB5HaNVBaFc1M6dRjWSYnmewUMYy").unwrap();
check( check(
BIP84(prvkey, ScriptType::External).build(), BIP84(prvkey, KeychainKind::External).build(),
true, true,
false, false,
&[ &[
@ -660,7 +660,7 @@ mod test {
], ],
); );
check( check(
BIP84(prvkey, ScriptType::Internal).build(), BIP84(prvkey, KeychainKind::Internal).build(),
true, true,
false, false,
&[ &[
@ -677,7 +677,7 @@ mod test {
let pubkey = bitcoin::util::bip32::ExtendedPubKey::from_str("tpubDC2Qwo2TFsaNC4ju8nrUJ9mqVT3eSgdmy1yPqhgkjwmke3PRXutNGRYAUo6RCHTcVQaDR3ohNU9we59brGHuEKPvH1ags2nevW5opEE9Z5Q").unwrap(); let pubkey = bitcoin::util::bip32::ExtendedPubKey::from_str("tpubDC2Qwo2TFsaNC4ju8nrUJ9mqVT3eSgdmy1yPqhgkjwmke3PRXutNGRYAUo6RCHTcVQaDR3ohNU9we59brGHuEKPvH1ags2nevW5opEE9Z5Q").unwrap();
let fingerprint = bitcoin::util::bip32::Fingerprint::from_str("c55b303f").unwrap(); let fingerprint = bitcoin::util::bip32::Fingerprint::from_str("c55b303f").unwrap();
check( check(
BIP84Public(pubkey, fingerprint, ScriptType::External).build(), BIP84Public(pubkey, fingerprint, KeychainKind::External).build(),
true, true,
false, false,
&[ &[
@ -687,7 +687,7 @@ mod test {
], ],
); );
check( check(
BIP84Public(pubkey, fingerprint, ScriptType::Internal).build(), BIP84Public(pubkey, fingerprint, KeychainKind::Internal).build(),
true, true,
false, false,
&[ &[

View File

@ -82,8 +82,8 @@ pub enum Error {
Key(crate::keys::KeyError), Key(crate::keys::KeyError),
/// Descriptor checksum mismatch /// Descriptor checksum mismatch
ChecksumMismatch, ChecksumMismatch,
/// Spending policy is not compatible with this [`ScriptType`](crate::types::ScriptType) /// Spending policy is not compatible with this [`KeychainKind`](crate::types::KeychainKind)
SpendingPolicyRequired(crate::types::ScriptType), SpendingPolicyRequired(crate::types::KeychainKind),
#[allow(missing_docs)] #[allow(missing_docs)]
InvalidPolicyPathError(crate::descriptor::policy::PolicyError), InvalidPolicyPathError(crate::descriptor::policy::PolicyError),
#[allow(missing_docs)] #[allow(missing_docs)]

View File

@ -31,27 +31,27 @@ use serde::{Deserialize, Serialize};
/// Types of script /// Types of script
#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, Hash)] #[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum ScriptType { pub enum KeychainKind {
/// External /// External
External = 0, External = 0,
/// Internal, usually used for change outputs /// Internal, usually used for change outputs
Internal = 1, Internal = 1,
} }
impl ScriptType { impl KeychainKind {
pub fn as_byte(&self) -> u8 { pub fn as_byte(&self) -> u8 {
match self { match self {
ScriptType::External => b'e', KeychainKind::External => b'e',
ScriptType::Internal => b'i', KeychainKind::Internal => b'i',
} }
} }
} }
impl AsRef<[u8]> for ScriptType { impl AsRef<[u8]> for KeychainKind {
fn as_ref(&self) -> &[u8] { fn as_ref(&self) -> &[u8] {
match self { match self {
ScriptType::External => b"e", KeychainKind::External => b"e",
ScriptType::Internal => b"i", KeychainKind::Internal => b"i",
} }
} }
} }
@ -94,7 +94,7 @@ impl std::default::Default for FeeRate {
pub struct UTXO { pub struct UTXO {
pub outpoint: OutPoint, pub outpoint: OutPoint,
pub txout: TxOut, pub txout: TxOut,
pub script_type: ScriptType, pub keychain: KeychainKind,
} }
/// A wallet transaction /// A wallet transaction

View File

@ -50,7 +50,7 @@
//! impl AddressValidator for PrintAddressAndContinue { //! impl AddressValidator for PrintAddressAndContinue {
//! fn validate( //! fn validate(
//! &self, //! &self,
//! script_type: ScriptType, //! keychain: KeychainKind,
//! hd_keypaths: &HDKeyPaths, //! hd_keypaths: &HDKeyPaths,
//! script: &Script //! script: &Script
//! ) -> Result<(), AddressValidatorError> { //! ) -> Result<(), AddressValidatorError> {
@ -58,7 +58,7 @@
//! .as_ref() //! .as_ref()
//! .map(Address::to_string) //! .map(Address::to_string)
//! .unwrap_or(script.to_string()); //! .unwrap_or(script.to_string());
//! println!("New address of type {:?}: {}", script_type, address); //! println!("New address of type {:?}: {}", keychain, address);
//! println!("HD keypaths: {:#?}", hd_keypaths); //! println!("HD keypaths: {:#?}", hd_keypaths);
//! //!
//! Ok(()) //! Ok(())
@ -79,7 +79,7 @@ use std::fmt;
use bitcoin::Script; use bitcoin::Script;
use crate::descriptor::HDKeyPaths; use crate::descriptor::HDKeyPaths;
use crate::types::ScriptType; use crate::types::KeychainKind;
/// Errors that can be returned to fail the validation of an address /// Errors that can be returned to fail the validation of an address
#[derive(Debug, Clone, PartialEq, Eq)] #[derive(Debug, Clone, PartialEq, Eq)]
@ -110,7 +110,7 @@ pub trait AddressValidator: Send + Sync {
/// Validate or inspect an address /// Validate or inspect an address
fn validate( fn validate(
&self, &self,
script_type: ScriptType, keychain: KeychainKind,
hd_keypaths: &HDKeyPaths, hd_keypaths: &HDKeyPaths,
script: &Script, script: &Script,
) -> Result<(), AddressValidatorError>; ) -> Result<(), AddressValidatorError>;
@ -128,7 +128,7 @@ mod test {
impl AddressValidator for TestValidator { impl AddressValidator for TestValidator {
fn validate( fn validate(
&self, &self,
_script_type: ScriptType, _keychain: KeychainKind,
_hd_keypaths: &HDKeyPaths, _hd_keypaths: &HDKeyPaths,
_script: &bitcoin::Script, _script: &bitcoin::Script,
) -> Result<(), AddressValidatorError> { ) -> Result<(), AddressValidatorError> {

View File

@ -539,7 +539,7 @@ mod test {
value: 100_000, value: 100_000,
script_pubkey: Script::new(), script_pubkey: Script::new(),
}, },
script_type: ScriptType::External, keychain: KeychainKind::External,
}, },
P2WPKH_WITNESS_SIZE, P2WPKH_WITNESS_SIZE,
), ),
@ -553,7 +553,7 @@ mod test {
value: 200_000, value: 200_000,
script_pubkey: Script::new(), script_pubkey: Script::new(),
}, },
script_type: ScriptType::Internal, keychain: KeychainKind::Internal,
}, },
P2WPKH_WITNESS_SIZE, P2WPKH_WITNESS_SIZE,
), ),
@ -573,7 +573,7 @@ mod test {
value: rng.gen_range(0, 200000000), value: rng.gen_range(0, 200000000),
script_pubkey: Script::new(), script_pubkey: Script::new(),
}, },
script_type: ScriptType::External, keychain: KeychainKind::External,
}, },
P2WPKH_WITNESS_SIZE, P2WPKH_WITNESS_SIZE,
)); ));
@ -592,7 +592,7 @@ mod test {
value: utxos_value, value: utxos_value,
script_pubkey: Script::new(), script_pubkey: Script::new(),
}, },
script_type: ScriptType::External, keychain: KeychainKind::External,
}, },
P2WPKH_WITNESS_SIZE, P2WPKH_WITNESS_SIZE,
); );

View File

@ -124,7 +124,7 @@ where
) -> Result<Self, Error> { ) -> Result<Self, Error> {
let (descriptor, keymap) = descriptor.to_wallet_descriptor(network)?; let (descriptor, keymap) = descriptor.to_wallet_descriptor(network)?;
database.check_descriptor_checksum( database.check_descriptor_checksum(
ScriptType::External, KeychainKind::External,
get_checksum(&descriptor.to_string())?.as_bytes(), get_checksum(&descriptor.to_string())?.as_bytes(),
)?; )?;
let signers = Arc::new(SignersContainer::from(keymap)); let signers = Arc::new(SignersContainer::from(keymap));
@ -132,7 +132,7 @@ where
Some(desc) => { Some(desc) => {
let (change_descriptor, change_keymap) = desc.to_wallet_descriptor(network)?; let (change_descriptor, change_keymap) = desc.to_wallet_descriptor(network)?;
database.check_descriptor_checksum( database.check_descriptor_checksum(
ScriptType::Internal, KeychainKind::Internal,
get_checksum(&change_descriptor.to_string())?.as_bytes(), get_checksum(&change_descriptor.to_string())?.as_bytes(),
)?; )?;
@ -166,7 +166,7 @@ where
/// Return a newly generated address using the external descriptor /// Return a newly generated address using the external descriptor
pub fn get_new_address(&self) -> Result<Address, Error> { pub fn get_new_address(&self) -> Result<Address, Error> {
let index = self.fetch_and_increment_index(ScriptType::External)?; let index = self.fetch_and_increment_index(KeychainKind::External)?;
let deriv_ctx = descriptor_to_pk_ctx(&self.secp); let deriv_ctx = descriptor_to_pk_ctx(&self.secp);
self.descriptor self.descriptor
@ -215,14 +215,14 @@ where
/// See [the `signer` module](signer) for an example. /// See [the `signer` module](signer) for an example.
pub fn add_signer( pub fn add_signer(
&mut self, &mut self,
script_type: ScriptType, keychain: KeychainKind,
id: SignerId, id: SignerId,
ordering: SignerOrdering, ordering: SignerOrdering,
signer: Arc<dyn Signer>, signer: Arc<dyn Signer>,
) { ) {
let signers = match script_type { let signers = match keychain {
ScriptType::External => Arc::make_mut(&mut self.signers), KeychainKind::External => Arc::make_mut(&mut self.signers),
ScriptType::Internal => Arc::make_mut(&mut self.change_signers), KeychainKind::Internal => Arc::make_mut(&mut self.change_signers),
}; };
signers.add_external(id, ordering, signer); signers.add_external(id, ordering, signer);
@ -278,7 +278,7 @@ where
&& external_policy.requires_path() && external_policy.requires_path()
&& builder.external_policy_path.is_none() && builder.external_policy_path.is_none()
{ {
return Err(Error::SpendingPolicyRequired(ScriptType::External)); return Err(Error::SpendingPolicyRequired(KeychainKind::External));
}; };
// Same for the internal_policy path, if present // Same for the internal_policy path, if present
if let Some(internal_policy) = &internal_policy { if let Some(internal_policy) = &internal_policy {
@ -286,7 +286,7 @@ where
&& internal_policy.requires_path() && internal_policy.requires_path()
&& builder.internal_policy_path.is_none() && builder.internal_policy_path.is_none()
{ {
return Err(Error::SpendingPolicyRequired(ScriptType::Internal)); return Err(Error::SpendingPolicyRequired(KeychainKind::Internal));
}; };
} }
@ -600,18 +600,17 @@ where
None => { None => {
let mut change_output = None; let mut change_output = None;
for (index, txout) in tx.output.iter().enumerate() { for (index, txout) in tx.output.iter().enumerate() {
// look for an output that we know and that has the right ScriptType. We use // look for an output that we know and that has the right KeychainKind. We use
// `get_descriptor_for` to find what's the ScriptType for `Internal` // `get_descriptor_for` to find what's the KeychainKind for `Internal`
// addresses really is, because if there's no change_descriptor it's actually equal // addresses really is, because if there's no change_descriptor it's actually equal
// to "External" // to "External"
let (_, change_type) = let (_, change_type) = self.get_descriptor_for_keychain(KeychainKind::Internal);
self.get_descriptor_for_script_type(ScriptType::Internal);
match self match self
.database .database
.borrow() .borrow()
.get_path_from_script_pubkey(&txout.script_pubkey)? .get_path_from_script_pubkey(&txout.script_pubkey)?
{ {
Some((script_type, _)) if script_type == change_type => { Some((keychain, _)) if keychain == change_type => {
change_output = Some(index); change_output = Some(index);
break; break;
} }
@ -657,31 +656,31 @@ where
.get_previous_output(&txin.previous_output)? .get_previous_output(&txin.previous_output)?
.ok_or(Error::UnknownUTXO)?; .ok_or(Error::UnknownUTXO)?;
let (weight, script_type) = match self let (weight, keychain) = match self
.database .database
.borrow() .borrow()
.get_path_from_script_pubkey(&txout.script_pubkey)? .get_path_from_script_pubkey(&txout.script_pubkey)?
{ {
Some((script_type, _)) => ( Some((keychain, _)) => (
self.get_descriptor_for_script_type(script_type) self.get_descriptor_for_keychain(keychain)
.0 .0
.max_satisfaction_weight(deriv_ctx) .max_satisfaction_weight(deriv_ctx)
.unwrap(), .unwrap(),
script_type, keychain,
), ),
None => { None => {
// estimate the weight based on the scriptsig/witness size present in the // estimate the weight based on the scriptsig/witness size present in the
// original transaction // original transaction
let weight = let weight =
serialize(&txin.script_sig).len() * 4 + serialize(&txin.witness).len(); serialize(&txin.script_sig).len() * 4 + serialize(&txin.witness).len();
(weight, ScriptType::External) (weight, KeychainKind::External)
} }
}; };
let utxo = UTXO { let utxo = UTXO {
outpoint: txin.previous_output, outpoint: txin.previous_output,
txout, txout,
script_type, keychain,
}; };
Ok((utxo, weight)) Ok((utxo, weight))
@ -853,13 +852,13 @@ where
} }
/// Return the spending policies for the wallet's descriptor /// Return the spending policies for the wallet's descriptor
pub fn policies(&self, script_type: ScriptType) -> Result<Option<Policy>, Error> { pub fn policies(&self, keychain: KeychainKind) -> Result<Option<Policy>, Error> {
match (script_type, self.change_descriptor.as_ref()) { match (keychain, self.change_descriptor.as_ref()) {
(ScriptType::External, _) => { (KeychainKind::External, _) => {
Ok(self.descriptor.extract_policy(&self.signers, &self.secp)?) Ok(self.descriptor.extract_policy(&self.signers, &self.secp)?)
} }
(ScriptType::Internal, None) => Ok(None), (KeychainKind::Internal, None) => Ok(None),
(ScriptType::Internal, Some(desc)) => { (KeychainKind::Internal, Some(desc)) => {
Ok(desc.extract_policy(&self.change_signers, &self.secp)?) Ok(desc.extract_policy(&self.change_signers, &self.secp)?)
} }
} }
@ -871,12 +870,12 @@ where
/// This can be used to build a watch-only version of a wallet /// This can be used to build a watch-only version of a wallet
pub fn public_descriptor( pub fn public_descriptor(
&self, &self,
script_type: ScriptType, keychain: KeychainKind,
) -> Result<Option<ExtendedDescriptor>, Error> { ) -> Result<Option<ExtendedDescriptor>, Error> {
match (script_type, self.change_descriptor.as_ref()) { match (keychain, self.change_descriptor.as_ref()) {
(ScriptType::External, _) => Ok(Some(self.descriptor.clone())), (KeychainKind::External, _) => Ok(Some(self.descriptor.clone())),
(ScriptType::Internal, None) => Ok(None), (KeychainKind::Internal, None) => Ok(None),
(ScriptType::Internal, Some(desc)) => Ok(Some(desc.clone())), (KeychainKind::Internal, Some(desc)) => Ok(Some(desc.clone())),
} }
} }
@ -909,7 +908,7 @@ where
); );
// - Try to derive the descriptor by looking at the txout. If it's in our database, we // - Try to derive the descriptor by looking at the txout. If it's in our database, we
// know exactly which `script_type` to use, and which derivation index it is // know exactly which `keychain` to use, and which derivation index it is
// - If that fails, try to derive it by looking at the psbt input: the complete logic // - If that fails, try to derive it by looking at the psbt input: the complete logic
// is in `src/descriptor/mod.rs`, but it will basically look at `hd_keypaths`, // is in `src/descriptor/mod.rs`, but it will basically look at `hd_keypaths`,
// `redeem_script` and `witness_script` to determine the right derivation // `redeem_script` and `witness_script` to determine the right derivation
@ -970,16 +969,16 @@ where
// Internals // Internals
fn get_descriptor_for_script_type( fn get_descriptor_for_keychain(
&self, &self,
script_type: ScriptType, keychain: KeychainKind,
) -> (&ExtendedDescriptor, ScriptType) { ) -> (&ExtendedDescriptor, KeychainKind) {
match script_type { match keychain {
ScriptType::Internal if self.change_descriptor.is_some() => ( KeychainKind::Internal if self.change_descriptor.is_some() => (
self.change_descriptor.as_ref().unwrap(), self.change_descriptor.as_ref().unwrap(),
ScriptType::Internal, KeychainKind::Internal,
), ),
_ => (&self.descriptor, ScriptType::External), _ => (&self.descriptor, KeychainKind::External),
} }
} }
@ -988,38 +987,35 @@ where
.database .database
.borrow() .borrow()
.get_path_from_script_pubkey(&txout.script_pubkey)? .get_path_from_script_pubkey(&txout.script_pubkey)?
.map(|(script_type, child)| (self.get_descriptor_for_script_type(script_type).0, child)) .map(|(keychain, child)| (self.get_descriptor_for_keychain(keychain).0, child))
.map(|(desc, child)| desc.derive(ChildNumber::from_normal_idx(child).unwrap()))) .map(|(desc, child)| desc.derive(ChildNumber::from_normal_idx(child).unwrap())))
} }
fn get_change_address(&self) -> Result<Script, Error> { fn get_change_address(&self) -> Result<Script, Error> {
let deriv_ctx = descriptor_to_pk_ctx(&self.secp); let deriv_ctx = descriptor_to_pk_ctx(&self.secp);
let (desc, script_type) = self.get_descriptor_for_script_type(ScriptType::Internal); let (desc, keychain) = self.get_descriptor_for_keychain(KeychainKind::Internal);
let index = self.fetch_and_increment_index(script_type)?; let index = self.fetch_and_increment_index(keychain)?;
Ok(desc Ok(desc
.derive(ChildNumber::from_normal_idx(index)?) .derive(ChildNumber::from_normal_idx(index)?)
.script_pubkey(deriv_ctx)) .script_pubkey(deriv_ctx))
} }
fn fetch_and_increment_index(&self, script_type: ScriptType) -> Result<u32, Error> { fn fetch_and_increment_index(&self, keychain: KeychainKind) -> Result<u32, Error> {
let (descriptor, script_type) = self.get_descriptor_for_script_type(script_type); let (descriptor, keychain) = self.get_descriptor_for_keychain(keychain);
let index = match descriptor.is_fixed() { let index = match descriptor.is_fixed() {
true => 0, true => 0,
false => self false => self.database.borrow_mut().increment_last_index(keychain)?,
.database
.borrow_mut()
.increment_last_index(script_type)?,
}; };
if self if self
.database .database
.borrow() .borrow()
.get_script_pubkey_from_path(script_type, index)? .get_script_pubkey_from_path(keychain, index)?
.is_none() .is_none()
{ {
self.cache_addresses(script_type, index, CACHE_ADDR_BATCH_SIZE)?; self.cache_addresses(keychain, index, CACHE_ADDR_BATCH_SIZE)?;
} }
let deriv_ctx = descriptor_to_pk_ctx(&self.secp); let deriv_ctx = descriptor_to_pk_ctx(&self.secp);
@ -1029,7 +1025,7 @@ where
.derive(ChildNumber::from_normal_idx(index)?) .derive(ChildNumber::from_normal_idx(index)?)
.script_pubkey(deriv_ctx); .script_pubkey(deriv_ctx);
for validator in &self.address_validators { for validator in &self.address_validators {
validator.validate(script_type, &hd_keypaths, &script)?; validator.validate(keychain, &hd_keypaths, &script)?;
} }
Ok(index) Ok(index)
@ -1037,11 +1033,11 @@ where
fn cache_addresses( fn cache_addresses(
&self, &self,
script_type: ScriptType, keychain: KeychainKind,
from: u32, from: u32,
mut count: u32, mut count: u32,
) -> Result<(), Error> { ) -> Result<(), Error> {
let (descriptor, script_type) = self.get_descriptor_for_script_type(script_type); let (descriptor, keychain) = self.get_descriptor_for_keychain(keychain);
if descriptor.is_fixed() { if descriptor.is_fixed() {
if from > 0 { if from > 0 {
return Ok(()); return Ok(());
@ -1060,7 +1056,7 @@ where
&descriptor &descriptor
.derive(ChildNumber::from_normal_idx(i)?) .derive(ChildNumber::from_normal_idx(i)?)
.script_pubkey(deriv_ctx), .script_pubkey(deriv_ctx),
script_type, keychain,
i, i,
)?; )?;
} }
@ -1083,10 +1079,10 @@ where
.list_unspent()? .list_unspent()?
.into_iter() .into_iter()
.map(|utxo| { .map(|utxo| {
let script_type = utxo.script_type; let keychain = utxo.keychain;
( (
utxo, utxo,
self.get_descriptor_for_script_type(script_type) self.get_descriptor_for_keychain(keychain)
.0 .0
.max_satisfaction_weight(deriv_ctx) .max_satisfaction_weight(deriv_ctx)
.unwrap(), .unwrap(),
@ -1230,7 +1226,7 @@ where
// Try to find the prev_script in our db to figure out if this is internal or external, // Try to find the prev_script in our db to figure out if this is internal or external,
// and the derivation index // and the derivation index
let (script_type, child) = match self let (keychain, child) = match self
.database .database
.borrow() .borrow()
.get_path_from_script_pubkey(&utxo.txout.script_pubkey)? .get_path_from_script_pubkey(&utxo.txout.script_pubkey)?
@ -1239,7 +1235,7 @@ where
None => continue, None => continue,
}; };
let (desc, _) = self.get_descriptor_for_script_type(script_type); let (desc, _) = self.get_descriptor_for_keychain(keychain);
psbt_input.hd_keypaths = desc.get_hd_keypaths(child, &self.secp)?; psbt_input.hd_keypaths = desc.get_hd_keypaths(child, &self.secp)?;
let derived_descriptor = desc.derive(ChildNumber::from_normal_idx(child)?); let derived_descriptor = desc.derive(ChildNumber::from_normal_idx(child)?);
@ -1267,12 +1263,12 @@ where
.iter_mut() .iter_mut()
.zip(psbt.global.unsigned_tx.output.iter()) .zip(psbt.global.unsigned_tx.output.iter())
{ {
if let Some((script_type, child)) = self if let Some((keychain, child)) = self
.database .database
.borrow() .borrow()
.get_path_from_script_pubkey(&tx_output.script_pubkey)? .get_path_from_script_pubkey(&tx_output.script_pubkey)?
{ {
let (desc, _) = self.get_descriptor_for_script_type(script_type); let (desc, _) = self.get_descriptor_for_keychain(keychain);
psbt_output.hd_keypaths = desc.get_hd_keypaths(child, &self.secp)?; psbt_output.hd_keypaths = desc.get_hd_keypaths(child, &self.secp)?;
if builder.include_output_redeem_witness_script { if builder.include_output_redeem_witness_script {
let derived_descriptor = desc.derive(ChildNumber::from_normal_idx(child)?); let derived_descriptor = desc.derive(ChildNumber::from_normal_idx(child)?);
@ -1294,15 +1290,15 @@ where
// try to add hd_keypaths if we've already seen the output // try to add hd_keypaths if we've already seen the output
for (psbt_input, out) in psbt.inputs.iter_mut().zip(input_utxos.iter()) { for (psbt_input, out) in psbt.inputs.iter_mut().zip(input_utxos.iter()) {
if let Some(out) = out { if let Some(out) = out {
if let Some((script_type, child)) = self if let Some((keychain, child)) = self
.database .database
.borrow() .borrow()
.get_path_from_script_pubkey(&out.script_pubkey)? .get_path_from_script_pubkey(&out.script_pubkey)?
{ {
debug!("Found descriptor {:?}/{}", script_type, child); debug!("Found descriptor {:?}/{}", keychain, child);
// merge hd_keypaths // merge hd_keypaths
let (desc, _) = self.get_descriptor_for_script_type(script_type); let (desc, _) = self.get_descriptor_for_keychain(keychain);
let mut hd_keypaths = desc.get_hd_keypaths(child, &self.secp)?; let mut hd_keypaths = desc.get_hd_keypaths(child, &self.secp)?;
psbt_input.hd_keypaths.append(&mut hd_keypaths); psbt_input.hd_keypaths.append(&mut hd_keypaths);
} }
@ -1353,11 +1349,11 @@ where
if self if self
.database .database
.borrow() .borrow()
.get_script_pubkey_from_path(ScriptType::External, max_address.saturating_sub(1))? .get_script_pubkey_from_path(KeychainKind::External, max_address.saturating_sub(1))?
.is_none() .is_none()
{ {
run_setup = true; run_setup = true;
self.cache_addresses(ScriptType::External, 0, max_address)?; self.cache_addresses(KeychainKind::External, 0, max_address)?;
} }
if let Some(change_descriptor) = &self.change_descriptor { if let Some(change_descriptor) = &self.change_descriptor {
@ -1369,11 +1365,11 @@ where
if self if self
.database .database
.borrow() .borrow()
.get_script_pubkey_from_path(ScriptType::Internal, max_address.saturating_sub(1))? .get_script_pubkey_from_path(KeychainKind::Internal, max_address.saturating_sub(1))?
.is_none() .is_none()
{ {
run_setup = true; run_setup = true;
self.cache_addresses(ScriptType::Internal, 0, max_address)?; self.cache_addresses(KeychainKind::Internal, 0, max_address)?;
} }
} }
@ -1425,7 +1421,7 @@ mod test {
use crate::database::memory::MemoryDatabase; use crate::database::memory::MemoryDatabase;
use crate::database::Database; use crate::database::Database;
use crate::types::ScriptType; use crate::types::KeychainKind;
use super::*; use super::*;
@ -1452,13 +1448,13 @@ mod test {
assert!(wallet assert!(wallet
.database .database
.borrow_mut() .borrow_mut()
.get_script_pubkey_from_path(ScriptType::External, 0) .get_script_pubkey_from_path(KeychainKind::External, 0)
.unwrap() .unwrap()
.is_some()); .is_some());
assert!(wallet assert!(wallet
.database .database
.borrow_mut() .borrow_mut()
.get_script_pubkey_from_path(ScriptType::Internal, 0) .get_script_pubkey_from_path(KeychainKind::Internal, 0)
.unwrap() .unwrap()
.is_none()); .is_none());
} }
@ -1480,13 +1476,13 @@ mod test {
assert!(wallet assert!(wallet
.database .database
.borrow_mut() .borrow_mut()
.get_script_pubkey_from_path(ScriptType::External, CACHE_ADDR_BATCH_SIZE - 1) .get_script_pubkey_from_path(KeychainKind::External, CACHE_ADDR_BATCH_SIZE - 1)
.unwrap() .unwrap()
.is_some()); .is_some());
assert!(wallet assert!(wallet
.database .database
.borrow_mut() .borrow_mut()
.get_script_pubkey_from_path(ScriptType::External, CACHE_ADDR_BATCH_SIZE) .get_script_pubkey_from_path(KeychainKind::External, CACHE_ADDR_BATCH_SIZE)
.unwrap() .unwrap()
.is_none()); .is_none());
} }
@ -1503,7 +1499,7 @@ mod test {
assert!(wallet assert!(wallet
.database .database
.borrow_mut() .borrow_mut()
.get_script_pubkey_from_path(ScriptType::External, CACHE_ADDR_BATCH_SIZE - 1) .get_script_pubkey_from_path(KeychainKind::External, CACHE_ADDR_BATCH_SIZE - 1)
.unwrap() .unwrap()
.is_some()); .is_some());
@ -1514,7 +1510,7 @@ mod test {
assert!(wallet assert!(wallet
.database .database
.borrow_mut() .borrow_mut()
.get_script_pubkey_from_path(ScriptType::External, CACHE_ADDR_BATCH_SIZE * 2 - 1) .get_script_pubkey_from_path(KeychainKind::External, CACHE_ADDR_BATCH_SIZE * 2 - 1)
.unwrap() .unwrap()
.is_some()); .is_some());
} }
@ -2311,7 +2307,7 @@ mod test {
fn test_create_tx_policy_path_no_csv() { fn test_create_tx_policy_path_no_csv() {
let (wallet, _, _) = get_funded_wallet(get_test_a_or_b_plus_csv()); let (wallet, _, _) = get_funded_wallet(get_test_a_or_b_plus_csv());
let external_policy = wallet.policies(ScriptType::External).unwrap().unwrap(); let external_policy = wallet.policies(KeychainKind::External).unwrap().unwrap();
let root_id = external_policy.id; let root_id = external_policy.id;
// child #0 is just the key "A" // child #0 is just the key "A"
let path = vec![(root_id, vec![0])].into_iter().collect(); let path = vec![(root_id, vec![0])].into_iter().collect();
@ -2320,7 +2316,7 @@ mod test {
let (psbt, _) = wallet let (psbt, _) = wallet
.create_tx( .create_tx(
TxBuilder::with_recipients(vec![(addr.script_pubkey(), 30_000)]) TxBuilder::with_recipients(vec![(addr.script_pubkey(), 30_000)])
.policy_path(path, ScriptType::External), .policy_path(path, KeychainKind::External),
) )
.unwrap(); .unwrap();
@ -2331,7 +2327,7 @@ mod test {
fn test_create_tx_policy_path_use_csv() { fn test_create_tx_policy_path_use_csv() {
let (wallet, _, _) = get_funded_wallet(get_test_a_or_b_plus_csv()); let (wallet, _, _) = get_funded_wallet(get_test_a_or_b_plus_csv());
let external_policy = wallet.policies(ScriptType::External).unwrap().unwrap(); let external_policy = wallet.policies(KeychainKind::External).unwrap().unwrap();
let root_id = external_policy.id; let root_id = external_policy.id;
// child #1 is or(pk(B),older(144)) // child #1 is or(pk(B),older(144))
let path = vec![(root_id, vec![1])].into_iter().collect(); let path = vec![(root_id, vec![1])].into_iter().collect();
@ -2340,7 +2336,7 @@ mod test {
let (psbt, _) = wallet let (psbt, _) = wallet
.create_tx( .create_tx(
TxBuilder::with_recipients(vec![(addr.script_pubkey(), 30_000)]) TxBuilder::with_recipients(vec![(addr.script_pubkey(), 30_000)])
.policy_path(path, ScriptType::External), .policy_path(path, KeychainKind::External),
) )
.unwrap(); .unwrap();

View File

@ -81,7 +81,7 @@
//! let descriptor = "wpkh(tpubD6NzVbkrYhZ4Xferm7Pz4VnjdcDPFyjVu5K4iZXQ4pVN8Cks4pHVowTBXBKRhX64pkRyJZJN5xAKj4UDNnLPb5p2sSKXhewoYx5GbTdUFWq/*)"; //! let descriptor = "wpkh(tpubD6NzVbkrYhZ4Xferm7Pz4VnjdcDPFyjVu5K4iZXQ4pVN8Cks4pHVowTBXBKRhX64pkRyJZJN5xAKj4UDNnLPb5p2sSKXhewoYx5GbTdUFWq/*)";
//! let mut wallet: OfflineWallet<_> = Wallet::new_offline(descriptor, None, Network::Testnet, MemoryDatabase::default())?; //! let mut wallet: OfflineWallet<_> = Wallet::new_offline(descriptor, None, Network::Testnet, MemoryDatabase::default())?;
//! wallet.add_signer( //! wallet.add_signer(
//! ScriptType::External, //! KeychainKind::External,
//! Fingerprint::from_str("e30f11b8").unwrap().into(), //! Fingerprint::from_str("e30f11b8").unwrap().into(),
//! SignerOrdering(200), //! SignerOrdering(200),
//! Arc::new(custom_signer) //! Arc::new(custom_signer)

View File

@ -51,7 +51,7 @@ use bitcoin::{OutPoint, Script, SigHashType, Transaction};
use super::coin_selection::{CoinSelectionAlgorithm, DefaultCoinSelectionAlgorithm}; use super::coin_selection::{CoinSelectionAlgorithm, DefaultCoinSelectionAlgorithm};
use crate::database::Database; use crate::database::Database;
use crate::types::{FeeRate, ScriptType, UTXO}; use crate::types::{FeeRate, KeychainKind, UTXO};
/// Context in which the [`TxBuilder`] is valid /// Context in which the [`TxBuilder`] is valid
pub trait TxBuilderContext: std::fmt::Debug + Default + Clone {} pub trait TxBuilderContext: std::fmt::Debug + Default + Clone {}
@ -163,7 +163,7 @@ impl<D: Database, Cs: CoinSelectionAlgorithm<D>, Ctx: TxBuilderContext> TxBuilde
self self
} }
/// Set the policy path to use while creating the transaction for a given script type /// Set the policy path to use while creating the transaction for a given keychain.
/// ///
/// This method accepts a map where the key is the policy node id (see /// This method accepts a map where the key is the policy node id (see
/// [`Policy::id`](crate::descriptor::Policy::id)) and the value is the list of the indexes of /// [`Policy::id`](crate::descriptor::Policy::id)) and the value is the list of the indexes of
@ -215,17 +215,17 @@ impl<D: Database, Cs: CoinSelectionAlgorithm<D>, Ctx: TxBuilderContext> TxBuilde
/// path.insert("aabbccdd".to_string(), vec![0, 1]); /// path.insert("aabbccdd".to_string(), vec![0, 1]);
/// ///
/// let builder = TxBuilder::with_recipients(vec![(to_address.script_pubkey(), 50_000)]) /// let builder = TxBuilder::with_recipients(vec![(to_address.script_pubkey(), 50_000)])
/// .policy_path(path, ScriptType::External); /// .policy_path(path, KeychainKind::External);
/// # let builder: TxBuilder<bdk::database::MemoryDatabase, _, _> = builder; /// # let builder: TxBuilder<bdk::database::MemoryDatabase, _, _> = builder;
/// ``` /// ```
pub fn policy_path( pub fn policy_path(
mut self, mut self,
policy_path: BTreeMap<String, Vec<usize>>, policy_path: BTreeMap<String, Vec<usize>>,
script_type: ScriptType, keychain: KeychainKind,
) -> Self { ) -> Self {
let to_update = match script_type { let to_update = match keychain {
ScriptType::Internal => &mut self.internal_policy_path, KeychainKind::Internal => &mut self.internal_policy_path,
ScriptType::External => &mut self.external_policy_path, KeychainKind::External => &mut self.external_policy_path,
}; };
*to_update = Some(policy_path); *to_update = Some(policy_path);
@ -585,8 +585,8 @@ impl ChangeSpendPolicy {
pub(crate) fn is_satisfied_by(&self, utxo: &UTXO) -> bool { pub(crate) fn is_satisfied_by(&self, utxo: &UTXO) -> bool {
match self { match self {
ChangeSpendPolicy::ChangeAllowed => true, ChangeSpendPolicy::ChangeAllowed => true,
ChangeSpendPolicy::OnlyChange => utxo.script_type == ScriptType::Internal, ChangeSpendPolicy::OnlyChange => utxo.keychain == KeychainKind::Internal,
ChangeSpendPolicy::ChangeForbidden => utxo.script_type == ScriptType::External, ChangeSpendPolicy::ChangeForbidden => utxo.keychain == KeychainKind::External,
} }
} }
} }
@ -681,7 +681,7 @@ mod test {
vout: 0, vout: 0,
}, },
txout: Default::default(), txout: Default::default(),
script_type: ScriptType::External, keychain: KeychainKind::External,
}, },
UTXO { UTXO {
outpoint: OutPoint { outpoint: OutPoint {
@ -689,7 +689,7 @@ mod test {
vout: 1, vout: 1,
}, },
txout: Default::default(), txout: Default::default(),
script_type: ScriptType::Internal, keychain: KeychainKind::Internal,
}, },
] ]
} }
@ -714,7 +714,7 @@ mod test {
.collect::<Vec<_>>(); .collect::<Vec<_>>();
assert_eq!(filtered.len(), 1); assert_eq!(filtered.len(), 1);
assert_eq!(filtered[0].script_type, ScriptType::External); assert_eq!(filtered[0].keychain, KeychainKind::External);
} }
#[test] #[test]
@ -726,7 +726,7 @@ mod test {
.collect::<Vec<_>>(); .collect::<Vec<_>>();
assert_eq!(filtered.len(), 1); assert_eq!(filtered.len(), 1);
assert_eq!(filtered[0].script_type, ScriptType::Internal); assert_eq!(filtered[0].keychain, KeychainKind::Internal);
} }
#[test] #[test]

View File

@ -82,7 +82,7 @@ pub fn bdk_blockchain_tests(attr: TokenStream, item: TokenStream) -> TokenStream
use #root_ident::blockchain::{Blockchain, noop_progress}; use #root_ident::blockchain::{Blockchain, noop_progress};
use #root_ident::descriptor::ExtendedDescriptor; use #root_ident::descriptor::ExtendedDescriptor;
use #root_ident::database::MemoryDatabase; use #root_ident::database::MemoryDatabase;
use #root_ident::types::ScriptType; use #root_ident::types::KeychainKind;
use #root_ident::{Wallet, TxBuilder, FeeRate}; use #root_ident::{Wallet, TxBuilder, FeeRate};
use super::*; use super::*;
@ -120,7 +120,7 @@ pub fn bdk_blockchain_tests(attr: TokenStream, item: TokenStream) -> TokenStream
wallet.sync(noop_progress(), None).unwrap(); wallet.sync(noop_progress(), None).unwrap();
assert_eq!(wallet.get_balance().unwrap(), 50_000); assert_eq!(wallet.get_balance().unwrap(), 50_000);
assert_eq!(wallet.list_unspent().unwrap()[0].script_type, ScriptType::External); assert_eq!(wallet.list_unspent().unwrap()[0].keychain, KeychainKind::External);
let list_tx_item = &wallet.list_transactions(false).unwrap()[0]; let list_tx_item = &wallet.list_transactions(false).unwrap()[0];
assert_eq!(list_tx_item.txid, txid); assert_eq!(list_tx_item.txid, txid);