Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add the "planning" module #481

Closed
wants to merge 6 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 8 additions & 10 deletions bitcoind-tests/tests/test_cpp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,28 +11,24 @@ use std::path::Path;

use bitcoin::hashes::{sha256d, Hash};
use bitcoin::psbt::Psbt;
use bitcoin::secp256k1::{self, Secp256k1};
use bitcoin::{psbt, Amount, OutPoint, Sequence, Transaction, TxIn, TxOut, Txid};
use bitcoin::{psbt, secp256k1, Amount, OutPoint, Sequence, Transaction, TxIn, TxOut, Txid};
use bitcoind::bitcoincore_rpc::{json, Client, RpcApi};
use miniscript::bitcoin::absolute;
use miniscript::psbt::PsbtExt;
use miniscript::{bitcoin, Descriptor};
use miniscript::{bitcoin, DefiniteDescriptorKey, Descriptor};

mod setup;
use setup::test_util::{self, PubData, TestData};

// parse ~30 miniscripts from file
pub(crate) fn parse_miniscripts(
secp: &Secp256k1<secp256k1::All>,
pubdata: &PubData,
) -> Vec<Descriptor<bitcoin::PublicKey>> {
pub(crate) fn parse_miniscripts(pubdata: &PubData) -> Vec<Descriptor<DefiniteDescriptorKey>> {
// File must exist in current path before this produces output
let mut desc_vec = vec![];
// Consumes the iterator, returns an (Optional) String
for line in read_lines("tests/data/random_ms.txt") {
let ms = test_util::parse_insane_ms(&line.unwrap(), pubdata);
let wsh = Descriptor::new_wsh(ms).unwrap();
desc_vec.push(wsh.derived_descriptor(secp, 0).unwrap());
desc_vec.push(wsh.at_derivation_index(0).unwrap());
}
desc_vec
}
Expand Down Expand Up @@ -71,7 +67,7 @@ fn get_vout(cl: &Client, txid: Txid, value: u64) -> (OutPoint, TxOut) {

pub fn test_from_cpp_ms(cl: &Client, testdata: &TestData) {
let secp = secp256k1::Secp256k1::new();
let desc_vec = parse_miniscripts(&secp, &testdata.pubdata);
let desc_vec = parse_miniscripts(&testdata.pubdata);
let sks = &testdata.secretdata.sks;
let pks = &testdata.pubdata.pks;
// Generate some blocks
Expand Down Expand Up @@ -152,6 +148,7 @@ pub fn test_from_cpp_ms(cl: &Client, testdata: &TestData) {
input.witness_utxo = Some(witness_utxo);
input.witness_script = Some(desc.explicit_script().unwrap());
psbt.inputs.push(input);
psbt.update_input_with_descriptor(0, &desc).unwrap();
psbt.outputs.push(psbt::Output::default());
psbts.push(psbt);
}
Expand All @@ -160,7 +157,8 @@ pub fn test_from_cpp_ms(cl: &Client, testdata: &TestData) {
// Sign the transactions with all keys
// AKA the signer role of psbt
for i in 0..psbts.len() {
let ms = if let Descriptor::Wsh(wsh) = &desc_vec[i] {
let wsh_derived = desc_vec[i].derived_descriptor(&secp).unwrap();
let ms = if let Descriptor::Wsh(wsh) = &wsh_derived {
match wsh.as_inner() {
miniscript::descriptor::WshInner::Ms(ms) => ms,
_ => unreachable!(),
Expand Down
66 changes: 66 additions & 0 deletions src/descriptor/bare.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,11 @@ use bitcoin::script::{self, PushBytes};
use bitcoin::{Address, Network, ScriptBuf};

use super::checksum::{self, verify_checksum};
use crate::descriptor::DefiniteDescriptorKey;
use crate::expression::{self, FromTree};
use crate::miniscript::context::{ScriptContext, ScriptContextError};
use crate::miniscript::satisfy::{Placeholder, Satisfaction, Witness};
use crate::plan::AssetProvider;
use crate::policy::{semantic, Liftable};
use crate::prelude::*;
use crate::util::{varint_len, witness_to_scriptsig};
Expand Down Expand Up @@ -134,6 +137,30 @@ impl<Pk: MiniscriptKey + ToPublicKey> Bare<Pk> {
}
}

impl Bare<DefiniteDescriptorKey> {
/// Returns a plan if the provided assets are sufficient to produce a non-malleable satisfaction
pub fn plan_satisfaction<P>(
&self,
provider: &P,
) -> Satisfaction<Placeholder<DefiniteDescriptorKey>>
where
P: AssetProvider<DefiniteDescriptorKey>,
{
self.ms.build_template(provider)
}

/// Returns a plan if the provided assets are sufficient to produce a malleable satisfaction
pub fn plan_satisfaction_mall<P>(
&self,
provider: &P,
) -> Satisfaction<Placeholder<DefiniteDescriptorKey>>
where
P: AssetProvider<DefiniteDescriptorKey>,
{
self.ms.build_template_mall(provider)
}
}

impl<Pk: MiniscriptKey> fmt::Debug for Bare<Pk> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{:?}", self.ms)
Expand Down Expand Up @@ -311,6 +338,45 @@ impl<Pk: MiniscriptKey + ToPublicKey> Pkh<Pk> {
}
}

impl Pkh<DefiniteDescriptorKey> {
/// Returns a plan if the provided assets are sufficient to produce a non-malleable satisfaction
pub fn plan_satisfaction<P>(
&self,
provider: &P,
) -> Satisfaction<Placeholder<DefiniteDescriptorKey>>
where
P: AssetProvider<DefiniteDescriptorKey>,
{
let stack = if provider.provider_lookup_ecdsa_sig(&self.pk) {
let stack = vec![
Placeholder::EcdsaSigPk(self.pk.clone()),
Placeholder::Pubkey(self.pk.clone(), BareCtx::pk_len(&self.pk)),
];
Witness::Stack(stack)
} else {
Witness::Unavailable
};

Satisfaction {
stack,
has_sig: true,
relative_timelock: None,
absolute_timelock: None,
}
}

/// Returns a plan if the provided assets are sufficient to produce a malleable satisfaction
pub fn plan_satisfaction_mall<P>(
&self,
provider: &P,
) -> Satisfaction<Placeholder<DefiniteDescriptorKey>>
where
P: AssetProvider<DefiniteDescriptorKey>,
{
self.plan_satisfaction(provider)
}
}

impl<Pk: MiniscriptKey> fmt::Debug for Pkh<Pk> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "pkh({:?})", self.pk)
Expand Down
76 changes: 76 additions & 0 deletions src/descriptor/key.rs
Original file line number Diff line number Diff line change
Expand Up @@ -592,6 +592,33 @@ impl DescriptorPublicKey {
}
}

/// Returns a vector containing the full derivation paths from the master key.
/// The vector will contain just one element for single keys, and multiple elements
/// for multipath extended keys.
///
/// For wildcard keys this will return the path up to the wildcard, so you
/// can get full paths by appending one additional derivation step, according
/// to the wildcard type (hardened or normal).
pub fn full_derivation_paths(&self) -> Vec<bip32::DerivationPath> {
match self {
DescriptorPublicKey::MultiXPub(xpub) => {
let origin_path = if let Some((_, ref path)) = xpub.origin {
path.clone()
} else {
bip32::DerivationPath::from(vec![])
};
xpub.derivation_paths
.paths()
.into_iter()
.map(|p| origin_path.extend(p))
.collect()
}
_ => vec![self
.full_derivation_path()
.expect("Must be Some for non-multipath keys")],
}
}

/// Whether or not the key has a wildcard
#[deprecated(note = "use has_wildcard instead")]
pub fn is_deriveable(&self) -> bool {
Expand Down Expand Up @@ -694,6 +721,41 @@ impl DescriptorPublicKey {
}
}
}

/// Whether this key is the "parent" of a [`DefiniteDescriptorKey`]
///
/// The key is considered "parent" if it represents the non-derived version of a definite key,
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This definition is a little awkward because it doesn't include all parents. It seems you added it as part of applying a policy where A is not a parent of A/1 but A/* is in the asset code. Don't we usually want to express the policy where I have A and am willing to sign anything under it e.g. A/2/7 and A and A/1 etc. By returning a full derivation path it also implies there might be multiple items in the path but this function only returns a derivation path with one item.

If this function is indeed useful how about rename it to derivation_index_for where it just return an Option<u32> i.e. it returns the value that could be passed to at_derivation_index to get the DefiniteDescriptorKey if it exists (a sort of inverse function).

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah I think this just needs a better name, essentially what I'm trying to figure out is whether a DefiniteDescriptorKey is a derivation of a given DescriptorPublicKey, which can only extend the path by one item (multiple wildcards are not supported).

I like your suggestion of naming it derivation_index_for, but I think Option<u32> is not a great return type because in case the DescriptorPublicKey doesn't have a wildcard we need to still return a positive "match" result but we don't have a derivation index.

I guess I could add an enum for this specifically, with two variants: Wildcard(bip32::ChildNumber) and NonWildcard or something like this.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

As of 4849893 this is still TODO.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

6151612 in #592 removes the method altogether

/// meaning it contains a wildcard where the definite key has a definite derivation number.
///
/// If `self` is a single key or doesn't contain any wildcards, the definite key will have to
/// be exactly the same.
///
/// Returns the derivation path to apply to `self` to obtain the definite key.
pub fn is_parent(&self, definite_key: &DefiniteDescriptorKey) -> Option<bip32::DerivationPath> {
// If the key is `Single` or it's an `XPub` with no wildcard it will match the definite key
// exactly, so we try this check first
if self == &definite_key.0 {
return Some(bip32::DerivationPath::default());
}

match (self, &definite_key.0) {
(DescriptorPublicKey::XPub(self_xkey), DescriptorPublicKey::XPub(definite_xkey))
if definite_xkey.derivation_path.len() > 0 =>
{
let definite_path_len = definite_xkey.derivation_path.len();
if self_xkey.origin == definite_xkey.origin
&& self_xkey.xkey == definite_xkey.xkey
&& self_xkey.derivation_path.as_ref()
== &definite_xkey.derivation_path[..(definite_path_len - 1)]
{
Some(vec![definite_xkey.derivation_path[definite_path_len - 1]].into())
} else {
None
}
}
_ => None,
}
}
}

impl FromStr for DescriptorSecretKey {
Expand Down Expand Up @@ -1075,6 +1137,12 @@ impl DefiniteDescriptorKey {
self.0.full_derivation_path()
}

/// Full paths from the master key. The vector will contain just one path for single
/// keys, and multiple ones for multipath extended keys
pub fn full_derivation_paths(&self) -> Vec<bip32::DerivationPath> {
self.0.full_derivation_paths()
}

/// Reference to the underlying `DescriptorPublicKey`
pub fn as_descriptor_public_key(&self) -> &DescriptorPublicKey {
&self.0
Expand Down Expand Up @@ -1476,6 +1544,14 @@ mod test {
let desc_key = DescriptorPublicKey::from_str("[abcdef00/0'/1']tpubDBrgjcxBxnXyL575sHdkpKohWu5qHKoQ7TJXKNrYznh5fVEGBv89hA8ENW7A8MFVpFUSvgLqc4Nj1WZcpePX6rrxviVtPowvMuGF5rdT2Vi/9478'/<0';1>/8h/*'").unwrap();
assert!(desc_key.full_derivation_path().is_none());
assert!(desc_key.is_multipath());
// But you can get all the derivation paths
assert_eq!(
desc_key.full_derivation_paths(),
vec![
bip32::DerivationPath::from_str("m/0'/1'/9478'/0'/8'").unwrap(),
bip32::DerivationPath::from_str("m/0'/1'/9478'/1/8'").unwrap(),
],
);
assert_eq!(desc_key.into_single_keys(), vec![DescriptorPublicKey::from_str("[abcdef00/0'/1']tpubDBrgjcxBxnXyL575sHdkpKohWu5qHKoQ7TJXKNrYznh5fVEGBv89hA8ENW7A8MFVpFUSvgLqc4Nj1WZcpePX6rrxviVtPowvMuGF5rdT2Vi/9478'/0'/8h/*'").unwrap(), DescriptorPublicKey::from_str("[abcdef00/0'/1']tpubDBrgjcxBxnXyL575sHdkpKohWu5qHKoQ7TJXKNrYznh5fVEGBv89hA8ENW7A8MFVpFUSvgLqc4Nj1WZcpePX6rrxviVtPowvMuGF5rdT2Vi/9478'/1/8h/*'").unwrap()]);

// All the same but with extended private keys instead of xpubs.
Expand Down
65 changes: 62 additions & 3 deletions src/descriptor/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,8 @@ use sync::Arc;

use self::checksum::verify_checksum;
use crate::miniscript::decode::Terminal;
use crate::miniscript::{Legacy, Miniscript, Segwitv0};
use crate::miniscript::{satisfy, Legacy, Miniscript, Segwitv0};
use crate::plan::{AssetProvider, Plan};
use crate::prelude::*;
use crate::{
expression, hash256, BareCtx, Error, ForEachKey, MiniscriptKey, Satisfier, ToPublicKey,
Expand Down Expand Up @@ -474,7 +475,7 @@ impl<Pk: MiniscriptKey + ToPublicKey> Descriptor<Pk> {
Descriptor::Wpkh(ref wpkh) => wpkh.get_satisfaction(satisfier),
Descriptor::Wsh(ref wsh) => wsh.get_satisfaction(satisfier),
Descriptor::Sh(ref sh) => sh.get_satisfaction(satisfier),
Descriptor::Tr(ref tr) => tr.get_satisfaction(satisfier),
Descriptor::Tr(ref tr) => tr.get_satisfaction(&satisfier),
}
}

Expand All @@ -491,7 +492,7 @@ impl<Pk: MiniscriptKey + ToPublicKey> Descriptor<Pk> {
Descriptor::Wpkh(ref wpkh) => wpkh.get_satisfaction_mall(satisfier),
Descriptor::Wsh(ref wsh) => wsh.get_satisfaction_mall(satisfier),
Descriptor::Sh(ref sh) => sh.get_satisfaction_mall(satisfier),
Descriptor::Tr(ref tr) => tr.get_satisfaction_mall(satisfier),
Descriptor::Tr(ref tr) => tr.get_satisfaction_mall(&satisfier),
}
}

Expand All @@ -509,6 +510,64 @@ impl<Pk: MiniscriptKey + ToPublicKey> Descriptor<Pk> {
}
}

impl Descriptor<DefiniteDescriptorKey> {
/// Returns a plan if the provided assets are sufficient to produce a non-malleable satisfaction
///
/// If the assets aren't sufficient for generating a Plan, the descriptor is returned
pub fn plan<P>(self, provider: &P) -> Result<Plan, Self>
where
P: AssetProvider<DefiniteDescriptorKey>,
{
let satisfaction = match self {
Descriptor::Bare(ref bare) => bare.plan_satisfaction(provider),
Descriptor::Pkh(ref pkh) => pkh.plan_satisfaction(provider),
Descriptor::Wpkh(ref wpkh) => wpkh.plan_satisfaction(provider),
Descriptor::Wsh(ref wsh) => wsh.plan_satisfaction(provider),
Descriptor::Sh(ref sh) => sh.plan_satisfaction(provider),
Descriptor::Tr(ref tr) => tr.plan_satisfaction(provider),
};

if let satisfy::Witness::Stack(stack) = satisfaction.stack {
Ok(Plan {
descriptor: self,
template: stack,
absolute_timelock: satisfaction.absolute_timelock.map(Into::into),
relative_timelock: satisfaction.relative_timelock,
})
} else {
Err(self)
}
}

/// Returns a plan if the provided assets are sufficient to produce a malleable satisfaction
///
/// If the assets aren't sufficient for generating a Plan, the descriptor is returned
pub fn plan_mall<P>(self, provider: &P) -> Result<Plan, Self>
where
P: AssetProvider<DefiniteDescriptorKey>,
{
let satisfaction = match self {
Descriptor::Bare(ref bare) => bare.plan_satisfaction_mall(provider),
Descriptor::Pkh(ref pkh) => pkh.plan_satisfaction_mall(provider),
Descriptor::Wpkh(ref wpkh) => wpkh.plan_satisfaction_mall(provider),
Descriptor::Wsh(ref wsh) => wsh.plan_satisfaction_mall(provider),
Descriptor::Sh(ref sh) => sh.plan_satisfaction_mall(provider),
Descriptor::Tr(ref tr) => tr.plan_satisfaction_mall(provider),
};

if let satisfy::Witness::Stack(stack) = satisfaction.stack {
Ok(Plan {
descriptor: self,
template: stack,
absolute_timelock: satisfaction.absolute_timelock.map(Into::into),
relative_timelock: satisfaction.relative_timelock,
})
} else {
Err(self)
}
}
}

impl<P, Q> TranslatePk<P, Q> for Descriptor<P>
where
P: MiniscriptKey,
Expand Down
Loading
Loading