Skip to content

Commit

Permalink
Merge pull request #123 from h4sh3d/fix-clippy-warns
Browse files Browse the repository at this point in the history
Fix clippy warnings
  • Loading branch information
h4sh3d authored Aug 24, 2021
2 parents e849aa2 + 685a5e9 commit 6e8b24b
Show file tree
Hide file tree
Showing 17 changed files with 176 additions and 179 deletions.
4 changes: 2 additions & 2 deletions .github/workflows/analysis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ env:

jobs:

format:
fmt:

runs-on: ubuntu-latest

Expand All @@ -29,4 +29,4 @@ jobs:
- uses: actions/checkout@v2

- name: Run Clippy
run: cargo clippy --workspace --all-targets
run: cargo clippy --workspace --all-targets -- -D warnings
6 changes: 2 additions & 4 deletions src/bitcoin/address.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,7 @@ impl CanonicalBytes for Address {
where
Self: Sized,
{
Ok(
Address::from_str(str::from_utf8(bytes).map_err(consensus::Error::new)?)
.map_err(consensus::Error::new)?,
)
Address::from_str(str::from_utf8(bytes).map_err(consensus::Error::new)?)
.map_err(consensus::Error::new)
}
}
16 changes: 8 additions & 8 deletions src/bitcoin/fee.rs
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ impl FromStr for SatPerVByte {
type Err = consensus::Error;

fn from_str(s: &str) -> Result<Self, Self::Err> {
let parts = s.split("/").collect::<Vec<&str>>();
let parts = s.split('/').collect::<Vec<&str>>();
if parts.len() != 2 {
return Err(consensus::Error::ParseFailed(
"SatPerVByte format is not respected",
Expand All @@ -95,7 +95,7 @@ impl FromStr for SatPerVByte {
let amount = parts[0].parse::<Amount>().map_err(consensus::Error::new)?;
match parts[1] {
"vByte" => Ok(Self(amount)),
_ => Err(consensus::Error::ParseFailed("SatPerVByte parse failed"))?,
_ => Err(consensus::Error::ParseFailed("SatPerVByte parse failed")),
}
}
}
Expand Down Expand Up @@ -132,7 +132,7 @@ impl<S: Strategy> Fee for Bitcoin<S> {
));
}

let input_sum = get_available_input_sat(&tx)?;
let input_sum = get_available_input_sat(tx)?;

// FIXME This does not account for witnesses
// currently the fees are wrong
Expand All @@ -147,12 +147,12 @@ impl<S: Strategy> Fee for Bitcoin<S> {
FeePriority::High => range.end.as_native_unit().checked_mul(weight),
},
}
.ok_or_else(|| FeeStrategyError::AmountOfFeeTooHigh)?;
.ok_or(FeeStrategyError::AmountOfFeeTooHigh)?;

// Apply the fee on the first output
tx.global.unsigned_tx.output[0].value = input_sum
.checked_sub(fee_amount)
.ok_or_else(|| FeeStrategyError::NotEnoughAssets)?
.ok_or(FeeStrategyError::NotEnoughAssets)?
.as_sat();

// Return the fee amount set in native blockchain asset unit
Expand All @@ -170,11 +170,11 @@ impl<S: Strategy> Fee for Bitcoin<S> {
));
}

let input_sum = get_available_input_sat(&tx)?.as_sat();
let input_sum = get_available_input_sat(tx)?.as_sat();
let output_sum = tx.global.unsigned_tx.output[0].value;
let fee = input_sum
.checked_sub(output_sum)
.ok_or_else(|| FeeStrategyError::AmountOfFeeTooHigh)?;
.ok_or(FeeStrategyError::AmountOfFeeTooHigh)?;
let weight = tx.global.unsigned_tx.get_weight() as u64;

let effective_sat_per_vbyte = SatPerVByte::from_sat(
Expand Down Expand Up @@ -217,6 +217,6 @@ mod tests {
#[test]
fn display_sats_per_vbyte() {
let fee_rate = SatPerVByte::from_sat(100);
assert_eq!(format!("{}", fee_rate), format!("100 satoshi/vByte"));
assert_eq!(format!("{}", fee_rate), "100 satoshi/vByte".to_string());
}
}
6 changes: 6 additions & 0 deletions src/bitcoin/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,12 @@ impl<S: Strategy> Bitcoin<S> {
}
}

