[wallet] Specify the policy branch with a map

This commit is contained in:
Alekos Filini 2020-05-16 16:48:31 +02:00
parent c1b01e4d8c
commit fb4abfb99c
No known key found for this signature in database
GPG Key ID: 5E8AFC3034FDFA4F
3 changed files with 26 additions and 19 deletions

View File

@ -1,3 +1,4 @@
use std::collections::BTreeMap;
use std::str::FromStr; use std::str::FromStr;
use clap::{App, Arg, ArgMatches, SubCommand}; use clap::{App, Arg, ArgMatches, SubCommand};
@ -110,7 +111,7 @@ pub fn make_cli_subcommands<'a, 'b>() -> App<'a, 'b> {
Arg::with_name("policy") Arg::with_name("policy")
.long("policy") .long("policy")
.value_name("POLICY") .value_name("POLICY")
.help("Selects which policy will be used to satisfy the descriptor") .help("Selects which policy should be used to satisfy the descriptor")
.takes_value(true) .takes_value(true)
.number_of_values(1), .number_of_values(1),
), ),
@ -252,9 +253,9 @@ where
let unspendable = sub_matches let unspendable = sub_matches
.values_of("unspendable") .values_of("unspendable")
.map(|s| s.map(|i| parse_outpoint(i).unwrap()).collect()); .map(|s| s.map(|i| parse_outpoint(i).unwrap()).collect());
let policy: Option<Vec<_>> = sub_matches let policy: Option<_> = sub_matches
.value_of("policy") .value_of("policy")
.map(|s| serde_json::from_str::<Vec<Vec<usize>>>(&s).unwrap()); .map(|s| serde_json::from_str::<BTreeMap<String, Vec<usize>>>(&s).unwrap());
let result = wallet.create_tx( let result = wallet.create_tx(
addressees, addressees,

View File

@ -14,6 +14,7 @@ use miniscript::{Descriptor, Miniscript, Terminal};
#[allow(unused_imports)] #[allow(unused_imports)]
use log::{debug, error, info, trace}; use log::{debug, error, info, trace};
use super::checksum::get_checksum;
use super::error::Error; use super::error::Error;
use crate::descriptor::{Key, MiniscriptExtractPolicy}; use crate::descriptor::{Key, MiniscriptExtractPolicy};
use crate::psbt::PSBTSatisfier; use crate::psbt::PSBTSatisfier;
@ -93,6 +94,11 @@ impl SatisfiableItem {
_ => true, _ => true,
} }
} }
pub fn id(&self) -> String {
get_checksum(&serde_json::to_string(self).expect("Failed to serialize a SatisfiableItem"))
.expect("Failed to compute a SatisfiableItem id")
}
} }
fn combinations(vec: &Vec<usize>, size: usize) -> Vec<Vec<usize>> { fn combinations(vec: &Vec<usize>, size: usize) -> Vec<Vec<usize>> {
@ -328,6 +334,8 @@ impl From<bool> for Satisfaction {
#[derive(Debug, Clone, Serialize)] #[derive(Debug, Clone, Serialize)]
pub struct Policy { pub struct Policy {
id: String,
#[serde(flatten)] #[serde(flatten)]
item: SatisfiableItem, item: SatisfiableItem,
satisfaction: Satisfaction, satisfaction: Satisfaction,
@ -376,8 +384,8 @@ impl Condition {
#[derive(Debug)] #[derive(Debug)]
pub enum PolicyError { pub enum PolicyError {
NotEnoughItemsSelected(usize), NotEnoughItemsSelected(String),
TooManyItemsSelected(usize), TooManyItemsSelected(String),
IndexOutOfRange(usize), IndexOutOfRange(usize),
AddOnLeaf, AddOnLeaf,
AddOnPartialComplete, AddOnPartialComplete,
@ -388,6 +396,7 @@ pub enum PolicyError {
impl Policy { impl Policy {
pub fn new(item: SatisfiableItem) -> Self { pub fn new(item: SatisfiableItem) -> Self {
Policy { Policy {
id: item.id(),
item, item,
satisfaction: Satisfaction::None, satisfaction: Satisfaction::None,
contribution: Satisfaction::None, contribution: Satisfaction::None,
@ -479,17 +488,12 @@ impl Policy {
} }
pub fn requires_path(&self) -> bool { pub fn requires_path(&self) -> bool {
self.get_requirements(&vec![]).is_err() self.get_requirements(&BTreeMap::new()).is_err()
} }
pub fn get_requirements(&self, path: &Vec<Vec<usize>>) -> Result<Condition, PolicyError> { pub fn get_requirements(
self.recursive_get_requirements(path, 0)
}
fn recursive_get_requirements(
&self, &self,
path: &Vec<Vec<usize>>, path: &BTreeMap<String, Vec<usize>>,
index: usize,
) -> Result<Condition, PolicyError> { ) -> Result<Condition, PolicyError> {
// if items.len() == threshold, selected can be omitted and we take all of them by default // if items.len() == threshold, selected can be omitted and we take all of them by default
let default = match &self.item { let default = match &self.item {
@ -498,7 +502,7 @@ impl Policy {
} }
_ => vec![], _ => vec![],
}; };
let selected = match path.get(index) { let selected = match path.get(&self.id) {
_ if !default.is_empty() => &default, _ if !default.is_empty() => &default,
Some(arr) => arr, Some(arr) => arr,
_ => &default, _ => &default,
@ -508,7 +512,7 @@ impl Policy {
SatisfiableItem::Thresh { items, threshold } => { SatisfiableItem::Thresh { items, threshold } => {
let mapped_req = items let mapped_req = items
.iter() .iter()
.map(|i| i.recursive_get_requirements(path, index + 1)) .map(|i| i.get_requirements(path))
.collect::<Result<Vec<_>, _>>()?; .collect::<Result<Vec<_>, _>>()?;
// if all the requirements are null we don't care about `selected` because there // if all the requirements are null we don't care about `selected` because there
@ -521,7 +525,9 @@ impl Policy {
// an empty value for this step in case of n-of-n, because `selected` is set to all // an empty value for this step in case of n-of-n, because `selected` is set to all
// the elements above // the elements above
if selected.len() < *threshold { if selected.len() < *threshold {
return Err(PolicyError::NotEnoughItemsSelected(index)); return Err(PolicyError::NotEnoughItemsSelected(self.id.clone()));
} else if selected.len() > *threshold {
return Err(PolicyError::TooManyItemsSelected(self.id.clone()));
} }
// check the selected items, see if there are conflicting requirements // check the selected items, see if there are conflicting requirements
@ -536,7 +542,7 @@ impl Policy {
Ok(requirements) Ok(requirements)
} }
_ if !selected.is_empty() => Err(PolicyError::TooManyItemsSelected(index)), _ if !selected.is_empty() => Err(PolicyError::TooManyItemsSelected(self.id.clone())),
SatisfiableItem::AbsoluteTimelock { value } => Ok(Condition { SatisfiableItem::AbsoluteTimelock { value } => Ok(Condition {
csv: None, csv: None,
timelock: Some(*value), timelock: Some(*value),

View File

@ -126,7 +126,7 @@ where
addressees: Vec<(Address, u64)>, addressees: Vec<(Address, u64)>,
send_all: bool, send_all: bool,
fee_perkb: f32, fee_perkb: f32,
policy_path: Option<Vec<Vec<usize>>>, policy_path: Option<BTreeMap<String, Vec<usize>>>,
utxos: Option<Vec<OutPoint>>, utxos: Option<Vec<OutPoint>>,
unspendable: Option<Vec<OutPoint>>, unspendable: Option<Vec<OutPoint>>,
) -> Result<(PSBT, TransactionDetails), Error> { ) -> Result<(PSBT, TransactionDetails), Error> {
@ -134,7 +134,7 @@ where
if policy.requires_path() && policy_path.is_none() { if policy.requires_path() && policy_path.is_none() {
return Err(Error::SpendingPolicyRequired); return Err(Error::SpendingPolicyRequired);
} }
let requirements = policy.get_requirements(&policy_path.unwrap_or(vec![]))?; let requirements = policy.get_requirements(&policy_path.unwrap_or(BTreeMap::new()))?;
debug!("requirements: {:?}", requirements); debug!("requirements: {:?}", requirements);
let mut tx = Transaction { let mut tx = Transaction {