From 2df1977a384b644c1adeae9d7f0e33ee085da619 Mon Sep 17 00:00:00 2001 From: Lucas Soriano del Pino Date: Thu, 4 Apr 2024 10:59:02 +1100 Subject: [PATCH] Format code base using rustfmt --- bitcoin-rpc-provider/src/lib.rs | 12 +- dlc-manager/src/channel/accepted_channel.rs | 4 +- dlc-manager/src/channel/mod.rs | 6 +- dlc-manager/src/channel/offered_channel.rs | 15 +- dlc-manager/src/channel/ser.rs | 5 +- dlc-manager/src/channel_updater.rs | 110 +++++---- dlc-manager/src/manager.rs | 221 +++++++++++------- dlc-manager/src/sub_channel_manager.rs | 25 +- dlc-manager/src/utils.rs | 5 +- dlc-manager/tests/channel_execution_tests.rs | 71 ++++-- .../tests/ln_dlc_channel_execution_tests.rs | 7 +- dlc-messages/src/channel.rs | 28 +-- dlc-messages/src/lib.rs | 6 +- dlc-messages/src/oracle_msgs.rs | 4 +- dlc-sled-storage-provider/src/lib.rs | 15 +- dlc-trie/src/multi_oracle_trie.rs | 4 +- dlc-trie/src/utils.rs | 4 +- dlc/src/channel/mod.rs | 9 +- dlc/src/channel/sub_channel.rs | 14 +- dlc/src/lib.rs | 55 +++-- dlc/src/util.rs | 5 +- mocks/src/memory_storage_provider.rs | 3 +- rustfmt.toml | 2 + simple-wallet/src/lib.rs | 5 +- 24 files changed, 394 insertions(+), 241 deletions(-) create mode 100644 rustfmt.toml diff --git a/bitcoin-rpc-provider/src/lib.rs b/bitcoin-rpc-provider/src/lib.rs index 80ee4e33..919f6174 100644 --- a/bitcoin-rpc-provider/src/lib.rs +++ b/bitcoin-rpc-provider/src/lib.rs @@ -297,9 +297,17 @@ impl Wallet for BitcoinCoreProvider { } fn unreserve_utxos(&self, outpoints: &[OutPoint]) -> Result<(), ManagerError> { - match self.client.lock().unwrap().unlock_unspent(outpoints).map_err(rpc_err_to_manager_err)? { + match self + .client + .lock() + .unwrap() + .unlock_unspent(outpoints) + .map_err(rpc_err_to_manager_err)? + { true => Ok(()), - false => Err(ManagerError::StorageError(format!("Failed to unlock utxos: {outpoints:?}"))) + false => Err(ManagerError::StorageError(format!( + "Failed to unlock utxos: {outpoints:?}" + ))), } } } diff --git a/dlc-manager/src/channel/accepted_channel.rs b/dlc-manager/src/channel/accepted_channel.rs index 995846bd..f2698be2 100644 --- a/dlc-manager/src/channel/accepted_channel.rs +++ b/dlc-manager/src/channel/accepted_channel.rs @@ -39,7 +39,7 @@ pub struct AcceptedChannel { /// The accept party adaptor signature for the buffer transaction. pub accept_buffer_adaptor_signature: EcdsaAdaptorSignature, /// The reference id set by the api user. - pub reference_id: Option + pub reference_id: Option, } impl AcceptedChannel { @@ -67,7 +67,7 @@ impl AcceptedChannel { own_basepoint: self.accept_base_points.own_basepoint, first_per_update_point: self.accept_per_update_point, buffer_adaptor_signature: *buffer_adaptor_signature, - reference_id + reference_id, } } } diff --git a/dlc-manager/src/channel/mod.rs b/dlc-manager/src/channel/mod.rs index 947b02ed..14e919a4 100644 --- a/dlc-manager/src/channel/mod.rs +++ b/dlc-manager/src/channel/mod.rs @@ -73,7 +73,7 @@ impl std::fmt::Debug for Channel { Channel::CounterClosed(_) => "counter closed", Channel::ClosedPunished(_) => "closed punished", Channel::CollaborativelyClosed(_) => "collaboratively closed", - Channel::Cancelled(_) => "cancelled" + Channel::Cancelled(_) => "cancelled", }; f.debug_struct("Channel").field("state", &state).finish() } @@ -94,7 +94,7 @@ impl Channel { c.counter_party } Channel::ClosedPunished(c) => c.counter_party, - Channel::Cancelled(o) => o.counter_party + Channel::Cancelled(o) => o.counter_party, } } @@ -112,7 +112,7 @@ impl Channel { c.reference_id } Channel::ClosedPunished(c) => c.reference_id, - Channel::Cancelled(o) => o.reference_id + Channel::Cancelled(o) => o.reference_id, } } } diff --git a/dlc-manager/src/channel/offered_channel.rs b/dlc-manager/src/channel/offered_channel.rs index e9b93e7f..b2c56a63 100644 --- a/dlc-manager/src/channel/offered_channel.rs +++ b/dlc-manager/src/channel/offered_channel.rs @@ -6,7 +6,10 @@ use dlc_messages::channel::OfferChannel; // use dlc_messages::channel::OfferChannel; use secp256k1_zkp::PublicKey; -use crate::{contract::offered_contract::OfferedContract, conversion_utils::get_tx_input_infos, error::Error, ContractId, DlcChannelId, ReferenceId}; +use crate::{ + contract::offered_contract::OfferedContract, conversion_utils::get_tx_input_infos, + error::Error, ContractId, DlcChannelId, ReferenceId, +}; use super::party_points::PartyBasePoints; @@ -39,11 +42,15 @@ pub struct OfferedChannel { /// The nSequence value to use for the CETs. pub cet_nsequence: u32, /// The reference id set by the api user. - pub reference_id: Option + pub reference_id: Option, } impl OfferedChannel { - pub(crate) fn get_offer_channel_msg(&self, offered_contract: &OfferedContract, reference_id: Option) -> OfferChannel { + pub(crate) fn get_offer_channel_msg( + &self, + offered_contract: &OfferedContract, + reference_id: Option, + ) -> OfferChannel { let party_points = &self.party_points; OfferChannel { protocol_version: crate::conversion_utils::PROTOCOL_VERSION, @@ -72,7 +79,7 @@ impl OfferedChannel { fee_rate_per_vb: offered_contract.fee_rate_per_vb, fund_output_serial_id: offered_contract.fund_output_serial_id, cet_nsequence: crate::manager::CET_NSEQUENCE, - reference_id + reference_id, } } diff --git a/dlc-manager/src/channel/ser.rs b/dlc-manager/src/channel/ser.rs index c0746537..0ba416f6 100644 --- a/dlc-manager/src/channel/ser.rs +++ b/dlc-manager/src/channel/ser.rs @@ -3,7 +3,10 @@ use super::accepted_channel::AcceptedChannel; use super::offered_channel::OfferedChannel; use super::party_points::PartyBasePoints; use super::signed_channel::{SignedChannel, SignedChannelState}; -use super::{ClosedChannel, ClosedPunishedChannel, ClosingChannel, FailedAccept, FailedSign, SettledClosingChannel}; +use super::{ + ClosedChannel, ClosedPunishedChannel, ClosingChannel, FailedAccept, FailedSign, + SettledClosingChannel, +}; use dlc_messages::ser_impls::{ read_ecdsa_adaptor_signature, read_string, write_ecdsa_adaptor_signature, write_string, diff --git a/dlc-manager/src/channel_updater.rs b/dlc-manager/src/channel_updater.rs index 662ae7e1..fffba071 100644 --- a/dlc-manager/src/channel_updater.rs +++ b/dlc-manager/src/channel_updater.rs @@ -2,23 +2,34 @@ use std::{ops::Deref, sync::Mutex}; -use crate::{chain_monitor::{ChainMonitor, ChannelInfo, TxType}, channel::{ - accepted_channel::AcceptedChannel, - offered_channel::OfferedChannel, - party_points::PartyBasePoints, - signed_channel::{SignedChannel, SignedChannelState}, - Channel, ClosedChannel, SettledClosingChannel, -}, contract::{ - accepted_contract::AcceptedContract, contract_info::ContractInfo, - contract_input::ContractInput, offered_contract::OfferedContract, - signed_contract::SignedContract, AdaptorInfo, -}, contract_updater::{ - accept_contract_internal, verify_accepted_and_sign_contract_internal, - verify_signed_contract_internal, -}, error::Error, subchannel::{ClosingSubChannel, SubChannel}, Blockchain, ContractId, DlcChannelId, Signer, Time, Wallet, ReferenceId, manager::CET_NSEQUENCE}; -use bitcoin::{OutPoint, Script, Sequence, Transaction, Address}; +use crate::{ + chain_monitor::{ChainMonitor, ChannelInfo, TxType}, + channel::{ + accepted_channel::AcceptedChannel, + offered_channel::OfferedChannel, + party_points::PartyBasePoints, + signed_channel::{SignedChannel, SignedChannelState}, + Channel, ClosedChannel, SettledClosingChannel, + }, + contract::{ + accepted_contract::AcceptedContract, contract_info::ContractInfo, + contract_input::ContractInput, offered_contract::OfferedContract, + signed_contract::SignedContract, AdaptorInfo, + }, + contract_updater::{ + accept_contract_internal, verify_accepted_and_sign_contract_internal, + verify_signed_contract_internal, + }, + error::Error, + manager::CET_NSEQUENCE, + subchannel::{ClosingSubChannel, SubChannel}, + Blockchain, ContractId, DlcChannelId, ReferenceId, Signer, Time, Wallet, +}; +use bitcoin::{Address, OutPoint, Script, Sequence, Transaction}; use dlc::{ - channel::{get_tx_adaptor_signature, verify_tx_adaptor_signature, DlcChannelTransactions}, util::dlc_channel_extra_fee, PartyParams + channel::{get_tx_adaptor_signature, verify_tx_adaptor_signature, DlcChannelTransactions}, + util::dlc_channel_extra_fee, + PartyParams, }; use dlc_messages::{ channel::{ @@ -101,7 +112,7 @@ pub fn offer_channel( time: &T, temporary_channel_id: DlcChannelId, is_sub_channel: bool, - reference_id: Option + reference_id: Option, ) -> Result<(OfferedChannel, OfferedContract), Error> where W::Target: Wallet, @@ -155,7 +166,7 @@ where is_offer_party: true, counter_party: *counter_party, cet_nsequence, - reference_id + reference_id, }; Ok((offered_channel, offered_contract)) @@ -204,7 +215,6 @@ where W::Target: Wallet, B::Target: Blockchain, { - assert_eq!(offered_channel.offered_contract_id, offered_contract.id); let (accept_params, funding_inputs, accept_points, per_update_seed) = @@ -221,7 +231,7 @@ where wallet, blockchain, sub_channel_info.is_none(), - extra_fee + extra_fee, )?; let accept_points = crate::utils::get_party_base_points(secp, wallet)?; let per_update_seed = wallet.get_new_secret_key()?; @@ -626,7 +636,7 @@ where .offered_contract .fee_rate_per_vb, sub_channel_id, - reference_id: offered_channel.reference_id + reference_id: offered_channel.reference_id, }; let sign_channel = SignChannel { @@ -635,7 +645,7 @@ where buffer_adaptor_signature: own_buffer_adaptor_signature, refund_signature: signed_contract.offer_refund_signature, funding_signatures: signed_contract.funding_signatures.clone(), - reference_id: offered_channel.reference_id + reference_id: offered_channel.reference_id, }; Ok((signed_channel, signed_contract, sign_channel)) @@ -808,7 +818,7 @@ pub fn settle_channel_offer( peer_timeout: u64, signer: &S, time: &T, - reference_id: Option + reference_id: Option, ) -> Result where S::Target: Signer, @@ -848,7 +858,7 @@ where counter_payout, next_per_update_point, timestamp: get_unix_time_now(), - reference_id + reference_id, }; Ok(settle_channel_offer) @@ -1011,7 +1021,7 @@ where own_settle_adaptor_signature: settle_adaptor_signature, timeout: time.unix_time_now() + peer_timeout, own_payout, - counter_payout + counter_payout, }; let msg = SettleAccept { @@ -1163,7 +1173,7 @@ where channel_id: channel.channel_id, prev_per_update_secret, settle_adaptor_signature, - reference_id: channel.reference_id + reference_id: channel.reference_id, }; Ok(msg) @@ -1217,7 +1227,7 @@ where settle_tx, own_settle_adaptor_signature, *own_payout, - *counter_payout + *counter_payout, ), _ => { return Err(Error::InvalidState( @@ -1276,7 +1286,7 @@ where counter_settle_adaptor_signature: settle_channel_confirm.settle_adaptor_signature, own_settle_adaptor_signature: *own_settle_adaptor_signature, own_payout, - counter_payout + counter_payout, }; channel.own_per_update_point = *own_next_per_update_point; @@ -1310,7 +1320,7 @@ pub fn settle_channel_on_finalize( own_next_per_update_point, own_settle_adaptor_signature, own_payout, - counter_payout + counter_payout, ) = match &channel.state { SignedChannelState::SettledConfirmed { settle_tx, @@ -1360,7 +1370,7 @@ pub fn settle_channel_on_finalize( counter_settle_adaptor_signature, own_settle_adaptor_signature, own_payout, - counter_payout + counter_payout, }; channel.roll_back_state = None; @@ -1374,7 +1384,7 @@ pub fn settle_channel_on_finalize( /// Creates a [`Reject`] message and rolls back the state of the channel. Expects /// the channel to be in [`SignedChannelState::SettledOffered`] state. pub fn reject_settle_offer(signed_channel: &mut SignedChannel) -> Result { - get_signed_channel_state!(signed_channel, SettledReceived, )?; + get_signed_channel_state!(signed_channel, SettledReceived,)?; signed_channel.state = signed_channel .roll_back_state @@ -1384,7 +1394,7 @@ pub fn reject_settle_offer(signed_channel: &mut SignedChannel) -> Result( cet_nsequence: u32, signer: &S, time: &T, - reference_id: Option + reference_id: Option, ) -> Result<(RenewOffer, OfferedContract), Error> where S::Target: Signer, @@ -1492,7 +1502,7 @@ where cet_locktime: offered_contract.cet_locktime, refund_locktime: offered_contract.refund_locktime, cet_nsequence, - reference_id + reference_id, }; Ok((msg, offered_contract)) @@ -1506,7 +1516,8 @@ pub fn on_renew_offer( renew_offer: &RenewOffer, peer_timeout: u64, time: &T, -) -> Result where +) -> Result +where T::Target: Time, { if let SignedChannelState::Settled { .. } | SignedChannelState::Established { .. } = @@ -1905,7 +1916,7 @@ where &accept_per_update_point, own_payout, buffer_transaction, - buffer_script_pubkey + buffer_script_pubkey, ) = get_signed_channel_state!( signed_channel, RenewAccepted, @@ -2013,7 +2024,7 @@ where channel_id: signed_channel.channel_id, per_update_secret: prev_per_update_secret, buffer_adaptor_signature, - reference_id: signed_channel.reference_id + reference_id: signed_channel.reference_id, }; Ok((signed_contract, renew_finalize)) @@ -2036,7 +2047,7 @@ where offer_per_update_point, accept_per_update_point, offer_buffer_adaptor_signature, - buffer_transaction + buffer_transaction, ) = get_signed_channel_state!( signed_channel, RenewConfirmed, @@ -2132,7 +2143,7 @@ pub fn renew_channel_on_revoke( prev_offer_per_update_point, offer_buffer_adaptor_signature, accept_buffer_adaptor_signature, - buffer_transaction + buffer_transaction, ) = get_signed_channel_state!( signed_channel, RenewFinalized, @@ -2193,7 +2204,7 @@ pub fn reject_renew_offer(signed_channel: &mut SignedChannel) -> Result( counter_payout: u64, signer: &S, time: &T, - reference_id: Option + reference_id: Option, ) -> Result<(CollaborativeCloseOffer, Transaction), Error> where S::Target: Signer, @@ -2252,7 +2263,7 @@ where offer_signature: close_signature, close_tx: close_tx.clone(), timeout: time.unix_time_now() + super::manager::PEER_TIMEOUT, - is_offer: true + is_offer: true, }; std::mem::swap(&mut state, &mut signed_channel.state); signed_channel.roll_back_state = Some(state); @@ -2263,7 +2274,7 @@ where channel_id: signed_channel.channel_id, counter_payout, close_signature, - reference_id + reference_id, }, close_tx, )) @@ -2336,7 +2347,8 @@ where let (offer_signature, close_tx, is_offer) = get_signed_channel_state!( signed_channel, CollaborativeCloseOffered, - offer_signature | close_tx, is_offer + offer_signature | close_tx, + is_offer )?; if *is_offer { @@ -2368,7 +2380,7 @@ where temporary_channel_id: signed_channel.temporary_channel_id, channel_id: signed_channel.channel_id, reference_id: signed_channel.reference_id, - closing_txid: close_tx.txid() + closing_txid: close_tx.txid(), }); Ok((close_tx, channel)) } @@ -2491,7 +2503,7 @@ pub fn initiate_unilateral_close_established_channel( signer: &S, sub_channel: Option<(SubChannel, &ClosingSubChannel)>, is_initiator: bool, //TODO(holzeis): Check what this flag is for. It kind of is in conflict with the function name. - reference_id: Option + reference_id: Option, ) -> Result<(), Error> where S::Target: Signer, @@ -2701,7 +2713,7 @@ where temporary_channel_id: signed_channel.temporary_channel_id, channel_id: signed_channel.channel_id, reference_id: signed_channel.reference_id, - closing_txid: cet.txid() + closing_txid: cet.txid(), }; let channel = if is_initiator { Channel::Closed(closed_channel) @@ -2719,7 +2731,7 @@ pub(crate) fn initiate_unilateral_close_settled_channel( sub_channel: Option<(SubChannel, &ClosingSubChannel)>, is_settle_offer: bool, is_initiator: bool, - reference_id: Option + reference_id: Option, ) -> Result<(), Error> where S::Target: Signer, @@ -2821,8 +2833,6 @@ where )?; } - - signed_channel.state = SignedChannelState::SettledClosing { settle_transaction: settle_tx, is_offer: is_settle_offer, diff --git a/dlc-manager/src/manager.rs b/dlc-manager/src/manager.rs index 06a31eb1..cbcebf37 100644 --- a/dlc-manager/src/manager.rs +++ b/dlc-manager/src/manager.rs @@ -5,8 +5,8 @@ use crate::chain_monitor::{ChainMonitor, ChannelInfo, RevokedTxType, TxType}; use crate::channel::offered_channel::OfferedChannel; use crate::channel::signed_channel::{SignedChannel, SignedChannelState, SignedChannelStateType}; use crate::channel::{Channel, ClosedChannel, ClosedPunishedChannel, SettledClosingChannel}; -use crate::channel_updater::{get_unix_time_now, verify_signed_channel}; use crate::channel_updater::{self, get_signed_channel_state}; +use crate::channel_updater::{get_unix_time_now, verify_signed_channel}; use crate::contract::{ accepted_contract::AcceptedContract, contract_info::ContractInfo, contract_input::ContractInput, contract_input::OracleInput, offered_contract::OfferedContract, @@ -20,9 +20,11 @@ use crate::subchannel::{ClosingSubChannel, SubChannel, SubChannelState}; use crate::utils::get_object_in_state; use crate::{ContractId, DlcChannelId, ReferenceId, Signer}; use bitcoin::consensus::encode::serialize_hex; -use bitcoin::{Address, OutPoint, Txid}; -use bitcoin::Transaction; +use bitcoin::consensus::Decodable; use bitcoin::hashes::hex::ToHex; +use bitcoin::hashes::Hash; +use bitcoin::Transaction; +use bitcoin::{Address, OutPoint, Txid}; use dlc_messages::channel::{ AcceptChannel, CollaborativeCloseOffer, OfferChannel, Reject, RenewAccept, RenewConfirm, RenewFinalize, RenewOffer, RenewRevoke, SettleAccept, SettleConfirm, SettleFinalize, @@ -32,7 +34,7 @@ use dlc_messages::oracle_msgs::{OracleAnnouncement, OracleAttestation}; use dlc_messages::{ AcceptDlc, ChannelMessage, Message as DlcMessage, OfferDlc, OnChainMessage, SignDlc, }; -use lightning::chain::chaininterface::{FeeEstimator, ConfirmationTarget}; +use lightning::chain::chaininterface::{ConfirmationTarget, FeeEstimator}; use lightning::ln::chan_utils::{ build_commitment_secret, derive_private_key, derive_private_revocation_key, }; @@ -43,8 +45,6 @@ use std::collections::HashMap; use std::ops::Deref; use std::string::ToString; use std::sync::Mutex; -use bitcoin::consensus::Decodable; -use bitcoin::hashes::Hash; /// The number of confirmations required before moving the the confirmed state. pub const NB_CONFIRMATIONS: u32 = 1; @@ -297,7 +297,7 @@ where Ok(None) } ChannelMessage::Reject(r) => { - self.on_reject(r ,&counter_party)?; + self.on_reject(r, &counter_party)?; Ok(None) } ChannelMessage::RenewRevoke(r) => { @@ -788,7 +788,7 @@ where &self.time, crate::utils::get_new_temporary_id(), false, - reference_id + reference_id, )?; let msg = offered_channel.get_offer_channel_msg(&offered_contract, reference_id); @@ -804,7 +804,8 @@ where /// Reject a channel that was offered. Returns the [`dlc_messages::channel::Reject`] /// message to be sent as well as the public key of the offering node. pub fn reject_channel(&self, channel_id: &DlcChannelId) -> Result<(Reject, PublicKey), Error> { - let offered_channel = get_channel_in_state!(self, channel_id, Offered, None as Option)?; + let offered_channel = + get_channel_in_state!(self, channel_id, Offered, None as Option)?; if offered_channel.is_offer_party { return Err(Error::InvalidState( @@ -812,13 +813,25 @@ where )); } - let offered_contract = get_contract_in_state!(self, &offered_channel.offered_contract_id, Offered, None as Option)?; + let offered_contract = get_contract_in_state!( + self, + &offered_channel.offered_contract_id, + Offered, + None as Option + )?; let reference_id = offered_channel.reference_id; let counterparty = offered_channel.counter_party; - self.store.upsert_channel(Channel::Cancelled(offered_channel), Some(Contract::Rejected(offered_contract)))?; + self.store.upsert_channel( + Channel::Cancelled(offered_channel), + Some(Contract::Rejected(offered_contract)), + )?; - let msg = Reject{ channel_id: *channel_id, timestamp: get_unix_time_now(), reference_id }; + let msg = Reject { + channel_id: *channel_id, + timestamp: get_unix_time_now(), + reference_id, + }; Ok((msg, counterparty)) } @@ -872,7 +885,11 @@ where } /// Force close the channel with given [`DlcChannelId`]. - pub fn force_close_channel(&self, channel_id: &DlcChannelId, reference_id: Option) -> Result<(), Error> { + pub fn force_close_channel( + &self, + channel_id: &DlcChannelId, + reference_id: Option, + ) -> Result<(), Error> { let channel = get_channel_in_state!(self, channel_id, Signed, None as Option)?; self.force_close_channel_internal(channel, None, true, reference_id) @@ -885,7 +902,7 @@ where &self, channel_id: &DlcChannelId, counter_payout: u64, - reference_id: Option + reference_id: Option, ) -> Result<(SettleOffer, PublicKey), Error> { let mut signed_channel = get_channel_in_state!(self, channel_id, Signed, None as Option)?; @@ -960,7 +977,7 @@ where channel_id: &DlcChannelId, counter_payout: u64, contract_input: &ContractInput, - reference_id: Option + reference_id: Option, ) -> Result<(RenewOffer, PublicKey), Error> { let mut signed_channel = get_channel_in_state!(self, channel_id, Signed, None as Option)?; @@ -1097,7 +1114,7 @@ where &self, channel_id: &DlcChannelId, counter_payout: u64, - reference_id: Option + reference_id: Option, ) -> Result { let mut signed_channel = get_channel_in_state!(self, channel_id, Signed, None as Option)?; @@ -1108,7 +1125,7 @@ where counter_payout, &self.wallet, &self.time, - reference_id + reference_id, )?; self.chain_monitor.lock().unwrap().add_tx( @@ -1257,9 +1274,7 @@ where let fee_rate_per_vb: u64 = { let fee_rate = self .fee_estimator - .get_est_sat_per_1000_weight( - ConfirmationTarget::HighPriority, - ); + .get_est_sat_per_1000_weight(ConfirmationTarget::HighPriority); let fee_rate = fee_rate / 250; @@ -1285,8 +1300,7 @@ where self.blockchain.send_transaction(&claim_tx)?; } - self.store - .upsert_channel(settled_closing_channel, None)?; + self.store.upsert_channel(settled_closing_channel, None)?; } Ok(()) @@ -1318,7 +1332,7 @@ where // TODO(lucas): We are losing the context of the settle transaction here, but it // can always be found based on the claim transaction. We could introduce a // dedicated `SettledClosed` state to fix this. - closing_txid: channel.claim_transaction.txid() + closing_txid: channel.claim_transaction.txid(), }) } else { Channel::CounterClosed(ClosedChannel { @@ -1326,7 +1340,7 @@ where temporary_channel_id: channel.temporary_channel_id, channel_id: channel.channel_id, reference_id: channel.reference_id, - closing_txid: channel.claim_transaction.txid() + closing_txid: channel.claim_transaction.txid(), }) }; @@ -1335,8 +1349,7 @@ where .unwrap() .cleanup_channel(channel.channel_id); - self.store - .upsert_channel(closed_channel, None)?; + self.store.upsert_channel(closed_channel, None)?; } Ok(()) @@ -1413,7 +1426,7 @@ where error_message: format!("Error validating accept channel: {e}"), accept_message: accept_channel.clone(), counter_party: *peer_id, - reference_id: accept_channel.reference_id + reference_id: accept_channel.reference_id, }; self.store .upsert_channel(Channel::FailedAccept(channel), None)?; @@ -1484,7 +1497,7 @@ where error_message: format!("Error validating accept channel: {e}"), sign_message: sign_channel.clone(), counter_party: *peer_id, - reference_id: accepted_channel.reference_id + reference_id: accepted_channel.reference_id, }; self.store .upsert_channel(Channel::FailedSign(channel), None)?; @@ -1540,7 +1553,7 @@ where return Ok(Some(Reject { channel_id: settle_offer.channel_id, timestamp: get_unix_time_now(), - reference_id: settle_offer.reference_id + reference_id: settle_offer.reference_id, })); } @@ -1753,8 +1766,12 @@ where } } - let offered_contract = - crate::channel_updater::on_renew_offer(&mut signed_channel, renew_offer,PEER_TIMEOUT, &self.time)?; + let offered_contract = crate::channel_updater::on_renew_offer( + &mut signed_channel, + renew_offer, + PEER_TIMEOUT, + &self.time, + )?; self.store.create_contract(&offered_contract)?; self.store @@ -2114,44 +2131,69 @@ where } match channel { Channel::Offered(offered_channel) => { - let offered_contract = get_contract_in_state!(self, &offered_channel.offered_contract_id, Offered, None as Option)?; + let offered_contract = get_contract_in_state!( + self, + &offered_channel.offered_contract_id, + Offered, + None as Option + )?; - let utxos = offered_contract.funding_inputs_info.iter().map(|funding_input_info| { - let txid = Transaction::consensus_decode(&mut funding_input_info.funding_input.prev_tx.as_slice()) + let utxos = offered_contract + .funding_inputs_info + .iter() + .map(|funding_input_info| { + let txid = Transaction::consensus_decode( + &mut funding_input_info.funding_input.prev_tx.as_slice(), + ) .expect("Transaction Decode Error") .txid(); - let vout = funding_input_info.funding_input.prev_tx_vout; - OutPoint{txid, vout} - }).collect::>(); + let vout = funding_input_info.funding_input.prev_tx_vout; + OutPoint { txid, vout } + }) + .collect::>(); self.wallet.unreserve_utxos(&utxos)?; // remove rejected channel, since nothing has been confirmed on chain yet. - self.store.upsert_channel(Channel::Cancelled(offered_channel), Some(Contract::Rejected(offered_contract)))?; - }, + self.store.upsert_channel( + Channel::Cancelled(offered_channel), + Some(Contract::Rejected(offered_contract)), + )?; + } Channel::Signed(mut signed_channel) => { let contract = match signed_channel.state { - SignedChannelState::RenewOffered { offered_contract_id, .. } => { - let offered_contract = get_contract_in_state!(self, &offered_contract_id, Offered, None::)?; + SignedChannelState::RenewOffered { + offered_contract_id, + .. + } => { + let offered_contract = get_contract_in_state!( + self, + &offered_contract_id, + Offered, + None:: + )?; Some(Contract::Rejected(offered_contract)) - } - _ => None + _ => None, }; crate::channel_updater::on_reject(&mut signed_channel)?; self.store .upsert_channel(Channel::Signed(signed_channel), contract)?; - }, + } channel => { - return Err(Error::InvalidState( - format!("Not in a state adequate to receive a reject message. {:?}", channel), - )) + return Err(Error::InvalidState(format!( + "Not in a state adequate to receive a reject message. {:?}", + channel + ))) } } } else { - warn!("Couldn't find rejected dlc channel with id: {}", reject.channel_id.to_hex()); + warn!( + "Couldn't find rejected dlc channel with id: {}", + reject.channel_id.to_hex() + ); } Ok(()) @@ -2178,9 +2220,7 @@ where } } - let settled_closing_channels = self - .store - .get_settled_closing_channels()?; + let settled_closing_channels = self.store.get_settled_closing_channels()?; for channel in settled_closing_channels { if let Err(e) = self.try_confirm_claim_tx(&channel) { @@ -2397,7 +2437,7 @@ where temporary_channel_id: signed_channel.temporary_channel_id, channel_id: signed_channel.channel_id, punish_txid: signed_tx.txid(), - reference_id: None + reference_id: None, }); //TODO(tibo): should probably make sure the tx is confirmed somewhere before @@ -2411,10 +2451,10 @@ where } TxType::CollaborativeClose => { let counter_payout = get_signed_channel_state!( - signed_channel, - CollaborativeCloseOffered, - counter_payout - )?; + signed_channel, + CollaborativeCloseOffered, + counter_payout + )?; if let Some(SignedChannelState::Established { signed_contract_id, .. }) = signed_channel.roll_back_state @@ -2433,7 +2473,7 @@ where temporary_channel_id: signed_channel.temporary_channel_id, channel_id: signed_channel.channel_id, reference_id: signed_channel.reference_id, - closing_txid: tx.txid() + closing_txid: tx.txid(), }); self.chain_monitor .lock() @@ -2451,7 +2491,8 @@ where let is_settle_offer = { let chain_monitor = self.chain_monitor.lock().unwrap(); - chain_monitor.did_we_offer_last_channel_settlement(&signed_channel.channel_id) + chain_monitor + .did_we_offer_last_channel_settlement(&signed_channel.channel_id) }; let is_settle_offer = match is_settle_offer { @@ -2459,7 +2500,7 @@ where None => { log::error!("Cannot force close settled channel without knowledge of who offered settlement"); continue; - }, + } }; let mut state = SignedChannelState::SettledClosing { @@ -2508,7 +2549,7 @@ where temporary_channel_id: signed_channel.temporary_channel_id, channel_id: signed_channel.channel_id, reference_id: signed_channel.reference_id, - closing_txid: tx.txid() + closing_txid: tx.txid(), }) } else { Channel::CounterClosed(ClosedChannel { @@ -2516,7 +2557,7 @@ where temporary_channel_id: signed_channel.temporary_channel_id, channel_id: signed_channel.channel_id, reference_id: signed_channel.reference_id, - closing_txid: tx.txid() + closing_txid: tx.txid(), }) } } @@ -2527,7 +2568,7 @@ where temporary_channel_id: signed_channel.temporary_channel_id, channel_id: signed_channel.channel_id, reference_id: None, - closing_txid: tx.txid() + closing_txid: tx.txid(), }) } } @@ -2587,7 +2628,7 @@ where pub(crate) fn force_close_sub_channel( &self, channel_id: &DlcChannelId, - sub_channel: (SubChannel, &ClosingSubChannel) + sub_channel: (SubChannel, &ClosingSubChannel), ) -> Result<(), Error> { let channel = get_channel_in_state!(self, channel_id, Signed, None as Option)?; let is_initiator = sub_channel.1.is_initiator; @@ -2599,7 +2640,7 @@ where mut channel: SignedChannel, sub_channel: Option<(SubChannel, &ClosingSubChannel)>, is_initiator: bool, - reference_id: Option + reference_id: Option, ) -> Result<(), Error> { match &channel.state { SignedChannelState::Established { @@ -2607,7 +2648,10 @@ where buffer_transaction, .. } => { - warn!("Force closing established channel with id: {}", channel.channel_id.to_hex()); + warn!( + "Force closing established channel with id: {}", + channel.channel_id.to_hex() + ); let counter_buffer_adaptor_signature = *counter_buffer_adaptor_signature; let buffer_transaction = buffer_transaction.clone(); @@ -2617,7 +2661,7 @@ where is_initiator, counter_buffer_adaptor_signature, buffer_transaction, - reference_id + reference_id, ) } SignedChannelState::RenewFinalized { @@ -2625,7 +2669,10 @@ where offer_buffer_adaptor_signature, .. } => { - warn!("Force closing renew finalized channel with id: {}", channel.channel_id.to_hex()); + warn!( + "Force closing renew finalized channel with id: {}", + channel.channel_id.to_hex() + ); let offer_buffer_adaptor_signature = *offer_buffer_adaptor_signature; let buffer_transaction = buffer_transaction.clone(); @@ -2635,13 +2682,21 @@ where is_initiator, offer_buffer_adaptor_signature, buffer_transaction, - reference_id + reference_id, ) } SignedChannelState::Settled { .. } => { - warn!("Force closing settled channel with id: {}", channel.channel_id.to_hex()); + warn!( + "Force closing settled channel with id: {}", + channel.channel_id.to_hex() + ); - self.initiate_unilateral_close_settled_channel(channel, sub_channel, is_initiator, reference_id) + self.initiate_unilateral_close_settled_channel( + channel, + sub_channel, + is_initiator, + reference_id, + ) } SignedChannelState::SettledOffered { .. } | SignedChannelState::SettledReceived { .. } @@ -2657,9 +2712,9 @@ where .expect("to have a rollback state"); self.force_close_channel_internal(channel, sub_channel, is_initiator, reference_id) } - SignedChannelState::Closing { .. } | SignedChannelState::SettledClosing { .. } => Err(Error::InvalidState( - "Channel is already closing.".to_string(), - )), + SignedChannelState::Closing { .. } | SignedChannelState::SettledClosing { .. } => Err( + Error::InvalidState("Channel is already closing.".to_string()), + ), } } @@ -2671,7 +2726,7 @@ where is_initiator: bool, buffer_adaptor_signature: EcdsaAdaptorSignature, buffer_transaction: Transaction, - reference_id: Option + reference_id: Option, ) -> Result<(), Error> { crate::channel_updater::initiate_unilateral_close_established_channel( &self.secp, @@ -2681,7 +2736,7 @@ where &self.wallet, sub_channel, is_initiator, - reference_id + reference_id, )?; let buffer_transaction = @@ -2716,17 +2771,18 @@ where mut signed_channel: SignedChannel, sub_channel: Option<(SubChannel, &ClosingSubChannel)>, is_initiator: bool, - reference_id: Option + reference_id: Option, ) -> Result<(), Error> { let is_settle_offer = { let chain_monitor = self.chain_monitor.lock().unwrap(); chain_monitor.did_we_offer_last_channel_settlement(&signed_channel.channel_id) - }.ok_or_else( - || Error::InvalidState( + } + .ok_or_else(|| { + Error::InvalidState( "Cannot force close settled channel without knowledge of who offered settlement" - .to_string() + .to_string(), ) - )?; + })?; crate::channel_updater::initiate_unilateral_close_settled_channel( &self.secp, @@ -2755,7 +2811,8 @@ where .unwrap() .cleanup_channel(signed_channel.channel_id); - self.store.upsert_channel(Channel::Signed(signed_channel), None)?; + self.store + .upsert_channel(Channel::Signed(signed_channel), None)?; Ok(()) } @@ -2785,7 +2842,7 @@ where channel_id, reference_id: None, // TODO(holzeis): Ignoring closing txid on dlc channels for sub channels - closing_txid: Txid::all_zeros() + closing_txid: Txid::all_zeros(), }); Ok((closed_channel, contract)) diff --git a/dlc-manager/src/sub_channel_manager.rs b/dlc-manager/src/sub_channel_manager.rs index 3ec3405c..a4f451ff 100644 --- a/dlc-manager/src/sub_channel_manager.rs +++ b/dlc-manager/src/sub_channel_manager.rs @@ -3,8 +3,8 @@ use std::{collections::HashMap, marker::PhantomData, ops::Deref, sync::Mutex}; -use bitcoin::{hashes::hex::ToHex, OutPoint, PackedLockTime, Script, Sequence, Transaction, Txid}; use bitcoin::hashes::Hash; +use bitcoin::{hashes::hex::ToHex, OutPoint, PackedLockTime, Script, Sequence, Transaction, Txid}; use dlc::{channel::sub_channel::LN_GLUE_TX_WEIGHT, PartyParams}; use dlc_messages::{ channel::{AcceptChannel, OfferChannel}, @@ -406,7 +406,7 @@ where self.dlc_channel_manager.get_time(), temporary_channel_id, true, - None + None, )?; // TODO(tibo): refactor properly. @@ -631,8 +631,11 @@ where let ln_output_value = split_tx.transaction.output[0].value; let glue_tx_output_value = ln_output_value - - dlc::util::tx_weight_to_fee(LN_GLUE_TX_WEIGHT, offered_contract.fee_rate_per_vb) - .map_err(|e| APIError::ExternalError { err: e.to_string() })?; + - dlc::util::tx_weight_to_fee( + LN_GLUE_TX_WEIGHT, + offered_contract.fee_rate_per_vb, + ) + .map_err(|e| APIError::ExternalError { err: e.to_string() })?; let ln_glue_tx = dlc::channel::sub_channel::create_ln_glue_tx( &OutPoint { @@ -1689,7 +1692,7 @@ where cet_locktime: sub_channel_offer.cet_locktime, refund_locktime: sub_channel_offer.refund_locktime, cet_nsequence: sub_channel_offer.cet_nsequence, - reference_id: None + reference_id: None, }; let (offered_channel, offered_contract) = @@ -1893,7 +1896,7 @@ where refund_signature: sub_channel_accept.refund_signature, negotiation_fields: None, payout_spk: sub_channel_accept.payout_spk.clone(), - reference_id: None + reference_id: None, }; let sub_channel_info = SubChannelSignVerifyInfo { @@ -2083,7 +2086,7 @@ where funding_signatures: FundingSignatures { funding_signatures: vec![], }, - reference_id: None + reference_id: None, }; let offer_revoke_params = accepted_sub_channel @@ -3307,7 +3310,7 @@ where is_offer_party: false, counter_party: dlc_channel.counter_party, cet_nsequence: CET_NSEQUENCE, - reference_id: None + reference_id: None, }; self.dlc_channel_manager .get_store() @@ -3383,7 +3386,7 @@ where counter_party: dlc_channel.counter_party, // TODO(tibo): use value from original offer cet_nsequence: CET_NSEQUENCE, - reference_id: None + reference_id: None, }; self.ln_channel_manager.set_funding_outpoint( channel_lock, @@ -3451,7 +3454,7 @@ where is_offer_party: false, counter_party: dlc_channel.counter_party, cet_nsequence: CET_NSEQUENCE, - reference_id: None + reference_id: None, }; self.dlc_channel_manager .get_store() @@ -3704,7 +3707,7 @@ where channel_id: channel.get_id(), reference_id: None, // TODO(holzeis): Ignoring closing txid on dlc channels for sub channels - closing_txid: Txid::all_zeros() + closing_txid: Txid::all_zeros(), }; let closed_channel = if counter_closed { Channel::CounterClosed(closed_channel_data) diff --git a/dlc-manager/src/utils.rs b/dlc-manager/src/utils.rs index 3170aa5f..b7e4cb04 100644 --- a/dlc-manager/src/utils.rs +++ b/dlc-manager/src/utils.rs @@ -1,7 +1,10 @@ use std::ops::Deref; use bitcoin::{consensus::Encodable, Txid}; -use dlc::{util::{cet_or_refund_base_fee, dlc_payout_spk_fee}, PartyParams, TxInputInfo, FUND_TX_BASE_WEIGHT}; +use dlc::{ + util::{cet_or_refund_base_fee, dlc_payout_spk_fee}, + PartyParams, TxInputInfo, FUND_TX_BASE_WEIGHT, +}; use dlc_messages::{ oracle_msgs::{OracleAnnouncement, OracleAttestation}, FundingInput, diff --git a/dlc-manager/tests/channel_execution_tests.rs b/dlc-manager/tests/channel_execution_tests.rs index 9ed0baeb..e9225250 100644 --- a/dlc-manager/tests/channel_execution_tests.rs +++ b/dlc-manager/tests/channel_execution_tests.rs @@ -90,9 +90,7 @@ enum TestPath { BufferCheat, RenewedClose, SettleCheat, - CollaborativeClose{ - accept_own_offer: bool - }, + CollaborativeClose { accept_own_offer: bool }, SettleRenewSettle, SettleOfferTimeout, SettleAcceptTimeout, @@ -171,7 +169,9 @@ fn channel_settle_cheat_test() { fn channel_collaborative_close_test() { channel_execution_test( get_enum_test_params(1, 1, None), - TestPath::CollaborativeClose{ accept_own_offer: false}, + TestPath::CollaborativeClose { + accept_own_offer: false, + }, ); } @@ -180,7 +180,9 @@ fn channel_collaborative_close_test() { fn channel_collaborative_close_own_offer_test() { channel_execution_test( get_enum_test_params(1, 1, None), - TestPath::CollaborativeClose{ accept_own_offer: true}, + TestPath::CollaborativeClose { + accept_own_offer: true, + }, ); } @@ -484,7 +486,7 @@ fn channel_execution_test(test_params: TestParams, path: TestPath) { "0218845781f631c48f1c9709e23092067d06837f30aa0cd0544ac887fe91ddd166" .parse() .unwrap(), - None + None, ) .expect("Send offer error"); @@ -500,7 +502,11 @@ fn channel_execution_test(test_params: TestParams, path: TestPath) { assert_channel_state!(alice_manager_send, temporary_channel_id, Offered); if let TestPath::CancelOffer = path { - let (reject_msg, _) = alice_manager_send.lock().unwrap().reject_channel(&temporary_channel_id).expect("Error rejecting contract offer"); + let (reject_msg, _) = alice_manager_send + .lock() + .unwrap() + .reject_channel(&temporary_channel_id) + .expect("Error rejecting contract offer"); assert_channel_state!(alice_manager_send, temporary_channel_id, Cancelled); alice_send .send(Some(Message::Channel(ChannelMessage::Reject(reject_msg)))) @@ -597,7 +603,7 @@ fn channel_execution_test(test_params: TestParams, path: TestPath) { channel_id, second_receive, &generate_blocks, - accept_own_offer + accept_own_offer, ); } TestPath::SettleOfferTimeout @@ -1059,7 +1065,12 @@ fn renew_channel( let (renew_offer, _) = first .lock() .unwrap() - .renew_offer(&channel_id, test_utils::ACCEPT_COLLATERAL, contract_input, None) + .renew_offer( + &channel_id, + test_utils::ACCEPT_COLLATERAL, + contract_input, + None, + ) .expect("to be able to renew channel contract"); first_send @@ -1122,7 +1133,12 @@ fn renew_reject( let (renew_offer, _) = first .lock() .unwrap() - .renew_offer(&channel_id, test_utils::ACCEPT_COLLATERAL, contract_input, None) + .renew_offer( + &channel_id, + test_utils::ACCEPT_COLLATERAL, + contract_input, + None, + ) .expect("to be able to renew channel contract"); first_send @@ -1166,7 +1182,12 @@ fn renew_race( let (renew_offer, _) = first .lock() .unwrap() - .renew_offer(&channel_id, test_utils::OFFER_COLLATERAL, contract_input, None) + .renew_offer( + &channel_id, + test_utils::OFFER_COLLATERAL, + contract_input, + None, + ) .expect("to be able to renew channel contract"); let mut contract_input_2 = contract_input.clone(); @@ -1176,7 +1197,12 @@ fn renew_race( let (renew_offer_2, _) = second .lock() .unwrap() - .renew_offer(&channel_id, test_utils::OFFER_COLLATERAL, &contract_input_2, None) + .renew_offer( + &channel_id, + test_utils::OFFER_COLLATERAL, + &contract_input_2, + None, + ) .expect("to be able to renew channel contract"); first_send @@ -1216,7 +1242,7 @@ fn collaborative_close( channel_id: DlcChannelId, sync_receive: &Receiver<()>, generate_blocks: &F, - accept_own_offer: bool + accept_own_offer: bool, ) { let contract_id = get_established_channel_contract_id(&first, &channel_id); let close_offer = first @@ -1235,8 +1261,15 @@ fn collaborative_close( assert_channel_state!(second, channel_id, Signed, CollaborativeCloseOffered); if accept_own_offer { - if let Err(e) = first.lock().unwrap().accept_collaborative_close(&channel_id) { - assert_eq!("Invalid state: Cannot accept own collaborative close offer", e.to_string()); + if let Err(e) = first + .lock() + .unwrap() + .accept_collaborative_close(&channel_id) + { + assert_eq!( + "Invalid state: Cannot accept own collaborative close offer", + e.to_string() + ); } else { panic!("It should not be possible to accept own collaborative close offer"); } @@ -1244,7 +1277,6 @@ fn collaborative_close( return; } - second .lock() .unwrap() @@ -1278,7 +1310,12 @@ fn renew_timeout( let (renew_offer, _) = first .lock() .unwrap() - .renew_offer(&channel_id, test_utils::ACCEPT_COLLATERAL, contract_input, None) + .renew_offer( + &channel_id, + test_utils::ACCEPT_COLLATERAL, + contract_input, + None, + ) .expect("to be able to offer a settlement of the contract."); first_send diff --git a/dlc-manager/tests/ln_dlc_channel_execution_tests.rs b/dlc-manager/tests/ln_dlc_channel_execution_tests.rs index 6ba8c9c0..84c3968c 100644 --- a/dlc-manager/tests/ln_dlc_channel_execution_tests.rs +++ b/dlc-manager/tests/ln_dlc_channel_execution_tests.rs @@ -13,10 +13,7 @@ use std::{ use crate::test_utils::{ get_enum_test_params_custom_collateral, refresh_wallet, TestParams, EVENT_MATURITY, }; -use bitcoin::{ - hashes::Hash, Address, Amount, Network, PackedLockTime, Transaction, TxIn, - TxOut, -}; +use bitcoin::{hashes::Hash, Address, Amount, Network, PackedLockTime, Transaction, TxIn, TxOut}; use bitcoin_bech32::WitnessProgram; use bitcoin_test_utils::rpc_helpers::init_clients; use bitcoincore_rpc::{Client, RpcApi}; @@ -2274,7 +2271,7 @@ fn renew(test_params: &LnDlcTestParams, dlc_channel_id: &DlcChannelId) { dlc_channel_id, test_params.test_params.contract_input.accept_collateral, &test_params.test_params.contract_input, - None + None, ) .unwrap(); diff --git a/dlc-messages/src/channel.rs b/dlc-messages/src/channel.rs index 7f13a753..7d8aa969 100644 --- a/dlc-messages/src/channel.rs +++ b/dlc-messages/src/channel.rs @@ -81,7 +81,7 @@ pub struct OfferChannel { /// The nSequence value to use for the CETs. pub cet_nsequence: u32, /// The reference id set by the api user. - pub reference_id: Option<[u8; 32]> + pub reference_id: Option<[u8; 32]>, } impl_dlc_writeable!(OfferChannel, { @@ -195,7 +195,7 @@ pub struct AcceptChannel { /// Fields used to negotiate parameters with the counter party. pub negotiation_fields: Option, /// The reference id set by the api user. - pub reference_id: Option<[u8; 32]> + pub reference_id: Option<[u8; 32]>, } impl_dlc_writeable!(AcceptChannel, { @@ -245,7 +245,7 @@ pub struct SignChannel { /// The signatures for the offer party's inputs. pub funding_signatures: FundingSignatures, /// The reference id set by the api user. - pub reference_id: Option<[u8; 32]> + pub reference_id: Option<[u8; 32]>, } impl_dlc_writeable!(SignChannel, { @@ -282,7 +282,7 @@ pub struct SettleOffer { /// The timestamp when the message was created pub timestamp: u64, /// The reference id set by the api user. - pub reference_id: Option<[u8; 32]> + pub reference_id: Option<[u8; 32]>, } impl_dlc_writeable!(SettleOffer, { @@ -317,7 +317,7 @@ pub struct SettleAccept { /// party. pub settle_adaptor_signature: EcdsaAdaptorSignature, /// The reference id set by the api user. - pub reference_id: Option<[u8; 32]> + pub reference_id: Option<[u8; 32]>, } impl_dlc_writeable!(SettleAccept, { @@ -351,7 +351,7 @@ pub struct SettleConfirm { /// sending party. pub settle_adaptor_signature: EcdsaAdaptorSignature, /// The reference id set by the api user. - pub reference_id: Option<[u8; 32]> + pub reference_id: Option<[u8; 32]>, } impl_dlc_writeable!(SettleConfirm, { @@ -382,7 +382,7 @@ pub struct SettleFinalize { /// the establishment of the previous channel state. pub prev_per_update_secret: SecretKey, /// The reference id set by the api user. - pub reference_id: Option<[u8; 32]> + pub reference_id: Option<[u8; 32]>, } impl_dlc_writeable!(SettleFinalize, { @@ -423,7 +423,7 @@ pub struct RenewOffer { /// The nSequence value to use for the CETs. pub cet_nsequence: u32, /// The reference id set by the api user. - pub reference_id: Option<[u8; 32]> + pub reference_id: Option<[u8; 32]>, } impl_dlc_writeable!(RenewOffer, { @@ -462,7 +462,7 @@ pub struct RenewAccept { /// The refund signature generated by the offer party. pub refund_signature: Signature, /// The reference id set by the api user. - pub reference_id: Option<[u8; 32]> + pub reference_id: Option<[u8; 32]>, } impl_dlc_writeable!(RenewAccept, { @@ -498,7 +498,7 @@ pub struct RenewConfirm { /// The refund signature generated by the offer party. pub refund_signature: Signature, /// The reference id set by the api user. - pub reference_id: Option<[u8; 32]> + pub reference_id: Option<[u8; 32]>, } impl_dlc_writeable!(RenewConfirm, { @@ -533,7 +533,7 @@ pub struct RenewFinalize { /// party. pub buffer_adaptor_signature: EcdsaAdaptorSignature, /// The reference id set by the api user. - pub reference_id: Option<[u8; 32]> + pub reference_id: Option<[u8; 32]>, } impl_dlc_writeable!(RenewFinalize, { @@ -564,7 +564,7 @@ pub struct RenewRevoke { /// the previous channel state. pub per_update_secret: SecretKey, /// The reference id set by the api user. - pub reference_id: Option<[u8; 32]> + pub reference_id: Option<[u8; 32]>, } impl_dlc_writeable!(RenewRevoke, { @@ -595,7 +595,7 @@ pub struct CollaborativeCloseOffer { /// The signature of the sending party for the closing transaction. pub close_signature: Signature, /// The reference id set by the api user. - pub reference_id: Option<[u8; 32]> + pub reference_id: Option<[u8; 32]>, } impl_dlc_writeable!(CollaborativeCloseOffer, { @@ -626,7 +626,7 @@ pub struct Reject { /// The timestamp when the message was created pub timestamp: u64, /// The reference id set by the api user. - pub reference_id: Option<[u8; 32]> + pub reference_id: Option<[u8; 32]>, } impl_dlc_writeable!(Reject, { (channel_id, writeable), (timestamp, writeable), (reference_id, option) }); diff --git a/dlc-messages/src/lib.rs b/dlc-messages/src/lib.rs index 6b5ca1e6..74d4d0d8 100644 --- a/dlc-messages/src/lib.rs +++ b/dlc-messages/src/lib.rs @@ -52,8 +52,8 @@ use lightning::ln::wire::Type; use lightning::util::ser::{Readable, Writeable, Writer}; use secp256k1_zkp::Verification; use secp256k1_zkp::{ecdsa::Signature, EcdsaAdaptorSignature, PublicKey, Secp256k1}; -use serde::{Deserialize, Serialize}; use segmentation::{SegmentChunk, SegmentStart}; +use serde::{Deserialize, Serialize}; use sub_channel::{ Reject as SubChannelReject, SubChannelAccept, SubChannelCloseAccept, SubChannelCloseConfirm, SubChannelCloseFinalize, SubChannelCloseOffer, SubChannelConfirm, SubChannelFinalize, @@ -383,7 +383,9 @@ impl OfferDlc { ContractInfo::SingleContractInfo(s) => s.contract_info.oracle_info.validate(secp)?, ContractInfo::DisjointContractInfo(d) => { if d.contract_infos.len() < 2 { - return Err(Error::InvalidArgument("Contract infos length smaller than 2".to_string())); + return Err(Error::InvalidArgument( + "Contract infos length smaller than 2".to_string(), + )); } for c in &d.contract_infos { diff --git a/dlc-messages/src/oracle_msgs.rs b/dlc-messages/src/oracle_msgs.rs index 7a844b07..922a187e 100644 --- a/dlc-messages/src/oracle_msgs.rs +++ b/dlc-messages/src/oracle_msgs.rs @@ -224,7 +224,9 @@ impl OracleEvent { if expected_nb_nonces == self.oracle_nonces.len() { Ok(()) } else { - Err(Error::InvalidArgument("Expected nb nonces is not equal to oracle nonecs length".to_string())) + Err(Error::InvalidArgument( + "Expected nb nonces is not equal to oracle nonecs length".to_string(), + )) } } } diff --git a/dlc-sled-storage-provider/src/lib.rs b/dlc-sled-storage-provider/src/lib.rs index a33e45f3..a977b8c6 100644 --- a/dlc-sled-storage-provider/src/lib.rs +++ b/dlc-sled-storage-provider/src/lib.rs @@ -21,7 +21,8 @@ use dlc_manager::channel::accepted_channel::AcceptedChannel; use dlc_manager::channel::offered_channel::OfferedChannel; use dlc_manager::channel::signed_channel::{SignedChannel, SignedChannelStateType}; use dlc_manager::channel::{ - Channel, ClosedChannel, ClosedPunishedChannel, ClosingChannel, FailedAccept, FailedSign, SettledClosingChannel, + Channel, ClosedChannel, ClosedPunishedChannel, ClosingChannel, FailedAccept, FailedSign, + SettledClosingChannel, }; use dlc_manager::contract::accepted_contract::AcceptedContract; use dlc_manager::contract::offered_contract::OfferedContract; @@ -782,9 +783,9 @@ fn deserialize_channel(buff: &sled::IVec) -> Result { ChannelPrefix::Closing => { Channel::Closing(ClosingChannel::deserialize(&mut cursor).map_err(to_storage_error)?) } - ChannelPrefix::SettledClosing => { - Channel::SettledClosing(SettledClosingChannel::deserialize(&mut cursor).map_err(to_storage_error)?) - } + ChannelPrefix::SettledClosing => Channel::SettledClosing( + SettledClosingChannel::deserialize(&mut cursor).map_err(to_storage_error)?, + ), ChannelPrefix::Closed => { Channel::Closed(ClosedChannel::deserialize(&mut cursor).map_err(to_storage_error)?) } @@ -797,9 +798,9 @@ fn deserialize_channel(buff: &sled::IVec) -> Result { ChannelPrefix::ClosedPunished => Channel::ClosedPunished( ClosedPunishedChannel::deserialize(&mut cursor).map_err(to_storage_error)?, ), - ChannelPrefix::Cancelled => Channel::Cancelled( - OfferedChannel::deserialize(&mut cursor).map_err(to_storage_error)?, - ) + ChannelPrefix::Cancelled => { + Channel::Cancelled(OfferedChannel::deserialize(&mut cursor).map_err(to_storage_error)?) + } }; Ok(channel) } diff --git a/dlc-trie/src/multi_oracle_trie.rs b/dlc-trie/src/multi_oracle_trie.rs index c2b397d4..e80361c9 100644 --- a/dlc-trie/src/multi_oracle_trie.rs +++ b/dlc-trie/src/multi_oracle_trie.rs @@ -168,7 +168,9 @@ impl MultiOracleTrie { /// Creates a new MultiOracleTrie pub fn new(oracle_numeric_infos: &OracleNumericInfo, threshold: usize) -> Result { if oracle_numeric_infos.nb_digits.is_empty() { - return Err(Error::InvalidArgument("Oracle numeric infos nb digits is empty".to_string())); + return Err(Error::InvalidArgument( + "Oracle numeric infos nb digits is empty".to_string(), + )); } let digit_trie = DigitTrie::new(oracle_numeric_infos.base); let extra_cover_trie = if oracle_numeric_infos.has_diff_nb_digits() { diff --git a/dlc-trie/src/utils.rs b/dlc-trie/src/utils.rs index 559ed655..76a2aca5 100644 --- a/dlc-trie/src/utils.rs +++ b/dlc-trie/src/utils.rs @@ -18,7 +18,9 @@ pub(crate) fn get_adaptor_point_for_indexed_paths( debug_assert!(indexes.len() == paths.len()); debug_assert!(precomputed_points.len() >= indexes.len()); if indexes.is_empty() { - return Err(super::Error::InvalidArgument("Indexes is empty".to_string())); + return Err(super::Error::InvalidArgument( + "Indexes is empty".to_string(), + )); } let mut keys = Vec::new(); diff --git a/dlc/src/channel/mod.rs b/dlc/src/channel/mod.rs index 386a5f8c..6f15fec6 100644 --- a/dlc/src/channel/mod.rs +++ b/dlc/src/channel/mod.rs @@ -417,11 +417,7 @@ pub fn create_and_sign_claim_settle_transaction( ) -> Result { let own_descriptor = settle_descriptor(own_params, &counter_params.own_pk, csv_timelock); - let vout = if is_offer { - 0 - } else { - 1 - }; + let vout = if is_offer { 0 } else { 1 }; let tx_in = TxIn { previous_output: OutPoint { @@ -471,8 +467,7 @@ pub fn create_and_sign_claim_settle_transaction( let satisfier = (sigs, Sequence::from_height(csv_timelock as u16)); - own_descriptor - .satisfy(&mut tx.input[0], satisfier)?; + own_descriptor.satisfy(&mut tx.input[0], satisfier)?; Ok(tx) } diff --git a/dlc/src/channel/sub_channel.rs b/dlc/src/channel/sub_channel.rs index de934766..8cb7e212 100644 --- a/dlc/src/channel/sub_channel.rs +++ b/dlc/src/channel/sub_channel.rs @@ -87,14 +87,22 @@ pub fn create_split_tx( let dlc_output_value = dlc_collateral .checked_add(dlc_fee) - .ok_or(Error::InvalidArgument("Failed to checked add dlc fee to dlc collateral".to_string()))?; + .ok_or(Error::InvalidArgument( + "Failed to checked add dlc fee to dlc collateral".to_string(), + ))?; if dlc_output_value > channel_value .checked_add(crate::DUST_LIMIT) - .ok_or(Error::InvalidArgument("Failed to checked add dust limit to channel value".to_string()))? + .ok_or(Error::InvalidArgument( + "Failed to checked add dust limit to channel value".to_string(), + ))? { - return Err(Error::InvalidArgument(format!("Dlc output value greater than channel value: {} + dust limit: {}", channel_value, crate::DUST_LIMIT))); + return Err(Error::InvalidArgument(format!( + "Dlc output value greater than channel value: {} + dust limit: {}", + channel_value, + crate::DUST_LIMIT + ))); } let ln_output_value = channel_value diff --git a/dlc/src/lib.rs b/dlc/src/lib.rs index d78e0cbc..ba998d0e 100644 --- a/dlc/src/lib.rs +++ b/dlc/src/lib.rs @@ -71,7 +71,8 @@ pub const P2WPKH_WITNESS_SIZE: usize = 107; macro_rules! checked_add { ($a: expr, $b: expr) => { - $a.checked_add($b).ok_or(Error::InvalidArgument("Failed to checked add".to_string())) + $a.checked_add($b) + .ok_or(Error::InvalidArgument("Failed to checked add".to_string())) }; ($a: expr, $b: expr, $c: expr) => { checked_add!(checked_add!($a, $b)?, $c) @@ -280,7 +281,9 @@ impl PartyParams { let script_weight = util::redeem_script_to_script_sig(&w.redeem_script) .len() .checked_mul(4) - .ok_or(Error::InvalidArgument("Failed to multiple 4 to script weight".to_string()))?; + .ok_or(Error::InvalidArgument( + "Failed to multiple 4 to script weight".to_string(), + ))?; inputs_weight = checked_add!( inputs_weight, TX_INPUT_BASE_WEIGHT, @@ -293,24 +296,24 @@ impl PartyParams { // independently of inputs contributed let this_party_fund_base_weight = FUND_TX_BASE_WEIGHT / 2; - let fund_weight_without_change = checked_add!( - this_party_fund_base_weight, - inputs_weight - )?; - let fund_fee_without_change = util::tx_weight_to_fee(fund_weight_without_change, fee_rate_per_vb)?; + let fund_weight_without_change = checked_add!(this_party_fund_base_weight, inputs_weight)?; + let fund_fee_without_change = + util::tx_weight_to_fee(fund_weight_without_change, fee_rate_per_vb)?; // Base weight (nLocktime, nVersion, funding input ...) is distributed // among parties independently of output types let this_party_cet_base_weight = CET_BASE_WEIGHT / 2; - let output_spk_fee = dlc_payout_spk_fee( - &self.payout_script_pubkey, - fee_rate_per_vb, - ); - let cet_or_refund_base_fee = util::weight_to_fee(this_party_cet_base_weight, fee_rate_per_vb)?; + let output_spk_fee = dlc_payout_spk_fee(&self.payout_script_pubkey, fee_rate_per_vb); + let cet_or_refund_base_fee = + util::weight_to_fee(this_party_cet_base_weight, fee_rate_per_vb)?; let cet_or_refund_fee = checked_add!(cet_or_refund_base_fee, output_spk_fee)?; - let required_input_funds = - checked_add!(self.collateral, fund_fee_without_change, cet_or_refund_fee, extra_fee)?; + let required_input_funds = checked_add!( + self.collateral, + fund_fee_without_change, + cet_or_refund_fee, + extra_fee + )?; if self.input_amount < required_input_funds { return Err(Error::InvalidArgument(format!("input amount: {} smaller than required input funds: {} (collateral: {}, fund_fee: {}, cet_or_refund_fee: {}, extra_fee: {})", self.input_amount, required_input_funds, self.collateral, fund_fee_without_change, cet_or_refund_fee, extra_fee))); } @@ -331,11 +334,9 @@ impl PartyParams { let change_fee = util::weight_to_fee(change_weight, fee_rate_per_vb)?; - let change_amount = leftover - .checked_sub(change_fee) - .ok_or_else(|| { - Error::InvalidArgument("Change output value is lower than cost".to_string()) - })?; + let change_amount = leftover.checked_sub(change_fee).ok_or_else(|| { + Error::InvalidArgument("Change output value is lower than cost".to_string()) + })?; (change_amount, change_fee) }; @@ -509,7 +510,9 @@ pub(crate) fn create_cets_and_refund_tx( }); if !has_proper_outcomes { - return Err(Error::InvalidArgument("payouts doe not have proper outcomes".to_string())); + return Err(Error::InvalidArgument( + "payouts doe not have proper outcomes".to_string(), + )); } let cet_input = TxIn { @@ -699,7 +702,9 @@ fn get_oracle_sig_point( msgs: &[Message], ) -> Result { if oracle_info.nonces.len() < msgs.len() { - return Err(Error::InvalidArgument("length of oracle info nonces is smaller than msgs length".to_string())); + return Err(Error::InvalidArgument( + "length of oracle info nonces is smaller than msgs length".to_string(), + )); } let sig_points: Vec = oracle_info @@ -722,7 +727,9 @@ pub fn get_adaptor_point_from_oracle_info( msgs: &[Vec], ) -> Result { if oracle_infos.is_empty() || msgs.is_empty() { - return Err(Error::InvalidArgument("empty oracle infos or msgs".to_string())); + return Err(Error::InvalidArgument( + "empty oracle infos or msgs".to_string(), + )); } let mut oracle_sigpoints = Vec::with_capacity(msgs[0].len()); @@ -808,7 +815,9 @@ pub fn create_cet_adaptor_sigs_from_oracle_info( msgs: &[Vec>], ) -> Result, Error> { if msgs.len() != cets.len() { - return Err(Error::InvalidArgument("length of msgs is not equal to length of cets".to_string())); + return Err(Error::InvalidArgument( + "length of msgs is not equal to length of cets".to_string(), + )); } cets.iter() diff --git a/dlc/src/util.rs b/dlc/src/util.rs index 75df9000..e40f0e99 100644 --- a/dlc/src/util.rs +++ b/dlc/src/util.rs @@ -294,7 +294,10 @@ pub(crate) fn compute_var_int_prefix_size(len: usize) -> usize { /// Validate that the fee rate is not too high pub fn validate_fee_rate(fee_rate_per_vb: u64) -> Result<(), Error> { if fee_rate_per_vb > 25 * 250 { - return Err(Error::InvalidArgument(format!("Fee rate: {} greater than 25 * 250", fee_rate_per_vb))); + return Err(Error::InvalidArgument(format!( + "Fee rate: {} greater than 25 * 250", + fee_rate_per_vb + ))); } Ok(()) diff --git a/mocks/src/memory_storage_provider.rs b/mocks/src/memory_storage_provider.rs index 2e55d9f9..93017811 100644 --- a/mocks/src/memory_storage_provider.rs +++ b/mocks/src/memory_storage_provider.rs @@ -3,8 +3,7 @@ use dlc_manager::chain_monitor::ChainMonitor; use dlc_manager::channel::{ offered_channel::OfferedChannel, signed_channel::{SignedChannel, SignedChannelStateType}, - Channel, - SettledClosingChannel, + Channel, SettledClosingChannel, }; use dlc_manager::contract::{ offered_contract::OfferedContract, signed_contract::SignedContract, Contract, PreClosedContract, diff --git a/rustfmt.toml b/rustfmt.toml new file mode 100644 index 00000000..f42c8b39 --- /dev/null +++ b/rustfmt.toml @@ -0,0 +1,2 @@ +edition = "2021" +max_width = 100 diff --git a/simple-wallet/src/lib.rs b/simple-wallet/src/lib.rs index 5a3ba00e..e1141063 100644 --- a/simple-wallet/src/lib.rs +++ b/simple-wallet/src/lib.rs @@ -1,7 +1,10 @@ use std::ops::Deref; use bitcoin::psbt::PartiallySignedTransaction; -use bitcoin::{Address, Network, PackedLockTime, Script, Sequence, Transaction, TxIn, TxOut, Txid, Witness, OutPoint}; +use bitcoin::{ + Address, Network, OutPoint, PackedLockTime, Script, Sequence, Transaction, TxIn, TxOut, Txid, + Witness, +}; use dlc_manager::{error::Error, Blockchain, Signer, Utxo, Wallet}; use lightning::chain::chaininterface::{ConfirmationTarget, FeeEstimator}; use rust_bitcoin_coin_selection::select_coins;