impl<S: Strategy> Default for Bitcoin<S> {
fn default() -> Self {
Self::new()
}
}

impl<S: Strategy> Asset for Bitcoin<S> {
/// Type for quantifying the traded asset.
type AssetUnit = Amount;
Expand Down
15 changes: 6 additions & 9 deletions src/bitcoin/segwitv0/funding.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,9 +25,9 @@ impl Linkable<MetadataOutput> for Funding {
fn get_consumable_output(&self) -> Result<MetadataOutput, FError> {
// Create a **COMPRESSED** ECDSA public key.
let pubkey = match self.pubkey {
Some(pubkey) => Ok(bitcoin::util::ecdsa::PublicKey::new(pubkey)),
None => Err(FError::MissingPublicKey),
}?;
Some(pubkey) => bitcoin::util::ecdsa::PublicKey::new(pubkey),
None => return Err(FError::MissingPublicKey),
};

let (script_pubkey, network) = match self.network {
Some(Network::Mainnet) => (
Expand All @@ -42,7 +42,7 @@ impl Linkable<MetadataOutput> for Funding {
Address::p2wpkh(&pubkey, BtcNetwork::Regtest),
BtcNetwork::Regtest,
),
None => Err(FError::MissingNetwork)?,
None => return Err(FError::MissingNetwork),
};

// Safety: we can unwrap here as `Address::p2wpkh` only returns an error when
Expand All @@ -61,7 +61,7 @@ impl Linkable<MetadataOutput> for Funding {
tx_out: tx_out.clone(),
script_pubkey: Some(Address::p2pkh(&pubkey, network).script_pubkey()),
})
.ok_or_else(|| FError::MissingUTXO),
.ok_or(FError::MissingUTXO),
// The transaction has not been see yet, cannot infer the UTXO
None => Err(FError::MissingOnchainTransaction),
}
Expand Down Expand Up @@ -111,9 +111,6 @@ impl Fundable<Bitcoin<SegwitV0>, MetadataOutput> for Funding {
}

fn was_seen(&self) -> bool {
match self.seen_tx {
Some(_) => true,
None => false,
}
self.seen_tx.is_some()
}
}
17 changes: 8 additions & 9 deletions src/bitcoin/segwitv0/lock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -55,9 +55,8 @@ impl Lockable<Bitcoin<SegwitV0>, MetadataOutput> for Tx<Lock> {

let output_metadata = prev.get_consumable_output()?;

match output_metadata.tx_out.value < target_amount.as_sat() {
true => Err(FError::NotEnoughAssets)?,
false => (),
if output_metadata.tx_out.value < target_amount.as_sat() {
return Err(FError::NotEnoughAssets);
}

let unsigned_tx = bitcoin::blockdata::transaction::Transaction {
Expand Down Expand Up @@ -99,21 +98,21 @@ impl Lockable<Bitcoin<SegwitV0>, MetadataOutput> for Tx<Lock> {
fn verify_template(&self, lock: script::DataLock<Bitcoin<SegwitV0>>) -> Result<(), FError> {
(self.psbt.global.unsigned_tx.version == 2)
.then(|| 0)
.ok_or_else(|| FError::WrongTemplate)?;
.ok_or(FError::WrongTemplate)?;
(self.psbt.global.unsigned_tx.lock_time == 0)
.then(|| 0)
.ok_or_else(|| FError::WrongTemplate)?;
.ok_or(FError::WrongTemplate)?;
(self.psbt.global.unsigned_tx.input.len() == 1)
.then(|| 0)
.ok_or_else(|| FError::WrongTemplate)?;
.ok_or(FError::WrongTemplate)?;
(self.psbt.global.unsigned_tx.output.len() == 1)
.then(|| 0)
.ok_or_else(|| FError::WrongTemplate)?;
.ok_or(FError::WrongTemplate)?;

let txin = &self.psbt.global.unsigned_tx.input[0];
(txin.sequence == (1 << 31) as u32)
.then(|| 0)
.ok_or_else(|| FError::WrongTemplate)?;
.ok_or(FError::WrongTemplate)?;

let txout = &self.psbt.global.unsigned_tx.output[0];
let script = Builder::new()
Expand All @@ -136,7 +135,7 @@ impl Lockable<Bitcoin<SegwitV0>, MetadataOutput> for Tx<Lock> {
.into_script();
(txout.script_pubkey == script.to_v0_p2wsh())
.then(|| 0)
.ok_or_else(|| FError::WrongTemplate)?;
.ok_or(FError::WrongTemplate)?;

Ok(())
}
Expand Down
10 changes: 5 additions & 5 deletions src/bitcoin/segwitv0/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -136,16 +136,16 @@ impl CanonicalBytes for EncryptedSignature {
where
Self: Sized,
{
bincode::deserialize::<EncryptedSignature>(&bytes).map_err(consensus::Error::new)
bincode::deserialize::<EncryptedSignature>(bytes).map_err(consensus::Error::new)
}
}

/// Computes the [`BIP-143`][bip-143] compliant sighash for a `SIGHASH_ALL` signature for the given
/// input.
///
/// [bip-143]: https://github.com/bitcoin/bips/blob/master/bip-0143.mediawiki
pub fn signature_hash<'a>(
txin: TxInRef<'a>,
pub fn signature_hash(
txin: TxInRef,
script: &Script,
value: u64,
sighash_type: SigHashType,
Expand All @@ -158,9 +158,9 @@ pub fn signature_hash<'a>(
/// Computes the [`BIP-143`][bip-143] compliant signature for the given input.
///
/// [bip-143]: https://github.com/bitcoin/bips/blob/master/bip-0143.mediawiki
pub fn sign_input<'a, C>(
pub fn sign_input<C>(
context: &mut Secp256k1<C>,
txin: TxInRef<'a>,
txin: TxInRef,
script: &Script,
value: u64,
sighash_type: SigHashType,
Expand Down
8 changes: 3 additions & 5 deletions src/bitcoin/transaction.rs
Original file line number Diff line number Diff line change
Expand Up @@ -110,9 +110,7 @@ where

fn based_on(&self) -> MetadataOutput {
MetadataOutput {
out_point: self.psbt.global.unsigned_tx.input[0]
.previous_output
.clone(),
out_point: self.psbt.global.unsigned_tx.input[0].previous_output,
tx_out: self.psbt.inputs[0].witness_utxo.clone().unwrap(), // FIXME
script_pubkey: self.psbt.inputs[0].witness_script.clone(),
}
Expand Down Expand Up @@ -189,15 +187,15 @@ where

let sighash_type = self.psbt.inputs[0]
.sighash_type
.ok_or(FError::new(Error::MissingSigHashType))?;
.ok_or_else(|| FError::new(Error::MissingSigHashType))?;

Ok(signature_hash(txin, &script, value, sighash_type))
}

fn add_witness(&mut self, pubkey: PublicKey, sig: Signature) -> Result<(), FError> {
let sighash_type = self.psbt.inputs[0]
.sighash_type
.ok_or(FError::new(Error::MissingSigHashType))?;
.ok_or_else(|| FError::new(Error::MissingSigHashType))?;
let mut full_sig = sig.serialize_der().to_vec();
full_sig.extend_from_slice(&[sighash_type.as_u32() as u8]);
let pubkey = bitcoin::util::ecdsa::PublicKey::new(pubkey);
Expand Down
7 changes: 5 additions & 2 deletions src/blockchain.rs
Original file line number Diff line number Diff line change
Expand Up @@ -352,11 +352,14 @@ mod tests {
#[test]
fn display_fee_strategy() {
let strategy = FeeStrategy::Fixed(SatPerVByte::from_sat(100));
assert_eq!(format!("{}", strategy), format!("Fixed: 100 satoshi/vByte"));
assert_eq!(
format!("{}", strategy),
"Fixed: 100 satoshi/vByte".to_string()
);
let strategy = FeeStrategy::Range(SatPerVByte::from_sat(50)..SatPerVByte::from_sat(150));
assert_eq!(
format!("{}", strategy),
format!("Range: from 50 satoshi/vByte to 150 satoshi/vByte")
"Range: from 50 satoshi/vByte to 150 satoshi/vByte".to_string()
)
}
}
9 changes: 9 additions & 0 deletions src/crypto.rs
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,15 @@ where
}
}

/// A vector of `T` tagged elements `E`.
pub type TaggedElements<T, E> = Vec<TaggedElement<T, E>>;

/// A vector of [`u16`] tagged keys of type `E`.
pub type TaggedExtraKeys<E> = Vec<TaggedElement<u16, E>>;

/// A vector of shared keys tagged with [`SharedKeyId`] of type `E`.
pub type TaggedSharedKeys<E> = Vec<TaggedElement<SharedKeyId, E>>;

/// List of all possible arbitrating keys as defined for the base protocol in the RFCs. Extra keys
/// can be defined with [`Self::Extra`] variant and an `u16` identifier. Those keys can be used for
/// extra off-chain protocol such as multi-signature or multi-party computation schemes.
Expand Down
4 changes: 4 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -104,3 +104,7 @@ pub enum Error {
#[error("Syncer error: {0}")]
Syncer(#[from] syncer::Error),
}

/// Result of an high level computation such as in Alice and Bob roles executing the protocol,
/// wraps the crate level [`enum@Error`] type.
pub type Res<T> = Result<T, Error>;
16 changes: 8 additions & 8 deletions src/protocol_message.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ use crate::blockchain::{Address, Onchain};
use crate::bundle;
use crate::consensus::{self, CanonicalBytes, Decodable, Encodable};
use crate::crypto::{
self, Commit, Keys, SharedKeyId, SharedPrivateKeys, Signatures, TaggedElement,
self, Commit, Keys, SharedKeyId, SharedPrivateKeys, Signatures, TaggedElement, TaggedElements,
};
use crate::swap::{Swap, SwapId};
use crate::Error;
Expand All @@ -16,9 +16,9 @@ use lightning_encoding::{strategies::AsStrict, Strategy};

fn commit_to_vec<T: Clone + Eq, K: CanonicalBytes, C: Clone + Eq>(
wallet: &impl Commit<C>,
keys: &Vec<TaggedElement<T, K>>,
) -> Vec<TaggedElement<T, C>> {
keys.into_iter()
keys: &[TaggedElement<T, K>],
) -> TaggedElements<T, C> {
keys.iter()
.map(|tagged_key| {
TaggedElement::new(
tagged_key.tag().clone(),
Expand All @@ -31,7 +31,7 @@ fn commit_to_vec<T: Clone + Eq, K: CanonicalBytes, C: Clone + Eq>(
fn verify_vec_of_commitments<T: Eq, K: CanonicalBytes, C: Clone + Eq>(
wallet: &impl Commit<C>,
keys: Vec<TaggedElement<T, K>>,
commitments: &Vec<TaggedElement<T, C>>,
commitments: &[TaggedElement<T, C>],
) -> Result<(), Error> {
keys.into_iter()
.map(|tagged_key| {
Expand All @@ -44,7 +44,7 @@ fn verify_vec_of_commitments<T: Eq, K: CanonicalBytes, C: Clone + Eq>(
tagged_key.elem().as_canonical_bytes(),
tagged_commitment.elem().clone(),
)
.map_err(|e| Error::Crypto(e))
.map_err(Error::Crypto)
})
.ok_or(Error::Crypto(crypto::Error::InvalidCommitment))
})
Expand Down Expand Up @@ -728,7 +728,7 @@ where
Self {
swap_id: bundles.0,
cancel_sig: bundles.1.cancel_sig.clone(),
refund_adaptor_sig: bundles.2.refund_adaptor_sig.clone(),
refund_adaptor_sig: bundles.2.refund_adaptor_sig,
}
}
}
Expand Down Expand Up @@ -799,7 +799,7 @@ where
Self {
swap_id: bundle.0,
buy: bundle.1.buy.clone(),
buy_adaptor_sig: bundle.1.buy_adaptor_sig.clone(),
buy_adaptor_sig: bundle.1.buy_adaptor_sig,
}
}
}
Expand Down
Loading

0 comments on commit 6e8b24b

Please sign in to comment.