use core::fmt;
use bitcoin::script::{self, PushBytes};
use bitcoin::{Address, Network, ScriptBuf, Weight};
use super::checksum::verify_checksum;
use crate::descriptor::{write_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};
use crate::{
BareCtx, Error, ForEachKey, FromStrKey, Miniscript, MiniscriptKey, Satisfier, ToPublicKey,
TranslateErr, TranslatePk, Translator,
};
#[derive(Clone, Ord, PartialOrd, Eq, PartialEq, Hash)]
pub struct Bare<Pk: MiniscriptKey> {
ms: Miniscript<Pk, BareCtx>,
}
impl<Pk: MiniscriptKey> Bare<Pk> {
pub fn new(ms: Miniscript<Pk, BareCtx>) -> Result<Self, Error> {
BareCtx::top_level_checks(&ms)?;
Ok(Self { ms })
}
pub fn into_inner(self) -> Miniscript<Pk, BareCtx> { self.ms }
pub fn as_inner(&self) -> &Miniscript<Pk, BareCtx> { &self.ms }
pub fn sanity_check(&self) -> Result<(), Error> {
self.ms.sanity_check()?;
Ok(())
}
pub fn max_weight_to_satisfy(&self) -> Result<Weight, Error> {
let scriptsig_size = self.ms.max_satisfaction_size()?;
let scriptsig_varint_diff = varint_len(scriptsig_size) - varint_len(0);
Weight::from_vb((scriptsig_varint_diff + scriptsig_size) as u64)
.ok_or(Error::CouldNotSatisfy)
}
#[deprecated(
since = "10.0.0",
note = "Use max_weight_to_satisfy instead. The method to count bytes was redesigned and the results will differ from max_weight_to_satisfy. For more details check rust-bitcoin/rust-miniscript#476."
)]
pub fn max_satisfaction_weight(&self) -> Result<usize, Error> {
let scriptsig_len = self.ms.max_satisfaction_size()?;
Ok(4 * (varint_len(scriptsig_len) + scriptsig_len))
}
}
impl<Pk: MiniscriptKey + ToPublicKey> Bare<Pk> {
pub fn script_pubkey(&self) -> ScriptBuf { self.ms.encode() }
pub fn inner_script(&self) -> ScriptBuf { self.script_pubkey() }
pub fn ecdsa_sighash_script_code(&self) -> ScriptBuf { self.script_pubkey() }
pub fn get_satisfaction<S>(&self, satisfier: S) -> Result<(Vec<Vec<u8>>, ScriptBuf), Error>
where
S: Satisfier<Pk>,
{
let ms = self.ms.satisfy(satisfier)?;
let script_sig = witness_to_scriptsig(&ms);
let witness = vec![];
Ok((witness, script_sig))
}
pub fn get_satisfaction_mall<S>(&self, satisfier: S) -> Result<(Vec<Vec<u8>>, ScriptBuf), Error>
where
S: Satisfier<Pk>,
{
let ms = self.ms.satisfy_malleable(satisfier)?;
let script_sig = witness_to_scriptsig(&ms);
let witness = vec![];
Ok((witness, script_sig))
}
}
impl Bare<DefiniteDescriptorKey> {
pub fn plan_satisfaction<P>(
&self,
provider: &P,
) -> Satisfaction<Placeholder<DefiniteDescriptorKey>>
where
P: AssetProvider<DefiniteDescriptorKey>,
{
self.ms.build_template(provider)
}
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) }
}
impl<Pk: MiniscriptKey> fmt::Display for Bare<Pk> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write_descriptor!(f, "{}", self.ms) }
}
impl<Pk: MiniscriptKey> Liftable<Pk> for Bare<Pk> {
fn lift(&self) -> Result<semantic::Policy<Pk>, Error> { self.ms.lift() }
}
impl<Pk: FromStrKey> FromTree for Bare<Pk> {
fn from_tree(top: &expression::Tree) -> Result<Self, Error> {
let sub = Miniscript::<Pk, BareCtx>::from_tree(top)?;
BareCtx::top_level_checks(&sub)?;
Bare::new(sub)
}
}
impl<Pk: FromStrKey> core::str::FromStr for Bare<Pk> {
type Err = Error;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let desc_str = verify_checksum(s)?;
let top = expression::Tree::from_str(desc_str)?;
Self::from_tree(&top)
}
}
impl<Pk: MiniscriptKey> ForEachKey<Pk> for Bare<Pk> {
fn for_each_key<'a, F: FnMut(&'a Pk) -> bool>(&'a self, pred: F) -> bool {
self.ms.for_each_key(pred)
}
}
impl<P, Q> TranslatePk<P, Q> for Bare<P>
where
P: MiniscriptKey,
Q: MiniscriptKey,
{
type Output = Bare<Q>;
fn translate_pk<T, E>(&self, t: &mut T) -> Result<Bare<Q>, TranslateErr<E>>
where
T: Translator<P, Q, E>,
{
Bare::new(self.ms.translate_pk(t)?).map_err(TranslateErr::OuterError)
}
}
#[derive(Clone, Ord, PartialOrd, Eq, PartialEq, Hash)]
pub struct Pkh<Pk: MiniscriptKey> {
pk: Pk,
}
impl<Pk: MiniscriptKey> Pkh<Pk> {
pub fn new(pk: Pk) -> Result<Self, ScriptContextError> {
match BareCtx::check_pk(&pk) {
Ok(()) => Ok(Pkh { pk }),
Err(e) => Err(e),
}
}
pub fn as_inner(&self) -> &Pk { &self.pk }
pub fn into_inner(self) -> Pk { self.pk }
pub fn max_weight_to_satisfy(&self) -> Weight {
let scriptsig_size = 73 + BareCtx::pk_len(&self.pk);
let scriptsig_varint_diff = varint_len(scriptsig_size) - varint_len(0);
Weight::from_vb((scriptsig_varint_diff + scriptsig_size) as u64).unwrap()
}
#[deprecated(
since = "10.0.0",
note = "Use max_weight_to_satisfy instead. The method to count bytes was redesigned and the results will differ from max_weight_to_satisfy. For more details check rust-bitcoin/rust-miniscript#476."
)]
pub fn max_satisfaction_weight(&self) -> usize { 4 * (1 + 73 + BareCtx::pk_len(&self.pk)) }
}
impl<Pk: MiniscriptKey + ToPublicKey> Pkh<Pk> {
pub fn script_pubkey(&self) -> ScriptBuf {
let addr = self.address(Network::Bitcoin);
addr.script_pubkey()
}
pub fn address(&self, network: Network) -> Address {
Address::p2pkh(self.pk.to_public_key(), network)
}
pub fn inner_script(&self) -> ScriptBuf { self.script_pubkey() }
pub fn ecdsa_sighash_script_code(&self) -> ScriptBuf { self.script_pubkey() }
pub fn get_satisfaction<S>(&self, satisfier: S) -> Result<(Vec<Vec<u8>>, ScriptBuf), Error>
where
S: Satisfier<Pk>,
{
if let Some(sig) = satisfier.lookup_ecdsa_sig(&self.pk) {
let script_sig = script::Builder::new()
.push_slice::<&PushBytes>(
sig.serialize().as_ref(),
)
.push_key(&self.pk.to_public_key())
.into_script();
let witness = vec![];
Ok((witness, script_sig))
} else {
Err(Error::MissingSig(self.pk.to_public_key()))
}
}
pub fn get_satisfaction_mall<S>(&self, satisfier: S) -> Result<(Vec<Vec<u8>>, ScriptBuf), Error>
where
S: Satisfier<Pk>,
{
self.get_satisfaction(satisfier)
}
}
impl Pkh<DefiniteDescriptorKey> {
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 }
}
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) }
}
impl<Pk: MiniscriptKey> fmt::Display for Pkh<Pk> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write_descriptor!(f, "pkh({})", self.pk)
}
}
impl<Pk: MiniscriptKey> Liftable<Pk> for Pkh<Pk> {
fn lift(&self) -> Result<semantic::Policy<Pk>, Error> {
Ok(semantic::Policy::Key(self.pk.clone()))
}
}
impl<Pk: FromStrKey> FromTree for Pkh<Pk> {
fn from_tree(top: &expression::Tree) -> Result<Self, Error> {
if top.name == "pkh" && top.args.len() == 1 {
Ok(Pkh::new(expression::terminal(&top.args[0], |pk| Pk::from_str(pk))?)?)
} else {
Err(Error::Unexpected(format!(
"{}({} args) while parsing pkh descriptor",
top.name,
top.args.len(),
)))
}
}
}
impl<Pk: FromStrKey> core::str::FromStr for Pkh<Pk> {
type Err = Error;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let desc_str = verify_checksum(s)?;
let top = expression::Tree::from_str(desc_str)?;
Self::from_tree(&top)
}
}
impl<Pk: MiniscriptKey> ForEachKey<Pk> for Pkh<Pk> {
fn for_each_key<'a, F: FnMut(&'a Pk) -> bool>(&'a self, mut pred: F) -> bool { pred(&self.pk) }
}
impl<P, Q> TranslatePk<P, Q> for Pkh<P>
where
P: MiniscriptKey,
Q: MiniscriptKey,
{
type Output = Pkh<Q>;
fn translate_pk<T, E>(&self, t: &mut T) -> Result<Self::Output, TranslateErr<E>>
where
T: Translator<P, Q, E>,
{
let res = Pkh::new(t.pk(&self.pk)?);
match res {
Ok(pk) => Ok(pk),
Err(e) => Err(TranslateErr::OuterError(Error::from(e))),
}
}
}