run cargo clippy and fmt

This commit is contained in:
Andrew Poelstra 2022-10-19 16:51:41 +00:00
parent f2a5596899
commit 1b15a13e5a
No known key found for this signature in database
GPG Key ID: C588D63CE41B97C1
8 changed files with 63 additions and 32 deletions

View File

@ -144,7 +144,10 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
ExtendedPrivKey::from_str(BENEFACTOR_XPRIV_STR)?, ExtendedPrivKey::from_str(BENEFACTOR_XPRIV_STR)?,
beneficiary.master_xpub(), beneficiary.master_xpub(),
)?; )?;
let (tx, psbt) = benefactor.create_inheritance_funding_tx(absolute::LockTime::from_height(1000).unwrap(), UTXO_2)?; let (tx, psbt) = benefactor.create_inheritance_funding_tx(
absolute::LockTime::from_height(1000).unwrap(),
UTXO_2,
)?;
let tx_hex = encode::serialize_hex(&tx); let tx_hex = encode::serialize_hex(&tx);
println!("Inheritance funding tx hex:\n\n{}", tx_hex); println!("Inheritance funding tx hex:\n\n{}", tx_hex);
@ -154,7 +157,11 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
// And mine a block to confirm the transaction: // And mine a block to confirm the transaction:
// bt generatetoaddress 1 $(bt-benefactor getnewaddress '' 'bech32m') // bt generatetoaddress 1 $(bt-benefactor getnewaddress '' 'bech32m')
let spending_tx = beneficiary.spend_inheritance(psbt, absolute::LockTime::from_height(1000).unwrap(), to_address)?; let spending_tx = beneficiary.spend_inheritance(
psbt,
absolute::LockTime::from_height(1000).unwrap(),
to_address,
)?;
let spending_tx_hex = encode::serialize_hex(&spending_tx); let spending_tx_hex = encode::serialize_hex(&spending_tx);
println!("\nInheritance spending tx hex:\n\n{}", spending_tx_hex); println!("\nInheritance spending tx hex:\n\n{}", spending_tx_hex);
// If you try to broadcast now, the transaction will be rejected as it is timelocked. // If you try to broadcast now, the transaction will be rejected as it is timelocked.
@ -176,7 +183,10 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
ExtendedPrivKey::from_str(BENEFACTOR_XPRIV_STR)?, ExtendedPrivKey::from_str(BENEFACTOR_XPRIV_STR)?,
beneficiary.master_xpub(), beneficiary.master_xpub(),
)?; )?;
let (tx, _) = benefactor.create_inheritance_funding_tx(absolute::LockTime::from_height(2000).unwrap(), UTXO_3)?; let (tx, _) = benefactor.create_inheritance_funding_tx(
absolute::LockTime::from_height(2000).unwrap(),
UTXO_3,
)?;
let tx_hex = encode::serialize_hex(&tx); let tx_hex = encode::serialize_hex(&tx);
println!("Inheritance funding tx hex:\n\n{}", tx_hex); println!("Inheritance funding tx hex:\n\n{}", tx_hex);
@ -482,7 +492,10 @@ impl BenefactorWallet {
self.beneficiary_xpub.derive_pub(&self.secp, &new_derivation_path)?.to_x_only_pub(); self.beneficiary_xpub.derive_pub(&self.secp, &new_derivation_path)?.to_x_only_pub();
// Build up the leaf script and combine with internal key into a taproot commitment // Build up the leaf script and combine with internal key into a taproot commitment
let lock_time = absolute::LockTime::from_height(psbt.unsigned_tx.lock_time.to_consensus_u32() + lock_time_delta).unwrap(); let lock_time = absolute::LockTime::from_height(
psbt.unsigned_tx.lock_time.to_consensus_u32() + lock_time_delta,
)
.unwrap();
let script = Self::time_lock_script(lock_time, beneficiary_key); let script = Self::time_lock_script(lock_time, beneficiary_key);
let leaf_hash = TapLeafHash::from_script(&script, LeafVersion::TapScript); let leaf_hash = TapLeafHash::from_script(&script, LeafVersion::TapScript);

View File

@ -1470,8 +1470,14 @@ mod verification {
let n2 = kani::any::<i64>(); let n2 = kani::any::<i64>();
kani::assume(n1.checked_add(n2).is_some()); // assume we don't overflow in the actual test kani::assume(n1.checked_add(n2).is_some()); // assume we don't overflow in the actual test
kani::assume(n1.checked_sub(n2).is_some()); // assume we don't overflow in the actual test kani::assume(n1.checked_sub(n2).is_some()); // assume we don't overflow in the actual test
assert_eq!(SignedAmount::from_sat(n1) + SignedAmount::from_sat(n2), SignedAmount::from_sat(n1 + n2)); assert_eq!(
assert_eq!(SignedAmount::from_sat(n1) - SignedAmount::from_sat(n2), SignedAmount::from_sat(n1 - n2)); SignedAmount::from_sat(n1) + SignedAmount::from_sat(n2),
SignedAmount::from_sat(n1 + n2)
);
assert_eq!(
SignedAmount::from_sat(n1) - SignedAmount::from_sat(n2),
SignedAmount::from_sat(n1 - n2)
);
let mut amt = SignedAmount::from_sat(n1); let mut amt = SignedAmount::from_sat(n1);
amt += SignedAmount::from_sat(n2); amt += SignedAmount::from_sat(n2);
@ -1506,7 +1512,11 @@ mod verification {
assert_eq!( assert_eq!(
SignedAmount::from_sat(n1).positive_sub(SignedAmount::from_sat(n2)), SignedAmount::from_sat(n1).positive_sub(SignedAmount::from_sat(n2)),
if n1 >= 0 && n2 >= 0 && n1 >= n2 { Some(SignedAmount::from_sat(n1 - n2)) } else { None }, if n1 >= 0 && n2 >= 0 && n1 >= n2 {
Some(SignedAmount::from_sat(n1 - n2))
} else {
None
},
); );
} }
} }

