Use miniscript::DescriptorPublicKey
This allows us to remove all our custom "ExtendedDescriptor" implementation since that is now built directly in miniscript.
This commit is contained in:
@@ -1,372 +0,0 @@
|
||||
use std::fmt::{self, Display};
|
||||
use std::str::FromStr;
|
||||
|
||||
use bitcoin::hashes::hex::{FromHex, ToHex};
|
||||
use bitcoin::secp256k1;
|
||||
use bitcoin::util::base58;
|
||||
use bitcoin::util::bip32::{
|
||||
ChildNumber, DerivationPath, ExtendedPrivKey, ExtendedPubKey, Fingerprint,
|
||||
};
|
||||
use bitcoin::PublicKey;
|
||||
|
||||
#[allow(unused_imports)]
|
||||
use log::{debug, error, info, trace};
|
||||
|
||||
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
|
||||
pub enum DerivationIndex {
|
||||
Fixed,
|
||||
Normal,
|
||||
Hardened,
|
||||
}
|
||||
|
||||
impl DerivationIndex {
|
||||
fn as_path(&self, index: u32) -> DerivationPath {
|
||||
match self {
|
||||
DerivationIndex::Fixed => vec![],
|
||||
DerivationIndex::Normal => vec![ChildNumber::Normal { index }],
|
||||
DerivationIndex::Hardened => vec![ChildNumber::Hardened { index }],
|
||||
}
|
||||
.into()
|
||||
}
|
||||
}
|
||||
|
||||
impl Display for DerivationIndex {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
let chars = match *self {
|
||||
Self::Fixed => "",
|
||||
Self::Normal => "/*",
|
||||
Self::Hardened => "/*'",
|
||||
};
|
||||
|
||||
write!(f, "{}", chars)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct DescriptorExtendedKey {
|
||||
pub master_fingerprint: Option<Fingerprint>,
|
||||
pub master_derivation: Option<DerivationPath>,
|
||||
pub pubkey: ExtendedPubKey,
|
||||
pub secret: Option<ExtendedPrivKey>,
|
||||
pub path: DerivationPath,
|
||||
pub final_index: DerivationIndex,
|
||||
}
|
||||
|
||||
impl DescriptorExtendedKey {
|
||||
pub fn full_path(&self, index: u32) -> DerivationPath {
|
||||
let mut final_path: Vec<ChildNumber> = Vec::new();
|
||||
if let Some(path) = &self.master_derivation {
|
||||
let path_as_vec: Vec<ChildNumber> = path.clone().into();
|
||||
final_path.extend_from_slice(&path_as_vec);
|
||||
}
|
||||
let our_path: Vec<ChildNumber> = self.path_with_index(index).into();
|
||||
final_path.extend_from_slice(&our_path);
|
||||
|
||||
final_path.into()
|
||||
}
|
||||
|
||||
pub fn path_with_index(&self, index: u32) -> DerivationPath {
|
||||
let mut final_path: Vec<ChildNumber> = Vec::new();
|
||||
let our_path: Vec<ChildNumber> = self.path.clone().into();
|
||||
final_path.extend_from_slice(&our_path);
|
||||
let other_path: Vec<ChildNumber> = self.final_index.as_path(index).into();
|
||||
final_path.extend_from_slice(&other_path);
|
||||
|
||||
final_path.into()
|
||||
}
|
||||
|
||||
pub fn derive<C: secp256k1::Verification + secp256k1::Signing>(
|
||||
&self,
|
||||
ctx: &secp256k1::Secp256k1<C>,
|
||||
index: u32,
|
||||
) -> Result<PublicKey, super::Error> {
|
||||
Ok(self.derive_xpub(ctx, index)?.public_key)
|
||||
}
|
||||
|
||||
pub fn derive_xpub<C: secp256k1::Verification + secp256k1::Signing>(
|
||||
&self,
|
||||
ctx: &secp256k1::Secp256k1<C>,
|
||||
index: u32,
|
||||
) -> Result<ExtendedPubKey, super::Error> {
|
||||
if let Some(xprv) = self.secret {
|
||||
let derive_priv = xprv.derive_priv(ctx, &self.path_with_index(index))?;
|
||||
Ok(ExtendedPubKey::from_private(ctx, &derive_priv))
|
||||
} else {
|
||||
Ok(self.pubkey.derive_pub(ctx, &self.path_with_index(index))?)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn root_xpub<C: secp256k1::Verification + secp256k1::Signing>(
|
||||
&self,
|
||||
ctx: &secp256k1::Secp256k1<C>,
|
||||
) -> ExtendedPubKey {
|
||||
if let Some(ref xprv) = self.secret {
|
||||
ExtendedPubKey::from_private(ctx, xprv)
|
||||
} else {
|
||||
self.pubkey
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Display for DescriptorExtendedKey {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
if let Some(ref fingerprint) = self.master_fingerprint {
|
||||
write!(f, "[{}", fingerprint.to_hex())?;
|
||||
if let Some(ref path) = self.master_derivation {
|
||||
write!(f, "{}", &path.to_string()[1..])?;
|
||||
}
|
||||
write!(f, "]")?;
|
||||
}
|
||||
|
||||
if let Some(xprv) = self.secret {
|
||||
write!(f, "{}", xprv)?
|
||||
} else {
|
||||
write!(f, "{}", self.pubkey)?
|
||||
}
|
||||
|
||||
write!(f, "{}{}", &self.path.to_string()[1..], self.final_index)
|
||||
}
|
||||
}
|
||||
|
||||
impl FromStr for DescriptorExtendedKey {
|
||||
type Err = super::Error;
|
||||
|
||||
fn from_str(inp: &str) -> Result<DescriptorExtendedKey, Self::Err> {
|
||||
let len = inp.len();
|
||||
|
||||
let (master_fingerprint, master_derivation, offset) = match inp.starts_with("[") {
|
||||
false => (None, None, 0),
|
||||
true => {
|
||||
if inp.len() < 9 {
|
||||
return Err(super::Error::MalformedInput);
|
||||
}
|
||||
|
||||
let master_fingerprint = &inp[1..9];
|
||||
let close_bracket_index =
|
||||
&inp[9..].find("]").ok_or(super::Error::MalformedInput)?;
|
||||
let path = if *close_bracket_index > 0 {
|
||||
Some(DerivationPath::from_str(&format!(
|
||||
"m{}",
|
||||
&inp[9..9 + *close_bracket_index]
|
||||
))?)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
(
|
||||
Some(Fingerprint::from_hex(master_fingerprint)?),
|
||||
path,
|
||||
9 + *close_bracket_index + 1,
|
||||
)
|
||||
}
|
||||
};
|
||||
|
||||
let (key_range, offset) = match &inp[offset..].find("/") {
|
||||
Some(index) => (offset..offset + *index, offset + *index),
|
||||
None => (offset..len, len),
|
||||
};
|
||||
let data = base58::from_check(&inp[key_range.clone()])?;
|
||||
let secp = secp256k1::Secp256k1::new();
|
||||
let (pubkey, secret) = match &data[0..4] {
|
||||
[0x04u8, 0x88, 0xB2, 0x1E] | [0x04u8, 0x35, 0x87, 0xCF] => {
|
||||
(ExtendedPubKey::from_str(&inp[key_range])?, None)
|
||||
}
|
||||
[0x04u8, 0x88, 0xAD, 0xE4] | [0x04u8, 0x35, 0x83, 0x94] => {
|
||||
let private = ExtendedPrivKey::from_str(&inp[key_range])?;
|
||||
(ExtendedPubKey::from_private(&secp, &private), Some(private))
|
||||
}
|
||||
data => return Err(super::Error::InvalidPrefix(data.into())),
|
||||
};
|
||||
|
||||
let (path, final_index, _) = match &inp[offset..].starts_with("/") {
|
||||
false => (DerivationPath::from(vec![]), DerivationIndex::Fixed, offset),
|
||||
true => {
|
||||
let (all, skip) = match &inp[len - 2..len] {
|
||||
"/*" => (DerivationIndex::Normal, 2),
|
||||
"*'" | "*h" => (DerivationIndex::Hardened, 3),
|
||||
_ => (DerivationIndex::Fixed, 0),
|
||||
};
|
||||
|
||||
if all == DerivationIndex::Hardened && secret.is_none() {
|
||||
return Err(super::Error::HardenedDerivationOnXpub);
|
||||
}
|
||||
|
||||
(
|
||||
DerivationPath::from_str(&format!("m{}", &inp[offset..len - skip]))?,
|
||||
all,
|
||||
len,
|
||||
)
|
||||
}
|
||||
};
|
||||
|
||||
if secret.is_none()
|
||||
&& path.into_iter().any(|child| match child {
|
||||
ChildNumber::Hardened { .. } => true,
|
||||
_ => false,
|
||||
})
|
||||
{
|
||||
return Err(super::Error::HardenedDerivationOnXpub);
|
||||
}
|
||||
|
||||
Ok(DescriptorExtendedKey {
|
||||
master_fingerprint,
|
||||
master_derivation,
|
||||
pubkey,
|
||||
secret,
|
||||
path,
|
||||
final_index,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
use std::str::FromStr;
|
||||
|
||||
use bitcoin::hashes::hex::FromHex;
|
||||
use bitcoin::util::bip32::{ChildNumber, DerivationPath};
|
||||
|
||||
use crate::descriptor::*;
|
||||
|
||||
macro_rules! hex_fingerprint {
|
||||
($hex:expr) => {
|
||||
Fingerprint::from_hex($hex).unwrap()
|
||||
};
|
||||
}
|
||||
|
||||
macro_rules! deriv_path {
|
||||
($str:expr) => {
|
||||
DerivationPath::from_str($str).unwrap()
|
||||
};
|
||||
|
||||
() => {
|
||||
DerivationPath::from(vec![])
|
||||
};
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_derivation_index_fixed() {
|
||||
let index = DerivationIndex::Fixed;
|
||||
assert_eq!(index.as_path(1337), DerivationPath::from(vec![]));
|
||||
assert_eq!(format!("{}", index), "");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_derivation_index_normal() {
|
||||
let index = DerivationIndex::Normal;
|
||||
assert_eq!(
|
||||
index.as_path(1337),
|
||||
DerivationPath::from(vec![ChildNumber::Normal { index: 1337 }])
|
||||
);
|
||||
assert_eq!(format!("{}", index), "/*");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_derivation_index_hardened() {
|
||||
let index = DerivationIndex::Hardened;
|
||||
assert_eq!(
|
||||
index.as_path(1337),
|
||||
DerivationPath::from(vec![ChildNumber::Hardened { index: 1337 }])
|
||||
);
|
||||
assert_eq!(format!("{}", index), "/*'");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_parse_xpub_no_path_fixed() {
|
||||
let key = "xpub6ERApfZwUNrhLCkDtcHTcxd75RbzS1ed54G1LkBUHQVHQKqhMkhgbmJbZRkrgZw4koxb5JaHWkY4ALHY2grBGRjaDMzQLcgJvLJuZZvRcEL";
|
||||
let ek = DescriptorExtendedKey::from_str(key).unwrap();
|
||||
assert_eq!(ek.pubkey.fingerprint(), hex_fingerprint!("31a507b8"));
|
||||
assert_eq!(ek.path, deriv_path!());
|
||||
assert_eq!(ek.final_index, DerivationIndex::Fixed);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_parse_xpub_with_path_fixed() {
|
||||
let key = "xpub6ERApfZwUNrhLCkDtcHTcxd75RbzS1ed54G1LkBUHQVHQKqhMkhgbmJbZRkrgZw4koxb5JaHWkY4ALHY2grBGRjaDMzQLcgJvLJuZZvRcEL/1/2/3";
|
||||
let ek = DescriptorExtendedKey::from_str(key).unwrap();
|
||||
assert_eq!(ek.pubkey.fingerprint(), hex_fingerprint!("31a507b8"));
|
||||
assert_eq!(ek.path, deriv_path!("m/1/2/3"));
|
||||
assert_eq!(ek.final_index, DerivationIndex::Fixed);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_parse_xpub_with_path_normal() {
|
||||
let key = "xpub6ERApfZwUNrhLCkDtcHTcxd75RbzS1ed54G1LkBUHQVHQKqhMkhgbmJbZRkrgZw4koxb5JaHWkY4ALHY2grBGRjaDMzQLcgJvLJuZZvRcEL/1/2/3/*";
|
||||
let ek = DescriptorExtendedKey::from_str(key).unwrap();
|
||||
assert_eq!(ek.pubkey.fingerprint(), hex_fingerprint!("31a507b8"));
|
||||
assert_eq!(ek.path, deriv_path!("m/1/2/3"));
|
||||
assert_eq!(ek.final_index, DerivationIndex::Normal);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[should_panic(expected = "HardenedDerivationOnXpub")]
|
||||
fn test_parse_xpub_with_path_hardened() {
|
||||
let key = "xpub6ERApfZwUNrhLCkDtcHTcxd75RbzS1ed54G1LkBUHQVHQKqhMkhgbmJbZRkrgZw4koxb5JaHWkY4ALHY2grBGRjaDMzQLcgJvLJuZZvRcEL/*'";
|
||||
let ek = DescriptorExtendedKey::from_str(key).unwrap();
|
||||
assert_eq!(ek.pubkey.fingerprint(), hex_fingerprint!("31a507b8"));
|
||||
assert_eq!(ek.path, deriv_path!("m/1/2/3"));
|
||||
assert_eq!(ek.final_index, DerivationIndex::Fixed);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_parse_tprv_with_path_hardened() {
|
||||
let key = "tprv8ZgxMBicQKsPduL5QnGihpprdHyypMGi4DhimjtzYemu7se5YQNcZfAPLqXRuGHb5ZX2eTQj62oNqMnyxJ7B7wz54Uzswqw8fFqMVdcmVF7/1/2/3/*'";
|
||||
let ek = DescriptorExtendedKey::from_str(key).unwrap();
|
||||
assert!(ek.secret.is_some());
|
||||
assert_eq!(ek.pubkey.fingerprint(), hex_fingerprint!("5ea4190e"));
|
||||
assert_eq!(ek.path, deriv_path!("m/1/2/3"));
|
||||
assert_eq!(ek.final_index, DerivationIndex::Hardened);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_parse_xpub_master_details() {
|
||||
let key = "[d34db33f/44'/0'/0']xpub6ERApfZwUNrhLCkDtcHTcxd75RbzS1ed54G1LkBUHQVHQKqhMkhgbmJbZRkrgZw4koxb5JaHWkY4ALHY2grBGRjaDMzQLcgJvLJuZZvRcEL";
|
||||
let ek = DescriptorExtendedKey::from_str(key).unwrap();
|
||||
assert_eq!(ek.master_fingerprint, Some(hex_fingerprint!("d34db33f")));
|
||||
assert_eq!(ek.master_derivation, Some(deriv_path!("m/44'/0'/0'")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_parse_xpub_master_details_empty_derivation() {
|
||||
let key = "[d34db33f]xpub6ERApfZwUNrhLCkDtcHTcxd75RbzS1ed54G1LkBUHQVHQKqhMkhgbmJbZRkrgZw4koxb5JaHWkY4ALHY2grBGRjaDMzQLcgJvLJuZZvRcEL";
|
||||
let ek = DescriptorExtendedKey::from_str(key).unwrap();
|
||||
assert_eq!(ek.master_fingerprint, Some(hex_fingerprint!("d34db33f")));
|
||||
assert_eq!(ek.master_derivation, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[should_panic(expected = "MalformedInput")]
|
||||
fn test_parse_xpub_short_input() {
|
||||
let key = "[d34d";
|
||||
DescriptorExtendedKey::from_str(key).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[should_panic(expected = "MalformedInput")]
|
||||
fn test_parse_xpub_missing_closing_bracket() {
|
||||
let key = "[d34db33fxpub6ERApfZwUNrhLCkDtcHTcxd75RbzS1ed54G1LkBUHQVHQKqhMkhgbmJbZRkrgZw4koxb5JaHWkY4ALHY2grBGRjaDMzQLcgJvLJuZZvRcEL";
|
||||
DescriptorExtendedKey::from_str(key).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[should_panic(expected = "InvalidChar")]
|
||||
fn test_parse_xpub_invalid_fingerprint() {
|
||||
let key = "[d34db33z]xpub6ERApfZwUNrhLCkDtcHTcxd75RbzS1ed54G1LkBUHQVHQKqhMkhgbmJbZRkrgZw4koxb5JaHWkY4ALHY2grBGRjaDMzQLcgJvLJuZZvRcEL";
|
||||
DescriptorExtendedKey::from_str(key).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_xpub_normal_full_path() {
|
||||
let key = "xpub6ERApfZwUNrhLCkDtcHTcxd75RbzS1ed54G1LkBUHQVHQKqhMkhgbmJbZRkrgZw4koxb5JaHWkY4ALHY2grBGRjaDMzQLcgJvLJuZZvRcEL/1/2/*";
|
||||
let ek = DescriptorExtendedKey::from_str(key).unwrap();
|
||||
assert_eq!(ek.full_path(42), deriv_path!("m/1/2/42"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_xpub_fixed_full_path() {
|
||||
let key = "xpub6ERApfZwUNrhLCkDtcHTcxd75RbzS1ed54G1LkBUHQVHQKqhMkhgbmJbZRkrgZw4koxb5JaHWkY4ALHY2grBGRjaDMzQLcgJvLJuZZvRcEL/1/2";
|
||||
let ek = DescriptorExtendedKey::from_str(key).unwrap();
|
||||
assert_eq!(ek.full_path(42), deriv_path!("m/1/2"));
|
||||
assert_eq!(ek.full_path(1337), deriv_path!("m/1/2"));
|
||||
}
|
||||
}
|
||||
@@ -1,181 +0,0 @@
|
||||
use bitcoin::secp256k1::{All, Secp256k1};
|
||||
use bitcoin::{PrivateKey, PublicKey};
|
||||
|
||||
use bitcoin::util::bip32::{
|
||||
ChildNumber, DerivationPath, ExtendedPrivKey, ExtendedPubKey, Fingerprint,
|
||||
};
|
||||
|
||||
use super::error::Error;
|
||||
use super::extended_key::DerivationIndex;
|
||||
use super::DescriptorExtendedKey;
|
||||
|
||||
pub(super) trait Key: std::fmt::Debug + std::fmt::Display {
|
||||
fn fingerprint(&self, secp: &Secp256k1<All>) -> Option<Fingerprint>;
|
||||
fn as_public_key(&self, secp: &Secp256k1<All>, index: Option<u32>) -> Result<PublicKey, Error>;
|
||||
fn as_secret_key(&self) -> Option<PrivateKey>;
|
||||
fn xprv(&self) -> Option<ExtendedPrivKey>;
|
||||
fn full_path(&self, index: u32) -> Option<DerivationPath>;
|
||||
fn is_fixed(&self) -> bool;
|
||||
|
||||
fn has_secret(&self) -> bool {
|
||||
self.xprv().is_some() || self.as_secret_key().is_some()
|
||||
}
|
||||
|
||||
fn public(&self, secp: &Secp256k1<All>) -> Result<Box<dyn Key>, Error> {
|
||||
Ok(Box::new(self.as_public_key(secp, None)?))
|
||||
}
|
||||
}
|
||||
|
||||
impl Key for PublicKey {
|
||||
fn fingerprint(&self, _secp: &Secp256k1<All>) -> Option<Fingerprint> {
|
||||
None
|
||||
}
|
||||
|
||||
fn as_public_key(
|
||||
&self,
|
||||
_secp: &Secp256k1<All>,
|
||||
_index: Option<u32>,
|
||||
) -> Result<PublicKey, Error> {
|
||||
Ok(PublicKey::clone(self))
|
||||
}
|
||||
|
||||
fn as_secret_key(&self) -> Option<PrivateKey> {
|
||||
None
|
||||
}
|
||||
|
||||
fn xprv(&self) -> Option<ExtendedPrivKey> {
|
||||
None
|
||||
}
|
||||
|
||||
fn full_path(&self, _index: u32) -> Option<DerivationPath> {
|
||||
None
|
||||
}
|
||||
|
||||
fn is_fixed(&self) -> bool {
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
impl Key for PrivateKey {
|
||||
fn fingerprint(&self, _secp: &Secp256k1<All>) -> Option<Fingerprint> {
|
||||
None
|
||||
}
|
||||
|
||||
fn as_public_key(
|
||||
&self,
|
||||
secp: &Secp256k1<All>,
|
||||
_index: Option<u32>,
|
||||
) -> Result<PublicKey, Error> {
|
||||
Ok(self.public_key(secp))
|
||||
}
|
||||
|
||||
fn as_secret_key(&self) -> Option<PrivateKey> {
|
||||
Some(PrivateKey::clone(self))
|
||||
}
|
||||
|
||||
fn xprv(&self) -> Option<ExtendedPrivKey> {
|
||||
None
|
||||
}
|
||||
|
||||
fn full_path(&self, _index: u32) -> Option<DerivationPath> {
|
||||
None
|
||||
}
|
||||
|
||||
fn is_fixed(&self) -> bool {
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
impl Key for DescriptorExtendedKey {
|
||||
fn fingerprint(&self, secp: &Secp256k1<All>) -> Option<Fingerprint> {
|
||||
if let Some(fing) = self.master_fingerprint {
|
||||
Some(fing.clone())
|
||||
} else {
|
||||
Some(self.root_xpub(secp).fingerprint())
|
||||
}
|
||||
}
|
||||
|
||||
fn as_public_key(&self, secp: &Secp256k1<All>, index: Option<u32>) -> Result<PublicKey, Error> {
|
||||
Ok(self.derive_xpub(secp, index.unwrap_or(0))?.public_key)
|
||||
}
|
||||
|
||||
fn public(&self, secp: &Secp256k1<All>) -> Result<Box<dyn Key>, Error> {
|
||||
if self.final_index == DerivationIndex::Hardened {
|
||||
return Err(Error::HardenedDerivationOnXpub);
|
||||
}
|
||||
|
||||
if self.xprv().is_none() {
|
||||
return Ok(Box::new(self.clone()));
|
||||
}
|
||||
|
||||
// copy the part of the path that can be derived on the xpub
|
||||
let path = self
|
||||
.path
|
||||
.into_iter()
|
||||
.rev()
|
||||
.take_while(|child| match child {
|
||||
ChildNumber::Normal { .. } => true,
|
||||
_ => false,
|
||||
})
|
||||
.cloned()
|
||||
.collect::<Vec<_>>();
|
||||
// take the prefix that has to be derived on the xprv
|
||||
let master_derivation_add = self
|
||||
.path
|
||||
.into_iter()
|
||||
.take(self.path.as_ref().len() - path.len())
|
||||
.cloned()
|
||||
.collect::<Vec<_>>();
|
||||
let has_derived = !master_derivation_add.is_empty();
|
||||
|
||||
let derived_xprv = self
|
||||
.secret
|
||||
.as_ref()
|
||||
.unwrap()
|
||||
.derive_priv(secp, &master_derivation_add)?;
|
||||
let pubkey = ExtendedPubKey::from_private(secp, &derived_xprv);
|
||||
|
||||
let master_derivation = self
|
||||
.master_derivation
|
||||
.as_ref()
|
||||
.map_or(vec![], |path| path.as_ref().to_vec())
|
||||
.into_iter()
|
||||
.chain(master_derivation_add.into_iter())
|
||||
.collect::<Vec<_>>();
|
||||
let master_derivation = match &master_derivation[..] {
|
||||
&[] => None,
|
||||
child_vec => Some(child_vec.into()),
|
||||
};
|
||||
|
||||
let master_fingerprint = match self.master_fingerprint {
|
||||
Some(desc) => Some(desc.clone()),
|
||||
None if has_derived => Some(self.fingerprint(secp).unwrap()),
|
||||
_ => None,
|
||||
};
|
||||
|
||||
Ok(Box::new(DescriptorExtendedKey {
|
||||
master_fingerprint,
|
||||
master_derivation,
|
||||
pubkey,
|
||||
secret: None,
|
||||
path: path.into(),
|
||||
final_index: self.final_index,
|
||||
}))
|
||||
}
|
||||
|
||||
fn as_secret_key(&self) -> Option<PrivateKey> {
|
||||
None
|
||||
}
|
||||
|
||||
fn xprv(&self) -> Option<ExtendedPrivKey> {
|
||||
self.secret
|
||||
}
|
||||
|
||||
fn full_path(&self, index: u32) -> Option<DerivationPath> {
|
||||
Some(self.full_path(index))
|
||||
}
|
||||
|
||||
fn is_fixed(&self) -> bool {
|
||||
self.final_index == DerivationIndex::Fixed
|
||||
}
|
||||
}
|
||||
@@ -1,45 +1,275 @@
|
||||
use std::cell::RefCell;
|
||||
use std::collections::BTreeMap;
|
||||
use std::convert::{Into, TryFrom};
|
||||
use std::collections::{BTreeMap, HashMap};
|
||||
use std::fmt;
|
||||
use std::str::FromStr;
|
||||
use std::sync::Arc;
|
||||
|
||||
use bitcoin::hashes::{hash160, Hash};
|
||||
use bitcoin::secp256k1::{All, Secp256k1};
|
||||
use bitcoin::util::bip32::{DerivationPath, ExtendedPrivKey, Fingerprint};
|
||||
use bitcoin::util::psbt::PartiallySignedTransaction as PSBT;
|
||||
use bitcoin::{PrivateKey, PublicKey, Script};
|
||||
use bitcoin::hashes::hash160;
|
||||
use bitcoin::secp256k1::Secp256k1;
|
||||
use bitcoin::util::bip32::{ChildNumber, DerivationPath, Fingerprint};
|
||||
use bitcoin::util::psbt;
|
||||
use bitcoin::{PublicKey, Script, TxOut};
|
||||
|
||||
use miniscript::descriptor::{DescriptorPublicKey, DescriptorXKey, InnerXKey};
|
||||
pub use miniscript::{
|
||||
Descriptor, Legacy, Miniscript, MiniscriptKey, ScriptContext, Segwitv0, Terminal,
|
||||
Descriptor, Legacy, Miniscript, MiniscriptKey, ScriptContext, Segwitv0, Terminal, ToPublicKey,
|
||||
};
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::psbt::utils::PSBTUtils;
|
||||
|
||||
pub mod checksum;
|
||||
pub mod error;
|
||||
pub mod extended_key;
|
||||
mod keys;
|
||||
pub mod policy;
|
||||
|
||||
// use crate::wallet::utils::AddressType;
|
||||
use crate::wallet::signer::SignersContainer;
|
||||
|
||||
pub use self::checksum::get_checksum;
|
||||
use self::error::Error;
|
||||
pub use self::extended_key::{DerivationIndex, DescriptorExtendedKey};
|
||||
pub use self::policy::Policy;
|
||||
|
||||
use self::keys::Key;
|
||||
pub type ExtendedDescriptor = Descriptor<DescriptorPublicKey>;
|
||||
type HDKeyPaths = BTreeMap<PublicKey, (Fingerprint, DerivationPath)>;
|
||||
|
||||
trait MiniscriptExtractPolicy {
|
||||
pub trait ExtractPolicy {
|
||||
fn extract_policy(
|
||||
&self,
|
||||
lookup_map: &BTreeMap<String, Box<dyn Key>>,
|
||||
signers: Arc<SignersContainer<DescriptorPublicKey>>,
|
||||
) -> Result<Option<Policy>, Error>;
|
||||
}
|
||||
|
||||
pub trait ExtractPolicy {
|
||||
fn extract_policy(&self) -> Result<Option<Policy>, Error>;
|
||||
pub trait XKeyUtils {
|
||||
fn full_path(&self, append: &[ChildNumber]) -> DerivationPath;
|
||||
fn root_fingerprint(&self) -> Fingerprint;
|
||||
}
|
||||
|
||||
impl<K: InnerXKey> XKeyUtils for DescriptorXKey<K> {
|
||||
fn full_path(&self, append: &[ChildNumber]) -> DerivationPath {
|
||||
let full_path = match &self.source {
|
||||
&Some((_, ref path)) => path
|
||||
.into_iter()
|
||||
.chain(self.derivation_path.into_iter())
|
||||
.cloned()
|
||||
.collect(),
|
||||
&None => self.derivation_path.clone(),
|
||||
};
|
||||
|
||||
if self.is_wildcard {
|
||||
full_path
|
||||
.into_iter()
|
||||
.chain(append.into_iter())
|
||||
.cloned()
|
||||
.collect()
|
||||
} else {
|
||||
full_path
|
||||
}
|
||||
}
|
||||
|
||||
fn root_fingerprint(&self) -> Fingerprint {
|
||||
match &self.source {
|
||||
&Some((fingerprint, _)) => fingerprint.clone(),
|
||||
&None => self.xkey.xkey_fingerprint(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub trait DescriptorMeta: Sized {
|
||||
fn is_witness(&self) -> bool;
|
||||
fn get_hd_keypaths(&self, index: u32) -> Result<HDKeyPaths, Error>;
|
||||
fn is_fixed(&self) -> bool;
|
||||
fn derive_from_hd_keypaths(&self, hd_keypaths: &HDKeyPaths) -> Option<Self>;
|
||||
fn derive_from_psbt_input(&self, psbt_input: &psbt::Input, utxo: Option<TxOut>)
|
||||
-> Option<Self>;
|
||||
// fn address_type(&self) -> Option<AddressType>;
|
||||
}
|
||||
|
||||
pub trait DescriptorScripts {
|
||||
fn psbt_redeem_script(&self) -> Option<Script>;
|
||||
fn psbt_witness_script(&self) -> Option<Script>;
|
||||
}
|
||||
|
||||
impl<T> DescriptorScripts for Descriptor<T>
|
||||
where
|
||||
T: miniscript::MiniscriptKey + miniscript::ToPublicKey,
|
||||
{
|
||||
fn psbt_redeem_script(&self) -> Option<Script> {
|
||||
match self {
|
||||
Descriptor::ShWpkh(_) => Some(self.witness_script()),
|
||||
Descriptor::ShWsh(ref script) => Some(script.encode().to_v0_p2wsh()),
|
||||
Descriptor::Sh(ref script) => Some(script.encode()),
|
||||
Descriptor::Bare(ref script) => Some(script.encode()),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn psbt_witness_script(&self) -> Option<Script> {
|
||||
match self {
|
||||
Descriptor::Wsh(ref script) => Some(script.encode()),
|
||||
Descriptor::ShWsh(ref script) => Some(script.encode()),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl DescriptorMeta for Descriptor<DescriptorPublicKey> {
|
||||
fn is_witness(&self) -> bool {
|
||||
match self {
|
||||
Descriptor::Bare(_) | Descriptor::Pk(_) | Descriptor::Pkh(_) | Descriptor::Sh(_) => {
|
||||
false
|
||||
}
|
||||
Descriptor::Wpkh(_)
|
||||
| Descriptor::ShWpkh(_)
|
||||
| Descriptor::Wsh(_)
|
||||
| Descriptor::ShWsh(_) => true,
|
||||
}
|
||||
}
|
||||
|
||||
fn get_hd_keypaths(&self, index: u32) -> Result<HDKeyPaths, Error> {
|
||||
let mut answer = BTreeMap::new();
|
||||
|
||||
let translatefpk = |key: &DescriptorPublicKey| -> Result<_, Error> {
|
||||
match key {
|
||||
DescriptorPublicKey::PubKey(_) => {}
|
||||
DescriptorPublicKey::XPub(xpub) => {
|
||||
let derive_path = if xpub.is_wildcard {
|
||||
xpub.derivation_path
|
||||
.into_iter()
|
||||
.chain([ChildNumber::from_normal_idx(index)?].iter())
|
||||
.cloned()
|
||||
.collect()
|
||||
} else {
|
||||
xpub.derivation_path.clone()
|
||||
};
|
||||
let derived_pubkey = xpub
|
||||
.xkey
|
||||
.derive_pub(&Secp256k1::verification_only(), &derive_path)?;
|
||||
|
||||
answer.insert(
|
||||
derived_pubkey.public_key,
|
||||
(
|
||||
xpub.root_fingerprint(),
|
||||
xpub.full_path(&[ChildNumber::from_normal_idx(index)?]),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
Ok(DummyKey::default())
|
||||
};
|
||||
let translatefpkh = |_: &hash160::Hash| -> Result<_, Error> { Ok(DummyKey::default()) };
|
||||
|
||||
self.translate_pk(translatefpk, translatefpkh)?;
|
||||
|
||||
Ok(answer)
|
||||
}
|
||||
|
||||
fn is_fixed(&self) -> bool {
|
||||
let mut found_wildcard = false;
|
||||
|
||||
let translatefpk = |key: &DescriptorPublicKey| -> Result<_, Error> {
|
||||
match key {
|
||||
DescriptorPublicKey::PubKey(_) => {}
|
||||
DescriptorPublicKey::XPub(xpub) => {
|
||||
if xpub.is_wildcard {
|
||||
found_wildcard = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(DummyKey::default())
|
||||
};
|
||||
let translatefpkh = |_: &hash160::Hash| -> Result<_, Error> { Ok(DummyKey::default()) };
|
||||
|
||||
self.translate_pk(translatefpk, translatefpkh).unwrap();
|
||||
|
||||
!found_wildcard
|
||||
}
|
||||
|
||||
fn derive_from_hd_keypaths(&self, hd_keypaths: &HDKeyPaths) -> Option<Self> {
|
||||
let index: HashMap<_, _> = hd_keypaths.values().cloned().collect();
|
||||
|
||||
let mut derive_path = None::<DerivationPath>;
|
||||
let translatefpk = |key: &DescriptorPublicKey| -> Result<_, Error> {
|
||||
if derive_path.is_some() {
|
||||
// already found a matching path, we are done
|
||||
return Ok(DummyKey::default());
|
||||
}
|
||||
|
||||
if let DescriptorPublicKey::XPub(xpub) = key {
|
||||
// Check if the key matches one entry in our `index`. If it does, `matches()` will
|
||||
// return the "prefix" that matched, so we remove that prefix from the full path
|
||||
// found in `index` and save it in `derive_path`
|
||||
let root_fingerprint = xpub.root_fingerprint();
|
||||
derive_path = index
|
||||
.get_key_value(&root_fingerprint)
|
||||
.and_then(|(fingerprint, path)| xpub.matches(*fingerprint, path))
|
||||
.map(|prefix_path| prefix_path.into_iter().cloned().collect::<Vec<_>>())
|
||||
.map(|prefix| {
|
||||
index
|
||||
.get(&xpub.root_fingerprint())
|
||||
.unwrap()
|
||||
.into_iter()
|
||||
.skip(prefix.len())
|
||||
.cloned()
|
||||
.collect()
|
||||
});
|
||||
}
|
||||
|
||||
Ok(DummyKey::default())
|
||||
};
|
||||
let translatefpkh = |_: &hash160::Hash| -> Result<_, Error> { Ok(DummyKey::default()) };
|
||||
|
||||
self.translate_pk(translatefpk, translatefpkh).unwrap();
|
||||
|
||||
derive_path.map(|path| self.derive(path.as_ref()))
|
||||
}
|
||||
|
||||
fn derive_from_psbt_input(
|
||||
&self,
|
||||
psbt_input: &psbt::Input,
|
||||
utxo: Option<TxOut>,
|
||||
) -> Option<Self> {
|
||||
if let Some(derived) = self.derive_from_hd_keypaths(&psbt_input.hd_keypaths) {
|
||||
return Some(derived);
|
||||
} else if !self.is_fixed() {
|
||||
// If the descriptor is not fixed we can't brute-force the derivation address, so just
|
||||
// exit here
|
||||
return None;
|
||||
}
|
||||
|
||||
match self {
|
||||
Descriptor::Pk(_)
|
||||
| Descriptor::Pkh(_)
|
||||
| Descriptor::Wpkh(_)
|
||||
| Descriptor::ShWpkh(_)
|
||||
if utxo.is_some()
|
||||
&& self.script_pubkey() == utxo.as_ref().unwrap().script_pubkey =>
|
||||
{
|
||||
Some(self.clone())
|
||||
}
|
||||
Descriptor::Bare(ms) | Descriptor::Sh(ms)
|
||||
if psbt_input.redeem_script.is_some()
|
||||
&& &ms.encode() == psbt_input.redeem_script.as_ref().unwrap() =>
|
||||
{
|
||||
Some(self.clone())
|
||||
}
|
||||
Descriptor::Wsh(ms) | Descriptor::ShWsh(ms)
|
||||
if psbt_input.witness_script.is_some()
|
||||
&& &ms.encode() == psbt_input.witness_script.as_ref().unwrap() =>
|
||||
{
|
||||
Some(self.clone())
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
// fn address_type(&self) -> Option<AddressType> {
|
||||
// match self {
|
||||
// Descriptor::Pkh(_) => Some(AddressType::Pkh),
|
||||
// Descriptor::Wpkh(_) => Some(AddressType::Wpkh),
|
||||
// Descriptor::ShWpkh(_) => Some(AddressType::ShWpkh),
|
||||
// Descriptor::Sh(_) => Some(AddressType::Sh),
|
||||
// Descriptor::Wsh(_) => Some(AddressType::Wsh),
|
||||
// Descriptor::ShWsh(_) => Some(AddressType::ShWsh),
|
||||
// _ => None,
|
||||
// }
|
||||
// }
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Hash, PartialEq, PartialOrd, Eq, Ord, Default)]
|
||||
@@ -67,480 +297,27 @@ impl miniscript::MiniscriptKey for DummyKey {
|
||||
}
|
||||
}
|
||||
|
||||
pub type DerivedDescriptor = Descriptor<PublicKey>;
|
||||
pub type StringDescriptor = Descriptor<String>;
|
||||
|
||||
pub trait DescriptorMeta {
|
||||
fn is_witness(&self) -> bool;
|
||||
fn psbt_redeem_script(&self) -> Option<Script>;
|
||||
fn psbt_witness_script(&self) -> Option<Script>;
|
||||
}
|
||||
|
||||
impl<T> DescriptorMeta for Descriptor<T>
|
||||
where
|
||||
T: miniscript::MiniscriptKey + miniscript::ToPublicKey,
|
||||
{
|
||||
fn is_witness(&self) -> bool {
|
||||
match self {
|
||||
Descriptor::Bare(_) | Descriptor::Pk(_) | Descriptor::Pkh(_) | Descriptor::Sh(_) => {
|
||||
false
|
||||
}
|
||||
Descriptor::Wpkh(_)
|
||||
| Descriptor::ShWpkh(_)
|
||||
| Descriptor::Wsh(_)
|
||||
| Descriptor::ShWsh(_) => true,
|
||||
}
|
||||
}
|
||||
|
||||
fn psbt_redeem_script(&self) -> Option<Script> {
|
||||
match self {
|
||||
Descriptor::ShWpkh(_) => Some(self.witness_script()),
|
||||
Descriptor::ShWsh(ref script) => Some(script.encode().to_v0_p2wsh()),
|
||||
Descriptor::Sh(ref script) => Some(script.encode()),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn psbt_witness_script(&self) -> Option<Script> {
|
||||
match self {
|
||||
Descriptor::Wsh(ref script) => Some(script.encode()),
|
||||
Descriptor::ShWsh(ref script) => Some(script.encode()),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[serde(try_from = "&str", into = "String")]
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
pub struct ExtendedDescriptor {
|
||||
#[serde(flatten)]
|
||||
internal: StringDescriptor,
|
||||
|
||||
#[serde(skip)]
|
||||
keys: BTreeMap<String, Box<dyn Key>>,
|
||||
|
||||
#[serde(skip)]
|
||||
ctx: Secp256k1<All>,
|
||||
}
|
||||
|
||||
impl fmt::Display for ExtendedDescriptor {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
write!(f, "{}", self.internal)
|
||||
}
|
||||
}
|
||||
|
||||
impl std::clone::Clone for ExtendedDescriptor {
|
||||
fn clone(&self) -> Self {
|
||||
Self {
|
||||
internal: self.internal.clone(),
|
||||
ctx: self.ctx.clone(),
|
||||
keys: BTreeMap::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::convert::AsRef<StringDescriptor> for ExtendedDescriptor {
|
||||
fn as_ref(&self) -> &StringDescriptor {
|
||||
&self.internal
|
||||
}
|
||||
}
|
||||
|
||||
impl ExtendedDescriptor {
|
||||
fn parse_string(string: &str) -> Result<(String, Box<dyn Key>), Error> {
|
||||
if let Ok(pk) = PublicKey::from_str(string) {
|
||||
return Ok((string.to_string(), Box::new(pk)));
|
||||
} else if let Ok(sk) = PrivateKey::from_wif(string) {
|
||||
return Ok((string.to_string(), Box::new(sk)));
|
||||
} else if let Ok(ext_key) = DescriptorExtendedKey::from_str(string) {
|
||||
return Ok((string.to_string(), Box::new(ext_key)));
|
||||
}
|
||||
|
||||
return Err(Error::KeyParsingError(string.to_string()));
|
||||
}
|
||||
|
||||
fn new(sd: StringDescriptor) -> Result<Self, Error> {
|
||||
let ctx = Secp256k1::gen_new();
|
||||
let keys: RefCell<BTreeMap<String, Box<dyn Key>>> = RefCell::new(BTreeMap::new());
|
||||
|
||||
let translatefpk = |string: &String| -> Result<_, Error> {
|
||||
let (key, parsed) = Self::parse_string(string)?;
|
||||
keys.borrow_mut().insert(key, parsed);
|
||||
|
||||
Ok(DummyKey::default())
|
||||
};
|
||||
let translatefpkh = |string: &String| -> Result<_, Error> {
|
||||
let (key, parsed) = Self::parse_string(string)?;
|
||||
keys.borrow_mut().insert(key, parsed);
|
||||
|
||||
Ok(DummyKey::default())
|
||||
};
|
||||
|
||||
sd.translate_pk(translatefpk, translatefpkh)?;
|
||||
|
||||
Ok(ExtendedDescriptor {
|
||||
internal: sd,
|
||||
keys: keys.into_inner(),
|
||||
ctx,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn derive_with_miniscript_legacy(
|
||||
&self,
|
||||
miniscript: Miniscript<PublicKey, Legacy>,
|
||||
) -> Result<DerivedDescriptor, Error> {
|
||||
let derived_desc = match self.internal {
|
||||
Descriptor::Bare(_) => Descriptor::Bare(miniscript),
|
||||
Descriptor::Sh(_) => Descriptor::Sh(miniscript),
|
||||
_ => return Err(Error::CantDeriveWithMiniscript),
|
||||
};
|
||||
|
||||
// if !self.same_structure(&derived_desc) {
|
||||
// Err(Error::CantDeriveWithMiniscript)
|
||||
// } else {
|
||||
Ok(derived_desc)
|
||||
// }
|
||||
}
|
||||
|
||||
pub fn derive_with_miniscript_segwit_v0(
|
||||
&self,
|
||||
miniscript: Miniscript<PublicKey, Segwitv0>,
|
||||
) -> Result<DerivedDescriptor, Error> {
|
||||
let derived_desc = match self.internal {
|
||||
Descriptor::Wsh(_) => Descriptor::Wsh(miniscript),
|
||||
Descriptor::ShWsh(_) => Descriptor::ShWsh(miniscript),
|
||||
_ => return Err(Error::CantDeriveWithMiniscript),
|
||||
};
|
||||
|
||||
// if !self.same_structure(&derived_desc) {
|
||||
// Err(Error::CantDeriveWithMiniscript)
|
||||
// } else {
|
||||
Ok(derived_desc)
|
||||
// }
|
||||
}
|
||||
|
||||
pub fn derive_from_psbt_input(
|
||||
&self,
|
||||
psbt: &PSBT,
|
||||
input_index: usize,
|
||||
) -> Result<DerivedDescriptor, Error> {
|
||||
let get_pk_from_partial_sigs = || {
|
||||
// here we need the public key.. since it's a single sig, there are only two
|
||||
// options: we can either find it in the `partial_sigs`, or we can't. if we
|
||||
// can't, it means that we can't even satisfy the input, so we can exit knowing
|
||||
// that we did our best to try to find it.
|
||||
psbt.inputs[input_index]
|
||||
.partial_sigs
|
||||
.keys()
|
||||
.nth(0)
|
||||
.ok_or(Error::MissingPublicKey)
|
||||
};
|
||||
|
||||
if let Some(wit_script) = &psbt.inputs[input_index].witness_script {
|
||||
self.derive_with_miniscript_segwit_v0(Miniscript::parse(wit_script)?)
|
||||
} else if let Some(p2sh_script) = &psbt.inputs[input_index].redeem_script {
|
||||
if p2sh_script.is_v0_p2wpkh() {
|
||||
// wrapped p2wpkh
|
||||
get_pk_from_partial_sigs().map(|pk| Descriptor::ShWpkh(*pk))
|
||||
} else {
|
||||
self.derive_with_miniscript_legacy(Miniscript::parse(p2sh_script)?)
|
||||
}
|
||||
} else if let Some(utxo) = psbt.get_utxo_for(input_index) {
|
||||
if utxo.script_pubkey.is_p2pkh() {
|
||||
get_pk_from_partial_sigs().map(|pk| Descriptor::Pkh(*pk))
|
||||
} else if utxo.script_pubkey.is_p2pk() {
|
||||
get_pk_from_partial_sigs().map(|pk| Descriptor::Pk(*pk))
|
||||
} else if utxo.script_pubkey.is_v0_p2wpkh() {
|
||||
get_pk_from_partial_sigs().map(|pk| Descriptor::Wpkh(*pk))
|
||||
} else {
|
||||
// try as bare script
|
||||
self.derive_with_miniscript_legacy(Miniscript::parse(&utxo.script_pubkey)?)
|
||||
}
|
||||
} else {
|
||||
Err(Error::MissingDetails)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn derive(&self, index: u32) -> Result<DerivedDescriptor, Error> {
|
||||
let translatefpk = |xpub: &String| {
|
||||
self.keys
|
||||
.get(xpub)
|
||||
.unwrap()
|
||||
.as_public_key(&self.ctx, Some(index))
|
||||
};
|
||||
let translatefpkh =
|
||||
|xpub: &String| Ok(hash160::Hash::hash(&translatefpk(xpub)?.to_bytes()));
|
||||
|
||||
Ok(self.internal.translate_pk(translatefpk, translatefpkh)?)
|
||||
}
|
||||
|
||||
pub fn get_xprv(&self) -> impl IntoIterator<Item = ExtendedPrivKey> + '_ {
|
||||
self.keys
|
||||
.iter()
|
||||
.filter(|(_, v)| v.xprv().is_some())
|
||||
.map(|(_, v)| v.xprv().unwrap())
|
||||
}
|
||||
|
||||
pub fn get_secret_keys(&self) -> impl IntoIterator<Item = PrivateKey> + '_ {
|
||||
self.keys
|
||||
.iter()
|
||||
.filter(|(_, v)| v.as_secret_key().is_some())
|
||||
.map(|(_, v)| v.as_secret_key().unwrap())
|
||||
}
|
||||
|
||||
pub fn get_hd_keypaths(
|
||||
&self,
|
||||
index: u32,
|
||||
) -> Result<BTreeMap<PublicKey, (Fingerprint, DerivationPath)>, Error> {
|
||||
let mut answer = BTreeMap::new();
|
||||
|
||||
for (_, key) in &self.keys {
|
||||
if let Some(fingerprint) = key.fingerprint(&self.ctx) {
|
||||
let derivation_path = key.full_path(index).unwrap();
|
||||
let pubkey = key.as_public_key(&self.ctx, Some(index))?;
|
||||
|
||||
answer.insert(pubkey, (fingerprint, derivation_path));
|
||||
}
|
||||
}
|
||||
|
||||
Ok(answer)
|
||||
}
|
||||
|
||||
pub fn max_satisfaction_weight(&self) -> usize {
|
||||
let fake_pk = PublicKey::from_slice(&[
|
||||
2, 140, 40, 169, 123, 248, 41, 139, 192, 210, 61, 140, 116, 148, 82, 163, 46, 105, 75,
|
||||
101, 227, 10, 148, 114, 163, 149, 74, 179, 15, 229, 50, 76, 170,
|
||||
])
|
||||
.unwrap();
|
||||
let translated: Descriptor<PublicKey> = self
|
||||
.internal
|
||||
.translate_pk(
|
||||
|_| -> Result<_, ()> { Ok(fake_pk.clone()) },
|
||||
|_| -> Result<_, ()> { Ok(Default::default()) },
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
translated.max_satisfaction_weight()
|
||||
}
|
||||
|
||||
pub fn is_fixed(&self) -> bool {
|
||||
self.keys.iter().all(|(_, key)| key.is_fixed())
|
||||
}
|
||||
|
||||
pub fn same_structure<K: MiniscriptKey>(&self, other: &Descriptor<K>) -> bool {
|
||||
// Translate all the public keys to () and then check if the two descriptors are equal.
|
||||
// TODO: translate hashes to their default value before checking for ==
|
||||
|
||||
let func_string = |_string: &String| -> Result<_, Error> { Ok(DummyKey::default()) };
|
||||
|
||||
let func_generic_pk = |_data: &K| -> Result<_, Error> { Ok(DummyKey::default()) };
|
||||
let func_generic_pkh =
|
||||
|_data: &<K as MiniscriptKey>::Hash| -> Result<_, Error> { Ok(DummyKey::default()) };
|
||||
|
||||
let translated_a = self.internal.translate_pk(func_string, func_string);
|
||||
let translated_b = other.translate_pk(func_generic_pk, func_generic_pkh);
|
||||
|
||||
match (translated_a, translated_b) {
|
||||
(Ok(a), Ok(b)) => a == b,
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn as_public_version(&self) -> Result<ExtendedDescriptor, Error> {
|
||||
let keys: RefCell<BTreeMap<String, Box<dyn Key>>> = RefCell::new(BTreeMap::new());
|
||||
|
||||
let translatefpk = |string: &String| -> Result<_, Error> {
|
||||
let public = self.keys.get(string).unwrap().public(&self.ctx)?;
|
||||
|
||||
let result = format!("{}", public);
|
||||
keys.borrow_mut().insert(string.clone(), public);
|
||||
|
||||
Ok(result)
|
||||
};
|
||||
let translatefpkh = |string: &String| -> Result<_, Error> {
|
||||
let public = self.keys.get(string).unwrap().public(&self.ctx)?;
|
||||
|
||||
let result = format!("{}", public);
|
||||
keys.borrow_mut().insert(string.clone(), public);
|
||||
|
||||
Ok(result)
|
||||
};
|
||||
|
||||
let internal = self.internal.translate_pk(translatefpk, translatefpkh)?;
|
||||
|
||||
Ok(ExtendedDescriptor {
|
||||
internal,
|
||||
keys: keys.into_inner(),
|
||||
ctx: self.ctx.clone(),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl ExtractPolicy for ExtendedDescriptor {
|
||||
fn extract_policy(&self) -> Result<Option<Policy>, Error> {
|
||||
self.internal.extract_policy(&self.keys)
|
||||
}
|
||||
}
|
||||
|
||||
impl TryFrom<&str> for ExtendedDescriptor {
|
||||
type Error = Error;
|
||||
|
||||
fn try_from(value: &str) -> Result<Self, Self::Error> {
|
||||
let internal = StringDescriptor::from_str(value)?;
|
||||
ExtendedDescriptor::new(internal)
|
||||
}
|
||||
}
|
||||
|
||||
impl TryFrom<StringDescriptor> for ExtendedDescriptor {
|
||||
type Error = Error;
|
||||
|
||||
fn try_from(other: StringDescriptor) -> Result<Self, Self::Error> {
|
||||
ExtendedDescriptor::new(other)
|
||||
}
|
||||
}
|
||||
|
||||
impl FromStr for ExtendedDescriptor {
|
||||
type Err = Error;
|
||||
|
||||
fn from_str(s: &str) -> Result<Self, Self::Err> {
|
||||
Self::try_from(s)
|
||||
}
|
||||
}
|
||||
|
||||
impl Into<String> for ExtendedDescriptor {
|
||||
fn into(self) -> String {
|
||||
format!("{}", self.internal)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
use std::str::FromStr;
|
||||
|
||||
use bitcoin::consensus::encode::deserialize;
|
||||
use bitcoin::hashes::hex::FromHex;
|
||||
use bitcoin::{Network, PublicKey};
|
||||
use bitcoin::util::psbt;
|
||||
|
||||
use crate::descriptor::*;
|
||||
|
||||
macro_rules! hex_fingerprint {
|
||||
($hex:expr) => {
|
||||
Fingerprint::from_hex($hex).unwrap()
|
||||
};
|
||||
}
|
||||
|
||||
macro_rules! hex_pubkey {
|
||||
($hex:expr) => {
|
||||
PublicKey::from_str($hex).unwrap()
|
||||
};
|
||||
}
|
||||
|
||||
macro_rules! deriv_path {
|
||||
($str:expr) => {
|
||||
DerivationPath::from_str($str).unwrap()
|
||||
};
|
||||
|
||||
() => {
|
||||
DerivationPath::from(vec![])
|
||||
};
|
||||
}
|
||||
use super::*;
|
||||
use crate::psbt::PSBTUtils;
|
||||
|
||||
#[test]
|
||||
fn test_descriptor_parse_wif() {
|
||||
let string = "pkh(cVt4o7BGAig1UXywgGSmARhxMdzP5qvQsxKkSsc1XEkw3tDTQFpy)";
|
||||
let desc = ExtendedDescriptor::from_str(string).unwrap();
|
||||
assert!(desc.is_fixed());
|
||||
assert_eq!(
|
||||
desc.derive(0)
|
||||
.unwrap()
|
||||
.address(Network::Testnet)
|
||||
.unwrap()
|
||||
.to_string(),
|
||||
"mqwpxxvfv3QbM8PU8uBx2jaNt9btQqvQNx"
|
||||
);
|
||||
assert_eq!(
|
||||
desc.derive(42)
|
||||
.unwrap()
|
||||
.address(Network::Testnet)
|
||||
.unwrap()
|
||||
.to_string(),
|
||||
"mqwpxxvfv3QbM8PU8uBx2jaNt9btQqvQNx"
|
||||
);
|
||||
assert_eq!(
|
||||
desc.get_secret_keys().into_iter().collect::<Vec<_>>().len(),
|
||||
1
|
||||
);
|
||||
}
|
||||
fn test_derive_from_psbt_input_wpkh() {
|
||||
let psbt: psbt::PartiallySignedTransaction = deserialize(&Vec::<u8>::from_hex("70736274ff010052010000000162307be8e431fbaff807cdf9cdc3fde44d740211bc8342c31ffd6ec11fe35bcc0100000000ffffffff01328601000000000016001493ce48570b55c42c2af816aeaba06cfee1224fae000000000001011fa08601000000000016001493ce48570b55c42c2af816aeaba06cfee1224fae010304010000000000").unwrap()).unwrap();
|
||||
|
||||
#[test]
|
||||
fn test_descriptor_parse_pubkey() {
|
||||
let string = "pkh(039b6347398505f5ec93826dc61c19f47c66c0283ee9be980e29ce325a0f4679ef)";
|
||||
let desc = ExtendedDescriptor::from_str(string).unwrap();
|
||||
assert!(desc.is_fixed());
|
||||
assert_eq!(
|
||||
desc.derive(0)
|
||||
.unwrap()
|
||||
.address(Network::Testnet)
|
||||
.unwrap()
|
||||
.to_string(),
|
||||
"mqwpxxvfv3QbM8PU8uBx2jaNt9btQqvQNx"
|
||||
);
|
||||
assert_eq!(
|
||||
desc.derive(42)
|
||||
.unwrap()
|
||||
.address(Network::Testnet)
|
||||
.unwrap()
|
||||
.to_string(),
|
||||
"mqwpxxvfv3QbM8PU8uBx2jaNt9btQqvQNx"
|
||||
);
|
||||
assert_eq!(
|
||||
desc.get_secret_keys().into_iter().collect::<Vec<_>>().len(),
|
||||
0
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_descriptor_parse_xpub() {
|
||||
let string = "pkh(tpubDEnoLuPdBep9bzw5LoGYpsxUQYheRQ9gcgrJhJEcdKFB9cWQRyYmkCyRoTqeD4tJYiVVgt6A3rN6rWn9RYhR9sBsGxji29LYWHuKKbdb1ev/*)";
|
||||
let desc = ExtendedDescriptor::from_str(string).unwrap();
|
||||
assert!(!desc.is_fixed());
|
||||
assert_eq!(
|
||||
desc.derive(0)
|
||||
.unwrap()
|
||||
.address(Network::Testnet)
|
||||
.unwrap()
|
||||
.to_string(),
|
||||
"mxbXpnVkwARGtYXk5yeGYf59bGWuPpdE4X"
|
||||
);
|
||||
assert_eq!(
|
||||
desc.derive(42)
|
||||
.unwrap()
|
||||
.address(Network::Testnet)
|
||||
.unwrap()
|
||||
.to_string(),
|
||||
"mhtuS1QaEV4HPcK4bWk4Wvpd64SUjiC5Zt"
|
||||
);
|
||||
assert_eq!(desc.get_xprv().into_iter().collect::<Vec<_>>().len(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[should_panic(expected = "KeyParsingError")]
|
||||
fn test_descriptor_parse_fail() {
|
||||
let string = "pkh(this_is_not_a_valid_key)";
|
||||
ExtendedDescriptor::from_str(string).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_descriptor_hd_keypaths() {
|
||||
let string = "pkh(tpubDEnoLuPdBep9bzw5LoGYpsxUQYheRQ9gcgrJhJEcdKFB9cWQRyYmkCyRoTqeD4tJYiVVgt6A3rN6rWn9RYhR9sBsGxji29LYWHuKKbdb1ev/*)";
|
||||
let desc = ExtendedDescriptor::from_str(string).unwrap();
|
||||
let keypaths = desc.get_hd_keypaths(0).unwrap();
|
||||
assert!(keypaths.contains_key(&hex_pubkey!(
|
||||
"025d5fc65ebb8d44a5274b53bac21ff8307fec2334a32df05553459f8b1f7fe1b6"
|
||||
)));
|
||||
assert_eq!(
|
||||
keypaths.get(&hex_pubkey!(
|
||||
"025d5fc65ebb8d44a5274b53bac21ff8307fec2334a32df05553459f8b1f7fe1b6"
|
||||
)),
|
||||
Some(&(hex_fingerprint!("31a507b8"), deriv_path!("m/0")))
|
||||
let descriptor = Descriptor::<DescriptorPublicKey>::from_str(
|
||||
"wpkh(02b4632d08485ff1df2db55b9dafd23347d1c47a457072a1e87be26896549a8737)",
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let result = descriptor.derive_from_psbt_input(&psbt.inputs[0], psbt.get_utxo_for(0));
|
||||
println!("{:?}", result);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,23 +1,26 @@
|
||||
use std::cmp::max;
|
||||
use std::collections::{BTreeMap, HashSet, VecDeque};
|
||||
use std::sync::Arc;
|
||||
|
||||
use serde::ser::SerializeMap;
|
||||
use serde::{Serialize, Serializer};
|
||||
|
||||
use bitcoin::hashes::*;
|
||||
use bitcoin::secp256k1::Secp256k1;
|
||||
use bitcoin::util::bip32::Fingerprint;
|
||||
use bitcoin::PublicKey;
|
||||
|
||||
use miniscript::{Descriptor, Miniscript, ScriptContext, Terminal};
|
||||
use miniscript::descriptor::DescriptorPublicKey;
|
||||
use miniscript::{Descriptor, Miniscript, MiniscriptKey, ScriptContext, Terminal};
|
||||
|
||||
#[allow(unused_imports)]
|
||||
use log::{debug, error, info, trace};
|
||||
|
||||
use crate::descriptor::ExtractPolicy;
|
||||
use crate::wallet::signer::{SignerId, SignersContainer};
|
||||
|
||||
use super::checksum::get_checksum;
|
||||
use super::error::Error;
|
||||
use crate::descriptor::{Key, MiniscriptExtractPolicy};
|
||||
use crate::psbt::PSBTSatisfier;
|
||||
use super::XKeyUtils;
|
||||
|
||||
#[derive(Debug, Clone, Default, Serialize)]
|
||||
pub struct PKOrF {
|
||||
@@ -30,20 +33,23 @@ pub struct PKOrF {
|
||||
}
|
||||
|
||||
impl PKOrF {
|
||||
fn from_key(k: &Box<dyn Key>) -> Self {
|
||||
let secp = Secp256k1::gen_new();
|
||||
fn from_key(k: &DescriptorPublicKey) -> Self {
|
||||
match k {
|
||||
DescriptorPublicKey::PubKey(pubkey) => PKOrF {
|
||||
pubkey: Some(*pubkey),
|
||||
..Default::default()
|
||||
},
|
||||
DescriptorPublicKey::XPub(xpub) => PKOrF {
|
||||
fingerprint: Some(xpub.root_fingerprint()),
|
||||
..Default::default()
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
let pubkey = k.as_public_key(&secp, None).unwrap();
|
||||
if let Some(fing) = k.fingerprint(&secp) {
|
||||
PKOrF {
|
||||
fingerprint: Some(fing),
|
||||
..Default::default()
|
||||
}
|
||||
} else {
|
||||
PKOrF {
|
||||
pubkey: Some(pubkey),
|
||||
..Default::default()
|
||||
}
|
||||
fn from_key_hash(k: hash160::Hash) -> Self {
|
||||
PKOrF {
|
||||
pubkey_hash: Some(k),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -445,14 +451,15 @@ impl Policy {
|
||||
}
|
||||
|
||||
fn make_multisig(
|
||||
keys: Vec<Option<&Box<dyn Key>>>,
|
||||
keys: &Vec<DescriptorPublicKey>,
|
||||
signers: Arc<SignersContainer<DescriptorPublicKey>>,
|
||||
threshold: usize,
|
||||
) -> Result<Option<Policy>, PolicyError> {
|
||||
if threshold == 0 {
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
let parsed_keys = keys.iter().map(|k| PKOrF::from_key(k.unwrap())).collect();
|
||||
let parsed_keys = keys.iter().map(|k| PKOrF::from_key(k)).collect();
|
||||
|
||||
let mut contribution = Satisfaction::Partial {
|
||||
n: keys.len(),
|
||||
@@ -461,14 +468,14 @@ impl Policy {
|
||||
conditions: Default::default(),
|
||||
};
|
||||
for (index, key) in keys.iter().enumerate() {
|
||||
let val = if key.is_some() && key.unwrap().has_secret() {
|
||||
Satisfaction::Complete {
|
||||
condition: Default::default(),
|
||||
}
|
||||
} else {
|
||||
Satisfaction::None
|
||||
};
|
||||
contribution.add(&val, index)?;
|
||||
if let Some(_) = signers.find(signer_id(key)) {
|
||||
contribution.add(
|
||||
&Satisfaction::Complete {
|
||||
condition: Default::default(),
|
||||
},
|
||||
index,
|
||||
)?;
|
||||
}
|
||||
}
|
||||
contribution.finalize()?;
|
||||
|
||||
@@ -482,15 +489,6 @@ impl Policy {
|
||||
Ok(Some(policy))
|
||||
}
|
||||
|
||||
pub fn satisfy<Ctx: ScriptContext>(
|
||||
&mut self,
|
||||
_satisfier: &PSBTSatisfier,
|
||||
_desc_node: &Terminal<PublicKey, Ctx>,
|
||||
) {
|
||||
//self.satisfaction = self.item.satisfy(satisfier, desc_node);
|
||||
//self.contribution += &self.satisfaction;
|
||||
}
|
||||
|
||||
pub fn requires_path(&self) -> bool {
|
||||
self.get_requirements(&BTreeMap::new()).is_err()
|
||||
}
|
||||
@@ -566,60 +564,55 @@ impl From<SatisfiableItem> for Policy {
|
||||
}
|
||||
}
|
||||
|
||||
fn signature_from_string(key: Option<&Box<dyn Key>>) -> Option<Policy> {
|
||||
key.map(|k| {
|
||||
let mut policy: Policy = SatisfiableItem::Signature(PKOrF::from_key(k)).into();
|
||||
policy.contribution = if k.has_secret() {
|
||||
Satisfaction::Complete {
|
||||
condition: Default::default(),
|
||||
}
|
||||
} else {
|
||||
Satisfaction::None
|
||||
};
|
||||
|
||||
policy
|
||||
})
|
||||
fn signer_id(key: &DescriptorPublicKey) -> SignerId<DescriptorPublicKey> {
|
||||
match key {
|
||||
DescriptorPublicKey::PubKey(pubkey) => pubkey.to_pubkeyhash().into(),
|
||||
DescriptorPublicKey::XPub(xpub) => xpub.root_fingerprint().into(),
|
||||
}
|
||||
}
|
||||
|
||||
fn signature_key_from_string(key: Option<&Box<dyn Key>>) -> Option<Policy> {
|
||||
let secp = Secp256k1::gen_new();
|
||||
fn signature(
|
||||
key: &DescriptorPublicKey,
|
||||
signers: Arc<SignersContainer<DescriptorPublicKey>>,
|
||||
) -> Policy {
|
||||
let mut policy: Policy = SatisfiableItem::Signature(PKOrF::from_key(key)).into();
|
||||
|
||||
key.map(|k| {
|
||||
let pubkey = k.as_public_key(&secp, None).unwrap();
|
||||
let mut policy: Policy = if let Some(fing) = k.fingerprint(&secp) {
|
||||
SatisfiableItem::SignatureKey(PKOrF {
|
||||
fingerprint: Some(fing),
|
||||
..Default::default()
|
||||
})
|
||||
} else {
|
||||
SatisfiableItem::SignatureKey(PKOrF {
|
||||
pubkey_hash: Some(hash160::Hash::hash(&pubkey.to_bytes())),
|
||||
..Default::default()
|
||||
})
|
||||
policy.contribution = if signers.find(signer_id(key)).is_some() {
|
||||
Satisfaction::Complete {
|
||||
condition: Default::default(),
|
||||
}
|
||||
.into();
|
||||
policy.contribution = if k.has_secret() {
|
||||
Satisfaction::Complete {
|
||||
condition: Default::default(),
|
||||
}
|
||||
} else {
|
||||
Satisfaction::None
|
||||
};
|
||||
} else {
|
||||
Satisfaction::None
|
||||
};
|
||||
|
||||
policy
|
||||
})
|
||||
policy
|
||||
}
|
||||
|
||||
impl<Ctx: ScriptContext> MiniscriptExtractPolicy for Miniscript<String, Ctx> {
|
||||
fn signature_key(
|
||||
key_hash: &<DescriptorPublicKey as MiniscriptKey>::Hash,
|
||||
signers: Arc<SignersContainer<DescriptorPublicKey>>,
|
||||
) -> Policy {
|
||||
let mut policy: Policy = SatisfiableItem::Signature(PKOrF::from_key_hash(*key_hash)).into();
|
||||
|
||||
if let Some(_) = signers.find(SignerId::PkHash(*key_hash)) {
|
||||
policy.contribution = Satisfaction::Complete {
|
||||
condition: Default::default(),
|
||||
}
|
||||
}
|
||||
|
||||
policy
|
||||
}
|
||||
|
||||
impl<Ctx: ScriptContext> ExtractPolicy for Miniscript<DescriptorPublicKey, Ctx> {
|
||||
fn extract_policy(
|
||||
&self,
|
||||
lookup_map: &BTreeMap<String, Box<dyn Key>>,
|
||||
signers: Arc<SignersContainer<DescriptorPublicKey>>,
|
||||
) -> Result<Option<Policy>, Error> {
|
||||
Ok(match &self.node {
|
||||
// Leaves
|
||||
Terminal::True | Terminal::False => None,
|
||||
Terminal::PkK(pubkey) => signature_from_string(lookup_map.get(pubkey)),
|
||||
Terminal::PkH(pubkey_hash) => signature_key_from_string(lookup_map.get(pubkey_hash)),
|
||||
Terminal::PkK(pubkey) => Some(signature(pubkey, Arc::clone(&signers))),
|
||||
Terminal::PkH(pubkey_hash) => Some(signature_key(pubkey_hash, Arc::clone(&signers))),
|
||||
Terminal::After(value) => {
|
||||
let mut policy: Policy = SatisfiableItem::AbsoluteTimelock { value: *value }.into();
|
||||
policy.contribution = Satisfaction::Complete {
|
||||
@@ -652,9 +645,7 @@ impl<Ctx: ScriptContext> MiniscriptExtractPolicy for Miniscript<String, Ctx> {
|
||||
Terminal::Hash160(hash) => {
|
||||
Some(SatisfiableItem::HASH160Preimage { hash: *hash }.into())
|
||||
}
|
||||
Terminal::Multi(k, pks) => {
|
||||
Policy::make_multisig(pks.iter().map(|s| lookup_map.get(s)).collect(), *k)?
|
||||
}
|
||||
Terminal::Multi(k, pks) => Policy::make_multisig(pks, Arc::clone(&signers), *k)?,
|
||||
// Identities
|
||||
Terminal::Alt(inner)
|
||||
| Terminal::Swap(inner)
|
||||
@@ -662,26 +653,31 @@ impl<Ctx: ScriptContext> MiniscriptExtractPolicy for Miniscript<String, Ctx> {
|
||||
| Terminal::DupIf(inner)
|
||||
| Terminal::Verify(inner)
|
||||
| Terminal::NonZero(inner)
|
||||
| Terminal::ZeroNotEqual(inner) => inner.extract_policy(lookup_map)?,
|
||||
| Terminal::ZeroNotEqual(inner) => inner.extract_policy(Arc::clone(&signers))?,
|
||||
// Complex policies
|
||||
Terminal::AndV(a, b) | Terminal::AndB(a, b) => {
|
||||
Policy::make_and(a.extract_policy(lookup_map)?, b.extract_policy(lookup_map)?)?
|
||||
}
|
||||
Terminal::AndV(a, b) | Terminal::AndB(a, b) => Policy::make_and(
|
||||
a.extract_policy(Arc::clone(&signers))?,
|
||||
b.extract_policy(Arc::clone(&signers))?,
|
||||
)?,
|
||||
Terminal::AndOr(x, y, z) => Policy::make_or(
|
||||
Policy::make_and(x.extract_policy(lookup_map)?, y.extract_policy(lookup_map)?)?,
|
||||
z.extract_policy(lookup_map)?,
|
||||
Policy::make_and(
|
||||
x.extract_policy(Arc::clone(&signers))?,
|
||||
y.extract_policy(Arc::clone(&signers))?,
|
||||
)?,
|
||||
z.extract_policy(Arc::clone(&signers))?,
|
||||
)?,
|
||||
Terminal::OrB(a, b)
|
||||
| Terminal::OrD(a, b)
|
||||
| Terminal::OrC(a, b)
|
||||
| Terminal::OrI(a, b) => {
|
||||
Policy::make_or(a.extract_policy(lookup_map)?, b.extract_policy(lookup_map)?)?
|
||||
}
|
||||
| Terminal::OrI(a, b) => Policy::make_or(
|
||||
a.extract_policy(Arc::clone(&signers))?,
|
||||
b.extract_policy(Arc::clone(&signers))?,
|
||||
)?,
|
||||
Terminal::Thresh(k, nodes) => {
|
||||
let mut threshold = *k;
|
||||
let mapped: Vec<_> = nodes
|
||||
.iter()
|
||||
.map(|n| n.extract_policy(lookup_map))
|
||||
.map(|n| n.extract_policy(Arc::clone(&signers)))
|
||||
.collect::<Result<Vec<_>, _>>()?
|
||||
.into_iter()
|
||||
.filter_map(|x| x)
|
||||
@@ -700,22 +696,18 @@ impl<Ctx: ScriptContext> MiniscriptExtractPolicy for Miniscript<String, Ctx> {
|
||||
}
|
||||
}
|
||||
|
||||
impl MiniscriptExtractPolicy for Descriptor<String> {
|
||||
impl ExtractPolicy for Descriptor<DescriptorPublicKey> {
|
||||
fn extract_policy(
|
||||
&self,
|
||||
lookup_map: &BTreeMap<String, Box<dyn Key>>,
|
||||
signers: Arc<SignersContainer<DescriptorPublicKey>>,
|
||||
) -> Result<Option<Policy>, Error> {
|
||||
match self {
|
||||
Descriptor::Pk(pubkey)
|
||||
| Descriptor::Pkh(pubkey)
|
||||
| Descriptor::Wpkh(pubkey)
|
||||
| Descriptor::ShWpkh(pubkey) => Ok(signature_from_string(lookup_map.get(pubkey))),
|
||||
Descriptor::Bare(inner) | Descriptor::Sh(inner) => {
|
||||
Ok(inner.extract_policy(lookup_map)?)
|
||||
}
|
||||
Descriptor::Wsh(inner) | Descriptor::ShWsh(inner) => {
|
||||
Ok(inner.extract_policy(lookup_map)?)
|
||||
}
|
||||
| Descriptor::ShWpkh(pubkey) => Ok(Some(signature(pubkey, signers))),
|
||||
Descriptor::Bare(inner) | Descriptor::Sh(inner) => Ok(inner.extract_policy(signers)?),
|
||||
Descriptor::Wsh(inner) | Descriptor::ShWsh(inner) => Ok(inner.extract_policy(signers)?),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user