Skip to content

Commit

Permalink
cargo fmt
Browse files Browse the repository at this point in the history
  • Loading branch information
apoelstra committed Jun 15, 2023
1 parent 9992bee commit e5d4593
Show file tree
Hide file tree
Showing 22 changed files with 91 additions and 75 deletions.
2 changes: 1 addition & 1 deletion rustfmt.toml
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ enum_discrim_align_threshold = 0
match_arm_blocks = true
match_arm_leading_pipes = "Never"
force_multiline_blocks = false
fn_args_layout = "Tall"
fn_params_layout = "Tall"
brace_style = "SameLineWhere"
control_brace_style = "AlwaysSameLine"
trailing_semicolon = true
Expand Down
4 changes: 2 additions & 2 deletions src/descriptor/csfs_cov/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -64,8 +64,8 @@ mod tests {
use elements::secp256k1_zkp::ZERO_TWEAK;
use elements::{
self, confidential, opcodes, script, secp256k1_zkp, AssetId, AssetIssuance,
EcdsaSigHashType, LockTime, OutPoint, Script, Sequence, Transaction, TxIn,
TxInWitness, TxOut, Txid,
EcdsaSigHashType, LockTime, OutPoint, Script, Sequence, Transaction, TxIn, TxInWitness,
TxOut, Txid,
};

use super::cov::*;
Expand Down
16 changes: 8 additions & 8 deletions src/descriptor/key.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@ use std::convert::TryInto;
use std::str::FromStr;
use std::{error, fmt};

use bitcoin::bip32;
use bitcoin::{self, hash_types::XpubIdentifier};
use bitcoin::hash_types::XpubIdentifier;
use bitcoin::{self, bip32};
use elements::hashes::{hash160, ripemd160, sha256, Hash, HashEngine};
use elements::secp256k1_zkp::{Secp256k1, Signing, Verification};

Expand Down Expand Up @@ -461,9 +461,10 @@ impl FromStr for DescriptorPublicKey {
} else {
let key = match key_part.len() {
64 => {
let x_only_key = bitcoin::key::XOnlyPublicKey::from_str(key_part).map_err(|_| {
DescriptorKeyParseError("Error while parsing simple xonly key")
})?;
let x_only_key =
bitcoin::key::XOnlyPublicKey::from_str(key_part).map_err(|_| {
DescriptorKeyParseError("Error while parsing simple xonly key")
})?;
SinglePubKey::XOnly(x_only_key)
}
66 | 130 => {
Expand Down Expand Up @@ -978,7 +979,7 @@ impl MiniscriptKey for DescriptorPublicKey {

fn is_x_only_key(&self) -> bool {
matches!(
self,
self,
DescriptorPublicKey::Single(SinglePub {
key: SinglePubKey::XOnly(ref _key),
..
Expand Down Expand Up @@ -1160,8 +1161,7 @@ impl Serialize for DescriptorPublicKey {
mod test {
use std::str::FromStr;

use bitcoin::secp256k1;
use bitcoin::bip32;
use bitcoin::{bip32, secp256k1};
use elements::secp256k1_zkp;
#[cfg(feature = "serde")]
use serde_test::{assert_tokens, Token};
Expand Down
5 changes: 2 additions & 3 deletions src/descriptor/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1276,10 +1276,9 @@ mod tests {
use std::str::FromStr;

use bitcoin;
use bitcoin::bip32;
use bitcoin::PublicKey;
use elements::hex::{FromHex, ToHex};
use bitcoin::{bip32, PublicKey};
use elements::hashes::{hash160, sha256};
use elements::hex::{FromHex, ToHex};
use elements::opcodes::all::{OP_CLTV, OP_CSV};
use elements::script::Instruction;
use elements::{opcodes, script, Sequence};
Expand Down
4 changes: 1 addition & 3 deletions src/descriptor/pegin/dynafed_pegin.rs
Original file line number Diff line number Diff line change
Expand Up @@ -189,9 +189,7 @@ impl<Pk: MiniscriptKey> Pegin<Pk> {
.expect("TODO after taproot");
let push_bytes = <&PushBytes>::try_from(witness_script.as_bytes())
.expect("Witness script is not too larg");
script::Builder::new()
.push_slice(push_bytes)
.into_script()
script::Builder::new().push_slice(push_bytes).into_script()
}

/// Computes the bitcoin "witness script" of the descriptor, i.e. the underlying
Expand Down
6 changes: 2 additions & 4 deletions src/descriptor/pegin/legacy_pegin.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,8 @@ use std::fmt;
use std::str::FromStr;
use std::sync::Arc;

use bitcoin::blockdata::{opcodes, script};
use bitcoin::blockdata::script::PushBytes;
use bitcoin::blockdata::{opcodes, script};
use bitcoin::hashes::{hash160, ripemd160, sha256, Hash};
use bitcoin::{self, hashes, ScriptBuf as BtcScript};
use bitcoin_miniscript::TranslatePk as BtcTranslatePk;
Expand Down Expand Up @@ -440,9 +440,7 @@ impl<Pk: MiniscriptKey> LegacyPegin<Pk> {
let witness_script = self.explicit_script(secp);
let push_bytes = <&PushBytes>::try_from(witness_script.as_bytes())
.expect("Witness script is not too larg");
script::Builder::new()
.push_slice(push_bytes)
.into_script()
script::Builder::new().push_slice(push_bytes).into_script()
}
/// Computes the bitcoin "witness script" of the descriptor, i.e. the underlying
/// script before any hashing is done. For `Bare`, `Pkh` and `Wpkh` this
Expand Down
16 changes: 10 additions & 6 deletions src/extensions/arith.rs
Original file line number Diff line number Diff line change
Expand Up @@ -947,7 +947,9 @@ impl<T: ExtParam> Arith<T> {
return Err(TypeError::PriceOracle1Missing);
}
// All the elements in b should be PriceOracle1W
if b.iter_terminals().any(|x| matches!(x, ExprInner::PriceOracle1(..))) {
if b.iter_terminals()
.any(|x| matches!(x, ExprInner::PriceOracle1(..)))
{
return Err(TypeError::PriceOracle1Missing);
}
}
Expand Down Expand Up @@ -1347,7 +1349,10 @@ impl<T: ExtParam> Extension for Arith<T> {
))
}

fn from_name_tree(name: &str, children: &[expression::Tree<'_>]) -> Result<Self, FromTokenIterError> {
fn from_name_tree(
name: &str,
children: &[expression::Tree<'_>],
) -> Result<Self, FromTokenIterError> {
let tree = Tree {
name,
args: children.to_vec(), // Cloning two references here, it is possible to avoid the to_vec() here,
Expand Down Expand Up @@ -1603,10 +1608,9 @@ where
ExprInner::Negate(a) => Ok(Expr::from_inner(ExprInner::Negate(Box::new(
a.translate_ext(t)?,
)))),
ExprInner::PriceOracle1(pk, time) => Ok(Expr::from_inner(ExprInner::PriceOracle1(
t.ext(pk)?,
*time,
))),
ExprInner::PriceOracle1(pk, time) => {
Ok(Expr::from_inner(ExprInner::PriceOracle1(t.ext(pk)?, *time)))
}
ExprInner::PriceOracle1W(pk, time) => Ok(Expr::from_inner(ExprInner::PriceOracle1W(
t.ext(pk)?,
*time,
Expand Down
5 changes: 4 additions & 1 deletion src/extensions/csfs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,10 @@ impl<T: ExtParam> Extension for CheckSigFromStack<T> {
))
}

fn from_name_tree(name: &str, children: &[expression::Tree<'_>]) -> Result<Self, FromTokenIterError> {
fn from_name_tree(
name: &str,
children: &[expression::Tree<'_>],
) -> Result<Self, FromTokenIterError> {
if children.len() == 2 && name == "csfs" {
if !children[0].args.is_empty() || !children[1].args.is_empty() {
return Err(FromTokenIterError);
Expand Down
11 changes: 6 additions & 5 deletions src/extensions/introspect_ops.rs
Original file line number Diff line number Diff line change
Expand Up @@ -567,8 +567,7 @@ impl ArgFromStr for confidential::Asset {
));
}
let asset_hex = Vec::<u8>::from_hex(s).map_err(|e| Error::Unexpected(e.to_string()))?;
elements::encode::deserialize(&asset_hex)
.map_err(|e| Error::Unexpected(e.to_string()))
elements::encode::deserialize(&asset_hex).map_err(|e| Error::Unexpected(e.to_string()))
}
}

Expand All @@ -580,8 +579,7 @@ impl ArgFromStr for confidential::Value {
));
}
let asset_hex = Vec::<u8>::from_hex(s).map_err(|e| Error::Unexpected(e.to_string()))?;
elements::encode::deserialize(&asset_hex)
.map_err(|e| Error::Unexpected(e.to_string()))
elements::encode::deserialize(&asset_hex).map_err(|e| Error::Unexpected(e.to_string()))
}
}

Expand Down Expand Up @@ -638,7 +636,10 @@ fn spk(pref: i8, prog: &[u8]) -> Option<elements::Script> {
// This converts legacy programs to (-1, sha256::Hash(spk))
fn spk_to_components(s: &elements::Script) -> (i8, Vec<u8>) {
if !s.is_witness_program() {
(-1, sha256::Hash::hash(s.as_bytes()).to_byte_array().to_vec())
(
-1,
sha256::Hash::hash(s.as_bytes()).to_byte_array().to_vec(),
)
} else {
// indirect way to get payload.
// The address parameters don't really matter here
Expand Down
10 changes: 7 additions & 3 deletions src/extensions/outputs_pref.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@
use std::fmt;

use elements::encode::serialize;
use elements::hex::{FromHex, ToHex};
use elements::hashes::{sha256d, Hash};
use elements::hex::{FromHex, ToHex};

use super::{FromTokenIterError, ParseableExt, TxEnv};
use crate::descriptor::CovError;
Expand Down Expand Up @@ -105,9 +105,13 @@ impl Extension for LegacyOutputsPref {
+ 6 /* line 2 */
}

fn from_name_tree(name: &str, children: &[expression::Tree<'_>]) -> Result<Self, FromTokenIterError> {
fn from_name_tree(
name: &str,
children: &[expression::Tree<'_>],
) -> Result<Self, FromTokenIterError> {
if children.len() == 1 && name == "outputs_pref" {
let pref = expression::terminal(&children[0], Vec::<u8>::from_hex).map_err(|_| FromTokenIterError)?;
let pref = expression::terminal(&children[0], Vec::<u8>::from_hex)
.map_err(|_| FromTokenIterError)?;
Ok(Self { pref })
} else {
// Correct error handling while parsing fromtree
Expand Down
8 changes: 6 additions & 2 deletions src/extensions/tx_ver.rs
Original file line number Diff line number Diff line change
Expand Up @@ -84,9 +84,13 @@ impl Extension for LegacyVerEq {
4 + 1 + 1 + 4 // opcodes + push opcodes + target size
}

fn from_name_tree(name: &str, children: &[expression::Tree<'_>]) -> Result<Self, FromTokenIterError> {
fn from_name_tree(
name: &str,
children: &[expression::Tree<'_>],
) -> Result<Self, FromTokenIterError> {
if children.len() == 1 && name == "ver_eq" {
let n = expression::terminal(&children[0], expression::parse_num).map_err(|_| FromTokenIterError)?;
let n = expression::terminal(&children[0], expression::parse_num)
.map_err(|_| FromTokenIterError)?;
Ok(Self { n })
} else {
// Correct error handling while parsing fromtree
Expand Down
9 changes: 6 additions & 3 deletions src/interpreter/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -304,8 +304,9 @@ where
// schnorr sigs in ecdsa descriptors
return false;
};
let msg = sighash_msg
.map(|hash| secp256k1_zkp::Message::from_slice(hash.as_ref()).expect("32 byte"));
let msg = sighash_msg.map(|hash| {
secp256k1_zkp::Message::from_slice(hash.as_ref()).expect("32 byte")
});
let success =
msg.map(|msg| secp.verify_schnorr(&schnorr_sig.sig, &msg, xpk).is_ok());
success.unwrap_or(false) // unwrap_or_default checks for errors, while success would have checksig results
Expand Down Expand Up @@ -699,7 +700,9 @@ where
Terminal::After(ref n) => {
debug_assert_eq!(node_state.n_evaluated, 0);
debug_assert_eq!(node_state.n_satisfied, 0);
let res = self.stack.evaluate_after(&LockTime::from(*n), self.lock_time);
let res = self
.stack
.evaluate_after(&LockTime::from(*n), self.lock_time);
if res.is_some() {
return res;
}
Expand Down
11 changes: 5 additions & 6 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -98,8 +98,8 @@
#![deny(dead_code)]
#![deny(unused_imports)]
#![deny(missing_docs)]
#![allow(clippy::manual_range_contains)] // this lint is just stupid
#![allow(clippy::type_complexity)] // clippy doesn't like how many generics we use
#![allow(clippy::manual_range_contains)] // this lint is just stupid
#![allow(clippy::type_complexity)] // clippy doesn't like how many generics we use

#[cfg(target_pointer_width = "16")]
compile_error!(
Expand All @@ -119,12 +119,12 @@ extern crate test;
use bitcoin_miniscript::expression::{FromTree as BtcFromTree, Tree as BtcTree};
use bitcoin_miniscript::policy::semantic::Policy as BtcPolicy;
use bitcoin_miniscript::policy::Liftable as BtcLiftable;
// re-export imports
pub use bitcoin_miniscript::{hash256, ForEachKey, MiniscriptKey, SigType, ToPublicKey};
use bitcoin_miniscript::{
Descriptor as BtcDescriptor, Error as BtcError, Miniscript as BtcMiniscript,
Satisfier as BtcSatisfier, Segwitv0 as BtcSegwitv0, Terminal as BtcTerminal,
};
// re-export imports
pub use bitcoin_miniscript::{hash256, ForEachKey, MiniscriptKey, SigType, ToPublicKey};
// End imports

#[macro_use]
Expand All @@ -149,10 +149,9 @@ mod util;

use std::{cmp, error, fmt, str};

use elements::locktime;
use elements::hashes::sha256;
use elements::secp256k1_zkp::Secp256k1;
use elements::{opcodes, script, secp256k1_zkp};
use elements::{locktime, opcodes, script, secp256k1_zkp};

pub use crate::descriptor::{DefiniteDescriptorKey, Descriptor, DescriptorPublicKey};
pub use crate::extensions::{CovenantExt, Extension, NoExt, TxEnv};
Expand Down
3 changes: 2 additions & 1 deletion src/miniscript/analyzable.rs
Original file line number Diff line number Diff line change
Expand Up @@ -217,7 +217,8 @@ impl<Pk: MiniscriptKey, Ctx: ScriptContext, Ext: Extension> Miniscript<Pk, Ctx,

/// Whether the given miniscript contains a raw pkh fragment
pub fn contains_raw_pkh(&self) -> bool {
self.iter().any(|ms| matches!(ms.node, Terminal::RawPkH(..)))
self.iter()
.any(|ms| matches!(ms.node, Terminal::RawPkH(..)))
}

/// Check whether the underlying Miniscript is safe under the current context
Expand Down
4 changes: 2 additions & 2 deletions src/miniscript/astelem.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,8 @@ use crate::miniscript::types::{self, Property};
use crate::miniscript::ScriptContext;
use crate::util::MsKeyBuilder;
use crate::{
errstr, expression, script_num_size, AbsLockTime, Error, ExtTranslator, Extension, ForEachKey, Miniscript,
MiniscriptKey, Terminal, ToPublicKey, TranslateExt, TranslatePk, Translator,
errstr, expression, script_num_size, AbsLockTime, Error, ExtTranslator, Extension, ForEachKey,
Miniscript, MiniscriptKey, Terminal, ToPublicKey, TranslateExt, TranslatePk, Translator,
};

impl<Pk: MiniscriptKey, Ctx: ScriptContext, Ext: Extension> Terminal<Pk, Ctx, Ext> {
Expand Down
15 changes: 8 additions & 7 deletions src/miniscript/decode.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,9 @@ use crate::miniscript::types::{Property, Type};
use crate::miniscript::ScriptContext;
#[cfg(doc)]
use crate::Descriptor;
use crate::{bitcoin, hash256, AbsLockTime, Error, Extension, Miniscript, MiniscriptKey, NoExt, ToPublicKey};
use crate::{
bitcoin, hash256, AbsLockTime, Error, Extension, Miniscript, MiniscriptKey, NoExt, ToPublicKey,
};

fn return_none<T>(_: usize) -> Option<T> {
None
Expand Down Expand Up @@ -655,11 +657,10 @@ pub fn parse<Ctx: ScriptContext, Ext: ParseableExt>(
fn is_and_v(tokens: &mut TokenIter<'_>) -> bool {
!matches!(
tokens.peek(),
None
| Some(&Tk::If)
| Some(&Tk::NotIf)
| Some(&Tk::Else)
| Some(&Tk::ToAltStack)
| Some(&Tk::Swap)
None | Some(&Tk::If)
| Some(&Tk::NotIf)
| Some(&Tk::Else)
| Some(&Tk::ToAltStack)
| Some(&Tk::Swap)
)
}
6 changes: 4 additions & 2 deletions src/miniscript/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -535,7 +535,8 @@ mod tests {
use std::str::FromStr;
use std::sync::Arc;

use bitcoin::{self, key::XOnlyPublicKey};
use bitcoin::key::XOnlyPublicKey;
use bitcoin::{self};
use elements::hashes::{hash160, sha256, Hash};
use elements::taproot::TapLeafHash;
use elements::{self, secp256k1_zkp, Sequence};
Expand Down Expand Up @@ -1161,7 +1162,8 @@ mod tests {
.unwrap();
// script rtt test
assert_eq!(
Miniscript::<bitcoin::key::XOnlyPublicKey, Tap>::parse_insane(&tap_ms.encode()).unwrap(),
Miniscript::<bitcoin::key::XOnlyPublicKey, Tap>::parse_insane(&tap_ms.encode())
.unwrap(),
tap_ms
);
assert_eq!(tap_ms.script_size(), 104);
Expand Down
8 changes: 2 additions & 6 deletions src/policy/compiler.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1164,8 +1164,7 @@ where
best_compilations(policy_cache, policy, sat_prob, dissat_prob)?
.into_iter()
.filter(|&(key, _)| {
key.ty.corr.base == types::Base::B
&& key.dissat_prob == dissat_prob.map(OrdF64)
key.ty.corr.base == types::Base::B && key.dissat_prob == dissat_prob.map(OrdF64)
})
.map(|(_, val)| val)
.min_by_key(|ext| OrdF64(ext.cost_1d(sat_prob, dissat_prob)))
Expand Down Expand Up @@ -1417,10 +1416,7 @@ mod tests {
left_sat.insert(*key, elements_sig);
}
for key in keys.iter().skip(5) {
right_sat.insert(
key.to_pubkeyhash(SigType::Ecdsa),
(*key, elements_sig),
);
right_sat.insert(key.to_pubkeyhash(SigType::Ecdsa), (*key, elements_sig));
}

assert!(ms.satisfy(no_sat).is_err());
Expand Down
4 changes: 1 addition & 3 deletions src/policy/concrete.rs
Original file line number Diff line number Diff line change
Expand Up @@ -888,9 +888,7 @@ impl<Pk: MiniscriptKey> Policy<Pk> {
TimelockInfo::combine_threshold(subs.len(), iter)
}
Policy::Or(ref subs) => {
let iter = subs
.iter()
.map(|(_p, sub)| sub.check_timelocks_helper());
let iter = subs.iter().map(|(_p, sub)| sub.check_timelocks_helper());
TimelockInfo::combine_threshold(1, iter)
}
}
Expand Down
Loading

0 comments on commit e5d4593

Please sign in to comment.