View File

@ -384,7 +384,7 @@ mod test {
fn dummy_tx(nonce: &[u8]) -> Transaction { fn dummy_tx(nonce: &[u8]) -> Transaction {
Transaction { Transaction {
version: 1, version: 1,
lock_time: absolute::LockTime::from_consensus(2).into(), lock_time: absolute::LockTime::from_consensus(2),
input: vec![TxIn { input: vec![TxIn {
previous_output: OutPoint::new(Txid::hash(nonce), 0), previous_output: OutPoint::new(Txid::hash(nonce), 0),
script_sig: Script::new(), script_sig: Script::new(),

View File

@ -601,7 +601,7 @@ pub struct Transaction {
impl cmp::PartialOrd for Transaction { impl cmp::PartialOrd for Transaction {
fn partial_cmp(&self, other: &Self) -> Option<cmp::Ordering> { fn partial_cmp(&self, other: &Self) -> Option<cmp::Ordering> {
Some(self.cmp(&other)) Some(self.cmp(other))
} }
} }
impl cmp::Ord for Transaction { impl cmp::Ord for Transaction {
@ -910,7 +910,7 @@ impl Transaction {
if !self.is_lock_time_enabled() { if !self.is_lock_time_enabled() {
return true; return true;
} }
absolute::LockTime::from(self.lock_time).is_satisfied_by(height, time) self.lock_time.is_satisfied_by(height, time)
} }
/// Returns `true` if this transactions nLockTime is enabled ([BIP-65]). /// Returns `true` if this transactions nLockTime is enabled ([BIP-65]).

View File

@ -111,20 +111,18 @@ pub mod string;
pub mod taproot; pub mod taproot;
pub mod util; pub mod util;
#[cfg(feature = "std")]
use std::io;
#[cfg(not(feature = "std"))]
use core2::io;
// May depend on crate features and we don't want to bother with it // May depend on crate features and we don't want to bother with it
#[allow(unused)] #[allow(unused)]
#[cfg(feature = "std")] #[cfg(feature = "std")]
use std::error::Error as StdError; use std::error::Error as StdError;
#[cfg(feature = "std")]
use std::io;
#[allow(unused)] #[allow(unused)]
#[cfg(not(feature = "std"))] #[cfg(not(feature = "std"))]
use core2::error::Error as StdError; use core2::error::Error as StdError;
#[cfg(not(feature = "std"))]
use core2::io;
pub use crate::address::{Address, AddressType}; pub use crate::address::{Address, AddressType};
pub use crate::amount::{Amount, Denomination, SignedAmount}; pub use crate::amount::{Amount, Denomination, SignedAmount};

View File

@ -133,11 +133,11 @@ impl Network {
use Network::*; use Network::*;
let network = match core_arg { let network = match core_arg {
"main" => Bitcoin, "main" => Bitcoin,
"test" => Testnet, "test" => Testnet,
"signet" => Signet, "signet" => Signet,
"regtest" => Regtest, "regtest" => Regtest,
_ => return Err(ParseNetworkError(core_arg.to_owned())), _ => return Err(ParseNetworkError(core_arg.to_owned())),
}; };
Ok(network) Ok(network)
} }

View File

@ -1379,18 +1379,26 @@ mod tests {
#[cfg(feature = "serde")] #[cfg(feature = "serde")]
#[test] #[test]
fn bip_341_sighash_tests() { fn bip_341_sighash_tests() {
fn sighash_deser_numeric<'de, D>(deserializer: D) -> Result<SchnorrSighashType, D::Error> where D: actual_serde::Deserializer<'de> { fn sighash_deser_numeric<'de, D>(deserializer: D) -> Result<SchnorrSighashType, D::Error>
where
D: actual_serde::Deserializer<'de>,
{
use actual_serde::de::{Deserialize, Error, Unexpected}; use actual_serde::de::{Deserialize, Error, Unexpected};
let raw = u8::deserialize(deserializer)?; let raw = u8::deserialize(deserializer)?;
SchnorrSighashType::from_consensus_u8(raw) SchnorrSighashType::from_consensus_u8(raw).map_err(|_| {
.map_err(|_| D::Error::invalid_value(Unexpected::Unsigned(raw.into()), &"number in range 0-3 or 0x81-0x83")) D::Error::invalid_value(
Unexpected::Unsigned(raw.into()),
&"number in range 0-3 or 0x81-0x83",
)
})
} }
use crate::hashes::hex::ToHex;
use crate::taproot::{TapTweakHash, TapBranchHash};
use secp256k1::{self, SecretKey, XOnlyPublicKey}; use secp256k1::{self, SecretKey, XOnlyPublicKey};
use crate::consensus::serde as con_serde; use crate::consensus::serde as con_serde;
use crate::hashes::hex::ToHex;
use crate::taproot::{TapBranchHash, TapTweakHash};
#[derive(serde::Deserialize)] #[derive(serde::Deserialize)]
#[serde(crate = "actual_serde")] #[serde(crate = "actual_serde")]
@ -1480,14 +1488,18 @@ mod tests {
} }
let json_str = include_str!("../tests/data/bip341_tests.json"); let json_str = include_str!("../tests/data/bip341_tests.json");
let mut data = serde_json::from_str::<TestData>(json_str).expect("JSON was not well-formatted"); let mut data =
serde_json::from_str::<TestData>(json_str).expect("JSON was not well-formatted");
assert_eq!(data.version, 1u64); assert_eq!(data.version, 1u64);
let secp = &secp256k1::Secp256k1::new(); let secp = &secp256k1::Secp256k1::new();
let key_path = data.key_path_spending.remove(0); let key_path = data.key_path_spending.remove(0);
let raw_unsigned_tx = key_path.given.raw_unsigned_tx; let raw_unsigned_tx = key_path.given.raw_unsigned_tx;
let utxos = key_path.given.utxos_spent.into_iter() let utxos = key_path
.given
.utxos_spent
.into_iter()
.map(|txo| TxOut { value: txo.value, script_pubkey: txo.script_pubkey }) .map(|txo| TxOut { value: txo.value, script_pubkey: txo.script_pubkey })
.collect::<Vec<_>>(); .collect::<Vec<_>>();

View File

@ -215,9 +215,7 @@ impl<T: AsOutBytes> BufEncoder<T> {
/// ///
/// Note that this returns the number of bytes before encoding, not number of hex digits. /// Note that this returns the number of bytes before encoding, not number of hex digits.
#[inline] #[inline]
pub fn space_remaining(&self) -> usize { pub fn space_remaining(&self) -> usize { (self.buf.as_out_bytes().len() - self.pos) / 2 }
(self.buf.as_out_bytes().len() - self.pos) / 2
}
} }
#[cfg(test)] #[cfg(test)]