diff --git a/fuzz/src/msg_targets/mod.rs b/fuzz/src/msg_targets/mod.rs index 6f5f8120ca0..00bcd10847e 100644 --- a/fuzz/src/msg_targets/mod.rs +++ b/fuzz/src/msg_targets/mod.rs @@ -1,48 +1,47 @@ -#![cfg_attr(rustfmt, rustfmt_skip)] -mod utils; pub mod msg_accept_channel; +pub mod msg_accept_channel_v2; pub mod msg_announcement_signatures; +pub mod msg_channel_announcement; +pub mod msg_channel_details; +pub mod msg_channel_ready; +pub mod msg_channel_reestablish; +pub mod msg_channel_update; pub mod msg_closing_signed; pub mod msg_commitment_signed; +pub mod msg_decoded_onion_error_packet; +pub mod msg_error_message; pub mod msg_funding_created; -pub mod msg_channel_ready; pub mod msg_funding_signed; pub mod msg_gossip_timestamp_filter; pub mod msg_init; +pub mod msg_node_announcement; pub mod msg_open_channel; +pub mod msg_open_channel_v2; pub mod msg_ping; pub mod msg_pong; pub mod msg_query_channel_range; +pub mod msg_query_short_channel_ids; +pub mod msg_reply_channel_range; pub mod msg_reply_short_channel_ids_end; pub mod msg_revoke_and_ack; pub mod msg_shutdown; +pub mod msg_splice_ack; +pub mod msg_splice_init; +pub mod msg_splice_locked; +pub mod msg_stfu; +pub mod msg_tx_abort; +pub mod msg_tx_ack_rbf; +pub mod msg_tx_add_input; +pub mod msg_tx_add_output; +pub mod msg_tx_complete; +pub mod msg_tx_init_rbf; +pub mod msg_tx_remove_input; +pub mod msg_tx_remove_output; +pub mod msg_tx_signatures; pub mod msg_update_add_htlc; pub mod msg_update_fail_htlc; pub mod msg_update_fail_malformed_htlc; pub mod msg_update_fee; pub mod msg_update_fulfill_htlc; -pub mod msg_channel_reestablish; -pub mod msg_decoded_onion_error_packet; -pub mod msg_channel_announcement; -pub mod msg_node_announcement; -pub mod msg_channel_update; -pub mod msg_query_short_channel_ids; -pub mod msg_reply_channel_range; -pub mod msg_error_message; pub mod msg_warning_message; -pub mod msg_channel_details; -pub mod msg_open_channel_v2; -pub mod msg_accept_channel_v2; -pub mod msg_tx_add_input; -pub mod msg_tx_add_output; -pub mod msg_tx_remove_input; -pub mod msg_tx_remove_output; -pub mod msg_tx_complete; -pub mod msg_tx_signatures; -pub mod msg_tx_init_rbf; -pub mod msg_tx_ack_rbf; -pub mod msg_tx_abort; -pub mod msg_stfu; -pub mod msg_splice_init; -pub mod msg_splice_ack; -pub mod msg_splice_locked; +mod utils; diff --git a/lightning/src/chain/chaininterface.rs b/lightning/src/chain/chaininterface.rs index 5da9f4a22ae..4d82c4104af 100644 --- a/lightning/src/chain/chaininterface.rs +++ b/lightning/src/chain/chaininterface.rs @@ -1,5 +1,3 @@ -#![cfg_attr(rustfmt, rustfmt_skip)] - // This file is Copyright its original authors, visible in version control // history. // @@ -189,14 +187,20 @@ pub const FEERATE_FLOOR_SATS_PER_KW: u32 = 253; /// /// Note that this does *not* implement [`FeeEstimator`] to make it harder to accidentally mix the /// two. -pub(crate) struct LowerBoundedFeeEstimator(pub F) where F::Target: FeeEstimator; - -impl LowerBoundedFeeEstimator where F::Target: FeeEstimator { +pub(crate) struct LowerBoundedFeeEstimator(pub F) +where + F::Target: FeeEstimator; + +impl LowerBoundedFeeEstimator +where + F::Target: FeeEstimator, +{ /// Creates a new `LowerBoundedFeeEstimator` which wraps the provided fee_estimator pub fn new(fee_estimator: F) -> Self { LowerBoundedFeeEstimator(fee_estimator) } + #[rustfmt::skip] pub fn bounded_sat_per_1000_weight(&self, confirmation_target: ConfirmationTarget) -> u32 { cmp::max( self.0.get_est_sat_per_1000_weight(confirmation_target), @@ -207,7 +211,9 @@ impl LowerBoundedFeeEstimator where F::Target: FeeEstimator { #[cfg(test)] mod tests { - use super::{FEERATE_FLOOR_SATS_PER_KW, LowerBoundedFeeEstimator, ConfirmationTarget, FeeEstimator}; + use super::{ + ConfirmationTarget, FeeEstimator, LowerBoundedFeeEstimator, FEERATE_FLOOR_SATS_PER_KW, + }; struct TestFeeEstimator { sat_per_kw: u32, @@ -220,6 +226,7 @@ mod tests { } #[test] + #[rustfmt::skip] fn test_fee_estimator_less_than_floor() { let sat_per_kw = FEERATE_FLOOR_SATS_PER_KW - 1; let test_fee_estimator = &TestFeeEstimator { sat_per_kw }; @@ -229,6 +236,7 @@ mod tests { } #[test] + #[rustfmt::skip] fn test_fee_estimator_greater_than_floor() { let sat_per_kw = FEERATE_FLOOR_SATS_PER_KW + 1; let test_fee_estimator = &TestFeeEstimator { sat_per_kw }; diff --git a/lightning/src/chain/chainmonitor.rs b/lightning/src/chain/chainmonitor.rs index 09d87b775be..e51c3c22575 100644 --- a/lightning/src/chain/chainmonitor.rs +++ b/lightning/src/chain/chainmonitor.rs @@ -1,5 +1,3 @@ -#![cfg_attr(rustfmt, rustfmt_skip)] - // This file is Copyright its original authors, visible in version control // history. // @@ -26,27 +24,30 @@ //! servicing [`ChannelMonitor`] updates from the client. use bitcoin::block::Header; -use bitcoin::hash_types::{Txid, BlockHash}; +use bitcoin::hash_types::{BlockHash, Txid}; use crate::chain; -use crate::chain::{ChannelMonitorUpdateStatus, Filter, WatchedOutput}; use crate::chain::chaininterface::{BroadcasterInterface, FeeEstimator}; -use crate::chain::channelmonitor::{ChannelMonitor, ChannelMonitorUpdate, Balance, MonitorEvent, TransactionOutputs, WithChannelMonitor}; +use crate::chain::channelmonitor::{ + Balance, ChannelMonitor, ChannelMonitorUpdate, MonitorEvent, TransactionOutputs, + WithChannelMonitor, +}; use crate::chain::transaction::{OutPoint, TransactionData}; +use crate::chain::{ChannelMonitorUpdateStatus, Filter, WatchedOutput}; +use crate::events::{self, Event, EventHandler, ReplayEvent}; +use crate::ln::channel_state::ChannelDetails; use crate::ln::types::ChannelId; use crate::sign::ecdsa::EcdsaChannelSigner; -use crate::events::{self, Event, EventHandler, ReplayEvent}; -use crate::util::logger::{Logger, WithContext}; use crate::util::errors::APIError; +use crate::util::logger::{Logger, WithContext}; use crate::util::persist::MonitorName; use crate::util::wakers::{Future, Notifier}; -use crate::ln::channel_state::ChannelDetails; use crate::prelude::*; -use crate::sync::{RwLock, RwLockReadGuard, Mutex, MutexGuard}; +use crate::sync::{Mutex, MutexGuard, RwLock, RwLockReadGuard}; +use bitcoin::secp256k1::PublicKey; use core::ops::Deref; use core::sync::atomic::{AtomicUsize, Ordering}; -use bitcoin::secp256k1::PublicKey; /// `Persist` defines behavior for persisting channel monitors: this could mean /// writing once to disk, and/or uploading to one or more backup services. @@ -122,6 +123,7 @@ pub trait Persist { /// /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager /// [`Writeable::write`]: crate::util::ser::Writeable::write + #[rustfmt::skip] fn persist_new_channel(&self, monitor_name: MonitorName, monitor: &ChannelMonitor) -> ChannelMonitorUpdateStatus; /// Update one channel's data. The provided [`ChannelMonitor`] has already applied the given @@ -161,6 +163,7 @@ pub trait Persist { /// [`ChannelMonitorUpdateStatus`] for requirements when returning errors. /// /// [`Writeable::write`]: crate::util::ser::Writeable::write + #[rustfmt::skip] fn update_persisted_channel(&self, monitor_name: MonitorName, monitor_update: Option<&ChannelMonitorUpdate>, monitor: &ChannelMonitor) -> ChannelMonitorUpdateStatus; /// Prevents the channel monitor from being loaded on startup. /// @@ -233,12 +236,19 @@ impl Deref for LockedChannelMonitor<'_, Chann /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager /// [module-level documentation]: crate::chain::chainmonitor /// [`rebroadcast_pending_claims`]: Self::rebroadcast_pending_claims -pub struct ChainMonitor - where C::Target: chain::Filter, - T::Target: BroadcasterInterface, - F::Target: FeeEstimator, - L::Target: Logger, - P::Target: Persist, +pub struct ChainMonitor< + ChannelSigner: EcdsaChannelSigner, + C: Deref, + T: Deref, + F: Deref, + L: Deref, + P: Deref, +> where + C::Target: chain::Filter, + T::Target: BroadcasterInterface, + F::Target: FeeEstimator, + L::Target: Logger, + P::Target: Persist, { monitors: RwLock>>, chain_source: Option, @@ -257,12 +267,14 @@ pub struct ChainMonitor ChainMonitor -where C::Target: chain::Filter, - T::Target: BroadcasterInterface, - F::Target: FeeEstimator, - L::Target: Logger, - P::Target: Persist, +impl + ChainMonitor +where + C::Target: chain::Filter, + T::Target: BroadcasterInterface, + F::Target: FeeEstimator, + L::Target: Logger, + P::Target: Persist, { /// Dispatches to per-channel monitors, which are responsible for updating their on-chain view /// of a channel and reacting accordingly based on transactions in the given chain data. See @@ -275,6 +287,7 @@ where C::Target: chain::Filter, /// updated `txdata`. /// /// Calls which represent a new blockchain tip height should set `best_height`. + #[rustfmt::skip] fn process_chain_data(&self, header: &Header, best_height: Option, txdata: &TransactionData, process: FN) where FN: Fn(&ChannelMonitor, &TransactionData) -> Vec @@ -318,6 +331,7 @@ where C::Target: chain::Filter, } } + #[rustfmt::skip] fn update_monitor_with_chain_data( &self, header: &Header, best_height: Option, txdata: &TransactionData, process: FN, channel_id: &ChannelId, monitor_state: &MonitorHolder, channel_count: usize, @@ -388,7 +402,9 @@ where C::Target: chain::Filter, /// pre-filter blocks or only fetch blocks matching a compact filter. Otherwise, clients may /// always need to fetch full blocks absent another means for determining which blocks contain /// transactions relevant to the watched channels. - pub fn new(chain_source: Option, broadcaster: T, logger: L, feeest: F, persister: P) -> Self { + pub fn new( + chain_source: Option, broadcaster: T, logger: L, feeest: F, persister: P, + ) -> Self { Self { monitors: RwLock::new(new_hash_map()), chain_source, @@ -431,7 +447,9 @@ where C::Target: chain::Filter, /// /// Note that the result holds a mutex over our monitor set, and should not be held /// indefinitely. - pub fn get_monitor(&self, channel_id: ChannelId) -> Result, ()> { + pub fn get_monitor( + &self, channel_id: ChannelId, + ) -> Result, ()> { let lock = self.monitors.read().unwrap(); if lock.get(&channel_id).is_some() { Ok(LockedChannelMonitor { lock, channel_id }) @@ -464,13 +482,13 @@ where C::Target: chain::Filter, /// Each `Vec` contains `update_id`s from [`ChannelMonitor::get_latest_update_id`] for updates /// that have not yet been fully persisted. Note that if a full monitor is persisted all the pending /// monitor updates must be individually marked completed by calling [`ChainMonitor::channel_monitor_updated`]. + #[rustfmt::skip] pub fn list_pending_monitor_updates(&self) -> Vec<(ChannelId, Vec)> { self.monitors.read().unwrap().iter().map(|(channel_id, holder)| { (*channel_id, holder.pending_monitor_updates.lock().unwrap().clone()) }).collect() } - #[cfg(any(test, feature = "_test_utils"))] pub fn remove_monitor(&self, channel_id: &ChannelId) -> ChannelMonitor { self.monitors.write().unwrap().remove(channel_id).unwrap().monitor @@ -496,6 +514,7 @@ where C::Target: chain::Filter, /// /// Returns an [`APIError::APIMisuseError`] if `funding_txo` does not match any currently /// registered [`ChannelMonitor`]s. + #[rustfmt::skip] pub fn channel_monitor_updated(&self, channel_id: ChannelId, completed_update_id: u64) -> Result<(), APIError> { let monitors = self.monitors.read().unwrap(); let monitor_data = if let Some(mon) = monitors.get(&channel_id) { mon } else { @@ -535,6 +554,7 @@ where C::Target: chain::Filter, /// chain::Watch API wherein we mark a monitor fully-updated by just calling /// channel_monitor_updated once with the highest ID. #[cfg(any(test, fuzzing))] + #[rustfmt::skip] pub fn force_channel_monitor_updated(&self, channel_id: ChannelId, monitor_update_id: u64) { let monitors = self.monitors.read().unwrap(); let monitor = &monitors.get(&channel_id).unwrap().monitor; @@ -563,6 +583,7 @@ where C::Target: chain::Filter, /// See the trait-level documentation of [`EventsProvider`] for requirements. /// /// [`EventsProvider`]: crate::events::EventsProvider + #[rustfmt::skip] pub async fn process_pending_events_async>, H: Fn(Event) -> Future>( &self, handler: H ) { @@ -598,6 +619,7 @@ where C::Target: chain::Filter, /// feerate changes between blocks, and ensuring reliability if broadcasting fails. We recommend /// invoking this every 30 seconds, or lower if running in an environment with spotty /// connections, like on mobile. + #[rustfmt::skip] pub fn rebroadcast_pending_claims(&self) { let monitors = self.monitors.read().unwrap(); for (_, monitor_holder) in &*monitors { @@ -611,6 +633,7 @@ where C::Target: chain::Filter, /// signature generation failure. /// /// `monitor_opt` can be used as a filter to only trigger them for a specific channel monitor. + #[rustfmt::skip] pub fn signer_unblocked(&self, monitor_opt: Option) { let monitors = self.monitors.read().unwrap(); if let Some(channel_id) = monitor_opt { @@ -637,6 +660,7 @@ where C::Target: chain::Filter, /// /// Depending on the implementation of [`Persist::archive_persisted_channel`] the monitor /// data could be moved to an archive location or removed entirely. + #[rustfmt::skip] pub fn archive_fully_resolved_channel_monitors(&self) { let mut have_monitors_to_prune = false; for monitor_holder in self.monitors.read().unwrap().values() { @@ -670,7 +694,7 @@ where C::Target: chain::Filter, } impl -chain::Listen for ChainMonitor + chain::Listen for ChainMonitor where C::Target: chain::Filter, T::Target: BroadcasterInterface, @@ -678,6 +702,7 @@ where L::Target: Logger, P::Target: Persist, { + #[rustfmt::skip] fn filtered_block_connected(&self, header: &Header, txdata: &TransactionData, height: u32) { log_debug!(self.logger, "New best block {} at height {} provided via block_connected", header.block_hash(), height); self.process_chain_data(header, Some(height), &txdata, |monitor, txdata| { @@ -688,6 +713,7 @@ where self.event_notifier.notify(); } + #[rustfmt::skip] fn block_disconnected(&self, header: &Header, height: u32) { let monitor_states = self.monitors.read().unwrap(); log_debug!(self.logger, "Latest block {} at height {} removed via block_disconnected", header.block_hash(), height); @@ -699,7 +725,7 @@ where } impl -chain::Confirm for ChainMonitor + chain::Confirm for ChainMonitor where C::Target: chain::Filter, T::Target: BroadcasterInterface, @@ -707,6 +733,7 @@ where L::Target: Logger, P::Target: Persist, { + #[rustfmt::skip] fn transactions_confirmed(&self, header: &Header, txdata: &TransactionData, height: u32) { log_debug!(self.logger, "{} provided transactions confirmed at height {} in block {}", txdata.len(), height, header.block_hash()); self.process_chain_data(header, None, txdata, |monitor, txdata| { @@ -717,6 +744,7 @@ where self.event_notifier.notify(); } + #[rustfmt::skip] fn transaction_unconfirmed(&self, txid: &Txid) { log_debug!(self.logger, "Transaction {} reorganized out of chain", txid); let monitor_states = self.monitors.read().unwrap(); @@ -725,6 +753,7 @@ where } } + #[rustfmt::skip] fn best_block_updated(&self, header: &Header, height: u32) { log_debug!(self.logger, "New best block {} at height {} provided via best_block_updated", header.block_hash(), height); self.process_chain_data(header, Some(height), &[], |monitor, txdata| { @@ -752,14 +781,16 @@ where } } -impl -chain::Watch for ChainMonitor -where C::Target: chain::Filter, - T::Target: BroadcasterInterface, - F::Target: FeeEstimator, - L::Target: Logger, - P::Target: Persist, +impl + chain::Watch for ChainMonitor +where + C::Target: chain::Filter, + T::Target: BroadcasterInterface, + F::Target: FeeEstimator, + L::Target: Logger, + P::Target: Persist, { + #[rustfmt::skip] fn watch_channel(&self, channel_id: ChannelId, monitor: ChannelMonitor) -> Result { let logger = WithChannelMonitor::from(&self.logger, &monitor, None); let mut monitors = self.monitors.write().unwrap(); @@ -798,6 +829,7 @@ where C::Target: chain::Filter, Ok(persist_res) } + #[rustfmt::skip] fn update_channel(&self, channel_id: ChannelId, update: &ChannelMonitorUpdate) -> ChannelMonitorUpdateStatus { // `ChannelMonitorUpdate`'s `channel_id` is `None` prior to 0.0.121 and all channels in those // versions are V1-established. For 0.0.121+ the `channel_id` fields is always `Some`. @@ -876,6 +908,7 @@ where C::Target: chain::Filter, } } + #[rustfmt::skip] fn release_pending_monitor_events(&self) -> Vec<(OutPoint, ChannelId, Vec, PublicKey)> { let mut pending_monitor_events = self.pending_monitor_events.lock().unwrap().split_off(0); for monitor_state in self.monitors.read().unwrap().values() { @@ -891,12 +924,14 @@ where C::Target: chain::Filter, } } -impl events::EventsProvider for ChainMonitor - where C::Target: chain::Filter, - T::Target: BroadcasterInterface, - F::Target: FeeEstimator, - L::Target: Logger, - P::Target: Persist, +impl + events::EventsProvider for ChainMonitor +where + C::Target: chain::Filter, + T::Target: BroadcasterInterface, + F::Target: FeeEstimator, + L::Target: Logger, + P::Target: Persist, { /// Processes [`SpendableOutputs`] events produced from each [`ChannelMonitor`] upon maturity. /// @@ -911,6 +946,7 @@ impl(&self, handler: H) where H::Target: EventHandler { for monitor_state in self.monitors.read().unwrap().values() { match monitor_state.monitor.process_pending_events(&handler, &self.logger) { @@ -925,18 +961,19 @@ impl(r: &mut R) -> Result { let _ver = read_ver_prefix!(r, SERIALIZATION_VERSION); let update_id: u64 = Readable::read(r)?; @@ -306,6 +323,7 @@ impl_writeable_tlv_based!(HolderSignedTx, { impl HolderCommitment { // Matches the serialization of `HolderSignedTx` for backwards compatibility reasons. + #[rustfmt::skip] fn write_as_legacy(&self, writer: &mut W) -> Result<(), io::Error> { let trusted_tx = self.tx.trust(); let tx_keys = trusted_tx.keys(); @@ -382,6 +400,7 @@ impl Writeable for CounterpartyCommitmentParameters { } } impl Readable for CounterpartyCommitmentParameters { + #[rustfmt::skip] fn read(r: &mut R) -> Result { let counterparty_commitment_transaction = { // Versions prior to 0.0.100 had some per-HTLC state stored here, which is no longer @@ -427,6 +446,7 @@ struct OnchainEventEntry { } impl OnchainEventEntry { + #[rustfmt::skip] fn confirmation_threshold(&self) -> u32 { let mut conf_threshold = self.height + ANTI_REORG_DELAY - 1; match self.event { @@ -478,9 +498,7 @@ enum OnchainEvent { }, /// An output waiting on [`ANTI_REORG_DELAY`] confirmations before we hand the user the /// [`SpendableOutputDescriptor`]. - MaturingOutput { - descriptor: SpendableOutputDescriptor, - }, + MaturingOutput { descriptor: SpendableOutputDescriptor }, /// A spend of the funding output, either a commitment transaction or a cooperative closing /// transaction. FundingSpendConfirmation { @@ -530,6 +548,7 @@ impl Writeable for OnchainEventEntry { } impl MaybeReadable for OnchainEventEntry { + #[rustfmt::skip] fn read(reader: &mut R) -> Result, DecodeError> { let mut txid = Txid::all_zeros(); let mut transaction = None; @@ -622,6 +641,7 @@ pub(crate) enum ChannelMonitorUpdateStep { } impl ChannelMonitorUpdateStep { + #[rustfmt::skip] fn variant_name(&self) -> &'static str { match self { ChannelMonitorUpdateStep::LatestHolderCommitmentTXInfo { .. } => "LatestHolderCommitmentTXInfo", @@ -832,6 +852,7 @@ impl Balance { /// [`Balance::MaybePreimageClaimableHTLC`]. /// /// On-chain fees required to claim the balance are not included in this amount. + #[rustfmt::skip] pub fn claimable_amount_satoshis(&self) -> u64 { match self { Balance::ClaimableOnChannelClose { amount_satoshis, .. }| @@ -877,6 +898,7 @@ impl Writeable for IrrevocablyResolvedHTLC { } impl Readable for IrrevocablyResolvedHTLC { + #[rustfmt::skip] fn read(reader: &mut R) -> Result { let mut mapped_commitment_tx_output_idx = 0; let mut resolving_txid = None; @@ -912,7 +934,10 @@ pub struct ChannelMonitor { pub(crate) inner: Mutex>, } -impl Clone for ChannelMonitor where Signer: Clone { +impl Clone for ChannelMonitor +where + Signer: Clone, +{ fn clone(&self) -> Self { let inner = self.inner.lock().unwrap().clone(); ChannelMonitor::from_impl(inner) @@ -930,6 +955,7 @@ struct HolderCommitment { impl TryFrom<(HolderCommitmentTransaction, HolderSignedTx)> for HolderCommitment { type Error = (); + #[rustfmt::skip] fn try_from(value: (HolderCommitmentTransaction, HolderSignedTx)) -> Result { let holder_commitment_tx = value.0; let holder_signed_tx = value.1; @@ -976,7 +1002,9 @@ impl HolderCommitment { self.tx.nondust_htlcs().iter().chain(self.dust_htlcs.iter().map(|(htlc, _)| htlc)) } - fn htlcs_with_sources(&self) -> impl Iterator)> { + fn htlcs_with_sources( + &self, + ) -> impl Iterator)> { let mut sources = self.nondust_htlc_sources.iter(); let nondust_htlcs = self.tx.nondust_htlcs().iter().map(move |htlc| { let mut source = None; @@ -1011,7 +1039,8 @@ struct FundingScope { // consistent across all commitments. Unfortunately, doing so requires that our HTLCs are not // tied to their respective commitment transaction via `transaction_output_index`, as those may // not be consistent across all commitments. - counterparty_claimable_outpoints: HashMap>)>>, + counterparty_claimable_outpoints: + HashMap>)>>, // We store two holder commitment transactions to avoid any race conditions where we may update // some monitors (potentially on watchtowers) but then fail to update others, resulting in the @@ -1189,7 +1218,11 @@ pub(crate) struct ChannelMonitorImpl { /// Transaction outputs to watch for on-chain spends. pub type TransactionOutputs = (Txid, Vec<(u32, TxOut)>); -impl PartialEq for ChannelMonitor where Signer: PartialEq { +impl PartialEq for ChannelMonitor +where + Signer: PartialEq, +{ + #[rustfmt::skip] fn eq(&self, other: &Self) -> bool { // We need some kind of total lockorder. Absent a better idea, we sort by position in // memory and take locks in that order (assuming that we can't move within memory while a @@ -1212,6 +1245,7 @@ const SERIALIZATION_VERSION: u8 = 1; const MIN_SERIALIZATION_VERSION: u8 = 1; impl Writeable for ChannelMonitorImpl { + #[rustfmt::skip] fn write(&self, writer: &mut W) -> Result<(), Error> { write_ver_prefix!(writer, SERIALIZATION_VERSION, MIN_SERIALIZATION_VERSION); @@ -1271,6 +1305,7 @@ impl Writeable for ChannelMonitorImpl { self.commitment_secrets.write(writer)?; + #[rustfmt::skip] macro_rules! serialize_htlc_in_commitment { ($htlc_output: expr) => { writer.write_all(&[$htlc_output.offered as u8; 1])?; @@ -1407,6 +1442,7 @@ impl Writeable for ChannelMonitorImpl { } } +#[rustfmt::skip] macro_rules! _process_events_body { ($self_opt: expr, $logger: expr, $event_to_handle: expr, $handle_event: expr) => { loop { @@ -1465,14 +1501,20 @@ macro_rules! _process_events_body { } pub(super) use _process_events_body as process_events_body; -pub(crate) struct WithChannelMonitor<'a, L: Deref> where L::Target: Logger { +pub(crate) struct WithChannelMonitor<'a, L: Deref> +where + L::Target: Logger, +{ logger: &'a L, peer_id: Option, channel_id: Option, payment_hash: Option, } -impl<'a, L: Deref> Logger for WithChannelMonitor<'a, L> where L::Target: Logger { +impl<'a, L: Deref> Logger for WithChannelMonitor<'a, L> +where + L::Target: Logger, +{ fn log(&self, mut record: Record) { record.peer_id = self.peer_id; record.channel_id = self.channel_id; @@ -1481,11 +1523,17 @@ impl<'a, L: Deref> Logger for WithChannelMonitor<'a, L> where L::Target: Logger } } -impl<'a, L: Deref> WithChannelMonitor<'a, L> where L::Target: Logger { - pub(crate) fn from(logger: &'a L, monitor: &ChannelMonitor, payment_hash: Option) -> Self { +impl<'a, L: Deref> WithChannelMonitor<'a, L> +where + L::Target: Logger, +{ + pub(crate) fn from( + logger: &'a L, monitor: &ChannelMonitor, payment_hash: Option, + ) -> Self { Self::from_impl(logger, &*monitor.inner.lock().unwrap(), payment_hash) } + #[rustfmt::skip] pub(crate) fn from_impl(logger: &'a L, monitor_impl: &ChannelMonitorImpl, payment_hash: Option) -> Self { let peer_id = Some(monitor_impl.counterparty_node_id); let channel_id = Some(monitor_impl.channel_id()); @@ -1503,6 +1551,7 @@ impl ChannelMonitor { ChannelMonitor { inner: Mutex::new(imp) } } + #[rustfmt::skip] pub(crate) fn new( secp_ctx: Secp256k1, keys: Signer, shutdown_script: Option, on_counterparty_tx_csv: u16, destination_script: &Script, @@ -1651,7 +1700,8 @@ impl ChannelMonitor { /// before the initial persistence of a new channel. pub(crate) fn provide_initial_counterparty_commitment_tx( &self, commitment_tx: CommitmentTransaction, logger: &L, - ) where L::Target: Logger + ) where + L::Target: Logger, { let mut inner = self.inner.lock().unwrap(); let logger = WithChannelMonitor::from_impl(logger, &*inner, None); @@ -1663,6 +1713,7 @@ impl ChannelMonitor { /// possibly future revocation/preimage information) to claim outputs where possible. /// We cache also the mapping hash:commitment number to lighten pruning of old preimages by watchtowers. #[cfg(test)] + #[rustfmt::skip] fn provide_latest_counterparty_commitment_tx( &self, txid: Txid, @@ -1678,6 +1729,7 @@ impl ChannelMonitor { } #[cfg(test)] + #[rustfmt::skip] fn provide_latest_holder_commitment_tx( &self, holder_commitment_tx: HolderCommitmentTransaction, htlc_outputs: Vec<(HTLCOutputInCommitment, Option, Option)>, @@ -1695,6 +1747,7 @@ impl ChannelMonitor { /// get the preimage back into this [`ChannelMonitor`] on startup). /// /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager + #[rustfmt::skip] pub(crate) fn provide_payment_preimage_unsafe_legacy( &self, payment_hash: &PaymentHash, @@ -1721,11 +1774,7 @@ impl ChannelMonitor { /// /// panics if the given update is not the next update by update_id. pub fn update_monitor( - &self, - updates: &ChannelMonitorUpdate, - broadcaster: &B, - fee_estimator: &F, - logger: &L, + &self, updates: &ChannelMonitorUpdate, broadcaster: &B, fee_estimator: &F, logger: &L, ) -> Result<(), ()> where B::Target: BroadcasterInterface, @@ -1767,6 +1816,7 @@ impl ChannelMonitor { /// Gets a list of txids, with their output scripts (in the order they appear in the /// transaction), which we must learn about spends of via block_connected(). + #[rustfmt::skip] pub fn get_outputs_to_watch(&self) -> Vec<(Txid, Vec<(u32, ScriptBuf)>)> { self.inner.lock().unwrap().get_outputs_to_watch() .iter().map(|(txid, outputs)| (*txid, outputs.clone())).collect() @@ -1775,6 +1825,7 @@ impl ChannelMonitor { /// Loads the funding txo and outputs to watch into the given `chain::Filter` by repeatedly /// calling `chain::Filter::register_output` and `chain::Filter::register_tx` until all outputs /// have been registered. + #[rustfmt::skip] pub fn load_outputs_to_watch(&self, filter: &F, logger: &L) where F::Target: chain::Filter, L::Target: Logger, @@ -1819,8 +1870,13 @@ impl ChannelMonitor { /// /// [`SpendableOutputs`]: crate::events::Event::SpendableOutputs /// [`BumpTransaction`]: crate::events::Event::BumpTransaction - pub fn process_pending_events(&self, handler: &H, logger: &L) - -> Result<(), ReplayEvent> where H::Target: EventHandler, L::Target: Logger { + pub fn process_pending_events( + &self, handler: &H, logger: &L, + ) -> Result<(), ReplayEvent> + where + H::Target: EventHandler, + L::Target: Logger, + { let mut ev; process_events_body!(Some(self), logger, ev, handler.handle_event(ev)) } @@ -1829,11 +1885,15 @@ impl ChannelMonitor { /// /// See [`Self::process_pending_events`] for more information. pub async fn process_pending_events_async< - Future: core::future::Future>, H: Fn(Event) -> Future, + Future: core::future::Future>, + H: Fn(Event) -> Future, L: Deref, >( &self, handler: &H, logger: &L, - ) -> Result<(), ReplayEvent> where L::Target: Logger { + ) -> Result<(), ReplayEvent> + where + L::Target: Logger, + { let mut ev; process_events_body!(Some(self), logger, ev, { handler(ev).await }) } @@ -1883,7 +1943,9 @@ impl ChannelMonitor { /// may have been created prior to upgrading. /// /// [`Persist::update_persisted_channel`]: crate::chain::chainmonitor::Persist::update_persisted_channel - pub fn counterparty_commitment_txs_from_update(&self, update: &ChannelMonitorUpdate) -> Vec { + pub fn counterparty_commitment_txs_from_update( + &self, update: &ChannelMonitorUpdate, + ) -> Vec { self.inner.lock().unwrap().counterparty_commitment_txs_from_update(update) } @@ -1904,6 +1966,7 @@ impl ChannelMonitor { /// /// [`EcdsaChannelSigner::sign_justice_revoked_output`]: crate::sign::ecdsa::EcdsaChannelSigner::sign_justice_revoked_output /// [`Persist`]: crate::chain::chainmonitor::Persist + #[rustfmt::skip] pub fn sign_to_local_justice_tx(&self, justice_tx: Transaction, input_idx: usize, value: u64, commitment_number: u64) -> Result { self.inner.lock().unwrap().sign_to_local_justice_tx(justice_tx, input_idx, value, commitment_number) } @@ -1944,6 +2007,7 @@ impl ChannelMonitor { /// close channel with their commitment transaction after a substantial amount of time. Best /// may be to contact the other node operator out-of-band to coordinate other options available /// to you. + #[rustfmt::skip] pub fn broadcast_latest_holder_commitment_txn( &self, broadcaster: &B, fee_estimator: &F, logger: &L ) @@ -1963,7 +2027,9 @@ impl ChannelMonitor { /// revoked commitment transaction. #[cfg(any(test, feature = "_test_utils", feature = "unsafe_revoked_tx_signing"))] pub fn unsafe_get_latest_holder_commitment_txn(&self, logger: &L) -> Vec - where L::Target: Logger { + where + L::Target: Logger, + { let mut inner = self.inner.lock().unwrap(); let logger = WithChannelMonitor::from_impl(logger, &*inner, None); inner.unsafe_get_latest_holder_commitment_txn(&logger) @@ -1980,6 +2046,7 @@ impl ChannelMonitor { /// [`get_outputs_to_watch`]. /// /// [`get_outputs_to_watch`]: #method.get_outputs_to_watch + #[rustfmt::skip] pub fn block_connected( &self, header: &Header, @@ -2002,6 +2069,7 @@ impl ChannelMonitor { /// Determines if the disconnected block contained any transactions of interest and updates /// appropriately. + #[rustfmt::skip] pub fn block_disconnected( &self, header: &Header, @@ -2027,6 +2095,7 @@ impl ChannelMonitor { /// blocks. See [`chain::Confirm`] for calling expectations. /// /// [`block_connected`]: Self::block_connected + #[rustfmt::skip] pub fn transactions_confirmed( &self, header: &Header, @@ -2054,6 +2123,7 @@ impl ChannelMonitor { /// than blocks. See [`chain::Confirm`] for calling expectations. /// /// [`block_disconnected`]: Self::block_disconnected + #[rustfmt::skip] pub fn transaction_unconfirmed( &self, txid: &Txid, @@ -2080,6 +2150,7 @@ impl ChannelMonitor { /// blocks. See [`chain::Confirm`] for calling expectations. /// /// [`block_connected`]: Self::block_connected + #[rustfmt::skip] pub fn best_block_updated( &self, header: &Header, @@ -2102,6 +2173,7 @@ impl ChannelMonitor { } /// Returns the set of txids that should be monitored for re-organization out of the chain. + #[rustfmt::skip] pub fn get_relevant_txids(&self) -> Vec<(Txid, u32, Option)> { let inner = self.inner.lock().unwrap(); let mut txids: Vec<(Txid, u32, Option)> = inner.onchain_events_awaiting_threshold_conf @@ -2125,6 +2197,7 @@ impl ChannelMonitor { /// feerate changes between blocks, and ensuring reliability if broadcasting fails. We recommend /// invoking this every 30 seconds, or lower if running in an environment with spotty /// connections, like on mobile. + #[rustfmt::skip] pub fn rebroadcast_pending_claims( &self, broadcaster: B, fee_estimator: F, logger: &L, ) @@ -2146,13 +2219,13 @@ impl ChannelMonitor { } /// Returns true if the monitor has pending claim requests that are not fully confirmed yet. - pub fn has_pending_claims(&self) -> bool - { + pub fn has_pending_claims(&self) -> bool { self.inner.lock().unwrap().onchain_tx_handler.has_pending_claims() } /// Triggers rebroadcasts of pending claims from a force-closed channel after a transaction /// signature generation failure. + #[rustfmt::skip] pub fn signer_unblocked( &self, broadcaster: B, fee_estimator: F, logger: &L, ) @@ -2191,6 +2264,7 @@ impl ChannelMonitor { /// outputs which can be spent by us are found, at least one descriptor is returned. /// /// `confirmation_height` must be the height of the block in which `tx` was included in. + #[rustfmt::skip] pub fn get_spendable_outputs(&self, tx: &Transaction, confirmation_height: u32) -> Vec { let inner = self.inner.lock().unwrap(); let current_height = inner.best_block.height; @@ -2220,6 +2294,7 @@ impl ChannelMonitor { /// The first boolean is true only if [`Self::get_claimable_balances`] has been empty for at /// least [`ARCHIVAL_DELAY_BLOCKS`] blocks as an additional protection against any bugs /// resulting in spuriously empty balance sets. + #[rustfmt::skip] pub fn check_and_update_full_resolution_status(&self, logger: &L) -> (bool, bool) { let mut is_all_funds_claimed = self.get_claimable_balances().is_empty(); let current_height = self.current_best_block().height; @@ -2289,6 +2364,7 @@ impl ChannelMonitor { impl ChannelMonitorImpl { /// Helper for get_claimable_balances which does the work for an individual HTLC, generating up /// to one `Balance` for the HTLC. + #[rustfmt::skip] fn get_htlc_balance(&self, htlc: &HTLCOutputInCommitment, source: Option<&HTLCSource>, holder_commitment: bool, counterparty_revoked_commitment: bool, confirmed_txid: Option @@ -2489,6 +2565,7 @@ impl ChannelMonitor { /// /// See [`Balance`] for additional details on the types of claimable balances which /// may be returned here and their meanings. + #[rustfmt::skip] pub fn get_claimable_balances(&self) -> Vec { let mut res = Vec::new(); let us = self.inner.lock().unwrap(); @@ -2511,6 +2588,7 @@ impl ChannelMonitor { pending_commitment_tx_conf_thresh = Some(conf_thresh); } + #[rustfmt::skip] macro_rules! walk_htlcs { ($holder_commitment: expr, $counterparty_revoked_commitment: expr, $htlc_iter: expr) => { for (htlc, source) in $htlc_iter { @@ -2706,6 +2784,7 @@ impl ChannelMonitor { /// This is similar to [`Self::get_pending_or_resolved_outbound_htlcs`] except it includes /// HTLCs which were resolved on-chain (i.e. where the final HTLC resolution was done by an /// event from this `ChannelMonitor`). + #[rustfmt::skip] pub(crate) fn get_all_current_outbound_htlcs(&self) -> HashMap)> { let mut res = new_hash_map(); // Just examine the available counterparty commitment transactions. See docs on @@ -2739,6 +2818,7 @@ impl ChannelMonitor { /// /// Currently, the preimage is unused, however if it is present in the relevant internal state /// an HTLC is always included even if it has been resolved. + #[rustfmt::skip] pub(crate) fn get_pending_or_resolved_outbound_htlcs(&self) -> HashMap)> { let us = self.inner.lock().unwrap(); // We're only concerned with the confirmation count of HTLC transactions, and don't @@ -2760,6 +2840,7 @@ impl ChannelMonitor { } let mut res = new_hash_map(); + #[rustfmt::skip] macro_rules! walk_htlcs { ($holder_commitment: expr, $htlc_iter: expr) => { for (htlc, source) in $htlc_iter { @@ -2821,7 +2902,9 @@ impl ChannelMonitor { res } - pub(crate) fn get_stored_preimages(&self) -> HashMap)> { + pub(crate) fn get_stored_preimages( + &self, + ) -> HashMap)> { self.inner.lock().unwrap().payment_preimages.clone() } } @@ -2933,6 +3016,7 @@ pub fn deliberately_bogus_accepted_htlc_witness_program() -> Vec { } #[cfg(any(test, feature = "_test_utils"))] +#[rustfmt::skip] pub fn deliberately_bogus_accepted_htlc_witness() -> Vec> { vec![Vec::new(), Vec::new(), Vec::new(), Vec::new(), deliberately_bogus_accepted_htlc_witness_program().into()].into() } @@ -2966,6 +3050,7 @@ impl ChannelMonitorImpl { /// Inserts a revocation secret into this channel monitor. Prunes old preimages if neither /// needed by holder commitment transactions HTCLs nor by counterparty ones. Unless we haven't already seen /// counterparty commitment transaction's secret, they are de facto pruned (we can use revocation key). + #[rustfmt::skip] fn provide_secret(&mut self, idx: u64, secret: [u8; 32]) -> Result<(), &'static str> { if let Err(()) = self.commitment_secrets.provide_secret(idx, secret) { return Err("Previous secret did not match new one"); @@ -3029,6 +3114,7 @@ impl ChannelMonitorImpl { Ok(()) } + #[rustfmt::skip] fn provide_initial_counterparty_commitment_tx( &mut self, commitment_tx: CommitmentTransaction, logger: &WithChannelMonitor, ) where L::Target: Logger { @@ -3047,6 +3133,7 @@ impl ChannelMonitorImpl { self.initial_counterparty_commitment_tx = Some(commitment_tx); } + #[rustfmt::skip] fn provide_latest_counterparty_commitment_tx( &mut self, txid: Txid, htlc_outputs: Vec<(HTLCOutputInCommitment, Option>)>, @@ -3091,6 +3178,7 @@ impl ChannelMonitorImpl { /// is important that any clones of this channel monitor (including remote clones) by kept /// up-to-date as our holder commitment transaction is updated. /// Panics if set_on_holder_tx_csv has never been called. + #[rustfmt::skip] fn provide_latest_holder_commitment_tx( &mut self, holder_commitment_tx: HolderCommitmentTransaction, htlc_outputs: Vec<(HTLCOutputInCommitment, Option, Option)>, @@ -3181,6 +3269,7 @@ impl ChannelMonitorImpl { /// commitment_tx_infos which contain the payment hash have been revoked. /// /// Note that this is often called multiple times for the same payment and must be idempotent. + #[rustfmt::skip] fn provide_payment_preimage( &mut self, payment_hash: &PaymentHash, payment_preimage: &PaymentPreimage, payment_info: &Option, broadcaster: &B, @@ -3215,6 +3304,7 @@ impl ChannelMonitorImpl { // If the channel is force closed, try to claim the output from this preimage. // First check if a counterparty commitment transaction has been broadcasted: + #[rustfmt::skip] macro_rules! claim_htlcs { ($commitment_number: expr, $txid: expr, $htlcs: expr) => { let (htlc_claim_reqs, _) = self.get_counterparty_output_claim_info($commitment_number, $txid, None, $htlcs); @@ -3279,6 +3369,7 @@ impl ChannelMonitorImpl { } } + #[rustfmt::skip] fn generate_claimable_outpoints_and_watch_outputs(&mut self, reason: ClosureReason) -> (Vec, Vec) { let funding_outp = HolderFundingOutput::build( self.funding.current_holder_commitment.tx.clone(), @@ -3324,6 +3415,7 @@ impl ChannelMonitorImpl { (claimable_outpoints, watch_outputs) } + #[rustfmt::skip] pub(crate) fn queue_latest_holder_commitment_txn_for_broadcast( &mut self, broadcaster: &B, fee_estimator: &LowerBoundedFeeEstimator, logger: &WithChannelMonitor ) @@ -3340,6 +3432,7 @@ impl ChannelMonitorImpl { ); } + #[rustfmt::skip] fn update_monitor( &mut self, updates: &ChannelMonitorUpdate, broadcaster: &B, fee_estimator: &F, logger: &WithChannelMonitor ) -> Result<(), ()> @@ -3494,6 +3587,7 @@ impl ChannelMonitorImpl { self.latest_update_id } + #[rustfmt::skip] fn get_funding_txo(&self) -> OutPoint { self.funding.channel_parameters.funding_outpoint .expect("Funding outpoint must be set for active monitor") @@ -3526,6 +3620,7 @@ impl ChannelMonitorImpl { /// Gets the set of events that are repeated regularly (e.g. those which RBF bump /// transactions). We're okay if we lose these on restart as they'll be regenerated for us at /// some regular interval via [`ChannelMonitor::rebroadcast_pending_claims`]. + #[rustfmt::skip] pub(super) fn get_repeated_events(&mut self) -> Vec { let pending_claim_events = self.onchain_tx_handler.get_and_clear_pending_claim_events(); let mut ret = Vec::with_capacity(pending_claim_events.len()); @@ -3608,6 +3703,7 @@ impl ChannelMonitorImpl { }) } + #[rustfmt::skip] fn build_counterparty_commitment_tx( &self, commitment_number: u64, their_per_commitment_point: &PublicKey, to_broadcaster_value: u64, to_countersignatory_value: u64, feerate_per_kw: u32, @@ -3618,6 +3714,7 @@ impl ChannelMonitorImpl { to_broadcaster_value, to_countersignatory_value, feerate_per_kw, nondust_htlcs, channel_parameters, &self.onchain_tx_handler.secp_ctx) } + #[rustfmt::skip] fn counterparty_commitment_txs_from_update(&self, update: &ChannelMonitorUpdate) -> Vec { update.updates.iter().filter_map(|update| { // Soon we will drop the first branch here in favor of the second. @@ -3652,6 +3749,7 @@ impl ChannelMonitorImpl { }).collect() } + #[rustfmt::skip] fn sign_to_local_justice_tx( &self, mut justice_tx: Transaction, input_idx: usize, value: u64, commitment_number: u64 ) -> Result { @@ -3702,6 +3800,7 @@ impl ChannelMonitorImpl { /// /// Returns packages to claim the revoked output(s) and general information about the output that /// is to the counterparty in the commitment transaction. + #[rustfmt::skip] fn check_spend_counterparty_transaction(&mut self, tx: &Transaction, height: u32, block_hash: &BlockHash, logger: &L) -> (Vec, CommitmentTxCounterpartyOutputInfo) where L::Target: Logger { @@ -3713,6 +3812,7 @@ impl ChannelMonitorImpl { let commitment_txid = tx.compute_txid(); //TODO: This is gonna be a performance bottleneck for watchtowers! let per_commitment_option = self.funding.counterparty_claimable_outpoints.get(&commitment_txid); + #[rustfmt::skip] macro_rules! ignore_error { ( $thing : expr ) => { match $thing { @@ -3829,6 +3929,7 @@ impl ChannelMonitorImpl { } /// Returns the HTLC claim package templates and the counterparty output info + #[rustfmt::skip] fn get_counterparty_output_claim_info(&self, commitment_number: u64, commitment_txid: Txid, tx: Option<&Transaction>, per_commitment_option: Option<&Vec<(HTLCOutputInCommitment, Option>)>>) -> (Vec, CommitmentTxCounterpartyOutputInfo) { let mut claimable_outpoints = Vec::new(); @@ -3909,6 +4010,7 @@ impl ChannelMonitorImpl { } /// Attempts to claim a counterparty HTLC-Success/HTLC-Timeout's outputs using the revocation key + #[rustfmt::skip] fn check_spend_counterparty_htlc( &mut self, tx: &Transaction, commitment_number: u64, commitment_txid: &Txid, height: u32, logger: &L ) -> (Vec, Option) where L::Target: Logger { @@ -3953,6 +4055,7 @@ impl ChannelMonitorImpl { (claimable_outpoints, outputs_to_watch) } + #[rustfmt::skip] fn get_broadcasted_holder_htlc_descriptors( &self, holder_tx: &HolderCommitmentTransaction, ) -> Vec { @@ -3994,6 +4097,7 @@ impl ChannelMonitorImpl { // Returns (1) `PackageTemplate`s that can be given to the OnchainTxHandler, so that the handler can // broadcast transactions claiming holder HTLC commitment outputs and (2) a holder revokable // script so we can detect whether a holder transaction has been seen on-chain. + #[rustfmt::skip] fn get_broadcasted_holder_claims( &self, holder_tx: &HolderCommitmentTransaction, conf_height: u32, ) -> (Vec, Option<(ScriptBuf, PublicKey, RevocationKey)>) { @@ -4027,6 +4131,7 @@ impl ChannelMonitorImpl { } // Returns holder HTLC outputs to watch and react to in case of spending. + #[rustfmt::skip] fn get_broadcasted_holder_watch_outputs(&self, holder_tx: &HolderCommitmentTransaction) -> Vec<(u32, TxOut)> { let mut watch_outputs = Vec::with_capacity(holder_tx.nondust_htlcs().len()); let tx = holder_tx.trust(); @@ -4047,11 +4152,17 @@ impl ChannelMonitorImpl { /// revoked using data in holder_claimable_outpoints. /// Should not be used if check_spend_revoked_transaction succeeds. /// Returns None unless the transaction is definitely one of our commitment transactions. - fn check_spend_holder_transaction(&mut self, tx: &Transaction, height: u32, block_hash: &BlockHash, logger: &L) -> Option<(Vec, TransactionOutputs)> where L::Target: Logger { + fn check_spend_holder_transaction( + &mut self, tx: &Transaction, height: u32, block_hash: &BlockHash, logger: &L, + ) -> Option<(Vec, TransactionOutputs)> + where + L::Target: Logger, + { let commitment_txid = tx.compute_txid(); let mut claim_requests = Vec::new(); let mut watch_outputs = Vec::new(); + #[rustfmt::skip] macro_rules! append_onchain_update { ($updates: expr, $to_watch: expr) => { claim_requests = $updates.0; @@ -4066,12 +4177,20 @@ impl ChannelMonitorImpl { if self.funding.current_holder_commitment.tx.trust().txid() == commitment_txid { is_holder_tx = true; log_info!(logger, "Got broadcast of latest holder commitment tx {}, searching for available HTLCs to claim", commitment_txid); - let res = self.get_broadcasted_holder_claims(&self.funding.current_holder_commitment.tx, height); - let mut to_watch = self.get_broadcasted_holder_watch_outputs(&self.funding.current_holder_commitment.tx); + let res = self + .get_broadcasted_holder_claims(&self.funding.current_holder_commitment.tx, height); + let mut to_watch = self + .get_broadcasted_holder_watch_outputs(&self.funding.current_holder_commitment.tx); append_onchain_update!(res, to_watch); fail_unbroadcast_htlcs!( - self, "latest holder", commitment_txid, tx, height, block_hash, - self.funding.current_holder_commitment.htlcs_with_sources(), logger + self, + "latest holder", + commitment_txid, + tx, + height, + block_hash, + self.funding.current_holder_commitment.htlcs_with_sources(), + logger ); } else if let &Some(ref holder_commitment) = &self.funding.prev_holder_commitment { if holder_commitment.tx.trust().txid() == commitment_txid { @@ -4081,8 +4200,14 @@ impl ChannelMonitorImpl { let mut to_watch = self.get_broadcasted_holder_watch_outputs(&holder_commitment.tx); append_onchain_update!(res, to_watch); fail_unbroadcast_htlcs!( - self, "previous holder", commitment_txid, tx, height, block_hash, - holder_commitment.htlcs_with_sources(), logger + self, + "previous holder", + commitment_txid, + tx, + height, + block_hash, + holder_commitment.htlcs_with_sources(), + logger ); } } @@ -4096,6 +4221,7 @@ impl ChannelMonitorImpl { /// Cancels any existing pending claims for a commitment that previously confirmed and has now /// been replaced by another. + #[rustfmt::skip] pub fn cancel_prev_commitment_claims( &mut self, logger: &L, confirmed_commitment_txid: &Txid ) where L::Target: Logger { @@ -4151,6 +4277,7 @@ impl ChannelMonitorImpl { #[cfg(any(test, feature = "_test_utils", feature = "unsafe_revoked_tx_signing"))] /// Note that this includes possibly-locktimed-in-the-future transactions! + #[rustfmt::skip] fn unsafe_get_latest_holder_commitment_txn( &mut self, logger: &WithChannelMonitor ) -> Vec where L::Target: Logger { @@ -4188,6 +4315,7 @@ impl ChannelMonitorImpl { holder_transactions } + #[rustfmt::skip] fn block_connected( &mut self, header: &Header, txdata: &TransactionData, height: u32, broadcaster: B, fee_estimator: F, logger: &WithChannelMonitor, @@ -4203,6 +4331,7 @@ impl ChannelMonitorImpl { self.transactions_confirmed(header, txdata, height, broadcaster, &bounded_fee_estimator, logger) } + #[rustfmt::skip] fn best_block_updated( &mut self, header: &Header, @@ -4234,6 +4363,7 @@ impl ChannelMonitorImpl { } else { Vec::new() } } + #[rustfmt::skip] fn transactions_confirmed( &mut self, header: &Header, @@ -4387,6 +4517,7 @@ impl ChannelMonitorImpl { /// /// `conf_height` should be set to the height at which any new transaction(s)/block(s) were /// confirmed at, even if it is not the current best height. + #[rustfmt::skip] fn block_confirmed( &mut self, conf_height: u32, @@ -4585,6 +4716,7 @@ impl ChannelMonitorImpl { watch_outputs } + #[rustfmt::skip] fn block_disconnected( &mut self, header: &Header, height: u32, broadcaster: B, fee_estimator: F, logger: &WithChannelMonitor ) where B::Target: BroadcasterInterface, @@ -4607,6 +4739,7 @@ impl ChannelMonitorImpl { self.best_block = BestBlock::new(header.prev_blockhash, height - 1); } + #[rustfmt::skip] fn transaction_unconfirmed( &mut self, txid: &Txid, @@ -4644,6 +4777,7 @@ impl ChannelMonitorImpl { /// Filters a block's `txdata` for transactions spending watched outputs or for any child /// transactions thereof. + #[rustfmt::skip] fn filter_block<'a>(&self, txdata: &TransactionData<'a>) -> Vec<&'a Transaction> { let mut matched_txn = new_hash_set(); txdata.iter().filter(|&&(_, tx)| { @@ -4662,6 +4796,7 @@ impl ChannelMonitorImpl { } /// Checks if a given transaction spends any watched outputs. + #[rustfmt::skip] fn spends_watched_output(&self, tx: &Transaction) -> bool { for input in tx.input.iter() { if let Some(outputs) = self.get_outputs_to_watch().get(&input.previous_output.txid) { @@ -4694,6 +4829,7 @@ impl ChannelMonitorImpl { false } + #[rustfmt::skip] fn should_broadcast_holder_commitment_txn( &self, logger: &WithChannelMonitor ) -> bool where L::Target: Logger { @@ -4761,8 +4897,11 @@ impl ChannelMonitorImpl { /// Check if any transaction broadcasted is resolving HTLC output by a success or timeout on a holder /// or counterparty commitment tx, if so send back the source, preimage if found and payment_hash of resolved HTLC fn is_resolving_htlc_output( - &mut self, tx: &Transaction, height: u32, block_hash: &BlockHash, logger: &WithChannelMonitor, - ) where L::Target: Logger { + &mut self, tx: &Transaction, height: u32, block_hash: &BlockHash, + logger: &WithChannelMonitor, + ) where + L::Target: Logger, + { 'outer_loop: for input in &tx.input { let mut payment_data = None; let htlc_claim = HTLCClaim::from_witness(&input.witness); @@ -4809,6 +4948,7 @@ impl ChannelMonitorImpl { } } + #[rustfmt::skip] macro_rules! check_htlc_valid_counterparty { ($htlc_output: expr, $per_commitment_data: expr) => { for &(ref pending_htlc, ref pending_source) in $per_commitment_data { @@ -4823,6 +4963,7 @@ impl ChannelMonitorImpl { } } + #[rustfmt::skip] macro_rules! scan_commitment { ($htlcs: expr, $tx_info: expr, $holder_tx: expr) => { for (ref htlc_output, source_option) in $htlcs { @@ -4869,8 +5010,11 @@ impl ChannelMonitorImpl { } } - if input.previous_output.txid == self.funding.current_holder_commitment.tx.trust().txid() { - let htlcs_with_sources = self.funding.current_holder_commitment.htlcs_with_sources(); + if input.previous_output.txid + == self.funding.current_holder_commitment.tx.trust().txid() + { + let htlcs_with_sources = + self.funding.current_holder_commitment.htlcs_with_sources(); scan_commitment!(htlcs_with_sources, "our latest holder commitment tx", true); } if let Some(ref prev_holder_commitment) = self.funding.prev_holder_commitment { @@ -4879,17 +5023,29 @@ impl ChannelMonitorImpl { scan_commitment!(htlcs_with_sources, "our previous holder commitment tx", true); } } - if let Some(ref htlc_outputs) = self.funding.counterparty_claimable_outpoints.get(&input.previous_output.txid) { - scan_commitment!(htlc_outputs.iter().map(|&(ref a, ref b)| (a, b.as_ref().map(|boxed| &**boxed))), - "counterparty commitment tx", false); + if let Some(ref htlc_outputs) = + self.funding.counterparty_claimable_outpoints.get(&input.previous_output.txid) + { + scan_commitment!( + htlc_outputs + .iter() + .map(|&(ref a, ref b)| (a, b.as_ref().map(|boxed| &**boxed))), + "counterparty commitment tx", + false + ); } // Check that scan_commitment, above, decided there is some source worth relaying an // HTLC resolution backwards to and figure out whether we learned a preimage from it. if let Some((source, payment_hash, amount_msat)) = payment_data { if accepted_preimage_claim { - if !self.pending_monitor_events.iter().any( - |update| if let &MonitorEvent::HTLCEvent(ref upd) = update { upd.source == source } else { false }) { + if !self.pending_monitor_events.iter().any(|update| { + if let &MonitorEvent::HTLCEvent(ref upd) = update { + upd.source == source + } else { + false + } + }) { self.onchain_events_awaiting_threshold_conf.push(OnchainEventEntry { txid: tx.compute_txid(), height, @@ -4909,10 +5065,13 @@ impl ChannelMonitorImpl { })); } } else if offered_preimage_claim { - if !self.pending_monitor_events.iter().any( - |update| if let &MonitorEvent::HTLCEvent(ref upd) = update { + if !self.pending_monitor_events.iter().any(|update| { + if let &MonitorEvent::HTLCEvent(ref upd) = update { upd.source == source - } else { false }) { + } else { + false + } + }) { self.onchain_events_awaiting_threshold_conf.push(OnchainEventEntry { txid: tx.compute_txid(), transaction: Some(tx.clone()), @@ -4933,7 +5092,9 @@ impl ChannelMonitorImpl { } } else { self.onchain_events_awaiting_threshold_conf.retain(|ref entry| { - if entry.height != height { return true; } + if entry.height != height { + return true; + } match entry.event { OnchainEvent::HTLCUpdate { source: ref htlc_source, .. } => { *htlc_source != source @@ -4960,6 +5121,7 @@ impl ChannelMonitorImpl { } } + #[rustfmt::skip] fn get_spendable_outputs(&self, tx: &Transaction) -> Vec { let mut spendable_outputs = Vec::new(); for (i, outp) in tx.output.iter().enumerate() { @@ -5006,6 +5168,7 @@ impl ChannelMonitorImpl { /// Checks if the confirmed transaction is paying funds back to some address we can assume to /// own. + #[rustfmt::skip] fn check_tx_and_push_spendable_outputs( &mut self, tx: &Transaction, height: u32, block_hash: &BlockHash, logger: &WithChannelMonitor, ) where L::Target: Logger { @@ -5027,7 +5190,8 @@ impl ChannelMonitorImpl { } } -impl chain::Listen for (ChannelMonitor, T, F, L) +impl chain::Listen + for (ChannelMonitor, T, F, L) where T::Target: BroadcasterInterface, F::Target: FeeEstimator, @@ -5066,10 +5230,12 @@ where } } -const MAX_ALLOC_SIZE: usize = 64*1024; +const MAX_ALLOC_SIZE: usize = 64 * 1024; impl<'a, 'b, ES: EntropySource, SP: SignerProvider> ReadableArgs<(&'a ES, &'b SP)> - for (BlockHash, ChannelMonitor) { + for (BlockHash, ChannelMonitor) +{ + #[rustfmt::skip] fn read(reader: &mut R, args: (&'a ES, &'b SP)) -> Result { macro_rules! unwrap_obj { ($key: expr) => { @@ -5139,6 +5305,7 @@ impl<'a, 'b, ES: EntropySource, SP: SignerProvider> ReadableArgs<(&'a ES, &'b SP let commitment_secrets = Readable::read(reader)?; + #[rustfmt::skip] macro_rules! read_htlc_in_commitment { () => { { @@ -5463,50 +5630,64 @@ impl<'a, 'b, ES: EntropySource, SP: SignerProvider> ReadableArgs<(&'a ES, &'b SP #[cfg(test)] mod tests { use bitcoin::amount::Amount; - use bitcoin::locktime::absolute::LockTime; - use bitcoin::script::{ScriptBuf, Builder}; - use bitcoin::opcodes; - use bitcoin::transaction::{Transaction, TxIn, TxOut, Version}; - use bitcoin::transaction::OutPoint as BitcoinOutPoint; - use bitcoin::sighash; - use bitcoin::sighash::EcdsaSighashType; - use bitcoin::hashes::Hash; + use bitcoin::hash_types::{BlockHash, Txid}; use bitcoin::hashes::sha256::Hash as Sha256; + use bitcoin::hashes::Hash; use bitcoin::hex::FromHex; - use bitcoin::hash_types::{BlockHash, Txid}; + use bitcoin::locktime::absolute::LockTime; use bitcoin::network::Network; - use bitcoin::secp256k1::{SecretKey,PublicKey}; + use bitcoin::opcodes; + use bitcoin::script::{Builder, ScriptBuf}; use bitcoin::secp256k1::Secp256k1; + use bitcoin::secp256k1::{PublicKey, SecretKey}; + use bitcoin::sighash; + use bitcoin::sighash::EcdsaSighashType; + use bitcoin::transaction::OutPoint as BitcoinOutPoint; + use bitcoin::transaction::{Transaction, TxIn, TxOut, Version}; use bitcoin::{Sequence, Witness}; use crate::chain::chaininterface::LowerBoundedFeeEstimator; use super::ChannelMonitorUpdateStep; - use crate::{check_added_monitors, check_spends, get_local_commitment_txn, get_monitor, get_route_and_payment_hash}; - use crate::chain::{BestBlock, Confirm}; use crate::chain::channelmonitor::{ChannelMonitor, WithChannelMonitor}; - use crate::chain::package::{weight_offered_htlc, weight_received_htlc, weight_revoked_offered_htlc, weight_revoked_received_htlc, WEIGHT_REVOKED_OUTPUT}; + use crate::chain::package::{ + weight_offered_htlc, weight_received_htlc, weight_revoked_offered_htlc, + weight_revoked_received_htlc, WEIGHT_REVOKED_OUTPUT, + }; use crate::chain::transaction::OutPoint; - use crate::sign::InMemorySigner; - use crate::ln::types::ChannelId; - use crate::types::payment::{PaymentPreimage, PaymentHash}; - use crate::ln::channel_keys::{DelayedPaymentBasepoint, DelayedPaymentKey, HtlcBasepoint, RevocationBasepoint, RevocationKey}; - use crate::ln::chan_utils::{self,HTLCOutputInCommitment, ChannelPublicKeys, ChannelTransactionParameters, HolderCommitmentTransaction, CounterpartyChannelTransactionParameters}; + use crate::chain::{BestBlock, Confirm}; + use crate::io; + use crate::ln::chan_utils::{ + self, ChannelPublicKeys, ChannelTransactionParameters, + CounterpartyChannelTransactionParameters, HTLCOutputInCommitment, + HolderCommitmentTransaction, + }; + use crate::ln::channel_keys::{ + DelayedPaymentBasepoint, DelayedPaymentKey, HtlcBasepoint, RevocationBasepoint, + RevocationKey, + }; use crate::ln::channelmanager::{HTLCSource, PaymentId, RecipientOnionFields}; use crate::ln::functional_test_utils::*; use crate::ln::script::ShutdownScript; - use crate::util::test_utils::{TestLogger, TestBroadcaster, TestFeeEstimator}; - use crate::util::ser::{ReadableArgs, Writeable}; - use crate::util::logger::Logger; + use crate::ln::types::ChannelId; + use crate::sign::InMemorySigner; use crate::sync::Arc; - use crate::io; use crate::types::features::ChannelTypeFeatures; + use crate::types::payment::{PaymentHash, PaymentPreimage}; + use crate::util::logger::Logger; + use crate::util::ser::{ReadableArgs, Writeable}; + use crate::util::test_utils::{TestBroadcaster, TestFeeEstimator, TestLogger}; + use crate::{ + check_added_monitors, check_spends, get_local_commitment_txn, get_monitor, + get_route_and_payment_hash, + }; #[allow(unused_imports)] use crate::prelude::*; use std::str::FromStr; + #[rustfmt::skip] fn do_test_funding_spend_refuses_updates(use_local_txn: bool) { // Previously, monitor updates were allowed freely even after a funding-spend transaction // confirmed. This would allow a race condition where we could receive a payment (including @@ -5598,6 +5779,7 @@ mod tests { } #[test] + #[rustfmt::skip] fn test_prune_preimages() { let secp_ctx = Secp256k1::new(); let logger = Arc::new(TestLogger::new()); @@ -5617,6 +5799,7 @@ mod tests { let dummy_source = HTLCSource::dummy(); + #[rustfmt::skip] macro_rules! preimages_slice_to_htlcs { ($preimages_slice: expr) => { { @@ -5634,6 +5817,7 @@ mod tests { } } } + #[rustfmt::skip] macro_rules! preimages_slice_to_htlc_outputs { ($preimages_slice: expr) => { preimages_slice_to_htlcs!($preimages_slice).into_iter().map(|htlc| (htlc, None)).collect() @@ -5643,6 +5827,7 @@ mod tests { &bitcoin::secp256k1::Message::from_digest([42; 32]), &SecretKey::from_slice(&[42; 32]).unwrap()); + #[rustfmt::skip] macro_rules! test_preimages_exist { ($preimages_slice: expr, $monitor: expr) => { for preimage in $preimages_slice { @@ -5763,6 +5948,7 @@ mod tests { } #[test] + #[rustfmt::skip] fn test_claim_txn_weight_computation() { // We test Claim txn weight, knowing that we want expected weigth and // not actual case to avoid sigs and time-lock delays hell variances. @@ -5772,6 +5958,7 @@ mod tests { let pubkey = PublicKey::from_secret_key(&secp_ctx, &privkey); use crate::ln::channel_keys::{HtlcKey, HtlcBasepoint}; + #[rustfmt::skip] macro_rules! sign_input { ($sighash_parts: expr, $idx: expr, $amount: expr, $weight: expr, $sum_actual_sigs: expr, $opt_anchors: expr) => { let htlc = HTLCOutputInCommitment { @@ -5905,6 +6092,7 @@ mod tests { } #[test] + #[rustfmt::skip] fn test_with_channel_monitor_impl_logger() { let secp_ctx = Secp256k1::new(); let logger = Arc::new(TestLogger::new()); diff --git a/lightning/src/chain/mod.rs b/lightning/src/chain/mod.rs index 7ee7ad9804d..c16ee2519f7 100644 --- a/lightning/src/chain/mod.rs +++ b/lightning/src/chain/mod.rs @@ -1,5 +1,3 @@ -#![cfg_attr(rustfmt, rustfmt_skip)] - // This file is Copyright its original authors, visible in version control // history. // @@ -13,16 +11,16 @@ use bitcoin::block::{Block, Header}; use bitcoin::constants::genesis_block; -use bitcoin::script::{Script, ScriptBuf}; use bitcoin::hash_types::{BlockHash, Txid}; use bitcoin::network::Network; +use bitcoin::script::{Script, ScriptBuf}; use bitcoin::secp256k1::PublicKey; use crate::chain::channelmonitor::{ChannelMonitor, ChannelMonitorUpdate, MonitorEvent}; -use crate::ln::types::ChannelId; -use crate::sign::ecdsa::EcdsaChannelSigner; use crate::chain::transaction::{OutPoint, TransactionData}; use crate::impl_writeable_tlv_based; +use crate::ln::types::ChannelId; +use crate::sign::ecdsa::EcdsaChannelSigner; #[allow(unused_imports)] use crate::prelude::*; @@ -30,9 +28,9 @@ use crate::prelude::*; pub mod chaininterface; pub mod chainmonitor; pub mod channelmonitor; -pub mod transaction; pub(crate) mod onchaintx; pub(crate) mod package; +pub mod transaction; /// The best known block as identified by its hash and height. #[derive(Clone, Copy, Debug, Hash, PartialEq, Eq)] @@ -47,10 +45,7 @@ impl BestBlock { /// Constructs a `BestBlock` that represents the genesis block at height 0 of the given /// network. pub fn from_network(network: Network) -> Self { - BestBlock { - block_hash: genesis_block(network).header.block_hash(), - height: 0, - } + BestBlock { block_hash: genesis_block(network).header.block_hash(), height: 0 } } /// Returns a `BestBlock` as identified by the given block hash and height. @@ -67,7 +62,6 @@ impl_writeable_tlv_based!(BestBlock, { (2, height, required), }); - /// The `Listen` trait is used to notify when blocks have been connected or disconnected from the /// chain. /// @@ -289,7 +283,9 @@ pub trait Watch { /// [`get_outputs_to_watch`]: channelmonitor::ChannelMonitor::get_outputs_to_watch /// [`block_connected`]: channelmonitor::ChannelMonitor::block_connected /// [`block_disconnected`]: channelmonitor::ChannelMonitor::block_disconnected - fn watch_channel(&self, channel_id: ChannelId, monitor: ChannelMonitor) -> Result; + fn watch_channel( + &self, channel_id: ChannelId, monitor: ChannelMonitor, + ) -> Result; /// Updates a channel identified by `channel_id` by applying `update` to its monitor. /// @@ -306,7 +302,9 @@ pub trait Watch { /// [`ChannelMonitorUpdateStatus::UnrecoverableError`], see its documentation for more info. /// /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager - fn update_channel(&self, channel_id: ChannelId, update: &ChannelMonitorUpdate) -> ChannelMonitorUpdateStatus; + fn update_channel( + &self, channel_id: ChannelId, update: &ChannelMonitorUpdate, + ) -> ChannelMonitorUpdateStatus; /// Returns any monitor events since the last call. Subsequent calls must only return new /// events. @@ -317,7 +315,9 @@ pub trait Watch { /// /// For details on asynchronous [`ChannelMonitor`] updating and returning /// [`MonitorEvent::Completed`] here, see [`ChannelMonitorUpdateStatus::InProgress`]. - fn release_pending_monitor_events(&self) -> Vec<(OutPoint, ChannelId, Vec, PublicKey)>; + fn release_pending_monitor_events( + &self, + ) -> Vec<(OutPoint, ChannelId, Vec, PublicKey)>; } /// The `Filter` trait defines behavior for indicating chain activity of interest pertaining to diff --git a/lightning/src/chain/onchaintx.rs b/lightning/src/chain/onchaintx.rs index 2c2039f3e3b..b01291f2e69 100644 --- a/lightning/src/chain/onchaintx.rs +++ b/lightning/src/chain/onchaintx.rs @@ -1,5 +1,3 @@ -#![cfg_attr(rustfmt, rustfmt_skip)] - // This file is Copyright its original authors, visible in version control // history. // @@ -15,37 +13,41 @@ //! building, tracking, bumping and notifications functions. use bitcoin::amount::Amount; +use bitcoin::hash_types::{BlockHash, Txid}; +use bitcoin::hashes::sha256::Hash as Sha256; +use bitcoin::hashes::{Hash, HashEngine}; use bitcoin::locktime::absolute::LockTime; -use bitcoin::transaction::Transaction; -use bitcoin::transaction::OutPoint as BitcoinOutPoint; use bitcoin::script::{Script, ScriptBuf}; -use bitcoin::hashes::{Hash, HashEngine}; -use bitcoin::hashes::sha256::Hash as Sha256; -use bitcoin::hash_types::{Txid, BlockHash}; -use bitcoin::secp256k1::{Secp256k1, ecdsa::Signature}; use bitcoin::secp256k1; +use bitcoin::secp256k1::{ecdsa::Signature, Secp256k1}; +use bitcoin::transaction::OutPoint as BitcoinOutPoint; +use bitcoin::transaction::Transaction; -use crate::chain::chaininterface::{ConfirmationTarget, compute_feerate_sat_per_1000_weight}; -use crate::sign::{EntropySource, HTLCDescriptor, SignerProvider, ecdsa::EcdsaChannelSigner}; -use crate::ln::msgs::DecodeError; -use crate::ln::chan_utils::{self, ChannelTransactionParameters, HTLCOutputInCommitment, HolderCommitmentTransaction}; -use crate::chain::ClaimId; -use crate::chain::chaininterface::{FeeEstimator, BroadcasterInterface, LowerBoundedFeeEstimator}; +use crate::chain::chaininterface::{compute_feerate_sat_per_1000_weight, ConfirmationTarget}; +use crate::chain::chaininterface::{BroadcasterInterface, FeeEstimator, LowerBoundedFeeEstimator}; use crate::chain::channelmonitor::ANTI_REORG_DELAY; use crate::chain::package::{PackageSolvingData, PackageTemplate}; use crate::chain::transaction::MaybeSignedTransaction; +use crate::chain::ClaimId; +use crate::ln::chan_utils::{ + self, ChannelTransactionParameters, HTLCOutputInCommitment, HolderCommitmentTransaction, +}; +use crate::ln::msgs::DecodeError; +use crate::sign::{ecdsa::EcdsaChannelSigner, EntropySource, HTLCDescriptor, SignerProvider}; use crate::util::logger::Logger; -use crate::util::ser::{Readable, ReadableArgs, MaybeReadable, UpgradableRequired, Writer, Writeable}; +use crate::util::ser::{ + MaybeReadable, Readable, ReadableArgs, UpgradableRequired, Writeable, Writer, +}; use crate::io; use crate::prelude::*; use alloc::collections::BTreeMap; use core::cmp; -use core::ops::Deref; use core::mem::replace; use core::mem::swap; +use core::ops::Deref; -const MAX_ALLOC_SIZE: usize = 64*1024; +const MAX_ALLOC_SIZE: usize = 64 * 1024; /// An entry for an [`OnchainEvent`], stating the block height when the event was observed and the /// transaction causing it. @@ -77,18 +79,14 @@ enum OnchainEvent { /// as the request. This claim can either be ours or from the counterparty. Once the claiming /// transaction has met [`ANTI_REORG_DELAY`] confirmations, we consider it final and remove the /// pending request. - Claim { - claim_id: ClaimId, - }, + Claim { claim_id: ClaimId }, /// The counterparty has claimed an outpoint from one of our pending requests through a /// different transaction than ours. If our transaction was attempting to claim multiple /// outputs, we need to drop the outpoint claimed by the counterparty and regenerate a new claim /// transaction for ourselves. We keep tracking, separately, the outpoint claimed by the /// counterparty up to [`ANTI_REORG_DELAY`] confirmations to ensure we attempt to re-claim it /// if the counterparty's claim is reorged from the chain. - ContentiousOutpoint { - package: PackageTemplate, - } + ContentiousOutpoint { package: PackageTemplate }, } impl Writeable for OnchainEventEntry { @@ -104,6 +102,7 @@ impl Writeable for OnchainEventEntry { } impl MaybeReadable for OnchainEventEntry { + #[rustfmt::skip] fn read(reader: &mut R) -> Result, DecodeError> { let mut txid = Txid::all_zeros(); let mut height = 0; @@ -129,6 +128,7 @@ impl_writeable_tlv_based_enum_upgradable!(OnchainEvent, ); impl Readable for Option>> { + #[rustfmt::skip] fn read(reader: &mut R) -> Result { match Readable::read(reader)? { 0u8 => Ok(None), @@ -221,8 +221,8 @@ pub(crate) enum FeerateStrategy { /// do RBF bumping if possible. #[derive(Clone)] pub struct OnchainTxHandler { - channel_value_satoshis: u64, // Deprecated as of 0.2. - channel_keys_id: [u8; 32], // Deprecated as of 0.2. + channel_value_satoshis: u64, // Deprecated as of 0.2. + channel_keys_id: [u8; 32], // Deprecated as of 0.2. destination_script: ScriptBuf, // Deprecated as of 0.2. holder_commitment: HolderCommitmentTransaction, prev_holder_commitment: Option, @@ -277,6 +277,7 @@ pub struct OnchainTxHandler { } impl PartialEq for OnchainTxHandler { + #[rustfmt::skip] fn eq(&self, other: &Self) -> bool { // `signer`, `secp_ctx`, and `pending_claim_events` are excluded on purpose. self.channel_value_satoshis == other.channel_value_satoshis && @@ -296,6 +297,7 @@ const SERIALIZATION_VERSION: u8 = 1; const MIN_SERIALIZATION_VERSION: u8 = 1; impl OnchainTxHandler { + #[rustfmt::skip] pub(crate) fn write(&self, writer: &mut W) -> Result<(), io::Error> { write_ver_prefix!(writer, SERIALIZATION_VERSION, MIN_SERIALIZATION_VERSION); @@ -343,7 +345,10 @@ impl OnchainTxHandler { } } -impl<'a, 'b, ES: EntropySource, SP: SignerProvider> ReadableArgs<(&'a ES, &'b SP, u64, [u8; 32])> for OnchainTxHandler { +impl<'a, 'b, ES: EntropySource, SP: SignerProvider> ReadableArgs<(&'a ES, &'b SP, u64, [u8; 32])> + for OnchainTxHandler +{ + #[rustfmt::skip] fn read(reader: &mut R, args: (&'a ES, &'b SP, u64, [u8; 32])) -> Result { let entropy_source = args.0; let signer_provider = args.1; @@ -438,7 +443,7 @@ impl OnchainTxHandler { pub(crate) fn new( channel_value_satoshis: u64, channel_keys_id: [u8; 32], destination_script: ScriptBuf, signer: ChannelSigner, channel_parameters: ChannelTransactionParameters, - holder_commitment: HolderCommitmentTransaction, secp_ctx: Secp256k1 + holder_commitment: HolderCommitmentTransaction, secp_ctx: Secp256k1, ) -> Self { OnchainTxHandler { channel_value_satoshis, @@ -476,6 +481,7 @@ impl OnchainTxHandler { /// feerate changes between blocks, and ensuring reliability if broadcasting fails. We recommend /// invoking this every 30 seconds, or lower if running in an environment with spotty /// connections, like on mobile. + #[rustfmt::skip] pub(super) fn rebroadcast_pending_claims( &mut self, current_height: u32, feerate_strategy: FeerateStrategy, broadcaster: &B, conf_target: ConfirmationTarget, destination_script: &Script, @@ -532,8 +538,7 @@ impl OnchainTxHandler { /// Returns true if we are currently tracking any pending claim requests that are not fully /// confirmed yet. - pub(super) fn has_pending_claims(&self) -> bool - { + pub(super) fn has_pending_claims(&self) -> bool { self.pending_claim_requests.len() != 0 } @@ -545,6 +550,7 @@ impl OnchainTxHandler { /// /// Panics if there are signing errors, because signing operations in reaction to on-chain /// events are not expected to fail, and if they do, we may lose funds. + #[rustfmt::skip] fn generate_claim( &mut self, cur_height: u32, cached_request: &PackageTemplate, feerate_strategy: &FeerateStrategy, conf_target: ConfirmationTarget, @@ -713,6 +719,7 @@ impl OnchainTxHandler { None } + #[rustfmt::skip] pub fn abandon_claim(&mut self, outpoint: &BitcoinOutPoint) { let claim_id = self.claimable_outpoints.get(outpoint).map(|(claim_id, _)| *claim_id) .or_else(|| { @@ -741,6 +748,7 @@ impl OnchainTxHandler { /// `conf_height` represents the height at which the request was generated. This /// does not need to equal the current blockchain tip height, which should be provided via /// `cur_height`, however it must never be higher than `cur_height`. + #[rustfmt::skip] pub(super) fn update_claims_view_from_requests( &mut self, mut requests: Vec, conf_height: u32, cur_height: u32, broadcaster: &B, conf_target: ConfirmationTarget, destination_script: &Script, @@ -895,6 +903,7 @@ impl OnchainTxHandler { /// `conf_height` represents the height at which the transactions in `txn_matched` were /// confirmed. This does not need to equal the current blockchain tip height, which should be /// provided via `cur_height`, however it must never be higher than `cur_height`. + #[rustfmt::skip] pub(super) fn update_claims_view_from_matched_txn( &mut self, txn_matched: &[&Transaction], conf_height: u32, conf_hash: BlockHash, cur_height: u32, broadcaster: &B, conf_target: ConfirmationTarget, @@ -933,6 +942,7 @@ impl OnchainTxHandler { } } + #[rustfmt::skip] macro_rules! clean_claim_request_after_safety_delay { () => { let entry = OnchainEventEntry { @@ -1081,6 +1091,7 @@ impl OnchainTxHandler { } } + #[rustfmt::skip] pub(super) fn transaction_unconfirmed( &mut self, txid: &Txid, @@ -1108,6 +1119,7 @@ impl OnchainTxHandler { } } + #[rustfmt::skip] pub(super) fn block_disconnected( &mut self, height: u32, broadcaster: B, conf_target: ConfirmationTarget, destination_script: &Script, fee_estimator: &LowerBoundedFeeEstimator, logger: &L, @@ -1190,6 +1202,7 @@ impl OnchainTxHandler { self.claimable_outpoints.get(outpoint).is_some() } + #[rustfmt::skip] pub(crate) fn get_relevant_txids(&self) -> Vec<(Txid, u32, Option)> { let mut txids: Vec<(Txid, u32, Option)> = self.onchain_events_awaiting_threshold_conf .iter() @@ -1243,6 +1256,7 @@ mod tests { // immediately while claims with locktime greater than the current height are only broadcast // once the locktime is reached. #[test] + #[rustfmt::skip] fn test_broadcast_height() { let secp_ctx = Secp256k1::new(); let signer = InMemorySigner::new( diff --git a/lightning/src/chain/package.rs b/lightning/src/chain/package.rs index 9c0a19a187d..10ebf28b3a4 100644 --- a/lightning/src/chain/package.rs +++ b/lightning/src/chain/package.rs @@ -1,5 +1,3 @@ -#![cfg_attr(rustfmt, rustfmt_skip)] - // This file is Copyright its original authors, visible in version control // history. // @@ -13,36 +11,38 @@ //! packages are attached metadata, guiding their aggregable or fee-bumping re-schedule. This file //! also includes witness weight computation and fee computation methods. - -use bitcoin::{Sequence, Witness}; use bitcoin::amount::Amount; use bitcoin::constants::WITNESS_SCALE_FACTOR; +use bitcoin::hash_types::Txid; use bitcoin::locktime::absolute::LockTime; -use bitcoin::transaction::{TxOut,TxIn, Transaction}; -use bitcoin::transaction::OutPoint as BitcoinOutPoint; use bitcoin::script::{Script, ScriptBuf}; -use bitcoin::hash_types::Txid; -use bitcoin::secp256k1::{SecretKey, PublicKey}; +use bitcoin::secp256k1::{PublicKey, SecretKey}; use bitcoin::sighash::EcdsaSighashType; +use bitcoin::transaction::OutPoint as BitcoinOutPoint; use bitcoin::transaction::Version; +use bitcoin::transaction::{Transaction, TxIn, TxOut}; +use bitcoin::{Sequence, Witness}; -use crate::sign::{ChannelDerivationParameters, HTLCDescriptor}; -use crate::types::payment::PaymentPreimage; +use crate::chain::chaininterface::{ + compute_feerate_sat_per_1000_weight, ConfirmationTarget, FeeEstimator, + FEERATE_FLOOR_SATS_PER_KW, INCREMENTAL_RELAY_FEE_SAT_PER_1000_WEIGHT, +}; +use crate::chain::channelmonitor::COUNTERPARTY_CLAIMABLE_WITHIN_BLOCKS_PINNABLE; +use crate::chain::onchaintx::{FeerateStrategy, OnchainTxHandler}; +use crate::chain::transaction::MaybeSignedTransaction; use crate::ln::chan_utils::{ - self, ChannelTransactionParameters, HolderCommitmentTransaction, TxCreationKeys, - HTLCOutputInCommitment, + self, ChannelTransactionParameters, HTLCOutputInCommitment, HolderCommitmentTransaction, + TxCreationKeys, }; -use crate::types::features::ChannelTypeFeatures; use crate::ln::channel_keys::{DelayedPaymentBasepoint, HtlcBasepoint}; use crate::ln::channelmanager::MIN_CLTV_EXPIRY_DELTA; use crate::ln::msgs::DecodeError; -use crate::chain::channelmonitor::COUNTERPARTY_CLAIMABLE_WITHIN_BLOCKS_PINNABLE; -use crate::chain::chaininterface::{FeeEstimator, ConfirmationTarget, INCREMENTAL_RELAY_FEE_SAT_PER_1000_WEIGHT, compute_feerate_sat_per_1000_weight, FEERATE_FLOOR_SATS_PER_KW}; -use crate::chain::transaction::MaybeSignedTransaction; use crate::sign::ecdsa::EcdsaChannelSigner; -use crate::chain::onchaintx::{FeerateStrategy, OnchainTxHandler}; +use crate::sign::{ChannelDerivationParameters, HTLCDescriptor}; +use crate::types::features::ChannelTypeFeatures; +use crate::types::payment::PaymentPreimage; use crate::util::logger::Logger; -use crate::util::ser::{Readable, ReadableArgs, Writer, Writeable, RequiredWrapper}; +use crate::util::ser::{Readable, ReadableArgs, RequiredWrapper, Writeable, Writer}; use crate::io; use core::cmp; @@ -53,9 +53,9 @@ use crate::prelude::*; use super::chaininterface::LowerBoundedFeeEstimator; -const MAX_ALLOC_SIZE: usize = 64*1024; - +const MAX_ALLOC_SIZE: usize = 64 * 1024; +#[rustfmt::skip] pub(crate) fn weight_revoked_offered_htlc(channel_type_features: &ChannelTypeFeatures) -> u64 { // number_of_witness_elements + sig_length + revocation_sig + pubkey_length + revocationpubkey + witness_script_length + witness_script const WEIGHT_REVOKED_OFFERED_HTLC: u64 = 1 + 1 + 73 + 1 + 33 + 1 + 133; @@ -63,6 +63,7 @@ pub(crate) fn weight_revoked_offered_htlc(channel_type_features: &ChannelTypeFea if channel_type_features.supports_anchors_zero_fee_htlc_tx() { WEIGHT_REVOKED_OFFERED_HTLC_ANCHORS } else { WEIGHT_REVOKED_OFFERED_HTLC } } +#[rustfmt::skip] pub(crate) fn weight_revoked_received_htlc(channel_type_features: &ChannelTypeFeatures) -> u64 { // number_of_witness_elements + sig_length + revocation_sig + pubkey_length + revocationpubkey + witness_script_length + witness_script const WEIGHT_REVOKED_RECEIVED_HTLC: u64 = 1 + 1 + 73 + 1 + 33 + 1 + 139; @@ -70,6 +71,7 @@ pub(crate) fn weight_revoked_received_htlc(channel_type_features: &ChannelTypeFe if channel_type_features.supports_anchors_zero_fee_htlc_tx() { WEIGHT_REVOKED_RECEIVED_HTLC_ANCHORS } else { WEIGHT_REVOKED_RECEIVED_HTLC } } +#[rustfmt::skip] pub(crate) fn weight_offered_htlc(channel_type_features: &ChannelTypeFeatures) -> u64 { // number_of_witness_elements + sig_length + counterpartyhtlc_sig + preimage_length + preimage + witness_script_length + witness_script const WEIGHT_OFFERED_HTLC: u64 = 1 + 1 + 73 + 1 + 32 + 1 + 133; @@ -77,6 +79,7 @@ pub(crate) fn weight_offered_htlc(channel_type_features: &ChannelTypeFeatures) - if channel_type_features.supports_anchors_zero_fee_htlc_tx() { WEIGHT_OFFERED_HTLC_ANCHORS } else { WEIGHT_OFFERED_HTLC } } +#[rustfmt::skip] pub(crate) fn weight_received_htlc(channel_type_features: &ChannelTypeFeatures) -> u64 { // number_of_witness_elements + sig_length + counterpartyhtlc_sig + empty_vec_length + empty_vec + witness_script_length + witness_script const WEIGHT_RECEIVED_HTLC: u64 = 1 + 1 + 73 + 1 + 1 + 1 + 139; @@ -85,6 +88,7 @@ pub(crate) fn weight_received_htlc(channel_type_features: &ChannelTypeFeatures) } /// Verifies deserializable channel type features +#[rustfmt::skip] pub(crate) fn verify_channel_type_features(channel_type_features: &Option, additional_permitted_features: Option<&ChannelTypeFeatures>) -> Result<(), DecodeError> { if let Some(features) = channel_type_features.as_ref() { if features.requires_unknown_bits() { @@ -142,6 +146,7 @@ pub(crate) struct RevokedOutput { } impl RevokedOutput { + #[rustfmt::skip] pub(crate) fn build( per_commitment_point: PublicKey, per_commitment_key: SecretKey, amount: Amount, is_counterparty_balance_on_anchors: bool, channel_parameters: ChannelTransactionParameters, @@ -277,6 +282,7 @@ impl CounterpartyOfferedHTLCOutput { } impl Writeable for CounterpartyOfferedHTLCOutput { + #[rustfmt::skip] fn write(&self, writer: &mut W) -> Result<(), io::Error> { let legacy_deserialization_prevention_marker = chan_utils::legacy_deserialization_prevention_marker_for_channel_type_features(&self.channel_type_features); write_tlv_fields!(writer, { @@ -369,6 +375,7 @@ impl CounterpartyReceivedHTLCOutput { } impl Writeable for CounterpartyReceivedHTLCOutput { + #[rustfmt::skip] fn write(&self, writer: &mut W) -> Result<(), io::Error> { let legacy_deserialization_prevention_marker = chan_utils::legacy_deserialization_prevention_marker_for_channel_type_features(&self.channel_type_features); write_tlv_fields!(writer, { @@ -436,6 +443,7 @@ pub(crate) struct HolderHTLCOutput { } impl HolderHTLCOutput { + #[rustfmt::skip] pub(crate) fn build(htlc_descriptor: HTLCDescriptor) -> Self { let amount_msat = htlc_descriptor.htlc.amount_msat; let channel_type_features = htlc_descriptor.channel_derivation_parameters @@ -457,6 +465,7 @@ impl HolderHTLCOutput { } } + #[rustfmt::skip] pub(crate) fn get_htlc_descriptor( &self, onchain_tx_handler: &OnchainTxHandler, outp: &::bitcoin::OutPoint, ) -> Option { @@ -499,6 +508,7 @@ impl HolderHTLCOutput { .or_else(|| onchain_tx_handler.prev_holder_commitment_tx().and_then(|c| get_htlc_descriptor(c))) } + #[rustfmt::skip] pub(crate) fn get_maybe_signed_htlc_tx( &self, onchain_tx_handler: &mut OnchainTxHandler, outp: &::bitcoin::OutPoint, ) -> Option { @@ -535,6 +545,7 @@ impl HolderHTLCOutput { } impl Writeable for HolderHTLCOutput { + #[rustfmt::skip] fn write(&self, writer: &mut W) -> Result<(), io::Error> { let legacy_deserialization_prevention_marker = chan_utils::legacy_deserialization_prevention_marker_for_channel_type_features(&self.channel_type_features); write_tlv_fields!(writer, { @@ -595,10 +606,10 @@ pub(crate) struct HolderFundingOutput { pub(crate) channel_parameters: Option, } - impl HolderFundingOutput { pub(crate) fn build( - commitment_tx: HolderCommitmentTransaction, channel_parameters: ChannelTransactionParameters, + commitment_tx: HolderCommitmentTransaction, + channel_parameters: ChannelTransactionParameters, ) -> Self { let funding_redeemscript = channel_parameters.make_funding_redeemscript(); let funding_amount_sats = channel_parameters.channel_value_satoshis; @@ -612,6 +623,7 @@ impl HolderFundingOutput { } } + #[rustfmt::skip] pub(crate) fn get_maybe_signed_commitment_tx( &self, onchain_tx_handler: &mut OnchainTxHandler, ) -> MaybeSignedTransaction { @@ -632,6 +644,7 @@ impl HolderFundingOutput { } impl Writeable for HolderFundingOutput { + #[rustfmt::skip] fn write(&self, writer: &mut W) -> Result<(), io::Error> { let legacy_deserialization_prevention_marker = chan_utils::legacy_deserialization_prevention_marker_for_channel_type_features(&self.channel_type_features); write_tlv_fields!(writer, { @@ -693,6 +706,7 @@ pub(crate) enum PackageSolvingData { } impl PackageSolvingData { + #[rustfmt::skip] fn amount(&self) -> u64 { let amt = match self { PackageSolvingData::RevokedOutput(ref outp) => outp.amount.to_sat(), @@ -710,6 +724,7 @@ impl PackageSolvingData { }; amt } + #[rustfmt::skip] fn weight(&self) -> usize { match self { PackageSolvingData::RevokedOutput(ref outp) => outp.weight as usize, @@ -733,6 +748,7 @@ impl PackageSolvingData { /// Checks if this and `other` are spending types of inputs which could have descended from the /// same commitment transaction(s) and thus could both be spent without requiring a /// double-spend. + #[rustfmt::skip] fn is_possibly_from_same_tx_tree(&self, other: &PackageSolvingData) -> bool { match self { PackageSolvingData::RevokedOutput(_)|PackageSolvingData::RevokedHTLCOutput(_) => { @@ -761,6 +777,7 @@ impl PackageSolvingData { } } + #[rustfmt::skip] fn as_tx_input(&self, previous_output: BitcoinOutPoint) -> TxIn { let sequence = match self { PackageSolvingData::RevokedOutput(_) => Sequence::ENABLE_RBF_NO_LOCKTIME, @@ -787,6 +804,7 @@ impl PackageSolvingData { witness: Witness::new(), } } + #[rustfmt::skip] fn finalize_input(&self, bumped_tx: &mut Transaction, i: usize, onchain_handler: &mut OnchainTxHandler) -> bool { let channel_parameters = onchain_handler.channel_parameters(); match self { @@ -901,6 +919,7 @@ impl PackageSolvingData { } true } + #[rustfmt::skip] fn get_maybe_finalized_tx(&self, outpoint: &BitcoinOutPoint, onchain_handler: &mut OnchainTxHandler) -> Option { match self { PackageSolvingData::HolderHTLCOutput(ref outp) => { @@ -915,6 +934,7 @@ impl PackageSolvingData { } /// Some output types are locked with CHECKLOCKTIMEVERIFY and the spending transaction must /// have a minimum locktime, which is returned here. + #[rustfmt::skip] fn minimum_locktime(&self) -> Option { match self { PackageSolvingData::CounterpartyReceivedHTLCOutput(ref outp) => Some(outp.htlc.cltv_expiry), @@ -935,6 +955,7 @@ impl PackageSolvingData { } } + #[rustfmt::skip] fn map_output_type_flags(&self) -> PackageMalleability { // We classify claims into not-mergeable (i.e. transactions that have to be broadcasted // as-is) or merge-able (i.e. transactions we can merge with others and claim in batches), @@ -1038,6 +1059,7 @@ pub struct PackageTemplate { } impl PackageTemplate { + #[rustfmt::skip] pub(crate) fn can_merge_with(&self, other: &PackageTemplate, cur_height: u32) -> bool { match (self.malleability, other.malleability) { (PackageMalleability::Untractable, _) => false, @@ -1125,6 +1147,7 @@ impl PackageTemplate { pub(crate) fn inputs(&self) -> impl ExactSizeIterator { self.inputs.iter().map(|(_, i)| i) } + #[rustfmt::skip] pub(crate) fn split_package(&mut self, split_outp: &BitcoinOutPoint) -> Option { match self.malleability { PackageMalleability::Malleable(cluster) => { @@ -1156,7 +1179,9 @@ impl PackageTemplate { } } } - pub(crate) fn merge_package(&mut self, mut merge_from: PackageTemplate, cur_height: u32) -> Result<(), PackageTemplate> { + pub(crate) fn merge_package( + &mut self, mut merge_from: PackageTemplate, cur_height: u32, + ) -> Result<(), PackageTemplate> { if !self.can_merge_with(&merge_from, cur_height) { return Err(merge_from); } @@ -1182,6 +1207,7 @@ impl PackageTemplate { } amounts } + #[rustfmt::skip] fn signed_locktime(&self) -> Option { let signed_locktime = self.inputs.iter().find_map(|(_, outp)| outp.signed_locktime()); #[cfg(debug_assertions)] @@ -1190,6 +1216,7 @@ impl PackageTemplate { } signed_locktime } + #[rustfmt::skip] pub(crate) fn package_locktime(&self, current_height: u32) -> u32 { let minimum_locktime = self.inputs.iter().filter_map(|(_, outp)| outp.minimum_locktime()).max(); @@ -1214,6 +1241,7 @@ impl PackageTemplate { let output_weight = (8 + 1 + destination_script.len()) * WITNESS_SCALE_FACTOR; (inputs_weight + witnesses_weight + transaction_weight + output_weight) as u64 } + #[rustfmt::skip] pub(crate) fn construct_malleable_package_with_external_funding( &self, onchain_handler: &mut OnchainTxHandler, ) -> Option> { @@ -1232,6 +1260,7 @@ impl PackageTemplate { } htlcs } + #[rustfmt::skip] pub(crate) fn maybe_finalize_malleable_package( &self, current_height: u32, onchain_handler: &mut OnchainTxHandler, value: Amount, destination_script: ScriptBuf, logger: &L @@ -1255,6 +1284,7 @@ impl PackageTemplate { } Some(MaybeSignedTransaction(bumped_tx)) } + #[rustfmt::skip] pub(crate) fn maybe_finalize_untractable_package( &self, onchain_handler: &mut OnchainTxHandler, logger: &L, ) -> Option { @@ -1272,6 +1302,7 @@ impl PackageTemplate { /// /// As the deadline with which to get a claim confirmed approaches, the rate at which the timer /// ticks increases. + #[rustfmt::skip] pub(crate) fn get_height_timer(&self, current_height: u32) -> u32 { let mut height_timer = current_height + LOW_FREQUENCY_BUMP_INTERVAL; let timer_for_target_conf = |target_conf| -> u32 { @@ -1349,6 +1380,7 @@ impl PackageTemplate { /// Returns value in satoshis to be included as package outgoing output amount and feerate /// which was used to generate the value. Will not return less than `dust_limit_sats` for the /// value. + #[rustfmt::skip] pub(crate) fn compute_package_output( &self, predicted_weight: u64, dust_limit_sats: u64, feerate_strategy: &FeerateStrategy, conf_target: ConfirmationTarget, fee_estimator: &LowerBoundedFeeEstimator, logger: &L, @@ -1376,6 +1408,7 @@ impl PackageTemplate { } /// Computes a feerate based on the given confirmation target and feerate strategy. + #[rustfmt::skip] pub(crate) fn compute_package_feerate( &self, fee_estimator: &LowerBoundedFeeEstimator, conf_target: ConfirmationTarget, feerate_strategy: &FeerateStrategy, @@ -1409,6 +1442,7 @@ impl PackageTemplate { /// Determines whether a package contains an input which must have additional external inputs /// attached to help the spending transaction reach confirmation. + #[rustfmt::skip] pub(crate) fn requires_external_funding(&self) -> bool { self.inputs.iter().find(|input| match input.1 { PackageSolvingData::HolderFundingOutput(ref outp) => outp.channel_type_features.supports_anchors_zero_fee_htlc_tx(), @@ -1417,7 +1451,10 @@ impl PackageTemplate { }).is_some() } - pub (crate) fn build_package(txid: Txid, vout: u32, input_solving_data: PackageSolvingData, counterparty_spendable_height: u32) -> Self { + pub(crate) fn build_package( + txid: Txid, vout: u32, input_solving_data: PackageSolvingData, + counterparty_spendable_height: u32, + ) -> Self { let malleability = PackageSolvingData::map_output_type_flags(&input_solving_data); let inputs = vec![(BitcoinOutPoint { txid, vout }, input_solving_data)]; PackageTemplate { @@ -1449,6 +1486,7 @@ impl Writeable for PackageTemplate { } impl Readable for PackageTemplate { + #[rustfmt::skip] fn read(reader: &mut R) -> Result { let inputs_count = ::read(reader)?; let mut inputs: Vec<(BitcoinOutPoint, PackageSolvingData)> = Vec::with_capacity(cmp::min(inputs_count as usize, MAX_ALLOC_SIZE / 128)); @@ -1499,6 +1537,7 @@ impl Readable for PackageTemplate { /// If the proposed fee is less than the available spent output's values, we return the proposed /// fee and the corresponding updated feerate. If fee is under [`FEERATE_FLOOR_SATS_PER_KW`], /// we return nothing. +#[rustfmt::skip] fn compute_fee_from_spent_amounts( input_amounts: u64, predicted_weight: u64, conf_target: ConfirmationTarget, fee_estimator: &LowerBoundedFeeEstimator, logger: &L ) -> Option<(u64, u64)> @@ -1524,6 +1563,7 @@ fn compute_fee_from_spent_amounts( /// the previous feerate. If a feerate bump did happen, we also verify that those bumping heuristics /// respect BIP125 rules 3) and 4) and if required adjust the new fee to meet the RBF policy /// requirement. +#[rustfmt::skip] fn feerate_bump( predicted_weight: u64, input_amounts: u64, dust_limit_sats: u64, previous_feerate: u64, feerate_strategy: &FeerateStrategy, conf_target: ConfirmationTarget, @@ -1596,13 +1636,17 @@ where #[cfg(test)] mod tests { - use crate::chain::package::{CounterpartyOfferedHTLCOutput, CounterpartyReceivedHTLCOutput, HolderFundingOutput, HolderHTLCOutput, PackageTemplate, PackageSolvingData, RevokedHTLCOutput, RevokedOutput, WEIGHT_REVOKED_OUTPUT, weight_offered_htlc, weight_received_htlc, feerate_bump}; + use crate::chain::package::{ + feerate_bump, weight_offered_htlc, weight_received_htlc, CounterpartyOfferedHTLCOutput, + CounterpartyReceivedHTLCOutput, HolderFundingOutput, HolderHTLCOutput, PackageSolvingData, + PackageTemplate, RevokedHTLCOutput, RevokedOutput, WEIGHT_REVOKED_OUTPUT, + }; use crate::chain::Txid; use crate::ln::chan_utils::{ - ChannelTransactionParameters, HolderCommitmentTransaction, HTLCOutputInCommitment, + ChannelTransactionParameters, HTLCOutputInCommitment, HolderCommitmentTransaction, }; - use crate::types::payment::{PaymentPreimage, PaymentHash}; use crate::sign::{ChannelDerivationParameters, HTLCDescriptor}; + use crate::types::payment::{PaymentHash, PaymentPreimage}; use bitcoin::absolute::LockTime; use bitcoin::amount::Amount; @@ -1614,13 +1658,16 @@ mod tests { use bitcoin::hex::FromHex; - use bitcoin::secp256k1::{PublicKey,SecretKey}; - use bitcoin::secp256k1::Secp256k1; - use crate::chain::chaininterface::{ConfirmationTarget, FeeEstimator, FEERATE_FLOOR_SATS_PER_KW, LowerBoundedFeeEstimator}; + use crate::chain::chaininterface::{ + ConfirmationTarget, FeeEstimator, LowerBoundedFeeEstimator, FEERATE_FLOOR_SATS_PER_KW, + }; use crate::chain::onchaintx::FeerateStrategy; use crate::types::features::ChannelTypeFeatures; use crate::util::test_utils::TestLogger; + use bitcoin::secp256k1::Secp256k1; + use bitcoin::secp256k1::{PublicKey, SecretKey}; + #[rustfmt::skip] fn fake_txid(n: u64) -> Txid { Transaction { version: Version(0), @@ -1633,6 +1680,7 @@ mod tests { }.compute_txid() } + #[rustfmt::skip] macro_rules! dumb_revk_output { ($is_counterparty_balance_on_anchors: expr) => { { @@ -1648,6 +1696,7 @@ mod tests { } } + #[rustfmt::skip] macro_rules! dumb_revk_htlc_output { () => { { @@ -1666,6 +1715,7 @@ mod tests { } } + #[rustfmt::skip] macro_rules! dumb_counterparty_received_output { ($amt: expr, $expiry: expr, $features: expr) => { { @@ -1683,6 +1733,7 @@ mod tests { } } + #[rustfmt::skip] macro_rules! dumb_counterparty_offered_output { ($amt: expr, $features: expr) => { { @@ -1701,6 +1752,7 @@ mod tests { } } + #[rustfmt::skip] macro_rules! dumb_accepted_htlc_output { ($features: expr) => { { @@ -1736,6 +1788,7 @@ mod tests { } } + #[rustfmt::skip] macro_rules! dumb_offered_htlc_output { ($cltv_expiry: expr, $features: expr) => { { @@ -1770,6 +1823,7 @@ mod tests { } } + #[rustfmt::skip] macro_rules! dumb_funding_output { () => {{ let commitment_tx = HolderCommitmentTransaction::dummy(0, Vec::new()); @@ -1782,6 +1836,7 @@ mod tests { } #[test] + #[rustfmt::skip] fn test_merge_package_untractable_funding_output() { let funding_outp = dumb_funding_output!(); let htlc_outp = dumb_accepted_htlc_output!(ChannelTypeFeatures::anchors_zero_htlc_fee_and_dependencies()); @@ -1797,6 +1852,7 @@ mod tests { } #[test] + #[rustfmt::skip] fn test_merge_empty_package() { let revk_outp = dumb_revk_htlc_output!(); @@ -1808,6 +1864,7 @@ mod tests { } #[test] + #[rustfmt::skip] fn test_merge_package_different_signed_locktimes() { // Malleable HTLC transactions are signed over the locktime, and can't be aggregated with // different locktimes. @@ -1831,6 +1888,7 @@ mod tests { } #[test] + #[rustfmt::skip] fn test_merge_package_different_effective_locktimes() { // Spends of outputs can have different minimum locktimes, and are not mergeable if they are in the // future. @@ -1856,6 +1914,7 @@ mod tests { } #[test] + #[rustfmt::skip] fn test_merge_package_holder_htlc_output_clusters() { // Signed locktimes of 0. let unpinnable_1 = dumb_accepted_htlc_output!(ChannelTypeFeatures::anchors_zero_htlc_fee_and_dependencies()); @@ -1915,6 +1974,7 @@ mod tests { #[test] #[should_panic] + #[rustfmt::skip] fn test_merge_package_different_tx_trees() { let offered_htlc = dumb_offered_htlc_output!(900, ChannelTypeFeatures::anchors_zero_htlc_fee_and_dependencies()); let mut offered_htlc_package = PackageTemplate::build_package(fake_txid(1), 0, offered_htlc.clone(), 0); @@ -1926,6 +1986,7 @@ mod tests { } #[test] + #[rustfmt::skip] fn test_package_split_malleable() { let revk_outp_one = dumb_revk_output!(false); let revk_outp_two = dumb_revk_output!(false); @@ -1950,6 +2011,7 @@ mod tests { } #[test] + #[rustfmt::skip] fn test_package_split_untractable() { let htlc_outp_one = dumb_accepted_htlc_output!(ChannelTypeFeatures::only_static_remote_key()); @@ -1969,6 +2031,7 @@ mod tests { } #[test] + #[rustfmt::skip] fn test_package_amounts() { let counterparty_outp = dumb_counterparty_received_output!(1_000_000, 1000, ChannelTypeFeatures::only_static_remote_key()); @@ -1977,6 +2040,7 @@ mod tests { } #[test] + #[rustfmt::skip] fn test_package_weight() { // (nVersion (4) + nLocktime (4) + count_tx_in (1) + prevout (36) + sequence (4) + script_length (1) + count_tx_out (1) + value (8) + var_int (1)) * WITNESS_SCALE_FACTOR + witness marker (2) let weight_sans_output = (4 + 4 + 1 + 36 + 4 + 1 + 1 + 8 + 1) * WITNESS_SCALE_FACTOR as u64 + 2; @@ -2015,6 +2079,7 @@ mod tests { } #[test] + #[rustfmt::skip] fn test_feerate_bump() { let sat_per_kw = FEERATE_FLOOR_SATS_PER_KW; let test_fee_estimator = &TestFeeEstimator { sat_per_kw }; diff --git a/lightning/src/chain/transaction.rs b/lightning/src/chain/transaction.rs index f7cd9783589..fcbe50ce0a6 100644 --- a/lightning/src/chain/transaction.rs +++ b/lightning/src/chain/transaction.rs @@ -1,5 +1,3 @@ -#![cfg_attr(rustfmt, rustfmt_skip)] - // This file is Copyright its original authors, visible in version control // history. // @@ -62,6 +60,7 @@ impl OutPoint { /// /// This is not exported to bindings users as the same type is used universally in the C bindings /// for all outpoints + #[rustfmt::skip] pub fn into_bitcoin_outpoint(self) -> BitcoinOutPoint { BitcoinOutPoint { txid: self.txid, @@ -92,11 +91,12 @@ mod tests { use crate::chain::transaction::OutPoint; use crate::ln::types::ChannelId; - use bitcoin::transaction::Transaction; use bitcoin::consensus::encode; use bitcoin::hex::FromHex; + use bitcoin::transaction::Transaction; #[test] + #[rustfmt::skip] fn test_channel_id_calculation() { let tx: Transaction = encode::deserialize(&>::from_hex("020000000001010e0adef48412e4361325ac1c6e36411299ab09d4f083b9d8ddb55fbc06e1b0c00000000000feffffff0220a1070000000000220020f81d95e040bd0a493e38bae27bff52fe2bb58b93b293eb579c01c31b05c5af1dc072cfee54a3000016001434b1d6211af5551905dc2642d05f5b04d25a8fe80247304402207f570e3f0de50546aad25a872e3df059d277e776dda4269fa0d2cc8c2ee6ec9a022054e7fae5ca94d47534c86705857c24ceea3ad51c69dd6051c5850304880fc43a012103cb11a1bacc223d98d91f1946c6752e358a5eb1a1c983b3e6fb15378f453b76bd00000000").unwrap()[..]).unwrap(); assert_eq!(&ChannelId::v1_from_funding_outpoint(OutPoint { diff --git a/lightning/src/lib.rs b/lightning/src/lib.rs index 4b4aed5e673..8f94f99c721 100644 --- a/lightning/src/lib.rs +++ b/lightning/src/lib.rs @@ -1,5 +1,3 @@ -#![cfg_attr(rustfmt, rustfmt_skip)] - // This file is Copyright its original authors, visible in version control // history. // @@ -32,18 +30,14 @@ //! * `grind_signatures` #![cfg_attr(not(any(test, fuzzing, feature = "_test_utils")), deny(missing_docs))] - #![deny(rustdoc::broken_intra_doc_links)] #![deny(rustdoc::private_intra_doc_links)] - // In general, rust is absolutely horrid at supporting users doing things like, // for example, compiling Rust code for real environments. Disable useless lints // that don't do anything but annoy us and cant actually ever be resolved. #![allow(bare_trait_objects)] #![allow(ellipsis_inclusive_range_patterns)] - #![cfg_attr(docsrs, feature(doc_auto_cfg))] - #![cfg_attr(all(not(feature = "std"), not(test)), no_std)] #[cfg(all(fuzzing, test))] @@ -61,24 +55,28 @@ pub extern crate lightning_invoice as bolt11_invoice; #[cfg(any(test, feature = "std"))] extern crate core; -#[cfg(any(test, feature = "_test_utils"))] extern crate regex; +#[cfg(any(test, feature = "_test_utils"))] +extern crate regex; -#[cfg(not(feature = "std"))] extern crate libm; +#[cfg(not(feature = "std"))] +extern crate libm; -#[cfg(ldk_bench)] extern crate criterion; +#[cfg(ldk_bench)] +extern crate criterion; -#[cfg(all(feature = "std", test))] extern crate parking_lot; +#[cfg(all(feature = "std", test))] +extern crate parking_lot; #[macro_use] pub mod util; +pub mod blinded_path; pub mod chain; +pub mod events; pub mod ln; pub mod offers; +pub mod onion_message; pub mod routing; pub mod sign; -pub mod onion_message; -pub mod blinded_path; -pub mod events; pub(crate) mod crypto; @@ -96,7 +94,7 @@ pub mod io_extras { pub use bitcoin::io::sink; pub fn copy(reader: &mut R, writer: &mut W) -> Result - where + where R: Read, W: Write, { @@ -106,7 +104,10 @@ pub mod io_extras { loop { match reader.read(&mut buf) { Ok(0) => break, - Ok(n) => { writer.write_all(&buf[0..n])?; count += n as u64; }, + Ok(n) => { + writer.write_all(&buf[0..n])?; + count += n as u64; + }, Err(ref e) if e.kind() == io::ErrorKind::Interrupted => {}, Err(e) => return Err(e.into()), }; @@ -132,7 +133,7 @@ pub mod io_extras { mod prelude { #![allow(unused_imports)] - pub use alloc::{vec, vec::Vec, string::String, collections::VecDeque, boxed::Box}; + pub use alloc::{boxed::Box, collections::VecDeque, string::String, vec, vec::Vec}; pub use alloc::borrow::ToOwned; pub use alloc::string::ToString; diff --git a/lightning/src/ln/async_signer_tests.rs b/lightning/src/ln/async_signer_tests.rs index 96ec664da94..8f7da9ae113 100644 --- a/lightning/src/ln/async_signer_tests.rs +++ b/lightning/src/ln/async_signer_tests.rs @@ -1,5 +1,3 @@ -#![cfg_attr(rustfmt, rustfmt_skip)] - // This file is Copyright its original authors, visible in version control // history. // @@ -13,10 +11,10 @@ //! properly with a signer implementation that asynchronously derives signatures. use crate::prelude::*; -use bitcoin::secp256k1::Secp256k1; -use bitcoin::{Transaction, TxOut, TxIn, Amount}; use bitcoin::locktime::absolute::LockTime; +use bitcoin::secp256k1::Secp256k1; use bitcoin::transaction::Version; +use bitcoin::{Amount, Transaction, TxIn, TxOut}; use crate::chain::channelmonitor::LATENCY_GRACE_PERIOD_BLOCKS; use crate::chain::ChannelMonitorUpdateStatus; @@ -30,8 +28,8 @@ use crate::ln::msgs::{BaseMessageHandler, ChannelMessageHandler, MessageSendEven use crate::ln::{functional_test_utils::*, msgs}; use crate::sign::ecdsa::EcdsaChannelSigner; use crate::sign::SignerProvider; -use crate::util::test_channel_signer::SignerOp; use crate::util::logger::Logger; +use crate::util::test_channel_signer::SignerOp; #[test] fn test_open_channel() { @@ -39,6 +37,7 @@ fn test_open_channel() { do_test_open_channel(true); } +#[rustfmt::skip] fn do_test_open_channel(zero_conf: bool) { // Simulate acquiring the commitment point for `open_channel` and `accept_channel` asynchronously. let mut manually_accept_config = test_default_channel_config(); @@ -100,11 +99,13 @@ fn do_test_open_channel(zero_conf: bool) { } #[test] +#[rustfmt::skip] fn test_funding_created() { do_test_funding_created(vec![SignerOp::SignCounterpartyCommitment, SignerOp::GetPerCommitmentPoint]); do_test_funding_created(vec![SignerOp::GetPerCommitmentPoint, SignerOp::SignCounterpartyCommitment]); } +#[rustfmt::skip] fn do_test_funding_created(signer_ops: Vec) { // Simulate acquiring the signature for `funding_created` asynchronously. let chanmon_cfgs = create_chanmon_cfgs(2); @@ -160,11 +161,13 @@ fn do_test_funding_created(signer_ops: Vec) { } #[test] +#[rustfmt::skip] fn test_funding_signed() { do_test_funding_signed(vec![SignerOp::SignCounterpartyCommitment, SignerOp::GetPerCommitmentPoint]); do_test_funding_signed(vec![SignerOp::GetPerCommitmentPoint, SignerOp::SignCounterpartyCommitment]); } +#[rustfmt::skip] fn do_test_funding_signed(signer_ops: Vec) { // Simulate acquiring the signature for `funding_signed` asynchronously. let chanmon_cfgs = create_chanmon_cfgs(2); @@ -223,6 +226,7 @@ fn do_test_funding_signed(signer_ops: Vec) { } #[test] +#[rustfmt::skip] fn test_async_commitment_signature_for_commitment_signed() { for i in 0..=8 { let enable_signer_op_order = vec![ @@ -234,6 +238,7 @@ fn test_async_commitment_signature_for_commitment_signed() { } } +#[rustfmt::skip] fn do_test_async_commitment_signature_for_commitment_signed_revoke_and_ack(enable_signer_op_order: Vec) { let chanmon_cfgs = create_chanmon_cfgs(2); let node_cfgs = create_node_cfgs(2, &chanmon_cfgs); @@ -294,11 +299,13 @@ fn do_test_async_commitment_signature_for_commitment_signed_revoke_and_ack(enabl } #[test] +#[rustfmt::skip] fn test_funding_signed_0conf() { do_test_funding_signed_0conf(vec![SignerOp::GetPerCommitmentPoint, SignerOp::SignCounterpartyCommitment]); do_test_funding_signed_0conf(vec![SignerOp::SignCounterpartyCommitment, SignerOp::GetPerCommitmentPoint]); } +#[rustfmt::skip] fn do_test_funding_signed_0conf(signer_ops: Vec) { // Simulate acquiring the signature for `funding_signed` asynchronously for a zero-conf channel. let mut manually_accept_config = test_default_channel_config(); @@ -409,6 +416,7 @@ enum UnblockSignerAcrossDisconnectCase { } #[test] +#[rustfmt::skip] fn test_async_raa_peer_disconnect() { do_test_async_raa_peer_disconnect(UnblockSignerAcrossDisconnectCase::AtEnd, true); do_test_async_raa_peer_disconnect(UnblockSignerAcrossDisconnectCase::AtEnd, false); @@ -418,6 +426,7 @@ fn test_async_raa_peer_disconnect() { do_test_async_raa_peer_disconnect(UnblockSignerAcrossDisconnectCase::BeforeReestablish, false); } +#[rustfmt::skip] fn do_test_async_raa_peer_disconnect(test_case: UnblockSignerAcrossDisconnectCase, raa_blocked_by_commit_point: bool) { // `raa_blocked_by_commit_point` determines whether we block the RAA by blocking the // signer on `GetPerCommitmentPoint` or `ReleaseCommitmentSecret`. @@ -524,7 +533,6 @@ fn do_test_async_raa_peer_disconnect(test_case: UnblockSignerAcrossDisconnectCas } } - #[test] fn test_async_commitment_signature_peer_disconnect() { // This tests that if our signer is blocked and gets unblocked @@ -533,6 +541,7 @@ fn test_async_commitment_signature_peer_disconnect() { } #[test] +#[rustfmt::skip] fn test_async_commitment_signature_peer_disconnect_signer_restored_before_monitor_completion() { // This tests that if we were pending a monitor update completion across a disconnect, // and needed to send a CS, that if our signer becomes available before the monitor @@ -542,6 +551,7 @@ fn test_async_commitment_signature_peer_disconnect_signer_restored_before_monito } #[test] +#[rustfmt::skip] fn test_async_commitment_signature_peer_disconnect_signer_restored_before_reestablish() { // This tests that if we tried to send a commitment_signed, but our signer was blocked, // if we disconnect, reconnect, the signer becomes available, then handle channel_reestablish, @@ -549,6 +559,7 @@ fn test_async_commitment_signature_peer_disconnect_signer_restored_before_reesta do_test_async_commitment_signature_peer_disconnect(UnblockSignerAcrossDisconnectCase::BeforeReestablish); } +#[rustfmt::skip] fn do_test_async_commitment_signature_peer_disconnect(test_case: UnblockSignerAcrossDisconnectCase) { let chanmon_cfgs = create_chanmon_cfgs(2); let node_cfgs = create_node_cfgs(2, &chanmon_cfgs); @@ -654,6 +665,7 @@ fn test_async_commitment_signature_ordering_monitor_restored() { do_test_async_commitment_signature_ordering(true); } +#[rustfmt::skip] fn do_test_async_commitment_signature_ordering(monitor_update_failure: bool) { // Across disconnects we may end up in a situation where we need to send a // commitment_signed and then revoke_and_ack. We need to make sure that if @@ -807,6 +819,7 @@ fn do_test_async_commitment_signature_ordering(monitor_update_failure: bool) { claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2); } +#[rustfmt::skip] fn do_test_async_holder_signatures(anchors: bool, remote_commitment: bool) { // Ensures that we can obtain holder signatures for commitment and HTLC transactions // asynchronously by allowing their retrieval to fail and retrying via @@ -959,6 +972,7 @@ fn test_closing_signed() { do_test_closing_signed(true, true); } +#[rustfmt::skip] fn do_test_closing_signed(extra_closing_signed: bool, reconnect: bool) { // Based off of `expect_channel_shutdown_state`. // Test that we can asynchronously sign closing transactions. diff --git a/lightning/src/ln/blinded_payment_tests.rs b/lightning/src/ln/blinded_payment_tests.rs index f43d672a164..f616c731e8f 100644 --- a/lightning/src/ln/blinded_payment_tests.rs +++ b/lightning/src/ln/blinded_payment_tests.rs @@ -1,5 +1,3 @@ -#![cfg_attr(rustfmt, rustfmt_skip)] - // This file is Copyright its original authors, visible in version control // history. // @@ -9,42 +7,50 @@ // You may not use this file except in accordance with one or both of these // licenses. -use bitcoin::hashes::hex::FromHex; -use bitcoin::hashes::sha256::Hash as Sha256; -use bitcoin::hashes::Hash; -use bitcoin::hex::DisplayHex; -use bitcoin::secp256k1::{PublicKey, Scalar, Secp256k1, SecretKey, schnorr}; -use bitcoin::secp256k1::ecdh::SharedSecret; -use bitcoin::secp256k1::ecdsa::{RecoverableSignature, Signature}; use crate::blinded_path; -use crate::blinded_path::payment::{BlindedPaymentPath, Bolt12RefundContext, ForwardTlvs, PaymentConstraints, PaymentContext, PaymentForwardNode, PaymentRelay, UnauthenticatedReceiveTlvs, PAYMENT_PADDING_ROUND_OFF}; +use crate::blinded_path::payment::{ + BlindedPaymentPath, Bolt12RefundContext, ForwardTlvs, PaymentConstraints, PaymentContext, + PaymentForwardNode, PaymentRelay, UnauthenticatedReceiveTlvs, PAYMENT_PADDING_ROUND_OFF, +}; use crate::blinded_path::utils::is_padded; +use crate::blinded_path::BlindedHop; use crate::events::{Event, HTLCHandlingFailureType, PaymentFailureReason}; -use crate::ln::types::ChannelId; -use crate::types::payment::{PaymentHash, PaymentSecret}; use crate::ln::channelmanager; use crate::ln::channelmanager::{HTLCFailureMsg, PaymentId, RecipientOnionFields}; -use crate::types::features::{BlindedHopFeatures, ChannelFeatures, NodeFeatures}; use crate::ln::functional_test_utils::*; use crate::ln::inbound_payment::ExpandedKey; use crate::ln::msgs; -use crate::ln::msgs::{BaseMessageHandler, ChannelMessageHandler, UnsignedGossipMessage, MessageSendEvent}; +use crate::ln::msgs::{ + BaseMessageHandler, ChannelMessageHandler, MessageSendEvent, UnsignedGossipMessage, +}; use crate::ln::onion_payment; use crate::ln::onion_utils::{self, LocalHTLCFailureReason}; use crate::ln::outbound_payment::{Retry, IDEMPOTENCY_TIMEOUT_TICKS}; +use crate::ln::types::ChannelId; use crate::offers::invoice::UnsignedBolt12Invoice; use crate::offers::nonce::Nonce; use crate::prelude::*; -use crate::routing::router::{BlindedTail, Path, Payee, PaymentParameters, RouteHop, RouteParameters, TrampolineHop}; +use crate::routing::router::Route; +use crate::routing::router::{ + BlindedTail, Path, Payee, PaymentParameters, RouteHop, RouteParameters, TrampolineHop, +}; use crate::sign::{NodeSigner, Recipient}; +use crate::types::features::{BlindedHopFeatures, ChannelFeatures, NodeFeatures}; +use crate::types::payment::{PaymentHash, PaymentSecret}; use crate::util::config::UserConfig; use crate::util::ser::{WithoutLength, Writeable}; use crate::util::test_utils; +use bitcoin::hashes::hex::FromHex; +use bitcoin::hashes::sha256::Hash as Sha256; +use bitcoin::hashes::Hash; +use bitcoin::hex::DisplayHex; +use bitcoin::secp256k1::ecdh::SharedSecret; +use bitcoin::secp256k1::ecdsa::{RecoverableSignature, Signature}; +use bitcoin::secp256k1::{schnorr, PublicKey, Scalar, Secp256k1, SecretKey}; use lightning_invoice::RawBolt11Invoice; use types::features::Features; -use crate::blinded_path::BlindedHop; -use crate::routing::router::Route; +#[rustfmt::skip] pub fn blinded_payment_path( payment_secret: PaymentSecret, intro_node_min_htlc: u64, intro_node_max_htlc: u64, node_ids: Vec, channel_upds: &[&msgs::UnsignedChannelUpdate], @@ -98,6 +104,7 @@ pub fn blinded_payment_path( ).unwrap() } +#[rustfmt::skip] pub fn get_blinded_route_parameters( amt_msat: u64, payment_secret: PaymentSecret, intro_node_min_htlc: u64, intro_node_max_htlc: u64, node_ids: Vec, channel_upds: &[&msgs::UnsignedChannelUpdate], @@ -113,6 +120,7 @@ pub fn get_blinded_route_parameters( ) } +#[rustfmt::skip] pub fn fail_blinded_htlc_backwards( payment_hash: PaymentHash, intro_node_idx: usize, nodes: &[&Node], retry_expected: bool @@ -154,6 +162,7 @@ fn one_hop_blinded_path() { do_one_hop_blinded_path(false); } +#[rustfmt::skip] fn do_one_hop_blinded_path(success: bool) { let chanmon_cfgs = create_chanmon_cfgs(2); let node_cfgs = create_node_cfgs(2, &chanmon_cfgs); @@ -197,6 +206,7 @@ fn do_one_hop_blinded_path(success: bool) { } #[test] +#[rustfmt::skip] fn mpp_to_one_hop_blinded_path() { let chanmon_cfgs = create_chanmon_cfgs(4); let node_cfgs = create_node_cfgs(4, &chanmon_cfgs); @@ -277,6 +287,7 @@ fn mpp_to_one_hop_blinded_path() { } #[test] +#[rustfmt::skip] fn mpp_to_three_hop_blinded_paths() { let chanmon_cfgs = create_chanmon_cfgs(6); let node_cfgs = create_node_cfgs(6, &chanmon_cfgs); @@ -370,6 +381,7 @@ fn forward_checks_failure() { do_forward_checks_failure(ForwardCheckFail::OutboundChannelCheck, false); } +#[rustfmt::skip] fn do_forward_checks_failure(check: ForwardCheckFail, intro_fails: bool) { // Ensure we'll fail backwards properly if a forwarding check fails on initial update_add // receipt. @@ -397,6 +409,7 @@ fn do_forward_checks_failure(check: ForwardCheckFail, intro_fails: bool) { nodes[0].node.send_payment(payment_hash, RecipientOnionFields::spontaneous_empty(), PaymentId(payment_hash.0), route_params, Retry::Attempts(0)).unwrap(); check_added_monitors(&nodes[0], 1); + #[rustfmt::skip] macro_rules! cause_error { ($src_node_idx: expr, $target_node_idx: expr, $update_add: expr) => { match check { @@ -507,6 +520,7 @@ fn do_forward_checks_failure(check: ForwardCheckFail, intro_fails: bool) { } #[test] +#[rustfmt::skip] fn failed_backwards_to_intro_node() { // Ensure the intro node will error backwards properly even if the downstream node did not blind // their error. @@ -577,12 +591,14 @@ enum ProcessPendingHTLCsCheck { } #[test] +#[rustfmt::skip] fn forward_fail_in_process_pending_htlc_fwds() { do_forward_fail_in_process_pending_htlc_fwds(ProcessPendingHTLCsCheck::FwdPeerDisconnected, true); do_forward_fail_in_process_pending_htlc_fwds(ProcessPendingHTLCsCheck::FwdPeerDisconnected, false); do_forward_fail_in_process_pending_htlc_fwds(ProcessPendingHTLCsCheck::FwdChannelClosed, true); do_forward_fail_in_process_pending_htlc_fwds(ProcessPendingHTLCsCheck::FwdChannelClosed, false); } +#[rustfmt::skip] fn do_forward_fail_in_process_pending_htlc_fwds(check: ProcessPendingHTLCsCheck, intro_fails: bool) { // Ensure the intro node will error backwards properly if the HTLC fails in // process_pending_htlc_forwards. @@ -619,6 +635,7 @@ fn do_forward_fail_in_process_pending_htlc_fwds(check: ProcessPendingHTLCsCheck, check_added_monitors!(nodes[1], 0); do_commitment_signed_dance(&nodes[1], &nodes[0], &payment_event.commitment_msg, false, false); + #[rustfmt::skip] macro_rules! cause_error { ($prev_node: expr, $curr_node: expr, $next_node: expr, $failed_chan_id: expr, $failed_scid: expr) => { match check { @@ -697,6 +714,7 @@ fn blinded_intercept_payment() { do_blinded_intercept_payment(true); do_blinded_intercept_payment(false); } +#[rustfmt::skip] fn do_blinded_intercept_payment(intercept_node_fails: bool) { let chanmon_cfgs = create_chanmon_cfgs(3); let node_cfgs = create_node_cfgs(3, &chanmon_cfgs); @@ -779,6 +797,7 @@ fn do_blinded_intercept_payment(intercept_node_fails: bool) { } #[test] +#[rustfmt::skip] fn two_hop_blinded_path_success() { let chanmon_cfgs = create_chanmon_cfgs(3); let node_cfgs = create_node_cfgs(3, &chanmon_cfgs); @@ -800,6 +819,7 @@ fn two_hop_blinded_path_success() { } #[test] +#[rustfmt::skip] fn three_hop_blinded_path_success() { let chanmon_cfgs = create_chanmon_cfgs(5); let node_cfgs = create_node_cfgs(5, &chanmon_cfgs); @@ -829,6 +849,7 @@ fn three_hop_blinded_path_success() { } #[test] +#[rustfmt::skip] fn three_hop_blinded_path_fail() { // Test that an intermediate blinded forwarding node gets failed back to with // malformed and also fails back themselves with malformed. @@ -888,6 +909,7 @@ fn multi_hop_receiver_fail() { do_multi_hop_receiver_fail(ReceiveCheckFail::PaymentConstraints); } +#[rustfmt::skip] fn do_multi_hop_receiver_fail(check: ReceiveCheckFail) { // Test that the receiver to a multihop blinded path fails back correctly. let chanmon_cfgs = create_chanmon_cfgs(3); @@ -1089,6 +1111,7 @@ fn do_multi_hop_receiver_fail(check: ReceiveCheckFail) { } #[test] +#[rustfmt::skip] fn blinded_path_retries() { let chanmon_cfgs = create_chanmon_cfgs(4); // Make one blinded path's fees slightly higher so they are tried in a deterministic order. @@ -1139,6 +1162,7 @@ fn blinded_path_retries() { check_added_monitors(&nodes[0], 1); pass_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]]], amt_msat, payment_hash, payment_secret); + #[rustfmt::skip] macro_rules! fail_payment_back { ($intro_node: expr) => { nodes[3].node.fail_htlc_backwards(&payment_hash); @@ -1200,6 +1224,7 @@ fn blinded_path_retries() { } #[test] +#[rustfmt::skip] fn min_htlc() { // The min htlc of a blinded path is the max (htlc_min - following_fees) along the path. Make sure // the payment succeeds when we calculate the min htlc this way. @@ -1276,6 +1301,7 @@ fn min_htlc() { } #[test] +#[rustfmt::skip] fn conditionally_round_fwd_amt() { // Previously, the (rng-found) feerates below caught a bug where an intermediate node would // calculate an amt_to_forward that underpaid them by 1 msat, caused by rounding up the outbound @@ -1326,8 +1352,8 @@ fn conditionally_round_fwd_amt() { expect_payment_sent(&nodes[0], payment_preimage, Some(Some(expected_fee)), true, true); } - #[test] +#[rustfmt::skip] fn custom_tlvs_to_blinded_path() { let chanmon_cfgs = create_chanmon_cfgs(2); let node_cfgs = create_node_cfgs(2, &chanmon_cfgs); @@ -1382,6 +1408,7 @@ fn custom_tlvs_to_blinded_path() { } #[test] +#[rustfmt::skip] fn fails_receive_tlvs_authentication() { let chanmon_cfgs = create_chanmon_cfgs(2); let node_cfgs = create_node_cfgs(2, &chanmon_cfgs); @@ -1472,6 +1499,7 @@ fn fails_receive_tlvs_authentication() { } #[test] +#[rustfmt::skip] fn blinded_payment_path_padding() { // Make sure that for a blinded payment path, all encrypted payloads are padded to equal lengths. let chanmon_cfgs = create_chanmon_cfgs(5); @@ -1521,7 +1549,7 @@ fn pubkey_from_hex(hex: &str) -> PublicKey { fn update_add_msg( amount_msat: u64, cltv_expiry: u32, blinding_point: Option, - onion_routing_packet: msgs::OnionPacket + onion_routing_packet: msgs::OnionPacket, ) -> msgs::UpdateAddHTLC { msgs::UpdateAddHTLC { channel_id: ChannelId::from_bytes([0; 32]), @@ -1536,6 +1564,7 @@ fn update_add_msg( } #[test] +#[rustfmt::skip] fn route_blinding_spec_test_vector() { let mut secp_ctx = Secp256k1::new(); let bob_secret = secret_from_hex("4242424242424242424242424242424242424242424242424242424242424242"); @@ -1626,14 +1655,19 @@ fn route_blinding_spec_test_vector() { } Ok(SharedSecret::new(other_key, &node_secret)) } + #[rustfmt::skip] fn get_inbound_payment_key(&self) -> ExpandedKey { unreachable!() } + #[rustfmt::skip] fn get_node_id(&self, _recipient: Recipient) -> Result { unreachable!() } + #[rustfmt::skip] fn sign_invoice( &self, _invoice: &RawBolt11Invoice, _recipient: Recipient, ) -> Result { unreachable!() } + #[rustfmt::skip] fn sign_bolt12_invoice( &self, _invoice: &UnsignedBolt12Invoice, ) -> Result { unreachable!() } + #[rustfmt::skip] fn sign_gossip_message(&self, _msg: UnsignedGossipMessage) -> Result { unreachable!() } } let logger = test_utils::TestLogger::with_id("".to_owned()); @@ -1756,6 +1790,7 @@ fn route_blinding_spec_test_vector() { } #[test] +#[rustfmt::skip] fn test_combined_trampoline_onion_creation_vectors() { // As per https://github.com/lightning/bolts/blob/fa0594ac2af3531d734f1d707a146d6e13679451/bolt04/trampoline-to-blinded-path-payment-onion-test.json#L251 @@ -1839,6 +1874,7 @@ fn test_combined_trampoline_onion_creation_vectors() { } #[test] +#[rustfmt::skip] fn test_trampoline_inbound_payment_decoding() { let secp_ctx = Secp256k1::new(); let session_priv = secret_from_hex("0303030303030303030303030303030303030303030303030303030303030303"); @@ -1935,14 +1971,19 @@ fn test_trampoline_inbound_payment_decoding() { } Ok(SharedSecret::new(other_key, &node_secret)) } + #[rustfmt::skip] fn get_inbound_payment_key(&self) -> ExpandedKey { unreachable!() } + #[rustfmt::skip] fn get_node_id(&self, _recipient: Recipient) -> Result { unreachable!() } + #[rustfmt::skip] fn sign_invoice( &self, _invoice: &RawBolt11Invoice, _recipient: Recipient, ) -> Result { unreachable!() } + #[rustfmt::skip] fn sign_bolt12_invoice( &self, _invoice: &UnsignedBolt12Invoice, ) -> Result { unreachable!() } + #[rustfmt::skip] fn sign_gossip_message(&self, _msg: UnsignedGossipMessage) -> Result { unreachable!() } } let logger = test_utils::TestLogger::with_id("".to_owned()); @@ -1981,6 +2022,7 @@ fn test_trampoline_inbound_payment_decoding() { }; } +#[rustfmt::skip] fn do_test_trampoline_single_hop_receive(success: bool) { const TOTAL_NODE_COUNT: usize = 3; let secp_ctx = Secp256k1::new(); @@ -2204,6 +2246,7 @@ fn test_trampoline_single_hop_receive() { } #[test] +#[rustfmt::skip] fn test_trampoline_unblinded_receive() { // Simulate a payment of A (0) -> B (1) -> C(Trampoline) (2) @@ -2370,6 +2413,7 @@ fn test_trampoline_unblinded_receive() { } #[test] +#[rustfmt::skip] fn test_trampoline_forward_rejection() { const TOTAL_NODE_COUNT: usize = 3; diff --git a/lightning/src/ln/chan_utils.rs b/lightning/src/ln/chan_utils.rs index be43a02b381..04bb914281c 100644 --- a/lightning/src/ln/chan_utils.rs +++ b/lightning/src/ln/chan_utils.rs @@ -1,5 +1,3 @@ -#![cfg_attr(rustfmt, rustfmt_skip)] - // This file is Copyright its original authors, visible in version control // history. // @@ -12,43 +10,46 @@ //! Various utilities for building scripts related to channels. These are //! largely of interest for those implementing the traits on [`crate::sign`] by hand. -use bitcoin::{PubkeyHash, WPubkeyHash}; use bitcoin::amount::Amount; -use bitcoin::script::{Script, ScriptBuf, Builder}; use bitcoin::opcodes; -use bitcoin::transaction::{TxIn,TxOut,OutPoint,Transaction}; +use bitcoin::script::{Builder, Script, ScriptBuf}; use bitcoin::sighash; use bitcoin::sighash::EcdsaSighashType; use bitcoin::transaction::Version; +use bitcoin::transaction::{OutPoint, Transaction, TxIn, TxOut}; +use bitcoin::{PubkeyHash, WPubkeyHash}; -use bitcoin::hashes::{Hash, HashEngine}; +use bitcoin::hash_types::Txid; use bitcoin::hashes::hash160::Hash as Hash160; -use bitcoin::hashes::sha256::Hash as Sha256; use bitcoin::hashes::ripemd160::Hash as Ripemd160; -use bitcoin::hash_types::Txid; +use bitcoin::hashes::sha256::Hash as Sha256; +use bitcoin::hashes::{Hash, HashEngine}; use crate::chain::chaininterface::fee_for_weight; use crate::chain::package::WEIGHT_REVOKED_OUTPUT; +use crate::ln::msgs::DecodeError; use crate::sign::EntropySource; use crate::types::payment::{PaymentHash, PaymentPreimage}; -use crate::ln::msgs::DecodeError; use crate::util::ser::{Readable, ReadableArgs, RequiredWrapper, Writeable, Writer}; use crate::util::transaction_utils; -use bitcoin::locktime::absolute::LockTime; use bitcoin::ecdsa::Signature as BitcoinSignature; -use bitcoin::secp256k1::{SecretKey, PublicKey, Scalar}; -use bitcoin::secp256k1::{Secp256k1, ecdsa::Signature, Message}; +use bitcoin::locktime::absolute::LockTime; +use bitcoin::secp256k1::{ecdsa::Signature, Message, Secp256k1}; +use bitcoin::secp256k1::{PublicKey, Scalar, SecretKey}; use bitcoin::{secp256k1, Sequence, Witness}; +use super::channel_keys::{ + DelayedPaymentBasepoint, DelayedPaymentKey, HtlcBasepoint, HtlcKey, RevocationBasepoint, + RevocationKey, +}; +use crate::chain; +use crate::crypto::utils::{sign, sign_with_aux_rand}; use crate::io; +use crate::ln::channel::{ANCHOR_OUTPUT_VALUE_SATOSHI, INITIAL_COMMITMENT_NUMBER}; +use crate::types::features::ChannelTypeFeatures; use core::cmp; -use crate::ln::channel::{INITIAL_COMMITMENT_NUMBER, ANCHOR_OUTPUT_VALUE_SATOSHI}; use core::ops::Deref; -use crate::chain; -use crate::types::features::ChannelTypeFeatures; -use crate::crypto::utils::{sign, sign_with_aux_rand}; -use super::channel_keys::{DelayedPaymentBasepoint, DelayedPaymentKey, HtlcKey, HtlcBasepoint, RevocationKey, RevocationBasepoint}; #[allow(unused_imports)] use crate::prelude::*; @@ -89,18 +90,16 @@ pub const HTLC_TIMEOUT_INPUT_ANCHOR_WITNESS_WEIGHT: u64 = 288; pub const HTLC_SUCCESS_INPUT_ANCHOR_WITNESS_WEIGHT: u64 = 327; /// The size of the 2-of-2 multisig script -const MULTISIG_SCRIPT_SIZE: u64 = - 1 + // OP_2 +const MULTISIG_SCRIPT_SIZE: u64 = 1 + // OP_2 1 + // data len 33 + // pubkey1 1 + // data len 33 + // pubkey2 1 + // OP_2 - 1; // OP_CHECKMULTISIG + 1; // OP_CHECKMULTISIG /// The weight of a funding transaction input (2-of-2 P2WSH) /// See https://github.com/lightning/bolts/blob/master/03-transactions.md#expected-weight-of-the-commitment-transaction -pub const FUNDING_TRANSACTION_WITNESS_WEIGHT: u64 = - 1 + // number_of_witness_elements +pub const FUNDING_TRANSACTION_WITNESS_WEIGHT: u64 = 1 + // number_of_witness_elements 1 + // nil_len 1 + // sig len 73 + // sig1 @@ -111,6 +110,7 @@ pub const FUNDING_TRANSACTION_WITNESS_WEIGHT: u64 = /// Gets the weight for an HTLC-Success transaction. #[inline] +#[rustfmt::skip] pub fn htlc_success_tx_weight(channel_type_features: &ChannelTypeFeatures) -> u64 { const HTLC_SUCCESS_TX_WEIGHT: u64 = 703; const HTLC_SUCCESS_ANCHOR_TX_WEIGHT: u64 = 706; @@ -119,6 +119,7 @@ pub fn htlc_success_tx_weight(channel_type_features: &ChannelTypeFeatures) -> u6 /// Gets the weight for an HTLC-Timeout transaction. #[inline] +#[rustfmt::skip] pub fn htlc_timeout_tx_weight(channel_type_features: &ChannelTypeFeatures) -> u64 { const HTLC_TIMEOUT_TX_WEIGHT: u64 = 663; const HTLC_TIMEOUT_ANCHOR_TX_WEIGHT: u64 = 666; @@ -142,6 +143,7 @@ pub enum HTLCClaim { impl HTLCClaim { /// Check if a given input witness attempts to claim a HTLC. + #[rustfmt::skip] pub fn from_witness(witness: &Witness) -> Option { debug_assert_eq!(OFFERED_HTLC_SCRIPT_WEIGHT_ANCHORS, MIN_ACCEPTED_HTLC_SCRIPT_WEIGHT); if witness.len() < 2 { @@ -209,6 +211,7 @@ const COMMITMENT_TX_WEIGHT_PER_HTLC: u64 = 172; #[cfg(any(test, feature = "_test_utils"))] pub const COMMITMENT_TX_WEIGHT_PER_HTLC: u64 = 172; +#[rustfmt::skip] pub(crate) fn commitment_tx_base_weight(channel_type_features: &ChannelTypeFeatures) -> u64 { const COMMITMENT_TX_BASE_WEIGHT: u64 = 724; const COMMITMENT_TX_BASE_ANCHOR_WEIGHT: u64 = 1124; @@ -217,6 +220,7 @@ pub(crate) fn commitment_tx_base_weight(channel_type_features: &ChannelTypeFeatu /// Get the fee cost of a commitment tx with a given number of HTLC outputs. /// Note that num_htlcs should not include dust HTLCs. +#[rustfmt::skip] pub(crate) fn commit_tx_fee_sat(feerate_per_kw: u32, num_htlcs: usize, channel_type_features: &ChannelTypeFeatures) -> u64 { feerate_per_kw as u64 * (commitment_tx_base_weight(channel_type_features) + @@ -224,6 +228,7 @@ pub(crate) fn commit_tx_fee_sat(feerate_per_kw: u32, num_htlcs: usize, channel_t / 1000 } +#[rustfmt::skip] pub(crate) fn commit_and_htlc_tx_fees_sat(feerate_per_kw: u32, num_accepted_htlcs: usize, num_offered_htlcs: usize, channel_type_features: &ChannelTypeFeatures) -> u64 { let num_htlcs = num_accepted_htlcs + num_offered_htlcs; let commit_tx_fees_sat = commit_tx_fee_sat(feerate_per_kw, num_htlcs, channel_type_features); @@ -253,6 +258,7 @@ pub fn build_commitment_secret(commitment_seed: &[u8; 32], idx: u64) -> [u8; 32] } /// Build a closing transaction +#[rustfmt::skip] pub fn build_closing_transaction(to_holder_value_sat: Amount, to_counterparty_value_sat: Amount, to_holder_script: ScriptBuf, to_counterparty_script: ScriptBuf, funding_outpoint: OutPoint) -> Transaction { let txins = { let ins: Vec = vec![TxIn { @@ -307,6 +313,7 @@ pub struct CounterpartyCommitmentSecrets { impl Eq for CounterpartyCommitmentSecrets {} impl PartialEq for CounterpartyCommitmentSecrets { + #[rustfmt::skip] fn eq(&self, other: &Self) -> bool { for (&(ref secret, ref idx), &(ref o_secret, ref o_idx)) in self.old_secrets.iter().zip(other.old_secrets.iter()) { if secret != o_secret || idx != o_idx { @@ -319,11 +326,13 @@ impl PartialEq for CounterpartyCommitmentSecrets { impl CounterpartyCommitmentSecrets { /// Creates a new empty `CounterpartyCommitmentSecrets` structure. + #[rustfmt::skip] pub fn new() -> Self { Self { old_secrets: [([0; 32], 1 << 48); 49], } } #[inline] + #[rustfmt::skip] fn place_secret(idx: u64) -> u8 { for i in 0..48 { if idx & (1 << i) == (1 << i) { @@ -378,6 +387,7 @@ impl CounterpartyCommitmentSecrets { /// Returns the secret at `idx`. /// Returns `None` if `idx` is < [`CounterpartyCommitmentSecrets::get_min_seen_secret`]. + #[rustfmt::skip] pub fn get_secret(&self, idx: u64) -> Option<[u8; 32]> { for i in 0..self.old_secrets.len() { if (idx & (!((1 << i) - 1))) == self.old_secrets[i].1 { @@ -413,7 +423,9 @@ impl Readable for CounterpartyCommitmentSecrets { /// Derives a per-commitment-transaction private key (eg an htlc key or delayed_payment key) /// from the base secret and the per_commitment_point. -pub fn derive_private_key(secp_ctx: &Secp256k1, per_commitment_point: &PublicKey, base_secret: &SecretKey) -> SecretKey { +pub fn derive_private_key( + secp_ctx: &Secp256k1, per_commitment_point: &PublicKey, base_secret: &SecretKey, +) -> SecretKey { let mut sha = Sha256::engine(); sha.input(&per_commitment_point.serialize()); sha.input(&PublicKey::from_secret_key(&secp_ctx, &base_secret).serialize()); @@ -429,6 +441,7 @@ pub fn derive_private_key(secp_ctx: &Secp256k1, per_co /// commitment transaction, thus per_commitment_secret always come from cheater /// and revocation_base_secret always come from punisher, which is the broadcaster /// of the transaction spending with this key knowledge. +#[rustfmt::skip] pub fn derive_private_revocation_key(secp_ctx: &Secp256k1, per_commitment_secret: &SecretKey, countersignatory_revocation_base_secret: &SecretKey) -> SecretKey { @@ -528,6 +541,7 @@ impl_writeable_tlv_based!(ChannelPublicKeys, { impl TxCreationKeys { /// Create per-state keys from channel base points and the per-commitment point. /// Key set is asymmetric and can't be used as part of counter-signatory set of transactions. + #[rustfmt::skip] pub fn derive_new(secp_ctx: &Secp256k1, per_commitment_point: &PublicKey, broadcaster_delayed_payment_base: &DelayedPaymentBasepoint, broadcaster_htlc_base: &HtlcBasepoint, countersignatory_revocation_base: &RevocationBasepoint, countersignatory_htlc_base: &HtlcBasepoint) -> TxCreationKeys { TxCreationKeys { per_commitment_point: per_commitment_point.clone(), @@ -540,7 +554,10 @@ impl TxCreationKeys { /// Generate per-state keys from channel static keys. /// Key set is asymmetric and can't be used as part of counter-signatory set of transactions. - pub fn from_channel_static_keys(per_commitment_point: &PublicKey, broadcaster_keys: &ChannelPublicKeys, countersignatory_keys: &ChannelPublicKeys, secp_ctx: &Secp256k1) -> TxCreationKeys { + pub fn from_channel_static_keys( + per_commitment_point: &PublicKey, broadcaster_keys: &ChannelPublicKeys, + countersignatory_keys: &ChannelPublicKeys, secp_ctx: &Secp256k1, + ) -> TxCreationKeys { TxCreationKeys::derive_new( &secp_ctx, &per_commitment_point, @@ -557,11 +574,12 @@ impl TxCreationKeys { // keys of 33 bytes (+ 1 push). Generally, pushes are only 2 bytes (for values below 0x7fff, i.e. // around 7 months), however, a 7 month contest delay shouldn't result in being unable to reclaim // on-chain funds. -pub const REVOKEABLE_REDEEMSCRIPT_MAX_LENGTH: usize = 6 + 4 + 34*2; +pub const REVOKEABLE_REDEEMSCRIPT_MAX_LENGTH: usize = 6 + 4 + 34 * 2; /// A script either spendable by the revocation /// key or the broadcaster_delayed_payment_key and satisfying the relative-locktime OP_CSV constrain. /// Encumbering a `to_holder` output on a commitment transaction or 2nd-stage HTLC transactions. +#[rustfmt::skip] pub fn get_revokeable_redeemscript(revocation_key: &RevocationKey, contest_delay: u16, broadcaster_delayed_payment_key: &DelayedPaymentKey) -> ScriptBuf { let res = Builder::new().push_opcode(opcodes::all::OP_IF) .push_slice(&revocation_key.to_public_key().serialize()) @@ -579,7 +597,9 @@ pub fn get_revokeable_redeemscript(revocation_key: &RevocationKey, contest_delay /// Returns the script for the counterparty's output on a holder's commitment transaction based on /// the channel type. -pub fn get_counterparty_payment_script(channel_type_features: &ChannelTypeFeatures, payment_key: &PublicKey) -> ScriptBuf { +pub fn get_counterparty_payment_script( + channel_type_features: &ChannelTypeFeatures, payment_key: &PublicKey, +) -> ScriptBuf { if channel_type_features.supports_anchors_zero_fee_htlc_tx() { get_to_countersigner_keyed_anchor_redeemscript(payment_key).to_p2wsh() } else { @@ -635,6 +655,7 @@ impl_writeable_tlv_based!(HTLCOutputInCommitment, { }); #[inline] +#[rustfmt::skip] pub(crate) fn get_htlc_redeemscript_with_explicit_keys(htlc: &HTLCOutputInCommitment, channel_type_features: &ChannelTypeFeatures, broadcaster_htlc_key: &HtlcKey, countersignatory_htlc_key: &HtlcKey, revocation_key: &RevocationKey) -> ScriptBuf { let payment_hash160 = Ripemd160::hash(&htlc.payment_hash.0[..]).to_byte_array(); if htlc.offered { @@ -712,19 +733,23 @@ pub(crate) fn get_htlc_redeemscript_with_explicit_keys(htlc: &HTLCOutputInCommit /// Gets the witness redeemscript for an HTLC output in a commitment transaction. Note that htlc /// does not need to have its previous_output_index filled. #[inline] +#[rustfmt::skip] pub fn get_htlc_redeemscript(htlc: &HTLCOutputInCommitment, channel_type_features: &ChannelTypeFeatures, keys: &TxCreationKeys) -> ScriptBuf { get_htlc_redeemscript_with_explicit_keys(htlc, channel_type_features, &keys.broadcaster_htlc_key, &keys.countersignatory_htlc_key, &keys.revocation_key) } /// Gets the redeemscript for a funding output from the two funding public keys. /// Note that the order of funding public keys does not matter. -pub fn make_funding_redeemscript(broadcaster: &PublicKey, countersignatory: &PublicKey) -> ScriptBuf { +pub fn make_funding_redeemscript( + broadcaster: &PublicKey, countersignatory: &PublicKey, +) -> ScriptBuf { let broadcaster_funding_key = broadcaster.serialize(); let countersignatory_funding_key = countersignatory.serialize(); make_funding_redeemscript_from_slices(&broadcaster_funding_key, &countersignatory_funding_key) } +#[rustfmt::skip] pub(crate) fn make_funding_redeemscript_from_slices(broadcaster_funding_key: &[u8; 33], countersignatory_funding_key: &[u8; 33]) -> ScriptBuf { let builder = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2); if broadcaster_funding_key[..] < countersignatory_funding_key[..] { @@ -743,6 +768,7 @@ pub(crate) fn make_funding_redeemscript_from_slices(broadcaster_funding_key: &[u /// /// Panics if htlc.transaction_output_index.is_none() (as such HTLCs do not appear in the /// commitment transaction). +#[rustfmt::skip] pub fn build_htlc_transaction(commitment_txid: &Txid, feerate_per_kw: u32, contest_delay: u16, htlc: &HTLCOutputInCommitment, channel_type_features: &ChannelTypeFeatures, broadcaster_delayed_payment_key: &DelayedPaymentKey, revocation_key: &RevocationKey) -> Transaction { let txins= vec![build_htlc_input(commitment_txid, htlc, channel_type_features)]; @@ -760,6 +786,7 @@ pub fn build_htlc_transaction(commitment_txid: &Txid, feerate_per_kw: u32, conte } } +#[rustfmt::skip] pub(crate) fn build_htlc_input(commitment_txid: &Txid, htlc: &HTLCOutputInCommitment, channel_type_features: &ChannelTypeFeatures) -> TxIn { TxIn { previous_output: OutPoint { @@ -772,6 +799,7 @@ pub(crate) fn build_htlc_input(commitment_txid: &Txid, htlc: &HTLCOutputInCommit } } +#[rustfmt::skip] pub(crate) fn build_htlc_output( feerate_per_kw: u32, contest_delay: u16, htlc: &HTLCOutputInCommitment, channel_type_features: &ChannelTypeFeatures, broadcaster_delayed_payment_key: &DelayedPaymentKey, revocation_key: &RevocationKey ) -> TxOut { @@ -794,6 +822,7 @@ pub(crate) fn build_htlc_output( } /// Returns the witness required to satisfy and spend a HTLC input. +#[rustfmt::skip] pub fn build_htlc_input_witness( local_sig: &Signature, remote_sig: &Signature, preimage: &Option, redeem_script: &Script, channel_type_features: &ChannelTypeFeatures, @@ -838,7 +867,9 @@ pub fn build_htlc_input_witness( /// [`CounterpartyReceivedHTLCOutput`]: crate::chain::package::CounterpartyReceivedHTLCOutput /// [`HolderHTLCOutput`]: crate::chain::package::HolderHTLCOutput /// [`HolderFundingOutput`]: crate::chain::package::HolderFundingOutput -pub(crate) fn legacy_deserialization_prevention_marker_for_channel_type_features(features: &ChannelTypeFeatures) -> Option<()> { +pub(crate) fn legacy_deserialization_prevention_marker_for_channel_type_features( + features: &ChannelTypeFeatures, +) -> Option<()> { let mut legacy_version_bit_set = ChannelTypeFeatures::only_static_remote_key(); legacy_version_bit_set.set_scid_privacy_required(); legacy_version_bit_set.set_zero_conf_required(); @@ -876,6 +907,7 @@ pub fn shared_anchor_script_pubkey() -> ScriptBuf { /// After 16 blocks of confirmation, an alternative satisfying witness could be: /// <> /// (empty vector required to satisfy compliance with MINIMALIF-standard rule) +#[rustfmt::skip] pub fn get_keyed_anchor_redeemscript(funding_pubkey: &PublicKey) -> ScriptBuf { Builder::new().push_slice(funding_pubkey.serialize()) .push_opcode(opcodes::all::OP_CHECKSIG) @@ -889,6 +921,7 @@ pub fn get_keyed_anchor_redeemscript(funding_pubkey: &PublicKey) -> ScriptBuf { /// Locates the output with a keyed anchor (non-zero-fee-commitments) script paying to /// `funding_pubkey` within `commitment_tx`. +#[rustfmt::skip] pub(crate) fn get_keyed_anchor_output<'a>(commitment_tx: &'a Transaction, funding_pubkey: &PublicKey) -> Option<(u32, &'a TxOut)> { let anchor_script = get_keyed_anchor_redeemscript(funding_pubkey).to_p2wsh(); commitment_tx.output.iter().enumerate() @@ -898,7 +931,9 @@ pub(crate) fn get_keyed_anchor_output<'a>(commitment_tx: &'a Transaction, fundin /// Returns the witness required to satisfy and spend a keyed anchor (non-zero-fee-commitments) /// input. -pub fn build_keyed_anchor_input_witness(funding_key: &PublicKey, funding_sig: &Signature) -> Witness { +pub fn build_keyed_anchor_input_witness( + funding_key: &PublicKey, funding_sig: &Signature, +) -> Witness { let anchor_redeem_script = get_keyed_anchor_redeemscript(funding_key); let mut ret = Witness::new(); ret.push_ecdsa_signature(&BitcoinSignature::sighash_all(*funding_sig)); @@ -962,6 +997,7 @@ impl ChannelTransactionParameters { /// given that the holder is the broadcaster. /// /// self.is_populated() must be true before calling this function. + #[rustfmt::skip] pub fn as_holder_broadcastable(&self) -> DirectedChannelTransactionParameters { assert!(self.is_populated(), "self.late_parameters must be set before using as_holder_broadcastable"); DirectedChannelTransactionParameters { @@ -974,6 +1010,7 @@ impl ChannelTransactionParameters { /// given that the counterparty is the broadcaster. /// /// self.is_populated() must be true before calling this function. + #[rustfmt::skip] pub fn as_counterparty_broadcastable(&self) -> DirectedChannelTransactionParameters { assert!(self.is_populated(), "self.late_parameters must be set before using as_counterparty_broadcastable"); DirectedChannelTransactionParameters { @@ -982,6 +1019,7 @@ impl ChannelTransactionParameters { } } + #[rustfmt::skip] pub(crate) fn make_funding_redeemscript(&self) -> ScriptBuf { make_funding_redeemscript( &self.holder_pubkeys.funding_pubkey, @@ -995,6 +1033,7 @@ impl ChannelTransactionParameters { } #[cfg(test)] + #[rustfmt::skip] pub fn test_dummy(channel_value_satoshis: u64) -> Self { let dummy_keys = ChannelPublicKeys { funding_pubkey: PublicKey::from_slice(&[2; 33]).unwrap(), @@ -1027,6 +1066,7 @@ impl_writeable_tlv_based!(CounterpartyChannelTransactionParameters, { }); impl Writeable for ChannelTransactionParameters { + #[rustfmt::skip] fn write(&self, writer: &mut W) -> Result<(), io::Error> { let legacy_deserialization_prevention_marker = legacy_deserialization_prevention_marker_for_channel_type_features(&self.channel_type_features); write_tlv_fields!(writer, { @@ -1045,6 +1085,7 @@ impl Writeable for ChannelTransactionParameters { } impl ReadableArgs> for ChannelTransactionParameters { + #[rustfmt::skip] fn read(reader: &mut R, read_args: Option) -> Result { let mut holder_pubkeys = RequiredWrapper(None); let mut holder_selected_contest_delay = RequiredWrapper(None); @@ -1130,6 +1171,7 @@ impl<'a> DirectedChannelTransactionParameters<'a> { /// Get the contest delay applicable to the transactions. /// Note that the contest delay was selected by the countersignatory. + #[rustfmt::skip] pub fn contest_delay(&self) -> u16 { let counterparty_parameters = self.inner.counterparty_parameters.as_ref().unwrap(); if self.holder_is_broadcaster { counterparty_parameters.selected_contest_delay } else { self.inner.holder_selected_contest_delay } @@ -1139,6 +1181,7 @@ impl<'a> DirectedChannelTransactionParameters<'a> { /// /// The boolean representing the side that initiated the channel is /// an input to the commitment number obscure factor computation. + #[rustfmt::skip] pub fn is_outbound(&self) -> bool { if self.holder_is_broadcaster { self.inner.is_outbound_from_holder } else { !self.inner.is_outbound_from_holder } } @@ -1172,6 +1215,7 @@ pub struct HolderCommitmentTransaction { impl Deref for HolderCommitmentTransaction { type Target = CommitmentTransaction; + #[rustfmt::skip] fn deref(&self) -> &Self::Target { &self.inner } } @@ -1192,6 +1236,7 @@ impl_writeable_tlv_based!(HolderCommitmentTransaction, { impl HolderCommitmentTransaction { #[cfg(test)] + #[rustfmt::skip] pub fn dummy(channel_value_satoshis: u64, nondust_htlcs: Vec) -> Self { let secp_ctx = Secp256k1::new(); let dummy_key = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap()); @@ -1229,6 +1274,7 @@ impl HolderCommitmentTransaction { /// Create a new holder transaction with the given counterparty signatures. /// The funding keys are used to figure out which signature should go first when building the transaction for broadcast. + #[rustfmt::skip] pub fn new(commitment_tx: CommitmentTransaction, counterparty_sig: Signature, counterparty_htlc_sigs: Vec, holder_funding_key: &PublicKey, counterparty_funding_key: &PublicKey) -> Self { Self { inner: commitment_tx, @@ -1238,6 +1284,7 @@ impl HolderCommitmentTransaction { } } + #[rustfmt::skip] pub(crate) fn add_holder_sig(&self, funding_redeemscript: &Script, holder_sig: Signature) -> Transaction { // First push the multisig dummy, note that due to BIP147 (NULLDUMMY) it must be a zero-length element. let mut tx = self.inner.built.transaction.clone(); @@ -1277,13 +1324,17 @@ impl BuiltCommitmentTransaction { /// Get the SIGHASH_ALL sighash value of the transaction. /// /// This can be used to verify a signature. + #[rustfmt::skip] pub fn get_sighash_all(&self, funding_redeemscript: &Script, channel_value_satoshis: u64) -> Message { let sighash = &sighash::SighashCache::new(&self.transaction).p2wsh_signature_hash(0, funding_redeemscript, Amount::from_sat(channel_value_satoshis), EcdsaSighashType::All).unwrap()[..]; hash_to_message!(sighash) } /// Signs the counterparty's commitment transaction. - pub fn sign_counterparty_commitment(&self, funding_key: &SecretKey, funding_redeemscript: &Script, channel_value_satoshis: u64, secp_ctx: &Secp256k1) -> Signature { + pub fn sign_counterparty_commitment( + &self, funding_key: &SecretKey, funding_redeemscript: &Script, channel_value_satoshis: u64, + secp_ctx: &Secp256k1, + ) -> Signature { let sighash = self.get_sighash_all(funding_redeemscript, channel_value_satoshis); sign(secp_ctx, &sighash, funding_key) } @@ -1291,8 +1342,11 @@ impl BuiltCommitmentTransaction { /// Signs the holder commitment transaction because we are about to broadcast it. pub fn sign_holder_commitment( &self, funding_key: &SecretKey, funding_redeemscript: &Script, channel_value_satoshis: u64, - entropy_source: &ES, secp_ctx: &Secp256k1 - ) -> Signature where ES::Target: EntropySource { + entropy_source: &ES, secp_ctx: &Secp256k1, + ) -> Signature + where + ES::Target: EntropySource, + { let sighash = self.get_sighash_all(funding_redeemscript, channel_value_satoshis); sign_with_aux_rand(secp_ctx, &sighash, funding_key, entropy_source) } @@ -1314,6 +1368,7 @@ pub struct ClosingTransaction { impl ClosingTransaction { /// Construct an object of the class + #[rustfmt::skip] pub fn new( to_holder_value_sat: u64, to_counterparty_value_sat: u64, @@ -1353,6 +1408,7 @@ impl ClosingTransaction { /// /// An external validating signer must call this method before signing /// or using the built transaction. + #[rustfmt::skip] pub fn verify(&self, funding_outpoint: OutPoint) -> Result { let built = build_closing_transaction( self.to_holder_value_sat, self.to_counterparty_value_sat, @@ -1399,6 +1455,7 @@ pub struct TrustedClosingTransaction<'a> { impl<'a> Deref for TrustedClosingTransaction<'a> { type Target = ClosingTransaction; + #[rustfmt::skip] fn deref(&self) -> &Self::Target { self.inner } } @@ -1411,6 +1468,7 @@ impl<'a> TrustedClosingTransaction<'a> { /// Get the SIGHASH_ALL sighash value of the transaction. /// /// This can be used to verify a signature. + #[rustfmt::skip] pub fn get_sighash_all(&self, funding_redeemscript: &Script, channel_value_satoshis: u64) -> Message { let sighash = &sighash::SighashCache::new(&self.inner.built).p2wsh_signature_hash(0, funding_redeemscript, Amount::from_sat(channel_value_satoshis), EcdsaSighashType::All).unwrap()[..]; hash_to_message!(sighash) @@ -1418,7 +1476,10 @@ impl<'a> TrustedClosingTransaction<'a> { /// Sign a transaction, either because we are counter-signing the counterparty's transaction or /// because we are about to broadcast a holder transaction. - pub fn sign(&self, funding_key: &SecretKey, funding_redeemscript: &Script, channel_value_satoshis: u64, secp_ctx: &Secp256k1) -> Signature { + pub fn sign( + &self, funding_key: &SecretKey, funding_redeemscript: &Script, channel_value_satoshis: u64, + secp_ctx: &Secp256k1, + ) -> Signature { let sighash = self.get_sighash_all(funding_redeemscript, channel_value_satoshis); sign(secp_ctx, &sighash, funding_key) } @@ -1450,6 +1511,7 @@ pub struct CommitmentTransaction { impl Eq for CommitmentTransaction {} impl PartialEq for CommitmentTransaction { + #[rustfmt::skip] fn eq(&self, o: &Self) -> bool { let eq = self.commitment_number == o.commitment_number && self.to_broadcaster_value_sat == o.to_broadcaster_value_sat && @@ -1467,6 +1529,7 @@ impl PartialEq for CommitmentTransaction { } impl Writeable for CommitmentTransaction { + #[rustfmt::skip] fn write(&self, writer: &mut W) -> Result<(), io::Error> { let legacy_deserialization_prevention_marker = legacy_deserialization_prevention_marker_for_channel_type_features(&self.channel_type_features); write_tlv_fields!(writer, { @@ -1486,6 +1549,7 @@ impl Writeable for CommitmentTransaction { } impl Readable for CommitmentTransaction { + #[rustfmt::skip] fn read(reader: &mut R) -> Result { _init_and_read_len_prefixed_tlv_fields!(reader, { (0, commitment_number, required), @@ -1524,6 +1588,7 @@ impl CommitmentTransaction { /// All HTLCs MUST be above the dust limit for the channel. /// The broadcaster and countersignatory amounts MUST be either 0 or above dust. If the amount /// is 0, the corresponding output will be omitted from the transaction. + #[rustfmt::skip] pub fn new(commitment_number: u64, per_commitment_point: &PublicKey, to_broadcaster_value_sat: u64, to_countersignatory_value_sat: u64, feerate_per_kw: u32, mut nondust_htlcs: Vec, channel_parameters: &DirectedChannelTransactionParameters, secp_ctx: &Secp256k1) -> CommitmentTransaction { let to_broadcaster_value_sat = Amount::from_sat(to_broadcaster_value_sat); let to_countersignatory_value_sat = Amount::from_sat(to_countersignatory_value_sat); @@ -1570,6 +1635,7 @@ impl CommitmentTransaction { // // `txouts` and `nondust_htlcs` MUST be of equal length, and of length >= 2. // For all `i < len`, the `TxOut` at `txouts[i]` MUST correspond to the HTLC at `nondust_htlcs[i]`. + #[rustfmt::skip] fn is_left_greater(i: usize, txouts: &Vec, nondust_htlcs: &Vec) -> bool { txouts[i - 1].value.cmp(&txouts[i].value) .then(txouts[i - 1].script_pubkey.cmp(&txouts[i].script_pubkey)) @@ -1581,6 +1647,7 @@ impl CommitmentTransaction { .is_gt() } + #[rustfmt::skip] fn rebuild_transaction(&self, keys: &TxCreationKeys, channel_parameters: &DirectedChannelTransactionParameters) -> Result { let (obscured_commitment_transaction_number, txins) = Self::build_inputs(self.commitment_number, channel_parameters); @@ -1622,6 +1689,7 @@ impl CommitmentTransaction { Ok(built_transaction) } + #[rustfmt::skip] fn make_transaction(obscured_commitment_transaction_number: u64, txins: Vec, outputs: Vec) -> Transaction { Transaction { version: Version::TWO, @@ -1631,6 +1699,7 @@ impl CommitmentTransaction { } } + #[rustfmt::skip] fn build_outputs_and_htlcs( keys: &TxCreationKeys, to_broadcaster_value_sat: Amount, @@ -1685,6 +1754,7 @@ impl CommitmentTransaction { outputs } + #[rustfmt::skip] fn insert_non_htlc_outputs( keys: &TxCreationKeys, to_broadcaster_value_sat: Amount, @@ -1744,6 +1814,7 @@ impl CommitmentTransaction { } } + #[rustfmt::skip] fn build_htlc_outputs(keys: &TxCreationKeys, nondust_htlcs: &Vec, channel_type: &ChannelTypeFeatures) -> Vec { // Allocate memory for the 4 possible non-htlc outputs let mut txouts = Vec::with_capacity(nondust_htlcs.len() + 4); @@ -1760,6 +1831,7 @@ impl CommitmentTransaction { txouts } + #[rustfmt::skip] fn build_sorted_htlc_outputs( keys: &TxCreationKeys, nondust_htlcs: &mut Vec, @@ -1795,6 +1867,7 @@ impl CommitmentTransaction { txouts } + #[rustfmt::skip] fn build_inputs(commitment_number: u64, channel_parameters: &DirectedChannelTransactionParameters) -> (u64, Vec) { let broadcaster_pubkeys = channel_parameters.broadcaster_pubkeys(); let countersignatory_pubkeys = channel_parameters.countersignatory_pubkeys(); @@ -1871,6 +1944,7 @@ impl CommitmentTransaction { /// /// An external validating signer must call this method before signing /// or using the built transaction. + #[rustfmt::skip] pub fn verify(&self, channel_parameters: &DirectedChannelTransactionParameters, secp_ctx: &Secp256k1) -> Result { // This is the only field of the key cache that we trust let per_commitment_point = &self.keys.per_commitment_point; @@ -1899,6 +1973,7 @@ pub struct TrustedCommitmentTransaction<'a> { impl<'a> Deref for TrustedCommitmentTransaction<'a> { type Target = CommitmentTransaction; + #[rustfmt::skip] fn deref(&self) -> &Self::Target { self.inner } } @@ -1929,6 +2004,7 @@ impl<'a> TrustedCommitmentTransaction<'a> { /// The returned Vec has one entry for each HTLC, and in the same order. /// /// This function is only valid in the holder commitment context, it always uses EcdsaSighashType::All. + #[rustfmt::skip] pub fn get_htlc_sigs( &self, htlc_base_key: &SecretKey, channel_parameters: &DirectedChannelTransactionParameters, entropy_source: &ES, secp_ctx: &Secp256k1, @@ -1960,6 +2036,7 @@ impl<'a> TrustedCommitmentTransaction<'a> { /// - This commitment was created before LDK 0.0.117. In this case, the /// commitment transaction previously didn't contain enough information to locate the /// revokeable output. + #[rustfmt::skip] pub fn revokeable_output_index(&self) -> Option { let revokeable_redeemscript = get_revokeable_redeemscript( &self.keys.revocation_key, @@ -1984,6 +2061,7 @@ impl<'a> TrustedCommitmentTransaction<'a> { /// The built transaction will allow fee bumping with RBF, and this method takes /// `feerate_per_kw` as an input such that multiple copies of a justice transaction at different /// fee rates may be built. + #[rustfmt::skip] pub fn build_to_local_justice_tx(&self, feerate_per_kw: u64, destination_script: ScriptBuf) -> Result { let output_idx = self.revokeable_output_index().ok_or(())?; @@ -2012,7 +2090,6 @@ impl<'a> TrustedCommitmentTransaction<'a> { justice_tx.output[0].value = value.checked_sub(fee).ok_or(())?; Ok(justice_tx) } - } /// Commitment transaction numbers which appear in the transactions themselves are XOR'd with a @@ -2022,8 +2099,7 @@ impl<'a> TrustedCommitmentTransaction<'a> { /// This function gets the shared secret from relevant channel public keys and can be used to /// "decrypt" the commitment transaction number given a commitment transaction on-chain. pub fn get_commitment_transaction_number_obscure_factor( - broadcaster_payment_basepoint: &PublicKey, - countersignatory_payment_basepoint: &PublicKey, + broadcaster_payment_basepoint: &PublicKey, countersignatory_payment_basepoint: &PublicKey, outbound_from_broadcaster: bool, ) -> u64 { let mut sha = Sha256::engine(); @@ -2047,18 +2123,23 @@ pub fn get_commitment_transaction_number_obscure_factor( #[cfg(test)] mod tests { - use super::{CounterpartyCommitmentSecrets, ChannelPublicKeys}; + use super::{ChannelPublicKeys, CounterpartyCommitmentSecrets}; use crate::chain; - use crate::ln::chan_utils::{get_htlc_redeemscript, get_to_countersigner_keyed_anchor_redeemscript, CommitmentTransaction, ChannelTransactionParameters, CounterpartyChannelTransactionParameters, HTLCOutputInCommitment, TrustedCommitmentTransaction, BuiltCommitmentTransaction}; - use bitcoin::secp256k1::{self, PublicKey, SecretKey, Secp256k1}; - use crate::util::test_utils; + use crate::ln::chan_utils::{ + get_htlc_redeemscript, get_to_countersigner_keyed_anchor_redeemscript, + BuiltCommitmentTransaction, ChannelTransactionParameters, CommitmentTransaction, + CounterpartyChannelTransactionParameters, HTLCOutputInCommitment, + TrustedCommitmentTransaction, + }; use crate::sign::{ChannelSigner, SignerProvider}; - use bitcoin::{Network, Txid, ScriptBuf, CompressedPublicKey}; + use crate::types::features::ChannelTypeFeatures; + use crate::types::payment::PaymentHash; + use crate::util::test_utils; use bitcoin::hashes::Hash; use bitcoin::hex::FromHex; - use crate::types::payment::PaymentHash; + use bitcoin::secp256k1::{self, PublicKey, Secp256k1, SecretKey}; use bitcoin::PublicKey as BitcoinPublicKey; - use crate::types::features::ChannelTypeFeatures; + use bitcoin::{CompressedPublicKey, Network, ScriptBuf, Txid}; #[allow(unused_imports)] use crate::prelude::*; @@ -2069,10 +2150,11 @@ mod tests { feerate_per_kw: u32, channel_parameters: ChannelTransactionParameters, counterparty_pubkeys: ChannelPublicKeys, - secp_ctx: Secp256k1::, + secp_ctx: Secp256k1, } impl TestCommitmentTxBuilder { + #[rustfmt::skip] fn new() -> Self { let secp_ctx = Secp256k1::new(); let seed = [42; 32]; @@ -2105,6 +2187,7 @@ mod tests { } } + #[rustfmt::skip] fn build(&self, to_broadcaster_sats: u64, to_countersignatory_sats: u64, nondust_htlcs: Vec) -> CommitmentTransaction { CommitmentTransaction::new( self.commitment_number, &self.per_commitment_point, to_broadcaster_sats, to_countersignatory_sats, self.feerate_per_kw, @@ -2112,12 +2195,15 @@ mod tests { ) } - fn verify<'a>(&self, tx: &'a CommitmentTransaction) -> Result, ()> { + fn verify<'a>( + &self, tx: &'a CommitmentTransaction, + ) -> Result, ()> { tx.verify(&self.channel_parameters.as_holder_broadcastable(), &self.secp_ctx) } } #[test] + #[rustfmt::skip] fn test_anchors() { let mut builder = TestCommitmentTxBuilder::new(); @@ -2201,6 +2287,7 @@ mod tests { } #[test] + #[rustfmt::skip] fn test_building_to_local_justice_tx() { let builder = TestCommitmentTxBuilder::new(); @@ -2241,6 +2328,7 @@ mod tests { let mut secrets: Vec<[u8; 32]> = Vec::new(); let mut monitor; + #[rustfmt::skip] macro_rules! test_secrets { () => { let mut idx = 281474976710655; @@ -2259,42 +2347,82 @@ mod tests { secrets.clear(); secrets.push([0; 32]); - secrets.last_mut().unwrap()[0..32].clone_from_slice(&>::from_hex("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap()); + secrets.last_mut().unwrap()[0..32].clone_from_slice( + &>::from_hex( + "7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc", + ) + .unwrap(), + ); monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap(); test_secrets!(); secrets.push([0; 32]); - secrets.last_mut().unwrap()[0..32].clone_from_slice(&>::from_hex("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap()); + secrets.last_mut().unwrap()[0..32].clone_from_slice( + &>::from_hex( + "c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964", + ) + .unwrap(), + ); monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap(); test_secrets!(); secrets.push([0; 32]); - secrets.last_mut().unwrap()[0..32].clone_from_slice(&>::from_hex("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap()); + secrets.last_mut().unwrap()[0..32].clone_from_slice( + &>::from_hex( + "2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8", + ) + .unwrap(), + ); monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap(); test_secrets!(); secrets.push([0; 32]); - secrets.last_mut().unwrap()[0..32].clone_from_slice(&>::from_hex("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap()); + secrets.last_mut().unwrap()[0..32].clone_from_slice( + &>::from_hex( + "27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116", + ) + .unwrap(), + ); monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap(); test_secrets!(); secrets.push([0; 32]); - secrets.last_mut().unwrap()[0..32].clone_from_slice(&>::from_hex("c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd").unwrap()); + secrets.last_mut().unwrap()[0..32].clone_from_slice( + &>::from_hex( + "c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd", + ) + .unwrap(), + ); monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap(); test_secrets!(); secrets.push([0; 32]); - secrets.last_mut().unwrap()[0..32].clone_from_slice(&>::from_hex("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap()); + secrets.last_mut().unwrap()[0..32].clone_from_slice( + &>::from_hex( + "969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2", + ) + .unwrap(), + ); monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).unwrap(); test_secrets!(); secrets.push([0; 32]); - secrets.last_mut().unwrap()[0..32].clone_from_slice(&>::from_hex("a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32").unwrap()); + secrets.last_mut().unwrap()[0..32].clone_from_slice( + &>::from_hex( + "a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32", + ) + .unwrap(), + ); monitor.provide_secret(281474976710649, secrets.last().unwrap().clone()).unwrap(); test_secrets!(); secrets.push([0; 32]); - secrets.last_mut().unwrap()[0..32].clone_from_slice(&>::from_hex("05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17").unwrap()); + secrets.last_mut().unwrap()[0..32].clone_from_slice( + &>::from_hex( + "05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17", + ) + .unwrap(), + ); monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()).unwrap(); test_secrets!(); } @@ -2305,13 +2433,25 @@ mod tests { secrets.clear(); secrets.push([0; 32]); - secrets.last_mut().unwrap()[0..32].clone_from_slice(&>::from_hex("02a40c85b6f28da08dfdbe0926c53fab2de6d28c10301f8f7c4073d5e42e3148").unwrap()); + secrets.last_mut().unwrap()[0..32].clone_from_slice( + &>::from_hex( + "02a40c85b6f28da08dfdbe0926c53fab2de6d28c10301f8f7c4073d5e42e3148", + ) + .unwrap(), + ); monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap(); test_secrets!(); secrets.push([0; 32]); - secrets.last_mut().unwrap()[0..32].clone_from_slice(&>::from_hex("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap()); - assert!(monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).is_err()); + secrets.last_mut().unwrap()[0..32].clone_from_slice( + &>::from_hex( + "c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964", + ) + .unwrap(), + ); + assert!(monitor + .provide_secret(281474976710654, secrets.last().unwrap().clone()) + .is_err()); } { @@ -2320,23 +2460,45 @@ mod tests { secrets.clear(); secrets.push([0; 32]); - secrets.last_mut().unwrap()[0..32].clone_from_slice(&>::from_hex("02a40c85b6f28da08dfdbe0926c53fab2de6d28c10301f8f7c4073d5e42e3148").unwrap()); + secrets.last_mut().unwrap()[0..32].clone_from_slice( + &>::from_hex( + "02a40c85b6f28da08dfdbe0926c53fab2de6d28c10301f8f7c4073d5e42e3148", + ) + .unwrap(), + ); monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap(); test_secrets!(); secrets.push([0; 32]); - secrets.last_mut().unwrap()[0..32].clone_from_slice(&>::from_hex("dddc3a8d14fddf2b68fa8c7fbad2748274937479dd0f8930d5ebb4ab6bd866a3").unwrap()); + secrets.last_mut().unwrap()[0..32].clone_from_slice( + &>::from_hex( + "dddc3a8d14fddf2b68fa8c7fbad2748274937479dd0f8930d5ebb4ab6bd866a3", + ) + .unwrap(), + ); monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap(); test_secrets!(); secrets.push([0; 32]); - secrets.last_mut().unwrap()[0..32].clone_from_slice(&>::from_hex("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap()); + secrets.last_mut().unwrap()[0..32].clone_from_slice( + &>::from_hex( + "2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8", + ) + .unwrap(), + ); monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap(); test_secrets!(); secrets.push([0; 32]); - secrets.last_mut().unwrap()[0..32].clone_from_slice(&>::from_hex("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap()); - assert!(monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).is_err()); + secrets.last_mut().unwrap()[0..32].clone_from_slice( + &>::from_hex( + "27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116", + ) + .unwrap(), + ); + assert!(monitor + .provide_secret(281474976710652, secrets.last().unwrap().clone()) + .is_err()); } { @@ -2345,23 +2507,45 @@ mod tests { secrets.clear(); secrets.push([0; 32]); - secrets.last_mut().unwrap()[0..32].clone_from_slice(&>::from_hex("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap()); + secrets.last_mut().unwrap()[0..32].clone_from_slice( + &>::from_hex( + "7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc", + ) + .unwrap(), + ); monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap(); test_secrets!(); secrets.push([0; 32]); - secrets.last_mut().unwrap()[0..32].clone_from_slice(&>::from_hex("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap()); + secrets.last_mut().unwrap()[0..32].clone_from_slice( + &>::from_hex( + "c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964", + ) + .unwrap(), + ); monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap(); test_secrets!(); secrets.push([0; 32]); - secrets.last_mut().unwrap()[0..32].clone_from_slice(&>::from_hex("c51a18b13e8527e579ec56365482c62f180b7d5760b46e9477dae59e87ed423a").unwrap()); + secrets.last_mut().unwrap()[0..32].clone_from_slice( + &>::from_hex( + "c51a18b13e8527e579ec56365482c62f180b7d5760b46e9477dae59e87ed423a", + ) + .unwrap(), + ); monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap(); test_secrets!(); secrets.push([0; 32]); - secrets.last_mut().unwrap()[0..32].clone_from_slice(&>::from_hex("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap()); - assert!(monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).is_err()); + secrets.last_mut().unwrap()[0..32].clone_from_slice( + &>::from_hex( + "27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116", + ) + .unwrap(), + ); + assert!(monitor + .provide_secret(281474976710652, secrets.last().unwrap().clone()) + .is_err()); } { @@ -2370,43 +2554,85 @@ mod tests { secrets.clear(); secrets.push([0; 32]); - secrets.last_mut().unwrap()[0..32].clone_from_slice(&>::from_hex("02a40c85b6f28da08dfdbe0926c53fab2de6d28c10301f8f7c4073d5e42e3148").unwrap()); + secrets.last_mut().unwrap()[0..32].clone_from_slice( + &>::from_hex( + "02a40c85b6f28da08dfdbe0926c53fab2de6d28c10301f8f7c4073d5e42e3148", + ) + .unwrap(), + ); monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap(); test_secrets!(); secrets.push([0; 32]); - secrets.last_mut().unwrap()[0..32].clone_from_slice(&>::from_hex("dddc3a8d14fddf2b68fa8c7fbad2748274937479dd0f8930d5ebb4ab6bd866a3").unwrap()); + secrets.last_mut().unwrap()[0..32].clone_from_slice( + &>::from_hex( + "dddc3a8d14fddf2b68fa8c7fbad2748274937479dd0f8930d5ebb4ab6bd866a3", + ) + .unwrap(), + ); monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap(); test_secrets!(); secrets.push([0; 32]); - secrets.last_mut().unwrap()[0..32].clone_from_slice(&>::from_hex("c51a18b13e8527e579ec56365482c62f180b7d5760b46e9477dae59e87ed423a").unwrap()); + secrets.last_mut().unwrap()[0..32].clone_from_slice( + &>::from_hex( + "c51a18b13e8527e579ec56365482c62f180b7d5760b46e9477dae59e87ed423a", + ) + .unwrap(), + ); monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap(); test_secrets!(); secrets.push([0; 32]); - secrets.last_mut().unwrap()[0..32].clone_from_slice(&>::from_hex("ba65d7b0ef55a3ba300d4e87af29868f394f8f138d78a7011669c79b37b936f4").unwrap()); + secrets.last_mut().unwrap()[0..32].clone_from_slice( + &>::from_hex( + "ba65d7b0ef55a3ba300d4e87af29868f394f8f138d78a7011669c79b37b936f4", + ) + .unwrap(), + ); monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap(); test_secrets!(); secrets.push([0; 32]); - secrets.last_mut().unwrap()[0..32].clone_from_slice(&>::from_hex("c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd").unwrap()); + secrets.last_mut().unwrap()[0..32].clone_from_slice( + &>::from_hex( + "c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd", + ) + .unwrap(), + ); monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap(); test_secrets!(); secrets.push([0; 32]); - secrets.last_mut().unwrap()[0..32].clone_from_slice(&>::from_hex("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap()); + secrets.last_mut().unwrap()[0..32].clone_from_slice( + &>::from_hex( + "969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2", + ) + .unwrap(), + ); monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).unwrap(); test_secrets!(); secrets.push([0; 32]); - secrets.last_mut().unwrap()[0..32].clone_from_slice(&>::from_hex("a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32").unwrap()); + secrets.last_mut().unwrap()[0..32].clone_from_slice( + &>::from_hex( + "a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32", + ) + .unwrap(), + ); monitor.provide_secret(281474976710649, secrets.last().unwrap().clone()).unwrap(); test_secrets!(); secrets.push([0; 32]); - secrets.last_mut().unwrap()[0..32].clone_from_slice(&>::from_hex("05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17").unwrap()); - assert!(monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()).is_err()); + secrets.last_mut().unwrap()[0..32].clone_from_slice( + &>::from_hex( + "05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17", + ) + .unwrap(), + ); + assert!(monitor + .provide_secret(281474976710648, secrets.last().unwrap().clone()) + .is_err()); } { @@ -2415,33 +2641,65 @@ mod tests { secrets.clear(); secrets.push([0; 32]); - secrets.last_mut().unwrap()[0..32].clone_from_slice(&>::from_hex("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap()); + secrets.last_mut().unwrap()[0..32].clone_from_slice( + &>::from_hex( + "7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc", + ) + .unwrap(), + ); monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap(); test_secrets!(); secrets.push([0; 32]); - secrets.last_mut().unwrap()[0..32].clone_from_slice(&>::from_hex("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap()); + secrets.last_mut().unwrap()[0..32].clone_from_slice( + &>::from_hex( + "c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964", + ) + .unwrap(), + ); monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap(); test_secrets!(); secrets.push([0; 32]); - secrets.last_mut().unwrap()[0..32].clone_from_slice(&>::from_hex("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap()); + secrets.last_mut().unwrap()[0..32].clone_from_slice( + &>::from_hex( + "2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8", + ) + .unwrap(), + ); monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap(); test_secrets!(); secrets.push([0; 32]); - secrets.last_mut().unwrap()[0..32].clone_from_slice(&>::from_hex("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap()); + secrets.last_mut().unwrap()[0..32].clone_from_slice( + &>::from_hex( + "27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116", + ) + .unwrap(), + ); monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap(); test_secrets!(); secrets.push([0; 32]); - secrets.last_mut().unwrap()[0..32].clone_from_slice(&>::from_hex("631373ad5f9ef654bb3dade742d09504c567edd24320d2fcd68e3cc47e2ff6a6").unwrap()); + secrets.last_mut().unwrap()[0..32].clone_from_slice( + &>::from_hex( + "631373ad5f9ef654bb3dade742d09504c567edd24320d2fcd68e3cc47e2ff6a6", + ) + .unwrap(), + ); monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap(); test_secrets!(); secrets.push([0; 32]); - secrets.last_mut().unwrap()[0..32].clone_from_slice(&>::from_hex("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap()); - assert!(monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).is_err()); + secrets.last_mut().unwrap()[0..32].clone_from_slice( + &>::from_hex( + "969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2", + ) + .unwrap(), + ); + assert!(monitor + .provide_secret(281474976710650, secrets.last().unwrap().clone()) + .is_err()); } { @@ -2450,43 +2708,85 @@ mod tests { secrets.clear(); secrets.push([0; 32]); - secrets.last_mut().unwrap()[0..32].clone_from_slice(&>::from_hex("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap()); + secrets.last_mut().unwrap()[0..32].clone_from_slice( + &>::from_hex( + "7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc", + ) + .unwrap(), + ); monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap(); test_secrets!(); secrets.push([0; 32]); - secrets.last_mut().unwrap()[0..32].clone_from_slice(&>::from_hex("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap()); + secrets.last_mut().unwrap()[0..32].clone_from_slice( + &>::from_hex( + "c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964", + ) + .unwrap(), + ); monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap(); test_secrets!(); secrets.push([0; 32]); - secrets.last_mut().unwrap()[0..32].clone_from_slice(&>::from_hex("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap()); + secrets.last_mut().unwrap()[0..32].clone_from_slice( + &>::from_hex( + "2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8", + ) + .unwrap(), + ); monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap(); test_secrets!(); secrets.push([0; 32]); - secrets.last_mut().unwrap()[0..32].clone_from_slice(&>::from_hex("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap()); + secrets.last_mut().unwrap()[0..32].clone_from_slice( + &>::from_hex( + "27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116", + ) + .unwrap(), + ); monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap(); test_secrets!(); secrets.push([0; 32]); - secrets.last_mut().unwrap()[0..32].clone_from_slice(&>::from_hex("631373ad5f9ef654bb3dade742d09504c567edd24320d2fcd68e3cc47e2ff6a6").unwrap()); + secrets.last_mut().unwrap()[0..32].clone_from_slice( + &>::from_hex( + "631373ad5f9ef654bb3dade742d09504c567edd24320d2fcd68e3cc47e2ff6a6", + ) + .unwrap(), + ); monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap(); test_secrets!(); secrets.push([0; 32]); - secrets.last_mut().unwrap()[0..32].clone_from_slice(&>::from_hex("b7e76a83668bde38b373970155c868a653304308f9896692f904a23731224bb1").unwrap()); + secrets.last_mut().unwrap()[0..32].clone_from_slice( + &>::from_hex( + "b7e76a83668bde38b373970155c868a653304308f9896692f904a23731224bb1", + ) + .unwrap(), + ); monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).unwrap(); test_secrets!(); secrets.push([0; 32]); - secrets.last_mut().unwrap()[0..32].clone_from_slice(&>::from_hex("a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32").unwrap()); + secrets.last_mut().unwrap()[0..32].clone_from_slice( + &>::from_hex( + "a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32", + ) + .unwrap(), + ); monitor.provide_secret(281474976710649, secrets.last().unwrap().clone()).unwrap(); test_secrets!(); secrets.push([0; 32]); - secrets.last_mut().unwrap()[0..32].clone_from_slice(&>::from_hex("05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17").unwrap()); - assert!(monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()).is_err()); + secrets.last_mut().unwrap()[0..32].clone_from_slice( + &>::from_hex( + "05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17", + ) + .unwrap(), + ); + assert!(monitor + .provide_secret(281474976710648, secrets.last().unwrap().clone()) + .is_err()); } { @@ -2495,43 +2795,85 @@ mod tests { secrets.clear(); secrets.push([0; 32]); - secrets.last_mut().unwrap()[0..32].clone_from_slice(&>::from_hex("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap()); + secrets.last_mut().unwrap()[0..32].clone_from_slice( + &>::from_hex( + "7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc", + ) + .unwrap(), + ); monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap(); test_secrets!(); secrets.push([0; 32]); - secrets.last_mut().unwrap()[0..32].clone_from_slice(&>::from_hex("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap()); + secrets.last_mut().unwrap()[0..32].clone_from_slice( + &>::from_hex( + "c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964", + ) + .unwrap(), + ); monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap(); test_secrets!(); secrets.push([0; 32]); - secrets.last_mut().unwrap()[0..32].clone_from_slice(&>::from_hex("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap()); + secrets.last_mut().unwrap()[0..32].clone_from_slice( + &>::from_hex( + "2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8", + ) + .unwrap(), + ); monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap(); test_secrets!(); secrets.push([0; 32]); - secrets.last_mut().unwrap()[0..32].clone_from_slice(&>::from_hex("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap()); + secrets.last_mut().unwrap()[0..32].clone_from_slice( + &>::from_hex( + "27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116", + ) + .unwrap(), + ); monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap(); test_secrets!(); secrets.push([0; 32]); - secrets.last_mut().unwrap()[0..32].clone_from_slice(&>::from_hex("c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd").unwrap()); + secrets.last_mut().unwrap()[0..32].clone_from_slice( + &>::from_hex( + "c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd", + ) + .unwrap(), + ); monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap(); test_secrets!(); secrets.push([0; 32]); - secrets.last_mut().unwrap()[0..32].clone_from_slice(&>::from_hex("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap()); + secrets.last_mut().unwrap()[0..32].clone_from_slice( + &>::from_hex( + "969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2", + ) + .unwrap(), + ); monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).unwrap(); test_secrets!(); secrets.push([0; 32]); - secrets.last_mut().unwrap()[0..32].clone_from_slice(&>::from_hex("e7971de736e01da8ed58b94c2fc216cb1dca9e326f3a96e7194fe8ea8af6c0a3").unwrap()); + secrets.last_mut().unwrap()[0..32].clone_from_slice( + &>::from_hex( + "e7971de736e01da8ed58b94c2fc216cb1dca9e326f3a96e7194fe8ea8af6c0a3", + ) + .unwrap(), + ); monitor.provide_secret(281474976710649, secrets.last().unwrap().clone()).unwrap(); test_secrets!(); secrets.push([0; 32]); - secrets.last_mut().unwrap()[0..32].clone_from_slice(&>::from_hex("05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17").unwrap()); - assert!(monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()).is_err()); + secrets.last_mut().unwrap()[0..32].clone_from_slice( + &>::from_hex( + "05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17", + ) + .unwrap(), + ); + assert!(monitor + .provide_secret(281474976710648, secrets.last().unwrap().clone()) + .is_err()); } { @@ -2540,43 +2882,85 @@ mod tests { secrets.clear(); secrets.push([0; 32]); - secrets.last_mut().unwrap()[0..32].clone_from_slice(&>::from_hex("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap()); + secrets.last_mut().unwrap()[0..32].clone_from_slice( + &>::from_hex( + "7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc", + ) + .unwrap(), + ); monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap(); test_secrets!(); secrets.push([0; 32]); - secrets.last_mut().unwrap()[0..32].clone_from_slice(&>::from_hex("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap()); + secrets.last_mut().unwrap()[0..32].clone_from_slice( + &>::from_hex( + "c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964", + ) + .unwrap(), + ); monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap(); test_secrets!(); secrets.push([0; 32]); - secrets.last_mut().unwrap()[0..32].clone_from_slice(&>::from_hex("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap()); + secrets.last_mut().unwrap()[0..32].clone_from_slice( + &>::from_hex( + "2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8", + ) + .unwrap(), + ); monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap(); test_secrets!(); secrets.push([0; 32]); - secrets.last_mut().unwrap()[0..32].clone_from_slice(&>::from_hex("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap()); + secrets.last_mut().unwrap()[0..32].clone_from_slice( + &>::from_hex( + "27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116", + ) + .unwrap(), + ); monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap(); test_secrets!(); secrets.push([0; 32]); - secrets.last_mut().unwrap()[0..32].clone_from_slice(&>::from_hex("c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd").unwrap()); + secrets.last_mut().unwrap()[0..32].clone_from_slice( + &>::from_hex( + "c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd", + ) + .unwrap(), + ); monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap(); test_secrets!(); secrets.push([0; 32]); - secrets.last_mut().unwrap()[0..32].clone_from_slice(&>::from_hex("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap()); + secrets.last_mut().unwrap()[0..32].clone_from_slice( + &>::from_hex( + "969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2", + ) + .unwrap(), + ); monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).unwrap(); test_secrets!(); secrets.push([0; 32]); - secrets.last_mut().unwrap()[0..32].clone_from_slice(&>::from_hex("a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32").unwrap()); + secrets.last_mut().unwrap()[0..32].clone_from_slice( + &>::from_hex( + "a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32", + ) + .unwrap(), + ); monitor.provide_secret(281474976710649, secrets.last().unwrap().clone()).unwrap(); test_secrets!(); secrets.push([0; 32]); - secrets.last_mut().unwrap()[0..32].clone_from_slice(&>::from_hex("a7efbc61aac46d34f77778bac22c8a20c6a46ca460addc49009bda875ec88fa4").unwrap()); - assert!(monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()).is_err()); + secrets.last_mut().unwrap()[0..32].clone_from_slice( + &>::from_hex( + "a7efbc61aac46d34f77778bac22c8a20c6a46ca460addc49009bda875ec88fa4", + ) + .unwrap(), + ); + assert!(monitor + .provide_secret(281474976710648, secrets.last().unwrap().clone()) + .is_err()); } } @@ -2584,6 +2968,7 @@ mod tests { fn test_verify_sorted_htlcs() { // Assert that `CommitmentTransaction::verify` checks that the HTLCs are sorted + #[rustfmt::skip] macro_rules! swap_htlcs { ($small_htlc: expr, $big_htlc: expr) => { let builder = TestCommitmentTxBuilder::new(); diff --git a/lightning/src/ln/chanmon_update_fail_tests.rs b/lightning/src/ln/chanmon_update_fail_tests.rs index d58934b4bcb..cd3cdf193e1 100644 --- a/lightning/src/ln/chanmon_update_fail_tests.rs +++ b/lightning/src/ln/chanmon_update_fail_tests.rs @@ -1,5 +1,3 @@ -#![cfg_attr(rustfmt, rustfmt_skip)] - // This file is Copyright its original authors, visible in version control // history. // @@ -14,31 +12,34 @@ //! There are a bunch of these as their handling is relatively error-prone so they are split out //! here. See also the chanmon_fail_consistency fuzz test. -use bitcoin::constants::genesis_block; -use bitcoin::hash_types::BlockHash; -use bitcoin::network::Network; -use crate::chain::channelmonitor::{ANTI_REORG_DELAY, ChannelMonitor}; +use crate::chain::channelmonitor::{ChannelMonitor, ANTI_REORG_DELAY}; use crate::chain::{ChannelMonitorUpdateStatus, Listen, Watch}; -use crate::events::{Event, PaymentPurpose, ClosureReason, HTLCHandlingFailureType}; -use crate::ln::channelmanager::{PaymentId, RAACommitmentOrder, RecipientOnionFields}; +use crate::events::{ClosureReason, Event, HTLCHandlingFailureType, PaymentPurpose}; use crate::ln::channel::AnnouncementSigsState; +use crate::ln::channelmanager::{PaymentId, RAACommitmentOrder, RecipientOnionFields}; use crate::ln::msgs; +use crate::ln::msgs::{ + BaseMessageHandler, ChannelMessageHandler, MessageSendEvent, RoutingMessageHandler, +}; use crate::ln::types::ChannelId; -use crate::ln::msgs::{BaseMessageHandler, ChannelMessageHandler, RoutingMessageHandler, MessageSendEvent}; -use crate::util::test_channel_signer::TestChannelSigner; use crate::util::ser::{ReadableArgs, Writeable}; +use crate::util::test_channel_signer::TestChannelSigner; use crate::util::test_utils::TestBroadcaster; +use bitcoin::constants::genesis_block; +use bitcoin::hash_types::BlockHash; +use bitcoin::network::Network; use crate::ln::functional_test_utils::*; use crate::util::test_utils; use crate::io; -use bitcoin::hashes::Hash; use crate::prelude::*; use crate::sync::{Arc, Mutex}; +use bitcoin::hashes::Hash; #[test] +#[rustfmt::skip] fn test_monitor_and_persister_update_fail() { // Test that if both updating the `ChannelMonitor` and persisting the updated // `ChannelMonitor` fail, then the failure from updating the `ChannelMonitor` @@ -119,6 +120,7 @@ fn test_monitor_and_persister_update_fail() { expect_payment_sent(&nodes[0], preimage, None, false, false); } +#[rustfmt::skip] fn do_test_simple_monitor_temporary_update_fail(disconnect: bool) { // Test that we can recover from a simple temporary monitor update failure optionally with // a disconnect in between @@ -226,6 +228,7 @@ fn test_simple_monitor_temporary_update_fail() { do_test_simple_monitor_temporary_update_fail(true); } +#[rustfmt::skip] fn do_test_monitor_temporary_update_fail(disconnect_count: usize) { let disconnect_flags = 8 | 16; @@ -319,6 +322,7 @@ fn do_test_monitor_temporary_update_fail(disconnect_count: usize) { nodes[0].chain_monitor.chain_monitor.force_channel_monitor_updated(channel_id, latest_update); check_added_monitors!(nodes[0], 0); + #[rustfmt::skip] macro_rules! disconnect_reconnect_peers { () => { { nodes[0].node.peer_disconnected(nodes[1].node.get_our_node_id()); nodes[1].node.peer_disconnected(nodes[0].node.get_our_node_id()); @@ -452,6 +456,7 @@ fn do_test_monitor_temporary_update_fail(disconnect_count: usize) { let as_commitment_update; let bs_second_commitment_update; + #[rustfmt::skip] macro_rules! handle_bs_raa { () => { nodes[0].node.handle_revoke_and_ack(nodes[1].node.get_our_node_id(), &bs_revoke_and_ack); as_commitment_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id()); @@ -463,6 +468,7 @@ fn do_test_monitor_temporary_update_fail(disconnect_count: usize) { check_added_monitors!(nodes[0], 1); } } + #[rustfmt::skip] macro_rules! handle_initial_raa { () => { nodes[1].node.handle_revoke_and_ack(nodes[0].node.get_our_node_id(), &initial_revoke_and_ack); bs_second_commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id()); @@ -599,6 +605,7 @@ fn test_monitor_temporary_update_fail_c() { } #[test] +#[rustfmt::skip] fn test_monitor_update_fail_cs() { // Tests handling of a monitor update failure when processing an incoming commitment_signed let chanmon_cfgs = create_chanmon_cfgs(2); @@ -691,6 +698,7 @@ fn test_monitor_update_fail_cs() { } #[test] +#[rustfmt::skip] fn test_monitor_update_fail_no_rebroadcast() { // Tests handling of a monitor update failure when no message rebroadcasting on // channel_monitor_updated() is required. Backported from chanmon_fail_consistency @@ -739,6 +747,7 @@ fn test_monitor_update_fail_no_rebroadcast() { } #[test] +#[rustfmt::skip] fn test_monitor_update_raa_while_paused() { // Tests handling of an RAA while monitor updating has already been marked failed. // Backported from chanmon_fail_consistency fuzz tests as this used to be broken. @@ -813,6 +822,7 @@ fn test_monitor_update_raa_while_paused() { claim_payment(&nodes[1], &[&nodes[0]], payment_preimage_2); } +#[rustfmt::skip] fn do_test_monitor_update_fail_raa(test_ignore_second_cs: bool) { // Tests handling of a monitor update failure when processing an incoming RAA let chanmon_cfgs = create_chanmon_cfgs(3); @@ -1085,6 +1095,7 @@ fn test_monitor_update_fail_raa() { } #[test] +#[rustfmt::skip] fn test_monitor_update_fail_reestablish() { // Simple test for message retransmission after monitor update failure on // channel_reestablish generating a monitor update (which comes from freeing holding cell @@ -1179,6 +1190,7 @@ fn test_monitor_update_fail_reestablish() { } #[test] +#[rustfmt::skip] fn raa_no_response_awaiting_raa_state() { // This is a rather convoluted test which ensures that if handling of an RAA does not happen // due to a previous monitor update failure, we still set AwaitingRemoteRevoke on the channel @@ -1298,6 +1310,7 @@ fn raa_no_response_awaiting_raa_state() { } #[test] +#[rustfmt::skip] fn claim_while_disconnected_monitor_update_fail() { // Test for claiming a payment while disconnected and then having the resulting // channel-update-generated monitor update fail. This kind of thing isn't a particularly @@ -1418,6 +1431,7 @@ fn claim_while_disconnected_monitor_update_fail() { } #[test] +#[rustfmt::skip] fn monitor_failed_no_reestablish_response() { // Test for receiving a channel_reestablish after a monitor update failure resulted in no // response to a commitment_signed. @@ -1499,6 +1513,7 @@ fn monitor_failed_no_reestablish_response() { } #[test] +#[rustfmt::skip] fn first_message_on_recv_ordering() { // Test that if the initial generator of a monitor-update-frozen state doesn't generate // messages, we're willing to flip the order of response messages if neccessary in resposne to @@ -1596,6 +1611,7 @@ fn first_message_on_recv_ordering() { } #[test] +#[rustfmt::skip] fn test_monitor_update_fail_claim() { // Basic test for monitor update failures when processing claim_funds calls. // We set up a simple 3-node network, sending a payment from A to B and failing B's monitor @@ -1718,6 +1734,7 @@ fn test_monitor_update_fail_claim() { } #[test] +#[rustfmt::skip] fn test_monitor_update_on_pending_forwards() { // Basic test for monitor update failures when processing pending HTLC fail/add forwards. // We do this with a simple 3-node network, sending a payment from A to C and one from C to A. @@ -1793,6 +1810,7 @@ fn test_monitor_update_on_pending_forwards() { } #[test] +#[rustfmt::skip] fn monitor_update_claim_fail_no_response() { // Test for claim_funds resulting in both a monitor update failure and no message response (due // to channel being AwaitingRAA). @@ -1849,6 +1867,7 @@ fn monitor_update_claim_fail_no_response() { // restore_b_before_conf has no meaning if !confirm_a_first // restore_b_before_lock has no meaning if confirm_a_first +#[rustfmt::skip] fn do_during_funding_monitor_fail(confirm_a_first: bool, restore_b_before_conf: bool, restore_b_before_lock: bool) { // Test that if the monitor update generated by funding_transaction_generated fails we continue // the channel setup happily after the update is restored. @@ -1976,6 +1995,7 @@ fn during_funding_monitor_fail() { } #[test] +#[rustfmt::skip] fn test_path_paused_mpp() { // Simple test of sending a multi-part payment where one path is currently blocked awaiting // monitor update @@ -2032,6 +2052,7 @@ fn test_path_paused_mpp() { } #[test] +#[rustfmt::skip] fn test_pending_update_fee_ack_on_reconnect() { // In early versions of our automated fee update patch, nodes did not correctly use the // previous channel feerate after sending an undelivered revoke_and_ack when re-sending an @@ -2127,6 +2148,7 @@ fn test_pending_update_fee_ack_on_reconnect() { } #[test] +#[rustfmt::skip] fn test_fail_htlc_on_broadcast_after_claim() { // In an earlier version of 7e78fa660cec8a73286c94c1073ee588140e7a01 we'd also fail the inbound // channel backwards if we received an HTLC failure after a HTLC fulfillment. Here we test a @@ -2172,6 +2194,7 @@ fn test_fail_htlc_on_broadcast_after_claim() { expect_payment_path_successful!(nodes[0]); } +#[rustfmt::skip] fn do_update_fee_resend_test(deliver_update: bool, parallel_updates: bool) { // In early versions we did not handle resending of update_fee on reconnect correctly. The // chanmon_consistency fuzz target, of course, immediately found it, but we test a few cases @@ -2273,6 +2296,7 @@ fn update_fee_resend_test() { do_update_fee_resend_test(true, true); } +#[rustfmt::skip] fn do_channel_holding_cell_serialize(disconnect: bool, reload_a: bool) { // Tests that, when we serialize a channel with AddHTLC entries in the holding cell, we // properly free them on reconnect. We previously failed such HTLCs upon serialization, but @@ -2469,6 +2493,7 @@ enum HTLCStatusAtDupClaim { HoldingCell, Cleared, } +#[rustfmt::skip] fn do_test_reconnect_dup_htlc_claims(htlc_status: HTLCStatusAtDupClaim, second_fails: bool) { // When receiving an update_fulfill_htlc message, we immediately forward the claim backwards // along the payment path before waiting for a full commitment_signed dance. This is great, but @@ -2588,6 +2613,7 @@ fn test_reconnect_dup_htlc_claims() { } #[test] +#[rustfmt::skip] fn test_temporary_error_during_shutdown() { // Test that temporary failures when updating the monitor's shutdown script delay cooperative // close. @@ -2643,6 +2669,7 @@ fn test_temporary_error_during_shutdown() { } #[test] +#[rustfmt::skip] fn double_temp_error() { // Test that it's OK to have multiple `ChainMonitor::update_channel` calls fail in a row. let chanmon_cfgs = create_chanmon_cfgs(2); @@ -2753,6 +2780,7 @@ fn double_temp_error() { expect_payment_sent!(nodes[0], payment_preimage_2); } +#[rustfmt::skip] fn do_test_outbound_reload_without_init_mon(use_0conf: bool) { // Test that if the monitor update generated in funding_signed is stored async and we restart // with the latest ChannelManager but the ChannelMonitor persistence never completed we happily @@ -2844,6 +2872,7 @@ fn test_outbound_reload_without_init_mon() { do_test_outbound_reload_without_init_mon(false); } +#[rustfmt::skip] fn do_test_inbound_reload_without_init_mon(use_0conf: bool, lock_commitment: bool) { // Test that if the monitor update generated by funding_transaction_generated is stored async // and we restart with the latest ChannelManager but the ChannelMonitor persistence never @@ -2935,6 +2964,7 @@ fn test_inbound_reload_without_init_mon() { } #[test] +#[rustfmt::skip] fn test_blocked_chan_preimage_release() { // Test that even if a channel's `ChannelMonitorUpdate` flow is blocked waiting on an event to // be handled HTLC preimage `ChannelMonitorUpdate`s will still go out. @@ -3007,6 +3037,7 @@ fn test_blocked_chan_preimage_release() { expect_payment_sent(&nodes[2], payment_preimage_2, None, true, true); } +#[rustfmt::skip] fn do_test_inverted_mon_completion_order(with_latest_manager: bool, complete_bc_commitment_dance: bool) { // When we forward a payment and receive `update_fulfill_htlc`+`commitment_signed` messages // from the downstream channel, we immediately claim the HTLC on the upstream channel, before @@ -3174,6 +3205,7 @@ fn test_inverted_mon_completion_order() { do_test_inverted_mon_completion_order(false, false); } +#[rustfmt::skip] fn do_test_durable_preimages_on_closed_channel(close_chans_before_reload: bool, close_only_a: bool, hold_post_reload_mon_update: bool) { // Test that we can apply a `ChannelMonitorUpdate` with a payment preimage even if the channel // is force-closed between when we generate the update on reload and when we go to handle the @@ -3345,6 +3377,7 @@ fn test_durable_preimages_on_closed_channel() { do_test_durable_preimages_on_closed_channel(false, false, false); } +#[rustfmt::skip] fn do_test_reload_mon_update_completion_actions(close_during_reload: bool) { // Test that if a `ChannelMonitorUpdate` completes but a `ChannelManager` isn't serialized // before restart we run the monitor update completion action on startup. @@ -3448,6 +3481,7 @@ fn test_reload_mon_update_completion_actions() { do_test_reload_mon_update_completion_actions(false); } +#[rustfmt::skip] fn do_test_glacial_peer_cant_hang(hold_chan_a: bool) { // Test that if a peer manages to send an `update_fulfill_htlc` message without a // `commitment_signed`, disconnects, then replays the `update_fulfill_htlc` message it doesn't @@ -3558,6 +3592,7 @@ fn test_glacial_peer_cant_hang() { } #[test] +#[rustfmt::skip] fn test_partial_claim_mon_update_compl_actions() { // Test that if we have an MPP claim that we ensure the preimage for the claim is retained in // all the `ChannelMonitor`s until the preimage reaches every `ChannelMonitor` for a channel @@ -3671,8 +3706,8 @@ fn test_partial_claim_mon_update_compl_actions() { assert!(!get_monitor!(nodes[3], chan_4_id).get_stored_preimages().contains_key(&payment_hash)); } - #[test] +#[rustfmt::skip] fn test_claim_to_closed_channel_blocks_forwarded_preimage_removal() { // One of the last features for async persistence we implemented was the correct blocking of // RAA(s) which remove a preimage from an outbound channel for a forwarded payment until the @@ -3736,6 +3771,7 @@ fn test_claim_to_closed_channel_blocks_forwarded_preimage_removal() { } #[test] +#[rustfmt::skip] fn test_claim_to_closed_channel_blocks_claimed_event() { // One of the last features for async persistence we implemented was the correct blocking of // event(s) until the preimage for a claimed HTLC is durably on disk in a ChannelMonitor for a @@ -3781,6 +3817,7 @@ fn test_claim_to_closed_channel_blocks_claimed_event() { #[test] #[cfg(all(feature = "std", not(target_os = "windows")))] +#[rustfmt::skip] fn test_single_channel_multiple_mpp() { use std::sync::atomic::{AtomicBool, Ordering}; diff --git a/lightning/src/ln/channel.rs b/lightning/src/ln/channel.rs index d68eac8e159..276399a6560 100644 --- a/lightning/src/ln/channel.rs +++ b/lightning/src/ln/channel.rs @@ -1,5 +1,3 @@ -#![cfg_attr(rustfmt, rustfmt_skip)] - // This file is Copyright its original authors, visible in version control // history. // @@ -9,75 +7,90 @@ // You may not use this file except in accordance with one or both of these // licenses. +use bitcoin::absolute::LockTime; use bitcoin::amount::Amount; +use bitcoin::consensus::encode; use bitcoin::constants::ChainHash; -use bitcoin::script::{Script, ScriptBuf, Builder, WScriptHash}; -use bitcoin::transaction::{Transaction, TxIn, TxOut}; +use bitcoin::script::{Builder, Script, ScriptBuf, WScriptHash}; use bitcoin::sighash::EcdsaSighashType; -use bitcoin::consensus::encode; -use bitcoin::absolute::LockTime; +use bitcoin::transaction::{Transaction, TxIn, TxOut}; use bitcoin::Weight; -use bitcoin::hashes::Hash; +use bitcoin::hash_types::{BlockHash, Txid}; use bitcoin::hashes::sha256::Hash as Sha256; use bitcoin::hashes::sha256d::Hash as Sha256d; -use bitcoin::hash_types::{Txid, BlockHash}; +use bitcoin::hashes::Hash; use bitcoin::secp256k1::constants::PUBLIC_KEY_SIZE; -use bitcoin::secp256k1::{PublicKey,SecretKey}; -use bitcoin::secp256k1::{Secp256k1,ecdsa::Signature}; +use bitcoin::secp256k1::{ecdsa::Signature, Secp256k1}; +use bitcoin::secp256k1::{PublicKey, SecretKey}; use bitcoin::{secp256k1, sighash}; -use crate::ln::types::ChannelId; -use crate::types::payment::{PaymentPreimage, PaymentHash}; -use crate::types::features::{ChannelTypeFeatures, InitFeatures}; +use crate::chain::chaininterface::{ + fee_for_weight, ConfirmationTarget, FeeEstimator, LowerBoundedFeeEstimator, +}; +use crate::chain::channelmonitor::{ + ChannelMonitor, ChannelMonitorUpdate, ChannelMonitorUpdateStep, LATENCY_GRACE_PERIOD_BLOCKS, +}; +use crate::chain::transaction::{OutPoint, TransactionData}; +use crate::chain::BestBlock; +use crate::events::bump_transaction::BASE_INPUT_WEIGHT; +use crate::events::{ClosureReason, Event}; +use crate::ln::chan_utils; +#[cfg(splicing)] +use crate::ln::chan_utils::FUNDING_TRANSACTION_WITNESS_WEIGHT; +use crate::ln::chan_utils::{ + commit_tx_fee_sat, get_commitment_transaction_number_obscure_factor, htlc_success_tx_weight, + htlc_timeout_tx_weight, max_htlcs, ChannelPublicKeys, ChannelTransactionParameters, + ClosingTransaction, CommitmentTransaction, CounterpartyChannelTransactionParameters, + CounterpartyCommitmentSecrets, HTLCOutputInCommitment, HolderCommitmentTransaction, +}; +use crate::ln::channel_state::{ + ChannelShutdownState, CounterpartyForwardingInfo, InboundHTLCDetails, InboundHTLCStateDetails, + OutboundHTLCDetails, OutboundHTLCStateDetails, +}; +use crate::ln::channelmanager::{ + self, HTLCFailureMsg, HTLCSource, OpenChannelMessage, PaymentClaimDetails, PendingHTLCInfo, + PendingHTLCStatus, RAACommitmentOrder, SentHTLCId, BREAKDOWN_TIMEOUT, + MAX_LOCAL_BREAKDOWN_TIMEOUT, MIN_CLTV_EXPIRY_DELTA, +}; use crate::ln::interactivetxs::{ - calculate_change_output_value, get_output_weight, AbortReason, HandleTxCompleteResult, InteractiveTxConstructor, - InteractiveTxConstructorArgs, InteractiveTxMessageSend, InteractiveTxSigningSession, InteractiveTxMessageSendResult, - OutputOwned, SharedOwnedOutput, TX_COMMON_FIELDS_WEIGHT, + calculate_change_output_value, get_output_weight, AbortReason, HandleTxCompleteResult, + InteractiveTxConstructor, InteractiveTxConstructorArgs, InteractiveTxMessageSend, + InteractiveTxMessageSendResult, InteractiveTxSigningSession, OutputOwned, SharedOwnedOutput, + TX_COMMON_FIELDS_WEIGHT, }; use crate::ln::msgs; use crate::ln::msgs::{ClosingSigned, ClosingSignedFeeRange, DecodeError, OnionErrorPacket}; +use crate::ln::onion_utils::{AttributionData, HTLCFailReason, LocalHTLCFailureReason}; use crate::ln::script::{self, ShutdownScript}; -use crate::ln::channel_state::{ChannelShutdownState, CounterpartyForwardingInfo, InboundHTLCDetails, InboundHTLCStateDetails, OutboundHTLCDetails, OutboundHTLCStateDetails}; -use crate::ln::channelmanager::{self, OpenChannelMessage, PendingHTLCStatus, HTLCSource, SentHTLCId, HTLCFailureMsg, PendingHTLCInfo, RAACommitmentOrder, PaymentClaimDetails, BREAKDOWN_TIMEOUT, MIN_CLTV_EXPIRY_DELTA, MAX_LOCAL_BREAKDOWN_TIMEOUT}; -use crate::ln::chan_utils::{ - CounterpartyCommitmentSecrets, HTLCOutputInCommitment, htlc_success_tx_weight, - htlc_timeout_tx_weight, ChannelPublicKeys, CommitmentTransaction, - HolderCommitmentTransaction, ChannelTransactionParameters, - CounterpartyChannelTransactionParameters, max_htlcs, - get_commitment_transaction_number_obscure_factor, - ClosingTransaction, commit_tx_fee_sat, -}; -#[cfg(splicing)] -use crate::ln::chan_utils::FUNDING_TRANSACTION_WITNESS_WEIGHT; -use crate::ln::chan_utils; -use crate::ln::onion_utils::{HTLCFailReason, LocalHTLCFailureReason, AttributionData}; -use crate::chain::BestBlock; -use crate::chain::chaininterface::{FeeEstimator, ConfirmationTarget, LowerBoundedFeeEstimator, fee_for_weight}; -use crate::chain::channelmonitor::{ChannelMonitor, ChannelMonitorUpdate, ChannelMonitorUpdateStep, LATENCY_GRACE_PERIOD_BLOCKS}; -use crate::chain::transaction::{OutPoint, TransactionData}; -use crate::sign::ecdsa::EcdsaChannelSigner; -use crate::sign::{EntropySource, ChannelSigner, SignerProvider, NodeSigner, Recipient}; -use crate::events::{ClosureReason, Event}; -use crate::events::bump_transaction::BASE_INPUT_WEIGHT; +use crate::ln::types::ChannelId; use crate::routing::gossip::NodeId; -use crate::util::ser::{Readable, ReadableArgs, RequiredWrapper, TransactionU16LenLimited, Writeable, Writer}; -use crate::util::logger::{Logger, Record, WithContext}; +use crate::sign::ecdsa::EcdsaChannelSigner; +use crate::sign::{ChannelSigner, EntropySource, NodeSigner, Recipient, SignerProvider}; +use crate::types::features::{ChannelTypeFeatures, InitFeatures}; +use crate::types::payment::{PaymentHash, PaymentPreimage}; +use crate::util::config::{ + ChannelConfig, ChannelHandshakeConfig, ChannelHandshakeLimits, LegacyChannelConfig, + MaxDustHTLCExposure, UserConfig, +}; use crate::util::errors::APIError; -use crate::util::config::{UserConfig, ChannelConfig, LegacyChannelConfig, ChannelHandshakeConfig, ChannelHandshakeLimits, MaxDustHTLCExposure}; +use crate::util::logger::{Logger, Record, WithContext}; use crate::util::scid_utils::scid_from_parts; +use crate::util::ser::{ + Readable, ReadableArgs, RequiredWrapper, TransactionU16LenLimited, Writeable, Writer, +}; use alloc::collections::BTreeMap; use crate::io; use crate::prelude::*; -use core::time::Duration; -use core::{cmp,mem,fmt}; -use core::ops::Deref; +use crate::sign::type_resolver::ChannelSignerType; #[cfg(any(test, fuzzing, debug_assertions))] use crate::sync::Mutex; -use crate::sign::type_resolver::ChannelSignerType; +use core::ops::Deref; +use core::time::Duration; +use core::{cmp, fmt, mem}; use super::channel_keys::{DelayedPaymentBasepoint, HtlcBasepoint, RevocationBasepoint}; @@ -134,15 +147,11 @@ enum InboundHTLCResolution { // // TODO: Once this variant is removed, we should also clean up // [`MonitorRestoreUpdates::accepted_htlcs`] as the path will be unreachable. - Resolved { - pending_htlc_status: PendingHTLCStatus, - }, + Resolved { pending_htlc_status: PendingHTLCStatus }, /// Pending implies we will attempt to resolve the inbound HTLC once it has been fully committed /// to by both sides of the channel, i.e., once a `revoke_and_ack` has been processed by both /// nodes for the state update in which it was proposed. - Pending { - update_add_htlc: msgs::UpdateAddHTLC, - }, + Pending { update_add_htlc: msgs::UpdateAddHTLC }, } impl_writeable_tlv_based_enum!(InboundHTLCResolution, @@ -209,6 +218,7 @@ enum InboundHTLCState { } impl From<&InboundHTLCState> for Option { + #[rustfmt::skip] fn from(state: &InboundHTLCState) -> Option { match state { InboundHTLCState::RemoteAnnounced(_) => None, @@ -229,6 +239,7 @@ impl From<&InboundHTLCState> for Option { } impl fmt::Display for InboundHTLCState { + #[rustfmt::skip] fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { InboundHTLCState::RemoteAnnounced(_) => write!(f, "RemoteAnnounced"), @@ -251,6 +262,7 @@ impl InboundHTLCState { } } + #[rustfmt::skip] fn preimage(&self) -> Option { match self { InboundHTLCState::LocalRemoved(InboundHTLCRemovalReason::Fulfill(preimage)) => Some(*preimage), @@ -268,7 +280,10 @@ struct InboundHTLCOutput { } impl InboundHTLCOutput { - fn is_dust(&self, local: bool, feerate_per_kw: u32, broadcaster_dust_limit_sat: u64, features: &ChannelTypeFeatures) -> bool { + fn is_dust( + &self, local: bool, feerate_per_kw: u32, broadcaster_dust_limit_sat: u64, + features: &ChannelTypeFeatures, + ) -> bool { let htlc_tx_fee_sat = if features.supports_anchors_zero_fee_htlc_tx() { 0 } else { @@ -319,6 +334,7 @@ enum OutboundHTLCState { } impl From<&OutboundHTLCState> for OutboundHTLCStateDetails { + #[rustfmt::skip] fn from(state: &OutboundHTLCState) -> OutboundHTLCStateDetails { match state { OutboundHTLCState::LocalAnnounced(_) => @@ -342,6 +358,7 @@ impl From<&OutboundHTLCState> for OutboundHTLCStateDetails { } impl fmt::Display for OutboundHTLCState { + #[rustfmt::skip] fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { OutboundHTLCState::LocalAnnounced(_) => write!(f, "LocalAnnounced"), @@ -364,6 +381,7 @@ impl OutboundHTLCState { } } + #[rustfmt::skip] fn preimage(&self) -> Option { match self { OutboundHTLCState::RemoteRemoved(OutboundHTLCOutcome::Success(preimage)) @@ -386,6 +404,7 @@ enum OutboundHTLCOutcome { } impl<'a> Into> for &'a OutboundHTLCOutcome { + #[rustfmt::skip] fn into(self) -> Option<&'a HTLCFailReason> { match self { OutboundHTLCOutcome::Success(_) => None, @@ -408,7 +427,10 @@ struct OutboundHTLCOutput { } impl OutboundHTLCOutput { - fn is_dust(&self, local: bool, feerate_per_kw: u32, broadcaster_dust_limit_sat: u64, features: &ChannelTypeFeatures) -> bool { + fn is_dust( + &self, local: bool, feerate_per_kw: u32, broadcaster_dust_limit_sat: u64, + features: &ChannelTypeFeatures, + ) -> bool { let htlc_tx_fee_sat = if features.supports_anchors_zero_fee_htlc_tx() { 0 } else { @@ -428,7 +450,8 @@ impl OutboundHTLCOutput { /// See AwaitingRemoteRevoke ChannelState for more info #[cfg_attr(test, derive(Clone, Debug, PartialEq))] enum HTLCUpdateAwaitingACK { - AddHTLC { // TODO: Time out if we're getting close to cltv_expiry + AddHTLC { + // TODO: Time out if we're getting close to cltv_expiry // always outbound amount_msat: u64, cltv_expiry: u32, @@ -743,6 +766,7 @@ macro_rules! impl_state_flag { } impl ChannelState { + #[rustfmt::skip] fn from_u32(state: u32) -> Result { match state { state_flags::SHUTDOWN_COMPLETE => Ok(ChannelState::ShutdownComplete), @@ -765,6 +789,7 @@ impl ChannelState { } } + #[rustfmt::skip] fn to_u32(self) -> u32 { match self { ChannelState::NegotiatingFunding(flags) => flags.0, @@ -787,6 +812,7 @@ impl ChannelState { self.is_local_shutdown_sent() && self.is_remote_shutdown_sent() } + #[rustfmt::skip] fn with_funded_state_flags_mask(&self) -> FundedStateFlags { match self { ChannelState::AwaitingChannelReady(flags) => FundedStateFlags((*flags & FundedStateFlags::ALL).0), @@ -795,6 +821,7 @@ impl ChannelState { } } + #[rustfmt::skip] fn can_generate_new_commitment(&self) -> bool { match self { ChannelState::ChannelReady(flags) => @@ -810,20 +837,85 @@ impl ChannelState { } } - impl_state_flag!(is_peer_disconnected, set_peer_disconnected, clear_peer_disconnected, FUNDED_STATES); - impl_state_flag!(is_monitor_update_in_progress, set_monitor_update_in_progress, clear_monitor_update_in_progress, FUNDED_STATES); - impl_state_flag!(is_local_shutdown_sent, set_local_shutdown_sent, clear_local_shutdown_sent, FUNDED_STATES); - impl_state_flag!(is_remote_shutdown_sent, set_remote_shutdown_sent, clear_remote_shutdown_sent, FUNDED_STATES); - impl_state_flag!(is_interactive_signing, set_interactive_signing, clear_interactive_signing, FundingNegotiated); - impl_state_flag!(is_our_tx_signatures_ready, set_our_tx_signatures_ready, clear_our_tx_signatures_ready, FundingNegotiated); - impl_state_flag!(is_their_tx_signatures_sent, set_their_tx_signatures_sent, clear_their_tx_signatures_sent, FundingNegotiated); - impl_state_flag!(is_our_channel_ready, set_our_channel_ready, clear_our_channel_ready, AwaitingChannelReady); - impl_state_flag!(is_their_channel_ready, set_their_channel_ready, clear_their_channel_ready, AwaitingChannelReady); - impl_state_flag!(is_waiting_for_batch, set_waiting_for_batch, clear_waiting_for_batch, AwaitingChannelReady); - impl_state_flag!(is_awaiting_remote_revoke, set_awaiting_remote_revoke, clear_awaiting_remote_revoke, ChannelReady); - impl_state_flag!(is_awaiting_quiescence, set_awaiting_quiescence, clear_awaiting_quiescence, ChannelReady); + impl_state_flag!( + is_peer_disconnected, + set_peer_disconnected, + clear_peer_disconnected, + FUNDED_STATES + ); + impl_state_flag!( + is_monitor_update_in_progress, + set_monitor_update_in_progress, + clear_monitor_update_in_progress, + FUNDED_STATES + ); + impl_state_flag!( + is_local_shutdown_sent, + set_local_shutdown_sent, + clear_local_shutdown_sent, + FUNDED_STATES + ); + impl_state_flag!( + is_remote_shutdown_sent, + set_remote_shutdown_sent, + clear_remote_shutdown_sent, + FUNDED_STATES + ); + impl_state_flag!( + is_interactive_signing, + set_interactive_signing, + clear_interactive_signing, + FundingNegotiated + ); + impl_state_flag!( + is_our_tx_signatures_ready, + set_our_tx_signatures_ready, + clear_our_tx_signatures_ready, + FundingNegotiated + ); + impl_state_flag!( + is_their_tx_signatures_sent, + set_their_tx_signatures_sent, + clear_their_tx_signatures_sent, + FundingNegotiated + ); + impl_state_flag!( + is_our_channel_ready, + set_our_channel_ready, + clear_our_channel_ready, + AwaitingChannelReady + ); + impl_state_flag!( + is_their_channel_ready, + set_their_channel_ready, + clear_their_channel_ready, + AwaitingChannelReady + ); + impl_state_flag!( + is_waiting_for_batch, + set_waiting_for_batch, + clear_waiting_for_batch, + AwaitingChannelReady + ); + impl_state_flag!( + is_awaiting_remote_revoke, + set_awaiting_remote_revoke, + clear_awaiting_remote_revoke, + ChannelReady + ); + impl_state_flag!( + is_awaiting_quiescence, + set_awaiting_quiescence, + clear_awaiting_quiescence, + ChannelReady + ); impl_state_flag!(is_local_stfu_sent, set_local_stfu_sent, clear_local_stfu_sent, ChannelReady); - impl_state_flag!(is_remote_stfu_sent, set_remote_stfu_sent, clear_remote_stfu_sent, ChannelReady); + impl_state_flag!( + is_remote_stfu_sent, + set_remote_stfu_sent, + clear_remote_stfu_sent, + ChannelReady + ); impl_state_flag!(is_quiescent, set_quiescent, clear_quiescent, ChannelReady); } @@ -881,6 +973,7 @@ pub(super) enum ChannelError { } impl fmt::Debug for ChannelError { + #[rustfmt::skip] fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { &ChannelError::Ignore(ref e) => write!(f, "Ignore: {}", e), @@ -910,14 +1003,20 @@ impl ChannelError { } } -pub(super) struct WithChannelContext<'a, L: Deref> where L::Target: Logger { +pub(super) struct WithChannelContext<'a, L: Deref> +where + L::Target: Logger, +{ pub logger: &'a L, pub peer_id: Option, pub channel_id: Option, pub payment_hash: Option, } -impl<'a, L: Deref> Logger for WithChannelContext<'a, L> where L::Target: Logger { +impl<'a, L: Deref> Logger for WithChannelContext<'a, L> +where + L::Target: Logger, +{ fn log(&self, mut record: Record) { record.peer_id = self.peer_id; record.channel_id = self.channel_id; @@ -927,7 +1026,10 @@ impl<'a, L: Deref> Logger for WithChannelContext<'a, L> where L::Target: Logger } impl<'a, 'b, L: Deref> WithChannelContext<'a, L> -where L::Target: Logger { +where + L::Target: Logger, +{ + #[rustfmt::skip] pub(super) fn from(logger: &'a L, context: &'b ChannelContext, payment_hash: Option) -> Self where S::Target: SignerProvider { @@ -1019,9 +1121,9 @@ struct CommitmentData<'a> { /// A struct gathering stats on a commitment transaction, either local or remote. struct CommitmentStats { - feerate_per_kw: u32, // the feerate of the commitment transaction - total_fee_sat: u64, // the total fee included in the transaction - total_anchors_sat: u64, // the sum of the anchors' amounts + feerate_per_kw: u32, // the feerate of the commitment transaction + total_fee_sat: u64, // the total fee included in the transaction + total_anchors_sat: u64, // the sum of the anchors' amounts broadcaster_dust_limit_sat: u64, // the broadcaster's dust limit local_balance_before_fee_anchors_msat: u64, // local balance before fees and anchors *not* considering dust limits remote_balance_before_fee_anchors_msat: u64, // remote balance before fees and anchors *not* considering dust limits @@ -1034,6 +1136,7 @@ struct HTLCCandidate { } impl HTLCCandidate { + #[rustfmt::skip] fn new(amount_msat: u64, origin: HTLCInitiator) -> Self { Self { amount_msat, @@ -1154,6 +1257,7 @@ enum HolderCommitmentPoint { } impl HolderCommitmentPoint { + #[rustfmt::skip] pub fn new(signer: &ChannelSignerType, secp_ctx: &Secp256k1) -> Option where SP::Target: SignerProvider { @@ -1167,6 +1271,7 @@ impl HolderCommitmentPoint { Some(point) } + #[rustfmt::skip] pub fn is_available(&self) -> bool { if let HolderCommitmentPoint::Available { .. } = self { true } else { false } } @@ -1197,6 +1302,7 @@ impl HolderCommitmentPoint { /// /// This method is used for the following transitions: /// - `PendingNext` -> `Available` + #[rustfmt::skip] pub fn try_resolve_pending(&mut self, signer: &ChannelSignerType, secp_ctx: &Secp256k1, logger: &L) where SP::Target: SignerProvider, L::Target: Logger { @@ -1226,9 +1332,11 @@ impl HolderCommitmentPoint { /// - `Available` -> `PendingNext` /// - `Available` -> `PendingNext` -> `Available` (in one fell swoop) pub fn advance( - &mut self, signer: &ChannelSignerType, secp_ctx: &Secp256k1, logger: &L + &mut self, signer: &ChannelSignerType, secp_ctx: &Secp256k1, logger: &L, ) -> Result<(), ()> - where SP::Target: SignerProvider, L::Target: Logger + where + SP::Target: SignerProvider, + L::Target: Logger, { if let HolderCommitmentPoint::Available { transaction_number, next, .. } = self { *self = HolderCommitmentPoint::PendingNext { @@ -1313,13 +1421,19 @@ impl_writeable_tlv_based!(PendingChannelMonitorUpdate, { /// A payment channel with a counterparty throughout its life-cycle, encapsulating negotiation and /// funding phases. -pub(super) struct Channel where SP::Target: SignerProvider { +pub(super) struct Channel +where + SP::Target: SignerProvider, +{ phase: ChannelPhase, } /// The `ChannelPhase` enum describes the current phase in life of a lightning channel with each of /// its variants containing an appropriate channel struct. -enum ChannelPhase where SP::Target: SignerProvider { +enum ChannelPhase +where + SP::Target: SignerProvider, +{ Undefined, UnfundedOutboundV1(OutboundV1Channel), UnfundedInboundV1(InboundV1Channel), @@ -1327,7 +1441,8 @@ enum ChannelPhase where SP::Target: SignerProvider { Funded(FundedChannel), } -impl Channel where +impl Channel +where SP::Target: SignerProvider, ::EcdsaSigner: ChannelSigner, { @@ -1382,6 +1497,7 @@ impl Channel where } } + #[rustfmt::skip] pub fn unfunded_context_mut(&mut self) -> Option<&mut UnfundedChannelContext> { match &mut self.phase { ChannelPhase::Undefined => unreachable!(), @@ -1421,6 +1537,7 @@ impl Channel where } #[cfg(any(test, feature = "_externalize_tests"))] + #[rustfmt::skip] pub fn is_unfunded_v1(&self) -> bool { matches!(self.phase, ChannelPhase::UnfundedOutboundV1(_) | ChannelPhase::UnfundedInboundV1(_)) } @@ -1457,6 +1574,7 @@ impl Channel where } } + #[rustfmt::skip] pub fn signer_maybe_unblocked( &mut self, chain_hash: ChainHash, logger: &L, ) -> Option where L::Target: Logger { @@ -1502,6 +1620,7 @@ impl Channel where /// Should be called when the peer is disconnected. Returns true if the channel can be resumed /// when the peer reconnects (via [`Self::peer_connected_get_handshake`]). If not, the channel /// must be immediately closed. + #[rustfmt::skip] pub fn peer_disconnected_is_resumable(&mut self, logger: &L) -> bool where L::Target: Logger { match &mut self.phase { ChannelPhase::Undefined => unreachable!(), @@ -1520,6 +1639,7 @@ impl Channel where /// Should be called when the peer re-connects, returning an initial message which we should /// send our peer to begin the channel reconnection process. + #[rustfmt::skip] pub fn peer_connected_get_handshake( &mut self, chain_hash: ChainHash, logger: &L, ) -> ReconnectionMsg where L::Target: Logger { @@ -1582,6 +1702,7 @@ impl Channel where } } + #[rustfmt::skip] pub fn funding_signed( &mut self, msg: &msgs::FundingSigned, best_block: BestBlock, signer_provider: &SP, logger: &L ) -> Result<(&mut FundedChannel, ChannelMonitor<::EcdsaSigner>), ChannelError> @@ -1614,10 +1735,10 @@ impl Channel where } pub fn funding_tx_constructed( - &mut self, signing_session: InteractiveTxSigningSession, logger: &L + &mut self, signing_session: InteractiveTxSigningSession, logger: &L, ) -> Result<(msgs::CommitmentSigned, Option), ChannelError> where - L::Target: Logger + L::Target: Logger, { if let ChannelPhase::UnfundedV2(chan) = &mut self.phase { let logger = WithChannelContext::from(logger, &chan.context, None); @@ -1627,11 +1748,14 @@ impl Channel where } } - pub fn force_shutdown(&mut self, should_broadcast: bool, closure_reason: ClosureReason) -> ShutdownResult { + pub fn force_shutdown( + &mut self, should_broadcast: bool, closure_reason: ClosureReason, + ) -> ShutdownResult { let (funding, context) = self.funding_and_context_mut(); context.force_shutdown(funding, should_broadcast, closure_reason) } + #[rustfmt::skip] pub fn commitment_signed( &mut self, msg: &msgs::CommitmentSigned, best_block: BestBlock, signer_provider: &SP, logger: &L ) -> Result<(Option::EcdsaSigner>>, Option), ChannelError> @@ -1688,6 +1812,7 @@ impl Channel where /// Doesn't bother handling the /// if-we-removed-it-already-but-haven't-fully-resolved-they-can-still-send-an-inbound-HTLC /// corner case properly. + #[rustfmt::skip] pub fn get_available_balances( &self, fee_estimator: &LowerBoundedFeeEstimator, ) -> AvailableBalances @@ -1709,6 +1834,7 @@ where SP::Target: SignerProvider, ::EcdsaSigner: ChannelSigner, { + #[rustfmt::skip] fn from(channel: OutboundV1Channel) -> Self { Channel { phase: ChannelPhase::UnfundedOutboundV1(channel), @@ -1721,6 +1847,7 @@ where SP::Target: SignerProvider, ::EcdsaSigner: ChannelSigner, { + #[rustfmt::skip] fn from(channel: InboundV1Channel) -> Self { Channel { phase: ChannelPhase::UnfundedInboundV1(channel), @@ -1733,6 +1860,7 @@ where SP::Target: SignerProvider, ::EcdsaSigner: ChannelSigner, { + #[rustfmt::skip] fn from(channel: PendingV2Channel) -> Self { Channel { phase: ChannelPhase::UnfundedV2(channel), @@ -1745,6 +1873,7 @@ where SP::Target: SignerProvider, ::EcdsaSigner: ChannelSigner, { + #[rustfmt::skip] fn from(channel: FundedChannel) -> Self { Channel { phase: ChannelPhase::Funded(channel), @@ -1775,6 +1904,7 @@ impl UnfundedChannelContext { self.unfunded_channel_age_ticks >= UNFUNDED_CHANNEL_AGE_LIMIT_TICKS } + #[rustfmt::skip] fn transaction_number(&self) -> u64 { self.holder_commitment_point.as_ref().map(|point| point.transaction_number()) .unwrap_or(INITIAL_COMMITMENT_NUMBER) @@ -1832,6 +1962,7 @@ impl Writeable for FundingScope { } impl Readable for FundingScope { + #[rustfmt::skip] fn read(reader: &mut R) -> Result { let mut value_to_self_msat = RequiredWrapper(None); let mut counterparty_selected_channel_reserve_satoshis = None; @@ -1874,10 +2005,12 @@ impl FundingScope { self.value_to_self_msat } + #[rustfmt::skip] pub fn get_holder_counterparty_selected_channel_reserve_satoshis(&self) -> (u64, Option) { (self.holder_selected_channel_reserve_satoshis, self.counterparty_selected_channel_reserve_satoshis) } + #[rustfmt::skip] fn get_htlc_maximum_msat(&self, party_max_htlc_value_in_flight_msat: u64) -> Option { self.counterparty_selected_channel_reserve_satoshis.map(|counterparty_reserve| { let holder_reserve = self.holder_selected_channel_reserve_satoshis; @@ -1906,6 +2039,7 @@ impl FundingScope { &self.channel_transaction_parameters.holder_pubkeys } + #[rustfmt::skip] pub fn get_counterparty_selected_contest_delay(&self) -> Option { self.channel_transaction_parameters.counterparty_parameters .as_ref().map(|params| params.selected_contest_delay) @@ -1939,7 +2073,10 @@ struct PendingSplice { } /// Contains everything about the channel including state, and various flags. -pub(super) struct ChannelContext where SP::Target: SignerProvider { +pub(super) struct ChannelContext +where + SP::Target: SignerProvider, +{ config: LegacyChannelConfig, // Track the previous `ChannelConfig` so that we can continue forwarding HTLCs that were @@ -1981,7 +2118,6 @@ pub(super) struct ChannelContext where SP::Target: SignerProvider { // Our commitment numbers start at 2^48-1 and count down, whereas the ones used in transaction // generation start at 0 and count up...this simplifies some parts of implementation at the // cost of others, but should really just be changed. - cur_counterparty_commitment_transaction_number: u64, pending_inbound_htlcs: Vec, pending_outbound_htlcs: Vec, @@ -2117,9 +2253,9 @@ pub(super) struct ChannelContext where SP::Target: SignerProvider { counterparty_htlc_minimum_msat: u64, holder_htlc_minimum_msat: u64, - #[cfg(any(test, feature="_test_utils"))] + #[cfg(any(test, feature = "_test_utils"))] pub counterparty_max_accepted_htlcs: u16, - #[cfg(not(any(test, feature="_test_utils")))] + #[cfg(not(any(test, feature = "_test_utils")))] counterparty_max_accepted_htlcs: u16, holder_max_accepted_htlcs: u16, minimum_depth: Option, @@ -2220,7 +2356,10 @@ pub(super) struct ChannelContext where SP::Target: SignerProvider { /// A channel struct implementing this trait can receive an initial counterparty commitment /// transaction signature. -trait InitialRemoteCommitmentReceiver where SP::Target: SignerProvider { +trait InitialRemoteCommitmentReceiver +where + SP::Target: SignerProvider, +{ fn context(&self) -> &ChannelContext; fn context_mut(&mut self) -> &mut ChannelContext; @@ -2231,6 +2370,7 @@ trait InitialRemoteCommitmentReceiver where SP::Target: SignerProvide fn received_msg(&self) -> &'static str; + #[rustfmt::skip] fn check_counterparty_commitment_signature( &self, sig: &Signature, holder_commitment_point: &HolderCommitmentPoint, logger: &L ) -> Result where L::Target: Logger { @@ -2253,6 +2393,7 @@ trait InitialRemoteCommitmentReceiver where SP::Target: SignerProvide Ok(initial_commitment_tx) } + #[rustfmt::skip] fn initial_commitment_signed( &mut self, channel_id: ChannelId, counterparty_signature: Signature, holder_commitment_point: &mut HolderCommitmentPoint, best_block: BestBlock, signer_provider: &SP, logger: &L, @@ -2346,7 +2487,10 @@ trait InitialRemoteCommitmentReceiver where SP::Target: SignerProvide fn is_v2_established(&self) -> bool; } -impl InitialRemoteCommitmentReceiver for OutboundV1Channel where SP::Target: SignerProvider { +impl InitialRemoteCommitmentReceiver for OutboundV1Channel +where + SP::Target: SignerProvider, +{ fn context(&self) -> &ChannelContext { &self.context } @@ -2372,7 +2516,10 @@ impl InitialRemoteCommitmentReceiver for OutboundV1Channel wh } } -impl InitialRemoteCommitmentReceiver for InboundV1Channel where SP::Target: SignerProvider { +impl InitialRemoteCommitmentReceiver for InboundV1Channel +where + SP::Target: SignerProvider, +{ fn context(&self) -> &ChannelContext { &self.context } @@ -2398,7 +2545,10 @@ impl InitialRemoteCommitmentReceiver for InboundV1Channel whe } } -impl InitialRemoteCommitmentReceiver for FundedChannel where SP::Target: SignerProvider { +impl InitialRemoteCommitmentReceiver for FundedChannel +where + SP::Target: SignerProvider, +{ fn context(&self) -> &ChannelContext { &self.context } @@ -2419,6 +2569,7 @@ impl InitialRemoteCommitmentReceiver for FundedChannel where "commitment_signed" } + #[rustfmt::skip] fn is_v2_established(&self) -> bool { let channel_parameters = &self.funding().channel_transaction_parameters; // This will return false if `counterparty_parameters` is `None`, but for a `FundedChannel`, it @@ -2432,12 +2583,16 @@ impl InitialRemoteCommitmentReceiver for FundedChannel where } } -impl PendingV2Channel where SP::Target: SignerProvider { +impl PendingV2Channel +where + SP::Target: SignerProvider, +{ /// Prepare and start interactive transaction negotiation. /// `change_destination_opt` - Optional destination for optional change; if None, /// default destination address is used. /// If error occurs, it is caused by our side, not the counterparty. #[allow(dead_code)] // TODO(dual_funding): Remove once contribution to V2 channels is enabled + #[rustfmt::skip] fn begin_interactive_funding_tx_construction( &mut self, signer_provider: &SP, entropy_source: &ES, holder_node_id: PublicKey, change_destination_opt: Option, @@ -2522,6 +2677,7 @@ impl PendingV2Channel where SP::Target: SignerProvider { Ok(msg) } + #[rustfmt::skip] pub fn tx_add_input(&mut self, msg: &msgs::TxAddInput) -> InteractiveTxMessageSendResult { InteractiveTxMessageSendResult(match &mut self.interactive_tx_constructor { Some(ref mut tx_constructor) => tx_constructor.handle_tx_add_input(msg).map_err( @@ -2533,6 +2689,7 @@ impl PendingV2Channel where SP::Target: SignerProvider { }) } + #[rustfmt::skip] pub fn tx_add_output(&mut self, msg: &msgs::TxAddOutput)-> InteractiveTxMessageSendResult { InteractiveTxMessageSendResult(match &mut self.interactive_tx_constructor { Some(ref mut tx_constructor) => tx_constructor.handle_tx_add_output(msg).map_err( @@ -2544,6 +2701,7 @@ impl PendingV2Channel where SP::Target: SignerProvider { }) } + #[rustfmt::skip] pub fn tx_remove_input(&mut self, msg: &msgs::TxRemoveInput)-> InteractiveTxMessageSendResult { InteractiveTxMessageSendResult(match &mut self.interactive_tx_constructor { Some(ref mut tx_constructor) => tx_constructor.handle_tx_remove_input(msg).map_err( @@ -2555,6 +2713,7 @@ impl PendingV2Channel where SP::Target: SignerProvider { }) } + #[rustfmt::skip] pub fn tx_remove_output(&mut self, msg: &msgs::TxRemoveOutput)-> InteractiveTxMessageSendResult { InteractiveTxMessageSendResult(match &mut self.interactive_tx_constructor { Some(ref mut tx_constructor) => tx_constructor.handle_tx_remove_output(msg).map_err( @@ -2566,6 +2725,7 @@ impl PendingV2Channel where SP::Target: SignerProvider { }) } + #[rustfmt::skip] pub fn tx_complete(&mut self, msg: &msgs::TxComplete) -> HandleTxCompleteResult { let tx_constructor = match &mut self.interactive_tx_constructor { Some(ref mut tx_constructor) => tx_constructor, @@ -2588,6 +2748,7 @@ impl PendingV2Channel where SP::Target: SignerProvider { HandleTxCompleteResult(Ok(tx_complete)) } + #[rustfmt::skip] pub fn funding_tx_constructed( &mut self, mut signing_session: InteractiveTxSigningSession, logger: &L ) -> Result<(msgs::CommitmentSigned, Option), ChannelError> @@ -2682,7 +2843,11 @@ impl PendingV2Channel where SP::Target: SignerProvider { } } -impl ChannelContext where SP::Target: SignerProvider { +impl ChannelContext +where + SP::Target: SignerProvider, +{ + #[rustfmt::skip] fn new_for_inbound_channel<'a, ES: Deref, F: Deref, L: Deref>( fee_estimator: &'a LowerBoundedFeeEstimator, entropy_source: &'a ES, @@ -3025,6 +3190,7 @@ impl ChannelContext where SP::Target: SignerProvider { Ok((funding, channel_context)) } + #[rustfmt::skip] fn new_for_outbound_channel<'a, ES: Deref, F: Deref, L: Deref>( fee_estimator: &'a LowerBoundedFeeEstimator, entropy_source: &'a ES, @@ -3277,12 +3443,14 @@ impl ChannelContext where SP::Target: SignerProvider { } /// Returns true if we've ever received a message from the remote end for this Channel + #[rustfmt::skip] pub fn have_received_message(&self) -> bool { self.channel_state > ChannelState::NegotiatingFunding(NegotiatingFundingFlags::OUR_INIT_SENT) } /// Returns true if this channel is fully established and not known to be closing. /// Allowed in any state (including after shutdown) + #[rustfmt::skip] pub fn is_usable(&self) -> bool { matches!(self.channel_state, ChannelState::ChannelReady(_)) && !self.channel_state.is_local_shutdown_sent() && @@ -3291,6 +3459,7 @@ impl ChannelContext where SP::Target: SignerProvider { } /// shutdown state returns the state of the channel in its various stages of shutdown + #[rustfmt::skip] pub fn shutdown_state(&self) -> ChannelShutdownState { match self.channel_state { ChannelState::AwaitingChannelReady(_)|ChannelState::ChannelReady(_) => @@ -3308,6 +3477,7 @@ impl ChannelContext where SP::Target: SignerProvider { } } + #[rustfmt::skip] fn closing_negotiation_ready(&self) -> bool { let is_ready_to_close = match self.channel_state { ChannelState::AwaitingChannelReady(flags) => @@ -3330,6 +3500,7 @@ impl ChannelContext where SP::Target: SignerProvider { } /// Returns false if our last broadcasted channel_update message has the "channel disabled" bit set + #[rustfmt::skip] pub fn is_enabled(&self) -> bool { self.is_usable() && match self.channel_update_status { ChannelUpdateStatus::Enabled | ChannelUpdateStatus::DisabledStaged(_) => true, @@ -3357,6 +3528,7 @@ impl ChannelContext where SP::Target: SignerProvider { /// Note that it is still possible for an update to be pending that's not captured here due to a /// pending monitor update or signer request. `is_monitor_or_signer_pending_channel_update` /// should also be checked in such cases. + #[rustfmt::skip] fn is_waiting_on_peer_pending_channel_update(&self) -> bool { // An update from the local/remote node may be pending on the remote/local commitment since // they are not tracked within our state, so we rely on whether any `commitment_signed` or @@ -3440,6 +3612,7 @@ impl ChannelContext where SP::Target: SignerProvider { /// Returns the holder signer for this channel. #[cfg(any(test, feature = "_test_utils"))] + #[rustfmt::skip] pub fn get_mut_signer(&mut self) -> &mut ChannelSignerType { return &mut self.holder_signer } @@ -3464,6 +3637,7 @@ impl ChannelContext where SP::Target: SignerProvider { /// Performs checks against necessary constraints after receiving either an `accept_channel` or /// `accept_channel2` message. + #[rustfmt::skip] pub fn do_accept_channel_checks( &mut self, funding: &mut FundingScope, default_limits: &ChannelHandshakeLimits, their_features: &InitFeatures, common_fields: &msgs::CommonAcceptChannelFields, @@ -3654,9 +3828,12 @@ impl ChannelContext where SP::Target: SignerProvider { cmp::max(self.config.options.cltv_expiry_delta, MIN_CLTV_EXPIRY_DELTA) } - fn get_dust_exposure_limiting_feerate(&self, - fee_estimator: &LowerBoundedFeeEstimator, - ) -> u32 where F::Target: FeeEstimator { + fn get_dust_exposure_limiting_feerate( + &self, fee_estimator: &LowerBoundedFeeEstimator, + ) -> u32 + where + F::Target: FeeEstimator, + { fee_estimator.bounded_sat_per_1000_weight(ConfirmationTarget::MaximumFeeEstimate) } @@ -3730,6 +3907,7 @@ impl ChannelContext where SP::Target: SignerProvider { /// Updates the channel's config. A bool is returned indicating whether the config update /// applied resulted in a new ChannelUpdate message. + #[rustfmt::skip] pub fn update_config(&mut self, config: &ChannelConfig) -> bool { let did_channel_update = self.config.options.forwarding_fee_proportional_millionths != config.forwarding_fee_proportional_millionths || @@ -3758,11 +3936,13 @@ impl ChannelContext where SP::Target: SignerProvider { /// Returns true if funding_signed was sent/received and the /// funding transaction has been broadcast if necessary. + #[rustfmt::skip] pub fn is_funding_broadcast(&self) -> bool { !self.channel_state.is_pre_funded_state() && !matches!(self.channel_state, ChannelState::AwaitingChannelReady(flags) if flags.is_set(AwaitingChannelReadyFlags::WAITING_FOR_BATCH)) } + #[rustfmt::skip] fn unset_funding_info(&mut self, funding: &mut FundingScope) { debug_assert!( matches!(self.channel_state, ChannelState::FundingNegotiated(flags) if !flags.is_their_tx_signatures_sent() && !flags.is_our_tx_signatures_ready()) @@ -3775,6 +3955,7 @@ impl ChannelContext where SP::Target: SignerProvider { ); } + #[rustfmt::skip] fn validate_commitment_signed( &self, funding: &FundingScope, holder_commitment_point: &HolderCommitmentPoint, msg: &msgs::CommitmentSigned, logger: &L, @@ -3888,6 +4069,7 @@ impl ChannelContext where SP::Target: SignerProvider { /// Builds stats on a potential commitment transaction build, without actually building the /// commitment transaction. See `build_commitment_transaction` for further docs. #[inline] + #[rustfmt::skip] fn build_commitment_stats(&self, funding: &FundingScope, local: bool, generated_by_local: bool) -> CommitmentStats { let broadcaster_dust_limit_sat = if local { self.holder_dust_limit_satoshis } else { self.counterparty_dust_limit_satoshis }; let mut non_dust_htlc_count = 0; @@ -3988,6 +4170,7 @@ impl ChannelContext where SP::Target: SignerProvider { /// generated by the peer which proposed adding the HTLCs, and thus we need to understand both /// which peer generated this transaction and "to whom" this transaction flows. #[inline] + #[rustfmt::skip] fn build_commitment_transaction(&self, funding: &FundingScope, commitment_number: u64, per_commitment_point: &PublicKey, local: bool, generated_by_local: bool, logger: &L) -> CommitmentData where L::Target: Logger { @@ -4011,6 +4194,7 @@ impl ChannelContext where SP::Target: SignerProvider { self.channel_id, if local { "us" } else { "remote" }, if generated_by_local { "us" } else { "remote" }, feerate_per_kw); + #[rustfmt::skip] macro_rules! get_htlc_in_commitment { ($htlc: expr, $offered: expr) => { HTLCOutputInCommitment { @@ -4023,6 +4207,7 @@ impl ChannelContext where SP::Target: SignerProvider { } } + #[rustfmt::skip] macro_rules! add_htlc_output { ($htlc: expr, $outbound: expr, $source: expr) => { let htlc_in_tx = get_htlc_in_commitment!($htlc, $outbound == local); @@ -4172,6 +4357,7 @@ impl ChannelContext where SP::Target: SignerProvider { } /// Returns a HTLCStats about pending htlcs + #[rustfmt::skip] fn get_pending_htlc_stats( &self, funding: &FundingScope, outbound_feerate_update: Option, dust_exposure_limiting_feerate: u32, @@ -4276,6 +4462,7 @@ impl ChannelContext where SP::Target: SignerProvider { } /// Returns information on all pending inbound HTLCs. + #[rustfmt::skip] pub fn get_pending_inbound_htlc_details(&self, funding: &FundingScope) -> Vec { let mut holding_cell_states = new_hash_map(); for holding_cell_update in self.holding_cell_htlc_updates.iter() { @@ -4326,6 +4513,7 @@ impl ChannelContext where SP::Target: SignerProvider { } /// Returns information on all pending outbound HTLCs. + #[rustfmt::skip] pub fn get_pending_outbound_htlc_details(&self, funding: &FundingScope) -> Vec { let mut outbound_details = Vec::new(); let htlc_timeout_dust_limit = if funding.get_channel_type().supports_anchors_zero_fee_htlc_tx() { @@ -4368,6 +4556,7 @@ impl ChannelContext where SP::Target: SignerProvider { outbound_details } + #[rustfmt::skip] fn get_available_balances_for_scope( &self, funding: &FundingScope, fee_estimator: &LowerBoundedFeeEstimator, ) -> AvailableBalances @@ -4530,6 +4719,7 @@ impl ChannelContext where SP::Target: SignerProvider { /// second allows for creating a buffer to ensure a further HTLC can always be accepted/added. /// /// Dust HTLCs are excluded. + #[rustfmt::skip] fn next_local_commit_tx_fee_msat( &self, funding: &FundingScope, htlc: HTLCCandidate, fee_spike_buffer_htlc: Option<()>, ) -> u64 { @@ -4636,6 +4826,7 @@ impl ChannelContext where SP::Target: SignerProvider { /// second allows for creating a buffer to ensure a further HTLC can always be accepted/added. /// /// Dust HTLCs are excluded. + #[rustfmt::skip] fn next_remote_commit_tx_fee_msat( &self, funding: &FundingScope, htlc: Option, fee_spike_buffer_htlc: Option<()>, ) -> u64 { @@ -4722,6 +4913,7 @@ impl ChannelContext where SP::Target: SignerProvider { res } + #[rustfmt::skip] fn if_unbroadcasted_funding(&self, f: F) -> Option where F: Fn() -> Option { match self.channel_state { ChannelState::FundingNegotiated(_) => f(), @@ -4748,6 +4940,7 @@ impl ChannelContext where SP::Target: SignerProvider { /// Returns the transaction ID if there is a pending funding transaction that is yet to be /// broadcast. + #[rustfmt::skip] pub fn unbroadcasted_funding_txid(&self, funding: &FundingScope) -> Option { self.if_unbroadcasted_funding(|| funding.channel_transaction_parameters.funding_outpoint.map(|txo| txo.txid) @@ -4770,6 +4963,7 @@ impl ChannelContext where SP::Target: SignerProvider { /// those explicitly stated to be allowed after shutdown completes, eg some simple getters). /// Also returns the list of payment_hashes for channels which we can safely fail backwards /// immediately (others we will have to allow to time out). + #[rustfmt::skip] pub fn force_shutdown(&mut self, funding: &FundingScope, should_broadcast: bool, closure_reason: ClosureReason) -> ShutdownResult { // Note that we MUST only generate a monitor update that indicates force-closure - we're // called during initialization prior to the chain_monitor in the encompassing ChannelManager @@ -4828,6 +5022,7 @@ impl ChannelContext where SP::Target: SignerProvider { } /// Only allowed after [`FundingScope::channel_transaction_parameters`] is set. + #[rustfmt::skip] fn get_funding_signed_msg( &mut self, channel_parameters: &ChannelTransactionParameters, logger: &L, counterparty_initial_commitment_tx: CommitmentTransaction, @@ -4867,6 +5062,7 @@ impl ChannelContext where SP::Target: SignerProvider { /// If we receive an error message when attempting to open a channel, it may only be a rejection /// of the channel type we tried, not of our ability to open any channel at all. We can see if a /// downgrade of channel features would be possible so that we can still open the channel. + #[rustfmt::skip] pub(crate) fn maybe_downgrade_channel_features( &mut self, funding: &mut FundingScope, fee_estimator: &LowerBoundedFeeEstimator ) -> Result<(), ()> @@ -4908,6 +5104,7 @@ impl ChannelContext where SP::Target: SignerProvider { } /// Asserts that the commitment tx numbers have not advanced from their initial number. + #[rustfmt::skip] fn assert_no_commitment_advancement(&self, holder_commitment_transaction_number: u64, msg_name: &str) { if self.commitment_secrets.get_min_seen_secret() != (1 << 48) || self.cur_counterparty_commitment_transaction_number != INITIAL_COMMITMENT_NUMBER || @@ -4917,6 +5114,7 @@ impl ChannelContext where SP::Target: SignerProvider { } } + #[rustfmt::skip] fn get_initial_counterparty_commitment_signature( &self, funding: &FundingScope, logger: &L ) -> Result @@ -4946,6 +5144,7 @@ impl ChannelContext where SP::Target: SignerProvider { } } + #[rustfmt::skip] fn get_initial_commitment_signed( &mut self, funding: &FundingScope, logger: &L ) -> Result @@ -4991,7 +5190,7 @@ impl ChannelContext where SP::Target: SignerProvider { ) -> Result where SP::Target: SignerProvider, - L::Target: Logger + L::Target: Logger, { self.counterparty_cur_commitment_point = Some(counterparty_cur_commitment_point_override); self.get_initial_counterparty_commitment_signature(funding, logger) @@ -5007,7 +5206,9 @@ impl ChannelContext where SP::Target: SignerProvider { /// The effective percentage is lower bounded by 1% and upper bounded by 100%. /// /// [`ChannelHandshakeConfig::max_inbound_htlc_value_in_flight_percent_of_channel`]: crate::util::config::ChannelHandshakeConfig::max_inbound_htlc_value_in_flight_percent_of_channel -fn get_holder_max_htlc_value_in_flight_msat(channel_value_satoshis: u64, config: &ChannelHandshakeConfig) -> u64 { +fn get_holder_max_htlc_value_in_flight_msat( + channel_value_satoshis: u64, config: &ChannelHandshakeConfig, +) -> u64 { let configured_percent = if config.max_inbound_htlc_value_in_flight_percent_of_channel < 1 { 1 } else if config.max_inbound_htlc_value_in_flight_percent_of_channel > 100 { @@ -5026,6 +5227,7 @@ fn get_holder_max_htlc_value_in_flight_msat(channel_value_satoshis: u64, config: /// /// This is used both for outbound and inbound channels and has lower bound /// of `MIN_THEIR_CHAN_RESERVE_SATOSHIS`. +#[rustfmt::skip] pub(crate) fn get_holder_selected_channel_reserve_satoshis(channel_value_satoshis: u64, config: &UserConfig) -> u64 { let calculated_reserve = channel_value_satoshis.saturating_mul(config.channel_handshake_config.their_channel_reserve_proportional_millionths as u64) / 1_000_000; cmp::min(channel_value_satoshis, cmp::max(calculated_reserve, MIN_THEIR_CHAN_RESERVE_SATOSHIS)) @@ -5035,7 +5237,9 @@ pub(crate) fn get_holder_selected_channel_reserve_satoshis(channel_value_satoshi /// LDK versions older than 0.0.104 don't know how read/handle values other than default /// from storage. Hence, we use this function to not persist default values of /// `holder_selected_channel_reserve_satoshis` for channels into storage. -pub(crate) fn get_legacy_default_holder_selected_channel_reserve_satoshis(channel_value_satoshis: u64) -> u64 { +pub(crate) fn get_legacy_default_holder_selected_channel_reserve_satoshis( + channel_value_satoshis: u64, +) -> u64 { let (q, _) = channel_value_satoshis.overflowing_div(100); cmp::min(channel_value_satoshis, cmp::max(q, 1000)) } @@ -5057,6 +5261,7 @@ fn get_v2_channel_reserve_satoshis(channel_value_satoshis: u64, dust_limit_satos /// input_count: Number of contributed inputs. /// witness_weight: The witness weight for contributed inputs. #[allow(dead_code)] // TODO(dual_funding): TODO(splicing): Remove allow once used. +#[rustfmt::skip] fn estimate_v2_funding_transaction_fee( is_initiator: bool, input_count: usize, witness_weight: Weight, funding_feerate_sat_per_1000_weight: u32, @@ -5089,6 +5294,7 @@ fn estimate_v2_funding_transaction_fee( /// the fees of the common fields as well as the output and extra input weights. /// Returns estimated (partial) fees as additional information #[cfg(splicing)] +#[rustfmt::skip] fn check_v2_funding_inputs_sufficient( contribution_amount: i64, funding_inputs: &[(TxIn, Transaction, Weight)], is_initiator: bool, is_splice: bool, funding_feerate_sat_per_1000_weight: u32, @@ -5162,7 +5368,10 @@ pub(super) struct DualFundingChannelContext { // Holder designates channel data owned for the benefit of the user client. // Counterparty designates channel data owned by the another channel participant entity. -pub(super) struct FundedChannel where SP::Target: SignerProvider { +pub(super) struct FundedChannel +where + SP::Target: SignerProvider, +{ pub funding: FundingScope, pending_funding: Vec, pub context: ChannelContext, @@ -5207,6 +5416,7 @@ trait FailHTLCContents { } impl FailHTLCContents for msgs::OnionErrorPacket { type Message = msgs::UpdateFailHTLC; + #[rustfmt::skip] fn to_message(self, htlc_id: u64, channel_id: ChannelId) -> Self::Message { msgs::UpdateFailHTLC { htlc_id, channel_id, reason: self.data, attribution_data: self.attribution_data } } @@ -5219,6 +5429,7 @@ impl FailHTLCContents for msgs::OnionErrorPacket { } impl FailHTLCContents for ([u8; 32], u16) { type Message = msgs::UpdateFailMalformedHTLC; + #[rustfmt::skip] fn to_message(self, htlc_id: u64, channel_id: ChannelId) -> Self::Message { msgs::UpdateFailMalformedHTLC { htlc_id, @@ -5230,6 +5441,7 @@ impl FailHTLCContents for ([u8; 32], u16) { fn to_inbound_htlc_state(self) -> InboundHTLCState { InboundHTLCState::LocalRemoved(InboundHTLCRemovalReason::FailMalformed(self)) } + #[rustfmt::skip] fn to_htlc_update_awaiting_ack(self, htlc_id: u64) -> HTLCUpdateAwaitingACK { HTLCUpdateAwaitingACK::FailMalformedHTLC { htlc_id, @@ -5253,10 +5465,12 @@ impl FailHTLCMessageName for msgs::UpdateFailMalformedHTLC { } } -impl FundedChannel where +impl FundedChannel +where SP::Target: SignerProvider, - ::EcdsaSigner: EcdsaChannelSigner + ::EcdsaSigner: EcdsaChannelSigner, { + #[rustfmt::skip] fn check_remote_fee( channel_type: &ChannelTypeFeatures, fee_estimator: &LowerBoundedFeeEstimator, feerate_per_kw: u32, cur_feerate_per_kw: Option, logger: &L @@ -5296,6 +5510,7 @@ impl FundedChannel where } #[inline] + #[rustfmt::skip] fn get_closing_transaction_weight(&self, a_scriptpubkey: Option<&Script>, b_scriptpubkey: Option<&Script>) -> u64 { let mut ret = (4 + // version @@ -5323,6 +5538,7 @@ impl FundedChannel where } #[inline] + #[rustfmt::skip] fn build_closing_transaction(&self, proposed_total_fee_satoshis: u64, skip_remote_output: bool) -> Result<(ClosingTransaction, u64), ChannelError> { assert!(self.context.pending_inbound_htlcs.is_empty()); assert!(self.context.pending_outbound_htlcs.is_empty()); @@ -5379,6 +5595,7 @@ impl FundedChannel where /// /// The HTLC claim will end up in the holding cell (because the caller must ensure the peer is /// disconnected). + #[rustfmt::skip] pub fn claim_htlc_while_disconnected_dropping_mon_update_legacy (&mut self, htlc_id_arg: u64, payment_preimage_arg: PaymentPreimage, logger: &L) where L::Target: Logger { @@ -5393,6 +5610,7 @@ impl FundedChannel where } } + #[rustfmt::skip] fn get_update_fulfill_htlc( &mut self, htlc_id_arg: u64, payment_preimage_arg: PaymentPreimage, payment_info: Option, logger: &L, @@ -5507,6 +5725,7 @@ impl FundedChannel where } } + #[rustfmt::skip] pub fn get_update_fulfill_htlc_and_commit( &mut self, htlc_id: u64, payment_preimage: PaymentPreimage, payment_info: Option, logger: &L, @@ -5550,8 +5769,12 @@ impl FundedChannel where /// Returns `Err` (always with [`ChannelError::Ignore`]) if the HTLC could not be failed (e.g. /// if it was already resolved). Otherwise returns `Ok`. - pub fn queue_fail_htlc(&mut self, htlc_id_arg: u64, err_packet: msgs::OnionErrorPacket, logger: &L) - -> Result<(), ChannelError> where L::Target: Logger { + pub fn queue_fail_htlc( + &mut self, htlc_id_arg: u64, err_packet: msgs::OnionErrorPacket, logger: &L, + ) -> Result<(), ChannelError> + where + L::Target: Logger, + { self.fail_htlc(htlc_id_arg, err_packet, true, logger) .map(|msg_opt| assert!(msg_opt.is_none(), "We forced holding cell?")) } @@ -5561,14 +5784,18 @@ impl FundedChannel where /// /// See [`Self::queue_fail_htlc`] for more info. pub fn queue_fail_malformed_htlc( - &mut self, htlc_id_arg: u64, failure_code: u16, sha256_of_onion: [u8; 32], logger: &L - ) -> Result<(), ChannelError> where L::Target: Logger { + &mut self, htlc_id_arg: u64, failure_code: u16, sha256_of_onion: [u8; 32], logger: &L, + ) -> Result<(), ChannelError> + where + L::Target: Logger, + { self.fail_htlc(htlc_id_arg, (sha256_of_onion, failure_code), true, logger) .map(|msg_opt| assert!(msg_opt.is_none(), "We forced holding cell?")) } /// Returns `Err` (always with [`ChannelError::Ignore`]) if the HTLC could not be failed (e.g. /// if it was already resolved). Otherwise returns `Ok`. + #[rustfmt::skip] fn fail_htlc( &mut self, htlc_id_arg: u64, err_contents: E, mut force_holding_cell: bool, logger: &L @@ -5663,6 +5890,7 @@ impl FundedChannel where /// Handles a channel_ready message from our peer. If we've already sent our channel_ready /// and the channel is now usable (and public), this may generate an announcement_signatures to /// reply with. + #[rustfmt::skip] pub fn channel_ready( &mut self, msg: &msgs::ChannelReady, node_signer: &NS, chain_hash: ChainHash, user_config: &UserConfig, best_block: &BestBlock, logger: &L @@ -5745,6 +5973,7 @@ impl FundedChannel where Ok(self.get_announcement_sigs(node_signer, chain_hash, user_config, best_block.height, logger)) } + #[rustfmt::skip] pub fn update_add_htlc( &mut self, msg: &msgs::UpdateAddHTLC, fee_estimator: &LowerBoundedFeeEstimator, ) -> Result<(), ChannelError> where F::Target: FeeEstimator { @@ -5865,6 +6094,7 @@ impl FundedChannel where /// Marks an outbound HTLC which we have received update_fail/fulfill/malformed #[inline] + #[rustfmt::skip] fn mark_outbound_htlc_removed(&mut self, htlc_id: u64, outcome: OutboundHTLCOutcome) -> Result<&OutboundHTLCOutput, ChannelError> { for htlc in self.context.pending_outbound_htlcs.iter_mut() { if htlc.htlc_id == htlc_id { @@ -5889,6 +6119,7 @@ impl FundedChannel where Err(ChannelError::close("Remote tried to fulfill/fail an HTLC we couldn't find".to_owned())) } + #[rustfmt::skip] pub fn update_fulfill_htlc(&mut self, msg: &msgs::UpdateFulfillHTLC) -> Result<(HTLCSource, u64, Option), ChannelError> { if self.context.channel_state.is_remote_stfu_sent() || self.context.channel_state.is_quiescent() { return Err(ChannelError::WarnAndDisconnect("Got fulfill HTLC message while quiescent".to_owned())); @@ -5903,6 +6134,7 @@ impl FundedChannel where self.mark_outbound_htlc_removed(msg.htlc_id, OutboundHTLCOutcome::Success(msg.payment_preimage)).map(|htlc| (htlc.source.clone(), htlc.amount_msat, htlc.skimmed_fee_msat)) } + #[rustfmt::skip] pub fn update_fail_htlc(&mut self, msg: &msgs::UpdateFailHTLC, fail_reason: HTLCFailReason) -> Result<(), ChannelError> { if self.context.channel_state.is_remote_stfu_sent() || self.context.channel_state.is_quiescent() { return Err(ChannelError::WarnAndDisconnect("Got fail HTLC message while quiescent".to_owned())); @@ -5918,6 +6150,7 @@ impl FundedChannel where Ok(()) } + #[rustfmt::skip] pub fn update_fail_malformed_htlc(&mut self, msg: &msgs::UpdateFailMalformedHTLC, fail_reason: HTLCFailReason) -> Result<(), ChannelError> { if self.context.channel_state.is_remote_stfu_sent() || self.context.channel_state.is_quiescent() { return Err(ChannelError::WarnAndDisconnect("Got fail malformed HTLC message while quiescent".to_owned())); @@ -5933,6 +6166,7 @@ impl FundedChannel where Ok(()) } + #[rustfmt::skip] pub fn commitment_signed_initial_v2( &mut self, msg: &msgs::CommitmentSigned, best_block: BestBlock, signer_provider: &SP, logger: &L ) -> Result::EcdsaSigner>, ChannelError> @@ -5974,6 +6208,7 @@ impl FundedChannel where Ok(channel_monitor) } + #[rustfmt::skip] pub fn commitment_signed(&mut self, msg: &msgs::CommitmentSigned, logger: &L) -> Result, ChannelError> where L::Target: Logger { @@ -5991,6 +6226,7 @@ impl FundedChannel where self.commitment_signed_update_monitor(updates, logger) } + #[rustfmt::skip] pub fn commitment_signed_batch(&mut self, batch: &BTreeMap, logger: &L) -> Result, ChannelError> where L::Target: Logger { @@ -6019,6 +6255,7 @@ impl FundedChannel where self.commitment_signed_update_monitor(updates, logger) } + #[rustfmt::skip] fn commitment_signed_check_state(&self) -> Result<(), ChannelError> { if self.context.channel_state.is_quiescent() { return Err(ChannelError::WarnAndDisconnect("Got commitment_signed message while quiescent".to_owned())); @@ -6036,6 +6273,7 @@ impl FundedChannel where Ok(()) } + #[rustfmt::skip] fn commitment_signed_update_monitor(&mut self, mut updates: Vec, logger: &L) -> Result, ChannelError> where L::Target: Logger { @@ -6156,6 +6394,7 @@ impl FundedChannel where /// Public version of the below, checking relevant preconditions first. /// If we're not in a state where freeing the holding cell makes sense, this is a no-op and /// returns `(None, Vec::new())`. + #[rustfmt::skip] pub fn maybe_free_holding_cell_htlcs( &mut self, fee_estimator: &LowerBoundedFeeEstimator, logger: &L ) -> (Option, Vec<(HTLCSource, PaymentHash)>) @@ -6168,6 +6407,7 @@ impl FundedChannel where /// Frees any pending commitment updates in the holding cell, generating the relevant messages /// for our counterparty. + #[rustfmt::skip] fn free_holding_cell_htlcs( &mut self, fee_estimator: &LowerBoundedFeeEstimator, logger: &L ) -> (Option, Vec<(HTLCSource, PaymentHash)>) @@ -6306,6 +6546,7 @@ impl FundedChannel where /// waiting on this revoke_and_ack. The generation of this new commitment_signed may also fail, /// generating an appropriate error *after* the channel state has been updated based on the /// revoke_and_ack message. + #[rustfmt::skip] pub fn revoke_and_ack(&mut self, msg: &msgs::RevokeAndACK, fee_estimator: &LowerBoundedFeeEstimator, logger: &L, hold_mon_update: bool, ) -> Result<(Vec<(HTLCSource, PaymentHash)>, Option), ChannelError> @@ -6521,6 +6762,7 @@ impl FundedChannel where let release_monitor = self.context.blocked_monitor_updates.is_empty() && !hold_mon_update; let release_state_str = if hold_mon_update { "Holding" } else if release_monitor { "Releasing" } else { "Blocked" }; + #[rustfmt::skip] macro_rules! return_with_htlcs_to_fail { ($htlcs_to_fail: expr) => { if !release_monitor { @@ -6595,6 +6837,7 @@ impl FundedChannel where } } + #[rustfmt::skip] pub fn tx_signatures(&mut self, msg: &msgs::TxSignatures, logger: &L) -> Result<(Option, Option), ChannelError> where L::Target: Logger { @@ -6682,9 +6925,11 @@ impl FundedChannel where /// Queues up an outbound update fee by placing it in the holding cell. You should call /// [`Self::maybe_free_holding_cell_htlcs`] in order to actually generate and send the /// commitment update. - pub fn queue_update_fee(&mut self, feerate_per_kw: u32, - fee_estimator: &LowerBoundedFeeEstimator, logger: &L) - where F::Target: FeeEstimator, L::Target: Logger + pub fn queue_update_fee( + &mut self, feerate_per_kw: u32, fee_estimator: &LowerBoundedFeeEstimator, logger: &L, + ) where + F::Target: FeeEstimator, + L::Target: Logger, { let msg_opt = self.send_update_fee(feerate_per_kw, true, fee_estimator, logger); assert!(msg_opt.is_none(), "We forced holding cell?"); @@ -6697,6 +6942,7 @@ impl FundedChannel where /// /// You MUST call [`Self::send_commitment_no_state_update`] prior to any other calls on this /// [`FundedChannel`] if `force_holding_cell` is false. + #[rustfmt::skip] fn send_update_fee( &mut self, feerate_per_kw: u32, mut force_holding_cell: bool, fee_estimator: &LowerBoundedFeeEstimator, logger: &L @@ -6766,6 +7012,7 @@ impl FundedChannel where /// No further message handling calls may be made until a channel_reestablish dance has /// completed. /// May return `Err(())`, which implies [`ChannelContext::force_shutdown`] should be called immediately. + #[rustfmt::skip] fn remove_uncommitted_htlcs_and_mark_paused(&mut self, logger: &L) -> Result<(), ()> where L::Target: Logger { assert!(!matches!(self.context.channel_state, ChannelState::ShutdownComplete)); if self.context.channel_state.is_pre_funded_state() { @@ -6861,6 +7108,7 @@ impl FundedChannel where /// [`ChannelManager`]: super::channelmanager::ChannelManager /// [`chain::Watch`]: crate::chain::Watch /// [`ChannelMonitorUpdateStatus::InProgress`]: crate::chain::ChannelMonitorUpdateStatus::InProgress + #[rustfmt::skip] fn monitor_updating_paused(&mut self, resend_raa: bool, resend_commitment: bool, resend_channel_ready: bool, mut pending_forwards: Vec<(PendingHTLCInfo, u64)>, mut pending_fails: Vec<(HTLCSource, PaymentHash, HTLCFailReason)>, @@ -6878,6 +7126,7 @@ impl FundedChannel where /// Indicates that the latest ChannelMonitor update has been committed by the client /// successfully and we should restore normal operation. Returns messages which should be sent /// to the remote side. + #[rustfmt::skip] pub fn monitor_updating_restored( &mut self, logger: &L, node_signer: &NS, chain_hash: ChainHash, user_config: &UserConfig, best_block_height: u32 @@ -6980,7 +7229,9 @@ impl FundedChannel where } } - pub fn check_for_stale_feerate(&mut self, logger: &L, min_feerate: u32) -> Result<(), ClosureReason> { + pub fn check_for_stale_feerate( + &mut self, logger: &L, min_feerate: u32, + ) -> Result<(), ClosureReason> { if self.funding.is_outbound() { // While its possible our fee is too low for an outbound channel because we've been // unable to increase the fee, we don't try to force-close directly here. @@ -7000,6 +7251,7 @@ impl FundedChannel where } } + #[rustfmt::skip] pub fn update_fee(&mut self, fee_estimator: &LowerBoundedFeeEstimator, msg: &msgs::UpdateFee, logger: &L) -> Result<(), ChannelError> where F::Target: FeeEstimator, L::Target: Logger { @@ -7033,6 +7285,7 @@ impl FundedChannel where /// Indicates that the signer may have some signatures for us, so we should retry if we're /// blocked. + #[rustfmt::skip] pub fn signer_maybe_unblocked(&mut self, logger: &L) -> SignerResumeUpdates where L::Target: Logger { if !self.holder_commitment_point.is_available() { log_trace!(logger, "Attempting to update holder per-commitment point..."); @@ -7129,6 +7382,7 @@ impl FundedChannel where } } + #[rustfmt::skip] fn get_last_revoke_and_ack(&mut self, logger: &L) -> Option where L::Target: Logger { debug_assert!(self.holder_commitment_point.transaction_number() <= INITIAL_COMMITMENT_NUMBER - 2); self.holder_commitment_point.try_resolve_pending(&self.context.holder_signer, &self.context.secp_ctx, logger); @@ -7167,6 +7421,7 @@ impl FundedChannel where } /// Gets the last commitment update for immediate sending to our peer. + #[rustfmt::skip] fn get_last_commitment_update_for_send(&mut self, logger: &L) -> Result where L::Target: Logger { let mut update_add_htlcs = Vec::new(); let mut update_fulfill_htlcs = Vec::new(); @@ -7248,6 +7503,7 @@ impl FundedChannel where } /// Gets the `Shutdown` message we should send our peer on reconnect, if any. + #[rustfmt::skip] pub fn get_outbound_shutdown(&self) -> Option { if self.context.channel_state.is_local_shutdown_sent() { assert!(self.context.shutdown_scriptpubkey.is_some()); @@ -7265,6 +7521,7 @@ impl FundedChannel where /// `cargo doc --document-private-items`): /// [`super::channelmanager::ChannelManager::force_close_without_broadcasting_txn`] and /// [`super::channelmanager::ChannelManager::force_close_all_channels_without_broadcasting_txn`]. + #[rustfmt::skip] pub fn channel_reestablish( &mut self, msg: &msgs::ChannelReestablish, logger: &L, node_signer: &NS, chain_hash: ChainHash, user_config: &UserConfig, best_block: &BestBlock @@ -7299,6 +7556,7 @@ impl FundedChannel where return Err(ChannelError::close("Peer sent a garbage channel_reestablish with secret key not matching the commitment height provided".to_owned())); } if msg.next_remote_commitment_number > our_commitment_transaction { + #[rustfmt::skip] macro_rules! log_and_panic { ($err_msg: expr) => { log_error!(logger, $err_msg, &self.context.channel_id, log_pubkey!(self.context.counterparty_node_id)); @@ -7547,6 +7805,7 @@ impl FundedChannel where /// Calculates and returns our minimum and maximum closing transaction fee amounts, in whole /// satoshis. The amounts remain consistent unless a peer disconnects/reconnects or we restart, /// at which point they will be recalculated. + #[rustfmt::skip] fn calculate_closing_fee_limits(&mut self, fee_estimator: &LowerBoundedFeeEstimator) -> (u64, u64) where F::Target: FeeEstimator @@ -7608,6 +7867,7 @@ impl FundedChannel where /// Checks if the closing_signed negotiation is making appropriate progress, possibly returning /// an Err if no progress is being made and the channel should be force-closed instead. /// Should be called on a one-minute timer. + #[rustfmt::skip] pub fn timer_check_closing_negotiation_progress(&mut self) -> Result<(), ChannelError> { if self.closing_negotiation_ready() { if self.context.closing_signed_in_flight { @@ -7619,6 +7879,7 @@ impl FundedChannel where Ok(()) } + #[rustfmt::skip] pub fn maybe_propose_closing_signed( &mut self, fee_estimator: &LowerBoundedFeeEstimator, logger: &L) -> Result<(Option, Option, Option), ChannelError> @@ -7666,6 +7927,7 @@ impl FundedChannel where /// This should be called for peers with an active socket on every /// [`super::channelmanager::ChannelManager::timer_tick_occurred`]. #[allow(clippy::assertions_on_constants)] + #[rustfmt::skip] pub fn should_disconnect_peer_awaiting_response(&mut self) -> bool { if let Some(ticks_elapsed) = self.context.sent_message_awaiting_response.as_mut() { *ticks_elapsed += 1; @@ -7693,6 +7955,7 @@ impl FundedChannel where } } + #[rustfmt::skip] pub fn shutdown( &mut self, signer_provider: &SP, their_features: &InitFeatures, msg: &msgs::Shutdown ) -> Result<(Option, Option, Vec<(HTLCSource, PaymentHash)>), ChannelError> @@ -7804,7 +8067,9 @@ impl FundedChannel where Ok((shutdown, monitor_update, dropped_outbound_htlcs)) } - fn build_signed_closing_transaction(&self, closing_tx: &ClosingTransaction, counterparty_sig: &Signature, sig: &Signature) -> Transaction { + fn build_signed_closing_transaction( + &self, closing_tx: &ClosingTransaction, counterparty_sig: &Signature, sig: &Signature, + ) -> Transaction { let mut tx = closing_tx.trust().built_transaction().clone(); tx.input[0].witness.push(Vec::new()); // First is the multisig dummy @@ -7827,6 +8092,7 @@ impl FundedChannel where tx } + #[rustfmt::skip] fn get_closing_signed_msg( &mut self, closing_tx: &ClosingTransaction, skip_remote_output: bool, fee_satoshis: u64, min_fee_satoshis: u64, max_fee_satoshis: u64, logger: &L @@ -7855,6 +8121,7 @@ impl FundedChannel where }) } + #[rustfmt::skip] fn shutdown_result_coop_close(&self) -> ShutdownResult { let closure_reason = if self.initiated_shutdown() { ClosureReason::LocallyInitiatedCooperativeClosure @@ -7877,6 +8144,7 @@ impl FundedChannel where } } + #[rustfmt::skip] pub fn closing_signed( &mut self, fee_estimator: &LowerBoundedFeeEstimator, msg: &msgs::ClosingSigned, logger: &L) -> Result<(Option, Option, Option), ChannelError> @@ -7946,6 +8214,7 @@ impl FundedChannel where let (our_min_fee, our_max_fee) = self.calculate_closing_fee_limits(fee_estimator); + #[rustfmt::skip] macro_rules! propose_fee { ($new_fee: expr) => { let (closing_tx, used_fee) = if $new_fee == msg.fee_satoshis { @@ -8031,6 +8300,7 @@ impl FundedChannel where } } + #[rustfmt::skip] fn internal_htlc_satisfies_config( &self, htlc: &msgs::UpdateAddHTLC, amt_to_forward: u64, outgoing_cltv_value: u32, config: &ChannelConfig, ) -> Result<(), LocalHTLCFailureReason> { @@ -8049,6 +8319,7 @@ impl FundedChannel where /// Determines whether the parameters of an incoming HTLC to be forwarded satisfy the channel's /// [`ChannelConfig`]. This first looks at the channel's current [`ChannelConfig`], and if /// unsuccessful, falls back to the previous one if one exists. + #[rustfmt::skip] pub fn htlc_satisfies_config( &self, htlc: &msgs::UpdateAddHTLC, amt_to_forward: u64, outgoing_cltv_value: u32, ) -> Result<(), LocalHTLCFailureReason> { @@ -8064,6 +8335,7 @@ impl FundedChannel where /// When this function is called, the HTLC is already irrevocably committed to the channel; /// this function determines whether to fail the HTLC, or forward / claim it. + #[rustfmt::skip] pub fn can_accept_incoming_htlc( &self, msg: &msgs::UpdateAddHTLC, fee_estimator: &LowerBoundedFeeEstimator, logger: L ) -> Result<(), LocalHTLCFailureReason> @@ -8146,6 +8418,7 @@ impl FundedChannel where self.holder_commitment_point.transaction_number() + 1 } + #[rustfmt::skip] pub fn get_cur_counterparty_commitment_transaction_number(&self) -> u64 { self.context.cur_counterparty_commitment_transaction_number + 1 - if self.context.channel_state.is_awaiting_remote_revoke() { 1 } else { 0 } } @@ -8160,6 +8433,7 @@ impl FundedChannel where } #[cfg(any(test, feature = "_externalize_tests"))] + #[rustfmt::skip] pub fn get_value_stat(&self) -> ChannelValueStat { ChannelValueStat { value_to_self_msat: self.funding.value_to_self_msat, @@ -8191,6 +8465,7 @@ impl FundedChannel where } /// Gets the latest [`ChannelMonitorUpdate`] ID which has been released and is in-flight. + #[rustfmt::skip] pub fn get_latest_unblocked_monitor_update_id(&self) -> u64 { if self.context.blocked_monitor_updates.is_empty() { return self.context.get_latest_monitor_update_id(); } self.context.blocked_monitor_updates[0].update.update_id - 1 @@ -8198,6 +8473,7 @@ impl FundedChannel where /// Returns the next blocked monitor update, if one exists, and a bool which indicates a /// further blocked monitor update exists after the next. + #[rustfmt::skip] pub fn unblock_next_blocked_monitor_update(&mut self) -> Option<(ChannelMonitorUpdate, bool)> { if self.context.blocked_monitor_updates.is_empty() { return None; } Some((self.context.blocked_monitor_updates.remove(0).update, @@ -8206,6 +8482,7 @@ impl FundedChannel where /// Pushes a new monitor update into our monitor update queue, returning it if it should be /// immediately given to the user for persisting or `None` if it should be held as blocked. + #[rustfmt::skip] fn push_ret_blockable_mon_update(&mut self, update: ChannelMonitorUpdate) -> Option { let release_monitor = self.context.blocked_monitor_updates.is_empty(); @@ -8222,7 +8499,9 @@ impl FundedChannel where /// On startup, its possible we detect some monitor updates have actually completed (and the /// ChannelManager was simply stale). In that case, we should simply drop them, which we do /// here after logging them. - pub fn on_startup_drop_completed_blocked_mon_updates_through(&mut self, logger: &L, loaded_mon_update_id: u64) { + pub fn on_startup_drop_completed_blocked_mon_updates_through( + &mut self, logger: &L, loaded_mon_update_id: u64, + ) { let channel_id = self.context.channel_id(); self.context.blocked_monitor_updates.retain(|update| { if update.update.update_id <= loaded_mon_update_id { @@ -8247,6 +8526,7 @@ impl FundedChannel where /// If the channel is outbound, this implies we have not yet broadcasted the funding /// transaction. If the channel is inbound, this implies simply that the channel has not /// advanced state. + #[rustfmt::skip] pub fn is_awaiting_initial_mon_persist(&self) -> bool { if !self.is_awaiting_monitor_update() { return false; } if matches!( @@ -8281,6 +8561,7 @@ impl FundedChannel where } /// Returns true if our channel_ready has been sent + #[rustfmt::skip] pub fn is_our_channel_ready(&self) -> bool { matches!(self.context.channel_state, ChannelState::AwaitingChannelReady(flags) if flags.is_set(AwaitingChannelReadyFlags::OUR_CHANNEL_READY)) || matches!(self.context.channel_state, ChannelState::ChannelReady(_)) @@ -8323,6 +8604,7 @@ impl FundedChannel where self.context.channel_update_status = status; } + #[rustfmt::skip] fn check_get_channel_ready(&mut self, height: u32, logger: &L) -> Option where L::Target: Logger { @@ -8390,6 +8672,7 @@ impl FundedChannel where self.get_channel_ready(logger) } + #[rustfmt::skip] fn get_channel_ready( &mut self, logger: &L ) -> Option where L::Target: Logger { @@ -8410,6 +8693,7 @@ impl FundedChannel where /// When a transaction is confirmed, we check whether it is or spends the funding transaction /// In the first case, we store the confirmation height and calculating the short channel id. /// In the second, we simply return an Err indicating we need to be force-closed now. + #[rustfmt::skip] pub fn transactions_confirmed( &mut self, block_hash: &BlockHash, height: u32, txdata: &TransactionData, chain_hash: ChainHash, node_signer: &NS, user_config: &UserConfig, logger: &L @@ -8499,6 +8783,7 @@ impl FundedChannel where /// /// May return some HTLCs (and their payment_hash) which have timed out and should be failed /// back. + #[rustfmt::skip] pub fn best_block_updated( &mut self, height: u32, highest_header_time: u32, chain_hash: ChainHash, node_signer: &NS, user_config: &UserConfig, logger: &L @@ -8510,6 +8795,7 @@ impl FundedChannel where self.do_best_block_updated(height, highest_header_time, Some((chain_hash, node_signer, user_config)), logger) } + #[rustfmt::skip] fn do_best_block_updated( &mut self, height: u32, highest_header_time: u32, chain_node_signer: Option<(ChainHash, &NS, &UserConfig)>, logger: &L @@ -8587,6 +8873,7 @@ impl FundedChannel where /// Indicates the funding transaction is no longer confirmed in the main chain. This may /// force-close the channel, but may also indicate a harmless reorganization of a block or two /// before the channel has reached channel_ready and we can just wait for more blocks. + #[rustfmt::skip] pub fn funding_transaction_unconfirmed(&mut self, logger: &L) -> Result<(), ClosureReason> where L::Target: Logger { if self.context.funding_tx_confirmation_height != 0 { // We handle the funding disconnection by calling best_block_updated with a height one @@ -8625,6 +8912,7 @@ impl FundedChannel where /// This will only return ChannelError::Ignore upon failure. /// /// [`ChannelReady`]: crate::ln::msgs::ChannelReady + #[rustfmt::skip] fn get_channel_announcement( &self, node_signer: &NS, chain_hash: ChainHash, user_config: &UserConfig, ) -> Result where NS::Target: NodeSigner { @@ -8656,6 +8944,7 @@ impl FundedChannel where Ok(msg) } + #[rustfmt::skip] fn get_announcement_sigs( &mut self, node_signer: &NS, chain_hash: ChainHash, user_config: &UserConfig, best_block_height: u32, logger: &L @@ -8729,6 +9018,7 @@ impl FundedChannel where /// Signs the given channel announcement, returning a ChannelError::Ignore if no keys are /// available. + #[rustfmt::skip] fn sign_channel_announcement( &self, node_signer: &NS, announcement: msgs::UnsignedChannelAnnouncement ) -> Result where NS::Target: NodeSigner { @@ -8765,6 +9055,7 @@ impl FundedChannel where /// Processes an incoming announcement_signatures message, providing a fully-signed /// channel_announcement message which we can broadcast and storing our counterparty's /// signatures for later reconstruction/rebroadcast of the channel_announcement. + #[rustfmt::skip] pub fn announcement_signatures( &mut self, node_signer: &NS, chain_hash: ChainHash, best_block_height: u32, msg: &msgs::AnnouncementSignatures, user_config: &UserConfig @@ -8795,6 +9086,7 @@ impl FundedChannel where /// Gets a signed channel_announcement for this channel, if we previously received an /// announcement_signatures from our counterparty. + #[rustfmt::skip] pub fn get_signed_channel_announcement( &self, node_signer: &NS, chain_hash: ChainHash, best_block_height: u32, user_config: &UserConfig ) -> Option where NS::Target: NodeSigner { @@ -8808,6 +9100,7 @@ impl FundedChannel where self.sign_channel_announcement(node_signer, announcement).ok() } + #[rustfmt::skip] fn maybe_get_next_funding_txid(&self) -> Option { // If we've sent `commtiment_signed` for an interactively constructed transaction // during a signing session, but have not received `tx_signatures` we MUST set `next_funding_txid` @@ -8829,6 +9122,7 @@ impl FundedChannel where /// May panic if called on a channel that wasn't immediately-previously /// self.remove_uncommitted_htlcs_and_mark_paused()'d + #[rustfmt::skip] fn get_channel_reestablish(&mut self, logger: &L) -> msgs::ChannelReestablish where L::Target: Logger { assert!(self.context.channel_state.is_peer_disconnected()); assert_ne!(self.context.cur_counterparty_commitment_transaction_number, INITIAL_COMMITMENT_NUMBER); @@ -8884,6 +9178,7 @@ impl FundedChannel where /// - `our_funding_inputs`: the inputs we contribute to the new funding transaction. /// Includes the witness weight for this input (e.g. P2WPKH_WITNESS_WEIGHT=109 for typical P2WPKH inputs). #[cfg(splicing)] + #[rustfmt::skip] pub fn splice_channel(&mut self, our_funding_contribution_satoshis: i64, our_funding_inputs: &Vec<(TxIn, Transaction, Weight)>, funding_feerate_per_kw: u32, locktime: u32, @@ -8936,8 +9231,8 @@ impl FundedChannel where /// Get the splice message that can be sent during splice initiation. #[cfg(splicing)] - fn get_splice_init(&self, our_funding_contribution_satoshis: i64, - funding_feerate_per_kw: u32, locktime: u32, + fn get_splice_init( + &self, our_funding_contribution_satoshis: i64, funding_feerate_per_kw: u32, locktime: u32, ) -> msgs::SpliceInit { // TODO(splicing): The exisiting pubkey is reused, but a new one should be generated. See #3542. // Note that channel_keys_id is supposed NOT to change @@ -8954,6 +9249,7 @@ impl FundedChannel where /// Handle splice_init #[cfg(splicing)] + #[rustfmt::skip] pub fn splice_init(&mut self, msg: &msgs::SpliceInit) -> Result { let their_funding_contribution_satoshis = msg.funding_contribution_satoshis; // TODO(splicing): Currently not possible to contribute on the splicing-acceptor side @@ -9021,6 +9317,7 @@ impl FundedChannel where /// Queues up an outbound HTLC to send by placing it in the holding cell. You should call /// [`Self::maybe_free_holding_cell_htlcs`] in order to actually generate and send the /// commitment update. + #[rustfmt::skip] pub fn queue_add_htlc( &mut self, amount_msat: u64, payment_hash: PaymentHash, cltv_expiry: u32, source: HTLCSource, onion_routing_packet: msgs::OnionPacket, skimmed_fee_msat: Option, @@ -9054,6 +9351,7 @@ impl FundedChannel where /// on this [`FundedChannel`] if `force_holding_cell` is false. /// /// `Err`'s will always be temporary channel failures. + #[rustfmt::skip] fn send_htlc( &mut self, amount_msat: u64, payment_hash: PaymentHash, cltv_expiry: u32, source: HTLCSource, onion_routing_packet: msgs::OnionPacket, mut force_holding_cell: bool, @@ -9160,6 +9458,7 @@ impl FundedChannel where Ok(Some(res)) } + #[rustfmt::skip] pub(super) fn get_available_balances( &self, fee_estimator: &LowerBoundedFeeEstimator, ) -> AvailableBalances @@ -9180,6 +9479,7 @@ impl FundedChannel where .expect("At least one FundingScope is always provided") } + #[rustfmt::skip] fn build_commitment_no_status_check(&mut self, logger: &L) -> ChannelMonitorUpdate where L::Target: Logger { log_trace!(logger, "Updating HTLC state for a newly-sent commitment_signed..."); // We can upgrade the status of some HTLCs that are waiting on a commitment, even if we @@ -9254,6 +9554,7 @@ impl FundedChannel where monitor_update } + #[rustfmt::skip] fn build_commitment_no_state_update( &self, funding: &FundingScope, logger: &L, ) -> (Vec<(HTLCOutputInCommitment, Option<&HTLCSource>)>, CommitmentTransaction) @@ -9301,6 +9602,7 @@ impl FundedChannel where .collect::, ChannelError>>() } + #[rustfmt::skip] fn send_commitment_no_state_update_for_funding( &self, funding: &FundingScope, logger: &L, ) -> Result @@ -9378,6 +9680,7 @@ impl FundedChannel where /// /// Shorthand for calling [`Self::send_htlc`] followed by a commitment update, see docs on /// [`Self::send_htlc`] and [`Self::build_commitment_no_state_update`] for more info. + #[rustfmt::skip] pub fn send_htlc_and_commit( &mut self, amount_msat: u64, payment_hash: PaymentHash, cltv_expiry: u32, source: HTLCSource, onion_routing_packet: msgs::OnionPacket, skimmed_fee_msat: Option, @@ -9400,6 +9703,7 @@ impl FundedChannel where /// Applies the `ChannelUpdate` and returns a boolean indicating whether a change actually /// happened. + #[rustfmt::skip] pub fn channel_update(&mut self, msg: &msgs::ChannelUpdate) -> Result { let new_forwarding_info = Some(CounterpartyForwardingInfo { fee_base_msat: msg.contents.fee_base_msat, @@ -9416,6 +9720,7 @@ impl FundedChannel where /// Begins the shutdown process, getting a message for the remote peer and returning all /// holding cell HTLCs for payment failure. + #[rustfmt::skip] pub fn get_shutdown(&mut self, signer_provider: &SP, their_features: &InitFeatures, target_feerate_sats_per_kw: Option, override_shutdown_script: Option) -> Result<(msgs::Shutdown, Option, Vec<(HTLCSource, PaymentHash)>), APIError> @@ -9515,6 +9820,7 @@ impl FundedChannel where // Miscellaneous utilities + #[rustfmt::skip] pub fn inflight_htlc_sources(&self) -> impl Iterator { self.context.holding_cell_htlc_updates.iter() .flat_map(|htlc_update| { @@ -9527,6 +9833,7 @@ impl FundedChannel where .chain(self.context.pending_outbound_htlcs.iter().map(|htlc| (&htlc.source, &htlc.payment_hash))) } + #[rustfmt::skip] pub fn get_announced_htlc_max_msat(&self) -> u64 { return cmp::min( // Upper bound by capacity. We make it a bit less than full capacity to prevent attempts @@ -9539,6 +9846,7 @@ impl FundedChannel where } #[cfg(any(test, fuzzing))] + #[rustfmt::skip] pub fn propose_quiescence( &mut self, logger: &L, ) -> Result, ChannelError> @@ -9567,6 +9875,7 @@ impl FundedChannel where } // Assumes we are either awaiting quiescence or our counterparty has requested quiescence. + #[rustfmt::skip] pub fn send_stfu(&mut self, logger: &L) -> Result where L::Target: Logger, @@ -9615,6 +9924,7 @@ impl FundedChannel where Ok(msgs::Stfu { channel_id: self.context.channel_id, initiator }) } + #[rustfmt::skip] pub fn stfu( &mut self, msg: &msgs::Stfu, logger: &L ) -> Result, ChannelError> where L::Target: Logger { @@ -9721,6 +10031,7 @@ impl FundedChannel where } #[cfg(any(test, fuzzing))] + #[rustfmt::skip] pub fn exit_quiescence(&mut self) -> bool { // Make sure we either finished the quiescence handshake and are quiescent, or we never // attempted to initiate quiescence at all. @@ -9739,7 +10050,10 @@ impl FundedChannel where } /// A not-yet-funded outbound (from holder) channel using V1 channel establishment. -pub(super) struct OutboundV1Channel where SP::Target: SignerProvider { +pub(super) struct OutboundV1Channel +where + SP::Target: SignerProvider, +{ pub funding: FundingScope, pub context: ChannelContext, pub unfunded_context: UnfundedChannelContext, @@ -9749,8 +10063,12 @@ pub(super) struct OutboundV1Channel where SP::Target: SignerProvider pub signer_pending_open_channel: bool, } -impl OutboundV1Channel where SP::Target: SignerProvider { +impl OutboundV1Channel +where + SP::Target: SignerProvider, +{ #[allow(dead_code)] // TODO(dual_funding): Remove once opending V2 channels is enabled. + #[rustfmt::skip] pub fn new( fee_estimator: &LowerBoundedFeeEstimator, entropy_source: &ES, signer_provider: &SP, counterparty_node_id: PublicKey, their_features: &InitFeatures, channel_value_satoshis: u64, push_msat: u64, user_id: u128, config: &UserConfig, current_chain_height: u32, @@ -9805,6 +10123,7 @@ impl OutboundV1Channel where SP::Target: SignerProvider { } /// Only allowed after [`FundingScope::channel_transaction_parameters`] is set. + #[rustfmt::skip] fn get_funding_created_msg(&mut self, logger: &L) -> Option where L::Target: Logger { let commitment_data = self.context.build_commitment_transaction(&self.funding, self.context.cur_counterparty_commitment_transaction_number, @@ -9849,6 +10168,7 @@ impl OutboundV1Channel where SP::Target: SignerProvider { /// Note that channel_id changes during this call! /// Do NOT broadcast the funding transaction until after a successful funding_signed call! /// If an Err is returned, it is a ChannelError::Close. + #[rustfmt::skip] pub fn get_funding_created(&mut self, funding_transaction: Transaction, funding_txo: OutPoint, is_batch_funding: bool, logger: &L) -> Result, (Self, ChannelError)> where L::Target: Logger { if !self.funding.is_outbound() { @@ -9889,7 +10209,7 @@ impl OutboundV1Channel where SP::Target: SignerProvider { /// not of our ability to open any channel at all. Thus, on error, we should first call this /// and see if we get a new `OpenChannel` message, otherwise the channel is failed. pub(crate) fn maybe_handle_error_without_close( - &mut self, chain_hash: ChainHash, fee_estimator: &LowerBoundedFeeEstimator, logger: &L + &mut self, chain_hash: ChainHash, fee_estimator: &LowerBoundedFeeEstimator, logger: &L, ) -> Result where F::Target: FeeEstimator, @@ -9900,11 +10220,13 @@ impl OutboundV1Channel where SP::Target: SignerProvider { } /// Returns true if we can resume the channel by sending the [`msgs::OpenChannel`] again. + #[rustfmt::skip] pub fn is_resumable(&self) -> bool { !self.context.have_received_message() && self.unfunded_context.transaction_number() == INITIAL_COMMITMENT_NUMBER } + #[rustfmt::skip] pub fn get_open_channel( &mut self, chain_hash: ChainHash, _logger: &L ) -> Option where L::Target: Logger { @@ -9962,6 +10284,7 @@ impl OutboundV1Channel where SP::Target: SignerProvider { } // Message handlers + #[rustfmt::skip] pub fn accept_channel( &mut self, msg: &msgs::AcceptChannel, default_limits: &ChannelHandshakeLimits, their_features: &InitFeatures @@ -9974,6 +10297,7 @@ impl OutboundV1Channel where SP::Target: SignerProvider { /// Handles a funding_signed message from the remote end. /// If this call is successful, broadcast the funding transaction (and not before!) + #[rustfmt::skip] pub fn funding_signed( mut self, msg: &msgs::FundingSigned, best_block: BestBlock, signer_provider: &SP, logger: &L ) -> Result<(FundedChannel, ChannelMonitor<::EcdsaSigner>), (OutboundV1Channel, ChannelError)> @@ -10020,6 +10344,7 @@ impl OutboundV1Channel where SP::Target: SignerProvider { /// Indicates that the signer may have some signatures for us, so we should retry if we're /// blocked. + #[rustfmt::skip] pub fn signer_maybe_unblocked( &mut self, chain_hash: ChainHash, logger: &L ) -> (Option, Option) where L::Target: Logger { @@ -10054,7 +10379,10 @@ impl OutboundV1Channel where SP::Target: SignerProvider { } /// A not-yet-funded inbound (from counterparty) channel using V1 channel establishment. -pub(super) struct InboundV1Channel where SP::Target: SignerProvider { +pub(super) struct InboundV1Channel +where + SP::Target: SignerProvider, +{ pub funding: FundingScope, pub context: ChannelContext, pub unfunded_context: UnfundedChannelContext, @@ -10063,6 +10391,7 @@ pub(super) struct InboundV1Channel where SP::Target: SignerProvider { /// Fetches the [`ChannelTypeFeatures`] that will be used for a channel built from a given /// [`msgs::CommonOpenChannelFields`]. +#[rustfmt::skip] pub(super) fn channel_type_from_open_channel( common_fields: &msgs::CommonOpenChannelFields, their_features: &InitFeatures, our_supported_features: &ChannelTypeFeatures @@ -10096,9 +10425,13 @@ pub(super) fn channel_type_from_open_channel( } } -impl InboundV1Channel where SP::Target: SignerProvider { +impl InboundV1Channel +where + SP::Target: SignerProvider, +{ /// Creates a new channel from a remote sides' request for one. /// Assumes chain_hash has already been checked and corresponds with what we expect! + #[rustfmt::skip] pub fn new( fee_estimator: &LowerBoundedFeeEstimator, entropy_source: &ES, signer_provider: &SP, counterparty_node_id: PublicKey, our_supported_features: &ChannelTypeFeatures, @@ -10156,9 +10489,10 @@ impl InboundV1Channel where SP::Target: SignerProvider { /// should be sent back to the counterparty node. /// /// [`msgs::AcceptChannel`]: crate::ln::msgs::AcceptChannel - pub fn accept_inbound_channel( - &mut self, logger: &L - ) -> Option where L::Target: Logger { + pub fn accept_inbound_channel(&mut self, logger: &L) -> Option + where + L::Target: Logger, + { if self.funding.is_outbound() { panic!("Tried to send accept_channel for an outbound channel?"); } @@ -10180,6 +10514,7 @@ impl InboundV1Channel where SP::Target: SignerProvider { /// [`InboundV1Channel::accept_inbound_channel`] instead. /// /// [`msgs::AcceptChannel`]: crate::ln::msgs::AcceptChannel + #[rustfmt::skip] fn generate_accept_channel_message( &mut self, _logger: &L ) -> Option where L::Target: Logger { @@ -10229,11 +10564,15 @@ impl InboundV1Channel where SP::Target: SignerProvider { /// [`msgs::AcceptChannel`]: crate::ln::msgs::AcceptChannel #[cfg(test)] pub fn get_accept_channel_message( - &mut self, logger: &L - ) -> Option where L::Target: Logger { + &mut self, logger: &L, + ) -> Option + where + L::Target: Logger, + { self.generate_accept_channel_message(logger) } + #[rustfmt::skip] pub fn funding_created( mut self, msg: &msgs::FundingCreated, best_block: BestBlock, signer_provider: &SP, logger: &L ) -> Result<(FundedChannel, Option, ChannelMonitor<::EcdsaSigner>), (Self, ChannelError)> @@ -10296,6 +10635,7 @@ impl InboundV1Channel where SP::Target: SignerProvider { /// Indicates that the signer may have some signatures for us, so we should retry if we're /// blocked. + #[rustfmt::skip] pub fn signer_maybe_unblocked( &mut self, logger: &L ) -> Option where L::Target: Logger { @@ -10315,7 +10655,10 @@ impl InboundV1Channel where SP::Target: SignerProvider { } // A not-yet-funded channel using V2 channel establishment. -pub(super) struct PendingV2Channel where SP::Target: SignerProvider { +pub(super) struct PendingV2Channel +where + SP::Target: SignerProvider, +{ pub funding: FundingScope, pub context: ChannelContext, pub unfunded_context: UnfundedChannelContext, @@ -10326,8 +10669,12 @@ pub(super) struct PendingV2Channel where SP::Target: SignerProvider { pub interactive_tx_signing_session: Option, } -impl PendingV2Channel where SP::Target: SignerProvider { +impl PendingV2Channel +where + SP::Target: SignerProvider, +{ #[allow(dead_code)] // TODO(dual_funding): Remove once creating V2 channels is enabled. + #[rustfmt::skip] pub fn new_outbound( fee_estimator: &LowerBoundedFeeEstimator, entropy_source: &ES, signer_provider: &SP, counterparty_node_id: PublicKey, their_features: &InitFeatures, funding_satoshis: u64, @@ -10401,15 +10748,16 @@ impl PendingV2Channel where SP::Target: SignerProvider { /// not of our ability to open any channel at all. Thus, on error, we should first call this /// and see if we get a new `OpenChannelV2` message, otherwise the channel is failed. pub(crate) fn maybe_handle_error_without_close( - &mut self, chain_hash: ChainHash, fee_estimator: &LowerBoundedFeeEstimator + &mut self, chain_hash: ChainHash, fee_estimator: &LowerBoundedFeeEstimator, ) -> Result where - F::Target: FeeEstimator + F::Target: FeeEstimator, { self.context.maybe_downgrade_channel_features(&mut self.funding, fee_estimator)?; Ok(self.get_open_channel_v2(chain_hash)) } + #[rustfmt::skip] pub fn get_open_channel_v2(&self, chain_hash: ChainHash) -> msgs::OpenChannelV2 { if !self.funding.is_outbound() { debug_assert!(false, "Tried to send open_channel2 for an inbound channel?"); @@ -10468,6 +10816,7 @@ impl PendingV2Channel where SP::Target: SignerProvider { /// Assumes chain_hash has already been checked and corresponds with what we expect! /// TODO(dual_funding): Allow contributions, pass intended amount and inputs #[allow(dead_code)] // TODO(dual_funding): Remove once V2 channels is enabled. + #[rustfmt::skip] pub fn new_inbound( fee_estimator: &LowerBoundedFeeEstimator, entropy_source: &ES, signer_provider: &SP, holder_node_id: PublicKey, counterparty_node_id: PublicKey, our_supported_features: &ChannelTypeFeatures, @@ -10575,6 +10924,7 @@ impl PendingV2Channel where SP::Target: SignerProvider { /// /// [`msgs::AcceptChannelV2`]: crate::ln::msgs::AcceptChannelV2 #[allow(dead_code)] // TODO(dual_funding): Remove once V2 channels is enabled. + #[rustfmt::skip] pub fn accept_inbound_dual_funded_channel(&self) -> msgs::AcceptChannelV2 { if self.funding.is_outbound() { debug_assert!(false, "Tried to send accept_channel for an outbound channel?"); @@ -10647,6 +10997,7 @@ impl PendingV2Channel where SP::Target: SignerProvider { // Unfunded channel utilities +#[rustfmt::skip] fn get_initial_channel_type(config: &UserConfig, their_features: &InitFeatures) -> ChannelTypeFeatures { // The default channel type (ie the first one we try) depends on whether the channel is // public - if it is, we just go with `only_static_remotekey` as it's the only option @@ -10673,7 +11024,6 @@ fn get_initial_channel_type(config: &UserConfig, their_features: &InitFeatures) const SERIALIZATION_VERSION: u8 = 4; const MIN_SERIALIZATION_VERSION: u8 = 4; - impl Writeable for ChannelUpdateStatus { fn write(&self, writer: &mut W) -> Result<(), io::Error> { // We only care about writing out the current state as it was announced, ie only either @@ -10722,7 +11072,11 @@ impl Readable for AnnouncementSigsState { } } -impl Writeable for FundedChannel where SP::Target: SignerProvider { +impl Writeable for FundedChannel +where + SP::Target: SignerProvider, +{ + #[rustfmt::skip] fn write(&self, writer: &mut W) -> Result<(), io::Error> { // Note that we write out as if remove_uncommitted_htlcs_and_mark_paused had just been // called. @@ -11101,11 +11455,13 @@ impl Writeable for FundedChannel where SP::Target: SignerProvider } } -impl<'a, 'b, 'c, ES: Deref, SP: Deref> ReadableArgs<(&'a ES, &'b SP, &'c ChannelTypeFeatures)> for FundedChannel - where - ES::Target: EntropySource, - SP::Target: SignerProvider +impl<'a, 'b, 'c, ES: Deref, SP: Deref> ReadableArgs<(&'a ES, &'b SP, &'c ChannelTypeFeatures)> + for FundedChannel +where + ES::Target: EntropySource, + SP::Target: SignerProvider, { + #[rustfmt::skip] fn read(reader: &mut R, args: (&'a ES, &'b SP, &'c ChannelTypeFeatures)) -> Result { let (entropy_source, signer_provider, our_supported_features) = args; let ver = read_ver_prefix!(reader, SERIALIZATION_VERSION); @@ -11746,6 +12102,7 @@ impl<'a, 'b, 'c, ES: Deref, SP: Deref> ReadableArgs<(&'a ES, &'b SP, &'c Channel } } +#[rustfmt::skip] fn duration_since_epoch() -> Option { #[cfg(not(feature = "std"))] let now = None; @@ -11760,50 +12117,60 @@ fn duration_since_epoch() -> Option { #[cfg(test)] mod tests { - use std::cmp; - use bitcoin::amount::Amount; - use bitcoin::constants::ChainHash; - use bitcoin::script::{ScriptBuf, Builder}; - use bitcoin::transaction::{Transaction, TxOut, Version}; - #[cfg(splicing)] - use bitcoin::transaction::TxIn; - use bitcoin::opcodes; - use bitcoin::network::Network; - #[cfg(splicing)] - use bitcoin::Weight; - use crate::ln::onion_utils::{AttributionData, LocalHTLCFailureReason}; - use crate::types::payment::{PaymentHash, PaymentPreimage}; - use crate::ln::channel_keys::{RevocationKey, RevocationBasepoint}; - use crate::ln::channelmanager::{self, HTLCSource, PaymentId}; + use crate::chain::chaininterface::{ + ConfirmationTarget, FeeEstimator, LowerBoundedFeeEstimator, + }; + use crate::chain::transaction::OutPoint; + use crate::chain::BestBlock; + use crate::ln::chan_utils::{self, htlc_success_tx_weight, htlc_timeout_tx_weight}; use crate::ln::channel::InitFeatures; - use crate::ln::channel::{AwaitingChannelReadyFlags, ChannelState, FundedChannel, InboundHTLCOutput, OutboundV1Channel, InboundV1Channel, OutboundHTLCOutput, InboundHTLCState, OutboundHTLCState, HTLCCandidate, HTLCInitiator, HTLCUpdateAwaitingACK, commit_tx_fee_sat}; - use crate::ln::channel::{MAX_FUNDING_SATOSHIS_NO_WUMBO, TOTAL_BITCOIN_SUPPLY_SATOSHIS, MIN_THEIR_CHAN_RESERVE_SATOSHIS}; - use crate::types::features::{ChannelFeatures, ChannelTypeFeatures, NodeFeatures}; + use crate::ln::channel::{ + commit_tx_fee_sat, AwaitingChannelReadyFlags, ChannelState, FundedChannel, HTLCCandidate, + HTLCInitiator, HTLCUpdateAwaitingACK, InboundHTLCOutput, InboundHTLCState, + InboundV1Channel, OutboundHTLCOutput, OutboundHTLCState, OutboundV1Channel, + }; + use crate::ln::channel::{ + MAX_FUNDING_SATOSHIS_NO_WUMBO, MIN_THEIR_CHAN_RESERVE_SATOSHIS, + TOTAL_BITCOIN_SUPPLY_SATOSHIS, + }; + use crate::ln::channel_keys::{RevocationBasepoint, RevocationKey}; + use crate::ln::channelmanager::{self, HTLCSource, PaymentId}; use crate::ln::msgs; use crate::ln::msgs::{ChannelUpdate, UnsignedChannelUpdate, MAX_VALUE_MSAT}; + use crate::ln::onion_utils::{AttributionData, LocalHTLCFailureReason}; use crate::ln::script::ShutdownScript; - use crate::ln::chan_utils::{self, htlc_success_tx_weight, htlc_timeout_tx_weight}; - use crate::chain::BestBlock; - use crate::chain::chaininterface::{FeeEstimator, LowerBoundedFeeEstimator, ConfirmationTarget}; - use crate::sign::{ChannelSigner, InMemorySigner, EntropySource, SignerProvider}; - use crate::chain::transaction::OutPoint; + use crate::prelude::*; use crate::routing::router::{Path, RouteHop}; + use crate::sign::{ChannelSigner, EntropySource, InMemorySigner, SignerProvider}; + use crate::types::features::{ChannelFeatures, ChannelTypeFeatures, NodeFeatures}; + use crate::types::payment::{PaymentHash, PaymentPreimage}; use crate::util::config::UserConfig; use crate::util::errors::APIError; use crate::util::ser::{ReadableArgs, Writeable}; use crate::util::test_utils; use crate::util::test_utils::{OnGetShutdownScriptpubkey, TestKeysInterface}; - use bitcoin::secp256k1::{Secp256k1, ecdsa::Signature}; - use bitcoin::secp256k1::ffi::Signature as FFISignature; - use bitcoin::secp256k1::{SecretKey,PublicKey}; + use bitcoin::amount::Amount; + use bitcoin::constants::ChainHash; use bitcoin::hashes::sha256::Hash as Sha256; use bitcoin::hashes::Hash; use bitcoin::hex::FromHex; use bitcoin::locktime::absolute::LockTime; - use bitcoin::{WitnessProgram, WitnessVersion, WPubkeyHash}; - use crate::prelude::*; + use bitcoin::network::Network; + use bitcoin::opcodes; + use bitcoin::script::{Builder, ScriptBuf}; + use bitcoin::secp256k1::ffi::Signature as FFISignature; + use bitcoin::secp256k1::{ecdsa::Signature, Secp256k1}; + use bitcoin::secp256k1::{PublicKey, SecretKey}; + #[cfg(splicing)] + use bitcoin::transaction::TxIn; + use bitcoin::transaction::{Transaction, TxOut, Version}; + #[cfg(splicing)] + use bitcoin::Weight; + use bitcoin::{WPubkeyHash, WitnessProgram, WitnessVersion}; + use std::cmp; #[test] + #[rustfmt::skip] fn test_channel_state_order() { use crate::ln::channel::NegotiatingFundingFlags; use crate::ln::channel::FundingNegotiatedFlags; @@ -11817,7 +12184,7 @@ mod tests { } struct TestFeeEstimator { - fee_est: u32 + fee_est: u32, } impl FeeEstimator for TestFeeEstimator { fn get_est_sat_per_1000_weight(&self, _: ConfirmationTarget) -> u32 { @@ -11826,6 +12193,7 @@ mod tests { } #[test] + #[rustfmt::skip] fn test_max_funding_satoshis_no_wumbo() { assert_eq!(TOTAL_BITCOIN_SUPPLY_SATOSHIS, 21_000_000 * 100_000_000); assert!(MAX_FUNDING_SATOSHIS_NO_WUMBO <= TOTAL_BITCOIN_SUPPLY_SATOSHIS, @@ -11837,6 +12205,7 @@ mod tests { } impl EntropySource for Keys { + #[rustfmt::skip] fn get_secure_random_bytes(&self) -> [u8; 32] { [0; 32] } } @@ -11853,6 +12222,7 @@ mod tests { self.signer.clone() } + #[rustfmt::skip] fn get_destination_script(&self, _channel_keys_id: [u8; 32]) -> Result { let secp_ctx = Secp256k1::signing_only(); let channel_monitor_claim_key = SecretKey::from_slice(&>::from_hex("0fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff").unwrap()[..]).unwrap(); @@ -11860,6 +12230,7 @@ mod tests { Ok(Builder::new().push_opcode(opcodes::all::OP_PUSHBYTES_0).push_slice(channel_monitor_claim_key_hash).into_script()) } + #[rustfmt::skip] fn get_shutdown_scriptpubkey(&self) -> Result { let secp_ctx = Secp256k1::signing_only(); let channel_close_key = SecretKey::from_slice(&>::from_hex("0fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff").unwrap()[..]).unwrap(); @@ -11868,12 +12239,14 @@ mod tests { } #[cfg(ldk_test_vectors)] + #[rustfmt::skip] fn public_from_secret_hex(secp_ctx: &Secp256k1, hex: &str) -> PublicKey { assert!(cfg!(not(feature = "grind_signatures"))); PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&>::from_hex(hex).unwrap()[..]).unwrap()) } #[test] + #[rustfmt::skip] fn upfront_shutdown_script_incompatibility() { let mut features = channelmanager::provided_init_features(&UserConfig::default()); features.clear_shutdown_anysegwit(); @@ -11904,6 +12277,7 @@ mod tests { // Check that, during channel creation, we use the same feerate in the open channel message // as we do in the Channel object creation itself. #[test] + #[rustfmt::skip] fn test_open_channel_msg_fee() { let original_fee = 253; let mut fee_est = TestFeeEstimator{fee_est: original_fee }; @@ -11926,6 +12300,7 @@ mod tests { } #[test] + #[rustfmt::skip] fn test_holder_vs_counterparty_dust_limit() { // Test that when calculating the local and remote commitment transaction fees, the correct // dust limits are used. @@ -12015,6 +12390,7 @@ mod tests { } #[test] + #[rustfmt::skip] fn test_timeout_vs_success_htlc_dust_limit() { // Make sure that when `next_remote_commit_tx_fee_msat` and `next_local_commit_tx_fee_msat` // calculate the real dust limits for HTLCs (i.e. the dust limit given by the counterparty @@ -12063,6 +12439,7 @@ mod tests { } #[test] + #[rustfmt::skip] fn channel_reestablish_no_updates() { let feeest = LowerBoundedFeeEstimator::new(&TestFeeEstimator{fee_est: 15000}); let logger = test_utils::TestLogger::new(); @@ -12120,6 +12497,7 @@ mod tests { } #[test] + #[rustfmt::skip] fn test_configured_holder_max_htlc_value_in_flight() { let feeest = LowerBoundedFeeEstimator::new(&TestFeeEstimator{fee_est: 15000}); let logger = test_utils::TestLogger::new(); @@ -12193,6 +12571,7 @@ mod tests { } #[test] + #[rustfmt::skip] fn test_configured_holder_selected_channel_reserve_satoshis() { // Test that `OutboundV1Channel::new` and `InboundV1Channel::new` create a channel with the correct @@ -12214,6 +12593,7 @@ mod tests { test_self_and_counterparty_channel_reserve(10_000_000, 0.60, 0.50); } + #[rustfmt::skip] fn test_self_and_counterparty_channel_reserve(channel_value_satoshis: u64, outbound_selected_channel_reserve_perc: f64, inbound_selected_channel_reserve_perc: f64) { let fee_est = LowerBoundedFeeEstimator::new(&TestFeeEstimator { fee_est: 15_000 }); let logger = test_utils::TestLogger::new(); @@ -12251,6 +12631,7 @@ mod tests { } #[test] + #[rustfmt::skip] fn channel_update() { let feeest = LowerBoundedFeeEstimator::new(&TestFeeEstimator{fee_est: 15000}); let logger = test_utils::TestLogger::new(); @@ -12326,6 +12707,7 @@ mod tests { } #[test] + #[rustfmt::skip] fn blinding_point_skimmed_fee_malformed_ser() { // Ensure that channel blinding points, skimmed fees, and malformed HTLCs are (de)serialized // properly. @@ -12454,6 +12836,7 @@ mod tests { #[cfg(ldk_test_vectors)] #[test] + #[rustfmt::skip] fn outbound_commitment_test() { assert!(cfg!(not(feature = "grind_signatures"))); @@ -12549,6 +12932,7 @@ mod tests { }; } + #[rustfmt::skip] macro_rules! test_commitment_common { ( $counterparty_sig_hex: expr, $sig_hex: expr, $tx_hex: expr, $channel_type_features: expr, { $( { $htlc_idx: expr, $counterparty_htlc_sig_hex: expr, $htlc_sig_hex: expr, $htlc_tx_hex: expr } ), * @@ -13186,6 +13570,7 @@ mod tests { } #[test] + #[rustfmt::skip] fn test_per_commitment_secret_gen() { // Test vectors from BOLT 3 Appendix D: @@ -13210,6 +13595,7 @@ mod tests { } #[test] + #[rustfmt::skip] fn test_key_derivation() { // Test vectors from BOLT 3 Appendix E: let secp_ctx = Secp256k1::new(); @@ -13234,6 +13620,7 @@ mod tests { } #[test] + #[rustfmt::skip] fn test_zero_conf_channel_type_support() { let feeest = LowerBoundedFeeEstimator::new(&TestFeeEstimator{fee_est: 15000}); let secp_ctx = Secp256k1::new(); @@ -13260,6 +13647,7 @@ mod tests { } #[test] + #[rustfmt::skip] fn test_supports_anchors_zero_htlc_tx_fee() { // Tests that if both sides support and negotiate `anchors_zero_fee_htlc_tx`, it is the // resulting `channel_type`. @@ -13306,6 +13694,7 @@ mod tests { } #[test] + #[rustfmt::skip] fn test_rejects_implicit_simple_anchors() { // Tests that if `option_anchors` is being negotiated implicitly through the intersection of // each side's `InitFeatures`, it is rejected. @@ -13347,6 +13736,7 @@ mod tests { } #[test] + #[rustfmt::skip] fn test_rejects_simple_anchors_channel_type() { // Tests that if `option_anchors` is being negotiated through the `channel_type` feature, // it is rejected. @@ -13416,6 +13806,7 @@ mod tests { } #[test] + #[rustfmt::skip] fn test_waiting_for_batch() { let feeest = LowerBoundedFeeEstimator::new(&TestFeeEstimator{fee_est: 15000}); let logger = test_utils::TestLogger::new(); @@ -13545,6 +13936,7 @@ mod tests { } #[test] + #[rustfmt::skip] fn test_estimate_v2_funding_transaction_fee() { use crate::ln::channel::estimate_v2_funding_transaction_fee; use bitcoin::Weight; @@ -13581,6 +13973,7 @@ mod tests { } #[cfg(splicing)] + #[rustfmt::skip] fn funding_input_sats(input_value_sats: u64) -> (TxIn, Transaction, Weight) { use crate::sign::P2WPKH_WITNESS_WEIGHT; @@ -13598,6 +13991,7 @@ mod tests { #[cfg(splicing)] #[test] + #[rustfmt::skip] fn test_check_v2_funding_inputs_sufficient() { use crate::ln::channel::check_v2_funding_inputs_sufficient; diff --git a/lightning/src/ln/channelmanager.rs b/lightning/src/ln/channelmanager.rs index dbd25de3bd8..9c1f89db29d 100644 --- a/lightning/src/ln/channelmanager.rs +++ b/lightning/src/ln/channelmanager.rs @@ -1,5 +1,3 @@ -#![cfg_attr(rustfmt, rustfmt_skip)] - // This file is Copyright its original authors, visible in version control // history. // @@ -20,54 +18,78 @@ //! imply it needs to fail HTLCs/payments/channels it manages). use bitcoin::block::Header; -use bitcoin::transaction::Transaction; use bitcoin::constants::ChainHash; use bitcoin::key::constants::SECRET_KEY_SIZE; use bitcoin::network::Network; +use bitcoin::transaction::Transaction; -use bitcoin::hashes::{Hash, HashEngine, HmacEngine}; +use bitcoin::hash_types::{BlockHash, Txid}; use bitcoin::hashes::hmac::Hmac; use bitcoin::hashes::sha256::Hash as Sha256; -use bitcoin::hash_types::{BlockHash, Txid}; +use bitcoin::hashes::{Hash, HashEngine, HmacEngine}; -use bitcoin::secp256k1::{SecretKey,PublicKey}; use bitcoin::secp256k1::Secp256k1; +use bitcoin::secp256k1::{PublicKey, SecretKey}; use bitcoin::{secp256k1, Sequence}; #[cfg(splicing)] use bitcoin::{TxIn, Weight}; -use crate::events::{FundingInfo, PaidBolt12Invoice}; use crate::blinded_path::message::{AsyncPaymentsContext, MessageContext, OffersContext}; -use crate::blinded_path::NodeIdLookUp; use crate::blinded_path::message::{BlindedMessagePath, MessageForwardNode}; -use crate::blinded_path::payment::{AsyncBolt12OfferContext, BlindedPaymentPath, Bolt12OfferContext, Bolt12RefundContext, PaymentConstraints, PaymentContext, UnauthenticatedReceiveTlvs}; +use crate::blinded_path::payment::{ + AsyncBolt12OfferContext, BlindedPaymentPath, Bolt12OfferContext, Bolt12RefundContext, + PaymentConstraints, PaymentContext, UnauthenticatedReceiveTlvs, +}; +use crate::blinded_path::NodeIdLookUp; use crate::chain; -use crate::chain::{Confirm, ChannelMonitorUpdateStatus, Watch, BestBlock}; -use crate::chain::chaininterface::{BroadcasterInterface, ConfirmationTarget, FeeEstimator, LowerBoundedFeeEstimator}; -use crate::chain::channelmonitor::{Balance, ChannelMonitor, ChannelMonitorUpdate, WithChannelMonitor, ChannelMonitorUpdateStep, HTLC_FAIL_BACK_BUFFER, MAX_BLOCKS_FOR_CONF, CLTV_CLAIM_BUFFER, LATENCY_GRACE_PERIOD_BLOCKS, ANTI_REORG_DELAY, MonitorEvent}; +use crate::chain::chaininterface::{ + BroadcasterInterface, ConfirmationTarget, FeeEstimator, LowerBoundedFeeEstimator, +}; +use crate::chain::channelmonitor::{ + Balance, ChannelMonitor, ChannelMonitorUpdate, ChannelMonitorUpdateStep, MonitorEvent, + WithChannelMonitor, ANTI_REORG_DELAY, CLTV_CLAIM_BUFFER, HTLC_FAIL_BACK_BUFFER, + LATENCY_GRACE_PERIOD_BLOCKS, MAX_BLOCKS_FOR_CONF, +}; use crate::chain::transaction::{OutPoint, TransactionData}; -use crate::events::{self, Event, EventHandler, EventsProvider, InboundChannelFunds, ClosureReason, HTLCHandlingFailureType, PaymentFailureReason, ReplayEvent}; +use crate::chain::{BestBlock, ChannelMonitorUpdateStatus, Confirm, Watch}; +use crate::events::{ + self, ClosureReason, Event, EventHandler, EventsProvider, HTLCHandlingFailureType, + InboundChannelFunds, PaymentFailureReason, ReplayEvent, +}; +use crate::events::{FundingInfo, PaidBolt12Invoice}; // Since this struct is returned in `list_channels` methods, expose it here in case users want to // construct one themselves. -use crate::ln::inbound_payment; -use crate::ln::types::ChannelId; -use crate::types::payment::{PaymentHash, PaymentPreimage, PaymentSecret}; -use crate::ln::channel::{self, Channel, ChannelError, ChannelUpdateStatus, FundedChannel, ShutdownResult, UpdateFulfillCommitFetch, OutboundV1Channel, ReconnectionMsg, InboundV1Channel, WithChannelContext}; use crate::ln::channel::PendingV2Channel; +use crate::ln::channel::{ + self, Channel, ChannelError, ChannelUpdateStatus, FundedChannel, InboundV1Channel, + OutboundV1Channel, ReconnectionMsg, ShutdownResult, UpdateFulfillCommitFetch, + WithChannelContext, +}; use crate::ln::channel_state::ChannelDetails; -use crate::types::features::{Bolt12InvoiceFeatures, ChannelFeatures, ChannelTypeFeatures, InitFeatures, NodeFeatures}; -#[cfg(any(feature = "_test_utils", test))] -use crate::types::features::Bolt11InvoiceFeatures; -use crate::routing::router::{BlindedTail, InFlightHtlcs, Path, Payee, PaymentParameters, RouteParameters, RouteParametersConfig, Router, FixedRouter, Route}; -use crate::ln::onion_payment::{check_incoming_htlc_cltv, create_recv_pending_htlc_info, create_fwd_pending_htlc_info, decode_incoming_update_add_htlc_onion, HopConnector, InboundHTLCErr, NextPacketDetails, invalid_payment_err_data}; +use crate::ln::inbound_payment; use crate::ln::msgs; +use crate::ln::msgs::{ + BaseMessageHandler, ChannelMessageHandler, CommitmentUpdate, DecodeError, LightningError, + MessageSendEvent, +}; +use crate::ln::onion_payment::{ + check_incoming_htlc_cltv, create_fwd_pending_htlc_info, create_recv_pending_htlc_info, + decode_incoming_update_add_htlc_onion, invalid_payment_err_data, HopConnector, InboundHTLCErr, + NextPacketDetails, +}; use crate::ln::onion_utils::{self}; use crate::ln::onion_utils::{HTLCFailReason, LocalHTLCFailureReason}; -use crate::ln::msgs::{BaseMessageHandler, ChannelMessageHandler, CommitmentUpdate, DecodeError, LightningError, MessageSendEvent}; #[cfg(test)] use crate::ln::outbound_payment; -use crate::ln::outbound_payment::{Bolt11PaymentError, OutboundPayments, PendingOutboundPayment, RetryableInvoiceRequest, SendAlongPathArgs, StaleExpiration}; -use crate::offers::invoice::{Bolt12Invoice, DEFAULT_RELATIVE_EXPIRY, DerivedSigningPubkey, ExplicitSigningPubkey, InvoiceBuilder, UnsignedBolt12Invoice}; +use crate::ln::outbound_payment::{ + Bolt11PaymentError, OutboundPayments, PendingOutboundPayment, RetryableInvoiceRequest, + SendAlongPathArgs, StaleExpiration, +}; +use crate::ln::types::ChannelId; +use crate::offers::invoice::{ + Bolt12Invoice, DerivedSigningPubkey, ExplicitSigningPubkey, InvoiceBuilder, + UnsignedBolt12Invoice, DEFAULT_RELATIVE_EXPIRY, +}; use crate::offers::invoice_error::InvoiceError; use crate::offers::invoice_request::{InvoiceRequest, InvoiceRequestBuilder}; use crate::offers::nonce::Nonce; @@ -75,37 +97,60 @@ use crate::offers::offer::{Offer, OfferBuilder}; use crate::offers::parse::Bolt12SemanticError; use crate::offers::refund::{Refund, RefundBuilder}; use crate::offers::signer; -use crate::onion_message::async_payments::{AsyncPaymentsMessage, HeldHtlcAvailable, ReleaseHeldHtlc, AsyncPaymentsMessageHandler}; +use crate::onion_message::async_payments::{ + AsyncPaymentsMessage, AsyncPaymentsMessageHandler, HeldHtlcAvailable, ReleaseHeldHtlc, +}; use crate::onion_message::dns_resolution::HumanReadableName; -use crate::onion_message::messenger::{Destination, MessageRouter, Responder, ResponseInstruction, MessageSendInstructions}; +use crate::onion_message::messenger::{ + Destination, MessageRouter, MessageSendInstructions, Responder, ResponseInstruction, +}; use crate::onion_message::offers::{OffersMessage, OffersMessageHandler}; use crate::onion_message::packet::OnionMessageContents; -use crate::sign::{EntropySource, NodeSigner, Recipient, SignerProvider}; +use crate::routing::router::{ + BlindedTail, FixedRouter, InFlightHtlcs, Path, Payee, PaymentParameters, Route, + RouteParameters, RouteParametersConfig, Router, +}; use crate::sign::ecdsa::EcdsaChannelSigner; -use crate::util::config::{ChannelConfig, ChannelConfigUpdate, ChannelConfigOverrides, UserConfig}; -use crate::util::wakers::{Future, Notifier}; +use crate::sign::{EntropySource, NodeSigner, Recipient, SignerProvider}; +#[cfg(any(feature = "_test_utils", test))] +use crate::types::features::Bolt11InvoiceFeatures; +use crate::types::features::{ + Bolt12InvoiceFeatures, ChannelFeatures, ChannelTypeFeatures, InitFeatures, NodeFeatures, +}; +use crate::types::payment::{PaymentHash, PaymentPreimage, PaymentSecret}; +use crate::util::config::{ChannelConfig, ChannelConfigOverrides, ChannelConfigUpdate, UserConfig}; +use crate::util::errors::APIError; +use crate::util::logger::{Level, Logger, WithContext}; use crate::util::scid_utils::fake_scid; +use crate::util::ser::{ + BigSize, FixedLengthReader, LengthReadable, MaybeReadable, Readable, ReadableArgs, VecWriter, + Writeable, Writer, +}; use crate::util::string::UntrustedString; -use crate::util::ser::{BigSize, FixedLengthReader, LengthReadable, Readable, ReadableArgs, MaybeReadable, Writeable, Writer, VecWriter}; -use crate::util::logger::{Level, Logger, WithContext}; -use crate::util::errors::APIError; +use crate::util::wakers::{Future, Notifier}; -#[cfg(async_payments)] use { +#[cfg(async_payments)] +use { crate::offers::offer::Amount, - crate::offers::static_invoice::{DEFAULT_RELATIVE_EXPIRY as STATIC_INVOICE_DEFAULT_RELATIVE_EXPIRY, StaticInvoice, StaticInvoiceBuilder}, + crate::offers::static_invoice::{ + StaticInvoice, StaticInvoiceBuilder, + DEFAULT_RELATIVE_EXPIRY as STATIC_INVOICE_DEFAULT_RELATIVE_EXPIRY, + }, }; #[cfg(feature = "dnssec")] use crate::blinded_path::message::DNSResolverContext; #[cfg(feature = "dnssec")] -use crate::onion_message::dns_resolution::{DNSResolverMessage, DNSResolverMessageHandler, DNSSECQuery, DNSSECProof, OMNameResolver}; +use crate::onion_message::dns_resolution::{ + DNSResolverMessage, DNSResolverMessageHandler, DNSSECProof, DNSSECQuery, OMNameResolver, +}; #[cfg(not(c_bindings))] use { crate::offers::offer::DerivedMetadata, crate::onion_message::messenger::DefaultMessageRouter, - crate::routing::router::DefaultRouter, crate::routing::gossip::NetworkGraph, + crate::routing::router::DefaultRouter, crate::routing::scoring::{ProbabilisticScorer, ProbabilisticScoringFeeParameters}, crate::sign::KeysManager, }; @@ -115,25 +160,30 @@ use { crate::offers::refund::RefundMaybeWithDerivedMetadataBuilder, }; -use lightning_invoice::{Bolt11Invoice, Bolt11InvoiceDescription, CreationError, Currency, Description, InvoiceBuilder as Bolt11InvoiceBuilder, SignOrCreationError, DEFAULT_EXPIRY_TIME}; +use lightning_invoice::{ + Bolt11Invoice, Bolt11InvoiceDescription, CreationError, Currency, Description, + InvoiceBuilder as Bolt11InvoiceBuilder, SignOrCreationError, DEFAULT_EXPIRY_TIME, +}; use alloc::collections::{btree_map, BTreeMap}; use crate::io; +use crate::io::Read; use crate::prelude::*; -use core::{cmp, mem}; +use crate::sync::{Arc, FairRwLock, LockHeldState, LockTestExt, Mutex, RwLock, RwLockReadGuard}; +use bitcoin::hex::impl_fmt_traits; use core::borrow::Borrow; use core::cell::RefCell; -use crate::io::Read; -use crate::sync::{Arc, Mutex, RwLock, RwLockReadGuard, FairRwLock, LockTestExt, LockHeldState}; -use core::sync::atomic::{AtomicUsize, AtomicBool, Ordering}; -use core::time::Duration; use core::ops::Deref; -use bitcoin::hex::impl_fmt_traits; +use core::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; +use core::time::Duration; +use core::{cmp, mem}; // Re-export this for use in the public API. -pub use crate::ln::outbound_payment::{Bolt12PaymentError, ProbeSendFailure, Retry, RetryableSendFailure, RecipientOnionFields}; #[cfg(any(test, feature = "_externalize_tests"))] pub(crate) use crate::ln::outbound_payment::PaymentSendFailure; +pub use crate::ln::outbound_payment::{ + Bolt12PaymentError, ProbeSendFailure, RecipientOnionFields, Retry, RetryableSendFailure, +}; use crate::ln::script::ShutdownScript; // We hold various information about HTLC relay in the HTLC objects in Channel itself: @@ -288,6 +338,7 @@ pub struct BlindedForward { impl PendingHTLCRouting { // Used to override the onion failure code and data if the HTLC is blinded. + #[rustfmt::skip] fn blinded_failure(&self) -> Option { match self { Self::Forward { blinded: Some(BlindedForward { failure, .. }), .. } => Some(*failure), @@ -387,15 +438,8 @@ pub(super) struct PendingAddHTLCInfo { #[cfg_attr(test, derive(Clone, Debug, PartialEq))] pub(super) enum HTLCForwardInfo { AddHTLC(PendingAddHTLCInfo), - FailHTLC { - htlc_id: u64, - err_packet: msgs::OnionErrorPacket, - }, - FailMalformedHTLC { - htlc_id: u64, - failure_code: u16, - sha256_of_onion: [u8; 32], - }, + FailHTLC { htlc_id: u64, err_packet: msgs::OnionErrorPacket }, + FailMalformedHTLC { htlc_id: u64, failure_code: u16, sha256_of_onion: [u8; 32] }, } /// Whether this blinded HTLC is being failed backwards by the introduction node or a blinded node, @@ -462,6 +506,7 @@ impl PartialOrd for ClaimableHTLC { } } impl Ord for ClaimableHTLC { + #[rustfmt::skip] fn cmp(&self, other: &ClaimableHTLC) -> cmp::Ordering { let res = (self.prev_hop.channel_id, self.prev_hop.htlc_id).cmp( &(other.prev_hop.channel_id, other.prev_hop.htlc_id) @@ -568,7 +613,9 @@ impl Verification for PaymentId { } impl PaymentId { - fn for_inbound_from_htlcs>(key: &[u8; 32], htlcs: I) -> PaymentId { + fn for_inbound_from_htlcs>( + key: &[u8; 32], htlcs: I, + ) -> PaymentId { let mut prev_pair = None; let mut hasher = HmacEngine::new(key); for (channel_id, htlc_id) in htlcs { @@ -634,6 +681,7 @@ pub(crate) enum SentHTLCId { OutboundRoute { session_priv: [u8; SECRET_KEY_SIZE] }, } impl SentHTLCId { + #[rustfmt::skip] pub(crate) fn from_source(source: &HTLCSource) -> Self { match source { HTLCSource::PreviousHopData(hop_data) => Self::PreviousHopData { @@ -705,6 +753,7 @@ pub(crate) use self::fuzzy_channelmanager::*; #[allow(clippy::derive_hash_xor_eq)] // Our Hash is faithful to the data, we just don't have SecretKey::hash impl core::hash::Hash for HTLCSource { + #[rustfmt::skip] fn hash(&self, hasher: &mut H) { match self { HTLCSource::PreviousHopData(prev_hop_data) => { @@ -736,7 +785,9 @@ impl HTLCSource { /// Checks whether this HTLCSource could possibly match the given HTLC output in a commitment /// transaction. Useful to ensure different datastructures match up. - pub(crate) fn possibly_matches_output(&self, htlc: &super::chan_utils::HTLCOutputInCommitment) -> bool { + pub(crate) fn possibly_matches_output( + &self, htlc: &super::chan_utils::HTLCOutputInCommitment, + ) -> bool { if let HTLCSource::OutboundRoute { first_hop_htlc_msat, .. } = self { *first_hop_htlc_msat == htlc.amount_msat } else { @@ -781,6 +832,7 @@ pub enum FailureCode { } impl Into for FailureCode { + #[rustfmt::skip] fn into(self) -> LocalHTLCFailureReason { match self { FailureCode::TemporaryNodeFailure => LocalHTLCFailureReason::TemporaryNodeFailure, @@ -803,6 +855,7 @@ struct MsgHandleErrInternal { } impl MsgHandleErrInternal { #[inline] + #[rustfmt::skip] fn send_err_msg_no_close(err: String, channel_id: ChannelId) -> Self { Self { err: LightningError { @@ -823,7 +876,10 @@ impl MsgHandleErrInternal { Self { err, closes_channel: false, shutdown_finish: None } } #[inline] - fn from_finish_shutdown(err: String, channel_id: ChannelId, shutdown_res: ShutdownResult, channel_update: Option) -> Self { + fn from_finish_shutdown( + err: String, channel_id: ChannelId, shutdown_res: ShutdownResult, + channel_update: Option, + ) -> Self { let err_msg = msgs::ErrorMessage { channel_id, data: err.clone() }; let action = if shutdown_res.monitor_update.is_some() { // We have a closing `ChannelMonitorUpdate`, which means the channel was funded and we @@ -840,6 +896,7 @@ impl MsgHandleErrInternal { } } #[inline] + #[rustfmt::skip] fn from_chan_no_close(err: ChannelError, channel_id: ChannelId) -> Self { Self { err: match err { @@ -932,6 +989,7 @@ struct ClaimablePayment { } impl ClaimablePayment { + #[rustfmt::skip] fn inbound_payment_id(&self, secret: &[u8; 32]) -> PaymentId { PaymentId::for_inbound_from_htlcs( secret, @@ -942,6 +1000,7 @@ impl ClaimablePayment { /// Returns the inbound `(channel_id, user_channel_id)` pairs for all HTLCs associated with the payment. /// /// Note: The `user_channel_id` will be `None` for HTLCs created using LDK version 0.0.117 or prior. + #[rustfmt::skip] fn via_channel_ids(&self) -> Vec<(ChannelId, Option)> { self.htlcs.iter().map(|htlc| { (htlc.prev_hop.channel_id, htlc.prev_hop.user_channel_id) @@ -1023,6 +1082,7 @@ impl ClaimablePayments { /// If `custom_tlvs_known` is true, and a matching payment is found, it will always be moved. /// /// If no payment is found, `Err(Vec::new())` is returned. + #[rustfmt::skip] fn begin_claiming_payment( &mut self, payment_hash: PaymentHash, node_signer: &S, logger: &L, inbound_payment_id_secret: &[u8; 32], custom_tlvs_known: bool, @@ -1097,15 +1157,12 @@ enum BackgroundEvent { counterparty_node_id: PublicKey, funding_txo: OutPoint, channel_id: ChannelId, - update: ChannelMonitorUpdate + update: ChannelMonitorUpdate, }, /// Some [`ChannelMonitorUpdate`] (s) completed before we were serialized but we still have /// them marked pending, thus we need to run any [`MonitorUpdateCompletionAction`] (s) pending /// on a channel. - MonitorUpdatesComplete { - counterparty_node_id: PublicKey, - channel_id: ChannelId, - }, + MonitorUpdatesComplete { counterparty_node_id: PublicKey, channel_id: ChannelId }, } /// A pointer to a channel that is unblocked when an event is surfaced @@ -1302,6 +1359,7 @@ impl_writeable_tlv_based!(PaymentClaimDetails, { pub(crate) struct PendingMPPClaimPointer(Arc>); impl PartialEq for PendingMPPClaimPointer { + #[rustfmt::skip] fn eq(&self, o: &Self) -> bool { Arc::ptr_eq(&self.0, &o.0) } } impl Eq for PendingMPPClaimPointer {} @@ -1332,9 +1390,7 @@ pub(crate) enum RAAMonitorUpdateBlockingAction { /// /// This variant is *not* written to disk, instead being inferred from [`ChannelMonitor`] /// state. - ClaimedMPPPayment { - pending_claim: PendingMPPClaimPointer, - } + ClaimedMPPPayment { pending_claim: PendingMPPClaimPointer }, } impl RAAMonitorUpdateBlockingAction { @@ -1358,7 +1414,10 @@ impl Readable for Option { } /// State we hold per-peer. -pub(super) struct PeerState where SP::Target: SignerProvider { +pub(super) struct PeerState +where + SP::Target: SignerProvider, +{ /// `channel_id` -> `Channel` /// /// Holds all channels where the peer is the counterparty. @@ -1426,10 +1485,14 @@ pub(super) struct PeerState where SP::Target: SignerProvider { peer_storage: Vec, } -impl PeerState where SP::Target: SignerProvider { +impl PeerState +where + SP::Target: SignerProvider, +{ /// Indicates that a peer meets the criteria where we're ok to remove it from our storage. /// If true is passed for `require_disconnected`, the function will return false if we haven't /// disconnected from the node already, ie. `PeerState::is_connected` is set to `true`. + #[rustfmt::skip] fn ok_to_remove(&self, require_disconnected: bool) -> bool { if require_disconnected && self.is_connected { return false @@ -1450,6 +1513,7 @@ impl PeerState where SP::Target: SignerProvider { } // Returns a bool indicating if the given `channel_id` matches a channel we have with this peer. + #[rustfmt::skip] fn has_channel(&self, channel_id: &ChannelId) -> bool { self.channel_by_id.contains_key(channel_id) || self.inbound_channel_request_by_id.contains_key(channel_id) @@ -1525,20 +1589,18 @@ pub type SimpleArcChannelManager = ChannelManager< Arc, Arc, Arc, - Arc>>, - Arc, - Arc, - Arc>>, Arc>>>, - ProbabilisticScoringFeeParameters, - ProbabilisticScorer>>, Arc>, - >>, - Arc>>, - Arc, - Arc, - >>, - Arc + Arc< + DefaultRouter< + Arc>>, + Arc, + Arc, + Arc>>, Arc>>>, + ProbabilisticScoringFeeParameters, + ProbabilisticScorer>>, Arc>, + >, + >, + Arc>>, Arc, Arc>>, + Arc, >; /// [`SimpleRefChannelManager`] is a type alias for a ChannelManager reference, and is the reference @@ -1553,29 +1615,24 @@ pub type SimpleArcChannelManager = ChannelManager< /// /// This is not exported to bindings users as type aliases aren't supported in most languages. #[cfg(not(c_bindings))] -pub type SimpleRefChannelManager<'a, 'b, 'c, 'd, 'e, 'f, 'g, 'h, 'i, M, T, F, L> = - ChannelManager< - &'a M, - &'b T, - &'c KeysManager, - &'c KeysManager, +pub type SimpleRefChannelManager<'a, 'b, 'c, 'd, 'e, 'f, 'g, 'h, 'i, M, T, F, L> = ChannelManager< + &'a M, + &'b T, + &'c KeysManager, + &'c KeysManager, + &'c KeysManager, + &'d F, + &'e DefaultRouter< + &'f NetworkGraph<&'g L>, + &'g L, &'c KeysManager, - &'d F, - &'e DefaultRouter< - &'f NetworkGraph<&'g L>, - &'g L, - &'c KeysManager, - &'h RwLock, &'g L>>, - ProbabilisticScoringFeeParameters, - ProbabilisticScorer<&'f NetworkGraph<&'g L>, &'g L> - >, - &'i DefaultMessageRouter< - &'f NetworkGraph<&'g L>, - &'g L, - &'c KeysManager, - >, - &'g L - >; + &'h RwLock, &'g L>>, + ProbabilisticScoringFeeParameters, + ProbabilisticScorer<&'f NetworkGraph<&'g L>, &'g L>, + >, + &'i DefaultMessageRouter<&'f NetworkGraph<&'g L>, &'g L, &'c KeysManager>, + &'g L, +>; /// A trivial trait which describes any [`ChannelManager`]. /// @@ -1601,7 +1658,7 @@ pub trait AChannelManager { /// A type implementing [`EcdsaChannelSigner`]. type Signer: EcdsaChannelSigner + Sized; /// A type implementing [`SignerProvider`] for [`Self::Signer`]. - type SignerProvider: SignerProvider + ?Sized; + type SignerProvider: SignerProvider + ?Sized; /// A type that may be dereferenced to [`Self::SignerProvider`]. type SP: Deref; /// A type implementing [`FeeEstimator`]. @@ -1621,11 +1678,32 @@ pub trait AChannelManager { /// A type that may be dereferenced to [`Self::Logger`]. type L: Deref; /// Returns a reference to the actual [`ChannelManager`] object. - fn get_cm(&self) -> &ChannelManager; + fn get_cm( + &self, + ) -> &ChannelManager< + Self::M, + Self::T, + Self::ES, + Self::NS, + Self::SP, + Self::F, + Self::R, + Self::MR, + Self::L, + >; } -impl AChannelManager -for ChannelManager +impl< + M: Deref, + T: Deref, + ES: Deref, + NS: Deref, + SP: Deref, + F: Deref, + R: Deref, + MR: Deref, + L: Deref, + > AChannelManager for ChannelManager where M::Target: chain::Watch<::EcdsaSigner>, T::Target: BroadcasterInterface, @@ -1656,6 +1734,7 @@ where type MR = MR; type Logger = L::Target; type L = L; + #[rustfmt::skip] fn get_cm(&self) -> &ChannelManager { self } } @@ -2442,8 +2521,17 @@ where // | // |__`pending_background_events` // -pub struct ChannelManager -where +pub struct ChannelManager< + M: Deref, + T: Deref, + ES: Deref, + NS: Deref, + SP: Deref, + F: Deref, + R: Deref, + MR: Deref, + L: Deref, +> where M::Target: chain::Watch<::EcdsaSigner>, T::Target: BroadcasterInterface, ES::Target: EntropySource, @@ -2736,17 +2824,21 @@ struct PersistenceNotifierGuard<'a, F: FnMut() -> NotifyOption> { _read_guard: RwLockReadGuard<'a, ()>, } -impl<'a> PersistenceNotifierGuard<'a, fn() -> NotifyOption> { // We don't care what the concrete F is here, it's unused +impl<'a> PersistenceNotifierGuard<'a, fn() -> NotifyOption> { + // We don't care what the concrete F is here, it's unused /// Notifies any waiters and indicates that we need to persist, in addition to possibly having /// events to handle. /// /// This must always be called if the changes included a `ChannelMonitorUpdate`, as well as in /// other cases where losing the changes on restart may result in a force-close or otherwise /// isn't ideal. - fn notify_on_drop(cm: &'a C) -> PersistenceNotifierGuard<'a, impl FnMut() -> NotifyOption> { + fn notify_on_drop( + cm: &'a C, + ) -> PersistenceNotifierGuard<'a, impl FnMut() -> NotifyOption> { Self::optionally_notify(cm, || -> NotifyOption { NotifyOption::DoPersist }) } + #[rustfmt::skip] fn optionally_notify NotifyOption, C: AChannelManager>(cm: &'a C, mut persist_check: F) -> PersistenceNotifierGuard<'a, impl FnMut() -> NotifyOption> { let read_guard = cm.get_cm().total_consistency_lock.read().unwrap(); @@ -2774,8 +2866,9 @@ impl<'a> PersistenceNotifierGuard<'a, fn() -> NotifyOption> { // We don't care w /// Note that if any [`ChannelMonitorUpdate`]s are possibly generated, /// [`ChannelManager::process_background_events`] MUST be called first (or /// [`Self::optionally_notify`] used). - fn optionally_notify_skipping_background_events NotifyOption, C: AChannelManager> - (cm: &'a C, persist_check: F) -> PersistenceNotifierGuard<'a, F> { + fn optionally_notify_skipping_background_events NotifyOption, C: AChannelManager>( + cm: &'a C, persist_check: F, + ) -> PersistenceNotifierGuard<'a, F> { let read_guard = cm.get_cm().total_consistency_lock.read().unwrap(); PersistenceNotifierGuard { @@ -2788,6 +2881,7 @@ impl<'a> PersistenceNotifierGuard<'a, fn() -> NotifyOption> { // We don't care w } impl<'a, F: FnMut() -> NotifyOption> Drop for PersistenceNotifierGuard<'a, F> { + #[rustfmt::skip] fn drop(&mut self) { match (self.should_persist)() { NotifyOption::DoPersist => { @@ -2822,7 +2916,7 @@ pub(crate) const MAX_LOCAL_BREAKDOWN_TIMEOUT: u16 = 2 * 6 * 24 * 7; // i.e. the node we forwarded the payment on to should always have enough room to reliably time out // the HTLC via a full update_fail_htlc/commitment_signed dance before we hit the // CLTV_CLAIM_BUFFER point (we static assert that it's at least 3 blocks more). -pub const MIN_CLTV_EXPIRY_DELTA: u16 = 6*8; +pub const MIN_CLTV_EXPIRY_DELTA: u16 = 6 * 8; // This should be long enough to allow a payment path drawn across multiple routing hops with substantial // `cltv_expiry_delta`. Indeed, the length of those values is the reaction delay offered to a routing node // in case of HTLC on-chain settlement. While appearing less competitive, a node operator could decide to @@ -2849,7 +2943,8 @@ pub const MIN_FINAL_CLTV_EXPIRY_DELTA: u16 = HTLC_FAIL_BACK_BUFFER as u16 + 3; // expiry, i.e. assuming the peer force-closes right at the expiry and we're behind by // LATENCY_GRACE_PERIOD_BLOCKS). const _CHECK_CLTV_EXPIRY_SANITY: () = assert!( - MIN_CLTV_EXPIRY_DELTA as u32 >= 2*LATENCY_GRACE_PERIOD_BLOCKS + 2*MAX_BLOCKS_FOR_CONF + ANTI_REORG_DELAY + MIN_CLTV_EXPIRY_DELTA as u32 + >= 2 * LATENCY_GRACE_PERIOD_BLOCKS + 2 * MAX_BLOCKS_FOR_CONF + ANTI_REORG_DELAY ); // Check that our MIN_CLTV_EXPIRY_DELTA gives us enough time to get the HTLC preimage back to our @@ -2865,7 +2960,8 @@ const _CHECK_COUNTERPARTY_REALISTIC: () = assert!(_ASSUMED_COUNTERPARTY_CLTV_CLAIM_BUFFER >= CLTV_CLAIM_BUFFER); const _CHECK_CLTV_EXPIRY_OFFCHAIN: () = assert!( - MIN_CLTV_EXPIRY_DELTA as u32 >= 2*LATENCY_GRACE_PERIOD_BLOCKS - 1 + _ASSUMED_COUNTERPARTY_CLTV_CLAIM_BUFFER + MIN_CLTV_EXPIRY_DELTA as u32 + >= 2 * LATENCY_GRACE_PERIOD_BLOCKS - 1 + _ASSUMED_COUNTERPARTY_CLTV_CLAIM_BUFFER ); /// The number of ticks of [`ChannelManager::timer_tick_occurred`] until expiry of incomplete MPPs @@ -2980,6 +3076,7 @@ pub struct PhantomRouteHints { pub real_node_pubkey: PublicKey, } +#[rustfmt::skip] macro_rules! handle_error { ($self: ident, $internal: expr, $counterparty_node_id: expr) => { { // In testing, ensure there are no deadlocks where the lock is already held upon @@ -3041,6 +3138,7 @@ macro_rules! handle_error { /// /// Note that this step can be skipped if the channel was never opened (through the creation of a /// [`ChannelMonitor`]/channel funding transaction) to begin with. +#[rustfmt::skip] macro_rules! locked_close_channel { ($self: ident, $peer_state: expr, $channel_context: expr, $shutdown_res_mut: expr) => {{ if let Some((_, funding_txo, _, update)) = $shutdown_res_mut.monitor_update.take() { @@ -3074,6 +3172,7 @@ macro_rules! locked_close_channel { } /// Returns (boolean indicating if we should remove the Channel object from memory, a mapped error) +#[rustfmt::skip] macro_rules! convert_channel_err { ($self: ident, $peer_state: expr, $err: expr, $context: expr, $funding: expr, $channel_id: expr, MANUAL_CHANNEL_UPDATE, $channel_update: expr) => { match $err { @@ -3119,6 +3218,7 @@ macro_rules! convert_channel_err { }; } +#[rustfmt::skip] macro_rules! break_channel_entry { ($self: ident, $peer_state: expr, $res: expr, $entry: expr) => { match $res { @@ -3135,6 +3235,7 @@ macro_rules! break_channel_entry { } } +#[rustfmt::skip] macro_rules! try_channel_entry { ($self: ident, $peer_state: expr, $res: expr, $entry: expr) => { match $res { @@ -3151,6 +3252,7 @@ macro_rules! try_channel_entry { } } +#[rustfmt::skip] macro_rules! remove_channel_entry { ($self: ident, $peer_state: expr, $entry: expr, $shutdown_res_mut: expr) => { { @@ -3196,6 +3298,7 @@ macro_rules! emit_funding_tx_broadcast_safe_event { } } +#[rustfmt::skip] macro_rules! emit_channel_pending_event { ($locked_events: expr, $channel: expr) => { if $channel.context.should_emit_channel_pending_event() { @@ -3212,6 +3315,7 @@ macro_rules! emit_channel_pending_event { } } +#[rustfmt::skip] macro_rules! emit_channel_ready_event { ($locked_events: expr, $channel: expr) => { if $channel.context.should_emit_channel_ready_event() { @@ -3458,6 +3562,7 @@ macro_rules! handle_new_monitor_update { } }; } +#[rustfmt::skip] macro_rules! process_events_body { ($self: expr, $event_to_handle: expr, $handle_event: expr) => { let mut handling_failed = false; @@ -3542,7 +3647,17 @@ macro_rules! process_events_body { } } -impl ChannelManager +impl< + M: Deref, + T: Deref, + ES: Deref, + NS: Deref, + SP: Deref, + F: Deref, + R: Deref, + MR: Deref, + L: Deref, + > ChannelManager where M::Target: chain::Watch<::EcdsaSigner>, T::Target: BroadcasterInterface, @@ -3571,6 +3686,7 @@ where /// [`block_connected`]: chain::Listen::block_connected /// [`block_disconnected`]: chain::Listen::block_disconnected /// [`params.best_block.block_hash`]: chain::BestBlock::block_hash + #[rustfmt::skip] pub fn new( fee_est: F, chain_monitor: M, tx_broadcaster: T, router: R, message_router: MR, logger: L, entropy_source: ES, node_signer: NS, signer_provider: SP, config: UserConfig, @@ -3655,6 +3771,7 @@ where self.create_and_insert_outbound_scid_alias() } + #[rustfmt::skip] fn create_and_insert_outbound_scid_alias(&self) -> u64 { let height = self.best_block.read().unwrap().height; let mut outbound_scid_alias = 0; @@ -3706,6 +3823,7 @@ where /// [`Event::FundingGenerationReady::user_channel_id`]: events::Event::FundingGenerationReady::user_channel_id /// [`Event::FundingGenerationReady::temporary_channel_id`]: events::Event::FundingGenerationReady::temporary_channel_id /// [`Event::ChannelClosed::channel_id`]: events::Event::ChannelClosed::channel_id + #[rustfmt::skip] pub fn create_channel(&self, their_network_key: PublicKey, channel_value_satoshis: u64, push_msat: u64, user_channel_id: u128, temporary_channel_id: Option, override_config: Option) -> Result { if channel_value_satoshis < 1000 { return Err(APIError::APIMisuseError { err: format!("Channel value must be at least 1000 satoshis. It was {}", channel_value_satoshis) }); @@ -3767,6 +3885,7 @@ where Ok(temporary_channel_id) } + #[rustfmt::skip] fn list_funded_channels_with_filter)) -> bool + Copy>(&self, f: Fn) -> Vec { // Allocate our best estimate of the number of channels we have in the `res` // Vec. Sadly the `short_to_chan_info` map doesn't cover channels without @@ -3798,6 +3917,7 @@ where /// Gets the list of open channels, in random order. See [`ChannelDetails`] field documentation for /// more information. + #[rustfmt::skip] pub fn list_channels(&self) -> Vec { // Allocate our best estimate of the number of channels we have in the `res` // Vec. Sadly the `short_to_chan_info` map doesn't cover channels without @@ -3837,6 +3957,7 @@ where } /// Gets the list of channels we have with a given counterparty, in random order. + #[rustfmt::skip] pub fn list_channels_with_counterparty(&self, counterparty_node_id: &PublicKey) -> Vec { let best_block_height = self.best_block.read().unwrap().height; let per_peer_state = self.per_peer_state.read().unwrap(); @@ -3867,6 +3988,7 @@ where /// [`Event::PaymentSent`] has not been received, you may consider resending the payment. /// /// [`Event::PaymentSent`]: events::Event::PaymentSent + #[rustfmt::skip] pub fn list_recent_payments(&self) -> Vec { self.pending_outbound_payments.pending_outbound_payments.lock().unwrap().iter() .filter_map(|(payment_id, pending_outbound_payment)| match pending_outbound_payment { @@ -3898,6 +4020,7 @@ where .collect() } + #[rustfmt::skip] fn close_channel_internal(&self, channel_id: &ChannelId, counterparty_node_id: &PublicKey, target_feerate_sats_per_1000_weight: Option, override_shutdown_script: Option) -> Result<(), APIError> { let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self); @@ -3993,7 +4116,9 @@ where /// [`ChannelCloseMinimum`]: crate::chain::chaininterface::ConfirmationTarget::ChannelCloseMinimum /// [`NonAnchorChannelFee`]: crate::chain::chaininterface::ConfirmationTarget::NonAnchorChannelFee /// [`SendShutdown`]: MessageSendEvent::SendShutdown - pub fn close_channel(&self, channel_id: &ChannelId, counterparty_node_id: &PublicKey) -> Result<(), APIError> { + pub fn close_channel( + &self, channel_id: &ChannelId, counterparty_node_id: &PublicKey, + ) -> Result<(), APIError> { self.close_channel_internal(channel_id, counterparty_node_id, None, None) } @@ -4026,11 +4151,13 @@ where /// [`ChannelConfig::force_close_avoidance_max_fee_satoshis`]: crate::util::config::ChannelConfig::force_close_avoidance_max_fee_satoshis /// [`NonAnchorChannelFee`]: crate::chain::chaininterface::ConfirmationTarget::NonAnchorChannelFee /// [`SendShutdown`]: MessageSendEvent::SendShutdown + #[rustfmt::skip] pub fn close_channel_with_feerate_and_script(&self, channel_id: &ChannelId, counterparty_node_id: &PublicKey, target_feerate_sats_per_1000_weight: Option, shutdown_script: Option) -> Result<(), APIError> { self.close_channel_internal(channel_id, counterparty_node_id, target_feerate_sats_per_1000_weight, shutdown_script) } /// Applies a [`ChannelMonitorUpdate`] which may or may not be for a channel which is closed. + #[rustfmt::skip] fn apply_post_close_monitor_update( &self, counterparty_node_id: PublicKey, channel_id: ChannelId, funding_txo: OutPoint, monitor_update: ChannelMonitorUpdate, @@ -4066,6 +4193,7 @@ where /// the channel-closing action, /// (b) this needs to be called without holding any locks (except /// [`ChannelManager::total_consistency_lock`]. + #[rustfmt::skip] fn finish_close_channel(&self, mut shutdown_res: ShutdownResult) { debug_assert_ne!(self.per_peer_state.held_by_thread(), LockHeldState::HeldByThread); #[cfg(debug_assertions)] @@ -4168,6 +4296,7 @@ where /// `peer_msg` should be set when we receive a message from a peer, but not set when the /// user closes, which will be re-exposed as the `ChannelClosed` reason. + #[rustfmt::skip] fn force_close_channel_with_peer(&self, channel_id: &ChannelId, peer_node_id: &PublicKey, peer_msg: Option<&String>, broadcast: bool) -> Result { let per_peer_state = self.per_peer_state.read().unwrap(); @@ -4221,6 +4350,7 @@ where Ok(counterparty_node_id) } + #[rustfmt::skip] fn force_close_sending_error(&self, channel_id: &ChannelId, counterparty_node_id: &PublicKey, broadcast: bool, error_message: String) -> Result<(), APIError> { let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self); @@ -4254,8 +4384,9 @@ where /// /// Fails if `channel_id` is unknown to the manager, or if the `counterparty_node_id` /// isn't the counterparty of the corresponding channel. - pub fn force_close_broadcasting_latest_txn(&self, channel_id: &ChannelId, counterparty_node_id: &PublicKey, error_message: String) - -> Result<(), APIError> { + pub fn force_close_broadcasting_latest_txn( + &self, channel_id: &ChannelId, counterparty_node_id: &PublicKey, error_message: String, + ) -> Result<(), APIError> { self.force_close_sending_error(channel_id, counterparty_node_id, true, error_message) } @@ -4269,8 +4400,9 @@ where /// `counterparty_node_id` isn't the counterparty of the corresponding channel. /// You can always broadcast the latest local transaction(s) via /// [`ChannelMonitor::broadcast_latest_holder_commitment_txn`]. - pub fn force_close_without_broadcasting_txn(&self, channel_id: &ChannelId, counterparty_node_id: &PublicKey, error_message: String) - -> Result<(), APIError> { + pub fn force_close_without_broadcasting_txn( + &self, channel_id: &ChannelId, counterparty_node_id: &PublicKey, error_message: String, + ) -> Result<(), APIError> { self.force_close_sending_error(channel_id, counterparty_node_id, false, error_message) } @@ -4279,6 +4411,7 @@ where /// /// The provided `error_message` is sent to connected peers for closing channels and should /// be a human-readable description of what went wrong. + #[rustfmt::skip] pub fn force_close_all_channels_broadcasting_latest_txn(&self, error_message: String) { for chan in self.list_channels() { let _ = self.force_close_broadcasting_latest_txn(&chan.channel_id, &chan.counterparty.node_id, error_message.clone()); @@ -4290,6 +4423,7 @@ where /// /// The provided `error_message` is sent to connected peers for closing channels and /// should be a human-readable description of what went wrong. + #[rustfmt::skip] pub fn force_close_all_channels_without_broadcasting_txn(&self, error_message: String) { for chan in self.list_channels() { let _ = self.force_close_without_broadcasting_txn(&chan.channel_id, &chan.counterparty.node_id, error_message.clone()); @@ -4308,6 +4442,7 @@ where /// Includes the witness weight for this input (e.g. P2WPKH_WITNESS_WEIGHT=109 for typical P2WPKH inputs). /// - `locktime`: Optional locktime for the new funding transaction. If None, set to the current block height. #[cfg(splicing)] + #[rustfmt::skip] pub fn splice_channel( &self, channel_id: &ChannelId, counterparty_node_id: &PublicKey, our_funding_contribution_satoshis: i64, our_funding_inputs: Vec<(TxIn, Transaction, Weight)>, @@ -4329,6 +4464,7 @@ where /// See [`splice_channel`] #[cfg(splicing)] + #[rustfmt::skip] fn internal_splice_channel( &self, channel_id: &ChannelId, counterparty_node_id: &PublicKey, our_funding_contribution_satoshis: i64, our_funding_inputs: &Vec<(TxIn, Transaction, Weight)>, @@ -4376,6 +4512,7 @@ where } } + #[rustfmt::skip] fn can_forward_htlc_to_outgoing_channel( &self, chan: &mut FundedChannel, msg: &msgs::UpdateAddHTLC, next_packet: &NextPacketDetails ) -> Result<(), LocalHTLCFailureReason> { @@ -4418,6 +4555,7 @@ where /// Executes a callback `C` that returns some value `X` on the channel found with the given /// `scid`. `None` is returned when the channel is not found. + #[rustfmt::skip] fn do_funded_channel_callback) -> X>( &self, scid: u64, callback: C, ) -> Option { @@ -4438,6 +4576,7 @@ where } } + #[rustfmt::skip] fn can_forward_htlc( &self, msg: &msgs::UpdateAddHTLC, next_packet_details: &NextPacketDetails ) -> Result<(), LocalHTLCFailureReason> { @@ -4470,6 +4609,7 @@ where Ok(()) } + #[rustfmt::skip] fn htlc_failure_from_update_add_err( &self, msg: &msgs::UpdateAddHTLC, counterparty_node_id: &PublicKey, reason: LocalHTLCFailureReason, is_intro_node_blinded_forward: bool, @@ -4522,6 +4662,7 @@ where }) } + #[rustfmt::skip] fn construct_pending_htlc_fail_msg<'a>( &self, msg: &msgs::UpdateAddHTLC, counterparty_node_id: &PublicKey, shared_secret: [u8; 32], inbound_err: InboundHTLCErr @@ -4550,6 +4691,7 @@ where }); } + #[rustfmt::skip] fn get_pending_htlc_info<'a>( &self, msg: &msgs::UpdateAddHTLC, shared_secret: [u8; 32], decoded_hop: onion_utils::Hop, allow_underpay: bool, @@ -4587,6 +4729,7 @@ where /// /// [`channel_update`]: msgs::ChannelUpdate /// [`internal_closing_signed`]: Self::internal_closing_signed + #[rustfmt::skip] fn get_channel_update_for_broadcast(&self, chan: &FundedChannel) -> Result { if !chan.context.should_announce() { return Err(LightningError { @@ -4613,6 +4756,7 @@ where /// /// [`channel_update`]: msgs::ChannelUpdate /// [`internal_closing_signed`]: Self::internal_closing_signed + #[rustfmt::skip] fn get_channel_update_for_unicast(&self, chan: &FundedChannel) -> Result { let logger = WithChannelContext::from(&self.logger, &chan.context, None); log_trace!(logger, "Attempting to generate channel update for channel {}", chan.context.channel_id()); @@ -4652,6 +4796,7 @@ where } #[cfg(any(test, feature = "_externalize_tests"))] + #[rustfmt::skip] pub(crate) fn test_send_payment_along_path(&self, path: &Path, payment_hash: &PaymentHash, recipient_onion: RecipientOnionFields, total_value: u64, cur_height: u32, payment_id: PaymentId, keysend_preimage: &Option, session_priv_bytes: [u8; 32]) -> Result<(), APIError> { let _lck = self.total_consistency_lock.read().unwrap(); self.send_payment_along_path(SendAlongPathArgs { @@ -4660,6 +4805,7 @@ where }) } + #[rustfmt::skip] fn send_payment_along_path(&self, args: SendAlongPathArgs) -> Result<(), APIError> { let SendAlongPathArgs { path, payment_hash, recipient_onion, total_value, cur_height, payment_id, keysend_preimage, @@ -4756,6 +4902,7 @@ where /// /// LDK will not automatically retry this payment, though it may be manually re-sent after an /// [`Event::PaymentFailed`] is generated. + #[rustfmt::skip] pub fn send_payment_with_route( &self, mut route: Route, payment_hash: PaymentHash, recipient_onion: RecipientOnionFields, payment_id: PaymentId @@ -4813,6 +4960,7 @@ where /// [`UpdateHTLCs`]: MessageSendEvent::UpdateHTLCs /// [`PeerManager::process_events`]: crate::ln::peer_handler::PeerManager::process_events /// [`ChannelMonitorUpdateStatus::InProgress`]: crate::chain::ChannelMonitorUpdateStatus::InProgress + #[rustfmt::skip] pub fn send_payment( &self, payment_hash: PaymentHash, recipient_onion: RecipientOnionFields, payment_id: PaymentId, route_params: RouteParameters, retry_strategy: Retry @@ -4827,6 +4975,7 @@ where } #[cfg(any(test, feature = "_externalize_tests"))] + #[rustfmt::skip] pub(super) fn test_send_payment_internal(&self, route: &Route, payment_hash: PaymentHash, recipient_onion: RecipientOnionFields, keysend_preimage: Option, payment_id: PaymentId, recv_value_msat: Option, onion_session_privs: Vec<[u8; 32]>) -> Result<(), PaymentSendFailure> { let best_block_height = self.best_block.read().unwrap().height; let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self); @@ -4836,12 +4985,14 @@ where } #[cfg(any(test, feature = "_externalize_tests"))] + #[rustfmt::skip] pub(crate) fn test_add_new_pending_payment(&self, payment_hash: PaymentHash, recipient_onion: RecipientOnionFields, payment_id: PaymentId, route: &Route) -> Result, PaymentSendFailure> { let best_block_height = self.best_block.read().unwrap().height; self.pending_outbound_payments.test_add_new_pending_payment(payment_hash, recipient_onion, payment_id, route, None, &self.entropy_source, best_block_height) } #[cfg(all(test, async_payments))] + #[rustfmt::skip] pub(crate) fn test_modify_pending_payment( &self, payment_id: &PaymentId, mut callback: Fn ) where Fn: FnMut(&mut PendingOutboundPayment) { @@ -4853,7 +5004,9 @@ where } #[cfg(test)] - pub(crate) fn test_set_payment_metadata(&self, payment_id: PaymentId, new_payment_metadata: Option>) { + pub(crate) fn test_set_payment_metadata( + &self, payment_id: PaymentId, new_payment_metadata: Option>, + ) { self.pending_outbound_payments.test_set_payment_metadata(payment_id, new_payment_metadata); } @@ -4872,6 +5025,7 @@ where /// # Custom Routing Parameters /// Users can customize routing parameters via [`RouteParametersConfig`]. /// To use default settings, call the function with `RouteParametersConfig::default()`. + #[rustfmt::skip] pub fn pay_for_bolt11_invoice( &self, invoice: &Bolt11Invoice, payment_id: PaymentId, amount_msats: Option, route_params_config: RouteParametersConfig, retry_strategy: Retry @@ -4931,6 +5085,7 @@ where } } + #[rustfmt::skip] fn send_payment_for_verified_bolt12_invoice(&self, invoice: &Bolt12Invoice, payment_id: PaymentId) -> Result<(), Bolt12PaymentError> { let best_block_height = self.best_block.read().unwrap().height; let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self); @@ -4945,6 +5100,7 @@ where } #[cfg(async_payments)] + #[rustfmt::skip] fn initiate_async_payment( &self, invoice: &StaticInvoice, payment_id: PaymentId ) -> Result<(), Bolt12PaymentError> { @@ -4996,6 +5152,7 @@ where } #[cfg(async_payments)] + #[rustfmt::skip] fn send_payment_for_static_invoice( &self, payment_id: PaymentId ) -> Result<(), Bolt12PaymentError> { @@ -5072,6 +5229,7 @@ where /// /// [`send_payment`]: Self::send_payment /// [`PaymentParameters::for_keysend`]: crate::routing::router::PaymentParameters::for_keysend + #[rustfmt::skip] pub fn send_spontaneous_payment( &self, payment_preimage: Option, recipient_onion: RecipientOnionFields, payment_id: PaymentId, route_params: RouteParameters, retry_strategy: Retry @@ -5087,6 +5245,7 @@ where /// Send a payment that is probing the given route for liquidity. We calculate the /// [`PaymentHash`] of probes based on a static secret and a random [`PaymentId`], which allows /// us to easily discern them from real payments. + #[rustfmt::skip] pub fn send_probe(&self, path: Path) -> Result<(PaymentHash, PaymentId), ProbeSendFailure> { let best_block_height = self.best_block.read().unwrap().height; let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self); @@ -5098,7 +5257,9 @@ where /// Returns whether a payment with the given [`PaymentHash`] and [`PaymentId`] is, in fact, a /// payment probe. #[cfg(test)] - pub(crate) fn payment_is_probe(&self, payment_hash: &PaymentHash, payment_id: &PaymentId) -> bool { + pub(crate) fn payment_is_probe( + &self, payment_hash: &PaymentHash, payment_id: &PaymentId, + ) -> bool { outbound_payment::payment_is_probe(payment_hash, payment_id, self.probing_cookie_secret) } @@ -5106,6 +5267,7 @@ where /// amount to the given `node_id`. /// /// See [`ChannelManager::send_preflight_probes`] for more information. + #[rustfmt::skip] pub fn send_spontaneous_preflight_probes( &self, node_id: PublicKey, amount_msat: u64, final_cltv_expiry_delta: u32, liquidity_limit_multiplier: Option, @@ -5214,6 +5376,7 @@ where /// Handles the generation of a funding transaction, optionally (for tests) with a function /// which checks the correctness of the funding transaction given the associated channel. + #[rustfmt::skip] fn funding_transaction_generated_intern) -> Result>( &self, temporary_channel_id: ChannelId, counterparty_node_id: PublicKey, funding_transaction: Transaction, is_batch_funding: bool, mut find_funding_output: FundingOutput, is_manual_broadcast: bool, @@ -5225,6 +5388,7 @@ where let mut peer_state_lock = peer_state_mutex.lock().unwrap(); let peer_state = &mut *peer_state_lock; + #[rustfmt::skip] macro_rules! close_chan { ($err: expr, $api_err: expr, $chan: expr) => { { let counterparty; let err = if let ChannelError::Close((msg, reason)) = $err { @@ -5309,6 +5473,7 @@ where } #[cfg(any(test, feature = "_externalize_tests"))] + #[rustfmt::skip] pub(crate) fn funding_transaction_generated_unchecked(&self, temporary_channel_id: ChannelId, counterparty_node_id: PublicKey, funding_transaction: Transaction, output_index: u16) -> Result<(), APIError> { let txid = funding_transaction.compute_txid(); self.funding_transaction_generated_intern(temporary_channel_id, counterparty_node_id, funding_transaction, false, |_| { @@ -5346,11 +5511,11 @@ where /// /// [`Event::FundingGenerationReady`]: crate::events::Event::FundingGenerationReady /// [`Event::ChannelClosed`]: crate::events::Event::ChannelClosed + #[rustfmt::skip] pub fn funding_transaction_generated(&self, temporary_channel_id: ChannelId, counterparty_node_id: PublicKey, funding_transaction: Transaction) -> Result<(), APIError> { self.batch_funding_transaction_generated(&[(&temporary_channel_id, &counterparty_node_id)], funding_transaction) } - /// **Unsafe**: This method does not validate the spent output. It is the caller's /// responsibility to ensure the spent outputs are SegWit, as well as making sure the funding /// transaction has a final absolute locktime, i.e., its locktime is lower than the next block height. @@ -5378,6 +5543,7 @@ where /// [`Event::FundingTxBroadcastSafe`]: crate::events::Event::FundingTxBroadcastSafe /// [`Event::ChannelClosed`]: crate::events::Event::ChannelClosed /// [`ChannelManager::funding_transaction_generated`]: crate::ln::channelmanager::ChannelManager::funding_transaction_generated + #[rustfmt::skip] pub fn unsafe_manual_funding_transaction_generated(&self, temporary_channel_id: ChannelId, counterparty_node_id: PublicKey, funding: OutPoint) -> Result<(), APIError> { let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self); @@ -5396,11 +5562,13 @@ where /// signature for each channel. /// /// If there is an error, all channels in the batch are to be considered closed. + #[rustfmt::skip] pub fn batch_funding_transaction_generated(&self, temporary_channels: &[(&ChannelId, &PublicKey)], funding_transaction: Transaction) -> Result<(), APIError> { let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self); self.batch_funding_transaction_generated_intern(temporary_channels, FundingType::Checked(funding_transaction)) } + #[rustfmt::skip] fn batch_funding_transaction_generated_intern(&self, temporary_channels: &[(&ChannelId, &PublicKey)], funding: FundingType) -> Result<(), APIError> { let mut result = Ok(()); if let FundingType::Checked(funding_transaction) = &funding { @@ -5556,6 +5724,7 @@ where /// [`ChannelUpdate`]: msgs::ChannelUpdate /// [`ChannelUnavailable`]: APIError::ChannelUnavailable /// [`APIMisuseError`]: APIError::APIMisuseError + #[rustfmt::skip] pub fn update_partial_channel_config( &self, counterparty_node_id: &PublicKey, channel_ids: &[ChannelId], config_update: &ChannelConfigUpdate, ) -> Result<(), APIError> { @@ -5633,6 +5802,7 @@ where /// [`ChannelUpdate`]: msgs::ChannelUpdate /// [`ChannelUnavailable`]: APIError::ChannelUnavailable /// [`APIMisuseError`]: APIError::APIMisuseError + #[rustfmt::skip] pub fn update_channel_config( &self, counterparty_node_id: &PublicKey, channel_ids: &[ChannelId], config: &ChannelConfig, ) -> Result<(), APIError> { @@ -5664,6 +5834,7 @@ where /// [`HTLCIntercepted::expected_outbound_amount_msat`]: events::Event::HTLCIntercepted::expected_outbound_amount_msat // TODO: when we move to deciding the best outbound channel at forward time, only take // `next_node_id` and not `next_hop_channel_id` + #[rustfmt::skip] pub fn forward_intercepted_htlc(&self, intercept_id: InterceptId, next_hop_channel_id: &ChannelId, next_node_id: PublicKey, amt_to_forward_msat: u64) -> Result<(), APIError> { let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self); @@ -5738,6 +5909,7 @@ where /// backwards. /// /// [`HTLCIntercepted`]: events::Event::HTLCIntercepted + #[rustfmt::skip] pub fn fail_intercepted_htlc(&self, intercept_id: InterceptId) -> Result<(), APIError> { let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self); @@ -5768,6 +5940,7 @@ where Ok(()) } + #[rustfmt::skip] pub(crate) fn process_pending_update_add_htlcs(&self) { let mut decode_update_add_htlcs = new_hash_map(); mem::swap(&mut decode_update_add_htlcs, &mut self.decode_update_add_htlcs.lock().unwrap()); @@ -5914,6 +6087,7 @@ where /// /// Should only really ever be called in response to a PendingHTLCsForwardable event. /// Will likely generate further events. + #[rustfmt::skip] pub fn process_pending_htlc_forwards(&self) { let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self); @@ -5979,6 +6153,7 @@ where } } } + #[rustfmt::skip] macro_rules! failed_payment { ($msg: expr, $reason: expr, $err_data: expr, $phantom_ss: expr) => { { @@ -6281,6 +6456,7 @@ where let mut committed_to_claimable = false; + #[rustfmt::skip] macro_rules! fail_htlc { ($htlc: expr, $payment_hash: expr) => { debug_assert!(!committed_to_claimable); @@ -6310,6 +6486,7 @@ where .expect("Failed to get node_id for phantom node recipient"); } + #[rustfmt::skip] macro_rules! check_total_value { ($purpose: expr) => {{ let mut payment_claimable_generated = false; @@ -6526,6 +6703,7 @@ where /// Free the background events, generally called from [`PersistenceNotifierGuard`] constructors. /// /// Expects the caller to have a total_consistency_lock read lock. + #[rustfmt::skip] fn process_background_events(&self) -> NotifyOption { debug_assert_ne!(self.total_consistency_lock.held_by_thread(), LockHeldState::NotHeldByThread); @@ -6573,6 +6751,7 @@ where let _ = self.process_background_events(); } + #[rustfmt::skip] fn update_channel_fee(&self, chan_id: &ChannelId, chan: &mut FundedChannel, new_feerate: u32) -> NotifyOption { if !chan.funding.is_outbound() { return NotifyOption::SkipPersistNoEvents; } @@ -6599,6 +6778,7 @@ where /// timer_tick_occurred, but we can't generate the disabled channel updates as it considers /// these a fuzz failure (as they usually indicate a channel force-close, which is exactly what /// it wants to detect). Thus, we have a variant exposed here for its benefit. + #[rustfmt::skip] pub fn maybe_update_chan_fees(&self) { PersistenceNotifierGuard::optionally_notify(self, || { let mut should_persist = NotifyOption::SkipPersistNoEvents; @@ -6648,6 +6828,7 @@ where /// /// [`ChannelUpdate`]: msgs::ChannelUpdate /// [`ChannelConfig`]: crate::util::config::ChannelConfig + #[rustfmt::skip] pub fn timer_tick_occurred(&self) { PersistenceNotifierGuard::optionally_notify(self, || { let mut should_persist = NotifyOption::SkipPersistNoEvents; @@ -6904,6 +7085,7 @@ where /// [`ChannelManager::claim_funds`]), you should still monitor for /// [`events::Event::PaymentClaimed`] events even for payments you intend to fail, especially on /// startup during which time claims that were in-progress at shutdown may be replayed. + #[rustfmt::skip] pub fn fail_htlc_backwards(&self, payment_hash: &PaymentHash) { self.fail_htlc_backwards_with_reason(payment_hash, FailureCode::IncorrectOrUnknownPaymentDetails); } @@ -6912,6 +7094,7 @@ where /// reason for the failure. /// /// See [`FailureCode`] for valid failure codes. + #[rustfmt::skip] pub fn fail_htlc_backwards_with_reason(&self, payment_hash: &PaymentHash, failure_code: FailureCode) { let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self); @@ -6927,6 +7110,7 @@ where } /// Gets error data to form an [`HTLCFailReason`] given a [`FailureCode`] and [`ClaimableHTLC`]. + #[rustfmt::skip] fn get_htlc_fail_reason_from_failure_code(&self, failure_code: FailureCode, htlc: &ClaimableHTLC) -> HTLCFailReason { match failure_code { FailureCode::TemporaryNodeFailure => HTLCFailReason::from_failure_code(failure_code.into()), @@ -6971,6 +7155,7 @@ where // Fail a list of HTLCs that were just freed from the holding cell. The HTLCs need to be // failed backwards or, if they were one of our outgoing HTLCs, then their failure needs to // be surfaced to the user. + #[rustfmt::skip] fn fail_holding_cell_htlcs( &self, mut htlcs_to_fail: Vec<(HTLCSource, PaymentHash)>, channel_id: ChannelId, counterparty_node_id: &PublicKey @@ -7004,6 +7189,7 @@ where } } + #[rustfmt::skip] fn fail_htlc_backwards_internal(&self, source: &HTLCSource, payment_hash: &PaymentHash, onion_error: &HTLCFailReason, destination: HTLCHandlingFailureType) { let push_forward_event = self.fail_htlc_backwards_internal_without_forward_event(source, payment_hash, onion_error, destination); if push_forward_event { self.push_pending_forwards_ev(); } @@ -7011,6 +7197,7 @@ where /// Fails an HTLC backwards to the sender of it to us. /// Note that we do not assume that channels corresponding to failed HTLCs are still available. + #[rustfmt::skip] fn fail_htlc_backwards_internal_without_forward_event(&self, source: &HTLCSource, payment_hash: &PaymentHash, onion_error: &HTLCFailReason, failure_type: HTLCHandlingFailureType) -> bool { // Ensure that no peer state channel storage lock is held when calling this function. // This ensures that future code doesn't introduce a lock-order requirement for @@ -7132,6 +7319,7 @@ where self.claim_payment_internal(payment_preimage, true); } + #[rustfmt::skip] fn claim_payment_internal(&self, payment_preimage: PaymentPreimage, custom_tlvs_known: bool) { let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0).to_byte_array()); @@ -7268,7 +7456,10 @@ where } fn claim_funds_from_hop< - ComplFunc: FnOnce(Option, bool) -> (Option, Option) + ComplFunc: FnOnce( + Option, + bool, + ) -> (Option, Option), >( &self, prev_hop: HTLCPreviousHopData, payment_preimage: PaymentPreimage, payment_info: Option, completion_action: ComplFunc, @@ -7287,6 +7478,7 @@ where self.claim_mpp_part(htlc_source, payment_preimage, payment_info, completion_action) } + #[rustfmt::skip] fn claim_mpp_part< ComplFunc: FnOnce(Option, bool) -> (Option, Option) >( @@ -7472,6 +7664,7 @@ This indicates a bug inside LDK. Please report this error at https://github.com/ self.pending_outbound_payments.finalize_claims(sources, &self.pending_events); } + #[rustfmt::skip] fn claim_funds_internal(&self, source: HTLCSource, payment_preimage: PaymentPreimage, forwarded_htlc_value_msat: Option, skimmed_fee_msat: Option, from_onchain: bool, startup_replay: bool, next_channel_counterparty_node_id: PublicKey, @@ -7553,6 +7746,7 @@ This indicates a bug inside LDK. Please report this error at https://github.com/ self.our_network_pubkey } + #[rustfmt::skip] fn handle_monitor_update_completion_actions>(&self, actions: I) { debug_assert_ne!(self.pending_events.held_by_thread(), LockHeldState::HeldByThread); debug_assert_ne!(self.claimable_payments.held_by_thread(), LockHeldState::HeldByThread); @@ -7661,6 +7855,7 @@ This indicates a bug inside LDK. Please report this error at https://github.com/ /// Handles a channel reentering a functional state, either due to reconnect or a monitor /// update completion. + #[rustfmt::skip] fn handle_channel_resumption(&self, pending_msg_events: &mut Vec, channel: &mut FundedChannel, raa: Option, commitment_update: Option, order: RAACommitmentOrder, @@ -7720,6 +7915,7 @@ This indicates a bug inside LDK. Please report this error at https://github.com/ }); } + #[rustfmt::skip] macro_rules! handle_cs { () => { if let Some(update) = commitment_update { pending_msg_events.push(MessageSendEvent::UpdateHTLCs { @@ -7729,6 +7925,7 @@ This indicates a bug inside LDK. Please report this error at https://github.com/ }); } } } + #[rustfmt::skip] macro_rules! handle_raa { () => { if let Some(revoke_and_ack) = raa { pending_msg_events.push(MessageSendEvent::SendRevokeAndACK { @@ -7776,6 +7973,7 @@ This indicates a bug inside LDK. Please report this error at https://github.com/ (htlc_forwards, decode_update_add_htlcs) } + #[rustfmt::skip] fn channel_monitor_updated(&self, channel_id: &ChannelId, highest_applied_update_id: u64, counterparty_node_id: &PublicKey) { debug_assert!(self.total_consistency_lock.try_write().is_err()); // Caller holds read lock @@ -7840,6 +8038,7 @@ This indicates a bug inside LDK. Please report this error at https://github.com/ /// /// [`Event::OpenChannelRequest`]: events::Event::OpenChannelRequest /// [`Event::ChannelClosed::user_channel_id`]: events::Event::ChannelClosed::user_channel_id + #[rustfmt::skip] pub fn accept_inbound_channel(&self, temporary_channel_id: &ChannelId, counterparty_node_id: &PublicKey, user_channel_id: u128, config_overrides: Option) -> Result<(), APIError> { self.do_accept_inbound_channel(temporary_channel_id, counterparty_node_id, false, user_channel_id, config_overrides) } @@ -7862,11 +8061,13 @@ This indicates a bug inside LDK. Please report this error at https://github.com/ /// /// [`Event::OpenChannelRequest`]: events::Event::OpenChannelRequest /// [`Event::ChannelClosed::user_channel_id`]: events::Event::ChannelClosed::user_channel_id + #[rustfmt::skip] pub fn accept_inbound_channel_from_trusted_peer_0conf(&self, temporary_channel_id: &ChannelId, counterparty_node_id: &PublicKey, user_channel_id: u128, config_overrides: Option) -> Result<(), APIError> { self.do_accept_inbound_channel(temporary_channel_id, counterparty_node_id, true, user_channel_id, config_overrides) } /// TODO(dual_funding): Allow contributions, pass intended amount and inputs + #[rustfmt::skip] fn do_accept_inbound_channel( &self, temporary_channel_id: &ChannelId, counterparty_node_id: &PublicKey, accept_0conf: bool, user_channel_id: u128, config_overrides: Option @@ -8022,6 +8223,7 @@ This indicates a bug inside LDK. Please report this error at https://github.com/ /// /// The filter is called for each peer and provided with the number of unfunded, inbound, and /// non-0-conf channels we have with the peer. + #[rustfmt::skip] fn peers_without_funded_channels(&self, maybe_count_peer: Filter) -> usize where Filter: Fn(&PeerState) -> bool { let mut peers_without_funded_channels = 0; @@ -8040,6 +8242,7 @@ This indicates a bug inside LDK. Please report this error at https://github.com/ return peers_without_funded_channels; } + #[rustfmt::skip] fn unfunded_channel_count( peer: &PeerState, best_block_height: u32 ) -> usize { @@ -8080,6 +8283,7 @@ This indicates a bug inside LDK. Please report this error at https://github.com/ num_unfunded_channels + peer.inbound_channel_request_by_id.len() } + #[rustfmt::skip] fn internal_open_channel(&self, counterparty_node_id: &PublicKey, msg: OpenChannelMessageRef<'_>) -> Result<(), MsgHandleErrInternal> { let common_fields = match msg { OpenChannelMessageRef::V1(msg) => &msg.common_fields, @@ -8230,6 +8434,7 @@ This indicates a bug inside LDK. Please report this error at https://github.com/ Ok(()) } + #[rustfmt::skip] fn internal_accept_channel(&self, counterparty_node_id: &PublicKey, msg: &msgs::AcceptChannel) -> Result<(), MsgHandleErrInternal> { // Note that the ChannelManager is NOT re-persisted on disk after this, so any changes are // likely to be lost on restart! @@ -8268,6 +8473,7 @@ This indicates a bug inside LDK. Please report this error at https://github.com/ Ok(()) } + #[rustfmt::skip] fn internal_funding_created(&self, counterparty_node_id: &PublicKey, msg: &msgs::FundingCreated) -> Result<(), MsgHandleErrInternal> { let best_block = *self.best_block.read().unwrap(); @@ -8310,6 +8516,7 @@ This indicates a bug inside LDK. Please report this error at https://github.com/ let funded_channel_id = chan.context.channel_id(); + #[rustfmt::skip] macro_rules! fail_chan { ($err: expr) => { { // Note that at this point we've filled in the funding outpoint on our // channel, but its actually in conflict with another channel. Thus, if @@ -8355,6 +8562,7 @@ This indicates a bug inside LDK. Please report this error at https://github.com/ } } + #[rustfmt::skip] fn internal_peer_storage_retrieval(&self, counterparty_node_id: PublicKey, _msg: msgs::PeerStorageRetrieval) -> Result<(), MsgHandleErrInternal> { // TODO: Decrypt and check if have any stale or missing ChannelMonitor. let logger = WithContext::from(&self.logger, Some(counterparty_node_id), None, None); @@ -8366,6 +8574,7 @@ This indicates a bug inside LDK. Please report this error at https://github.com/ ), ChannelId([0; 32]))) } + #[rustfmt::skip] fn internal_peer_storage(&self, counterparty_node_id: PublicKey, msg: msgs::PeerStorage) -> Result<(), MsgHandleErrInternal> { let per_peer_state = self.per_peer_state.read().unwrap(); let peer_state_mutex = per_peer_state.get(&counterparty_node_id) @@ -8401,6 +8610,7 @@ This indicates a bug inside LDK. Please report this error at https://github.com/ Ok(()) } + #[rustfmt::skip] fn internal_funding_signed(&self, counterparty_node_id: &PublicKey, msg: &msgs::FundingSigned) -> Result<(), MsgHandleErrInternal> { let best_block = *self.best_block.read().unwrap(); let per_peer_state = self.per_peer_state.read().unwrap(); @@ -8442,6 +8652,7 @@ This indicates a bug inside LDK. Please report this error at https://github.com/ } } + #[rustfmt::skip] fn internal_tx_msg) -> Result>( &self, counterparty_node_id: &PublicKey, channel_id: ChannelId, tx_msg_handler: HandleTxMsgFn ) -> Result<(), MsgHandleErrInternal> { @@ -8476,7 +8687,9 @@ This indicates a bug inside LDK. Please report this error at https://github.com/ } } - fn internal_tx_add_input(&self, counterparty_node_id: PublicKey, msg: &msgs::TxAddInput) -> Result<(), MsgHandleErrInternal> { + fn internal_tx_add_input( + &self, counterparty_node_id: PublicKey, msg: &msgs::TxAddInput, + ) -> Result<(), MsgHandleErrInternal> { self.internal_tx_msg(&counterparty_node_id, msg.channel_id, |channel: &mut Channel| { match channel.as_unfunded_v2_mut() { Some(unfunded_channel) => { @@ -8487,6 +8700,7 @@ This indicates a bug inside LDK. Please report this error at https://github.com/ }) } + #[rustfmt::skip] fn internal_tx_add_output(&self, counterparty_node_id: PublicKey, msg: &msgs::TxAddOutput) -> Result<(), MsgHandleErrInternal> { self.internal_tx_msg(&counterparty_node_id, msg.channel_id, |channel: &mut Channel| { match channel.as_unfunded_v2_mut() { @@ -8498,6 +8712,7 @@ This indicates a bug inside LDK. Please report this error at https://github.com/ }) } + #[rustfmt::skip] fn internal_tx_remove_input(&self, counterparty_node_id: PublicKey, msg: &msgs::TxRemoveInput) -> Result<(), MsgHandleErrInternal> { self.internal_tx_msg(&counterparty_node_id, msg.channel_id, |channel: &mut Channel| { match channel.as_unfunded_v2_mut() { @@ -8509,6 +8724,7 @@ This indicates a bug inside LDK. Please report this error at https://github.com/ }) } + #[rustfmt::skip] fn internal_tx_remove_output(&self, counterparty_node_id: PublicKey, msg: &msgs::TxRemoveOutput) -> Result<(), MsgHandleErrInternal> { self.internal_tx_msg(&counterparty_node_id, msg.channel_id, |channel: &mut Channel| { match channel.as_unfunded_v2_mut() { @@ -8520,6 +8736,7 @@ This indicates a bug inside LDK. Please report this error at https://github.com/ }) } + #[rustfmt::skip] fn internal_tx_complete(&self, counterparty_node_id: PublicKey, msg: &msgs::TxComplete) -> Result<(), MsgHandleErrInternal> { let per_peer_state = self.per_peer_state.read().unwrap(); let peer_state_mutex = per_peer_state.get(&counterparty_node_id) @@ -8575,6 +8792,7 @@ This indicates a bug inside LDK. Please report this error at https://github.com/ } } + #[rustfmt::skip] fn internal_tx_signatures(&self, counterparty_node_id: &PublicKey, msg: &msgs::TxSignatures) -> Result<(), MsgHandleErrInternal> { let per_peer_state = self.per_peer_state.read().unwrap(); @@ -8621,6 +8839,7 @@ This indicates a bug inside LDK. Please report this error at https://github.com/ } } + #[rustfmt::skip] fn internal_tx_abort(&self, counterparty_node_id: &PublicKey, msg: &msgs::TxAbort) -> Result<(), MsgHandleErrInternal> { let per_peer_state = self.per_peer_state.read().unwrap(); @@ -8683,6 +8902,7 @@ This indicates a bug inside LDK. Please report this error at https://github.com/ } } + #[rustfmt::skip] fn internal_channel_ready(&self, counterparty_node_id: &PublicKey, msg: &msgs::ChannelReady) -> Result<(), MsgHandleErrInternal> { // Note that the ChannelManager is NOT re-persisted on disk after this (unless we error // closing a channel), so any changes are likely to be lost on restart! @@ -8738,6 +8958,7 @@ This indicates a bug inside LDK. Please report this error at https://github.com/ } } + #[rustfmt::skip] fn internal_shutdown(&self, counterparty_node_id: &PublicKey, msg: &msgs::Shutdown) -> Result<(), MsgHandleErrInternal> { let mut dropped_htlcs: Vec<(HTLCSource, PaymentHash)> = Vec::new(); let mut finish_shutdown = None; @@ -8804,6 +9025,7 @@ This indicates a bug inside LDK. Please report this error at https://github.com/ Ok(()) } + #[rustfmt::skip] fn internal_closing_signed(&self, counterparty_node_id: &PublicKey, msg: &msgs::ClosingSigned) -> Result<(), MsgHandleErrInternal> { let per_peer_state = self.per_peer_state.read().unwrap(); let peer_state_mutex = per_peer_state.get(counterparty_node_id) @@ -8867,6 +9089,7 @@ This indicates a bug inside LDK. Please report this error at https://github.com/ Ok(()) } + #[rustfmt::skip] fn internal_update_add_htlc(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateAddHTLC) -> Result<(), MsgHandleErrInternal> { //TODO: BOLT 4 points out a specific attack where a peer may re-send an onion packet and //determine the state of the payment based on our response/if we forward anything/the time @@ -8902,6 +9125,7 @@ This indicates a bug inside LDK. Please report this error at https://github.com/ Ok(()) } + #[rustfmt::skip] fn internal_update_fulfill_htlc(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateFulfillHTLC) -> Result<(), MsgHandleErrInternal> { let funding_txo; let next_user_channel_id; @@ -8952,6 +9176,7 @@ This indicates a bug inside LDK. Please report this error at https://github.com/ Ok(()) } + #[rustfmt::skip] fn internal_update_fail_htlc(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateFailHTLC) -> Result<(), MsgHandleErrInternal> { // Note that the ChannelManager is NOT re-persisted on disk after this (unless we error // closing a channel), so any changes are likely to be lost on restart! @@ -8977,6 +9202,7 @@ This indicates a bug inside LDK. Please report this error at https://github.com/ Ok(()) } + #[rustfmt::skip] fn internal_update_fail_malformed_htlc(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateFailMalformedHTLC) -> Result<(), MsgHandleErrInternal> { // Note that the ChannelManager is NOT re-persisted on disk after this (unless we error // closing a channel), so any changes are likely to be lost on restart! @@ -9006,6 +9232,7 @@ This indicates a bug inside LDK. Please report this error at https://github.com/ } } + #[rustfmt::skip] fn internal_commitment_signed(&self, counterparty_node_id: &PublicKey, msg: &msgs::CommitmentSigned) -> Result<(), MsgHandleErrInternal> { let best_block = *self.best_block.read().unwrap(); let per_peer_state = self.per_peer_state.read().unwrap(); @@ -9052,6 +9279,7 @@ This indicates a bug inside LDK. Please report this error at https://github.com/ } } + #[rustfmt::skip] fn internal_commitment_signed_batch(&self, counterparty_node_id: &PublicKey, channel_id: ChannelId, batch: &BTreeMap) -> Result<(), MsgHandleErrInternal> { let per_peer_state = self.per_peer_state.read().unwrap(); let peer_state_mutex = per_peer_state.get(counterparty_node_id) @@ -9084,6 +9312,7 @@ This indicates a bug inside LDK. Please report this error at https://github.com/ } } + #[rustfmt::skip] fn push_decode_update_add_htlcs(&self, mut update_add_htlcs: (u64, Vec)) { let mut push_forward_event = self.forward_htlcs.lock().unwrap().is_empty(); let mut decode_update_add_htlcs = self.decode_update_add_htlcs.lock().unwrap(); @@ -9097,12 +9326,14 @@ This indicates a bug inside LDK. Please report this error at https://github.com/ } #[inline] + #[rustfmt::skip] fn forward_htlcs(&self, per_source_pending_forwards: &mut [(u64, Option, OutPoint, ChannelId, u128, Vec<(PendingHTLCInfo, u64)>)]) { let push_forward_event = self.forward_htlcs_without_forward_event(per_source_pending_forwards); if push_forward_event { self.push_pending_forwards_ev() } } #[inline] + #[rustfmt::skip] fn forward_htlcs_without_forward_event(&self, per_source_pending_forwards: &mut [(u64, Option, OutPoint, ChannelId, u128, Vec<(PendingHTLCInfo, u64)>)]) -> bool { let mut push_forward_event = false; for &mut (prev_short_channel_id, prev_counterparty_node_id, prev_funding_outpoint, prev_channel_id, prev_user_channel_id, ref mut pending_forwards) in per_source_pending_forwards { @@ -9197,6 +9428,7 @@ This indicates a bug inside LDK. Please report this error at https://github.com/ push_forward_event } + #[rustfmt::skip] fn push_pending_forwards_ev(&self) { let mut pending_events = self.pending_events.lock().unwrap(); let is_processing_events = self.pending_events_processor.load(Ordering::Acquire); @@ -9220,6 +9452,7 @@ This indicates a bug inside LDK. Please report this error at https://github.com/ /// [`msgs::RevokeAndACK`] should be held for the given channel until some other action /// completes. Note that this needs to happen in the same [`PeerState`] mutex as any release of /// the [`ChannelMonitorUpdate`] in question. + #[rustfmt::skip] fn raa_monitor_updates_held(&self, actions_blocking_raa_monitor_updates: &BTreeMap>, channel_funding_outpoint: OutPoint, channel_id: ChannelId, counterparty_node_id: PublicKey @@ -9236,6 +9469,7 @@ This indicates a bug inside LDK. Please report this error at https://github.com/ } #[cfg(any(test, feature = "_test_utils"))] + #[rustfmt::skip] pub(crate) fn test_raa_monitor_updates_held(&self, counterparty_node_id: PublicKey, channel_id: ChannelId ) -> bool { @@ -9252,6 +9486,7 @@ This indicates a bug inside LDK. Please report this error at https://github.com/ false } + #[rustfmt::skip] fn internal_revoke_and_ack(&self, counterparty_node_id: &PublicKey, msg: &msgs::RevokeAndACK) -> Result<(), MsgHandleErrInternal> { let htlcs_to_fail = { let per_peer_state = self.per_peer_state.read().unwrap(); @@ -9292,6 +9527,7 @@ This indicates a bug inside LDK. Please report this error at https://github.com/ Ok(()) } + #[rustfmt::skip] fn internal_update_fee(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateFee) -> Result<(), MsgHandleErrInternal> { let per_peer_state = self.per_peer_state.read().unwrap(); let peer_state_mutex = per_peer_state.get(counterparty_node_id) @@ -9316,6 +9552,7 @@ This indicates a bug inside LDK. Please report this error at https://github.com/ Ok(()) } + #[rustfmt::skip] fn internal_stfu(&self, counterparty_node_id: &PublicKey, msg: &msgs::Stfu) -> Result { let per_peer_state = self.per_peer_state.read().unwrap(); let peer_state_mutex = per_peer_state.get(counterparty_node_id).ok_or_else(|| { @@ -9368,6 +9605,7 @@ This indicates a bug inside LDK. Please report this error at https://github.com/ Ok(sent_stfu) } + #[rustfmt::skip] fn internal_announcement_signatures(&self, counterparty_node_id: &PublicKey, msg: &msgs::AnnouncementSignatures) -> Result<(), MsgHandleErrInternal> { let per_peer_state = self.per_peer_state.read().unwrap(); let peer_state_mutex = per_peer_state.get(counterparty_node_id) @@ -9404,6 +9642,7 @@ This indicates a bug inside LDK. Please report this error at https://github.com/ } /// Returns DoPersist if anything changed, otherwise either SkipPersistNoEvents or an Err. + #[rustfmt::skip] fn internal_channel_update(&self, counterparty_node_id: &PublicKey, msg: &msgs::ChannelUpdate) -> Result { let (chan_counterparty_node_id, chan_id) = match self.short_to_chan_info.read().unwrap().get(&msg.contents.short_channel_id) { Some((cp_id, chan_id)) => (cp_id.clone(), chan_id.clone()), @@ -9455,6 +9694,7 @@ This indicates a bug inside LDK. Please report this error at https://github.com/ Ok(NotifyOption::DoPersist) } + #[rustfmt::skip] fn internal_channel_reestablish(&self, counterparty_node_id: &PublicKey, msg: &msgs::ChannelReestablish) -> Result { let need_lnd_workaround = { let per_peer_state = self.per_peer_state.read().unwrap(); @@ -9557,6 +9797,7 @@ This indicates a bug inside LDK. Please report this error at https://github.com/ /// Handle incoming splice request, transition channel to splice-pending (unless some check fails). #[cfg(splicing)] + #[rustfmt::skip] fn internal_splice_init(&self, counterparty_node_id: &PublicKey, msg: &msgs::SpliceInit) -> Result<(), MsgHandleErrInternal> { let per_peer_state = self.per_peer_state.read().unwrap(); let peer_state_mutex = per_peer_state.get(counterparty_node_id) @@ -9596,6 +9837,7 @@ This indicates a bug inside LDK. Please report this error at https://github.com/ /// Handle incoming splice request ack, transition channel to splice-pending (unless some check fails). #[cfg(splicing)] + #[rustfmt::skip] fn internal_splice_ack(&self, counterparty_node_id: &PublicKey, msg: &msgs::SpliceAck) -> Result<(), MsgHandleErrInternal> { let per_peer_state = self.per_peer_state.read().unwrap(); let peer_state_mutex = per_peer_state.get(counterparty_node_id) @@ -9631,6 +9873,7 @@ This indicates a bug inside LDK. Please report this error at https://github.com/ } /// Process pending events from the [`chain::Watch`], returning whether any events were processed. + #[rustfmt::skip] fn process_pending_monitor_events(&self) -> bool { debug_assert!(self.total_consistency_lock.try_write().is_err()); // Caller holds read lock @@ -9718,6 +9961,7 @@ This indicates a bug inside LDK. Please report this error at https://github.com/ /// Check the holding cell in each channel and free any pending HTLCs in them if possible. /// Returns whether there were any updates such as if pending HTLCs were freed or a monitor /// update was applied. + #[rustfmt::skip] fn check_free_holding_cells(&self) -> bool { let mut has_monitor_update = false; let mut failed_htlcs = Vec::new(); @@ -9772,6 +10016,7 @@ This indicates a bug inside LDK. Please report this error at https://github.com/ /// attempted in every channel, or in the specifically provided channel. /// /// [`ChannelSigner`]: crate::sign::ChannelSigner + #[rustfmt::skip] pub fn signer_unblocked(&self, channel_opt: Option<(PublicKey, ChannelId)>) { let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self); @@ -9894,6 +10139,7 @@ This indicates a bug inside LDK. Please report this error at https://github.com/ /// Check whether any channels have finished removing all pending updates after a shutdown /// exchange and can now send a closing_signed. /// Returns whether any closing_signed messages were generated. + #[rustfmt::skip] fn maybe_generate_initial_closing_signed(&self) -> bool { let mut handle_errors: Vec<(PublicKey, Result<(), _>)> = Vec::new(); let mut has_update = false; @@ -9962,6 +10208,7 @@ This indicates a bug inside LDK. Please report this error at https://github.com/ has_update } + #[rustfmt::skip] fn maybe_send_stfu(&self) { let per_peer_state = self.per_peer_state.read().unwrap(); for (counterparty_node_id, peer_state_mutex) in per_peer_state.iter() { @@ -9991,6 +10238,7 @@ This indicates a bug inside LDK. Please report this error at https://github.com/ } #[cfg(any(test, fuzzing))] + #[rustfmt::skip] pub fn maybe_propose_quiescence(&self, counterparty_node_id: &PublicKey, channel_id: &ChannelId) -> Result<(), APIError> { let mut result = Ok(()); PersistenceNotifierGuard::optionally_notify(self, || { @@ -10049,6 +10297,7 @@ This indicates a bug inside LDK. Please report this error at https://github.com/ } #[cfg(any(test, fuzzing))] + #[rustfmt::skip] pub fn exit_quiescence(&self, counterparty_node_id: &PublicKey, channel_id: &ChannelId) -> Result { let per_peer_state = self.per_peer_state.read().unwrap(); let peer_state_mutex = per_peer_state.get(counterparty_node_id) @@ -10078,6 +10327,7 @@ This indicates a bug inside LDK. Please report this error at https://github.com/ /// storing any additional state. It achieves this by including a [`PaymentSecret`] in the /// invoice which it uses to verify that the invoice has not expired and the payment amount is /// sufficient, reproducing the [`PaymentPreimage`] if applicable. + #[rustfmt::skip] pub fn create_bolt11_invoice( &self, params: Bolt11InvoiceParameters, ) -> Result> { @@ -10358,7 +10608,17 @@ macro_rules! create_refund_builder { ($self: ident, $builder: ty) => { /// even if multiple invoices are received. const OFFERS_MESSAGE_REQUEST_LIMIT: usize = 10; -impl ChannelManager +impl< + M: Deref, + T: Deref, + ES: Deref, + NS: Deref, + SP: Deref, + F: Deref, + R: Deref, + MR: Deref, + L: Deref, + > ChannelManager where M::Target: chain::Watch<::EcdsaSigner>, T::Target: BroadcasterInterface, @@ -10389,6 +10649,7 @@ where /// [`Offer`] plus the returned [`Nonce`], and provide the static invoice to the /// aforementioned always-online node. #[cfg(async_payments)] + #[rustfmt::skip] pub fn create_async_receive_offer_builder( &self, message_paths_to_always_online_node: Vec ) -> Result<(OfferBuilder, Nonce), Bolt12SemanticError> { @@ -10417,6 +10678,7 @@ where /// created via [`Self::create_async_receive_offer_builder`]. If `relative_expiry` is unset, the /// invoice's expiry will default to [`STATIC_INVOICE_DEFAULT_RELATIVE_EXPIRY`]. #[cfg(async_payments)] + #[rustfmt::skip] pub fn create_static_invoice_builder<'a>( &self, offer: &'a Offer, offer_nonce: Nonce, relative_expiry: Option ) -> Result, Bolt12SemanticError> { @@ -10516,6 +10778,7 @@ where /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice /// [`Bolt12Invoice::payment_paths`]: crate::offers::invoice::Bolt12Invoice::payment_paths /// [Avoiding Duplicate Payments]: #avoiding-duplicate-payments + #[rustfmt::skip] pub fn pay_for_offer( &self, offer: &Offer, quantity: Option, amount_msats: Option, payer_note: Option, payment_id: PaymentId, retry_strategy: Retry, @@ -10537,6 +10800,7 @@ where }) } + #[rustfmt::skip] fn pay_for_offer_intern Result<(), Bolt12SemanticError>>( &self, offer: &Offer, quantity: Option, amount_msats: Option, payer_note: Option, payment_id: PaymentId, @@ -10584,6 +10848,7 @@ where self.enqueue_invoice_request(invoice_request, reply_paths) } + #[rustfmt::skip] fn enqueue_invoice_request( &self, invoice_request: InvoiceRequest, @@ -10634,6 +10899,7 @@ where /// the invoice. /// /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice + #[rustfmt::skip] pub fn request_refund_payment( &self, refund: &Refund ) -> Result { @@ -10745,6 +11011,7 @@ where /// [`Bolt12Invoice::payment_paths`]: crate::offers::invoice::Bolt12Invoice::payment_paths /// [Avoiding Duplicate Payments]: #avoiding-duplicate-payments #[cfg(feature = "dnssec")] + #[rustfmt::skip] pub fn pay_for_offer_from_human_readable_name( &self, name: HumanReadableName, amount_msats: u64, payment_id: PaymentId, retry_strategy: Retry, route_params_config: RouteParametersConfig, @@ -10801,6 +11068,7 @@ where /// [`PaymentClaimable::purpose`]: events::Event::PaymentClaimable::purpose /// [`PaymentPurpose::preimage`]: events::PaymentPurpose::preimage /// [`create_inbound_payment_for_hash`]: Self::create_inbound_payment_for_hash + #[rustfmt::skip] pub fn create_inbound_payment(&self, min_value_msat: Option, invoice_expiry_delta_secs: u32, min_final_cltv_expiry_delta: Option) -> Result<(PaymentHash, PaymentSecret), ()> { inbound_payment::create(&self.inbound_payment_key, min_value_msat, invoice_expiry_delta_secs, @@ -10854,6 +11122,7 @@ where /// /// [`create_inbound_payment`]: Self::create_inbound_payment /// [`PaymentClaimable`]: events::Event::PaymentClaimable + #[rustfmt::skip] pub fn create_inbound_payment_for_hash(&self, payment_hash: PaymentHash, min_value_msat: Option, invoice_expiry_delta_secs: u32, min_final_cltv_expiry: Option) -> Result { inbound_payment::create_from_hash(&self.inbound_payment_key, min_value_msat, payment_hash, @@ -10865,6 +11134,7 @@ where /// previously returned from [`create_inbound_payment`]. /// /// [`create_inbound_payment`]: Self::create_inbound_payment + #[rustfmt::skip] pub fn get_payment_preimage(&self, payment_hash: PaymentHash, payment_secret: PaymentSecret) -> Result { inbound_payment::get_payment_preimage(payment_hash, payment_secret, &self.inbound_payment_key) } @@ -10888,6 +11158,7 @@ where } } + #[rustfmt::skip] pub(super) fn duration_since_epoch(&self) -> Duration { #[cfg(not(feature = "std"))] let now = Duration::from_secs( @@ -10905,6 +11176,7 @@ where /// [`MessageRouter::create_blinded_paths`]. /// /// Errors if the `MessageRouter` errors. + #[rustfmt::skip] fn create_blinded_paths(&self, context: MessageContext) -> Result, ()> { let recipient = self.get_our_node_id(); let secp_ctx = &self.secp_ctx; @@ -10926,6 +11198,7 @@ where /// [`MessageRouter::create_compact_blinded_paths`]. /// /// Errors if the `MessageRouter` errors. + #[rustfmt::skip] fn create_compact_blinded_paths(&self, context: OffersContext) -> Result, ()> { let recipient = self.get_our_node_id(); let secp_ctx = &self.secp_ctx; @@ -10952,6 +11225,7 @@ where /// Creates multi-hop blinded payment paths for the given `amount_msats` by delegating to /// [`Router::create_blinded_payment_paths`]. + #[rustfmt::skip] fn create_blinded_payment_paths( &self, amount_msats: Option, payment_secret: PaymentSecret, payment_context: PaymentContext, relative_expiry_seconds: u32 @@ -10987,6 +11261,7 @@ where } #[cfg(all(test, async_payments))] + #[rustfmt::skip] pub(super) fn test_create_blinded_payment_paths( &self, amount_msats: Option, payment_secret: PaymentSecret, payment_context: PaymentContext, relative_expiry_seconds: u32 @@ -11000,6 +11275,7 @@ where /// are used when constructing the phantom invoice's route hints. /// /// [phantom node payments]: crate::sign::PhantomKeysManager + #[rustfmt::skip] pub fn get_phantom_scid(&self) -> u64 { let best_block_height = self.best_block.read().unwrap().height; let short_to_chan_info = self.short_to_chan_info.read().unwrap(); @@ -11030,6 +11306,7 @@ where /// /// Note that this method is not guaranteed to return unique values, you may need to call it a few /// times to get a unique scid. + #[rustfmt::skip] pub fn get_intercept_scid(&self) -> u64 { let best_block_height = self.best_block.read().unwrap().height; let short_to_chan_info = self.short_to_chan_info.read().unwrap(); @@ -11063,6 +11340,7 @@ where } #[cfg(any(test, feature = "_test_utils"))] + #[rustfmt::skip] pub fn get_and_clear_pending_events(&self) -> Vec { let events = core::cell::RefCell::new(Vec::new()); let event_handler = |event: events::Event| Ok(events.borrow_mut().push(event)); @@ -11130,6 +11408,7 @@ where /// [`Event`] being handled) completes, this should be called to restore the channel to normal /// operation. It will double-check that nothing *else* is also blocking the same channel from /// making progress and then let any blocked [`ChannelMonitorUpdate`]s fly. + #[rustfmt::skip] fn handle_monitor_update_release(&self, counterparty_node_id: PublicKey, channel_funding_outpoint: OutPoint, channel_id: ChannelId, mut completed_blocker: Option) { @@ -11190,6 +11469,7 @@ where } } + #[rustfmt::skip] fn handle_post_event_actions(&self, actions: Vec) { for action in actions { match action { @@ -11206,15 +11486,28 @@ where /// using the given event handler. /// /// See the trait-level documentation of [`EventsProvider`] for requirements. - pub async fn process_pending_events_async>, H: Fn(Event) -> Future>( - &self, handler: H + pub async fn process_pending_events_async< + Future: core::future::Future>, + H: Fn(Event) -> Future, + >( + &self, handler: H, ) { let mut ev; process_events_body!(self, ev, { handler(ev).await }); } } -impl BaseMessageHandler for ChannelManager +impl< + M: Deref, + T: Deref, + ES: Deref, + NS: Deref, + SP: Deref, + F: Deref, + R: Deref, + MR: Deref, + L: Deref, + > BaseMessageHandler for ChannelManager where M::Target: chain::Watch<::EcdsaSigner>, T::Target: BroadcasterInterface, @@ -11234,6 +11527,7 @@ where provided_init_features(&self.default_configuration) } + #[rustfmt::skip] fn peer_disconnected(&self, counterparty_node_id: PublicKey) { let _persistence_guard = PersistenceNotifierGuard::optionally_notify( self, || NotifyOption::SkipPersistHandleEvents); @@ -11336,6 +11630,7 @@ where } } + #[rustfmt::skip] fn peer_connected(&self, counterparty_node_id: PublicKey, init_msg: &msgs::Init, inbound: bool) -> Result<(), ()> { let logger = WithContext::from(&self.logger, Some(counterparty_node_id), None, None); if !init_msg.features.supports_static_remote_key() { @@ -11503,7 +11798,17 @@ where } } -impl EventsProvider for ChannelManager +impl< + M: Deref, + T: Deref, + ES: Deref, + NS: Deref, + SP: Deref, + F: Deref, + R: Deref, + MR: Deref, + L: Deref, + > EventsProvider for ChannelManager where M::Target: chain::Watch<::EcdsaSigner>, T::Target: BroadcasterInterface, @@ -11519,13 +11824,26 @@ where /// /// An [`EventHandler`] may safely call back to the provider in order to handle an event. /// However, it must not call [`Writeable::write`] as doing so would result in a deadlock. - fn process_pending_events(&self, handler: H) where H::Target: EventHandler { + fn process_pending_events(&self, handler: H) + where + H::Target: EventHandler, + { let mut ev; process_events_body!(self, ev, handler.handle_event(ev)); } } -impl chain::Listen for ChannelManager +impl< + M: Deref, + T: Deref, + ES: Deref, + NS: Deref, + SP: Deref, + F: Deref, + R: Deref, + MR: Deref, + L: Deref, + > chain::Listen for ChannelManager where M::Target: chain::Watch<::EcdsaSigner>, T::Target: BroadcasterInterface, @@ -11550,6 +11868,7 @@ where self.best_block_updated(header, height); } + #[rustfmt::skip] fn block_disconnected(&self, header: &Header, height: u32) { let _persistence_guard = PersistenceNotifierGuard::optionally_notify_skipping_background_events( @@ -11568,7 +11887,17 @@ where } } -impl chain::Confirm for ChannelManager +impl< + M: Deref, + T: Deref, + ES: Deref, + NS: Deref, + SP: Deref, + F: Deref, + R: Deref, + MR: Deref, + L: Deref, + > chain::Confirm for ChannelManager where M::Target: chain::Watch<::EcdsaSigner>, T::Target: BroadcasterInterface, @@ -11580,6 +11909,7 @@ where MR::Target: MessageRouter, L::Target: Logger, { + #[rustfmt::skip] fn transactions_confirmed(&self, header: &Header, txdata: &TransactionData, height: u32) { // Note that we MUST NOT end up calling methods on self.chain_monitor here - we're called // during initialization prior to the chain_monitor being fully configured in some cases. @@ -11601,6 +11931,7 @@ where } } + #[rustfmt::skip] fn best_block_updated(&self, header: &Header, height: u32) { // Note that we MUST NOT end up calling methods on self.chain_monitor here - we're called // during initialization prior to the chain_monitor being fully configured in some cases. @@ -11647,6 +11978,7 @@ where channel.best_block_updated(height, header.time, self.chain_hash, &self.node_signer, &self.default_configuration, &&WithChannelContext::from(&self.logger, &channel.context, None)) }); + #[rustfmt::skip] macro_rules! max_time { ($timestamp: expr) => { loop { @@ -11670,6 +12002,7 @@ where } } + #[rustfmt::skip] fn get_relevant_txids(&self) -> Vec<(Txid, u32, Option)> { let mut res = Vec::with_capacity(self.short_to_chan_info.read().unwrap().len()); for (_cp_id, peer_state_mutex) in self.per_peer_state.read().unwrap().iter() { @@ -11687,6 +12020,7 @@ where res } + #[rustfmt::skip] fn transaction_unconfirmed(&self, txid: &Txid) { let _persistence_guard = PersistenceNotifierGuard::optionally_notify_skipping_background_events( @@ -11701,7 +12035,17 @@ where } } -impl ChannelManager +impl< + M: Deref, + T: Deref, + ES: Deref, + NS: Deref, + SP: Deref, + F: Deref, + R: Deref, + MR: Deref, + L: Deref, + > ChannelManager where M::Target: chain::Watch<::EcdsaSigner>, T::Target: BroadcasterInterface, @@ -11716,6 +12060,7 @@ where /// Calls a function which handles an on-chain event (blocks dis/connected, transactions /// un/confirmed, etc) on each channel, handling any resulting errors or messages generated by /// the function. + #[rustfmt::skip] fn do_chain_event) -> Result<(Option, Vec<(HTLCSource, PaymentHash)>, Option), ClosureReason>> (&self, height_opt: Option, f: FN) { // Note that we MUST NOT end up calling methods on self.chain_monitor here - we're called @@ -11984,8 +12329,17 @@ where } } -impl - ChannelMessageHandler for ChannelManager +impl< + M: Deref, + T: Deref, + ES: Deref, + NS: Deref, + SP: Deref, + F: Deref, + R: Deref, + MR: Deref, + L: Deref, + > ChannelMessageHandler for ChannelManager where M::Target: chain::Watch<::EcdsaSigner>, T::Target: BroadcasterInterface, @@ -11997,6 +12351,7 @@ where MR::Target: MessageRouter, L::Target: Logger, { + #[rustfmt::skip] fn handle_open_channel(&self, counterparty_node_id: PublicKey, msg: &msgs::OpenChannel) { // Note that we never need to persist the updated ChannelManager for an inbound // open_channel message - pre-funded channels are never written so there should be no @@ -12015,6 +12370,7 @@ where }); } + #[rustfmt::skip] fn handle_open_channel_v2(&self, counterparty_node_id: PublicKey, msg: &msgs::OpenChannelV2) { if !self.init_features().supports_dual_fund() { let _: Result<(), _> = handle_error!(self, Err(MsgHandleErrInternal::send_err_msg_no_close( @@ -12039,6 +12395,7 @@ where }); } + #[rustfmt::skip] fn handle_accept_channel(&self, counterparty_node_id: PublicKey, msg: &msgs::AcceptChannel) { // Note that we never need to persist the updated ChannelManager for an inbound // accept_channel message - pre-funded channels are never written so there should be no @@ -12049,27 +12406,32 @@ where }); } + #[rustfmt::skip] fn handle_accept_channel_v2(&self, counterparty_node_id: PublicKey, msg: &msgs::AcceptChannelV2) { let _: Result<(), _> = handle_error!(self, Err(MsgHandleErrInternal::send_err_msg_no_close( "Dual-funded channels not supported".to_owned(), msg.common_fields.temporary_channel_id.clone())), counterparty_node_id); } + #[rustfmt::skip] fn handle_funding_created(&self, counterparty_node_id: PublicKey, msg: &msgs::FundingCreated) { let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self); let _ = handle_error!(self, self.internal_funding_created(&counterparty_node_id, msg), counterparty_node_id); } + #[rustfmt::skip] fn handle_funding_signed(&self, counterparty_node_id: PublicKey, msg: &msgs::FundingSigned) { let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self); let _ = handle_error!(self, self.internal_funding_signed(&counterparty_node_id, msg), counterparty_node_id); } + #[rustfmt::skip] fn handle_peer_storage(&self, counterparty_node_id: PublicKey, msg: msgs::PeerStorage) { let _persistence_guard = PersistenceNotifierGuard::optionally_notify(self, || NotifyOption::SkipPersistNoEvents); let _ = handle_error!(self, self.internal_peer_storage(counterparty_node_id, msg), counterparty_node_id); } + #[rustfmt::skip] fn handle_peer_storage_retrieval(&self, counterparty_node_id: PublicKey, msg: msgs::PeerStorageRetrieval) { let _persistence_guard = PersistenceNotifierGuard::optionally_notify(self, || NotifyOption::SkipPersistNoEvents); let _ = handle_error!(self, self.internal_peer_storage_retrieval(counterparty_node_id, msg), counterparty_node_id); @@ -12091,6 +12453,7 @@ where }); } + #[rustfmt::skip] fn handle_stfu(&self, counterparty_node_id: PublicKey, msg: &msgs::Stfu) { let _persistence_guard = PersistenceNotifierGuard::optionally_notify(self, || { let res = self.internal_stfu(&counterparty_node_id, msg); @@ -12137,17 +12500,20 @@ where } #[cfg(splicing)] + #[rustfmt::skip] fn handle_splice_locked(&self, counterparty_node_id: PublicKey, msg: &msgs::SpliceLocked) { let _: Result<(), _> = handle_error!(self, Err(MsgHandleErrInternal::send_err_msg_no_close( "Splicing not supported (splice_locked)".to_owned(), msg.channel_id)), counterparty_node_id); } + #[rustfmt::skip] fn handle_shutdown(&self, counterparty_node_id: PublicKey, msg: &msgs::Shutdown) { let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self); let _ = handle_error!(self, self.internal_shutdown(&counterparty_node_id, msg), counterparty_node_id); } + #[rustfmt::skip] fn handle_closing_signed(&self, counterparty_node_id: PublicKey, msg: &msgs::ClosingSigned) { let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self); let _ = handle_error!(self, self.internal_closing_signed(&counterparty_node_id, msg), counterparty_node_id); @@ -12169,6 +12535,7 @@ where }); } + #[rustfmt::skip] fn handle_update_fulfill_htlc(&self, counterparty_node_id: PublicKey, msg: &msgs::UpdateFulfillHTLC) { let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self); let _ = handle_error!(self, self.internal_update_fulfill_htlc(&counterparty_node_id, msg), counterparty_node_id); @@ -12190,7 +12557,9 @@ where }); } - fn handle_update_fail_malformed_htlc(&self, counterparty_node_id: PublicKey, msg: &msgs::UpdateFailMalformedHTLC) { + fn handle_update_fail_malformed_htlc( + &self, counterparty_node_id: PublicKey, msg: &msgs::UpdateFailMalformedHTLC, + ) { // Note that we never need to persist the updated ChannelManager for an inbound // update_fail_malformed_htlc message - the message itself doesn't change our channel state // only the `commitment_signed` message afterwards will. @@ -12206,16 +12575,19 @@ where }); } + #[rustfmt::skip] fn handle_commitment_signed(&self, counterparty_node_id: PublicKey, msg: &msgs::CommitmentSigned) { let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self); let _ = handle_error!(self, self.internal_commitment_signed(&counterparty_node_id, msg), counterparty_node_id); } + #[rustfmt::skip] fn handle_commitment_signed_batch(&self, counterparty_node_id: PublicKey, channel_id: ChannelId, batch: BTreeMap) { let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self); let _ = handle_error!(self, self.internal_commitment_signed_batch(&counterparty_node_id, channel_id, &batch), counterparty_node_id); } + #[rustfmt::skip] fn handle_revoke_and_ack(&self, counterparty_node_id: PublicKey, msg: &msgs::RevokeAndACK) { let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self); let _ = handle_error!(self, self.internal_revoke_and_ack(&counterparty_node_id, msg), counterparty_node_id); @@ -12237,11 +12609,13 @@ where }); } + #[rustfmt::skip] fn handle_announcement_signatures(&self, counterparty_node_id: PublicKey, msg: &msgs::AnnouncementSignatures) { let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self); let _ = handle_error!(self, self.internal_announcement_signatures(&counterparty_node_id, msg), counterparty_node_id); } + #[rustfmt::skip] fn handle_channel_update(&self, counterparty_node_id: PublicKey, msg: &msgs::ChannelUpdate) { PersistenceNotifierGuard::optionally_notify(self, || { if let Ok(persist) = handle_error!(self, self.internal_channel_update(&counterparty_node_id, msg), counterparty_node_id) { @@ -12252,7 +12626,9 @@ where }); } - fn handle_channel_reestablish(&self, counterparty_node_id: PublicKey, msg: &msgs::ChannelReestablish) { + fn handle_channel_reestablish( + &self, counterparty_node_id: PublicKey, msg: &msgs::ChannelReestablish, + ) { let _persistence_guard = PersistenceNotifierGuard::optionally_notify(self, || { let res = self.internal_channel_reestablish(&counterparty_node_id, msg); let persist = match &res { @@ -12265,6 +12641,7 @@ where }); } + #[rustfmt::skip] fn handle_error(&self, counterparty_node_id: PublicKey, msg: &msgs::ErrorMessage) { match &msg.data as &str { "cannot co-op close channel w/ active htlcs"| @@ -12377,6 +12754,7 @@ where Some(vec![self.chain_hash]) } + #[rustfmt::skip] fn handle_tx_add_input(&self, counterparty_node_id: PublicKey, msg: &msgs::TxAddInput) { // Note that we never need to persist the updated ChannelManager for an inbound // tx_add_input message - interactive transaction construction does not need to @@ -12387,6 +12765,7 @@ where }); } + #[rustfmt::skip] fn handle_tx_add_output(&self, counterparty_node_id: PublicKey, msg: &msgs::TxAddOutput) { // Note that we never need to persist the updated ChannelManager for an inbound // tx_add_output message - interactive transaction construction does not need to @@ -12397,6 +12776,7 @@ where }); } + #[rustfmt::skip] fn handle_tx_remove_input(&self, counterparty_node_id: PublicKey, msg: &msgs::TxRemoveInput) { // Note that we never need to persist the updated ChannelManager for an inbound // tx_remove_input message - interactive transaction construction does not need to @@ -12407,6 +12787,7 @@ where }); } + #[rustfmt::skip] fn handle_tx_remove_output(&self, counterparty_node_id: PublicKey, msg: &msgs::TxRemoveOutput) { // Note that we never need to persist the updated ChannelManager for an inbound // tx_remove_output message - interactive transaction construction does not need to @@ -12417,6 +12798,7 @@ where }); } + #[rustfmt::skip] fn handle_tx_complete(&self, counterparty_node_id: PublicKey, msg: &msgs::TxComplete) { // Note that we never need to persist the updated ChannelManager for an inbound // tx_complete message - interactive transaction construction does not need to @@ -12427,23 +12809,27 @@ where }); } + #[rustfmt::skip] fn handle_tx_signatures(&self, counterparty_node_id: PublicKey, msg: &msgs::TxSignatures) { let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self); let _ = handle_error!(self, self.internal_tx_signatures(&counterparty_node_id, msg), counterparty_node_id); } + #[rustfmt::skip] fn handle_tx_init_rbf(&self, counterparty_node_id: PublicKey, msg: &msgs::TxInitRbf) { let _: Result<(), _> = handle_error!(self, Err(MsgHandleErrInternal::send_err_msg_no_close( "Dual-funded channels not supported".to_owned(), msg.channel_id.clone())), counterparty_node_id); } + #[rustfmt::skip] fn handle_tx_ack_rbf(&self, counterparty_node_id: PublicKey, msg: &msgs::TxAckRbf) { let _: Result<(), _> = handle_error!(self, Err(MsgHandleErrInternal::send_err_msg_no_close( "Dual-funded channels not supported".to_owned(), msg.channel_id.clone())), counterparty_node_id); } + #[rustfmt::skip] fn handle_tx_abort(&self, counterparty_node_id: PublicKey, msg: &msgs::TxAbort) { // Note that we never need to persist the updated ChannelManager for an inbound // tx_abort message - interactive transaction construction does not need to @@ -12454,6 +12840,7 @@ where }); } + #[rustfmt::skip] fn message_received(&self) { for (payment_id, retryable_invoice_request) in self .pending_outbound_payments @@ -12488,8 +12875,17 @@ where } } -impl -OffersMessageHandler for ChannelManager +impl< + M: Deref, + T: Deref, + ES: Deref, + NS: Deref, + SP: Deref, + F: Deref, + R: Deref, + MR: Deref, + L: Deref, + > OffersMessageHandler for ChannelManager where M::Target: chain::Watch<::EcdsaSigner>, T::Target: BroadcasterInterface, @@ -12507,6 +12903,7 @@ where let secp_ctx = &self.secp_ctx; let expanded_key = &self.inbound_payment_key; + #[rustfmt::skip] macro_rules! handle_pay_invoice_res { ($res: expr, $invoice: expr, $logger: expr) => {{ let error = match $res { @@ -12557,7 +12954,9 @@ where let invoice_request = match nonce { Some(nonce) => match invoice_request.verify_using_recipient_data( - nonce, expanded_key, secp_ctx, + nonce, + expanded_key, + secp_ctx, ) { Ok(invoice_request) => invoice_request, Err(()) => return None, @@ -12569,50 +12968,61 @@ where }; let amount_msats = match InvoiceBuilder::::amount_msats( - &invoice_request.inner + &invoice_request.inner, ) { Ok(amount_msats) => amount_msats, - Err(error) => return Some((OffersMessage::InvoiceError(error.into()), responder.respond())), + Err(error) => { + return Some(( + OffersMessage::InvoiceError(error.into()), + responder.respond(), + )) + }, }; let relative_expiry = DEFAULT_RELATIVE_EXPIRY.as_secs() as u32; - let (payment_hash, payment_secret) = match self.create_inbound_payment( - Some(amount_msats), relative_expiry, None - ) { - Ok((payment_hash, payment_secret)) => (payment_hash, payment_secret), - Err(()) => { - let error = Bolt12SemanticError::InvalidAmount; - return Some((OffersMessage::InvoiceError(error.into()), responder.respond())); - }, - }; + let (payment_hash, payment_secret) = + match self.create_inbound_payment(Some(amount_msats), relative_expiry, None) { + Ok((payment_hash, payment_secret)) => (payment_hash, payment_secret), + Err(()) => { + let error = Bolt12SemanticError::InvalidAmount; + return Some(( + OffersMessage::InvoiceError(error.into()), + responder.respond(), + )); + }, + }; let payment_context = PaymentContext::Bolt12Offer(Bolt12OfferContext { offer_id: invoice_request.offer_id, invoice_request: invoice_request.fields(), }); let payment_paths = match self.create_blinded_payment_paths( - Some(amount_msats), payment_secret, payment_context, relative_expiry + Some(amount_msats), + payment_secret, + payment_context, + relative_expiry, ) { Ok(payment_paths) => payment_paths, Err(()) => { let error = Bolt12SemanticError::MissingPaths; - return Some((OffersMessage::InvoiceError(error.into()), responder.respond())); + return Some(( + OffersMessage::InvoiceError(error.into()), + responder.respond(), + )); }, }; #[cfg(not(feature = "std"))] - let created_at = Duration::from_secs( - self.highest_seen_timestamp.load(Ordering::Acquire) as u64 - ); + let created_at = Duration::from_secs(self.highest_seen_timestamp.load(Ordering::Acquire) as u64); let response = if invoice_request.keys.is_some() { #[cfg(feature = "std")] - let builder = invoice_request.respond_using_derived_keys( - payment_paths, payment_hash - ); + let builder = invoice_request.respond_using_derived_keys(payment_paths, payment_hash); #[cfg(not(feature = "std"))] let builder = invoice_request.respond_using_derived_keys_no_std( - payment_paths, payment_hash, created_at + payment_paths, + payment_hash, + created_at, ); builder .map(InvoiceBuilder::::from) @@ -12622,9 +13032,7 @@ where #[cfg(feature = "std")] let builder = invoice_request.respond_with(payment_paths, payment_hash); #[cfg(not(feature = "std"))] - let builder = invoice_request.respond_with_no_std( - payment_paths, payment_hash, created_at - ); + let builder = invoice_request.respond_with_no_std(payment_paths, payment_hash, created_at); builder .map(InvoiceBuilder::::from) .and_then(|builder| builder.allow_mpp().build()) @@ -12633,9 +13041,9 @@ where #[cfg(c_bindings)] let mut invoice = invoice; invoice - .sign(|invoice: &UnsignedBolt12Invoice| + .sign(|invoice: &UnsignedBolt12Invoice| { self.node_signer.sign_bolt12_invoice(invoice) - ) + }) .map_err(InvoiceError::from) }) }; @@ -12644,10 +13052,19 @@ where Ok(invoice) => { let nonce = Nonce::from_entropy_source(&*self.entropy_source); let hmac = payment_hash.hmac_for_offer_payment(nonce, expanded_key); - let context = MessageContext::Offers(OffersContext::InboundPayment { payment_hash, nonce, hmac }); - Some((OffersMessage::Invoice(invoice), responder.respond_with_reply_path(context))) + let context = MessageContext::Offers(OffersContext::InboundPayment { + payment_hash, + nonce, + hmac, + }); + Some(( + OffersMessage::Invoice(invoice), + responder.respond_with_reply_path(context), + )) + }, + Err(error) => { + Some((OffersMessage::InvoiceError(error.into()), responder.respond())) }, - Err(error) => Some((OffersMessage::InvoiceError(error.into()), responder.respond())), } }, OffersMessage::Invoice(invoice) => { @@ -12656,19 +13073,18 @@ where Err(()) => return None, }; - let logger = WithContext::from( - &self.logger, None, None, Some(invoice.payment_hash()), - ); + let logger = + WithContext::from(&self.logger, None, None, Some(invoice.payment_hash())); if self.default_configuration.manually_handle_bolt12_invoices { // Update the corresponding entry in `PendingOutboundPayment` for this invoice. // This ensures that event generation remains idempotent in case we receive // the same invoice multiple times. - self.pending_outbound_payments.mark_invoice_received(&invoice, payment_id).ok()?; + self.pending_outbound_payments + .mark_invoice_received(&invoice, payment_id) + .ok()?; - let event = Event::InvoiceReceived { - payment_id, invoice, context, responder, - }; + let event = Event::InvoiceReceived { payment_id, invoice, context, responder }; self.pending_events.lock().unwrap().push_back((event, None)); return None; } @@ -12679,13 +13095,17 @@ where #[cfg(async_payments)] OffersMessage::StaticInvoice(invoice) => { let payment_id = match context { - Some(OffersContext::OutboundPayment { payment_id, nonce, hmac: Some(hmac) }) => { + Some(OffersContext::OutboundPayment { + payment_id, + nonce, + hmac: Some(hmac), + }) => { if payment_id.verify_for_offer_payment(hmac, nonce, expanded_key).is_err() { - return None + return None; } payment_id }, - _ => return None + _ => return None, }; let res = self.initiate_async_payment(&invoice, payment_id); handle_pay_invoice_res!(res, invoice, self.logger); @@ -12705,10 +13125,17 @@ where log_trace!(logger, "Received invoice_error: {}", invoice_error); match context { - Some(OffersContext::OutboundPayment { payment_id, nonce, hmac: Some(hmac) }) => { - if let Ok(()) = payment_id.verify_for_offer_payment(hmac, nonce, expanded_key) { + Some(OffersContext::OutboundPayment { + payment_id, + nonce, + hmac: Some(hmac), + }) => { + if let Ok(()) = + payment_id.verify_for_offer_payment(hmac, nonce, expanded_key) + { self.abandon_payment_with_reason( - payment_id, PaymentFailureReason::InvoiceRequestRejected, + payment_id, + PaymentFailureReason::InvoiceRequestRejected, ); } }, @@ -12725,8 +13152,17 @@ where } } -impl -AsyncPaymentsMessageHandler for ChannelManager +impl< + M: Deref, + T: Deref, + ES: Deref, + NS: Deref, + SP: Deref, + F: Deref, + R: Deref, + MR: Deref, + L: Deref, + > AsyncPaymentsMessageHandler for ChannelManager where M::Target: chain::Watch<::EcdsaSigner>, T::Target: BroadcasterInterface, @@ -12738,6 +13174,7 @@ where MR::Target: MessageRouter, L::Target: Logger, { + #[rustfmt::skip] fn handle_held_htlc_available( &self, _message: HeldHtlcAvailable, _context: AsyncPaymentsContext, _responder: Option @@ -12758,6 +13195,7 @@ where return None } + #[rustfmt::skip] fn handle_release_held_htlc(&self, _message: ReleaseHeldHtlc, _context: AsyncPaymentsContext) { #[cfg(async_payments)] { let (payment_id, nonce, hmac) = match _context { @@ -12781,8 +13219,17 @@ where } #[cfg(feature = "dnssec")] -impl -DNSResolverMessageHandler for ChannelManager +impl< + M: Deref, + T: Deref, + ES: Deref, + NS: Deref, + SP: Deref, + F: Deref, + R: Deref, + MR: Deref, + L: Deref, + > DNSResolverMessageHandler for ChannelManager where M::Target: chain::Watch<::EcdsaSigner>, T::Target: BroadcasterInterface, @@ -12800,6 +13247,7 @@ where None } + #[rustfmt::skip] fn handle_dnssec_proof(&self, message: DNSSECProof, context: DNSResolverContext) { let offer_opt = self.hrn_resolver.handle_dnssec_proof_for_offer(message, context); #[cfg_attr(not(feature = "_test_utils"), allow(unused_mut))] @@ -12844,8 +13292,17 @@ where } } -impl -NodeIdLookUp for ChannelManager +impl< + M: Deref, + T: Deref, + ES: Deref, + NS: Deref, + SP: Deref, + F: Deref, + R: Deref, + MR: Deref, + L: Deref, + > NodeIdLookUp for ChannelManager where M::Target: chain::Watch<::EcdsaSigner>, T::Target: BroadcasterInterface, @@ -12862,6 +13319,7 @@ where } } +#[rustfmt::skip] fn enqueue_onion_message_with_reply_paths( message: T, message_paths: &[BlindedMessagePath], reply_paths: Vec, queue: &mut Vec<(T, MessageSendInstructions)> @@ -13013,8 +13471,8 @@ impl_writeable_tlv_based!(PendingHTLCInfo, { (10, skimmed_fee_msat, option), }); - impl Writeable for HTLCFailureMsg { + #[rustfmt::skip] fn write(&self, writer: &mut W) -> Result<(), io::Error> { match self { HTLCFailureMsg::Relay(msgs::UpdateFailHTLC { channel_id, htlc_id, reason, attribution_data }) => { @@ -13042,6 +13500,7 @@ impl Writeable for HTLCFailureMsg { } impl Readable for HTLCFailureMsg { + #[rustfmt::skip] fn read(reader: &mut R) -> Result { let id: u8 = Readable::read(reader)?; match id { @@ -13112,6 +13571,7 @@ impl_writeable_tlv_based!(HTLCPreviousHopData, { }); impl Writeable for ClaimableHTLC { + #[rustfmt::skip] fn write(&self, writer: &mut W) -> Result<(), io::Error> { let (payment_data, keysend_preimage) = match &self.onion_payload { OnionPayload::Invoice { _legacy_hop_data } => { @@ -13135,6 +13595,7 @@ impl Writeable for ClaimableHTLC { } impl Readable for ClaimableHTLC { + #[rustfmt::skip] fn read(reader: &mut R) -> Result { _init_and_read_len_prefixed_tlv_fields!(reader, { (0, prev_hop, required), @@ -13184,6 +13645,7 @@ impl Readable for ClaimableHTLC { } impl Readable for HTLCSource { + #[rustfmt::skip] fn read(reader: &mut R) -> Result { let id: u8 = Readable::read(reader)?; match id { @@ -13235,6 +13697,7 @@ impl Readable for HTLCSource { } impl Writeable for HTLCSource { + #[rustfmt::skip] fn write(&self, writer: &mut W) -> Result<(), crate::io::Error> { match self { HTLCSource::OutboundRoute { ref session_priv, ref first_hop_htlc_msat, ref path, payment_id, bolt12_invoice } => { @@ -13306,6 +13769,7 @@ impl Writeable for HTLCForwardInfo { } impl Readable for HTLCForwardInfo { + #[rustfmt::skip] fn read(r: &mut R) -> Result { let id: u8 = Readable::read(r)?; Ok(match id { @@ -13350,7 +13814,17 @@ impl_writeable_tlv_based!(PendingInboundPayment, { (8, min_value_msat, required), }); -impl Writeable for ChannelManager +impl< + M: Deref, + T: Deref, + ES: Deref, + NS: Deref, + SP: Deref, + F: Deref, + R: Deref, + MR: Deref, + L: Deref, + > Writeable for ChannelManager where M::Target: chain::Watch<::EcdsaSigner>, T::Target: BroadcasterInterface, @@ -13362,6 +13836,7 @@ where MR::Target: MessageRouter, L::Target: Logger, { + #[rustfmt::skip] fn write(&self, writer: &mut W) -> Result<(), io::Error> { let _consistency_lock = self.total_consistency_lock.write().unwrap(); @@ -13593,6 +14068,7 @@ where } impl Writeable for VecDeque<(Event, Option)> { + #[rustfmt::skip] fn write(&self, w: &mut W) -> Result<(), io::Error> { (self.len() as u64).write(w)?; for (event, action) in self.iter() { @@ -13614,6 +14090,7 @@ impl Writeable for VecDeque<(Event, Option)> { } } impl Readable for VecDeque<(Event, Option)> { + #[rustfmt::skip] fn read(reader: &mut R) -> Result { let len: u64 = Readable::read(reader)?; const MAX_ALLOC_SIZE: u64 = 1024 * 16; @@ -13668,8 +14145,18 @@ impl Readable for VecDeque<(Event, Option)> { /// which you've already broadcasted the transaction. /// /// [`ChainMonitor`]: crate::chain::chainmonitor::ChainMonitor -pub struct ChannelManagerReadArgs<'a, M: Deref, T: Deref, ES: Deref, NS: Deref, SP: Deref, F: Deref, R: Deref, MR: Deref, L: Deref> -where +pub struct ChannelManagerReadArgs< + 'a, + M: Deref, + T: Deref, + ES: Deref, + NS: Deref, + SP: Deref, + F: Deref, + R: Deref, + MR: Deref, + L: Deref, +> where M::Target: chain::Watch<::EcdsaSigner>, T::Target: BroadcasterInterface, ES::Target: EntropySource, @@ -13732,11 +14219,22 @@ where /// this struct. /// /// This is not exported to bindings users because we have no HashMap bindings - pub channel_monitors: HashMap::EcdsaSigner>>, + pub channel_monitors: + HashMap::EcdsaSigner>>, } -impl<'a, M: Deref, T: Deref, ES: Deref, NS: Deref, SP: Deref, F: Deref, R: Deref, MR: Deref, L: Deref> - ChannelManagerReadArgs<'a, M, T, ES, NS, SP, F, R, MR, L> +impl< + 'a, + M: Deref, + T: Deref, + ES: Deref, + NS: Deref, + SP: Deref, + F: Deref, + R: Deref, + MR: Deref, + L: Deref, + > ChannelManagerReadArgs<'a, M, T, ES, NS, SP, F, R, MR, L> where M::Target: chain::Watch<::EcdsaSigner>, T::Target: BroadcasterInterface, @@ -13751,6 +14249,7 @@ where /// Simple utility function to create a ChannelManagerReadArgs which creates the monitor /// HashMap for you. This is primarily useful for C bindings where it is not practical to /// populate a HashMap directly from C. + #[rustfmt::skip] pub fn new( entropy_source: ES, node_signer: NS, signer_provider: SP, fee_estimator: F, chain_monitor: M, tx_broadcaster: T, router: R, message_router: MR, logger: L, @@ -13769,8 +14268,19 @@ where // Implement ReadableArgs for an Arc'd ChannelManager to make it a bit easier to work with the // SipmleArcChannelManager type: -impl<'a, M: Deref, T: Deref, ES: Deref, NS: Deref, SP: Deref, F: Deref, R: Deref, MR: Deref, L: Deref> - ReadableArgs> for (BlockHash, Arc>) +impl< + 'a, + M: Deref, + T: Deref, + ES: Deref, + NS: Deref, + SP: Deref, + F: Deref, + R: Deref, + MR: Deref, + L: Deref, + > ReadableArgs> + for (BlockHash, Arc>) where M::Target: chain::Watch<::EcdsaSigner>, T::Target: BroadcasterInterface, @@ -13782,14 +14292,26 @@ where MR::Target: MessageRouter, L::Target: Logger, { + #[rustfmt::skip] fn read(reader: &mut Reader, args: ChannelManagerReadArgs<'a, M, T, ES, NS, SP, F, R, MR, L>) -> Result { let (blockhash, chan_manager) = <(BlockHash, ChannelManager)>::read(reader, args)?; Ok((blockhash, Arc::new(chan_manager))) } } -impl<'a, M: Deref, T: Deref, ES: Deref, NS: Deref, SP: Deref, F: Deref, R: Deref, MR: Deref, L: Deref> - ReadableArgs> for (BlockHash, ChannelManager) +impl< + 'a, + M: Deref, + T: Deref, + ES: Deref, + NS: Deref, + SP: Deref, + F: Deref, + R: Deref, + MR: Deref, + L: Deref, + > ReadableArgs> + for (BlockHash, ChannelManager) where M::Target: chain::Watch<::EcdsaSigner>, T::Target: BroadcasterInterface, @@ -13801,6 +14323,7 @@ where MR::Target: MessageRouter, L::Target: Logger, { + #[rustfmt::skip] fn read(reader: &mut Reader, mut args: ChannelManagerReadArgs<'a, M, T, ES, NS, SP, F, R, MR, L>) -> Result { let _ver = read_ver_prefix!(reader, SERIALIZATION_VERSION); @@ -14190,6 +14713,7 @@ where // // Because the actual handling of the in-flight updates is the same, it's macro'ized here: let mut pending_background_events = Vec::new(); + #[rustfmt::skip] macro_rules! handle_in_flight_updates { ($counterparty_node_id: expr, $chan_in_flight_upds: expr, $monitor: expr, $peer_state: expr, $logger: expr, $channel_info_log: expr @@ -15070,27 +15594,34 @@ where #[cfg(test)] mod tests { - use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey}; - use bitcoin::secp256k1::ecdh::SharedSecret; - use core::sync::atomic::Ordering; - use crate::events::{Event, HTLCHandlingFailureType, ClosureReason}; - use crate::ln::onion_utils::AttributionData; - use crate::ln::types::ChannelId; - use crate::types::payment::{PaymentPreimage, PaymentHash, PaymentSecret}; - use crate::ln::channelmanager::{create_recv_pending_htlc_info, inbound_payment, ChannelConfigOverrides, HTLCForwardInfo, InterceptId, PaymentId, RecipientOnionFields}; + use crate::events::{ClosureReason, Event, HTLCHandlingFailureType}; + use crate::ln::channelmanager::{ + create_recv_pending_htlc_info, inbound_payment, ChannelConfigOverrides, HTLCForwardInfo, + InterceptId, PaymentId, RecipientOnionFields, + }; use crate::ln::functional_test_utils::*; - use crate::ln::msgs::{self, BaseMessageHandler, ChannelMessageHandler, AcceptChannel, ErrorAction, MessageSendEvent}; + use crate::ln::msgs::{ + self, AcceptChannel, BaseMessageHandler, ChannelMessageHandler, ErrorAction, + MessageSendEvent, + }; + use crate::ln::onion_utils::AttributionData; use crate::ln::onion_utils::{self, LocalHTLCFailureReason}; use crate::ln::outbound_payment::Retry; + use crate::ln::types::ChannelId; use crate::prelude::*; - use crate::routing::router::{PaymentParameters, RouteParameters, find_route}; + use crate::routing::router::{find_route, PaymentParameters, RouteParameters}; + use crate::sign::EntropySource; + use crate::types::payment::{PaymentHash, PaymentPreimage, PaymentSecret}; + use crate::util::config::{ChannelConfig, ChannelConfigUpdate, ChannelHandshakeConfigUpdate}; use crate::util::errors::APIError; use crate::util::ser::Writeable; use crate::util::test_utils; - use crate::util::config::{ChannelConfig, ChannelConfigUpdate, ChannelHandshakeConfigUpdate}; - use crate::sign::EntropySource; + use bitcoin::secp256k1::ecdh::SharedSecret; + use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey}; + use core::sync::atomic::Ordering; #[test] + #[rustfmt::skip] fn test_notify_limits() { // Check that a few cases which don't require the persistence of a new ChannelManager, // indeed, do not cause the persistence of a new ChannelManager. @@ -15171,6 +15702,7 @@ mod tests { } #[test] + #[rustfmt::skip] fn test_keysend_dup_hash_partial_mpp() { // Test that a keysend payment with a duplicate hash to an existing partial MPP payment fails as // expected. @@ -15290,6 +15822,7 @@ mod tests { } #[test] + #[rustfmt::skip] fn test_peer_storage() { let chanmon_cfgs = create_chanmon_cfgs(2); let node_cfgs = create_node_cfgs(2, &chanmon_cfgs); @@ -15354,6 +15887,7 @@ mod tests { } #[test] + #[rustfmt::skip] fn test_keysend_dup_payment_hash() { // (1): Test that a keysend payment with a duplicate payment hash to an existing pending // outbound regular payment fails as expected. @@ -15502,6 +16036,7 @@ mod tests { } #[test] + #[rustfmt::skip] fn test_keysend_hash_mismatch() { // Test that if we receive a keysend `update_add_htlc` msg, we fail as expected if the keysend // preimage doesn't match the msg's payment hash. @@ -15550,6 +16085,7 @@ mod tests { } #[test] + #[rustfmt::skip] fn test_multi_hop_missing_secret() { let chanmon_cfgs = create_chanmon_cfgs(4); let node_cfgs = create_node_cfgs(4, &chanmon_cfgs); @@ -15587,6 +16123,7 @@ mod tests { } #[test] + #[rustfmt::skip] fn test_channel_update_cached() { let chanmon_cfgs = create_chanmon_cfgs(3); let node_cfgs = create_node_cfgs(3, &chanmon_cfgs); @@ -15642,6 +16179,7 @@ mod tests { } #[test] + #[rustfmt::skip] fn test_drop_disconnected_peers_when_removing_channels() { let chanmon_cfgs = create_chanmon_cfgs(2); let node_cfgs = create_node_cfgs(2, &chanmon_cfgs); @@ -15676,6 +16214,7 @@ mod tests { } #[test] + #[rustfmt::skip] fn test_drop_peers_when_removing_unfunded_channels() { let chanmon_cfgs = create_chanmon_cfgs(2); let node_cfgs = create_node_cfgs(2, &chanmon_cfgs); @@ -15701,6 +16240,7 @@ mod tests { } #[test] + #[rustfmt::skip] fn bad_inbound_payment_hash() { // Add coverage for checking that a user-provided payment hash matches the payment secret. let chanmon_cfgs = create_chanmon_cfgs(2); @@ -15729,16 +16269,20 @@ mod tests { assert!(inbound_payment::verify(payment_hash, &payment_data, nodes[0].node.highest_seen_timestamp.load(Ordering::Acquire) as u64, &nodes[0].node.inbound_payment_key, &nodes[0].logger).is_ok()); } - fn check_not_connected_to_peer_error(res_err: Result, expected_public_key: PublicKey) { + fn check_not_connected_to_peer_error( + res_err: Result, expected_public_key: PublicKey, + ) { let expected_message = format!("Not connected to node: {}", expected_public_key); check_api_error_message(expected_message, res_err) } + #[rustfmt::skip] fn check_unkown_peer_error(res_err: Result, expected_public_key: PublicKey) { let expected_message = format!("Can't find a peer matching the passed counterparty node_id {}", expected_public_key); check_api_error_message(expected_message, res_err) } + #[rustfmt::skip] fn check_channel_unavailable_error(res_err: Result, expected_channel_id: ChannelId, peer_node_id: PublicKey) { let expected_message = format!("Channel with id {} not found for the passed counterparty node_id {}", expected_channel_id, peer_node_id); check_api_error_message(expected_message, res_err) @@ -15763,6 +16307,7 @@ mod tests { } #[test] + #[rustfmt::skip] fn test_api_calls_with_unkown_counterparty_node() { // Tests that our API functions that expects a `counterparty_node_id` as input, behaves as // expected if the `counterparty_node_id` is an unkown peer in the @@ -15795,6 +16340,7 @@ mod tests { } #[test] + #[rustfmt::skip] fn test_api_calls_with_unavailable_channel() { // Tests that our API functions that expects a `counterparty_node_id` and a `channel_id` // as input, behaves as expected if the `counterparty_node_id` is a known peer in the @@ -15826,6 +16372,7 @@ mod tests { } #[test] + #[rustfmt::skip] fn test_connection_limiting() { // Test that we limit un-channel'd peers and un-funded channels properly. let chanmon_cfgs = create_chanmon_cfgs(2); @@ -15941,6 +16488,7 @@ mod tests { } #[test] + #[rustfmt::skip] fn test_outbound_chans_unlimited() { // Test that we never refuse an outbound channel even if a peer is unfuned-channel-limited let chanmon_cfgs = create_chanmon_cfgs(2); @@ -15976,6 +16524,7 @@ mod tests { } #[test] + #[rustfmt::skip] fn test_0conf_limiting() { // Tests that we properly limit inbound channels when we have the manual-channel-acceptance // flag set and (sometimes) accept channels as 0conf. @@ -16045,6 +16594,7 @@ mod tests { } #[test] + #[rustfmt::skip] fn reject_excessively_underpaying_htlcs() { let chanmon_cfg = create_chanmon_cfgs(1); let node_cfg = create_node_cfgs(1, &chanmon_cfg); @@ -16099,6 +16649,7 @@ mod tests { } #[test] + #[rustfmt::skip] fn test_final_incorrect_cltv(){ let chanmon_cfg = create_chanmon_cfgs(1); let node_cfg = create_node_cfgs(1, &chanmon_cfg); @@ -16155,6 +16706,7 @@ mod tests { assert_eq!(accept_message.channel_reserve_satoshis, 2_000); } + #[rustfmt::skip] fn test_inbound_anchors_manual_acceptance_with_override(config_overrides: Option) -> AcceptChannel { // Tests that we properly limit inbound channels when we have the manual-channel-acceptance // flag set and (sometimes) accept channels as 0conf. @@ -16199,6 +16751,7 @@ mod tests { } #[test] + #[rustfmt::skip] fn test_anchors_zero_fee_htlc_tx_fallback() { // Tests that if both nodes support anchors, but the remote node does not want to accept // anchor channels at the moment, an error it sent to the local node such that it can retry @@ -16237,6 +16790,7 @@ mod tests { } #[test] + #[rustfmt::skip] fn test_update_channel_config() { let chanmon_cfg = create_chanmon_cfgs(2); let node_cfg = create_node_cfgs(2, &chanmon_cfg); @@ -16314,6 +16868,7 @@ mod tests { } #[test] + #[rustfmt::skip] fn test_payment_display() { let payment_id = PaymentId([42; 32]); assert_eq!(format!("{}", &payment_id), "2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a"); @@ -16324,6 +16879,7 @@ mod tests { } #[test] + #[rustfmt::skip] fn test_trigger_lnd_force_close() { let chanmon_cfg = create_chanmon_cfgs(2); let node_cfg = create_node_cfgs(2, &chanmon_cfg); @@ -16386,6 +16942,7 @@ mod tests { } #[test] + #[rustfmt::skip] fn test_malformed_forward_htlcs_ser() { // Ensure that `HTLCForwardInfo::FailMalformedHTLC`s are (de)serialized properly. let chanmon_cfg = create_chanmon_cfgs(1); @@ -16449,52 +17006,72 @@ mod tests { #[cfg(ldk_bench)] pub mod bench { - use crate::chain::Listen; use crate::chain::chainmonitor::{ChainMonitor, Persist}; - use crate::sign::{KeysManager, InMemorySigner}; + use crate::chain::Listen; use crate::events::Event; - use crate::ln::channelmanager::{BestBlock, ChainParameters, ChannelManager, PaymentHash, PaymentPreimage, PaymentId, RecipientOnionFields, Retry}; + use crate::ln::channelmanager::{ + BestBlock, ChainParameters, ChannelManager, PaymentHash, PaymentId, PaymentPreimage, + RecipientOnionFields, Retry, + }; use crate::ln::functional_test_utils::*; use crate::ln::msgs::{BaseMessageHandler, ChannelMessageHandler, Init, MessageSendEvent}; use crate::routing::gossip::NetworkGraph; use crate::routing::router::{PaymentParameters, RouteParameters}; + use crate::sign::{InMemorySigner, KeysManager}; + use crate::util::config::{MaxDustHTLCExposure, UserConfig}; use crate::util::test_utils; - use crate::util::config::{UserConfig, MaxDustHTLCExposure}; use bitcoin::amount::Amount; - use bitcoin::locktime::absolute::LockTime; - use bitcoin::hashes::Hash; use bitcoin::hashes::sha256::Hash as Sha256; - use bitcoin::{Transaction, TxOut}; + use bitcoin::hashes::Hash; + use bitcoin::locktime::absolute::LockTime; use bitcoin::transaction::Version; + use bitcoin::{Transaction, TxOut}; use crate::sync::{Arc, RwLock}; use criterion::Criterion; type Manager<'a, P> = ChannelManager< - &'a ChainMonitor, - &'a test_utils::TestBroadcaster, &'a KeysManager, &'a KeysManager, &'a KeysManager, - &'a test_utils::TestFeeEstimator, &'a test_utils::TestRouter<'a>, - &'a test_utils::TestMessageRouter<'a>, &'a test_utils::TestLogger>; + &'a ChainMonitor< + InMemorySigner, + &'a test_utils::TestChainSource, + &'a test_utils::TestBroadcaster, + &'a test_utils::TestFeeEstimator, + &'a test_utils::TestLogger, + &'a P, + >, + &'a test_utils::TestBroadcaster, + &'a KeysManager, + &'a KeysManager, + &'a KeysManager, + &'a test_utils::TestFeeEstimator, + &'a test_utils::TestRouter<'a>, + &'a test_utils::TestMessageRouter<'a>, + &'a test_utils::TestLogger, + >; struct ANodeHolder<'node_cfg, 'chan_mon_cfg: 'node_cfg, P: Persist> { node: &'node_cfg Manager<'chan_mon_cfg, P>, } - impl<'node_cfg, 'chan_mon_cfg: 'node_cfg, P: Persist> NodeHolder for ANodeHolder<'node_cfg, 'chan_mon_cfg, P> { + impl<'node_cfg, 'chan_mon_cfg: 'node_cfg, P: Persist> NodeHolder + for ANodeHolder<'node_cfg, 'chan_mon_cfg, P> + { type CM = Manager<'chan_mon_cfg, P>; #[inline] + #[rustfmt::skip] fn node(&self) -> &Manager<'chan_mon_cfg, P> { self.node } #[inline] + #[rustfmt::skip] fn chain_monitor(&self) -> Option<&test_utils::TestChainMonitor> { None } } + #[rustfmt::skip] pub fn bench_sends(bench: &mut Criterion) { bench_two_sends(bench, "bench_sends", test_utils::TestPersister::new(), test_utils::TestPersister::new()); } + #[rustfmt::skip] pub fn bench_two_sends>(bench: &mut Criterion, bench_name: &str, persister_a: P, persister_b: P) { // Do a simple benchmark of sending a payment back and forth between two nodes. // Note that this is unrealistic as each payment send will require at least two fsync @@ -16611,6 +17188,7 @@ pub mod bench { } let mut payment_count: u64 = 0; + #[rustfmt::skip] macro_rules! send_payment { ($node_a: expr, $node_b: expr) => { let payment_params = PaymentParameters::from_node_id($node_b.get_our_node_id(), TEST_FINAL_CLTV) diff --git a/lightning/src/ln/functional_test_utils.rs b/lightning/src/ln/functional_test_utils.rs index 3ff2a045d28..9f667a02614 100644 --- a/lightning/src/ln/functional_test_utils.rs +++ b/lightning/src/ln/functional_test_utils.rs @@ -1,5 +1,3 @@ -#![cfg_attr(rustfmt, rustfmt_skip)] - // This file is Copyright its original authors, visible in version control // history. // @@ -12,59 +10,69 @@ //! A bunch of useful utilities for building networks of nodes and exchanging messages between //! nodes for functional tests. -use crate::chain::{BestBlock, ChannelMonitorUpdateStatus, Confirm, Listen, Watch}; use crate::chain::channelmonitor::ChannelMonitor; use crate::chain::transaction::OutPoint; -use crate::events::{ClaimedHTLC, ClosureReason, Event, HTLCHandlingFailureType, PaidBolt12Invoice, PathFailure, PaymentFailureReason, PaymentPurpose}; -use crate::events::bump_transaction::{BumpTransactionEvent, BumpTransactionEventHandler, Wallet, WalletSource}; -use crate::ln::types::ChannelId; -use crate::types::features::ChannelTypeFeatures; -use crate::types::payment::{PaymentPreimage, PaymentHash, PaymentSecret}; +use crate::chain::{BestBlock, ChannelMonitorUpdateStatus, Confirm, Listen, Watch}; +use crate::events::bump_transaction::{ + BumpTransactionEvent, BumpTransactionEventHandler, Wallet, WalletSource, +}; +use crate::events::{ + ClaimedHTLC, ClosureReason, Event, HTLCHandlingFailureType, PaidBolt12Invoice, PathFailure, + PaymentFailureReason, PaymentPurpose, +}; use crate::ln::chan_utils::{commitment_tx_base_weight, COMMITMENT_TX_WEIGHT_PER_HTLC}; -use crate::ln::channelmanager::{AChannelManager, ChainParameters, ChannelManager, ChannelManagerReadArgs, RAACommitmentOrder, RecipientOnionFields, PaymentId, MIN_CLTV_EXPIRY_DELTA}; -use crate::types::features::InitFeatures; +use crate::ln::channelmanager::{ + AChannelManager, ChainParameters, ChannelManager, ChannelManagerReadArgs, PaymentId, + RAACommitmentOrder, RecipientOnionFields, MIN_CLTV_EXPIRY_DELTA, +}; use crate::ln::msgs; -use crate::ln::msgs::{BaseMessageHandler, ChannelMessageHandler, MessageSendEvent, RoutingMessageHandler}; +use crate::ln::msgs::{ + BaseMessageHandler, ChannelMessageHandler, MessageSendEvent, RoutingMessageHandler, +}; +use crate::ln::onion_utils::LocalHTLCFailureReason; use crate::ln::outbound_payment::Retry; use crate::ln::peer_handler::IgnoringMessageHandler; +use crate::ln::types::ChannelId; use crate::onion_message::messenger::OnionMessenger; -use crate::ln::onion_utils::LocalHTLCFailureReason; -use crate::routing::gossip::{P2PGossipSync, NetworkGraph, NetworkUpdate}; +use crate::routing::gossip::{NetworkGraph, NetworkUpdate, P2PGossipSync}; use crate::routing::router::{self, PaymentParameters, Route, RouteParameters}; use crate::sign::{EntropySource, RandomBytes}; +use crate::types::features::ChannelTypeFeatures; +use crate::types::features::InitFeatures; +use crate::types::payment::{PaymentHash, PaymentPreimage, PaymentSecret}; use crate::util::config::{MaxDustHTLCExposure, UserConfig}; use crate::util::logger::Logger; use crate::util::scid_utils; -use crate::util::test_channel_signer::TestChannelSigner; +use crate::util::ser::{ReadableArgs, Writeable}; use crate::util::test_channel_signer::SignerOp; +use crate::util::test_channel_signer::TestChannelSigner; use crate::util::test_utils; -use crate::util::test_utils::{TestChainMonitor, TestScorer, TestKeysInterface}; -use crate::util::ser::{ReadableArgs, Writeable}; +use crate::util::test_utils::{TestChainMonitor, TestKeysInterface, TestScorer}; -use bitcoin::{Weight, WPubkeyHash}; use bitcoin::amount::Amount; use bitcoin::block::{Block, Header, Version as BlockVersion}; -use bitcoin::locktime::absolute::{LockTime, LOCK_TIME_THRESHOLD}; -use bitcoin::transaction::{Sequence, Transaction, TxIn, TxOut}; use bitcoin::hash_types::{BlockHash, TxMerkleNode}; use bitcoin::hashes::sha256::Hash as Sha256; use bitcoin::hashes::Hash as _; +use bitcoin::locktime::absolute::{LockTime, LOCK_TIME_THRESHOLD}; use bitcoin::network::Network; use bitcoin::pow::CompactTarget; use bitcoin::script::ScriptBuf; use bitcoin::secp256k1::{PublicKey, SecretKey}; use bitcoin::transaction::{self, Version as TxVersion}; +use bitcoin::transaction::{Sequence, Transaction, TxIn, TxOut}; use bitcoin::witness::Witness; +use bitcoin::{WPubkeyHash, Weight}; +use crate::io; +use crate::prelude::*; +use crate::sign::P2WPKH_WITNESS_WEIGHT; +use crate::sync::{Arc, LockTestExt, Mutex, RwLock}; use alloc::rc::Rc; use core::cell::RefCell; use core::iter::repeat; use core::mem; use core::ops::Deref; -use crate::io; -use crate::prelude::*; -use crate::sign::P2WPKH_WITNESS_WEIGHT; -use crate::sync::{Arc, Mutex, LockTestExt, RwLock}; pub const CHAN_CONFIRM_DEPTH: u32 = 10; @@ -93,6 +101,7 @@ pub fn mine_transactions<'a, 'b, 'c, 'd>(node: &'a Node<'b, 'c, 'd>, txn: &[&Tra } /// Mine a single block containing the given transaction without extra consistency checks which may /// impact ChannelManager state. +#[rustfmt::skip] pub fn mine_transaction_without_consistency_checks<'a, 'b, 'c, 'd>(node: &'a Node<'b, 'c, 'd>, tx: &Transaction) { let height = node.best_block_info().1 + 1; let mut block = Block { @@ -117,6 +126,7 @@ pub fn mine_transaction_without_consistency_checks<'a, 'b, 'c, 'd>(node: &'a Nod /// /// Returns the SCID a channel confirmed in the given transaction will have, assuming the funding /// output is the 1st output in the transaction. +#[rustfmt::skip] pub fn confirm_transactions_at<'a, 'b, 'c, 'd>(node: &'a Node<'b, 'c, 'd>, txn: &[&Transaction], conf_height: u32) -> u64 { let first_connect_height = node.best_block_info().1 + 1; assert!(first_connect_height <= conf_height); @@ -134,7 +144,9 @@ pub fn confirm_transactions_at<'a, 'b, 'c, 'd>(node: &'a Node<'b, 'c, 'd>, txn: connect_block(node, &block); scid_utils::scid_from_parts(conf_height as u64, block.txdata.len() as u64 - 1, 0).unwrap() } -pub fn confirm_transaction_at<'a, 'b, 'c, 'd>(node: &'a Node<'b, 'c, 'd>, tx: &Transaction, conf_height: u32) -> u64 { +pub fn confirm_transaction_at<'a, 'b, 'c, 'd>( + node: &'a Node<'b, 'c, 'd>, tx: &Transaction, conf_height: u32, +) -> u64 { confirm_transactions_at(node, &[tx], conf_height) } @@ -264,13 +276,16 @@ fn call_claimable_balances<'a, 'b, 'c, 'd>(node: &'a Node<'b, 'c, 'd>) { } } -fn do_connect_block_with_consistency_checks<'a, 'b, 'c, 'd>(node: &'a Node<'b, 'c, 'd>, block: Block, skip_intermediaries: bool) { +fn do_connect_block_with_consistency_checks<'a, 'b, 'c, 'd>( + node: &'a Node<'b, 'c, 'd>, block: Block, skip_intermediaries: bool, +) { call_claimable_balances(node); do_connect_block_without_consistency_checks(node, block, skip_intermediaries); call_claimable_balances(node); node.node.test_process_background_events(); } +#[rustfmt::skip] fn do_connect_block_without_consistency_checks<'a, 'b, 'c, 'd>(node: &'a Node<'b, 'c, 'd>, block: Block, skip_intermediaries: bool) { let height = node.best_block_info().1 + 1; eprintln!("Connecting block using Block Connection Style: {:?}", *node.connect_style.borrow()); @@ -339,6 +354,7 @@ fn do_connect_block_without_consistency_checks<'a, 'b, 'c, 'd>(node: &'a Node<'b } } +#[rustfmt::skip] pub fn disconnect_blocks<'a, 'b, 'c, 'd>(node: &'a Node<'b, 'c, 'd>, count: u32) { call_claimable_balances(node); eprintln!("Disconnecting {} blocks using Block Connection Style: {:?}", count, *node.connect_style.borrow()); @@ -449,6 +465,7 @@ pub struct DedicatedEntropy(RandomBytes); impl Deref for DedicatedEntropy { type Target = RandomBytes; + #[rustfmt::skip] fn deref(&self) -> &Self::Target { &self.0 } } @@ -463,7 +480,11 @@ pub struct Node<'chan_man, 'node_cfg: 'chan_man, 'chan_mon_cfg: 'node_cfg> { pub node: &'chan_man TestChannelManager<'node_cfg, 'chan_mon_cfg>, pub onion_messenger: TestOnionMessenger<'chan_man, 'node_cfg, 'chan_mon_cfg>, pub network_graph: &'node_cfg NetworkGraph<&'chan_mon_cfg test_utils::TestLogger>, - pub gossip_sync: P2PGossipSync<&'node_cfg NetworkGraph<&'chan_mon_cfg test_utils::TestLogger>, &'chan_mon_cfg test_utils::TestChainSource, &'chan_mon_cfg test_utils::TestLogger>, + pub gossip_sync: P2PGossipSync< + &'node_cfg NetworkGraph<&'chan_mon_cfg test_utils::TestLogger>, + &'chan_mon_cfg test_utils::TestChainSource, + &'chan_mon_cfg test_utils::TestLogger, + >, pub node_seed: [u8; 32], pub network_payment_count: Rc>, pub network_chan_count: Rc>, @@ -481,6 +502,7 @@ pub struct Node<'chan_man, 'node_cfg: 'chan_man, 'chan_mon_cfg: 'node_cfg> { } impl<'a, 'b, 'c> Node<'a, 'b, 'c> { + #[rustfmt::skip] pub fn init_features(&self, peer_node_id: PublicKey) -> InitFeatures { self.override_init_features.borrow().clone() .unwrap_or_else(|| self.node.init_features() | self.onion_messenger.provided_init_features(peer_node_id)) @@ -519,7 +541,9 @@ impl<'a, 'b, 'c> Node<'a, 'b, 'c> { /// Toggles this node's signer to be available for the given signer operation. /// This is useful for testing behavior for restoring an async signer that previously /// could not return a signature immediately. - pub fn enable_channel_signer_op(&self, peer_id: &PublicKey, chan_id: &ChannelId, signer_op: SignerOp) { + pub fn enable_channel_signer_op( + &self, peer_id: &PublicKey, chan_id: &ChannelId, signer_op: SignerOp, + ) { self.set_channel_signer_ops(peer_id, chan_id, signer_op, true); } @@ -527,7 +551,9 @@ impl<'a, 'b, 'c> Node<'a, 'b, 'c> { /// This is useful for testing behavior for an async signer that cannot return a signature /// immediately. #[cfg(test)] - pub fn disable_channel_signer_op(&self, peer_id: &PublicKey, chan_id: &ChannelId, signer_op: SignerOp) { + pub fn disable_channel_signer_op( + &self, peer_id: &PublicKey, chan_id: &ChannelId, signer_op: SignerOp, + ) { self.set_channel_signer_ops(peer_id, chan_id, signer_op, false); } @@ -538,6 +564,7 @@ impl<'a, 'b, 'c> Node<'a, 'b, 'c> { /// will behave normally, returning `Ok`. When set to `false`, and the channel signer will /// act like an off-line remote signer, returning `Err`. This applies to the signer in all /// relevant places, i.e. the channel manager, chain monitor, and the keys manager. + #[rustfmt::skip] fn set_channel_signer_ops(&self, peer_id: &PublicKey, chan_id: &ChannelId, signer_op: SignerOp, available: bool) { use crate::sign::ChannelSigner; log_debug!(self.logger, "Setting channel signer for {} as available={}", chan_id, available); @@ -600,9 +627,9 @@ impl NodePtr { unsafe impl Send for NodePtr {} unsafe impl Sync for NodePtr {} - pub trait NodeHolder { type CM: AChannelManager; + #[rustfmt::skip] fn node(&self) -> &ChannelManager< ::M, ::T, @@ -617,6 +644,7 @@ pub trait NodeHolder { } impl NodeHolder for &H { type CM = H::CM; + #[rustfmt::skip] fn node(&self) -> &ChannelManager< ::M, ::T, @@ -627,15 +655,19 @@ impl NodeHolder for &H { ::R, ::MR, ::L> { (*self).node() } + #[rustfmt::skip] fn chain_monitor(&self) -> Option<&test_utils::TestChainMonitor> { (*self).chain_monitor() } } impl<'a, 'b: 'a, 'c: 'b> NodeHolder for Node<'a, 'b, 'c> { type CM = TestChannelManager<'b, 'c>; + #[rustfmt::skip] fn node(&self) -> &TestChannelManager<'b, 'c> { &self.node } + #[rustfmt::skip] fn chain_monitor(&self) -> Option<&test_utils::TestChainMonitor> { Some(self.chain_monitor) } } impl<'a, 'b, 'c> Drop for Node<'a, 'b, 'c> { + #[rustfmt::skip] fn drop(&mut self) { if !std::thread::panicking() { // Check that we processed all pending events @@ -750,10 +782,13 @@ impl<'a, 'b, 'c> Drop for Node<'a, 'b, 'c> { } } -pub fn create_chan_between_nodes<'a, 'b, 'c: 'd, 'd>(node_a: &'a Node<'b, 'c, 'd>, node_b: &'a Node<'b, 'c, 'd>) -> (msgs::ChannelAnnouncement, msgs::ChannelUpdate, msgs::ChannelUpdate, ChannelId, Transaction) { +pub fn create_chan_between_nodes<'a, 'b, 'c: 'd, 'd>( + node_a: &'a Node<'b, 'c, 'd>, node_b: &'a Node<'b, 'c, 'd>, +) -> (msgs::ChannelAnnouncement, msgs::ChannelUpdate, msgs::ChannelUpdate, ChannelId, Transaction) { create_chan_between_nodes_with_value(node_a, node_b, 100000, 10001) } +#[rustfmt::skip] pub fn create_chan_between_nodes_with_value<'a, 'b, 'c: 'd, 'd>(node_a: &'a Node<'b, 'c, 'd>, node_b: &'a Node<'b, 'c, 'd>, channel_value: u64, push_msat: u64) -> (msgs::ChannelAnnouncement, msgs::ChannelUpdate, msgs::ChannelUpdate, ChannelId, Transaction) { let (channel_ready, channel_id, tx) = create_chan_between_nodes_with_value_a(node_a, node_b, channel_value, push_msat); let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(node_a, node_b, &channel_ready); @@ -761,6 +796,7 @@ pub fn create_chan_between_nodes_with_value<'a, 'b, 'c: 'd, 'd>(node_a: &'a Node } /// Gets an RAA and CS which were sent in response to a commitment update +#[rustfmt::skip] pub fn get_revoke_commit_msgs>(node: &H, recipient: &PublicKey) -> (msgs::RevokeAndACK, Vec) { let events = node.node().get_and_clear_pending_msg_events(); assert_eq!(events.len(), 2); @@ -787,6 +823,7 @@ pub fn get_revoke_commit_msgs>(node: & /// Gets a `UpdateHTLCs` and `revoke_and_ack` (i.e. after we get a responding `commitment_signed` /// while we have updates in the holding cell). +#[rustfmt::skip] pub fn get_updates_and_revoke>(node: &H, recipient: &PublicKey) -> (msgs::CommitmentUpdate, msgs::RevokeAndACK) { let events = node.node().get_and_clear_pending_msg_events(); assert_eq!(events.len(), 2); @@ -812,28 +849,27 @@ pub fn get_updates_and_revoke>(node: & macro_rules! get_revoke_commit_msgs { ($node: expr, $node_id: expr) => { $crate::ln::functional_test_utils::get_revoke_commit_msgs(&$node, &$node_id) - } + }; } /// Get an specific event message from the pending events queue. #[macro_export] macro_rules! get_event_msg { - ($node: expr, $event_type: path, $node_id: expr) => { - { - let events = $node.node.get_and_clear_pending_msg_events(); - assert_eq!(events.len(), 1); - match events[0] { - $event_type { ref node_id, ref msg } => { - assert_eq!(*node_id, $node_id); - (*msg).clone() - }, - _ => panic!("Unexpected event {:?}", events[0]), - } + ($node: expr, $event_type: path, $node_id: expr) => {{ + let events = $node.node.get_and_clear_pending_msg_events(); + assert_eq!(events.len(), 1); + match events[0] { + $event_type { ref node_id, ref msg } => { + assert_eq!(*node_id, $node_id); + (*msg).clone() + }, + _ => panic!("Unexpected event {:?}", events[0]), } - } + }}; } /// Get an error message from the pending events queue. +#[rustfmt::skip] pub fn get_err_msg(node: &Node, recipient: &PublicKey) -> msgs::ErrorMessage { let events = node.node.get_and_clear_pending_msg_events(); assert_eq!(events.len(), 1); @@ -856,6 +892,7 @@ pub fn get_err_msg(node: &Node, recipient: &PublicKey) -> msgs::ErrorMessage { /// Get a specific event from the pending events queue. #[macro_export] +#[rustfmt::skip] macro_rules! get_event { ($node: expr, $event_type: path) => { { @@ -892,7 +929,7 @@ pub fn get_htlc_update_msgs(node: &Node, recipient: &PublicKey) -> msgs::Commitm macro_rules! get_htlc_update_msgs { ($node: expr, $node_id: expr) => { $crate::ln::functional_test_utils::get_htlc_update_msgs(&$node, &$node_id) - } + }; } /// Fetches the first `msg_event` to the passed `node_id` in the passed `msg_events` vec. @@ -901,6 +938,7 @@ macro_rules! get_htlc_update_msgs { /// Note that even though `BroadcastChannelAnnouncement` and `BroadcastChannelUpdate` /// `msg_events` are stored under specific peers, this function does not fetch such `msg_events` as /// such messages are intended to all peers. +#[rustfmt::skip] pub fn remove_first_msg_event_to_node(msg_node_id: &PublicKey, msg_events: &mut Vec) -> MessageSendEvent { let ev_index = msg_events.iter().position(|e| { match e { MessageSendEvent::SendPeerStorage { node_id, .. } => { @@ -1026,6 +1064,7 @@ pub fn remove_first_msg_event_to_node(msg_node_id: &PublicKey, msg_events: &mut } #[cfg(any(test, feature = "_externalize_tests"))] +#[rustfmt::skip] macro_rules! get_channel_ref { ($node: expr, $counterparty_node: expr, $per_peer_state_lock: ident, $peer_state_lock: ident, $channel_id: expr) => { { @@ -1037,6 +1076,7 @@ macro_rules! get_channel_ref { } #[cfg(any(test, feature = "_externalize_tests"))] +#[rustfmt::skip] macro_rules! get_feerate { ($node: expr, $counterparty_node: expr, $channel_id: expr) => { { @@ -1049,6 +1089,7 @@ macro_rules! get_feerate { } #[cfg(any(test, feature = "_externalize_tests"))] +#[rustfmt::skip] macro_rules! get_channel_type_features { ($node: expr, $counterparty_node: expr, $channel_id: expr) => { { @@ -1063,25 +1104,23 @@ macro_rules! get_channel_type_features { /// Returns a channel monitor given a channel id, making some naive assumptions #[macro_export] macro_rules! get_monitor { - ($node: expr, $channel_id: expr) => { - { - $node.chain_monitor.chain_monitor.get_monitor($channel_id).unwrap() - } - } + ($node: expr, $channel_id: expr) => {{ + $node.chain_monitor.chain_monitor.get_monitor($channel_id).unwrap() + }}; } /// Returns any local commitment transactions for the channel. #[macro_export] macro_rules! get_local_commitment_txn { - ($node: expr, $channel_id: expr) => { - { - $crate::get_monitor!($node, $channel_id).unsafe_get_latest_holder_commitment_txn(&$node.logger) - } - } + ($node: expr, $channel_id: expr) => {{ + $crate::get_monitor!($node, $channel_id) + .unsafe_get_latest_holder_commitment_txn(&$node.logger) + }}; } /// Check the error from attempting a payment. #[macro_export] +#[rustfmt::skip] macro_rules! unwrap_send_err { ($node: expr, $res: expr, $all_failed: expr, $type: pat, $check: expr) => { assert!($res.is_ok()); @@ -1108,12 +1147,13 @@ macro_rules! unwrap_send_err { } } +#[rustfmt::skip] pub fn commit_tx_fee_msat(feerate: u32, num_htlcs: u64, channel_type_features: &ChannelTypeFeatures) -> u64 { (commitment_tx_base_weight(channel_type_features) + num_htlcs * COMMITMENT_TX_WEIGHT_PER_HTLC) * feerate as u64 / 1000 * 1000 } /// Check whether N channel monitor(s) have been added. -pub fn check_added_monitors>(node: &H, count: usize) { +pub fn check_added_monitors>(node: &H, count: usize) { if let Some(chain_monitor) = node.chain_monitor() { let mut added_monitors = chain_monitor.added_monitors.lock().unwrap(); let n = added_monitors.len(); @@ -1129,9 +1169,10 @@ pub fn check_added_monitors>(node: &H, macro_rules! check_added_monitors { ($node: expr, $count: expr) => { $crate::ln::functional_test_utils::check_added_monitors(&$node, $count); - } + }; } +#[rustfmt::skip] fn claimed_htlc_matches_path<'a, 'b, 'c>(origin_node: &Node<'a, 'b, 'c>, path: &[&Node<'a, 'b, 'c>], htlc: &ClaimedHTLC) -> bool { let mut nodes = path.iter().rev(); let dest = nodes.next().expect("path should have a destination").node; @@ -1143,7 +1184,9 @@ fn claimed_htlc_matches_path<'a, 'b, 'c>(origin_node: &Node<'a, 'b, 'c>, path: & ch.counterparty.node_id == prev.get_our_node_id() } -fn check_claimed_htlcs_match_route<'a, 'b, 'c>(origin_node: &Node<'a, 'b, 'c>, route: &[&[&Node<'a, 'b, 'c>]], htlcs: &[ClaimedHTLC]) { +fn check_claimed_htlcs_match_route<'a, 'b, 'c>( + origin_node: &Node<'a, 'b, 'c>, route: &[&[&Node<'a, 'b, 'c>]], htlcs: &[ClaimedHTLC], +) { assert_eq!(route.len(), htlcs.len()); for path in route { let mut found_matching_htlc = false; @@ -1157,6 +1200,7 @@ fn check_claimed_htlcs_match_route<'a, 'b, 'c>(origin_node: &Node<'a, 'b, 'c>, r } } +#[rustfmt::skip] pub fn _reload_node<'a, 'b, 'c>(node: &'a Node<'a, 'b, 'c>, default_config: UserConfig, chanman_encoded: &[u8], monitors_encoded: &[&[u8]]) -> TestChannelManager<'b, 'c> { let mut monitors_read = Vec::with_capacity(monitors_encoded.len()); for encoded in monitors_encoded { @@ -1200,6 +1244,7 @@ pub fn _reload_node<'a, 'b, 'c>(node: &'a Node<'a, 'b, 'c>, default_config: User } #[macro_export] +#[rustfmt::skip] macro_rules! reload_node { ($node: expr, $new_config: expr, $chanman_encoded: expr, $monitors_encoded: expr, $persister: ident, $new_chain_monitor: ident, $new_channelmanager: ident) => { let chanman_encoded = $chanman_encoded; @@ -1217,6 +1262,7 @@ macro_rules! reload_node { }; } +#[rustfmt::skip] pub fn create_funding_transaction<'a, 'b, 'c>(node: &Node<'a, 'b, 'c>, expected_counterparty_node_id: &PublicKey, expected_chan_value: u64, expected_user_chan_id: u128) -> (ChannelId, Transaction, OutPoint) @@ -1224,6 +1270,7 @@ pub fn create_funding_transaction<'a, 'b, 'c>(node: &Node<'a, 'b, 'c>, internal_create_funding_transaction(node, expected_counterparty_node_id, expected_chan_value, expected_user_chan_id, false) } +#[rustfmt::skip] pub fn create_coinbase_funding_transaction<'a, 'b, 'c>(node: &Node<'a, 'b, 'c>, expected_counterparty_node_id: &PublicKey, expected_chan_value: u64, expected_user_chan_id: u128) -> (ChannelId, Transaction, OutPoint) @@ -1231,6 +1278,7 @@ pub fn create_coinbase_funding_transaction<'a, 'b, 'c>(node: &Node<'a, 'b, 'c>, internal_create_funding_transaction(node, expected_counterparty_node_id, expected_chan_value, expected_user_chan_id, true) } +#[rustfmt::skip] fn internal_create_funding_transaction<'a, 'b, 'c>(node: &Node<'a, 'b, 'c>, expected_counterparty_node_id: &PublicKey, expected_chan_value: u64, expected_user_chan_id: u128, coinbase: bool) -> (ChannelId, Transaction, OutPoint) { @@ -1265,6 +1313,7 @@ fn internal_create_funding_transaction<'a, 'b, 'c>(node: &Node<'a, 'b, 'c>, /// Create test inputs for a funding transaction. /// Return the inputs (with prev tx), and the total witness weight for these inputs +#[rustfmt::skip] pub fn create_dual_funding_utxos_with_prev_txs( node: &Node<'_, '_, '_>, utxo_values_in_satoshis: &[u64], ) -> Vec<(TxIn, Transaction, Weight)> { @@ -1300,6 +1349,7 @@ pub fn create_dual_funding_utxos_with_prev_txs( inputs } +#[rustfmt::skip] pub fn sign_funding_transaction<'a, 'b, 'c>(node_a: &Node<'a, 'b, 'c>, node_b: &Node<'a, 'b, 'c>, channel_value: u64, expected_temporary_channel_id: ChannelId) -> Transaction { let (temporary_channel_id, tx, _) = create_funding_transaction(node_a, &node_b.node.get_our_node_id(), channel_value, 42); assert_eq!(temporary_channel_id, expected_temporary_channel_id); @@ -1348,6 +1398,7 @@ pub fn sign_funding_transaction<'a, 'b, 'c>(node_a: &Node<'a, 'b, 'c>, node_b: & } // Receiver must have been initialized with manually_accept_inbound_channels set to true. +#[rustfmt::skip] pub fn open_zero_conf_channel<'a, 'b, 'c, 'd>(initiator: &'a Node<'b, 'c, 'd>, receiver: &'a Node<'b, 'c, 'd>, initiator_config: Option) -> (bitcoin::Transaction, ChannelId) { let initiator_channels = initiator.node.list_usable_channels().len(); let receiver_channels = receiver.node.list_usable_channels().len(); @@ -1417,6 +1468,7 @@ pub fn open_zero_conf_channel<'a, 'b, 'c, 'd>(initiator: &'a Node<'b, 'c, 'd>, r (tx, as_channel_ready.channel_id) } +#[rustfmt::skip] pub fn exchange_open_accept_chan<'a, 'b, 'c>(node_a: &Node<'a, 'b, 'c>, node_b: &Node<'a, 'b, 'c>, channel_value: u64, push_msat: u64) -> ChannelId { let create_chan_id = node_a.node.create_channel(node_b.node.get_our_node_id(), channel_value, push_msat, 42, None, None).unwrap(); let open_channel_msg = get_event_msg!(node_a, MessageSendEvent::SendOpenChannel, node_b.node.get_our_node_id()); @@ -1440,17 +1492,21 @@ pub fn exchange_open_accept_chan<'a, 'b, 'c>(node_a: &Node<'a, 'b, 'c>, node_b: create_chan_id } -pub fn create_chan_between_nodes_with_value_init<'a, 'b, 'c>(node_a: &Node<'a, 'b, 'c>, node_b: &Node<'a, 'b, 'c>, channel_value: u64, push_msat: u64) -> Transaction { +pub fn create_chan_between_nodes_with_value_init<'a, 'b, 'c>( + node_a: &Node<'a, 'b, 'c>, node_b: &Node<'a, 'b, 'c>, channel_value: u64, push_msat: u64, +) -> Transaction { let create_chan_id = exchange_open_accept_chan(node_a, node_b, channel_value, push_msat); sign_funding_transaction(node_a, node_b, channel_value, create_chan_id) } +#[rustfmt::skip] pub fn create_chan_between_nodes_with_value_confirm_first<'a, 'b, 'c, 'd>(node_recv: &'a Node<'b, 'c, 'c>, node_conf: &'a Node<'b, 'c, 'd>, tx: &Transaction, conf_height: u32) { confirm_transaction_at(node_conf, tx, conf_height); connect_blocks(node_conf, CHAN_CONFIRM_DEPTH - 1); node_recv.node.handle_channel_ready(node_conf.node.get_our_node_id(), &get_event_msg!(node_conf, MessageSendEvent::SendChannelReady, node_recv.node.get_our_node_id())); } +#[rustfmt::skip] pub fn create_chan_between_nodes_with_value_confirm_second<'a, 'b, 'c>(node_recv: &Node<'a, 'b, 'c>, node_conf: &Node<'a, 'b, 'c>) -> ((msgs::ChannelReady, msgs::AnnouncementSignatures), ChannelId) { let channel_id; let events_6 = node_conf.node.get_and_clear_pending_msg_events(); @@ -1478,6 +1534,7 @@ pub fn create_chan_between_nodes_with_value_confirm_second<'a, 'b, 'c>(node_recv }), channel_id) } +#[rustfmt::skip] pub fn create_chan_between_nodes_with_value_confirm<'a, 'b, 'c: 'd, 'd>(node_a: &'a Node<'b, 'c, 'd>, node_b: &'a Node<'b, 'c, 'd>, tx: &Transaction) -> ((msgs::ChannelReady, msgs::AnnouncementSignatures), ChannelId) { let conf_height = core::cmp::max(node_a.best_block_info().1 + 1, node_b.best_block_info().1 + 1); create_chan_between_nodes_with_value_confirm_first(node_a, node_b, tx, conf_height); @@ -1487,12 +1544,15 @@ pub fn create_chan_between_nodes_with_value_confirm<'a, 'b, 'c: 'd, 'd>(node_a: create_chan_between_nodes_with_value_confirm_second(node_b, node_a) } -pub fn create_chan_between_nodes_with_value_a<'a, 'b, 'c: 'd, 'd>(node_a: &'a Node<'b, 'c, 'd>, node_b: &'a Node<'b, 'c, 'd>, channel_value: u64, push_msat: u64) -> ((msgs::ChannelReady, msgs::AnnouncementSignatures), ChannelId, Transaction) { +pub fn create_chan_between_nodes_with_value_a<'a, 'b, 'c: 'd, 'd>( + node_a: &'a Node<'b, 'c, 'd>, node_b: &'a Node<'b, 'c, 'd>, channel_value: u64, push_msat: u64, +) -> ((msgs::ChannelReady, msgs::AnnouncementSignatures), ChannelId, Transaction) { let tx = create_chan_between_nodes_with_value_init(node_a, node_b, channel_value, push_msat); let (msgs, chan_id) = create_chan_between_nodes_with_value_confirm(node_a, node_b, &tx); (msgs, chan_id, tx) } +#[rustfmt::skip] pub fn create_chan_between_nodes_with_value_b<'a, 'b, 'c>(node_a: &Node<'a, 'b, 'c>, node_b: &Node<'a, 'b, 'c>, as_funding_msgs: &(msgs::ChannelReady, msgs::AnnouncementSignatures)) -> (msgs::ChannelAnnouncement, msgs::ChannelUpdate, msgs::ChannelUpdate) { node_b.node.handle_channel_ready(node_a.node.get_our_node_id(), &as_funding_msgs.0); let bs_announcement_sigs = get_event_msg!(node_b, MessageSendEvent::SendAnnouncementSignatures, node_a.node.get_our_node_id()); @@ -1527,16 +1587,20 @@ pub fn create_chan_between_nodes_with_value_b<'a, 'b, 'c>(node_a: &Node<'a, 'b, ((*announcement).clone(), as_update, bs_update) } -pub fn create_announced_chan_between_nodes<'a, 'b, 'c: 'd, 'd>(nodes: &'a Vec>, a: usize, b: usize) -> (msgs::ChannelUpdate, msgs::ChannelUpdate, ChannelId, Transaction) { +pub fn create_announced_chan_between_nodes<'a, 'b, 'c: 'd, 'd>( + nodes: &'a Vec>, a: usize, b: usize, +) -> (msgs::ChannelUpdate, msgs::ChannelUpdate, ChannelId, Transaction) { create_announced_chan_between_nodes_with_value(nodes, a, b, 100000, 10001) } +#[rustfmt::skip] pub fn create_announced_chan_between_nodes_with_value<'a, 'b, 'c: 'd, 'd>(nodes: &'a Vec>, a: usize, b: usize, channel_value: u64, push_msat: u64) -> (msgs::ChannelUpdate, msgs::ChannelUpdate, ChannelId, Transaction) { let chan_announcement = create_chan_between_nodes_with_value(&nodes[a], &nodes[b], channel_value, push_msat); update_nodes_with_chan_announce(nodes, a, b, &chan_announcement.0, &chan_announcement.1, &chan_announcement.2); (chan_announcement.1, chan_announcement.2, chan_announcement.3, chan_announcement.4) } +#[rustfmt::skip] pub fn create_unannounced_chan_between_nodes_with_value<'a, 'b, 'c, 'd>(nodes: &'a Vec>, a: usize, b: usize, channel_value: u64, push_msat: u64) -> (msgs::ChannelReady, Transaction) { let mut no_announce_cfg = nodes[a].node.get_current_default_configuration().clone(); no_announce_cfg.channel_handshake_config.announce_for_forwarding = false; @@ -1601,7 +1665,10 @@ pub fn create_unannounced_chan_between_nodes_with_value<'a, 'b, 'c, 'd>(nodes: & (as_channel_ready, tx) } -pub fn update_nodes_with_chan_announce<'a, 'b, 'c, 'd>(nodes: &'a Vec>, a: usize, b: usize, ann: &msgs::ChannelAnnouncement, upd_1: &msgs::ChannelUpdate, upd_2: &msgs::ChannelUpdate) { +pub fn update_nodes_with_chan_announce<'a, 'b, 'c, 'd>( + nodes: &'a Vec>, a: usize, b: usize, ann: &msgs::ChannelAnnouncement, + upd_1: &msgs::ChannelUpdate, upd_2: &msgs::ChannelUpdate, +) { for node in nodes { let node_id_a = nodes[a].node.get_our_node_id(); let node_id_b = nodes[b].node.get_our_node_id(); @@ -1616,6 +1683,7 @@ pub fn update_nodes_with_chan_announce<'a, 'b, 'c, 'd>(nodes: &'a Vec Option>(tx: &Transaction, get_output: F) { for outp in tx.output.iter() { assert!(outp.value >= outp.script_pubkey.minimal_non_dust(), "Spending tx output didn't meet dust limit"); @@ -1656,6 +1724,7 @@ macro_rules! check_spends { } } +#[rustfmt::skip] macro_rules! get_closing_signed_broadcast { ($node: expr, $dest_pubkey: expr) => { { @@ -1681,6 +1750,7 @@ macro_rules! get_closing_signed_broadcast { } #[cfg(test)] +#[rustfmt::skip] macro_rules! check_warn_msg { ($node: expr, $recipient_node_id: expr, $chan_id: expr) => {{ let msg_events = $node.node.get_and_clear_pending_msg_events(); @@ -1697,6 +1767,7 @@ macro_rules! check_warn_msg { } /// Checks if at least one peer is connected. +#[rustfmt::skip] fn is_any_peer_connected(node: &Node) -> bool { let peer_state = node.node.per_peer_state.read().unwrap(); for (_, peer_mutex) in peer_state.iter() { @@ -1708,6 +1779,7 @@ fn is_any_peer_connected(node: &Node) -> bool { /// Check that a channel's closing channel update has been broadcasted, and optionally /// check whether an error message event has occurred. +#[rustfmt::skip] pub fn check_closed_broadcast(node: &Node, num_channels: usize, with_error_msg: bool) -> Vec { let mut dummy_connected = false; if !is_any_peer_connected(&node) { @@ -1748,7 +1820,7 @@ pub fn check_closed_broadcast(node: &Node, num_channels: usize, with_error_msg: macro_rules! check_closed_broadcast { ($node: expr, $with_error_msg: expr) => { $crate::ln::functional_test_utils::check_closed_broadcast(&$node, 1, $with_error_msg).pop() - } + }; } #[derive(Default)] @@ -1763,7 +1835,9 @@ pub struct ExpectedCloseEvent { } impl ExpectedCloseEvent { - pub fn from_id_reason(channel_id: ChannelId, discard_funding: bool, reason: ClosureReason) -> Self { + pub fn from_id_reason( + channel_id: ChannelId, discard_funding: bool, reason: ClosureReason, + ) -> Self { Self { channel_capacity_sats: None, channel_id: Some(channel_id), @@ -1777,6 +1851,7 @@ impl ExpectedCloseEvent { } /// Check that multiple channel closing events have been issued. +#[rustfmt::skip] pub fn check_closed_events(node: &Node, expected_close_events: &[ExpectedCloseEvent]) { let closed_events_count = expected_close_events.len(); let discard_events_count = expected_close_events.iter().filter(|e| e.discard_funding).count(); @@ -1814,6 +1889,7 @@ pub fn check_closed_events(node: &Node, expected_close_events: &[ExpectedCloseEv } /// Check that a channel's closing channel events has been issued +#[rustfmt::skip] pub fn check_closed_event(node: &Node, events_count: usize, expected_reason: ClosureReason, is_check_discard_funding: bool, expected_counterparty_node_ids: &[PublicKey], expected_channel_capacity: u64) { let expected_events_count = if is_check_discard_funding { @@ -1840,14 +1916,28 @@ pub fn check_closed_event(node: &Node, events_count: usize, expected_reason: Clo #[macro_export] macro_rules! check_closed_event { ($node: expr, $events: expr, $reason: expr, $counterparty_node_ids: expr, $channel_capacity: expr) => { - check_closed_event!($node, $events, $reason, false, $counterparty_node_ids, $channel_capacity); + check_closed_event!( + $node, + $events, + $reason, + false, + $counterparty_node_ids, + $channel_capacity + ); }; ($node: expr, $events: expr, $reason: expr, $is_check_discard_funding: expr, $counterparty_node_ids: expr, $channel_capacity: expr) => { - $crate::ln::functional_test_utils::check_closed_event(&$node, $events, $reason, - $is_check_discard_funding, &$counterparty_node_ids, $channel_capacity); - } + $crate::ln::functional_test_utils::check_closed_event( + &$node, + $events, + $reason, + $is_check_discard_funding, + &$counterparty_node_ids, + $channel_capacity, + ); + }; } +#[rustfmt::skip] pub fn handle_bump_htlc_event(node: &Node, count: usize) { let events = node.chain_monitor.chain_monitor.get_and_clear_pending_events(); assert_eq!(events.len(), count); @@ -1863,6 +1953,7 @@ pub fn handle_bump_htlc_event(node: &Node, count: usize) { } } +#[rustfmt::skip] pub fn close_channel<'a, 'b, 'c>(outbound_node: &Node<'a, 'b, 'c>, inbound_node: &Node<'a, 'b, 'c>, channel_id: &ChannelId, funding_tx: Transaction, close_inbound_first: bool) -> (msgs::ChannelUpdate, msgs::ChannelUpdate, Transaction) { let (node_a, broadcaster_a, struct_a) = if close_inbound_first { (&inbound_node.node, &inbound_node.tx_broadcaster, inbound_node) } else { (&outbound_node.node, &outbound_node.tx_broadcaster, outbound_node) }; let (node_b, broadcaster_b, struct_b) = if close_inbound_first { (&outbound_node.node, &outbound_node.tx_broadcaster, outbound_node) } else { (&inbound_node.node, &inbound_node.tx_broadcaster, inbound_node) }; @@ -1940,6 +2031,7 @@ pub struct SendEvent { pub commitment_msg: Vec, } impl SendEvent { + #[rustfmt::skip] pub fn from_commitment_update(node_id: PublicKey, channel_id: ChannelId, updates: msgs::CommitmentUpdate) -> SendEvent { assert!(updates.update_fulfill_htlcs.is_empty()); assert!(updates.update_fail_htlcs.is_empty()); @@ -1948,6 +2040,7 @@ impl SendEvent { SendEvent { node_id, channel_id, msgs: updates.update_add_htlcs, commitment_msg: updates.commitment_signed } } + #[rustfmt::skip] pub fn from_event(event: MessageSendEvent) -> SendEvent { match event { MessageSendEvent::UpdateHTLCs { node_id, channel_id, updates } => SendEvent::from_commitment_update(node_id, channel_id, updates), @@ -1964,6 +2057,7 @@ impl SendEvent { #[macro_export] /// Don't use this, use the identically-named function instead. +#[rustfmt::skip] macro_rules! expect_pending_htlcs_forwardable_conditions { ($node: expr, $expected_failures: expr) => { $crate::ln::functional_test_utils::expect_pending_htlcs_forwardable_conditions($node.node.get_and_clear_pending_events(), &$expected_failures); @@ -1971,6 +2065,7 @@ macro_rules! expect_pending_htlcs_forwardable_conditions { } #[macro_export] +#[rustfmt::skip] macro_rules! expect_htlc_handling_failed_destinations { ($events: expr, $expected_failures: expr) => {{ let mut num_expected_failures = $expected_failures.len(); @@ -1991,6 +2086,7 @@ macro_rules! expect_htlc_handling_failed_destinations { /// Checks that an [`Event::PendingHTLCsForwardable`] is available in the given events and, if /// there are any [`Event::HTLCHandlingFailed`] events their [`HTLCHandlingFailureType`] is included in the /// `expected_failures` set. +#[rustfmt::skip] pub fn expect_pending_htlcs_forwardable_conditions(events: Vec, expected_failures: &[HTLCHandlingFailureType]) { let count = expected_failures.len() + 1; assert_eq!(events.len(), count); @@ -2005,6 +2101,7 @@ pub fn expect_pending_htlcs_forwardable_conditions(events: Vec, expected_ /// /// Don't use this, call [`expect_pending_htlcs_forwardable_conditions()`] with an empty failure /// set instead. +#[rustfmt::skip] macro_rules! expect_pending_htlcs_forwardable_ignore { ($node: expr) => { $crate::ln::functional_test_utils::expect_pending_htlcs_forwardable_conditions($node.node.get_and_clear_pending_events(), &[]); @@ -2015,6 +2112,7 @@ macro_rules! expect_pending_htlcs_forwardable_ignore { /// Clears (and ignores) PendingHTLCsForwardable and HTLCHandlingFailed events /// /// Don't use this, call [`expect_pending_htlcs_forwardable_conditions()`] instead. +#[rustfmt::skip] macro_rules! expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore { ($node: expr, $expected_failures: expr) => { $crate::ln::functional_test_utils::expect_pending_htlcs_forwardable_conditions($node.node.get_and_clear_pending_events(), &$expected_failures); @@ -2023,6 +2121,7 @@ macro_rules! expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore { #[macro_export] /// Handles a PendingHTLCsForwardable event +#[rustfmt::skip] macro_rules! expect_pending_htlcs_forwardable { ($node: expr) => {{ $crate::ln::functional_test_utils::expect_pending_htlcs_forwardable_conditions($node.node.get_and_clear_pending_events(), &[]); @@ -2035,6 +2134,7 @@ macro_rules! expect_pending_htlcs_forwardable { #[macro_export] /// Handles a PendingHTLCsForwardable and HTLCHandlingFailed event +#[rustfmt::skip] macro_rules! expect_pending_htlcs_forwardable_and_htlc_handling_failed { ($node: expr, $expected_failures: expr) => {{ $crate::ln::functional_test_utils::expect_pending_htlcs_forwardable_conditions($node.node.get_and_clear_pending_events(), &$expected_failures); @@ -2046,6 +2146,7 @@ macro_rules! expect_pending_htlcs_forwardable_and_htlc_handling_failed { } #[cfg(any(test, feature = "_externalize_tests"))] +#[rustfmt::skip] macro_rules! expect_pending_htlcs_forwardable_from_events { ($node: expr, $events: expr, $ignore: expr) => {{ assert_eq!($events.len(), 1); @@ -2065,6 +2166,7 @@ macro_rules! expect_pending_htlcs_forwardable_from_events { #[macro_export] /// Performs the "commitment signed dance" - the series of message exchanges which occur after a /// commitment update. +#[rustfmt::skip] macro_rules! commitment_signed_dance { ($node_a: expr, $node_b: expr, $commitment_signed: expr, $fail_backwards: expr, true /* skip last step */) => { $crate::ln::functional_test_utils::do_commitment_signed_dance(&$node_a, &$node_b, &$commitment_signed, $fail_backwards, true); @@ -2101,6 +2203,7 @@ macro_rules! commitment_signed_dance { /// the commitment we're exchanging. `includes_claim` provides that information. /// /// Returns any additional message `node_b` generated in addition to the `revoke_and_ack` response. +#[rustfmt::skip] pub fn commitment_signed_dance_through_cp_raa(node_a: &Node<'_, '_, '_>, node_b: &Node<'_, '_, '_>, fail_backwards: bool, includes_claim: bool) -> Option { let (extra_msg_option, bs_revoke_and_ack) = do_main_commitment_signed_dance(node_a, node_b, fail_backwards); node_a.node.handle_revoke_and_ack(node_b.node.get_our_node_id(), &bs_revoke_and_ack); @@ -2112,6 +2215,7 @@ pub fn commitment_signed_dance_through_cp_raa(node_a: &Node<'_, '_, '_>, node_b: /// been delivered, this method picks up and delivers the response `revoke_and_ack` and /// `commitment_signed`, returning the recipient's `revoke_and_ack` and any extra message it may /// have included. +#[rustfmt::skip] pub fn do_main_commitment_signed_dance(node_a: &Node<'_, '_, '_>, node_b: &Node<'_, '_, '_>, fail_backwards: bool) -> (Option, msgs::RevokeAndACK) { let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(node_a, node_b.node.get_our_node_id()); check_added_monitors!(node_b, 0); @@ -2145,6 +2249,7 @@ pub fn do_main_commitment_signed_dance(node_a: &Node<'_, '_, '_>, node_b: &Node< /// /// If `skip_last_step` is unset, also checks for the payment failure update for the previous hop /// on failure or that no new messages are left over on success. +#[rustfmt::skip] pub fn do_commitment_signed_dance(node_a: &Node<'_, '_, '_>, node_b: &Node<'_, '_, '_>, commitment_signed: &Vec, fail_backwards: bool, skip_last_step: bool) { check_added_monitors!(node_a, 0); assert!(node_a.node.get_and_clear_pending_msg_events().is_empty()); @@ -2184,6 +2289,7 @@ pub fn do_commitment_signed_dance(node_a: &Node<'_, '_, '_>, node_b: &Node<'_, ' } /// Get a payment preimage and hash. +#[rustfmt::skip] pub fn get_payment_preimage_hash(recipient: &Node, min_value_msat: Option, min_final_cltv_expiry_delta: Option) -> (PaymentPreimage, PaymentHash, PaymentSecret) { let mut payment_count = recipient.network_payment_count.borrow_mut(); let payment_preimage = PaymentPreimage([*payment_count; 32]); @@ -2205,11 +2311,16 @@ macro_rules! get_payment_preimage_hash { crate::get_payment_preimage_hash!($dest_node, $min_value_msat, None) }; ($dest_node: expr, $min_value_msat: expr, $min_final_cltv_expiry_delta: expr) => { - $crate::ln::functional_test_utils::get_payment_preimage_hash(&$dest_node, $min_value_msat, $min_final_cltv_expiry_delta) + $crate::ln::functional_test_utils::get_payment_preimage_hash( + &$dest_node, + $min_value_msat, + $min_final_cltv_expiry_delta, + ) }; } /// Gets a route from the given sender to the node described in `payment_params`. +#[rustfmt::skip] pub fn get_route(send_node: &Node, route_params: &RouteParameters) -> Result { let scorer = TestScorer::new(); let keys_manager = TestKeysInterface::new(&[0u8; 32], Network::Testnet); @@ -2222,6 +2333,7 @@ pub fn get_route(send_node: &Node, route_params: &RouteParameters) -> Result Result { let scorer = TestScorer::new(); let keys_manager = TestKeysInterface::new(&[0u8; 32], Network::Testnet); @@ -2237,6 +2349,7 @@ pub fn find_route(send_node: &Node, route_params: &RouteParameters) -> Result {{ let route_params = $crate::routing::router::RouteParameters::from_payment_params_and_value($payment_params, $recv_value); @@ -2247,23 +2360,42 @@ macro_rules! get_route { #[macro_export] macro_rules! get_route_and_payment_hash { ($send_node: expr, $recv_node: expr, $recv_value: expr) => {{ - let payment_params = $crate::routing::router::PaymentParameters::from_node_id($recv_node.node.get_our_node_id(), TEST_FINAL_CLTV) - .with_bolt11_features($recv_node.node.bolt11_invoice_features()).unwrap(); + let payment_params = $crate::routing::router::PaymentParameters::from_node_id( + $recv_node.node.get_our_node_id(), + TEST_FINAL_CLTV, + ) + .with_bolt11_features($recv_node.node.bolt11_invoice_features()) + .unwrap(); $crate::get_route_and_payment_hash!($send_node, $recv_node, payment_params, $recv_value) }}; ($send_node: expr, $recv_node: expr, $payment_params: expr, $recv_value: expr) => {{ - $crate::get_route_and_payment_hash!($send_node, $recv_node, $payment_params, $recv_value, None) + $crate::get_route_and_payment_hash!( + $send_node, + $recv_node, + $payment_params, + $recv_value, + None + ) }}; ($send_node: expr, $recv_node: expr, $payment_params: expr, $recv_value: expr, $max_total_routing_fee_msat: expr) => {{ - let mut route_params = $crate::routing::router::RouteParameters::from_payment_params_and_value($payment_params, $recv_value); + let mut route_params = + $crate::routing::router::RouteParameters::from_payment_params_and_value( + $payment_params, + $recv_value, + ); route_params.max_total_routing_fee_msat = $max_total_routing_fee_msat; let (payment_preimage, payment_hash, payment_secret) = - $crate::ln::functional_test_utils::get_payment_preimage_hash(&$recv_node, Some($recv_value), None); + $crate::ln::functional_test_utils::get_payment_preimage_hash( + &$recv_node, + Some($recv_value), + None, + ); let route = $crate::ln::functional_test_utils::get_route(&$send_node, &route_params); (route.unwrap(), payment_hash, payment_preimage, payment_secret) - }} + }}; } +#[rustfmt::skip] pub fn check_payment_claimable( event: &Event, expected_payment_hash: PaymentHash, expected_payment_secret: PaymentSecret, expected_recv_value: u64, expected_payment_preimage: Option, @@ -2296,6 +2428,7 @@ pub fn check_payment_claimable( #[macro_export] #[cfg(any(test, ldk_bench, feature = "_test_utils"))] +#[rustfmt::skip] macro_rules! expect_payment_claimable { ($node: expr, $expected_payment_hash: expr, $expected_payment_secret: expr, $expected_recv_value: expr) => { expect_payment_claimable!($node, $expected_payment_hash, $expected_payment_secret, $expected_recv_value, None, $node.node.get_our_node_id()) @@ -2309,6 +2442,7 @@ macro_rules! expect_payment_claimable { #[macro_export] #[cfg(any(test, ldk_bench, feature = "_test_utils"))] +#[rustfmt::skip] macro_rules! expect_payment_claimed { ($node: expr, $expected_payment_hash: expr, $expected_recv_value: expr) => { let events = $node.node.get_and_clear_pending_events(); @@ -2323,6 +2457,7 @@ macro_rules! expect_payment_claimed { } } +#[rustfmt::skip] pub fn expect_payment_sent>(node: &H, expected_payment_preimage: PaymentPreimage, expected_fee_msat_opt: Option>, expect_per_path_claims: bool, expect_post_ev_mon_update: bool, @@ -2375,12 +2510,22 @@ macro_rules! expect_payment_sent { $crate::expect_payment_sent!($node, $expected_payment_preimage, None::, true) }; ($node: expr, $expected_payment_preimage: expr, $expected_fee_msat_opt: expr) => { - $crate::expect_payment_sent!($node, $expected_payment_preimage, $expected_fee_msat_opt, true) + $crate::expect_payment_sent!( + $node, + $expected_payment_preimage, + $expected_fee_msat_opt, + true + ) }; ($node: expr, $expected_payment_preimage: expr, $expected_fee_msat_opt: expr, $expect_paths: expr) => { - $crate::ln::functional_test_utils::expect_payment_sent(&$node, $expected_payment_preimage, - $expected_fee_msat_opt.map(|o| Some(o)), $expect_paths, true) - } + $crate::ln::functional_test_utils::expect_payment_sent( + &$node, + $expected_payment_preimage, + $expected_fee_msat_opt.map(|o| Some(o)), + $expect_paths, + true, + ) + }; } #[macro_export] @@ -2392,10 +2537,11 @@ macro_rules! expect_payment_path_successful { $crate::events::Event::PaymentPathSuccessful { .. } => {}, _ => panic!("Unexpected event"), } - } + }; } /// Returns the total fee earned by this HTLC forward, in msat. +#[rustfmt::skip] pub fn expect_payment_forwarded>( event: Event, node: &H, prev_node: &H, next_node: &H, expected_fee: Option, expected_extra_fees_msat: Option, upstream_force_closed: bool, @@ -2459,6 +2605,7 @@ pub fn expect_payment_forwarded>( } #[macro_export] +#[rustfmt::skip] macro_rules! expect_payment_forwarded { ($node: expr, $prev_node: expr, $next_node: expr, $expected_fee: expr, $upstream_force_closed: expr, $downstream_force_closed: expr) => { let mut events = $node.node.get_and_clear_pending_events(); @@ -2471,6 +2618,7 @@ macro_rules! expect_payment_forwarded { } #[macro_export] +#[rustfmt::skip] macro_rules! expect_channel_shutdown_state { ($node: expr, $chan_id: expr, $state: path) => { let chan_details = $node.node.list_channels().into_iter().filter(|cd| cd.channel_id == $chan_id).collect::>(); @@ -2480,7 +2628,9 @@ macro_rules! expect_channel_shutdown_state { } #[cfg(any(test, ldk_bench, feature = "_test_utils"))] -pub fn expect_channel_pending_event<'a, 'b, 'c, 'd>(node: &'a Node<'b, 'c, 'd>, expected_counterparty_node_id: &PublicKey) -> ChannelId { +pub fn expect_channel_pending_event<'a, 'b, 'c, 'd>( + node: &'a Node<'b, 'c, 'd>, expected_counterparty_node_id: &PublicKey, +) -> ChannelId { let events = node.node.get_and_clear_pending_events(); assert_eq!(events.len(), 1); match &events[0] { @@ -2493,6 +2643,7 @@ pub fn expect_channel_pending_event<'a, 'b, 'c, 'd>(node: &'a Node<'b, 'c, 'd>, } #[cfg(any(test, ldk_bench, feature = "_test_utils"))] +#[rustfmt::skip] pub fn expect_channel_ready_event<'a, 'b, 'c, 'd>(node: &'a Node<'b, 'c, 'd>, expected_counterparty_node_id: &PublicKey) { let events = node.node.get_and_clear_pending_events(); assert_eq!(events.len(), 1); @@ -2504,6 +2655,7 @@ pub fn expect_channel_ready_event<'a, 'b, 'c, 'd>(node: &'a Node<'b, 'c, 'd>, ex } } +#[rustfmt::skip] pub fn expect_probe_successful_events(node: &Node, mut probe_results: Vec<(PaymentHash, PaymentId)>) { let mut events = node.node.get_and_clear_pending_events(); @@ -2553,7 +2705,9 @@ impl<'a> PaymentFailedConditions<'a> { self.expected_blamed_chan_closed = Some(closed); self } - pub fn expected_htlc_error_data(mut self, reason: LocalHTLCFailureReason, data: &'a [u8]) -> Self { + pub fn expected_htlc_error_data( + mut self, reason: LocalHTLCFailureReason, data: &'a [u8], + ) -> Self { self.expected_htlc_error_data = Some((reason, data)); self } @@ -2564,6 +2718,7 @@ impl<'a> PaymentFailedConditions<'a> { } #[cfg(any(test, feature = "_externalize_tests"))] +#[rustfmt::skip] macro_rules! expect_payment_failed_with_update { ($node: expr, $expected_payment_hash: expr, $payment_failed_permanently: expr, $scid: expr, $chan_closed: expr) => { $crate::ln::functional_test_utils::expect_payment_failed_conditions( @@ -2585,6 +2740,7 @@ macro_rules! expect_payment_failed { }; } +#[rustfmt::skip] pub fn expect_payment_failed_conditions_event<'a, 'b, 'c, 'd, 'e>( payment_failed_events: Vec, expected_payment_hash: PaymentHash, expected_payment_failed_permanently: bool, conditions: PaymentFailedConditions<'e> @@ -2646,6 +2802,7 @@ pub fn expect_payment_failed_conditions_event<'a, 'b, 'c, 'd, 'e>( } } +#[rustfmt::skip] pub fn expect_payment_failed_conditions<'a, 'b, 'c, 'd, 'e>( node: &'a Node<'b, 'c, 'd>, expected_payment_hash: PaymentHash, expected_payment_failed_permanently: bool, conditions: PaymentFailedConditions<'e> @@ -2654,6 +2811,7 @@ pub fn expect_payment_failed_conditions<'a, 'b, 'c, 'd, 'e>( expect_payment_failed_conditions_event(events, expected_payment_hash, expected_payment_failed_permanently, conditions); } +#[rustfmt::skip] pub fn send_along_route_with_secret<'a, 'b, 'c>(origin_node: &Node<'a, 'b, 'c>, route: Route, expected_paths: &[&[&Node<'a, 'b, 'c>]], recv_value: u64, our_payment_hash: PaymentHash, our_payment_secret: PaymentSecret) -> PaymentId { let payment_id = PaymentId(origin_node.keys_manager.backing.get_secure_random_bytes()); origin_node.router.expect_find_route(route.route_params.clone().unwrap(), Ok(route.clone())); @@ -2666,6 +2824,7 @@ pub fn send_along_route_with_secret<'a, 'b, 'c>(origin_node: &Node<'a, 'b, 'c>, payment_id } +#[rustfmt::skip] fn fail_payment_along_path<'a, 'b, 'c>(expected_path: &[&Node<'a, 'b, 'c>]) { let origin_node_id = expected_path[0].node.get_our_node_id(); @@ -2698,6 +2857,7 @@ pub struct PassAlongPathArgs<'a, 'b, 'c, 'd> { } impl<'a, 'b, 'c, 'd> PassAlongPathArgs<'a, 'b, 'c, 'd> { + #[rustfmt::skip] pub fn new( origin_node: &'a Node<'b, 'c, 'd>, expected_path: &'a [&'a Node<'b, 'c, 'd>], recv_value: u64, payment_hash: PaymentHash, event: MessageSendEvent, @@ -2744,6 +2904,7 @@ impl<'a, 'b, 'c, 'd> PassAlongPathArgs<'a, 'b, 'c, 'd> { } } +#[rustfmt::skip] pub fn do_pass_along_path<'a, 'b, 'c>(args: PassAlongPathArgs) -> Option { let PassAlongPathArgs { origin_node, expected_path, recv_value, payment_hash: our_payment_hash, @@ -2847,6 +3008,7 @@ pub fn do_pass_along_path<'a, 'b, 'c>(args: PassAlongPathArgs) -> Option event } +#[rustfmt::skip] pub fn pass_along_path<'a, 'b, 'c>(origin_node: &Node<'a, 'b, 'c>, expected_path: &[&Node<'a, 'b, 'c>], recv_value: u64, our_payment_hash: PaymentHash, our_payment_secret: Option, ev: MessageSendEvent, payment_claimable_expected: bool, expected_preimage: Option) -> Option { let mut args = PassAlongPathArgs::new(origin_node, expected_path, recv_value, our_payment_hash, ev); if !payment_claimable_expected { @@ -2861,6 +3023,7 @@ pub fn pass_along_path<'a, 'b, 'c>(origin_node: &Node<'a, 'b, 'c>, expected_path do_pass_along_path(args) } +#[rustfmt::skip] pub fn send_probe_along_route<'a, 'b, 'c>(origin_node: &Node<'a, 'b, 'c>, expected_route: &[(&[&Node<'a, 'b, 'c>], PaymentHash)]) { let mut events = origin_node.node.get_and_clear_pending_msg_events(); assert_eq!(events.len(), expected_route.len()); @@ -2884,6 +3047,7 @@ pub fn send_probe_along_route<'a, 'b, 'c>(origin_node: &Node<'a, 'b, 'c>, expect } } +#[rustfmt::skip] pub fn pass_along_route<'a, 'b, 'c>(origin_node: &Node<'a, 'b, 'c>, expected_route: &[&[&Node<'a, 'b, 'c>]], recv_value: u64, our_payment_hash: PaymentHash, our_payment_secret: PaymentSecret) { let mut events = origin_node.node.get_and_clear_pending_msg_events(); assert_eq!(events.len(), expected_route.len()); @@ -2897,12 +3061,14 @@ pub fn pass_along_route<'a, 'b, 'c>(origin_node: &Node<'a, 'b, 'c>, expected_rou } } +#[rustfmt::skip] pub fn send_along_route<'a, 'b, 'c>(origin_node: &Node<'a, 'b, 'c>, route: Route, expected_route: &[&Node<'a, 'b, 'c>], recv_value: u64) -> (PaymentPreimage, PaymentHash, PaymentSecret, PaymentId) { let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(expected_route.last().unwrap()); let payment_id = send_along_route_with_secret(origin_node, route, &[expected_route], recv_value, our_payment_hash, our_payment_secret); (our_payment_preimage, our_payment_hash, our_payment_secret, payment_id) } +#[rustfmt::skip] pub fn do_claim_payment_along_route(args: ClaimAlongRouteArgs) -> u64 { for path in args.expected_paths.iter() { assert_eq!(path.last().unwrap().node.get_our_node_id(), args.expected_paths[0].last().unwrap().node.get_our_node_id()); @@ -2930,6 +3096,7 @@ pub struct ClaimAlongRouteArgs<'a, 'b, 'c, 'd> { } impl<'a, 'b, 'c, 'd> ClaimAlongRouteArgs<'a, 'b, 'c, 'd> { + #[rustfmt::skip] pub fn new( origin_node: &'a Node<'b, 'c, 'd>, expected_paths: &'a [&'a [&'a Node<'b, 'c, 'd>]], payment_preimage: PaymentPreimage, @@ -2962,6 +3129,7 @@ impl<'a, 'b, 'c, 'd> ClaimAlongRouteArgs<'a, 'b, 'c, 'd> { } } +#[rustfmt::skip] pub fn pass_claimed_payment_along_route(args: ClaimAlongRouteArgs) -> u64 { let ClaimAlongRouteArgs { origin_node, expected_paths, expected_extra_fees, expected_min_htlc_overpay, skip_last, @@ -3013,6 +3181,7 @@ pub fn pass_claimed_payment_along_route(args: ClaimAlongRouteArgs) -> u64 { let mut expected_total_fee_msat = 0; + #[rustfmt::skip] macro_rules! msgs_from_ev { ($ev: expr) => { match $ev { @@ -3051,6 +3220,7 @@ pub fn pass_claimed_payment_along_route(args: ClaimAlongRouteArgs) -> u64 { let mut next_msgs = Some(path_msgs); let mut expected_next_node = next_hop; + #[rustfmt::skip] macro_rules! last_update_fulfill_dance { ($node: expr, $prev_node: expr) => { { @@ -3061,6 +3231,7 @@ pub fn pass_claimed_payment_along_route(args: ClaimAlongRouteArgs) -> u64 { } } } + #[rustfmt::skip] macro_rules! mid_update_fulfill_dance { ($idx: expr, $node: expr, $prev_node: expr, $next_node: expr, $new_msgs: expr) => { { @@ -3159,6 +3330,7 @@ pub fn claim_payment_along_route(args: ClaimAlongRouteArgs) -> Option(origin_node: &Node<'a, 'b, 'c>, expected_route: &[&Node<'a, 'b, 'c>], our_payment_preimage: PaymentPreimage) -> Option { claim_payment_along_route( ClaimAlongRouteArgs::new(origin_node, &[expected_route], our_payment_preimage) @@ -3167,6 +3339,7 @@ pub fn claim_payment<'a, 'b, 'c>(origin_node: &Node<'a, 'b, 'c>, expected_route: pub const TEST_FINAL_CLTV: u32 = 70; +#[rustfmt::skip] pub fn route_payment<'a, 'b, 'c>(origin_node: &Node<'a, 'b, 'c>, expected_route: &[&Node<'a, 'b, 'c>], recv_value: u64) -> (PaymentPreimage, PaymentHash, PaymentSecret, PaymentId) { let payment_params = PaymentParameters::from_node_id(expected_route.last().unwrap().node.get_our_node_id(), TEST_FINAL_CLTV) .with_bolt11_features(expected_route.last().unwrap().node.bolt11_invoice_features()).unwrap(); @@ -3182,12 +3355,15 @@ pub fn route_payment<'a, 'b, 'c>(origin_node: &Node<'a, 'b, 'c>, expected_route: (res.0, res.1, res.2, res.3) } -pub fn send_payment<'a, 'b, 'c>(origin: &Node<'a, 'b, 'c>, expected_route: &[&Node<'a, 'b, 'c>], recv_value: u64) -> (PaymentPreimage, PaymentHash, PaymentSecret, PaymentId) { +pub fn send_payment<'a, 'b, 'c>( + origin: &Node<'a, 'b, 'c>, expected_route: &[&Node<'a, 'b, 'c>], recv_value: u64, +) -> (PaymentPreimage, PaymentHash, PaymentSecret, PaymentId) { let res = route_payment(&origin, expected_route, recv_value); claim_payment(&origin, expected_route, res.0); res } +#[rustfmt::skip] pub fn fail_payment_along_route<'a, 'b, 'c>(origin_node: &Node<'a, 'b, 'c>, expected_paths: &[&[&Node<'a, 'b, 'c>]], skip_last: bool, our_payment_hash: PaymentHash) { for path in expected_paths.iter() { assert_eq!(path.last().unwrap().node.get_our_node_id(), expected_paths[0].last().unwrap().node.get_our_node_id()); @@ -3199,6 +3375,7 @@ pub fn fail_payment_along_route<'a, 'b, 'c>(origin_node: &Node<'a, 'b, 'c>, expe pass_failed_payment_back(origin_node, expected_paths, skip_last, our_payment_hash, PaymentFailureReason::RecipientRejected); } +#[rustfmt::skip] pub fn pass_failed_payment_back<'a, 'b, 'c>(origin_node: &Node<'a, 'b, 'c>, expected_paths_slice: &[&[&Node<'a, 'b, 'c>]], skip_last: bool, our_payment_hash: PaymentHash, expected_fail_reason: PaymentFailureReason) { let mut expected_paths: Vec<_> = expected_paths_slice.iter().collect(); check_added_monitors!(expected_paths[0].last().unwrap(), expected_paths.len()); @@ -3305,7 +3482,10 @@ pub fn pass_failed_payment_back<'a, 'b, 'c>(origin_node: &Node<'a, 'b, 'c>, expe check_added_monitors!(expected_paths[0].last().unwrap(), 0); } -pub fn fail_payment<'a, 'b, 'c>(origin_node: &Node<'a, 'b, 'c>, expected_path: &[&Node<'a, 'b, 'c>], our_payment_hash: PaymentHash) { +pub fn fail_payment<'a, 'b, 'c>( + origin_node: &Node<'a, 'b, 'c>, expected_path: &[&Node<'a, 'b, 'c>], + our_payment_hash: PaymentHash, +) { fail_payment_along_route(origin_node, &[&expected_path[..]], false, our_payment_hash); } @@ -3313,6 +3493,7 @@ pub fn create_chanmon_cfgs(node_count: usize) -> Vec { create_chanmon_cfgs_with_keys(node_count, None) } +#[rustfmt::skip] pub fn create_chanmon_cfgs_with_keys(node_count: usize, predefined_keys_ids: Option>) -> Vec { let mut chan_mon_cfgs = Vec::new(); for i in 0..node_count { @@ -3338,10 +3519,12 @@ pub fn create_chanmon_cfgs_with_keys(node_count: usize, predefined_keys_ids: Opt chan_mon_cfgs } +#[rustfmt::skip] pub fn create_node_cfgs<'a>(node_count: usize, chanmon_cfgs: &'a Vec) -> Vec> { create_node_cfgs_with_persisters(node_count, chanmon_cfgs, chanmon_cfgs.iter().map(|c| &c.persister).collect()) } +#[rustfmt::skip] pub fn create_node_cfgs_with_persisters<'a>(node_count: usize, chanmon_cfgs: &'a Vec, persisters: Vec<&'a impl test_utils::SyncPersist>) -> Vec> { let mut nodes = Vec::new(); @@ -3385,6 +3568,7 @@ pub fn test_default_channel_config() -> UserConfig { default_config } +#[rustfmt::skip] pub fn create_node_chanmgrs<'a, 'b>(node_count: usize, cfgs: &'a Vec>, node_config: &[Option]) -> Vec, &'b test_utils::TestBroadcaster, &'a test_utils::TestKeysInterface, &'a test_utils::TestKeysInterface, &'a test_utils::TestKeysInterface, &'b test_utils::TestFeeEstimator, &'a test_utils::TestRouter<'b>, &'a test_utils::TestMessageRouter<'b>, &'b test_utils::TestLogger>> { let mut chanmgrs = Vec::new(); for i in 0..node_count { @@ -3402,6 +3586,7 @@ pub fn create_node_chanmgrs<'a, 'b>(node_count: usize, cfgs: &'a Vec chanmgrs } +#[rustfmt::skip] pub fn create_network<'a, 'b: 'a, 'c: 'b>(node_count: usize, cfgs: &'b Vec>, chan_mgrs: &'a Vec, &'c test_utils::TestBroadcaster, &'b test_utils::TestKeysInterface, &'b test_utils::TestKeysInterface, &'b test_utils::TestKeysInterface, &'c test_utils::TestFeeEstimator, &'c test_utils::TestRouter, &'c test_utils::TestMessageRouter, &'c test_utils::TestLogger>>) -> Vec> { let mut nodes = Vec::new(); let chan_count = Rc::new(RefCell::new(0)); @@ -3473,6 +3658,7 @@ pub fn connect_nodes<'a, 'b: 'a, 'c: 'b>(node_a: &Node<'a, 'b, 'c>, node_b: &Nod node_b.onion_messenger.peer_connected(node_id_a, &init_a, false).unwrap(); } +#[rustfmt::skip] pub fn connect_dummy_node<'a, 'b: 'a, 'c: 'b>(node: &Node<'a, 'b, 'c>) { let node_id_dummy = PublicKey::from_slice(&[2; 33]).unwrap(); @@ -3500,7 +3686,11 @@ pub const ACCEPTED_HTLC_SCRIPT_WEIGHT: usize = 137; // Here we have a diff due t pub const ACCEPTED_HTLC_SCRIPT_WEIGHT_ANCHORS: usize = 140; // Here we have a diff due to HTLC CLTV expiry being < 2^15 in test #[derive(PartialEq)] -pub enum HTLCType { NONE, TIMEOUT, SUCCESS } +pub enum HTLCType { + NONE, + TIMEOUT, + SUCCESS, +} /// Tests that the given node has broadcast transactions for the given Channel /// /// First checks that the latest holder commitment tx has been broadcast, unless an explicit @@ -3512,6 +3702,7 @@ pub enum HTLCType { NONE, TIMEOUT, SUCCESS } /// /// All broadcast transactions must be accounted for in one of the above three types of we'll /// also fail. +#[rustfmt::skip] pub fn test_txn_broadcast<'a, 'b, 'c>(node: &Node<'a, 'b, 'c>, chan: &(msgs::ChannelUpdate, msgs::ChannelUpdate, ChannelId, Transaction), commitment_tx: Option, has_htlc_tx: HTLCType) -> Vec { let mut node_txn = node.tx_broadcaster.txn_broadcasted.lock().unwrap(); let mut txn_seen = new_hash_set(); @@ -3559,6 +3750,7 @@ pub fn test_txn_broadcast<'a, 'b, 'c>(node: &Node<'a, 'b, 'c>, chan: &(msgs::Cha /// Tests that the given node has broadcast a claim transaction against the provided revoked /// HTLC transaction. +#[rustfmt::skip] pub fn test_revoked_htlc_claim_txn_broadcast<'a, 'b, 'c>(node: &Node<'a, 'b, 'c>, revoked_tx: Transaction, commitment_revoked_tx: Transaction) { let mut node_txn = node.tx_broadcaster.txn_broadcasted.lock().unwrap(); // We may issue multiple claiming transaction on revoked outputs due to block rescan @@ -3577,7 +3769,9 @@ pub fn test_revoked_htlc_claim_txn_broadcast<'a, 'b, 'c>(node: &Node<'a, 'b, 'c> assert!(node_txn.is_empty()); } -pub fn check_preimage_claim<'a, 'b, 'c>(node: &Node<'a, 'b, 'c>, prev_txn: &Vec) -> Vec { +pub fn check_preimage_claim<'a, 'b, 'c>( + node: &Node<'a, 'b, 'c>, prev_txn: &Vec, +) -> Vec { let mut node_txn = node.tx_broadcaster.txn_broadcasted.lock().unwrap(); let mut txn_seen = new_hash_set(); node_txn.retain(|tx| txn_seen.insert(tx.compute_txid())); @@ -3605,6 +3799,7 @@ pub fn check_preimage_claim<'a, 'b, 'c>(node: &Node<'a, 'b, 'c>, prev_txn: &Vec< res } +#[rustfmt::skip] pub fn handle_announce_close_broadcast_events<'a, 'b, 'c>(nodes: &Vec>, a: usize, b: usize, needs_err_handle: bool, expected_error: &str) { let mut dummy_connected = false; if !is_any_peer_connected(&nodes[a]) { @@ -3676,11 +3871,13 @@ pub fn handle_announce_close_broadcast_events<'a, 'b, 'c>(nodes: &Vec(nodes: &Vec>, a: usize, b: usize) { handle_announce_close_broadcast_events(nodes, a, b, false, "Channel closed because commitment or closing transaction was confirmed on chain."); } #[cfg(any(test, feature = "_externalize_tests"))] +#[rustfmt::skip] macro_rules! get_channel_value_stat { ($node: expr, $counterparty_node: expr, $channel_id: expr) => {{ let peer_state_lock = $node.node.per_peer_state.read().unwrap(); @@ -3690,6 +3887,7 @@ macro_rules! get_channel_value_stat { }} } +#[rustfmt::skip] macro_rules! get_chan_reestablish_msgs { ($src_node: expr, $dst_node: expr) => { { @@ -3712,6 +3910,7 @@ macro_rules! get_chan_reestablish_msgs { } } +#[rustfmt::skip] macro_rules! handle_chan_reestablish_msgs { ($src_node: expr, $dst_node: expr) => { { @@ -3828,6 +4027,7 @@ impl<'a, 'b, 'c, 'd> ReconnectArgs<'a, 'b, 'c, 'd> { /// pending_htlc_adds includes both the holding cell and in-flight update_add_htlcs, whereas /// for claims/fails they are separated out. +#[rustfmt::skip] pub fn reconnect_nodes<'a, 'b, 'c, 'd>(args: ReconnectArgs<'a, 'b, 'c, 'd>) { let ReconnectArgs { node_a, node_b, send_channel_ready, pending_htlc_adds, pending_htlc_claims, pending_htlc_fails, @@ -4013,6 +4213,7 @@ pub fn reconnect_nodes<'a, 'b, 'c, 'd>(args: ReconnectArgs<'a, 'b, 'c, 'd>) { /// Initiates channel opening and creates a single batch funding transaction. /// This will go through the open_channel / accept_channel flow, and return the batch funding /// transaction with corresponding funding_created messages. +#[rustfmt::skip] pub fn create_batch_channel_funding<'a, 'b, 'c>( funding_node: &Node<'a, 'b, 'c>, params: &[(&Node<'a, 'b, 'c>, u64, u64, u128, Option)], diff --git a/lightning/src/ln/max_payment_path_len_tests.rs b/lightning/src/ln/max_payment_path_len_tests.rs index d83f1800e1e..53529a60fd5 100644 --- a/lightning/src/ln/max_payment_path_len_tests.rs +++ b/lightning/src/ln/max_payment_path_len_tests.rs @@ -1,5 +1,3 @@ -#![cfg_attr(rustfmt, rustfmt_skip)] - // This file is Copyright its original authors, visible in version control // history. // @@ -12,14 +10,14 @@ //! Tests for calculating the maximum length of a path based on the payment metadata, custom TLVs, //! and/or blinded paths present. -use bitcoin::secp256k1::{Secp256k1, PublicKey}; +use crate::blinded_path::payment::{ + BlindedPayInfo, BlindedPaymentPath, Bolt12RefundContext, PaymentConstraints, PaymentContext, + UnauthenticatedReceiveTlvs, +}; use crate::blinded_path::BlindedHop; -use crate::blinded_path::payment::{BlindedPayInfo, BlindedPaymentPath, Bolt12RefundContext, PaymentConstraints, PaymentContext, UnauthenticatedReceiveTlvs}; use crate::events::Event; -use crate::types::payment::PaymentSecret; use crate::ln::blinded_payment_tests::get_blinded_route_parameters; use crate::ln::channelmanager::PaymentId; -use crate::types::features::BlindedHopFeatures; use crate::ln::functional_test_utils::*; use crate::ln::msgs; use crate::ln::msgs::{BaseMessageHandler, OnionMessageHandler}; @@ -28,11 +26,16 @@ use crate::ln::onion_utils::MIN_FINAL_VALUE_ESTIMATE_WITH_OVERPAY; use crate::ln::outbound_payment::{RecipientOnionFields, Retry, RetryableSendFailure}; use crate::offers::nonce::Nonce; use crate::prelude::*; -use crate::routing::router::{PaymentParameters, RouteParameters, RouteParametersConfig, DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA}; +use crate::routing::router::{ + PaymentParameters, RouteParameters, RouteParametersConfig, DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA, +}; use crate::sign::NodeSigner; +use crate::types::features::BlindedHopFeatures; +use crate::types::payment::PaymentSecret; use crate::util::errors::APIError; use crate::util::ser::Writeable; use crate::util::test_utils; +use bitcoin::secp256k1::{PublicKey, Secp256k1}; // 3+32 (payload length and HMAC) + 2+8 (amt_to_forward) + // 2+4 (outgoing_cltv_value) + 2+8 (short_channel_id) @@ -42,6 +45,7 @@ const INTERMED_PAYLOAD_LEN_ESTIMATE: usize = 61; const PAYLOAD_HMAC_LEN: usize = 32; #[test] +#[rustfmt::skip] fn large_payment_metadata() { // Test that we'll limit our maximum path length based on the size of the provided // payment_metadata, and refuse to send at all prior to pathfinding if it's too large. @@ -147,6 +151,7 @@ fn large_payment_metadata() { } #[test] +#[rustfmt::skip] fn one_hop_blinded_path_with_custom_tlv() { // Test that we'll limit our maximum path length when paying to a 1-hop blinded path based on the // size of the provided custom TLV, and refuse to send at all prior to pathfinding if it's too @@ -257,6 +262,7 @@ fn one_hop_blinded_path_with_custom_tlv() { } #[test] +#[rustfmt::skip] fn blinded_path_with_custom_tlv() { // Test that we'll limit our maximum path length when paying to a blinded path based on the size // of the provided custom TLV, and refuse to send at all prior to pathfinding if it's too large. @@ -365,6 +371,7 @@ fn blinded_path_with_custom_tlv() { } #[test] +#[rustfmt::skip] fn bolt12_invoice_too_large_blinded_paths() { // Check that we'll fail paying BOLT 12 invoices with too-large blinded paths prior to // pathfinding. diff --git a/lightning/src/ln/mod.rs b/lightning/src/ln/mod.rs index 89f877686ca..8d741f2954d 100644 --- a/lightning/src/ln/mod.rs +++ b/lightning/src/ln/mod.rs @@ -1,5 +1,3 @@ -#![cfg_attr(rustfmt, rustfmt_skip)] - // This file is Copyright its original authors, visible in version control // history. // @@ -15,15 +13,15 @@ #[macro_use] pub mod functional_test_utils; -pub mod onion_payment; -pub mod channelmanager; +pub mod chan_utils; pub mod channel_keys; pub mod channel_state; +pub mod channelmanager; +mod features; pub mod inbound_payment; pub mod msgs; +pub mod onion_payment; pub mod peer_handler; -pub mod chan_utils; -mod features; pub mod script; pub mod types; @@ -59,64 +57,64 @@ pub use onion_utils::process_onion_failure; #[cfg(fuzzing)] pub use onion_utils::AttributionData; +#[cfg(all(test, async_payments))] +#[allow(unused_mut)] +mod async_payments_tests; #[cfg(test)] #[allow(unused_mut)] -pub mod bolt11_payment_tests; +mod async_signer_tests; #[cfg(test)] #[allow(unused_mut)] mod blinded_payment_tests; -#[cfg(all(test, async_payments))] +#[cfg(test)] #[allow(unused_mut)] -mod async_payments_tests; +pub mod bolt11_payment_tests; +#[cfg(test)] +#[allow(unused_mut)] +mod chanmon_update_fail_tests; +#[cfg(test)] +#[allow(unused_mut)] +mod dual_funding_tests; #[cfg(any(test, feature = "_externalize_tests"))] #[allow(unused_mut)] pub mod functional_tests; #[cfg(any(test, feature = "_externalize_tests"))] #[allow(unused_mut)] pub mod htlc_reserve_unit_tests; -#[cfg(any(test, feature = "_externalize_tests"))] -#[allow(unused_mut)] -pub mod update_fee_tests; -#[cfg(all(test, splicing))] -#[allow(unused_mut)] -mod splicing_tests; #[cfg(test)] #[allow(unused_mut)] mod max_payment_path_len_tests; #[cfg(test)] #[allow(unused_mut)] -mod payment_tests; -#[cfg(test)] -#[allow(unused_mut)] -mod priv_short_conf_tests; -#[cfg(test)] -#[allow(unused_mut)] -mod chanmon_update_fail_tests; -#[cfg(test)] -#[allow(unused_mut)] -mod reorg_tests; +mod monitor_tests; #[cfg(test)] #[allow(unused_mut)] -mod reload_tests; +mod offers_tests; #[cfg(test)] #[allow(unused_mut)] mod onion_route_tests; #[cfg(test)] #[allow(unused_mut)] -mod monitor_tests; +mod payment_tests; #[cfg(test)] #[allow(unused_mut)] -mod shutdown_tests; +mod priv_short_conf_tests; #[cfg(test)] mod quiescence_tests; #[cfg(test)] #[allow(unused_mut)] -mod async_signer_tests; +mod reload_tests; #[cfg(test)] #[allow(unused_mut)] -mod offers_tests; +mod reorg_tests; #[cfg(test)] #[allow(unused_mut)] -mod dual_funding_tests; +mod shutdown_tests; +#[cfg(all(test, splicing))] +#[allow(unused_mut)] +mod splicing_tests; +#[cfg(any(test, feature = "_externalize_tests"))] +#[allow(unused_mut)] +pub mod update_fee_tests; pub use self::peer_channel_encryptor::LN_MAX_MSG_LEN; diff --git a/lightning/src/ln/monitor_tests.rs b/lightning/src/ln/monitor_tests.rs index 587f7343b06..bed03154104 100644 --- a/lightning/src/ln/monitor_tests.rs +++ b/lightning/src/ln/monitor_tests.rs @@ -1,5 +1,3 @@ -#![cfg_attr(rustfmt, rustfmt_skip)] - // This file is Copyright its original authors, visible in version control // history. // @@ -11,35 +9,43 @@ //! Further functional tests which test blockchain reorganizations. -use crate::sign::{ecdsa::EcdsaChannelSigner, OutputSpender, SignerProvider, SpendableOutputDescriptor}; -use crate::chain::channelmonitor::{ANTI_REORG_DELAY, ARCHIVAL_DELAY_BLOCKS,LATENCY_GRACE_PERIOD_BLOCKS, COUNTERPARTY_CLAIMABLE_WITHIN_BLOCKS_PINNABLE, Balance, BalanceSource, ChannelMonitorUpdateStep}; +use crate::chain::chaininterface::{ + compute_feerate_sat_per_1000_weight, ConfirmationTarget, LowerBoundedFeeEstimator, +}; +use crate::chain::channelmonitor::{ + Balance, BalanceSource, ChannelMonitorUpdateStep, ANTI_REORG_DELAY, ARCHIVAL_DELAY_BLOCKS, + COUNTERPARTY_CLAIMABLE_WITHIN_BLOCKS_PINNABLE, LATENCY_GRACE_PERIOD_BLOCKS, +}; use crate::chain::transaction::OutPoint; -use crate::chain::chaininterface::{ConfirmationTarget, LowerBoundedFeeEstimator, compute_feerate_sat_per_1000_weight}; +use crate::crypto::utils::sign; use crate::events::bump_transaction::{BumpTransactionEvent, WalletSource}; -use crate::events::{Event, ClosureReason, HTLCHandlingFailureType}; -use crate::ln::channel; -use crate::ln::types::ChannelId; +use crate::events::{ClosureReason, Event, HTLCHandlingFailureType}; use crate::ln::chan_utils; -use crate::ln::channelmanager::{BREAKDOWN_TIMEOUT, PaymentId, RecipientOnionFields}; +use crate::ln::channel; +use crate::ln::channelmanager::{PaymentId, RecipientOnionFields, BREAKDOWN_TIMEOUT}; use crate::ln::msgs::{BaseMessageHandler, ChannelMessageHandler, MessageSendEvent}; -use crate::crypto::utils::sign; -use crate::util::ser::Writeable; +use crate::ln::types::ChannelId; +use crate::sign::{ + ecdsa::EcdsaChannelSigner, OutputSpender, SignerProvider, SpendableOutputDescriptor, +}; use crate::util::scid_utils::block_from_scid; +use crate::util::ser::Writeable; -use bitcoin::{Amount, PublicKey, ScriptBuf, Transaction, TxIn, TxOut, Witness}; +use bitcoin::hex::FromHex; use bitcoin::locktime::absolute::LockTime; -use bitcoin::script::Builder; use bitcoin::opcodes; -use bitcoin::hex::FromHex; +use bitcoin::script::Builder; use bitcoin::secp256k1::{Secp256k1, SecretKey}; -use bitcoin::sighash::{SighashCache, EcdsaSighashType}; +use bitcoin::sighash::{EcdsaSighashType, SighashCache}; use bitcoin::transaction::Version; +use bitcoin::{Amount, PublicKey, ScriptBuf, Transaction, TxIn, TxOut, Witness}; use crate::prelude::*; use crate::ln::functional_test_utils::*; #[test] +#[rustfmt::skip] fn chanmon_fail_from_stale_commitment() { // If we forward an HTLC to our counterparty, but we force-closed the channel before our // counterparty provides us an updated commitment transaction, we'll end up with a commitment @@ -97,6 +103,7 @@ fn chanmon_fail_from_stale_commitment() { expect_payment_failed_with_update!(nodes[0], payment_hash, false, update_a.contents.short_channel_id, true); } +#[rustfmt::skip] fn test_spendable_output<'a, 'b, 'c, 'd>(node: &'a Node<'b, 'c, 'd>, spendable_tx: &Transaction, has_anchors_htlc_event: bool) -> Vec { let mut spendable = node.chain_monitor.chain_monitor.get_and_clear_pending_events(); assert_eq!(spendable.len(), if has_anchors_htlc_event { 2 } else { 1 }); @@ -114,6 +121,7 @@ fn test_spendable_output<'a, 'b, 'c, 'd>(node: &'a Node<'b, 'c, 'd>, spendable_t } #[test] +#[rustfmt::skip] fn revoked_output_htlc_resolution_timing() { // Tests that HTLCs which were present in a broadcasted remote revoked commitment transaction // are resolved only after a spend of the HTLC output reaches six confirmations. Previously @@ -168,6 +176,7 @@ fn revoked_output_htlc_resolution_timing() { } #[test] +#[rustfmt::skip] fn archive_fully_resolved_monitors() { // Test we archive fully resolved channel monitors at the right time. let chanmon_cfgs = create_chanmon_cfgs(2); @@ -305,6 +314,7 @@ fn archive_fully_resolved_monitors() { } } +#[rustfmt::skip] fn do_chanmon_claim_value_coop_close(anchors: bool) { // Tests `get_claimable_balances` returns the correct values across a simple cooperative claim. // Specifically, this tests that the channel non-HTLC balances show up in @@ -443,6 +453,7 @@ fn fuzzy_assert_eq>(a: V, b: V) { assert!(b_u64 >= a_u64 - 5); } +#[rustfmt::skip] fn do_test_claim_value_force_close(anchors: bool, prev_commitment_tx: bool) { // Tests `get_claimable_balances` with an HTLC across a force-close. // We build a channel with an HTLC pending, then force close the channel and check that the @@ -847,6 +858,7 @@ fn test_claim_value_force_close() { do_test_claim_value_force_close(true, false); } +#[rustfmt::skip] fn do_test_balances_on_local_commitment_htlcs(anchors: bool) { // Previously, when handling the broadcast of a local commitment transactions (with associated // CSV delays prior to spendability), we incorrectly handled the CSV delays on HTLC @@ -1104,6 +1116,7 @@ fn test_balances_on_local_commitment_htlcs() { } #[test] +#[rustfmt::skip] fn test_no_preimage_inbound_htlc_balances() { // Tests that MaybePreimageClaimableHTLC are generated for inbound HTLCs for which we do not // have a preimage. @@ -1347,6 +1360,7 @@ fn test_no_preimage_inbound_htlc_balances() { assert!(nodes[1].chain_monitor.chain_monitor.get_monitor(chan_id).unwrap().get_claimable_balances().is_empty()); } +#[rustfmt::skip] fn do_test_revoked_counterparty_commitment_balances(anchors: bool, confirm_htlc_spend_first: bool) { // Tests `get_claimable_balances` for revoked counterparty commitment transactions. let mut chanmon_cfgs = create_chanmon_cfgs(2); @@ -1637,6 +1651,7 @@ fn test_revoked_counterparty_commitment_balances() { do_test_revoked_counterparty_commitment_balances(true, false); } +#[rustfmt::skip] fn do_test_revoked_counterparty_htlc_tx_balances(anchors: bool) { // Tests `get_claimable_balances` for revocation spends of HTLC transactions. let mut chanmon_cfgs = create_chanmon_cfgs(2); @@ -1933,6 +1948,7 @@ fn test_revoked_counterparty_htlc_tx_balances() { do_test_revoked_counterparty_htlc_tx_balances(true); } +#[rustfmt::skip] fn do_test_revoked_counterparty_aggregated_claims(anchors: bool) { // Tests `get_claimable_balances` for revoked counterparty commitment transactions when // claiming with an aggregated claim transaction. @@ -2219,6 +2235,7 @@ fn test_revoked_counterparty_aggregated_claims() { do_test_revoked_counterparty_aggregated_claims(true); } +#[rustfmt::skip] fn do_test_claimable_balance_correct_while_payment_pending(outbound_payment: bool, anchors: bool) { // Previously when a user fetched their balances via `get_claimable_balances` after forwarding a // payment, but before it cleared, and summed up their balance using `Balance::claimable_amount_satoshis` @@ -2313,6 +2330,7 @@ fn test_claimable_balance_correct_while_payment_pending() { do_test_claimable_balance_correct_while_payment_pending(true, true); } +#[rustfmt::skip] fn do_test_restored_packages_retry(check_old_monitor_retries_after_upgrade: bool) { // Tests that we'll retry packages that were previously timelocked after we've restored them. let node0_key_id = <[u8; 32]>::from_hex("0000000000000000000000004D49E5DA0000000000000000000000000000002A").unwrap(); @@ -2393,6 +2411,7 @@ fn test_restored_packages_retry() { do_test_restored_packages_retry(true); } +#[rustfmt::skip] fn do_test_monitor_rebroadcast_pending_claims(anchors: bool) { // Test that we will retry broadcasting pending claims for a force-closed channel on every // `ChainMonitor::rebroadcast_pending_claims` call. @@ -2522,6 +2541,7 @@ fn test_monitor_timer_based_claim() { do_test_monitor_rebroadcast_pending_claims(true); } +#[rustfmt::skip] fn do_test_yield_anchors_events(have_htlcs: bool) { // Tests that two parties supporting anchor outputs can open a channel, route payments over // it, and finalize its resolution uncooperatively. Once the HTLCs are locked in, one side will @@ -2717,6 +2737,7 @@ fn test_yield_anchors_events() { } #[test] +#[rustfmt::skip] fn test_anchors_aggregated_revoked_htlc_tx() { // Test that `ChannelMonitor`s can properly detect and claim funds from a counterparty claiming // multiple HTLCs from multiple channels in a single transaction via the success path from a @@ -3024,6 +3045,7 @@ fn test_anchors_aggregated_revoked_htlc_tx() { assert_eq!(nodes[1].chain_monitor.chain_monitor.get_claimable_balances(&[]).len(), 6); } +#[rustfmt::skip] fn do_test_anchors_monitor_fixes_counterparty_payment_script_on_reload(confirm_commitment_before_reload: bool) { // Tests that we'll fix a ChannelMonitor's `counterparty_payment_script` for an anchor outputs // channel upon deserialization. @@ -3112,6 +3134,7 @@ fn test_anchors_monitor_fixes_counterparty_payment_script_on_reload() { } #[cfg(not(ldk_test_vectors))] +#[rustfmt::skip] fn do_test_monitor_claims_with_random_signatures(anchors: bool, confirm_counterparty_commitment: bool) { // Tests that our monitor claims will always use fresh random signatures (ensuring a unique // wtxid) to prevent certain classes of transaction replacement at the bitcoin P2P layer. @@ -3220,6 +3243,7 @@ fn test_monitor_claims_with_random_signatures() { } #[test] +#[rustfmt::skip] fn test_event_replay_causing_monitor_replay() { // In LDK 0.0.121 there was a bug where if a `PaymentSent` event caused an RAA // `ChannelMonitorUpdate` hold and then the node was restarted after the `PaymentSent` event @@ -3259,6 +3283,7 @@ fn test_event_replay_causing_monitor_replay() { } #[test] +#[rustfmt::skip] fn test_update_replay_panics() { // Tests that replaying a `ChannelMonitorUpdate` or applying them out-of-order causes a panic. let chanmon_cfgs = create_chanmon_cfgs(2); diff --git a/lightning/src/ln/offers_tests.rs b/lightning/src/ln/offers_tests.rs index 0344c23ed12..703e3c76d2b 100644 --- a/lightning/src/ln/offers_tests.rs +++ b/lightning/src/ln/offers_tests.rs @@ -1,5 +1,3 @@ -#![cfg_attr(rustfmt, rustfmt_skip)] - // This file is Copyright its original authors, visible in version control // history. // @@ -42,33 +40,44 @@ //! Nodes without channels are disconnected and connected as needed to ensure that deterministic //! blinded paths are used. -use bitcoin::network::Network; -use bitcoin::secp256k1::{PublicKey, Secp256k1}; -use core::time::Duration; -use crate::blinded_path::IntroductionNode; use crate::blinded_path::message::BlindedMessagePath; -use crate::blinded_path::payment::{Bolt12OfferContext, Bolt12RefundContext, PaymentContext}; use crate::blinded_path::message::OffersContext; -use crate::events::{ClosureReason, Event, HTLCHandlingFailureType, PaidBolt12Invoice, PaymentFailureReason, PaymentPurpose}; -use crate::ln::channelmanager::{Bolt12PaymentError, MAX_SHORT_LIVED_RELATIVE_EXPIRY, PaymentId, RecentPaymentDetails, RecipientOnionFields, Retry, self}; -use crate::types::features::Bolt12InvoiceFeatures; +use crate::blinded_path::payment::{Bolt12OfferContext, Bolt12RefundContext, PaymentContext}; +use crate::blinded_path::IntroductionNode; +use crate::events::{ + ClosureReason, Event, HTLCHandlingFailureType, PaidBolt12Invoice, PaymentFailureReason, + PaymentPurpose, +}; +use crate::ln::channelmanager::{ + self, Bolt12PaymentError, PaymentId, RecentPaymentDetails, RecipientOnionFields, Retry, + MAX_SHORT_LIVED_RELATIVE_EXPIRY, +}; use crate::ln::functional_test_utils::*; -use crate::ln::msgs::{BaseMessageHandler, ChannelMessageHandler, Init, NodeAnnouncement, OnionMessage, OnionMessageHandler, RoutingMessageHandler, SocketAddress, UnsignedGossipMessage, UnsignedNodeAnnouncement}; +use crate::ln::msgs::{ + BaseMessageHandler, ChannelMessageHandler, Init, NodeAnnouncement, OnionMessage, + OnionMessageHandler, RoutingMessageHandler, SocketAddress, UnsignedGossipMessage, + UnsignedNodeAnnouncement, +}; use crate::ln::outbound_payment::IDEMPOTENCY_TIMEOUT_TICKS; use crate::offers::invoice::Bolt12Invoice; use crate::offers::invoice_error::InvoiceError; use crate::offers::invoice_request::{InvoiceRequest, InvoiceRequestFields}; use crate::offers::nonce::Nonce; use crate::offers::parse::Bolt12SemanticError; -use crate::onion_message::messenger::{Destination, PeeledOnion, MessageSendInstructions}; +use crate::onion_message::messenger::{Destination, MessageSendInstructions, PeeledOnion}; use crate::onion_message::offers::OffersMessage; use crate::routing::gossip::{NodeAlias, NodeId}; use crate::routing::router::{PaymentParameters, RouteParameters, RouteParametersConfig}; use crate::sign::{NodeSigner, Recipient}; +use crate::types::features::Bolt12InvoiceFeatures; use crate::util::ser::Writeable; +use bitcoin::network::Network; +use bitcoin::secp256k1::{PublicKey, Secp256k1}; +use core::time::Duration; use crate::prelude::*; +#[rustfmt::skip] macro_rules! expect_recent_payment { ($node: expr, $payment_state: path, $payment_id: expr) => { match $node.node.list_recent_payments().first() { @@ -111,6 +120,7 @@ fn disconnect_peers<'a, 'b, 'c>(node_a: &Node<'a, 'b, 'c>, peers: &[&Node<'a, 'b } } +#[rustfmt::skip] fn announce_node_address<'a, 'b, 'c>( node: &Node<'a, 'b, 'c>, peers: &[&Node<'a, 'b, 'c>], address: SocketAddress, ) { @@ -143,14 +153,16 @@ fn announce_node_address<'a, 'b, 'c>( } } -fn resolve_introduction_node<'a, 'b, 'c>(node: &Node<'a, 'b, 'c>, path: &BlindedMessagePath) -> PublicKey { +fn resolve_introduction_node<'a, 'b, 'c>( + node: &Node<'a, 'b, 'c>, path: &BlindedMessagePath, +) -> PublicKey { path.public_introduction_node_id(&node.network_graph.read_only()) .and_then(|node_id| node_id.as_pubkey().ok()) .unwrap() } fn route_bolt12_payment<'a, 'b, 'c>( - node: &Node<'a, 'b, 'c>, path: &[&Node<'a, 'b, 'c>], invoice: &Bolt12Invoice + node: &Node<'a, 'b, 'c>, path: &[&Node<'a, 'b, 'c>], invoice: &Bolt12Invoice, ) { // Monitor added when handling the invoice onion message. check_added_monitors(node, 1); @@ -169,7 +181,8 @@ fn route_bolt12_payment<'a, 'b, 'c>( } fn claim_bolt12_payment<'a, 'b, 'c>( - node: &Node<'a, 'b, 'c>, path: &[&Node<'a, 'b, 'c>], expected_payment_context: PaymentContext, invoice: &Bolt12Invoice + node: &Node<'a, 'b, 'c>, path: &[&Node<'a, 'b, 'c>], expected_payment_context: PaymentContext, + invoice: &Bolt12Invoice, ) { let recipient = &path[path.len() - 1]; let payment_purpose = match get_event!(recipient, Event::PaymentClaimable) { @@ -196,6 +209,7 @@ fn claim_bolt12_payment<'a, 'b, 'c>( }; } +#[rustfmt::skip] fn extract_offer_nonce<'a, 'b, 'c>(node: &Node<'a, 'b, 'c>, message: &OnionMessage) -> Nonce { match node.onion_messenger.peel_onion_message(message) { Ok(PeeledOnion::Offers(_, Some(OffersContext::InvoiceRequest { nonce }), _)) => nonce, @@ -206,6 +220,7 @@ fn extract_offer_nonce<'a, 'b, 'c>(node: &Node<'a, 'b, 'c>, message: &OnionMessa } } +#[rustfmt::skip] pub(super) fn extract_invoice_request<'a, 'b, 'c>( node: &Node<'a, 'b, 'c>, message: &OnionMessage ) -> (InvoiceRequest, BlindedMessagePath) { @@ -223,6 +238,7 @@ pub(super) fn extract_invoice_request<'a, 'b, 'c>( } } +#[rustfmt::skip] fn extract_invoice<'a, 'b, 'c>(node: &Node<'a, 'b, 'c>, message: &OnionMessage) -> (Bolt12Invoice, BlindedMessagePath) { match node.onion_messenger.peel_onion_message(message) { Ok(PeeledOnion::Offers(message, _, reply_path)) => match message { @@ -238,6 +254,7 @@ fn extract_invoice<'a, 'b, 'c>(node: &Node<'a, 'b, 'c>, message: &OnionMessage) } } +#[rustfmt::skip] fn extract_invoice_error<'a, 'b, 'c>( node: &Node<'a, 'b, 'c>, message: &OnionMessage ) -> InvoiceError { @@ -257,6 +274,7 @@ fn extract_invoice_error<'a, 'b, 'c>( /// Checks that blinded paths without Tor-only nodes are preferred when constructing an offer. #[test] +#[rustfmt::skip] fn prefers_non_tor_nodes_in_blinded_paths() { let mut accept_forward_cfg = test_default_channel_config(); accept_forward_cfg.accept_forwards_to_priv_channels = true; @@ -326,6 +344,7 @@ fn prefers_non_tor_nodes_in_blinded_paths() { /// Checks that blinded paths prefer an introduction node that is the most connected. #[test] +#[rustfmt::skip] fn prefers_more_connected_nodes_in_blinded_paths() { let mut accept_forward_cfg = test_default_channel_config(); accept_forward_cfg.accept_forwards_to_priv_channels = true; @@ -377,6 +396,7 @@ fn prefers_more_connected_nodes_in_blinded_paths() { /// Checks that blinded paths are compact for short-lived offers. #[test] +#[rustfmt::skip] fn creates_short_lived_offer() { let chanmon_cfgs = create_chanmon_cfgs(2); let node_cfgs = create_node_cfgs(2, &chanmon_cfgs); @@ -404,6 +424,7 @@ fn creates_short_lived_offer() { /// Checks that blinded paths are not compact for long-lived offers. #[test] +#[rustfmt::skip] fn creates_long_lived_offer() { let chanmon_cfgs = create_chanmon_cfgs(2); let node_cfgs = create_node_cfgs(2, &chanmon_cfgs); @@ -439,6 +460,7 @@ fn creates_long_lived_offer() { /// Checks that blinded paths are compact for short-lived refunds. #[test] +#[rustfmt::skip] fn creates_short_lived_refund() { let chanmon_cfgs = create_chanmon_cfgs(2); let node_cfgs = create_node_cfgs(2, &chanmon_cfgs); @@ -468,6 +490,7 @@ fn creates_short_lived_refund() { /// Checks that blinded paths are not compact for long-lived refunds. #[test] +#[rustfmt::skip] fn creates_long_lived_refund() { let chanmon_cfgs = create_chanmon_cfgs(2); let node_cfgs = create_node_cfgs(2, &chanmon_cfgs); @@ -496,6 +519,7 @@ fn creates_long_lived_refund() { /// Checks that an offer can be paid through blinded paths and that ephemeral pubkeys are used /// rather than exposing a node's pubkey. #[test] +#[rustfmt::skip] fn creates_and_pays_for_offer_using_two_hop_blinded_path() { let mut accept_forward_cfg = test_default_channel_config(); accept_forward_cfg.accept_forwards_to_priv_channels = true; @@ -604,6 +628,7 @@ fn creates_and_pays_for_offer_using_two_hop_blinded_path() { /// Checks that a refund can be paid through blinded paths and that ephemeral pubkeys are used /// rather than exposing a node's pubkey. #[test] +#[rustfmt::skip] fn creates_and_pays_for_refund_using_two_hop_blinded_path() { let mut accept_forward_cfg = test_default_channel_config(); accept_forward_cfg.accept_forwards_to_priv_channels = true; @@ -688,6 +713,7 @@ fn creates_and_pays_for_refund_using_two_hop_blinded_path() { /// used rather than exposing a node's pubkey. However, the node's pubkey is still used as the /// introduction node of the blinded path. #[test] +#[rustfmt::skip] fn creates_and_pays_for_offer_using_one_hop_blinded_path() { let chanmon_cfgs = create_chanmon_cfgs(2); let node_cfgs = create_node_cfgs(2, &chanmon_cfgs); @@ -755,6 +781,7 @@ fn creates_and_pays_for_offer_using_one_hop_blinded_path() { /// used rather than exposing a node's pubkey. However, the node's pubkey is still used as the /// introduction node of the blinded path. #[test] +#[rustfmt::skip] fn creates_and_pays_for_refund_using_one_hop_blinded_path() { let chanmon_cfgs = create_chanmon_cfgs(2); let node_cfgs = create_node_cfgs(2, &chanmon_cfgs); @@ -811,6 +838,7 @@ fn creates_and_pays_for_refund_using_one_hop_blinded_path() { /// the requested is sent directly using the node's pubkey, the response and the payment still use /// blinded paths as required by the spec. #[test] +#[rustfmt::skip] fn pays_for_offer_without_blinded_paths() { let chanmon_cfgs = create_chanmon_cfgs(2); let node_cfgs = create_node_cfgs(2, &chanmon_cfgs); @@ -864,6 +892,7 @@ fn pays_for_offer_without_blinded_paths() { /// Checks that a refund without any blinded paths can be paid. Note that while the invoice is sent /// directly using the node's pubkey, the payment still use blinded paths as required by the spec. #[test] +#[rustfmt::skip] fn pays_for_refund_without_blinded_paths() { let chanmon_cfgs = create_chanmon_cfgs(2); let node_cfgs = create_node_cfgs(2, &chanmon_cfgs); @@ -907,6 +936,7 @@ fn pays_for_refund_without_blinded_paths() { /// This test checks that when multiple potential introduction nodes are available for the payer, /// multiple `invoice_request` messages are sent for the offer, each with a different `reply_path`. #[test] +#[rustfmt::skip] fn send_invoice_requests_with_distinct_reply_path() { let mut accept_forward_cfg = test_default_channel_config(); accept_forward_cfg.accept_forwards_to_priv_channels = true; @@ -991,6 +1021,7 @@ fn send_invoice_requests_with_distinct_reply_path() { /// This test checks that when multiple potential introduction nodes are available for the payee, /// multiple `Invoice` messages are sent for the Refund, each with a different `reply_path`. #[test] +#[rustfmt::skip] fn send_invoice_for_refund_with_distinct_reply_path() { let mut accept_forward_cfg = test_default_channel_config(); accept_forward_cfg.accept_forwards_to_priv_channels = true; @@ -1071,6 +1102,7 @@ fn send_invoice_for_refund_with_distinct_reply_path() { /// Verifies that the invoice request message can be retried if it fails to reach the /// payee on the first attempt. #[test] +#[rustfmt::skip] fn creates_and_pays_for_offer_with_retry() { let chanmon_cfgs = create_chanmon_cfgs(2); let node_cfgs = create_node_cfgs(2, &chanmon_cfgs); @@ -1144,6 +1176,7 @@ fn creates_and_pays_for_offer_with_retry() { /// Checks that a deferred invoice can be paid asynchronously from an Event::InvoiceReceived. #[test] +#[rustfmt::skip] fn pays_bolt12_invoice_asynchronously() { let mut manually_pay_cfg = test_default_channel_config(); manually_pay_cfg.manually_handle_bolt12_invoices = true; @@ -1239,6 +1272,7 @@ fn pays_bolt12_invoice_asynchronously() { /// is intended for the unannounced node or that the node is actually announced (e.g., an LSP) but /// the recipient doesn't have a network graph. #[test] +#[rustfmt::skip] fn creates_offer_with_blinded_path_using_unannounced_introduction_node() { let chanmon_cfgs = create_chanmon_cfgs(2); let node_cfgs = create_node_cfgs(2, &chanmon_cfgs); @@ -1305,6 +1339,7 @@ fn creates_offer_with_blinded_path_using_unannounced_introduction_node() { /// is intended for the unannounced node or that the node is actually announced (e.g., an LSP) but /// the sender doesn't have a network graph. #[test] +#[rustfmt::skip] fn creates_refund_with_blinded_path_using_unannounced_introduction_node() { let chanmon_cfgs = create_chanmon_cfgs(2); let node_cfgs = create_node_cfgs(2, &chanmon_cfgs); @@ -1347,6 +1382,7 @@ fn creates_refund_with_blinded_path_using_unannounced_introduction_node() { /// Check that authentication fails when an invoice request is handled using the wrong context /// (i.e., was sent directly or over an unexpected blinded path). #[test] +#[rustfmt::skip] fn fails_authentication_when_handling_invoice_request() { let mut accept_forward_cfg = test_default_channel_config(); accept_forward_cfg.accept_forwards_to_priv_channels = true; @@ -1459,6 +1495,7 @@ fn fails_authentication_when_handling_invoice_request() { /// Check that authentication fails when an invoice is handled using the wrong context (i.e., was /// sent over an unexpected blinded path). #[test] +#[rustfmt::skip] fn fails_authentication_when_handling_invoice_for_offer() { let mut accept_forward_cfg = test_default_channel_config(); accept_forward_cfg.accept_forwards_to_priv_channels = true; @@ -1567,6 +1604,7 @@ fn fails_authentication_when_handling_invoice_for_offer() { /// Check that authentication fails when an invoice is handled using the wrong context (i.e., was /// sent directly or over an unexpected blinded path). #[test] +#[rustfmt::skip] fn fails_authentication_when_handling_invoice_for_refund() { let mut accept_forward_cfg = test_default_channel_config(); accept_forward_cfg.accept_forwards_to_priv_channels = true; @@ -1672,6 +1710,7 @@ fn fails_authentication_when_handling_invoice_for_refund() { /// Fails creating or paying an offer when a blinded path cannot be created because no peers are /// connected. #[test] +#[rustfmt::skip] fn fails_creating_or_paying_for_offer_without_connected_peers() { let chanmon_cfgs = create_chanmon_cfgs(6); let node_cfgs = create_node_cfgs(6, &chanmon_cfgs); @@ -1731,6 +1770,7 @@ fn fails_creating_or_paying_for_offer_without_connected_peers() { /// Fails creating or sending an invoice for a refund when a blinded path cannot be created because /// no peers are connected. #[test] +#[rustfmt::skip] fn fails_creating_refund_or_sending_invoice_without_connected_peers() { let mut accept_forward_cfg = test_default_channel_config(); accept_forward_cfg.accept_forwards_to_priv_channels = true; @@ -1794,6 +1834,7 @@ fn fails_creating_refund_or_sending_invoice_without_connected_peers() { /// Fails creating an invoice request when the offer contains an unsupported chain. #[test] +#[rustfmt::skip] fn fails_creating_invoice_request_for_unsupported_chain() { let chanmon_cfgs = create_chanmon_cfgs(2); let node_cfgs = create_node_cfgs(2, &chanmon_cfgs); @@ -1820,6 +1861,7 @@ fn fails_creating_invoice_request_for_unsupported_chain() { /// Fails requesting a payment when the refund contains an unsupported chain. #[test] +#[rustfmt::skip] fn fails_sending_invoice_with_unsupported_chain_for_refund() { let chanmon_cfgs = create_chanmon_cfgs(2); let node_cfgs = create_node_cfgs(2, &chanmon_cfgs); @@ -1847,6 +1889,7 @@ fn fails_sending_invoice_with_unsupported_chain_for_refund() { /// Fails creating an invoice request when a blinded reply path cannot be created. #[test] +#[rustfmt::skip] fn fails_creating_invoice_request_without_blinded_reply_path() { let chanmon_cfgs = create_chanmon_cfgs(6); let node_cfgs = create_node_cfgs(6, &chanmon_cfgs); @@ -1880,6 +1923,7 @@ fn fails_creating_invoice_request_without_blinded_reply_path() { } #[test] +#[rustfmt::skip] fn fails_creating_invoice_request_with_duplicate_payment_id() { let chanmon_cfgs = create_chanmon_cfgs(6); let node_cfgs = create_node_cfgs(6, &chanmon_cfgs); @@ -1920,6 +1964,7 @@ fn fails_creating_invoice_request_with_duplicate_payment_id() { } #[test] +#[rustfmt::skip] fn fails_creating_refund_with_duplicate_payment_id() { let chanmon_cfgs = create_chanmon_cfgs(2); let node_cfgs = create_node_cfgs(2, &chanmon_cfgs); @@ -1948,6 +1993,7 @@ fn fails_creating_refund_with_duplicate_payment_id() { } #[test] +#[rustfmt::skip] fn fails_sending_invoice_without_blinded_payment_paths_for_offer() { let mut accept_forward_cfg = test_default_channel_config(); accept_forward_cfg.accept_forwards_to_priv_channels = true; @@ -2023,6 +2069,7 @@ fn fails_sending_invoice_without_blinded_payment_paths_for_offer() { } #[test] +#[rustfmt::skip] fn fails_sending_invoice_without_blinded_payment_paths_for_refund() { let mut accept_forward_cfg = test_default_channel_config(); accept_forward_cfg.accept_forwards_to_priv_channels = true; @@ -2069,6 +2116,7 @@ fn fails_sending_invoice_without_blinded_payment_paths_for_refund() { } #[test] +#[rustfmt::skip] fn fails_paying_invoice_more_than_once() { let mut accept_forward_cfg = test_default_channel_config(); accept_forward_cfg.accept_forwards_to_priv_channels = true; @@ -2157,6 +2205,7 @@ fn fails_paying_invoice_more_than_once() { } #[test] +#[rustfmt::skip] fn fails_paying_invoice_with_unknown_required_features() { let mut accept_forward_cfg = test_default_channel_config(); accept_forward_cfg.accept_forwards_to_priv_channels = true; @@ -2264,6 +2313,7 @@ fn fails_paying_invoice_with_unknown_required_features() { } #[test] +#[rustfmt::skip] fn rejects_keysend_to_non_static_invoice_path() { // Test that we'll fail a keysend payment that was sent over a non-static BOLT 12 invoice path. let chanmon_cfgs = create_chanmon_cfgs(2); @@ -2326,6 +2376,7 @@ fn rejects_keysend_to_non_static_invoice_path() { } #[test] +#[rustfmt::skip] fn no_double_pay_with_stale_channelmanager() { // This tests the following bug: // - An outbound payment is AwaitingInvoice diff --git a/lightning/src/ln/onion_payment.rs b/lightning/src/ln/onion_payment.rs index 998a04105a4..79952faca9a 100644 --- a/lightning/src/ln/onion_payment.rs +++ b/lightning/src/ln/onion_payment.rs @@ -1,25 +1,26 @@ -#![cfg_attr(rustfmt, rustfmt_skip)] - //! Utilities to decode payment onions and do contextless validation of incoming payments. //! //! Primarily features [`peel_payment_onion`], which allows the decoding of an onion statelessly //! and can be used to predict whether we'd accept a payment. -use bitcoin::hashes::Hash; use bitcoin::hashes::sha256::Hash as Sha256; -use bitcoin::secp256k1::{self, PublicKey, Secp256k1}; +use bitcoin::hashes::Hash; use bitcoin::secp256k1::ecdh::SharedSecret; +use bitcoin::secp256k1::{self, PublicKey, Secp256k1}; use crate::blinded_path; use crate::blinded_path::payment::{PaymentConstraints, PaymentRelay}; use crate::chain::channelmonitor::{HTLC_FAIL_BACK_BUFFER, LATENCY_GRACE_PERIOD_BLOCKS}; -use crate::types::payment::PaymentHash; -use crate::ln::channelmanager::{BlindedFailure, BlindedForward, CLTV_FAR_FAR_AWAY, HTLCFailureMsg, MIN_CLTV_EXPIRY_DELTA, PendingHTLCInfo, PendingHTLCRouting}; -use crate::types::features::BlindedHopFeatures; +use crate::ln::channelmanager::{ + BlindedFailure, BlindedForward, HTLCFailureMsg, PendingHTLCInfo, PendingHTLCRouting, + CLTV_FAR_FAR_AWAY, MIN_CLTV_EXPIRY_DELTA, +}; use crate::ln::msgs; use crate::ln::onion_utils; -use crate::ln::onion_utils::{HTLCFailReason, ONION_DATA_LEN, LocalHTLCFailureReason}; +use crate::ln::onion_utils::{HTLCFailReason, LocalHTLCFailureReason, ONION_DATA_LEN}; use crate::sign::{NodeSigner, Recipient}; +use crate::types::features::BlindedHopFeatures; +use crate::types::payment::PaymentHash; use crate::util::logger::Logger; #[allow(unused_imports)] @@ -39,13 +40,14 @@ pub struct InboundHTLCErr { } /// Writes payment data for invalid or unknown payment error code. -pub (super) fn invalid_payment_err_data(amt_msat: u64, current_height: u32) -> Vec{ +pub(super) fn invalid_payment_err_data(amt_msat: u64, current_height: u32) -> Vec { let mut err_data = Vec::with_capacity(12); err_data.extend_from_slice(&amt_msat.to_be_bytes()); err_data.extend_from_slice(¤t_height.to_be_bytes()); err_data } +#[rustfmt::skip] fn check_blinded_payment_constraints( amt_msat: u64, cltv_expiry: u32, constraints: &PaymentConstraints ) -> Result<(), ()> { @@ -55,6 +57,7 @@ fn check_blinded_payment_constraints( Ok(()) } +#[rustfmt::skip] fn check_blinded_forward( inbound_amt_msat: u64, inbound_cltv_expiry: u32, payment_relay: &PaymentRelay, payment_constraints: &PaymentConstraints, features: &BlindedHopFeatures @@ -75,7 +78,7 @@ enum RoutingInfo { Direct { short_channel_id: u64, new_packet_bytes: [u8; ONION_DATA_LEN], - next_hop_hmac: [u8; 32] + next_hop_hmac: [u8; 32], }, Trampoline { next_trampoline: PublicKey, @@ -83,10 +86,11 @@ enum RoutingInfo { new_packet_bytes: Vec, next_hop_hmac: [u8; 32], shared_secret: SharedSecret, - current_path_key: Option - } + current_path_key: Option, + }, } +#[rustfmt::skip] pub(super) fn create_fwd_pending_htlc_info( msg: &msgs::UpdateAddHTLC, hop_data: onion_utils::Hop, shared_secret: [u8; 32], next_packet_pubkey_opt: Option> @@ -239,6 +243,7 @@ pub(super) fn create_fwd_pending_htlc_info( }) } +#[rustfmt::skip] pub(super) fn create_recv_pending_htlc_info( hop_data: onion_utils::Hop, shared_secret: [u8; 32], payment_hash: PaymentHash, amt_msat: u64, cltv_expiry: u32, phantom_shared_secret: Option<[u8; 32]>, allow_underpay: bool, @@ -422,6 +427,7 @@ pub(super) fn create_recv_pending_htlc_info( /// channel, will generate an [`Event::PaymentClaimable`]. /// /// [`Event::PaymentClaimable`]: crate::events::Event::PaymentClaimable +#[rustfmt::skip] pub fn peel_payment_onion( msg: &msgs::UpdateAddHTLC, node_signer: NS, logger: L, secp_ctx: &Secp256k1, cur_height: u32, allow_skimmed_fees: bool, @@ -494,6 +500,7 @@ pub(super) struct NextPacketDetails { pub(super) outgoing_cltv_value: u32, } +#[rustfmt::skip] pub(super) fn decode_incoming_update_add_htlc_onion( msg: &msgs::UpdateAddHTLC, node_signer: NS, logger: L, secp_ctx: &Secp256k1, ) -> Result<(onion_utils::Hop, Option), (HTLCFailureMsg, LocalHTLCFailureReason)> @@ -602,7 +609,7 @@ where } pub(super) fn check_incoming_htlc_cltv( - cur_height: u32, outgoing_cltv_value: u32, cltv_expiry: u32 + cur_height: u32, outgoing_cltv_value: u32, cltv_expiry: u32, ) -> Result<(), LocalHTLCFailureReason> { if (cltv_expiry as u64) < (outgoing_cltv_value) as u64 + MIN_CLTV_EXPIRY_DELTA as u64 { return Err(LocalHTLCFailureReason::IncorrectCLTVExpiry); @@ -633,20 +640,21 @@ pub(super) fn check_incoming_htlc_cltv( #[cfg(test)] mod tests { - use bitcoin::hashes::Hash; - use bitcoin::hashes::sha256::Hash as Sha256; - use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey}; - use crate::ln::types::ChannelId; - use crate::types::payment::{PaymentPreimage, PaymentHash, PaymentSecret}; use crate::ln::channelmanager::{RecipientOnionFields, MIN_CLTV_EXPIRY_DELTA}; use crate::ln::functional_test_utils::TEST_FINAL_CLTV; - use crate::types::features::{ChannelFeatures, NodeFeatures}; use crate::ln::msgs; use crate::ln::onion_utils::create_payment_onion; + use crate::ln::types::ChannelId; use crate::routing::router::{Path, RouteHop}; + use crate::types::features::{ChannelFeatures, NodeFeatures}; + use crate::types::payment::{PaymentHash, PaymentPreimage, PaymentSecret}; use crate::util::test_utils; + use bitcoin::hashes::sha256::Hash as Sha256; + use bitcoin::hashes::Hash; + use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey}; #[test] + #[rustfmt::skip] fn fail_construct_onion_on_too_big_payloads() { // Ensure that if we call `construct_onion_packet` and friends where payloads are too large for // the allotted packet length, we'll fail to construct. Previously, senders would happily @@ -679,6 +687,7 @@ mod tests { } #[test] + #[rustfmt::skip] fn test_peel_payment_onion() { use super::*; let secp_ctx = Secp256k1::new(); @@ -733,7 +742,7 @@ mod tests { fn make_update_add_msg( amount_msat: u64, cltv_expiry: u32, payment_hash: PaymentHash, - onion_routing_packet: msgs::OnionPacket + onion_routing_packet: msgs::OnionPacket, ) -> msgs::UpdateAddHTLC { msgs::UpdateAddHTLC { channel_id: ChannelId::from_bytes([0; 32]), @@ -747,6 +756,7 @@ mod tests { } } + #[rustfmt::skip] fn payment_onion_args(hop_pk: PublicKey, recipient_pk: PublicKey) -> ( SecretKey, u64, u32, RecipientOnionFields, PaymentPreimage, PaymentHash, [u8; 32], Vec, u64, PaymentSecret, @@ -790,5 +800,4 @@ mod tests { (session_priv, total_amt_msat, cur_height, recipient_onion, preimage, payment_hash, prng_seed, hops, recipient_amount, pay_secret) } - } diff --git a/lightning/src/ln/onion_route_tests.rs b/lightning/src/ln/onion_route_tests.rs index 3af6a82c541..7609db1e3a8 100644 --- a/lightning/src/ln/onion_route_tests.rs +++ b/lightning/src/ln/onion_route_tests.rs @@ -1,5 +1,3 @@ -#![cfg_attr(rustfmt, rustfmt_skip)] - // This file is Copyright its original authors, visible in version control // history. // @@ -14,46 +12,54 @@ //! returned errors decode to the correct thing. use crate::chain::channelmonitor::{CLTV_CLAIM_BUFFER, LATENCY_GRACE_PERIOD_BLOCKS}; -use crate::sign::{EntropySource, NodeSigner, Recipient}; use crate::events::{Event, HTLCHandlingFailureType, PathFailure, PaymentFailureReason}; -use crate::types::payment::{PaymentHash, PaymentSecret}; use crate::ln::channel::EXPIRE_PREV_CONFIG_TICKS; -use crate::ln::channelmanager::{HTLCForwardInfo, FailureCode, CLTV_FAR_FAR_AWAY, DISABLE_GOSSIP_TICKS, MIN_CLTV_EXPIRY_DELTA, PendingAddHTLCInfo, PendingHTLCInfo, PendingHTLCRouting, PaymentId, RecipientOnionFields}; -use crate::ln::onion_utils::{self, LocalHTLCFailureReason}; -use crate::routing::gossip::{NetworkUpdate, RoutingFees}; -use crate::routing::router::{get_route, PaymentParameters, Route, RouteParameters, RouteHint, RouteHintHop, Path, TrampolineHop, BlindedTail, RouteHop}; -use crate::types::features::{InitFeatures, Bolt11InvoiceFeatures}; +use crate::ln::channelmanager::{ + FailureCode, HTLCForwardInfo, PaymentId, PendingAddHTLCInfo, PendingHTLCInfo, + PendingHTLCRouting, RecipientOnionFields, CLTV_FAR_FAR_AWAY, DISABLE_GOSSIP_TICKS, + MIN_CLTV_EXPIRY_DELTA, +}; use crate::ln::functional_test_utils::test_default_channel_config; use crate::ln::msgs; use crate::ln::msgs::{ - BaseMessageHandler, ChannelMessageHandler, ChannelUpdate, FinalOnionHopData, - OutboundOnionPayload, OutboundTrampolinePayload, MessageSendEvent, + BaseMessageHandler, ChannelMessageHandler, ChannelUpdate, FinalOnionHopData, MessageSendEvent, + OutboundOnionPayload, OutboundTrampolinePayload, }; +use crate::ln::onion_utils::{self, LocalHTLCFailureReason}; use crate::ln::wire::Encode; +use crate::routing::gossip::{NetworkUpdate, RoutingFees}; +use crate::routing::router::{ + get_route, BlindedTail, Path, PaymentParameters, Route, RouteHint, RouteHintHop, RouteHop, + RouteParameters, TrampolineHop, +}; +use crate::sign::{EntropySource, NodeSigner, Recipient}; +use crate::types::features::{Bolt11InvoiceFeatures, InitFeatures}; +use crate::types::payment::{PaymentHash, PaymentSecret}; +use crate::util::config::{ChannelConfig, MaxDustHTLCExposure, UserConfig}; +use crate::util::errors::APIError; use crate::util::ser::{BigSize, Writeable, Writer}; use crate::util::test_utils; -use crate::util::config::{UserConfig, ChannelConfig, MaxDustHTLCExposure}; -use crate::util::errors::APIError; use bitcoin::constants::ChainHash; -use bitcoin::hashes::{Hash, HashEngine}; use bitcoin::hashes::hmac::{Hmac, HmacEngine}; use bitcoin::hashes::sha256::Hash as Sha256; +use bitcoin::hashes::{Hash, HashEngine}; use bitcoin::secp256k1; use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey}; +use crate::blinded_path::BlindedHop; use crate::io; +use crate::ln::functional_test_utils::*; +use crate::ln::onion_utils::{construct_trampoline_onion_keys, construct_trampoline_onion_packet}; use crate::prelude::*; use bitcoin::hex::{DisplayHex, FromHex}; use types::features::{ChannelFeatures, Features, NodeFeatures}; -use crate::blinded_path::BlindedHop; -use crate::ln::functional_test_utils::*; -use crate::ln::onion_utils::{construct_trampoline_onion_keys, construct_trampoline_onion_packet}; use super::msgs::OnionErrorPacket; use super::onion_utils::AttributionData; +#[rustfmt::skip] fn run_onion_failure_test(_name: &str, test_case: u8, nodes: &Vec, route: &Route, payment_hash: &PaymentHash, payment_secret: &PaymentSecret, callback_msg: F1, callback_node: F2, expected_retryable: bool, expected_error_code: Option, expected_channel_update: Option, expected_short_channel_id: Option, expected_failure_type: Option) where F1: for <'a> FnMut(&'a mut msgs::UpdateAddHTLC), F2: FnMut(), @@ -68,17 +74,19 @@ fn run_onion_failure_test(_name: &str, test_case: u8, nodes: &Vec, // 3: final node fails backward (but tamper onion payloads from node0) // 100: trigger error in the intermediate node and tamper returning fail_htlc // 200: trigger error in the final node and tamper returning fail_htlc -fn run_onion_failure_test_with_fail_intercept( +fn run_onion_failure_test_with_fail_intercept( _name: &str, test_case: u8, nodes: &Vec, route: &Route, payment_hash: &PaymentHash, payment_secret: &PaymentSecret, mut callback_msg: F1, mut callback_fail: F2, - mut callback_node: F3, expected_retryable: bool, expected_error_reason: Option, + mut callback_node: F3, expected_retryable: bool, + expected_error_reason: Option, expected_channel_update: Option, expected_short_channel_id: Option, expected_failure_type: Option, -) - where F1: for <'a> FnMut(&'a mut msgs::UpdateAddHTLC), - F2: for <'a> FnMut(&'a mut msgs::UpdateFailHTLC), - F3: FnMut(), +) where + F1: for<'a> FnMut(&'a mut msgs::UpdateAddHTLC), + F2: for<'a> FnMut(&'a mut msgs::UpdateFailHTLC), + F3: FnMut(), { + #[rustfmt::skip] macro_rules! expect_event { ($node: expr, $event_type: path) => {{ let events = $node.node.get_and_clear_pending_events(); @@ -90,6 +98,7 @@ fn run_onion_failure_test_with_fail_intercept( }} } + #[rustfmt::skip] macro_rules! expect_htlc_forward { ($node: expr) => {{ expect_event!($node, Event::PendingHTLCsForwardable); @@ -99,8 +108,15 @@ fn run_onion_failure_test_with_fail_intercept( // 0 ~~> 2 send payment let payment_id = PaymentId(nodes[0].keys_manager.backing.get_secure_random_bytes()); - nodes[0].node.send_payment_with_route(route.clone(), *payment_hash, - RecipientOnionFields::secret_only(*payment_secret), payment_id).unwrap(); + nodes[0] + .node + .send_payment_with_route( + route.clone(), + *payment_hash, + RecipientOnionFields::secret_only(*payment_secret), + payment_id, + ) + .unwrap(); check_added_monitors!(nodes[0], 1); let update_0 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id()); // temper update_add (0 => 1) @@ -114,15 +130,24 @@ fn run_onion_failure_test_with_fail_intercept( commitment_signed_dance!(nodes[1], nodes[0], &update_0.commitment_signed, false, true); let update_1_0 = match test_case { - 0|100 => { // intermediate node failure; fail backward to 0 + 0 | 100 => { + // intermediate node failure; fail backward to 0 expect_pending_htlcs_forwardable!(nodes[1]); - expect_htlc_handling_failed_destinations!(nodes[1].node.get_and_clear_pending_events(), &[expected_failure_type.clone().unwrap()]); + expect_htlc_handling_failed_destinations!( + nodes[1].node.get_and_clear_pending_events(), + &[expected_failure_type.clone().unwrap()] + ); check_added_monitors(&nodes[1], 1); let update_1_0 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id()); - assert!(update_1_0.update_fail_htlcs.len()+update_1_0.update_fail_malformed_htlcs.len()==1 && (update_1_0.update_fail_htlcs.len()==1 || update_1_0.update_fail_malformed_htlcs.len()==1)); + assert!( + update_1_0.update_fail_htlcs.len() + update_1_0.update_fail_malformed_htlcs.len() + == 1 && (update_1_0.update_fail_htlcs.len() == 1 + || update_1_0.update_fail_malformed_htlcs.len() == 1) + ); update_1_0 }, - 1|2|3|200 => { // final node failure; forwarding to 2 + 1 | 2 | 3 | 200 => { + // final node failure; forwarding to 2 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty()); // forwarding on 1 if test_case != 200 { @@ -147,10 +172,16 @@ fn run_onion_failure_test_with_fail_intercept( expect_htlc_forward!(&nodes[2]); expect_event!(&nodes[2], Event::PaymentClaimable); callback_node(); - expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCHandlingFailureType::Receive { payment_hash: payment_hash.clone() }]); + expect_pending_htlcs_forwardable_and_htlc_handling_failed!( + nodes[2], + vec![HTLCHandlingFailureType::Receive { payment_hash: payment_hash.clone() }] + ); } else if test_case == 1 || test_case == 3 { expect_htlc_forward!(&nodes[2]); - expect_htlc_handling_failed_destinations!(nodes[2].node.get_and_clear_pending_events(), vec![expected_failure_type.clone().unwrap()]); + expect_htlc_handling_failed_destinations!( + nodes[2].node.get_and_clear_pending_events(), + vec![expected_failure_type.clone().unwrap()] + ); } check_added_monitors!(&nodes[2], 1); @@ -182,14 +213,24 @@ fn run_onion_failure_test_with_fail_intercept( } nodes[0].node.handle_update_fail_htlc(nodes[1].node.get_our_node_id(), &fail_msg); } else { - nodes[0].node.handle_update_fail_malformed_htlc(nodes[1].node.get_our_node_id(), &update_1_0.update_fail_malformed_htlcs[0]); + nodes[0].node.handle_update_fail_malformed_htlc( + nodes[1].node.get_our_node_id(), + &update_1_0.update_fail_malformed_htlcs[0], + ); }; commitment_signed_dance!(nodes[0], nodes[1], update_1_0.commitment_signed, false, true); let events = nodes[0].node.get_and_clear_pending_events(); assert_eq!(events.len(), 2); - if let &Event::PaymentPathFailed { ref payment_failed_permanently, ref short_channel_id, ref error_code, failure: PathFailure::OnPath { ref network_update }, .. } = &events[0] { + if let &Event::PaymentPathFailed { + ref payment_failed_permanently, + ref short_channel_id, + ref error_code, + failure: PathFailure::OnPath { ref network_update }, + .. + } = &events[0] + { assert_eq!(*payment_failed_permanently, !expected_retryable); assert_eq!(error_code.is_none(), expected_error_reason.is_none()); if let Some(expected_reason) = expected_error_reason { @@ -199,7 +240,11 @@ fn run_onion_failure_test_with_fail_intercept( match network_update { Some(update) => match update { &NetworkUpdate::ChannelFailure { ref short_channel_id, ref is_permanent } => { - if let NetworkUpdate::ChannelFailure { short_channel_id: ref expected_short_channel_id, is_permanent: ref expected_is_permanent } = expected_channel_update.unwrap() { + if let NetworkUpdate::ChannelFailure { + short_channel_id: ref expected_short_channel_id, + is_permanent: ref expected_is_permanent, + } = expected_channel_update.unwrap() + { assert!(*short_channel_id == *expected_short_channel_id); assert!(*is_permanent == *expected_is_permanent); } else { @@ -207,14 +252,18 @@ fn run_onion_failure_test_with_fail_intercept( } }, &NetworkUpdate::NodeFailure { ref node_id, ref is_permanent } => { - if let NetworkUpdate::NodeFailure { node_id: ref expected_node_id, is_permanent: ref expected_is_permanent } = expected_channel_update.unwrap() { + if let NetworkUpdate::NodeFailure { + node_id: ref expected_node_id, + is_permanent: ref expected_is_permanent, + } = expected_channel_update.unwrap() + { assert!(*node_id == *expected_node_id); assert!(*is_permanent == *expected_is_permanent); } else { panic!("Unexpected message event"); } }, - } + }, None => panic!("Expected channel update"), } } else { @@ -232,20 +281,28 @@ fn run_onion_failure_test_with_fail_intercept( panic!("Unexpected event"); } match events[1] { - Event::PaymentFailed { payment_hash: ev_payment_hash, payment_id: ev_payment_id, reason: ref ev_reason } => { + Event::PaymentFailed { + payment_hash: ev_payment_hash, + payment_id: ev_payment_id, + reason: ref ev_reason, + } => { assert_eq!(Some(*payment_hash), ev_payment_hash); assert_eq!(payment_id, ev_payment_id); - assert_eq!(if expected_retryable { - PaymentFailureReason::RetriesExhausted - } else { - PaymentFailureReason::RecipientRejected - }, ev_reason.unwrap()); - } + assert_eq!( + if expected_retryable { + PaymentFailureReason::RetriesExhausted + } else { + PaymentFailureReason::RecipientRejected + }, + ev_reason.unwrap() + ); + }, _ => panic!("Unexpected second event"), } } impl msgs::ChannelUpdate { + #[rustfmt::skip] fn dummy(short_channel_id: u64) -> msgs::ChannelUpdate { use bitcoin::hash_types::BlockHash; use bitcoin::secp256k1::ffi::Signature as FFISignature; @@ -270,7 +327,7 @@ impl msgs::ChannelUpdate { } struct BogusOnionHopData { - data: Vec + data: Vec, } impl BogusOnionHopData { fn new(orig: msgs::OutboundOnionPayload) -> Self { @@ -284,6 +341,7 @@ impl Writeable for BogusOnionHopData { } #[test] +#[rustfmt::skip] fn test_fee_failures() { // Tests that the fee required when forwarding remains consistent over time. This was // previously broken, with forwarding fees floating based on the fee estimator at the time of @@ -334,6 +392,7 @@ fn test_fee_failures() { } #[test] +#[rustfmt::skip] fn test_onion_failure() { // When we check for amount_below_minimum below, we want to test that we're using the *right* // amount, thus we need different htlc_minimum_msat values. We set node[2]'s htlc_minimum_msat @@ -781,6 +840,7 @@ fn test_onion_failure() { } #[test] +#[rustfmt::skip] fn test_overshoot_final_cltv() { let chanmon_cfgs = create_chanmon_cfgs(3); let node_cfgs = create_node_cfgs(3, &chanmon_cfgs); @@ -822,6 +882,7 @@ fn test_overshoot_final_cltv() { claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage); } +#[rustfmt::skip] fn do_test_onion_failure_stale_channel_update(announce_for_forwarding: bool) { // Create a network of three nodes and two channels connecting them. We'll be updating the // HTLC relay policy of the second channel, causing forwarding failures at the first hop. @@ -1001,6 +1062,7 @@ fn test_onion_failure_stale_channel_update() { } #[test] +#[rustfmt::skip] fn test_always_create_tlv_format_onion_payloads() { // Verify that we always generate tlv onion format payloads, even if the features specifically // specifies no support for variable length onions, as the legacy payload format has been @@ -1052,6 +1114,7 @@ fn test_always_create_tlv_format_onion_payloads() { } #[test] +#[rustfmt::skip] fn test_trampoline_onion_payload_serialization() { // As per https://github.com/lightning/bolts/blob/c01d2e6267d4a8d1095f0f1188970055a9a22d29/bolt04/trampoline-payment-onion-test.json#L3 let trampoline_payload = OutboundTrampolinePayload::Forward { @@ -1071,6 +1134,7 @@ fn test_trampoline_onion_payload_serialization() { } #[test] +#[rustfmt::skip] fn test_trampoline_onion_payload_assembly_values() { // Test that we produce Trampoline and outer onion payloads that align with our expectations // from the Path argument. Additionally, ensure that the fee and HTLC values using the @@ -1222,6 +1286,7 @@ fn test_trampoline_onion_payload_assembly_values() { } #[test] +#[rustfmt::skip] fn test_trampoline_onion_payload_construction_vectors() { // As per https://github.com/lightning/bolts/blob/fa0594ac2af3531d734f1d707a146d6e13679451/bolt04/trampoline-to-blinded-path-payment-onion-test.json#L251 @@ -1361,6 +1426,7 @@ fn test_trampoline_onion_payload_construction_vectors() { assert_eq!(outer_onion_packet_hex, "00025fd60556c134ae97e4baedba220a644037754ee67c54fd05e93bf40c17cbb73362fb9dee96001ff229945595b6edb59437a6bc143406d3f90f749892a84d8d430c6890437d26d5bfc599d565316ef51347521075bbab87c59c57bcf20af7e63d7192b46cf171e4f73cb11f9f603915389105d91ad630224bea95d735e3988add1e24b5bf28f1d7128db64284d90a839ba340d088c74b1fb1bd21136b1809428ec5399c8649e9bdf92d2dcfc694deae5046fa5b2bdf646847aaad73f5e95275763091c90e71031cae1f9a770fdea559642c9c02f424a2a28163dd0957e3874bd28a97bec67d18c0321b0e68bc804aa8345b17cb626e2348ca06c8312a167c989521056b0f25c55559d446507d6c491d50605cb79fa87929ce64b0a9860926eeaec2c431d926a1cadb9a1186e4061cb01671a122fc1f57602cbef06d6c194ec4b715c2e3dd4120baca3172cd81900b49fef857fb6d6afd24c983b608108b0a5ac0c1c6c52011f23b8778059ffadd1bb7cd06e2525417365f485a7fd1d4a9ba3818ede7cdc9e71afee8532252d08e2531ca52538655b7e8d912f7ec6d37bbcce8d7ec690709dbf9321e92c565b78e7fe2c22edf23e0902153d1ca15a112ad32fb19695ec65ce11ddf670da7915f05ad4b86c154fb908cb567315d1124f303f75fa075ebde8ef7bb12e27737ad9e4924439097338ea6d7a6fc3721b88c9b830a34e8d55f4c582b74a3895cc848fe57f4fe29f115dabeb6b3175be15d94408ed6771109cfaf57067ae658201082eae7605d26b1449af4425ae8e8f58cdda5c6265f1fd7a386fc6cea3074e4f25b909b96175883676f7610a00fdf34df9eb6c7b9a4ae89b839c69fd1f285e38cdceb634d782cc6d81179759bc9fd47d7fd060470d0b048287764c6837963274e708314f017ac7dc26d0554d59bfcfd3136225798f65f0b0fea337c6b256ebbb63a90b994c0ab93fd8b1d6bd4c74aebe535d6110014cd3d525394027dfe8faa98b4e9b2bee7949eb1961f1b026791092f84deea63afab66603dbe9b6365a102a1fef2f6b9744bc1bb091a8da9130d34d4d39f25dbad191649cfb67e10246364b7ce0c6ec072f9690cabb459d9fda0c849e17535de4357e9907270c75953fca3c845bb613926ecf73205219c7057a4b6bb244c184362bb4e2f24279dc4e60b94a5b1ec11c34081a628428ba5646c995b9558821053ba9c84a05afbf00dabd60223723096516d2f5668f3ec7e11612b01eb7a3a0506189a2272b88e89807943adb34291a17f6cb5516ffd6f945a1c42a524b21f096d66f350b1dad4db455741ae3d0e023309fbda5ef55fb0dc74f3297041448b2be76c525141963934c6afc53d263fb7836626df502d7c2ee9e79cbbd87afd84bbb8dfbf45248af3cd61ad5fac827e7683ca4f91dfad507a8eb9c17b2c9ac5ec051fe645a4a6cb37136f6f19b611e0ea8da7960af2d779507e55f57305bc74b7568928c5dd5132990fe54c22117df91c257d8c7b61935a018a28c1c3b17bab8e4294fa699161ec21123c9fc4e71079df31f300c2822e1246561e04765d3aab333eafd026c7431ac7616debb0e022746f4538e1c6348b600c988eeb2d051fc60c468dca260a84c79ab3ab8342dc345a764672848ea234e17332bc124799daf7c5fcb2e2358514a7461357e1c19c802c5ee32deccf1776885dd825bedd5f781d459984370a6b7ae885d4483a76ddb19b30f47ed47cd56aa5a079a89793dbcad461c59f2e002067ac98dd5a534e525c9c46c2af730741bf1f8629357ec0bfc0bc9ecb31af96777e507648ff4260dc3673716e098d9111dfd245f1d7c55a6de340deb8bd7a053e5d62d760f184dc70ca8fa255b9023b9b9aedfb6e419a5b5951ba0f83b603793830ee68d442d7b88ee1bbf6bbd1bcd6f68cc1af"); } +#[rustfmt::skip] fn do_test_fail_htlc_backwards_with_reason(failure_code: FailureCode) { let chanmon_cfgs = create_chanmon_cfgs(2); @@ -1435,6 +1501,7 @@ fn test_fail_htlc_backwards_with_reason() { do_test_fail_htlc_backwards_with_reason(FailureCode::InvalidOnionPayload(None)); } +#[rustfmt::skip] macro_rules! get_phantom_route { ($nodes: expr, $amt: expr, $channel: expr) => {{ let phantom_pubkey = $nodes[1].keys_manager.get_node_id(Recipient::PhantomNode).unwrap(); @@ -1477,6 +1544,7 @@ macro_rules! get_phantom_route { }} #[test] +#[rustfmt::skip] fn test_phantom_onion_hmac_failure() { let chanmon_cfgs = create_chanmon_cfgs(2); let node_cfgs = create_node_cfgs(2, &chanmon_cfgs); @@ -1538,6 +1606,7 @@ fn test_phantom_onion_hmac_failure() { } #[test] +#[rustfmt::skip] fn test_phantom_invalid_onion_payload() { let chanmon_cfgs = create_chanmon_cfgs(2); let node_cfgs = create_node_cfgs(2, &chanmon_cfgs); @@ -1616,6 +1685,7 @@ fn test_phantom_invalid_onion_payload() { } #[test] +#[rustfmt::skip] fn test_phantom_final_incorrect_cltv_expiry() { let chanmon_cfgs = create_chanmon_cfgs(2); let node_cfgs = create_node_cfgs(2, &chanmon_cfgs); @@ -1674,6 +1744,7 @@ fn test_phantom_final_incorrect_cltv_expiry() { } #[test] +#[rustfmt::skip] fn test_phantom_failure_too_low_cltv() { let chanmon_cfgs = create_chanmon_cfgs(2); let node_cfgs = create_node_cfgs(2, &chanmon_cfgs); @@ -1723,6 +1794,7 @@ fn test_phantom_failure_too_low_cltv() { } #[test] +#[rustfmt::skip] fn test_phantom_failure_modified_cltv() { // Test that we fail back phantoms if the upstream node fiddled with the CLTV too much with the // correct error code. @@ -1774,6 +1846,7 @@ fn test_phantom_failure_modified_cltv() { } #[test] +#[rustfmt::skip] fn test_phantom_failure_expires_too_soon() { // Test that we fail back phantoms if the HTLC got delayed and we got blocks in between with // the correct error code. @@ -1821,6 +1894,7 @@ fn test_phantom_failure_expires_too_soon() { } #[test] +#[rustfmt::skip] fn test_phantom_failure_too_low_recv_amt() { let chanmon_cfgs = create_chanmon_cfgs(2); let node_cfgs = create_node_cfgs(2, &chanmon_cfgs); @@ -1873,6 +1947,7 @@ fn test_phantom_dust_exposure_failure() { do_test_phantom_dust_exposure_failure(true); } +#[rustfmt::skip] fn do_test_phantom_dust_exposure_failure(multiplier_dust_limit: bool) { // Set the max dust exposure to the dust limit. let max_dust_exposure = 546; @@ -1926,6 +2001,7 @@ fn do_test_phantom_dust_exposure_failure(multiplier_dust_limit: bool) { } #[test] +#[rustfmt::skip] fn test_phantom_failure_reject_payment() { // Test that the user can successfully fail back a phantom node payment. let chanmon_cfgs = create_chanmon_cfgs(2); diff --git a/lightning/src/ln/outbound_payment.rs b/lightning/src/ln/outbound_payment.rs index e4b2075dac3..e01afb3d0c9 100644 --- a/lightning/src/ln/outbound_payment.rs +++ b/lightning/src/ln/outbound_payment.rs @@ -1,5 +1,3 @@ -#![cfg_attr(rustfmt, rustfmt_skip)] - // This file is Copyright its original authors, visible in version control // history. // @@ -11,8 +9,8 @@ //! Utilities to send payments and manage outbound payment information. -use bitcoin::hashes::Hash; use bitcoin::hashes::sha256::Hash as Sha256; +use bitcoin::hashes::Hash; use bitcoin::secp256k1::{self, Secp256k1, SecretKey}; use lightning_invoice::Bolt11Invoice; @@ -24,17 +22,20 @@ use crate::ln::onion_utils; use crate::ln::onion_utils::{DecodedOnionFailure, HTLCFailReason}; use crate::offers::invoice::Bolt12Invoice; use crate::offers::invoice_request::InvoiceRequest; -use crate::offers::static_invoice::StaticInvoice; use crate::offers::nonce::Nonce; -use crate::routing::router::{BlindedTail, InFlightHtlcs, Path, PaymentParameters, Route, RouteParameters, RouteParametersConfig, Router}; +use crate::offers::static_invoice::StaticInvoice; +use crate::routing::router::{ + BlindedTail, InFlightHtlcs, Path, PaymentParameters, Route, RouteParameters, + RouteParametersConfig, Router, +}; use crate::sign::{EntropySource, NodeSigner, Recipient}; use crate::types::features::Bolt12InvoiceFeatures; use crate::types::payment::{PaymentHash, PaymentPreimage, PaymentSecret}; use crate::util::errors::APIError; use crate::util::logger::Logger; +use crate::util::ser::ReadableArgs; #[cfg(feature = "std")] use crate::util::time::Instant; -use crate::util::ser::ReadableArgs; #[cfg(async_payments)] use crate::offers::invoice::{DerivedSigningPubkey, InvoiceBuilder}; @@ -72,7 +73,7 @@ pub(crate) enum PendingOutboundPayment { expiration: StaleExpiration, retry_strategy: Retry, route_params_config: RouteParametersConfig, - retryable_invoice_request: Option + retryable_invoice_request: Option, }, // Represents the state after the invoice has been received, transitioning from the corresponding // `AwaitingInvoice` state. @@ -171,6 +172,7 @@ impl PendingOutboundPayment { attempts.count += 1; } } + #[rustfmt::skip] fn is_auto_retryable_now(&self) -> bool { match self { PendingOutboundPayment::Retryable { @@ -181,6 +183,7 @@ impl PendingOutboundPayment { _ => false, } } + #[rustfmt::skip] fn is_retryable_now(&self) -> bool { match self { PendingOutboundPayment::Retryable { retry_strategy: None, .. } => { @@ -237,6 +240,7 @@ impl PendingOutboundPayment { } } + #[rustfmt::skip] fn payment_hash(&self) -> Option { match self { PendingOutboundPayment::Legacy { .. } => None, @@ -250,6 +254,7 @@ impl PendingOutboundPayment { } } + #[rustfmt::skip] fn mark_fulfilled(&mut self) { let mut session_privs = new_hash_set(); core::mem::swap(&mut session_privs, match self { @@ -267,6 +272,7 @@ impl PendingOutboundPayment { *self = PendingOutboundPayment::Fulfilled { session_privs, payment_hash, timer_ticks_without_htlcs: 0, total_msat }; } + #[rustfmt::skip] fn mark_abandoned(&mut self, reason: PaymentFailureReason) { let session_privs = match self { PendingOutboundPayment::Retryable { session_privs, .. } => { @@ -294,6 +300,7 @@ impl PendingOutboundPayment { } /// panics if path is None and !self.is_fulfilled + #[rustfmt::skip] fn remove(&mut self, session_priv: &[u8; 32], path: Option<&Path>) -> bool { let remove_res = match self { PendingOutboundPayment::Legacy { session_privs } | @@ -327,6 +334,7 @@ impl PendingOutboundPayment { remove_res } + #[rustfmt::skip] pub(super) fn insert(&mut self, session_priv: [u8; 32], path: &Path) -> bool { let insert_res = match self { PendingOutboundPayment::Legacy { session_privs } | @@ -359,6 +367,7 @@ impl PendingOutboundPayment { insert_res } + #[rustfmt::skip] pub(super) fn remaining_parts(&self) -> usize { match self { PendingOutboundPayment::Legacy { session_privs } | @@ -406,6 +415,7 @@ impl_writeable_tlv_based_enum_legacy!(Retry, ); impl Retry { + #[rustfmt::skip] pub(crate) fn is_retryable_now(&self, attempts: &PaymentAttempts) -> bool { match (self, attempts) { (Retry::Attempts(max_retry_count), PaymentAttempts { count, .. }) => { @@ -419,6 +429,7 @@ impl Retry { } #[cfg(feature = "std")] +#[rustfmt::skip] pub(super) fn has_expired(route_params: &RouteParameters) -> bool { if let Some(expiry_time) = route_params.payment_params.expiry_time { if let Ok(elapsed) = std::time::SystemTime::UNIX_EPOCH.elapsed() { @@ -492,7 +503,10 @@ pub enum RetryableSendFailure { /// the BOLT 12 invoice paid to via [`ChannelManager::send_payment_for_bolt12_invoice`] was /// expired. #[cfg_attr(feature = "std", doc = "")] - #[cfg_attr(feature = "std", doc = "Note that this error is *not* caused by [`Retry::Timeout`].")] + #[cfg_attr( + feature = "std", + doc = "Note that this error is *not* caused by [`Retry::Timeout`]." + )] /// /// [`PaymentParameters::expiry_time`]: crate::routing::router::PaymentParameters::expiry_time /// [`ChannelManager::send_payment_for_bolt12_invoice`]: crate::ln::channelmanager::ChannelManager::send_payment_for_bolt12_invoice @@ -693,6 +707,7 @@ impl RecipientOnionFields { /// Creates a [`RecipientOnionFields`] from only a [`PaymentSecret`]. This is the most common /// set of onion fields for today's BOLT11 invoices - most nodes require a [`PaymentSecret`] /// but do not require or provide any further data. + #[rustfmt::skip] pub fn secret_only(payment_secret: PaymentSecret) -> Self { Self { payment_secret: Some(payment_secret), payment_metadata: None, custom_tlvs: Vec::new() } } @@ -718,6 +733,7 @@ impl RecipientOnionFields { /// standardized within the protocol, which only includes 5482373484 (keysend) for now. /// /// See [`Self::custom_tlvs`] for more info. + #[rustfmt::skip] pub fn with_custom_tlvs(mut self, mut custom_tlvs: Vec<(u64, Vec)>) -> Result { custom_tlvs.sort_unstable_by_key(|(typ, _)| *typ); let mut prev_type = None; @@ -772,6 +788,7 @@ impl RecipientOnionFields { /// /// Here we implement this, first checking compatibility then mutating two objects and then /// dropping any remaining non-matching fields from both. + #[rustfmt::skip] pub(super) fn check_merge(&mut self, further_htlc_fields: &mut Self) -> Result<(), ()> { if self.payment_secret != further_htlc_fields.payment_secret { return Err(()); } if self.payment_metadata != further_htlc_fields.payment_metadata { return Err(()); } @@ -811,7 +828,9 @@ pub(super) struct OutboundPayments { } impl OutboundPayments { - pub(super) fn new(pending_outbound_payments: HashMap) -> Self { + pub(super) fn new( + pending_outbound_payments: HashMap, + ) -> Self { let has_invoice_requests = pending_outbound_payments.values().any(|payment| { matches!( payment, @@ -828,6 +847,7 @@ impl OutboundPayments { } } + #[rustfmt::skip] pub(super) fn send_payment( &self, payment_hash: PaymentHash, recipient_onion: RecipientOnionFields, payment_id: PaymentId, retry_strategy: Retry, route_params: RouteParameters, router: &R, @@ -848,6 +868,7 @@ impl OutboundPayments { best_block_height, logger, pending_events, &send_payment_along_path) } + #[rustfmt::skip] pub(super) fn send_spontaneous_payment( &self, payment_preimage: Option, recipient_onion: RecipientOnionFields, payment_id: PaymentId, retry_strategy: Retry, route_params: RouteParameters, router: &R, @@ -872,6 +893,7 @@ impl OutboundPayments { .map(|()| payment_hash) } + #[rustfmt::skip] pub(super) fn pay_for_bolt11_invoice( &self, invoice: &Bolt11Invoice, payment_id: PaymentId, amount_msats: Option, @@ -916,6 +938,7 @@ impl OutboundPayments { ).map_err(|err| Bolt11PaymentError::SendingFailed(err)) } + #[rustfmt::skip] pub(super) fn send_payment_for_bolt12_invoice< R: Deref, ES: Deref, NS: Deref, NL: Deref, IH, SP, L: Deref >( @@ -961,6 +984,7 @@ impl OutboundPayments { ) } + #[rustfmt::skip] fn send_payment_for_bolt12_invoice_internal< R: Deref, ES: Deref, NS: Deref, NL: Deref, IH, SP, L: Deref >( @@ -1072,6 +1096,7 @@ impl OutboundPayments { } #[cfg(async_payments)] + #[rustfmt::skip] pub(super) fn static_invoice_received( &self, invoice: &StaticInvoice, payment_id: PaymentId, features: Bolt12InvoiceFeatures, best_block_height: u32, duration_since_epoch: Duration, entropy_source: ES, @@ -1159,6 +1184,7 @@ impl OutboundPayments { } #[cfg(async_payments)] + #[rustfmt::skip] pub(super) fn send_payment_for_static_invoice< R: Deref, ES: Deref, NS: Deref, NL: Deref, IH, SP, L: Deref >( @@ -1198,6 +1224,7 @@ impl OutboundPayments { ) } + #[rustfmt::skip] pub(super) fn check_retry_payments( &self, router: &R, first_hops: FH, inflight_htlcs: IH, entropy_source: &ES, node_signer: &NS, best_block_height: u32, @@ -1255,6 +1282,7 @@ impl OutboundPayments { }); } + #[rustfmt::skip] pub(super) fn needs_abandon(&self) -> bool { let outbounds = self.pending_outbound_payments.lock().unwrap(); outbounds.iter().any(|(_, pmt)| @@ -1262,6 +1290,7 @@ impl OutboundPayments { !pmt.is_awaiting_invoice()) } + #[rustfmt::skip] fn find_initial_route( &self, payment_id: PaymentId, payment_hash: PaymentHash, recipient_onion: &RecipientOnionFields, keysend_preimage: Option, invoice_request: Option<&InvoiceRequest>, @@ -1316,6 +1345,7 @@ impl OutboundPayments { /// /// [`Event::PaymentPathFailed`]: crate::events::Event::PaymentPathFailed /// [`Event::PaymentFailed`]: crate::events::Event::PaymentFailed + #[rustfmt::skip] fn send_payment_for_non_bolt12_invoice( &self, payment_id: PaymentId, payment_hash: PaymentHash, recipient_onion: RecipientOnionFields, keysend_preimage: Option, retry_strategy: Retry, mut route_params: RouteParameters, @@ -1360,6 +1390,7 @@ impl OutboundPayments { Ok(()) } + #[rustfmt::skip] fn find_route_and_send_payment( &self, payment_hash: PaymentHash, payment_id: PaymentId, route_params: RouteParameters, router: &R, first_hops: Vec, inflight_htlcs: &IH, entropy_source: &ES, @@ -1409,6 +1440,7 @@ impl OutboundPayments { } } + #[rustfmt::skip] macro_rules! abandon_with_entry { ($payment: expr, $reason: expr) => { $payment.get_mut().mark_abandoned($reason); @@ -1520,6 +1552,7 @@ impl OutboundPayments { } } + #[rustfmt::skip] fn handle_pay_route_err( &self, err: PaymentSendFailure, payment_id: PaymentId, payment_hash: PaymentHash, route: Route, mut route_params: RouteParameters, onion_session_privs: Vec<[u8; 32]>, router: &R, @@ -1582,6 +1615,7 @@ impl OutboundPayments { } } + #[rustfmt::skip] fn push_path_failed_evs_and_scids>, L: Deref>( payment_id: PaymentId, payment_hash: PaymentHash, route_params: &mut RouteParameters, paths: Vec, path_results: I, logger: &L, @@ -1617,6 +1651,7 @@ impl OutboundPayments { // If a payment fails after adding the pending payment but before any HTLCs are locked into // channels, we need to clear the session_privs in order for abandoning the payment to succeed. + #[rustfmt::skip] fn remove_session_privs<'a, I: Iterator>( &self, payment_id: PaymentId, path_session_priv: I ) { @@ -1630,6 +1665,7 @@ impl OutboundPayments { } } + #[rustfmt::skip] pub(super) fn send_probe( &self, path: Path, probing_cookie_secret: [u8; 32], entropy_source: &ES, node_signer: &NS, best_block_height: u32, send_payment_along_path: F @@ -1693,7 +1729,7 @@ impl OutboundPayments { #[cfg(test)] pub(super) fn test_set_payment_metadata( - &self, payment_id: PaymentId, new_payment_metadata: Option> + &self, payment_id: PaymentId, new_payment_metadata: Option>, ) { match self.pending_outbound_payments.lock().unwrap().get_mut(&payment_id).unwrap() { PendingOutboundPayment::Retryable { payment_metadata, .. } => { @@ -1704,6 +1740,7 @@ impl OutboundPayments { } #[cfg(any(test, feature = "_externalize_tests"))] + #[rustfmt::skip] pub(super) fn test_add_new_pending_payment( &self, payment_hash: PaymentHash, recipient_onion: RecipientOnionFields, payment_id: PaymentId, route: &Route, retry_strategy: Option, entropy_source: &ES, best_block_height: u32 @@ -1711,6 +1748,7 @@ impl OutboundPayments { self.add_new_pending_payment(payment_hash, recipient_onion, payment_id, None, route, retry_strategy, None, entropy_source, best_block_height, None) } + #[rustfmt::skip] pub(super) fn add_new_pending_payment( &self, payment_hash: PaymentHash, recipient_onion: RecipientOnionFields, payment_id: PaymentId, keysend_preimage: Option, route: &Route, retry_strategy: Option, @@ -1731,6 +1769,7 @@ impl OutboundPayments { } } + #[rustfmt::skip] fn create_pending_payment( payment_hash: PaymentHash, recipient_onion: RecipientOnionFields, keysend_preimage: Option, invoice_request: Option, @@ -1794,7 +1833,9 @@ impl OutboundPayments { } #[cfg(feature = "dnssec")] - pub(super) fn amt_msats_for_payment_awaiting_offer(&self, payment_id: PaymentId) -> Result { + pub(super) fn amt_msats_for_payment_awaiting_offer( + &self, payment_id: PaymentId, + ) -> Result { match self.pending_outbound_payments.lock().unwrap().entry(payment_id) { hash_map::Entry::Occupied(entry) => match entry.get() { PendingOutboundPayment::AwaitingOffer { amount_msats, .. } => Ok(*amount_msats), @@ -1805,6 +1846,7 @@ impl OutboundPayments { } #[cfg(feature = "dnssec")] + #[rustfmt::skip] pub(super) fn received_offer( &self, payment_id: PaymentId, retryable_invoice_request: Option, ) -> Result<(), ()> { @@ -1830,7 +1872,8 @@ impl OutboundPayments { pub(super) fn add_new_awaiting_invoice( &self, payment_id: PaymentId, expiration: StaleExpiration, retry_strategy: Retry, - route_params_config: RouteParametersConfig, retryable_invoice_request: Option + route_params_config: RouteParametersConfig, + retryable_invoice_request: Option, ) -> Result<(), ()> { let mut pending_outbounds = self.pending_outbound_payments.lock().unwrap(); match pending_outbounds.entry(payment_id) { @@ -1851,6 +1894,7 @@ impl OutboundPayments { } } + #[rustfmt::skip] pub(super) fn mark_invoice_received( &self, invoice: &Bolt12Invoice, payment_id: PaymentId ) -> Result<(), Bolt12PaymentError> { @@ -1862,6 +1906,7 @@ impl OutboundPayments { }) } + #[rustfmt::skip] fn mark_invoice_received_and_get_details( &self, invoice: &Bolt12Invoice, payment_id: PaymentId ) -> Result<(PaymentHash, Retry, RouteParametersConfig, bool), Bolt12PaymentError> { @@ -1896,6 +1941,7 @@ impl OutboundPayments { } } + #[rustfmt::skip] fn pay_route_internal( &self, route: &Route, payment_hash: PaymentHash, recipient_onion: &RecipientOnionFields, keysend_preimage: Option, invoice_request: Option<&InvoiceRequest>, bolt12_invoice: Option<&PaidBolt12Invoice>, @@ -2010,6 +2056,7 @@ impl OutboundPayments { } #[cfg(any(test, feature = "_externalize_tests"))] + #[rustfmt::skip] pub(super) fn test_send_payment_internal( &self, route: &Route, payment_hash: PaymentHash, recipient_onion: RecipientOnionFields, keysend_preimage: Option, payment_id: PaymentId, recv_value_msat: Option, @@ -2028,6 +2075,7 @@ impl OutboundPayments { // If we failed to send any paths, remove the new PaymentId from the `pending_outbound_payments` // map as the payment is free to be resent. + #[rustfmt::skip] fn remove_outbound_if_all_failed(&self, payment_id: PaymentId, err: &PaymentSendFailure) { match err { PaymentSendFailure::AllFailedResendSafe(_) @@ -2041,6 +2089,7 @@ impl OutboundPayments { } } + #[rustfmt::skip] pub(super) fn claim_htlc( &self, payment_id: PaymentId, payment_preimage: PaymentPreimage, bolt12_invoice: Option, session_priv: SecretKey, path: Path, from_onchain: bool, ev_completion_action: EventCompletionAction, @@ -2089,6 +2138,7 @@ impl OutboundPayments { } } + #[rustfmt::skip] pub(super) fn finalize_claims(&self, sources: Vec, pending_events: &Mutex)>>) { @@ -2114,6 +2164,7 @@ impl OutboundPayments { } } + #[rustfmt::skip] pub(super) fn remove_stale_payments( &self, duration_since_epoch: Duration, pending_events: &Mutex)>>) @@ -2202,6 +2253,7 @@ impl OutboundPayments { } // Returns a bool indicating whether a PendingHTLCsForwardable event should be generated. + #[rustfmt::skip] pub(super) fn fail_htlc( &self, source: &HTLCSource, payment_hash: &PaymentHash, onion_error: &HTLCFailReason, path: &Path, session_priv: &SecretKey, payment_id: &PaymentId, @@ -2334,6 +2386,7 @@ impl OutboundPayments { pending_retry_ev } + #[rustfmt::skip] pub(super) fn abandon_payment( &self, payment_id: PaymentId, reason: PaymentFailureReason, pending_events: &Mutex)>> @@ -2377,6 +2430,7 @@ impl OutboundPayments { self.pending_outbound_payments.lock().unwrap().clear() } + #[rustfmt::skip] pub fn release_invoice_requests_awaiting_invoice(&self) -> Vec<(PaymentId, RetryableInvoiceRequest)> { if !self.awaiting_invoice.load(Ordering::Acquire) { return vec![]; @@ -2405,11 +2459,12 @@ impl OutboundPayments { pub(super) fn insert_from_monitor_on_startup( &self, payment_id: PaymentId, payment_hash: PaymentHash, session_priv_bytes: [u8; 32], - path: &Path, best_block_height: u32, logger: L + path: &Path, best_block_height: u32, logger: L, ) { let path_amt = path.final_value_msat(); let path_fee = path.fee_msat(); + #[rustfmt::skip] macro_rules! new_retryable { () => { PendingOutboundPayment::Retryable { @@ -2436,11 +2491,10 @@ impl OutboundPayments { match self.pending_outbound_payments.lock().unwrap().entry(payment_id) { hash_map::Entry::Occupied(mut entry) => { let newly_added = match entry.get() { - PendingOutboundPayment::AwaitingOffer { .. } | - PendingOutboundPayment::AwaitingInvoice { .. } | - PendingOutboundPayment::InvoiceReceived { .. } | - PendingOutboundPayment::StaticInvoiceReceived { .. } => - { + PendingOutboundPayment::AwaitingOffer { .. } + | PendingOutboundPayment::AwaitingInvoice { .. } + | PendingOutboundPayment::InvoiceReceived { .. } + | PendingOutboundPayment::StaticInvoiceReceived { .. } => { // If we've reached this point, it means we initiated a payment to a BOLT 12 invoice and // locked the htlc(s) into the `ChannelMonitor`(s), but failed to persist the // `ChannelManager` after transitioning from this state to `Retryable` prior to shutdown. @@ -2449,13 +2503,12 @@ impl OutboundPayments { *entry.get_mut() = new_retryable!(); true }, - PendingOutboundPayment::Legacy { .. } | - PendingOutboundPayment::Retryable { .. } | - PendingOutboundPayment::Fulfilled { .. } | - PendingOutboundPayment::Abandoned { .. } => - { + PendingOutboundPayment::Legacy { .. } + | PendingOutboundPayment::Retryable { .. } + | PendingOutboundPayment::Fulfilled { .. } + | PendingOutboundPayment::Abandoned { .. } => { entry.get_mut().insert(session_priv_bytes, &path) - } + }, }; log_info!(logger, "{} a pending payment path for {} msat for session priv {} on an existing pending payment with payment hash {}", if newly_added { "Added" } else { "Had" }, path_amt, log_bytes!(session_priv_bytes), payment_hash); @@ -2464,16 +2517,16 @@ impl OutboundPayments { entry.insert(new_retryable!()); log_info!(logger, "Added a pending payment for {} msat with payment hash {} for path with session priv {}", path_amt, payment_hash, log_bytes!(session_priv_bytes)); - } + }, } } } /// Returns whether a payment with the given [`PaymentHash`] and [`PaymentId`] is, in fact, a /// payment probe. -pub(super) fn payment_is_probe(payment_hash: &PaymentHash, payment_id: &PaymentId, - probing_cookie_secret: [u8; 32]) -> bool -{ +pub(super) fn payment_is_probe( + payment_hash: &PaymentHash, payment_id: &PaymentId, probing_cookie_secret: [u8; 32], +) -> bool { let target_payment_hash = probing_cookie_from_id(payment_id, probing_cookie_secret); target_payment_hash == *payment_hash } @@ -2595,11 +2648,12 @@ mod tests { use crate::blinded_path::EmptyNodeIdLookUp; use crate::events::{Event, PathFailure, PaymentFailureReason}; - use crate::types::payment::{PaymentHash, PaymentPreimage}; use crate::ln::channelmanager::{PaymentId, RecipientOnionFields}; use crate::ln::inbound_payment::ExpandedKey; - use crate::types::features::{Bolt12InvoiceFeatures, ChannelFeatures, NodeFeatures}; - use crate::ln::outbound_payment::{Bolt12PaymentError, OutboundPayments, PendingOutboundPayment, Retry, RetryableSendFailure, StaleExpiration}; + use crate::ln::outbound_payment::{ + Bolt12PaymentError, OutboundPayments, PendingOutboundPayment, Retry, RetryableSendFailure, + StaleExpiration, + }; #[cfg(feature = "std")] use crate::offers::invoice::DEFAULT_RELATIVE_EXPIRY; use crate::offers::invoice_request::InvoiceRequest; @@ -2607,8 +2661,13 @@ mod tests { use crate::offers::offer::OfferBuilder; use crate::offers::test_utils::*; use crate::routing::gossip::NetworkGraph; - use crate::routing::router::{InFlightHtlcs, Path, PaymentParameters, Route, RouteHop, RouteParameters, RouteParametersConfig}; + use crate::routing::router::{ + InFlightHtlcs, Path, PaymentParameters, Route, RouteHop, RouteParameters, + RouteParametersConfig, + }; use crate::sync::{Arc, Mutex, RwLock}; + use crate::types::features::{Bolt12InvoiceFeatures, ChannelFeatures, NodeFeatures}; + use crate::types::payment::{PaymentHash, PaymentPreimage}; use crate::util::errors::APIError; use crate::util::hash_tables::new_hash_map; use crate::util::test_utils; @@ -2616,6 +2675,7 @@ mod tests { use alloc::collections::VecDeque; #[test] + #[rustfmt::skip] fn test_recipient_onion_fields_with_custom_tlvs() { let onion_fields = RecipientOnionFields::spontaneous_empty(); @@ -2644,6 +2704,7 @@ mod tests { do_fails_paying_after_expiration(true); } #[cfg(feature = "std")] + #[rustfmt::skip] fn do_fails_paying_after_expiration(on_retry: bool) { let outbound_payments = OutboundPayments::new(new_hash_map()); let logger = test_utils::TestLogger::new(); @@ -2688,6 +2749,7 @@ mod tests { do_find_route_error(false); do_find_route_error(true); } + #[rustfmt::skip] fn do_find_route_error(on_retry: bool) { let outbound_payments = OutboundPayments::new(new_hash_map()); let logger = test_utils::TestLogger::new(); @@ -2726,6 +2788,7 @@ mod tests { } #[test] + #[rustfmt::skip] fn initial_send_payment_path_failed_evs() { let outbound_payments = OutboundPayments::new(new_hash_map()); let logger = test_utils::TestLogger::new(); @@ -2807,6 +2870,7 @@ mod tests { } #[test] + #[rustfmt::skip] fn removes_stale_awaiting_invoice_using_absolute_timeout() { let pending_events = Mutex::new(VecDeque::new()); let outbound_payments = OutboundPayments::new(new_hash_map()); @@ -2861,6 +2925,7 @@ mod tests { } #[test] + #[rustfmt::skip] fn removes_stale_awaiting_invoice_using_timer_ticks() { let pending_events = Mutex::new(VecDeque::new()); let outbound_payments = OutboundPayments::new(new_hash_map()); @@ -2914,6 +2979,7 @@ mod tests { } #[test] + #[rustfmt::skip] fn removes_abandoned_awaiting_invoice() { let pending_events = Mutex::new(VecDeque::new()); let outbound_payments = OutboundPayments::new(new_hash_map()); @@ -2944,6 +3010,7 @@ mod tests { #[cfg(feature = "std")] #[test] + #[rustfmt::skip] fn fails_sending_payment_for_expired_bolt12_invoice() { let logger = test_utils::TestLogger::new(); let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, &logger)); @@ -2998,6 +3065,7 @@ mod tests { } #[test] + #[rustfmt::skip] fn fails_finding_route_for_bolt12_invoice() { let logger = test_utils::TestLogger::new(); let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, &logger)); @@ -3060,6 +3128,7 @@ mod tests { } #[test] + #[rustfmt::skip] fn sends_payment_for_bolt12_invoice() { let logger = test_utils::TestLogger::new(); let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, &logger)); @@ -3156,6 +3225,7 @@ mod tests { assert!(pending_events.lock().unwrap().is_empty()); } + #[rustfmt::skip] fn dummy_invoice_request() -> InvoiceRequest { let expanded_key = ExpandedKey::new([42; 32]); let entropy = FixedEntropy {}; @@ -3173,6 +3243,7 @@ mod tests { } #[test] + #[rustfmt::skip] fn time_out_unreleased_async_payments() { let pending_events = Mutex::new(VecDeque::new()); let outbound_payments = OutboundPayments::new(new_hash_map()); @@ -3221,6 +3292,7 @@ mod tests { } #[test] + #[rustfmt::skip] fn abandon_unreleased_async_payment() { let pending_events = Mutex::new(VecDeque::new()); let outbound_payments = OutboundPayments::new(new_hash_map()); diff --git a/lightning/src/ln/peer_handler.rs b/lightning/src/ln/peer_handler.rs index 5c3bfd48d55..8bbecd0ccc1 100644 --- a/lightning/src/ln/peer_handler.rs +++ b/lightning/src/ln/peer_handler.rs @@ -1,5 +1,3 @@ -#![cfg_attr(rustfmt, rustfmt_skip)] - // This file is Copyright its original authors, visible in version control // history. // @@ -17,28 +15,39 @@ //! call into the provided message handlers (probably a ChannelManager and P2PGossipSync) with //! messages they should handle, and encoding/sending response messages. -use bitcoin::Txid; use bitcoin::constants::ChainHash; -use bitcoin::secp256k1::{self, Secp256k1, SecretKey, PublicKey}; +use bitcoin::secp256k1::{self, PublicKey, Secp256k1, SecretKey}; +use bitcoin::Txid; use crate::blinded_path::message::{AsyncPaymentsContext, DNSResolverContext, OffersContext}; -use crate::sign::{NodeSigner, Recipient}; -use crate::ln::types::ChannelId; -use crate::types::features::{InitFeatures, NodeFeatures}; use crate::ln::msgs; -use crate::ln::msgs::{BaseMessageHandler, ChannelMessageHandler, Init, LightningError, SocketAddress, MessageSendEvent, OnionMessageHandler, RoutingMessageHandler}; -use crate::util::ser::{VecWriter, Writeable, Writer}; -use crate::ln::peer_channel_encryptor::{PeerChannelEncryptor, NextNoiseStep, MessageBuf, MSG_BUF_ALLOC_SIZE}; +use crate::ln::msgs::{ + BaseMessageHandler, ChannelMessageHandler, Init, LightningError, MessageSendEvent, + OnionMessageHandler, RoutingMessageHandler, SocketAddress, +}; +use crate::ln::peer_channel_encryptor::{ + MessageBuf, NextNoiseStep, PeerChannelEncryptor, MSG_BUF_ALLOC_SIZE, +}; +use crate::ln::types::ChannelId; use crate::ln::wire; use crate::ln::wire::{Encode, Type}; -use crate::onion_message::async_payments::{AsyncPaymentsMessageHandler, HeldHtlcAvailable, ReleaseHeldHtlc}; -use crate::onion_message::dns_resolution::{DNSResolverMessageHandler, DNSResolverMessage, DNSSECProof, DNSSECQuery}; -use crate::onion_message::messenger::{CustomOnionMessageHandler, Responder, ResponseInstruction, MessageSendInstructions}; +use crate::onion_message::async_payments::{ + AsyncPaymentsMessageHandler, HeldHtlcAvailable, ReleaseHeldHtlc, +}; +use crate::onion_message::dns_resolution::{ + DNSResolverMessage, DNSResolverMessageHandler, DNSSECProof, DNSSECQuery, +}; +use crate::onion_message::messenger::{ + CustomOnionMessageHandler, MessageSendInstructions, Responder, ResponseInstruction, +}; use crate::onion_message::offers::{OffersMessage, OffersMessageHandler}; use crate::onion_message::packet::OnionMessageContents; -use crate::routing::gossip::{NodeId, NodeAlias}; +use crate::routing::gossip::{NodeAlias, NodeId}; +use crate::sign::{NodeSigner, Recipient}; +use crate::types::features::{InitFeatures, NodeFeatures}; use crate::util::atomic_counter::AtomicCounter; use crate::util::logger::{Level, Logger, WithContext}; +use crate::util::ser::{VecWriter, Writeable, Writer}; use crate::util::string::PrintableString; #[allow(unused_imports)] @@ -47,11 +56,11 @@ use crate::prelude::*; use alloc::collections::{btree_map, BTreeMap}; use crate::io; -use crate::sync::{Mutex, MutexGuard, FairRwLock}; -use core::sync::atomic::{AtomicBool, AtomicU32, AtomicI32, Ordering}; -use core::{cmp, hash, fmt, mem}; -use core::ops::Deref; +use crate::sync::{FairRwLock, Mutex, MutexGuard}; use core::convert::Infallible; +use core::ops::Deref; +use core::sync::atomic::{AtomicBool, AtomicI32, AtomicU32, Ordering}; +use core::{cmp, fmt, hash, mem}; #[cfg(not(c_bindings))] use { crate::ln::channelmanager::{SimpleArcChannelManager, SimpleRefChannelManager}, @@ -63,7 +72,7 @@ use { use bitcoin::hashes::sha256::Hash as Sha256; use bitcoin::hashes::sha256::HashEngine as Sha256Engine; -use bitcoin::hashes::{HashEngine, Hash}; +use bitcoin::hashes::{Hash, HashEngine}; /// A handler provided to [`PeerManager`] for reading and handling custom messages. /// @@ -77,6 +86,7 @@ pub trait CustomMessageHandler: wire::CustomMessageReader { /// Handles the given message sent from `sender_node_id`, possibly producing messages for /// [`CustomMessageHandler::get_and_clear_pending_msg`] to return and thus for [`PeerManager`] /// to send. + #[rustfmt::skip] fn handle_custom_message(&self, msg: Self::CustomMessage, sender_node_id: PublicKey) -> Result<(), LightningError>; /// Returns the list of pending messages that were generated by the handler, clearing the list @@ -94,6 +104,7 @@ pub trait CustomMessageHandler: wire::CustomMessageReader { /// message handlers may still wish to communicate with this peer. /// /// [`Self::peer_disconnected`] will not be called if `Err(())` is returned. + #[rustfmt::skip] fn peer_connected(&self, their_node_id: PublicKey, msg: &Init, inbound: bool) -> Result<(), ()>; /// Gets the node feature flags which this handler itself supports. All available handlers are @@ -113,39 +124,56 @@ pub trait CustomMessageHandler: wire::CustomMessageReader { /// A dummy struct which implements `RoutingMessageHandler` without storing any routing information /// or doing any processing. You can provide one of these as the route_handler in a MessageHandler. -pub struct IgnoringMessageHandler{} +pub struct IgnoringMessageHandler {} impl BaseMessageHandler for IgnoringMessageHandler { fn peer_disconnected(&self, _their_node_id: PublicKey) {} + #[rustfmt::skip] fn peer_connected(&self, _their_node_id: PublicKey, _init: &msgs::Init, _inbound: bool) -> Result<(), ()> { Ok(()) } + #[rustfmt::skip] fn provided_node_features(&self) -> NodeFeatures { NodeFeatures::empty() } fn provided_init_features(&self, _their_node_id: PublicKey) -> InitFeatures { InitFeatures::empty() } + #[rustfmt::skip] fn get_and_clear_pending_msg_events(&self) -> Vec { Vec::new() } } impl RoutingMessageHandler for IgnoringMessageHandler { + #[rustfmt::skip] fn handle_node_announcement(&self, _their_node_id: Option, _msg: &msgs::NodeAnnouncement) -> Result { Ok(false) } + #[rustfmt::skip] fn handle_channel_announcement(&self, _their_node_id: Option, _msg: &msgs::ChannelAnnouncement) -> Result { Ok(false) } + #[rustfmt::skip] fn handle_channel_update(&self, _their_node_id: Option, _msg: &msgs::ChannelUpdate) -> Result { Ok(false) } + #[rustfmt::skip] fn get_next_channel_announcement(&self, _starting_point: u64) -> Option<(msgs::ChannelAnnouncement, Option, Option)> { None } + #[rustfmt::skip] fn get_next_node_announcement(&self, _starting_point: Option<&NodeId>) -> Option { None } + #[rustfmt::skip] fn handle_reply_channel_range(&self, _their_node_id: PublicKey, _msg: msgs::ReplyChannelRange) -> Result<(), LightningError> { Ok(()) } + #[rustfmt::skip] fn handle_reply_short_channel_ids_end(&self, _their_node_id: PublicKey, _msg: msgs::ReplyShortChannelIdsEnd) -> Result<(), LightningError> { Ok(()) } + #[rustfmt::skip] fn handle_query_channel_range(&self, _their_node_id: PublicKey, _msg: msgs::QueryChannelRange) -> Result<(), LightningError> { Ok(()) } + #[rustfmt::skip] fn handle_query_short_channel_ids(&self, _their_node_id: PublicKey, _msg: msgs::QueryShortChannelIds) -> Result<(), LightningError> { Ok(()) } + #[rustfmt::skip] fn processing_queue_high(&self) -> bool { false } } impl OnionMessageHandler for IgnoringMessageHandler { fn handle_onion_message(&self, _their_node_id: PublicKey, _msg: &msgs::OnionMessage) {} + #[rustfmt::skip] fn next_onion_message_for_peer(&self, _peer_node_id: PublicKey) -> Option { None } fn timer_tick_occurred(&self) {} } impl OffersMessageHandler for IgnoringMessageHandler { - fn handle_message(&self, _message: OffersMessage, _context: Option, _responder: Option) -> Option<(OffersMessage, ResponseInstruction)> { + fn handle_message( + &self, _message: OffersMessage, _context: Option, + _responder: Option, + ) -> Option<(OffersMessage, ResponseInstruction)> { None } } @@ -168,11 +196,18 @@ impl DNSResolverMessageHandler for IgnoringMessageHandler { } impl CustomOnionMessageHandler for IgnoringMessageHandler { type CustomMessage = Infallible; - fn handle_custom_message(&self, _message: Infallible, _context: Option>, _responder: Option) -> Option<(Infallible, ResponseInstruction)> { + fn handle_custom_message( + &self, _message: Infallible, _context: Option>, _responder: Option, + ) -> Option<(Infallible, ResponseInstruction)> { // Since we always return `None` in the read the handle method should never be called. unreachable!(); } - fn read_custom_message(&self, _msg_type: u64, _buffer: &mut R) -> Result, msgs::DecodeError> where Self: Sized { + fn read_custom_message( + &self, _msg_type: u64, _buffer: &mut R, + ) -> Result, msgs::DecodeError> + where + Self: Sized, + { Ok(None) } fn release_pending_custom_messages(&self) -> Vec<(Infallible, MessageSendInstructions)> { @@ -181,15 +216,19 @@ impl CustomOnionMessageHandler for IgnoringMessageHandler { } impl OnionMessageContents for Infallible { + #[rustfmt::skip] fn tlv_type(&self) -> u64 { unreachable!(); } #[cfg(c_bindings)] + #[rustfmt::skip] fn msg_type(&self) -> String { unreachable!(); } #[cfg(not(c_bindings))] + #[rustfmt::skip] fn msg_type(&self) -> &'static str { unreachable!(); } } impl Deref for IgnoringMessageHandler { type Target = IgnoringMessageHandler; + #[rustfmt::skip] fn deref(&self) -> &Self { self } } @@ -208,23 +247,30 @@ impl Writeable for Infallible { impl wire::CustomMessageReader for IgnoringMessageHandler { type CustomMessage = Infallible; - fn read(&self, _message_type: u16, _buffer: &mut R) -> Result, msgs::DecodeError> { + fn read( + &self, _message_type: u16, _buffer: &mut R, + ) -> Result, msgs::DecodeError> { Ok(None) } } impl CustomMessageHandler for IgnoringMessageHandler { - fn handle_custom_message(&self, _msg: Infallible, _sender_node_id: PublicKey) -> Result<(), LightningError> { + fn handle_custom_message( + &self, _msg: Infallible, _sender_node_id: PublicKey, + ) -> Result<(), LightningError> { // Since we always return `None` in the read the handle method should never be called. unreachable!(); } + #[rustfmt::skip] fn get_and_clear_pending_msg(&self) -> Vec<(PublicKey, Self::CustomMessage)> { Vec::new() } fn peer_disconnected(&self, _their_node_id: PublicKey) {} + #[rustfmt::skip] fn peer_connected(&self, _their_node_id: PublicKey, _msg: &Init, _inbound: bool) -> Result<(), ()> { Ok(()) } + #[rustfmt::skip] fn provided_node_features(&self) -> NodeFeatures { NodeFeatures::empty() } fn provided_init_features(&self, _their_node_id: PublicKey) -> InitFeatures { @@ -235,13 +281,14 @@ impl CustomMessageHandler for IgnoringMessageHandler { /// A dummy struct which implements `ChannelMessageHandler` without having any channels. /// You can provide one of these as the route_handler in a MessageHandler. pub struct ErroringMessageHandler { - message_queue: Mutex> + message_queue: Mutex>, } impl ErroringMessageHandler { /// Constructs a new ErroringMessageHandler pub fn new() -> Self { Self { message_queue: Mutex::new(Vec::new()) } } + #[rustfmt::skip] fn push_error(&self, node_id: PublicKey, channel_id: ChannelId) { self.message_queue.lock().unwrap().push(MessageSendEvent::HandleError { action: msgs::ErrorAction::SendErrorMessage { @@ -253,7 +300,9 @@ impl ErroringMessageHandler { } impl BaseMessageHandler for ErroringMessageHandler { fn peer_disconnected(&self, _their_node_id: PublicKey) {} + #[rustfmt::skip] fn peer_connected(&self, _their_node_id: PublicKey, _init: &msgs::Init, _inbound: bool) -> Result<(), ()> { Ok(()) } + #[rustfmt::skip] fn provided_node_features(&self) -> NodeFeatures { NodeFeatures::empty() } fn provided_init_features(&self, _their_node_id: PublicKey) -> InitFeatures { // Set a number of features which various nodes may require to talk to us. It's totally @@ -285,9 +334,11 @@ impl BaseMessageHandler for ErroringMessageHandler { impl ChannelMessageHandler for ErroringMessageHandler { // Any messages which are related to a specific channel generate an error message to let the // peer know we don't care about channels. + #[rustfmt::skip] fn handle_open_channel(&self, their_node_id: PublicKey, msg: &msgs::OpenChannel) { ErroringMessageHandler::push_error(self, their_node_id, msg.common_fields.temporary_channel_id); } + #[rustfmt::skip] fn handle_accept_channel(&self, their_node_id: PublicKey, msg: &msgs::AcceptChannel) { ErroringMessageHandler::push_error(self, their_node_id, msg.common_fields.temporary_channel_id); } @@ -330,7 +381,9 @@ impl ChannelMessageHandler for ErroringMessageHandler { fn handle_update_fail_htlc(&self, their_node_id: PublicKey, msg: &msgs::UpdateFailHTLC) { ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id); } - fn handle_update_fail_malformed_htlc(&self, their_node_id: PublicKey, msg: &msgs::UpdateFailMalformedHTLC) { + fn handle_update_fail_malformed_htlc( + &self, their_node_id: PublicKey, msg: &msgs::UpdateFailMalformedHTLC, + ) { ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id); } fn handle_commitment_signed(&self, their_node_id: PublicKey, msg: &msgs::CommitmentSigned) { @@ -348,7 +401,9 @@ impl ChannelMessageHandler for ErroringMessageHandler { fn handle_update_fee(&self, their_node_id: PublicKey, msg: &msgs::UpdateFee) { ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id); } - fn handle_announcement_signatures(&self, their_node_id: PublicKey, msg: &msgs::AnnouncementSignatures) { + fn handle_announcement_signatures( + &self, their_node_id: PublicKey, msg: &msgs::AnnouncementSignatures, + ) { ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id); } fn handle_channel_reestablish(&self, their_node_id: PublicKey, msg: &msgs::ChannelReestablish) { @@ -358,6 +413,7 @@ impl ChannelMessageHandler for ErroringMessageHandler { fn handle_channel_update(&self, _their_node_id: PublicKey, _msg: &msgs::ChannelUpdate) {} fn handle_peer_storage(&self, _their_node_id: PublicKey, _msg: msgs::PeerStorage) {} + #[rustfmt::skip] fn handle_peer_storage_retrieval(&self, _their_node_id: PublicKey, _msg: msgs::PeerStorageRetrieval) {} fn handle_error(&self, _their_node_id: PublicKey, _msg: &msgs::ErrorMessage) {} @@ -369,10 +425,12 @@ impl ChannelMessageHandler for ErroringMessageHandler { None } + #[rustfmt::skip] fn handle_open_channel_v2(&self, their_node_id: PublicKey, msg: &msgs::OpenChannelV2) { ErroringMessageHandler::push_error(self, their_node_id, msg.common_fields.temporary_channel_id); } + #[rustfmt::skip] fn handle_accept_channel_v2(&self, their_node_id: PublicKey, msg: &msgs::AcceptChannelV2) { ErroringMessageHandler::push_error(self, their_node_id, msg.common_fields.temporary_channel_id); } @@ -418,11 +476,13 @@ impl ChannelMessageHandler for ErroringMessageHandler { impl Deref for ErroringMessageHandler { type Target = ErroringMessageHandler; + #[rustfmt::skip] fn deref(&self) -> &Self { self } } /// Provides references to trait impls which handle different types of messages. -pub struct MessageHandler where +pub struct MessageHandler +where CM::Target: ChannelMessageHandler, RM::Target: RoutingMessageHandler, OM::Target: OnionMessageHandler, @@ -462,7 +522,7 @@ pub struct MessageHandler where /// further calls to the [`PeerManager`] related to the original socket occur. This allows you to /// use a file descriptor for your SocketDescriptor directly, however for simplicity you may wish /// to simply use another value which is guaranteed to be globally unique instead. -pub trait SocketDescriptor : cmp::Eq + hash::Hash + Clone { +pub trait SocketDescriptor: cmp::Eq + hash::Hash + Clone { /// Attempts to send some data from the given slice to the peer. /// /// Returns the amount of data which was sent, possibly 0 if the socket has since disconnected. @@ -512,7 +572,7 @@ pub struct PeerDetails { /// generate no further read_event/write_buffer_space_avail/socket_disconnected calls for the /// descriptor. #[derive(Clone)] -pub struct PeerHandleError { } +pub struct PeerHandleError {} impl fmt::Debug for PeerHandleError { fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> { formatter.write_str("Peer Sent Invalid Data") @@ -525,7 +585,7 @@ impl fmt::Display for PeerHandleError { } /// Internal struct for keeping track of the gossip syncing progress with a given peer -enum InitSyncTracker{ +enum InitSyncTracker { /// Only sync ad-hoc gossip as it comes in, do not send historical gossip. /// Upon receipt of a GossipTimestampFilter message, this is the default initial state if the /// contained timestamp is less than 6 hours old. @@ -550,7 +610,8 @@ const FORWARD_INIT_SYNC_BUFFER_LIMIT_RATIO: usize = 2; const OUTBOUND_BUFFER_LIMIT_READ_PAUSE: usize = 12; /// When the outbound buffer has this many messages, we'll simply skip relaying gossip messages to /// the peer. -const OUTBOUND_BUFFER_LIMIT_DROP_GOSSIP: usize = OUTBOUND_BUFFER_LIMIT_READ_PAUSE * FORWARD_INIT_SYNC_BUFFER_LIMIT_RATIO; +const OUTBOUND_BUFFER_LIMIT_DROP_GOSSIP: usize = + OUTBOUND_BUFFER_LIMIT_READ_PAUSE * FORWARD_INIT_SYNC_BUFFER_LIMIT_RATIO; /// If we've sent a ping, and are still awaiting a response, we may need to churn our way through /// the socket receive buffer before receiving the ping. @@ -637,6 +698,7 @@ impl Peer { /// announcements/updates for the given channel_id then we will send it when we get to that /// point and we shouldn't send it yet to avoid sending duplicate updates. If we've already /// sent the old versions, we should send the update, and so return true here. + #[rustfmt::skip] fn should_forward_channel_announcement(&self, channel_id: u64) -> bool { if !self.handshake_complete() { return false; } if self.their_features.as_ref().unwrap().supports_gossip_queries() && @@ -651,6 +713,7 @@ impl Peer { } /// Similar to the above, but for node announcements indexed by node_id. + #[rustfmt::skip] fn should_forward_node_announcement(&self, node_id: NodeId) -> bool { if !self.handshake_complete() { return false; } if self.their_features.as_ref().unwrap().supports_gossip_queries() && @@ -666,6 +729,7 @@ impl Peer { /// Returns whether we should be reading bytes from this peer, based on whether its outbound /// buffer still has space and we don't need to pause reads to get some writes out. + #[rustfmt::skip] fn should_read(&mut self, gossip_processing_backlogged: bool) -> bool { if !gossip_processing_backlogged { self.received_channel_announce_since_backlogged = false; @@ -676,6 +740,7 @@ impl Peer { /// Determines if we should push additional gossip background sync (aka "backfill") onto a peer's /// outbound buffer. This is checked every time the peer's buffer may have been drained. + #[rustfmt::skip] fn should_buffer_gossip_backfill(&self) -> bool { self.pending_outbound_buffer.is_empty() && self.gossip_broadcast_buffer.is_empty() && self.msgs_sent_since_pong < BUFFER_DRAIN_MSGS_PER_TICK @@ -684,6 +749,7 @@ impl Peer { /// Determines if we should push an onion message onto a peer's outbound buffer. This is checked /// every time the peer's buffer may have been drained. + #[rustfmt::skip] fn should_buffer_onion_message(&self) -> bool { self.pending_outbound_buffer.is_empty() && self.handshake_complete() && self.msgs_sent_since_pong < BUFFER_DRAIN_MSGS_PER_TICK @@ -691,12 +757,14 @@ impl Peer { /// Determines if we should push additional gossip broadcast messages onto a peer's outbound /// buffer. This is checked every time the peer's buffer may have been drained. + #[rustfmt::skip] fn should_buffer_gossip_broadcast(&self) -> bool { self.pending_outbound_buffer.is_empty() && self.handshake_complete() && self.msgs_sent_since_pong < BUFFER_DRAIN_MSGS_PER_TICK } /// Returns whether this peer's outbound buffers are full and we should drop gossip broadcasts. + #[rustfmt::skip] fn buffer_full_drop_gossip_broadcast(&self) -> bool { let total_outbound_buffered = self.gossip_broadcast_buffer.len() + self.pending_outbound_buffer.len(); @@ -725,7 +793,7 @@ pub type SimpleArcPeerManager = PeerManager< Arc>, Arc, IgnoringMessageHandler, - Arc + Arc, >; /// SimpleRefPeerManager is a type alias for a PeerManager reference, and is the reference @@ -738,7 +806,25 @@ pub type SimpleArcPeerManager = PeerManager< /// This is not exported to bindings users as type aliases aren't supported in most languages. #[cfg(not(c_bindings))] pub type SimpleRefPeerManager< - 'a, 'b, 'c, 'd, 'e, 'f, 'logger, 'h, 'i, 'j, 'graph, 'k, 'mr, SD, M, T, F, C, L + 'a, + 'b, + 'c, + 'd, + 'e, + 'f, + 'logger, + 'h, + 'i, + 'j, + 'graph, + 'k, + 'mr, + SD, + M, + T, + F, + C, + L, > = PeerManager< SD, &'j SimpleRefChannelManager<'a, 'b, 'c, 'd, 'e, 'graph, 'logger, 'i, 'mr, M, T, F, L>, @@ -746,10 +832,9 @@ pub type SimpleRefPeerManager< &'h SimpleRefOnionMessenger<'a, 'b, 'c, 'd, 'e, 'graph, 'logger, 'i, 'j, 'k, M, T, F, L>, &'logger L, IgnoringMessageHandler, - &'c KeysManager + &'c KeysManager, >; - /// A generic trait which is implemented for all [`PeerManager`]s. This makes bounding functions or /// structs on any [`PeerManager`] much simpler as only this trait is needed as a bound, rather /// than the full set of bounds on [`PeerManager`] itself. @@ -760,23 +845,33 @@ pub type SimpleRefPeerManager< pub trait APeerManager { type Descriptor: SocketDescriptor; type CMT: ChannelMessageHandler + ?Sized; - type CM: Deref; + type CM: Deref; type RMT: RoutingMessageHandler + ?Sized; - type RM: Deref; + type RM: Deref; type OMT: OnionMessageHandler + ?Sized; - type OM: Deref; + type OM: Deref; type LT: Logger + ?Sized; - type L: Deref; + type L: Deref; type CMHT: CustomMessageHandler + ?Sized; - type CMH: Deref; + type CMH: Deref; type NST: NodeSigner + ?Sized; - type NS: Deref; + type NS: Deref; /// Gets a reference to the underlying [`PeerManager`]. - fn as_ref(&self) -> &PeerManager; + fn as_ref( + &self, + ) -> &PeerManager; } -impl -APeerManager for PeerManager where +impl< + Descriptor: SocketDescriptor, + CM: Deref, + RM: Deref, + OM: Deref, + L: Deref, + CMH: Deref, + NS: Deref, + > APeerManager for PeerManager +where CM::Target: ChannelMessageHandler, RM::Target: RoutingMessageHandler, OM::Target: OnionMessageHandler, @@ -797,6 +892,7 @@ APeerManager for PeerManager where type CMH = CMH; type NST = ::Target; type NS = NS; + #[rustfmt::skip] fn as_ref(&self) -> &PeerManager { self } } @@ -819,13 +915,22 @@ APeerManager for PeerManager where /// you're using lightning-net-tokio. /// /// [`read_event`]: PeerManager::read_event -pub struct PeerManager where - CM::Target: ChannelMessageHandler, - RM::Target: RoutingMessageHandler, - OM::Target: OnionMessageHandler, - L::Target: Logger, - CMH::Target: CustomMessageHandler, - NS::Target: NodeSigner { +pub struct PeerManager< + Descriptor: SocketDescriptor, + CM: Deref, + RM: Deref, + OM: Deref, + L: Deref, + CMH: Deref, + NS: Deref, +> where + CM::Target: ChannelMessageHandler, + RM::Target: RoutingMessageHandler, + OM::Target: OnionMessageHandler, + L::Target: Logger, + CMH::Target: CustomMessageHandler, + NS::Target: NodeSigner, +{ message_handler: MessageHandler, /// Connection state for each connected peer - we have an outer read-write lock which is taken /// as read while we're doing processing for a peer and taken write when a peer is being added @@ -868,7 +973,7 @@ pub struct PeerManager + secp_ctx: Secp256k1, } enum LogicalMessage { @@ -893,6 +998,7 @@ impl From for MessageHandlingError { } } +#[rustfmt::skip] macro_rules! encode_msg { ($msg: expr) => {{ let mut buffer = VecWriter(Vec::with_capacity(MSG_BUF_ALLOC_SIZE)); @@ -901,11 +1007,14 @@ macro_rules! encode_msg { }} } -impl PeerManager where - CM::Target: ChannelMessageHandler, - OM::Target: OnionMessageHandler, - L::Target: Logger, - NS::Target: NodeSigner { +impl + PeerManager +where + CM::Target: ChannelMessageHandler, + OM::Target: OnionMessageHandler, + L::Target: Logger, + NS::Target: NodeSigner, +{ /// Constructs a new `PeerManager` with the given `ChannelMessageHandler` and /// `OnionMessageHandler`. No routing message handler is used and network graph messages are /// ignored. @@ -919,6 +1028,7 @@ impl Pe /// minute should suffice. /// /// This is not exported to bindings users as we can't export a PeerManager with a dummy route handler + #[rustfmt::skip] pub fn new_channel_only(channel_message_handler: CM, onion_message_handler: OM, current_time: u32, ephemeral_random_data: &[u8; 32], logger: L, node_signer: NS) -> Self { Self::new(MessageHandler { chan_handler: channel_message_handler, @@ -929,10 +1039,20 @@ impl Pe } } -impl PeerManager where - RM::Target: RoutingMessageHandler, - L::Target: Logger, - NS::Target: NodeSigner { +impl + PeerManager< + Descriptor, + ErroringMessageHandler, + RM, + IgnoringMessageHandler, + L, + IgnoringMessageHandler, + NS, + > where + RM::Target: RoutingMessageHandler, + L::Target: Logger, + NS::Target: NodeSigner, +{ /// Constructs a new `PeerManager` with the given `RoutingMessageHandler`. No channel message /// handler or onion message handler is used and onion and channel messages will be ignored (or /// generate error messages). Note that some other lightning implementations time-out connections @@ -947,6 +1067,7 @@ impl PeerManager Self { Self::new(MessageHandler { chan_handler: ErroringMessageHandler::new(), @@ -963,6 +1084,7 @@ impl PeerManager(&'a Option<(PublicKey, NodeId)>); impl core::fmt::Display for OptionalFromDebugger<'_> { + #[rustfmt::skip] fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> Result<(), core::fmt::Error> { if let Some((node_id, _)) = self.0 { write!(f, " from {}", log_pubkey!(node_id)) } else { Ok(()) } } @@ -971,6 +1093,7 @@ impl core::fmt::Display for OptionalFromDebugger<'_> { /// A function used to filter out local or private addresses /// /// +#[rustfmt::skip] fn filter_addresses(ip_address: Option) -> Option { match ip_address{ // For IPv4 range 10.0.0.0 - 10.255.255.255 (10/8) @@ -998,13 +1121,22 @@ fn filter_addresses(ip_address: Option) -> Option } } -impl PeerManager where - CM::Target: ChannelMessageHandler, - RM::Target: RoutingMessageHandler, - OM::Target: OnionMessageHandler, - L::Target: Logger, - CMH::Target: CustomMessageHandler, - NS::Target: NodeSigner +impl< + Descriptor: SocketDescriptor, + CM: Deref, + RM: Deref, + OM: Deref, + L: Deref, + CMH: Deref, + NS: Deref, + > PeerManager +where + CM::Target: ChannelMessageHandler, + RM::Target: RoutingMessageHandler, + OM::Target: OnionMessageHandler, + L::Target: Logger, + CMH::Target: CustomMessageHandler, + NS::Target: NodeSigner, { /// Constructs a new `PeerManager` with the given message handlers. /// @@ -1015,7 +1147,10 @@ impl, current_time: u32, ephemeral_random_data: &[u8; 32], logger: L, node_signer: NS) -> Self { + pub fn new( + message_handler: MessageHandler, current_time: u32, + ephemeral_random_data: &[u8; 32], logger: L, node_signer: NS, + ) -> Self { let mut ephemeral_key_midstate = Sha256::engine(); ephemeral_key_midstate.input(ephemeral_random_data); @@ -1041,6 +1176,7 @@ impl Vec { let peers = self.peers.read().unwrap(); peers.values().filter_map(|peer_mutex| { @@ -1093,6 +1229,7 @@ impl SecretKey { let mut ephemeral_hash = self.ephemeral_key_midstate.clone(); let counter = self.peer_counter.next(); @@ -1122,6 +1259,7 @@ impl) -> Result, PeerHandleError> { let mut peer_encryptor = PeerChannelEncryptor::new_outbound(their_node_id.clone(), self.get_ephemeral_key()); let res = peer_encryptor.get_act_one(&self.secp_ctx).to_vec(); @@ -1181,6 +1319,7 @@ impl) -> Result<(), PeerHandleError> { let peer_encryptor = PeerChannelEncryptor::new_inbound(&self.node_signer); let pending_read_buffer = [0; 50].to_vec(); // Noise act one is 50 bytes @@ -1236,6 +1375,7 @@ impl Result<(), PeerHandleError> { let peers = self.peers.read().unwrap(); match peers.get(descriptor) { @@ -1375,6 +1516,7 @@ impl Result { match self.do_read_event(peer_descriptor, data) { Ok(res) => Ok(res), @@ -1386,6 +1528,7 @@ impl(&self, peer: &mut Peer, message: &M) { let logger = WithContext::from(&self.logger, peer.their_node_id.map(|p| p.0), None, None); if is_gossip_msg(message.type_id()) { @@ -1403,6 +1546,7 @@ impl Result { let mut pause_read = false; let peers = self.peers.read().unwrap(); @@ -1491,6 +1635,7 @@ impl { let logger = WithContext::from(&self.logger, peer.their_node_id.map(|p| p.0), None, None); @@ -1654,6 +1799,7 @@ impl, @@ -1684,6 +1830,7 @@ impl( &self, mut peer_lock: MutexGuard, @@ -1853,6 +2000,7 @@ impl( &self, peer_mutex: &Mutex, @@ -2077,6 +2225,7 @@ impl>, msg: &wire::Message<<::Target as wire::CustomMessageReader>::CustomMessage>, @@ -2186,6 +2335,7 @@ impl 0 { // If we're not the first event processor to get here, just return early, the increment @@ -2203,6 +2353,7 @@ impl { { @@ -2628,6 +2779,7 @@ impl) { if addresses.len() > 100 { panic!("More than half the message size was taken up by public addresses!"); @@ -2872,6 +3031,7 @@ impl bool { match type_id { msgs::ChannelAnnouncement::TYPE | @@ -2889,18 +3049,18 @@ fn is_gossip_msg(type_id: u16) -> bool { mod tests { use super::*; - use crate::sign::{NodeSigner, Recipient}; use crate::io; - use crate::ln::types::ChannelId; - use crate::types::features::{InitFeatures, NodeFeatures}; + use crate::ln::msgs::{Init, LightningError, SocketAddress}; use crate::ln::peer_channel_encryptor::PeerChannelEncryptor; + use crate::ln::types::ChannelId; use crate::ln::{msgs, wire}; - use crate::ln::msgs::{Init, LightningError, SocketAddress}; + use crate::sign::{NodeSigner, Recipient}; + use crate::types::features::{InitFeatures, NodeFeatures}; use crate::util::test_utils; - use bitcoin::Network; use bitcoin::constants::ChainHash; - use bitcoin::secp256k1::{PublicKey, SecretKey, Secp256k1}; + use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey}; + use bitcoin::Network; use crate::sync::{Arc, Mutex}; use core::convert::Infallible; @@ -2921,7 +3081,7 @@ mod tests { self.fd == other.fd } } - impl Eq for FileDescriptor { } + impl Eq for FileDescriptor {} impl core::hash::Hash for FileDescriptor { fn hash(&self, hasher: &mut H) { self.fd.hash(hasher) @@ -2938,6 +3098,7 @@ mod tests { } } + #[rustfmt::skip] fn disconnect_socket(&mut self) { self.disconnect.store(true, Ordering::Release); } } @@ -2966,6 +3127,7 @@ mod tests { } impl TestCustomMessageHandler { + #[rustfmt::skip] fn new(features: InitFeatures) -> Self { Self { features, @@ -2976,7 +3138,9 @@ mod tests { impl wire::CustomMessageReader for TestCustomMessageHandler { type CustomMessage = Infallible; - fn read(&self, _: u16, _: &mut R) -> Result, msgs::DecodeError> { + fn read( + &self, _: u16, _: &mut R, + ) -> Result, msgs::DecodeError> { Ok(None) } } @@ -2986,16 +3150,20 @@ mod tests { unreachable!(); } + #[rustfmt::skip] fn get_and_clear_pending_msg(&self) -> Vec<(PublicKey, Self::CustomMessage)> { Vec::new() } fn peer_disconnected(&self, their_node_id: PublicKey) { self.conn_tracker.peer_disconnected(their_node_id); } - fn peer_connected(&self, their_node_id: PublicKey, _msg: &Init, _inbound: bool) -> Result<(), ()> { + fn peer_connected( + &self, their_node_id: PublicKey, _msg: &Init, _inbound: bool, + ) -> Result<(), ()> { self.conn_tracker.peer_connected(their_node_id) } + #[rustfmt::skip] fn provided_node_features(&self) -> NodeFeatures { NodeFeatures::empty() } fn provided_init_features(&self, _: PublicKey) -> InitFeatures { @@ -3003,6 +3171,7 @@ mod tests { } } + #[rustfmt::skip] fn create_peermgr_cfgs(peer_count: usize) -> Vec { let mut cfgs = Vec::new(); for i in 0..peer_count { @@ -3026,6 +3195,7 @@ mod tests { cfgs } + #[rustfmt::skip] fn create_feature_incompatible_peermgr_cfgs(peer_count: usize) -> Vec { let mut cfgs = Vec::new(); for i in 0..peer_count { @@ -3049,6 +3219,7 @@ mod tests { cfgs } + #[rustfmt::skip] fn create_chain_incompatible_peermgr_cfgs(peer_count: usize) -> Vec { let mut cfgs = Vec::new(); for i in 0..peer_count { @@ -3069,6 +3240,7 @@ mod tests { cfgs } + #[rustfmt::skip] fn create_network<'a>(peer_count: usize, cfgs: &'a Vec) -> Vec> { let mut peers = Vec::new(); for i in 0..peer_count { @@ -3084,6 +3256,7 @@ mod tests { peers } + #[rustfmt::skip] fn try_establish_connection<'a>(peer_a: &PeerManager, peer_b: &PeerManager) -> (FileDescriptor, FileDescriptor, Result, Result) { let addr_a = SocketAddress::TcpIpV4{addr: [127, 0, 0, 1], port: 1000}; let addr_b = SocketAddress::TcpIpV4{addr: [127, 0, 0, 1], port: 1001}; @@ -3114,7 +3287,7 @@ mod tests { (fd_a, fd_b, a_refused, b_refused) } - + #[rustfmt::skip] fn establish_connection<'a>(peer_a: &PeerManager, peer_b: &PeerManager) -> (FileDescriptor, FileDescriptor) { let addr_a = SocketAddress::TcpIpV4{addr: [127, 0, 0, 1], port: 1000}; let addr_b = SocketAddress::TcpIpV4{addr: [127, 0, 0, 1], port: 1001}; @@ -3150,6 +3323,7 @@ mod tests { let peers = Arc::new(create_network(2, unsafe { &*(&*cfgs as *const _) as &'static _ })); let start_time = std::time::Instant::now(); + #[rustfmt::skip] macro_rules! spawn_thread { ($id: expr) => { { let peers = Arc::clone(&peers); let cfgs = Arc::clone(&cfgs); @@ -3214,6 +3388,7 @@ mod tests { } #[test] + #[rustfmt::skip] fn test_feature_incompatible_peers() { let cfgs = create_peermgr_cfgs(2); let incompatible_cfgs = create_feature_incompatible_peermgr_cfgs(2); @@ -3244,6 +3419,7 @@ mod tests { } #[test] + #[rustfmt::skip] fn test_chain_incompatible_peers() { let cfgs = create_peermgr_cfgs(2); let incompatible_cfgs = create_chain_incompatible_peermgr_cfgs(2); @@ -3293,6 +3469,7 @@ mod tests { } #[test] + #[rustfmt::skip] fn test_send_simple_msg() { // Simple test which builds a network of PeerManager, connects and brings them to NoiseState::Finished and // push a message from one peer to another. @@ -3321,6 +3498,7 @@ mod tests { } #[test] + #[rustfmt::skip] fn test_non_init_first_msg() { // Simple test of the first message received over a connection being something other than // Init. This results in an immediate disconnection, which previously included a spurious @@ -3381,6 +3559,7 @@ mod tests { assert_eq!(peers[0].peers.read().unwrap().len(), 0); } + #[rustfmt::skip] fn do_test_peer_connected_error_disconnects(handler: usize) { // Test that if a message handler fails a connection in `peer_connected` we reliably // produce `peer_disconnected` events for all other message handlers (that saw a @@ -3426,6 +3605,7 @@ mod tests { } #[test] + #[rustfmt::skip] fn test_do_attempt_write_data() { // Create 2 peers with custom TestRoutingMessageHandlers and connect them. let cfgs = create_peermgr_cfgs(2); @@ -3504,6 +3684,7 @@ mod tests { } #[test] + #[rustfmt::skip] fn test_inbound_conn_handshake_complete_awaiting_pong() { // Test that we do not disconnect an outbound peer after the noise handshake completes due // to a pong timeout for a ping that was never sent if a timer tick fires after we send act @@ -3607,6 +3788,7 @@ mod tests { let peers = create_network(2, &cfgs); let (mut fd_a, mut fd_b) = establish_connection(&peers[0], &peers[1]); + #[rustfmt::skip] macro_rules! drain_queues { () => { loop { peers[0].process_events(); @@ -3632,10 +3814,7 @@ mod tests { let secp_ctx = Secp256k1::new(); let key = SecretKey::from_slice(&[1; 32]).unwrap(); let msg = channel_announcement(&key, &key, ChannelFeatures::empty(), 42, &secp_ctx); - let msg_ev = MessageSendEvent::BroadcastChannelAnnouncement { - msg, - update_msg: None, - }; + let msg_ev = MessageSendEvent::BroadcastChannelAnnouncement { msg, update_msg: None }; fd_a.hang_writes.store(true, Ordering::Relaxed); @@ -3646,15 +3825,37 @@ mod tests { peers[0].process_events(); } - assert_eq!(peers[0].peers.read().unwrap().get(&fd_a).unwrap().lock().unwrap().gossip_broadcast_buffer.len(), - OUTBOUND_BUFFER_LIMIT_DROP_GOSSIP); + assert_eq!( + peers[0] + .peers + .read() + .unwrap() + .get(&fd_a) + .unwrap() + .lock() + .unwrap() + .gossip_broadcast_buffer + .len(), + OUTBOUND_BUFFER_LIMIT_DROP_GOSSIP + ); // Check that if a broadcast message comes in from the channel handler (i.e. it is an // announcement for our own channel), it gets queued anyway. cfgs[0].chan_handler.pending_events.lock().unwrap().push(msg_ev); peers[0].process_events(); - assert_eq!(peers[0].peers.read().unwrap().get(&fd_a).unwrap().lock().unwrap().gossip_broadcast_buffer.len(), - OUTBOUND_BUFFER_LIMIT_DROP_GOSSIP + 1); + assert_eq!( + peers[0] + .peers + .read() + .unwrap() + .get(&fd_a) + .unwrap() + .lock() + .unwrap() + .gossip_broadcast_buffer + .len(), + OUTBOUND_BUFFER_LIMIT_DROP_GOSSIP + 1 + ); // Finally, deliver all the messages and make sure we got the right count. Note that there // was an extra message that had already moved from the broadcast queue to the encrypted @@ -3664,12 +3865,24 @@ mod tests { peers[0].write_buffer_space_avail(&mut fd_a).unwrap(); drain_queues!(); - assert!(peers[0].peers.read().unwrap().get(&fd_a).unwrap().lock().unwrap().gossip_broadcast_buffer.is_empty()); - assert_eq!(cfgs[1].routing_handler.chan_anns_recvd.load(Ordering::Relaxed), - OUTBOUND_BUFFER_LIMIT_DROP_GOSSIP + 2); + assert!(peers[0] + .peers + .read() + .unwrap() + .get(&fd_a) + .unwrap() + .lock() + .unwrap() + .gossip_broadcast_buffer + .is_empty()); + assert_eq!( + cfgs[1].routing_handler.chan_anns_recvd.load(Ordering::Relaxed), + OUTBOUND_BUFFER_LIMIT_DROP_GOSSIP + 2 + ); } #[test] + #[rustfmt::skip] fn test_filter_addresses(){ // Tests the filter_addresses function. @@ -3767,6 +3980,7 @@ mod tests { #[test] #[cfg(feature = "std")] + #[rustfmt::skip] fn test_process_events_multithreaded() { use std::time::{Duration, Instant}; // `process_events` shouldn't block on another thread processing events and instead should diff --git a/lightning/src/ln/priv_short_conf_tests.rs b/lightning/src/ln/priv_short_conf_tests.rs index 8f0ab5e39ed..b7fa5d95e9f 100644 --- a/lightning/src/ln/priv_short_conf_tests.rs +++ b/lightning/src/ln/priv_short_conf_tests.rs @@ -1,5 +1,3 @@ -#![cfg_attr(rustfmt, rustfmt_skip)] - // This file is Copyright its original authors, visible in version control // history. // @@ -15,14 +13,16 @@ use crate::chain::ChannelMonitorUpdateStatus; use crate::events::{ClosureReason, Event, HTLCHandlingFailureType}; -use crate::ln::channelmanager::{MIN_CLTV_EXPIRY_DELTA, PaymentId, RecipientOnionFields}; +use crate::ln::channelmanager::{PaymentId, RecipientOnionFields, MIN_CLTV_EXPIRY_DELTA}; +use crate::ln::msgs; +use crate::ln::msgs::{ + BaseMessageHandler, ChannelMessageHandler, ErrorAction, MessageSendEvent, RoutingMessageHandler, +}; use crate::ln::onion_utils::LocalHTLCFailureReason; +use crate::ln::types::ChannelId; use crate::routing::gossip::RoutingFees; use crate::routing::router::{PaymentParameters, RouteHint, RouteHintHop}; use crate::types::features::ChannelTypeFeatures; -use crate::ln::msgs; -use crate::ln::types::ChannelId; -use crate::ln::msgs::{BaseMessageHandler, ChannelMessageHandler, RoutingMessageHandler, ErrorAction, MessageSendEvent}; use crate::util::config::{MaxDustHTLCExposure, UserConfig}; use crate::util::ser::Writeable; @@ -31,6 +31,7 @@ use crate::prelude::*; use crate::ln::functional_test_utils::*; #[test] +#[rustfmt::skip] fn test_priv_forwarding_rejection() { // If we have a private channel with outbound liquidity, and // UserConfig::accept_forwards_to_priv_channels is set to false, we should reject any attempts @@ -137,6 +138,7 @@ fn test_priv_forwarding_rejection() { claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], our_payment_preimage); } +#[rustfmt::skip] fn do_test_1_conf_open(connect_style: ConnectStyle) { // Previously, if the minium_depth config was set to 1, we'd never send a channel_ready. This // tests that we properly send one in that case. @@ -225,6 +227,7 @@ fn test_1_conf_open() { } #[test] +#[rustfmt::skip] fn test_routed_scid_alias() { // Trivially test sending a payment which is routed through an SCID alias. let chanmon_cfgs = create_chanmon_cfgs(3); @@ -283,6 +286,7 @@ fn test_routed_scid_alias() { } #[test] +#[rustfmt::skip] fn test_scid_privacy_on_pub_channel() { // Tests rejecting the scid_privacy feature for public channels and that we don't ever try to // send them. @@ -307,6 +311,7 @@ fn test_scid_privacy_on_pub_channel() { } #[test] +#[rustfmt::skip] fn test_scid_privacy_negotiation() { // Tests of the negotiation of SCID alias and falling back to non-SCID-alias if our // counterparty doesn't support it. @@ -349,6 +354,7 @@ fn test_scid_privacy_negotiation() { } #[test] +#[rustfmt::skip] fn test_inbound_scid_privacy() { // Tests accepting channels with the scid_privacy feature and rejecting forwards using the // channel's real SCID as required by the channel feature. @@ -464,6 +470,7 @@ fn test_inbound_scid_privacy() { } #[test] +#[rustfmt::skip] fn test_scid_alias_returned() { // Tests that when we fail an HTLC (in this case due to attempting to forward more than the // channel's available balance) we use the correct (in this case the aliased) SCID in the @@ -572,6 +579,7 @@ fn test_simple_0conf_channel() { } #[test] +#[rustfmt::skip] fn test_0conf_channel_with_async_monitor() { // Test that we properly send out channel_ready in (both inbound- and outbound-) zero-conf // channels if ChannelMonitor updates return a `TemporaryFailure` during the initial channel @@ -740,6 +748,7 @@ fn test_0conf_channel_with_async_monitor() { } #[test] +#[rustfmt::skip] fn test_0conf_close_no_early_chan_update() { // Tests that even with a public channel 0conf channel, we don't generate a channel_update on // closing. @@ -766,6 +775,7 @@ fn test_0conf_close_no_early_chan_update() { } #[test] +#[rustfmt::skip] fn test_public_0conf_channel() { // Tests that we will announce a public channel (after confirmation) even if its 0conf. let chanmon_cfgs = create_chanmon_cfgs(2); @@ -818,6 +828,7 @@ fn test_public_0conf_channel() { } #[test] +#[rustfmt::skip] fn test_0conf_channel_reorg() { // If we accept a 0conf channel, which is then confirmed, but then changes SCID in a reorg, we // have to make sure we handle this correctly (or, currently, just force-close the channel). @@ -869,6 +880,7 @@ fn test_0conf_channel_reorg() { } #[test] +#[rustfmt::skip] fn test_zero_conf_accept_reject() { let mut channel_type_features = ChannelTypeFeatures::only_static_remote_key(); channel_type_features.set_zero_conf_required(); @@ -966,6 +978,7 @@ fn test_zero_conf_accept_reject() { } #[test] +#[rustfmt::skip] fn test_connect_before_funding() { // Tests for a particularly dumb explicit panic that existed prior to 0.0.111 for 0conf // channels. If we received a block while awaiting funding for 0-conf channels we'd hit an @@ -1008,6 +1021,7 @@ fn test_connect_before_funding() { } #[test] +#[rustfmt::skip] fn test_0conf_ann_sigs_racing_conf() { // Previously we had a bug where we'd panic when receiving a counterparty's // announcement_signatures message for a 0conf channel pending confirmation on-chain. Here we diff --git a/lightning/src/ln/reload_tests.rs b/lightning/src/ln/reload_tests.rs index 17028b36ae5..4b86e731e12 100644 --- a/lightning/src/ln/reload_tests.rs +++ b/lightning/src/ln/reload_tests.rs @@ -1,5 +1,3 @@ -#![cfg_attr(rustfmt, rustfmt_skip)] - // This file is Copyright its original authors, visible in version control // history. // @@ -11,25 +9,29 @@ //! Functional tests which test for correct behavior across node restarts. -use crate::chain::{ChannelMonitorUpdateStatus, Watch}; use crate::chain::chaininterface::LowerBoundedFeeEstimator; use crate::chain::channelmonitor::{ChannelMonitor, ChannelMonitorUpdateStep}; -use crate::routing::router::{PaymentParameters, RouteParameters}; -use crate::sign::EntropySource; use crate::chain::transaction::OutPoint; +use crate::chain::{ChannelMonitorUpdateStatus, Watch}; use crate::events::{ClosureReason, Event, HTLCHandlingFailureType}; -use crate::ln::channelmanager::{ChannelManager, ChannelManagerReadArgs, PaymentId, RecipientOnionFields, RAACommitmentOrder}; +use crate::ln::channelmanager::{ + ChannelManager, ChannelManagerReadArgs, PaymentId, RAACommitmentOrder, RecipientOnionFields, +}; use crate::ln::msgs; +use crate::ln::msgs::{ + BaseMessageHandler, ChannelMessageHandler, ErrorAction, MessageSendEvent, RoutingMessageHandler, +}; use crate::ln::types::ChannelId; -use crate::ln::msgs::{BaseMessageHandler, ChannelMessageHandler, RoutingMessageHandler, ErrorAction, MessageSendEvent}; +use crate::routing::router::{PaymentParameters, RouteParameters}; +use crate::sign::EntropySource; +use crate::util::config::UserConfig; +use crate::util::errors::APIError; +use crate::util::ser::{ReadableArgs, Writeable}; use crate::util::test_channel_signer::TestChannelSigner; use crate::util::test_utils; -use crate::util::errors::APIError; -use crate::util::ser::{Writeable, ReadableArgs}; -use crate::util::config::UserConfig; -use bitcoin::hashes::Hash; use bitcoin::hash_types::BlockHash; +use bitcoin::hashes::Hash; use types::payment::{PaymentHash, PaymentPreimage}; use crate::prelude::*; @@ -37,6 +39,7 @@ use crate::prelude::*; use crate::ln::functional_test_utils::*; #[test] +#[rustfmt::skip] fn test_funding_peer_disconnect() { // Test that we can lock in our funding tx while disconnected let chanmon_cfgs = create_chanmon_cfgs(2); @@ -191,6 +194,7 @@ fn test_funding_peer_disconnect() { } #[test] +#[rustfmt::skip] fn test_no_txn_manager_serialize_deserialize() { let chanmon_cfgs = create_chanmon_cfgs(2); let node_cfgs = create_node_cfgs(2, &chanmon_cfgs); @@ -236,6 +240,7 @@ fn test_no_txn_manager_serialize_deserialize() { } #[test] +#[rustfmt::skip] fn test_manager_serialize_deserialize_events() { // This test makes sure the events field in ChannelManager survives de/serialization let chanmon_cfgs = create_chanmon_cfgs(2); @@ -332,6 +337,7 @@ fn test_manager_serialize_deserialize_events() { } #[test] +#[rustfmt::skip] fn test_simple_manager_serialize_deserialize() { let chanmon_cfgs = create_chanmon_cfgs(2); let node_cfgs = create_node_cfgs(2, &chanmon_cfgs); @@ -358,6 +364,7 @@ fn test_simple_manager_serialize_deserialize() { } #[test] +#[rustfmt::skip] fn test_manager_serialize_deserialize_inconsistent_monitor() { // Test deserializing a ChannelManager with an out-of-date ChannelMonitor let chanmon_cfgs = create_chanmon_cfgs(4); @@ -507,6 +514,7 @@ fn test_manager_serialize_deserialize_inconsistent_monitor() { } #[cfg(feature = "std")] +#[rustfmt::skip] fn do_test_data_loss_protect(reconnect_panicing: bool, substantially_old: bool, not_stale: bool) { use crate::ln::channelmanager::Retry; use crate::util::string::UntrustedString; @@ -710,6 +718,7 @@ fn test_data_loss_protect() { } #[test] +#[rustfmt::skip] fn test_forwardable_regen() { // Tests that if we reload a ChannelManager while forwards are pending we will regenerate the // PendingHTLCsForwardable event automatically, ensuring we don't forget to forward/receive @@ -785,6 +794,7 @@ fn test_forwardable_regen() { claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage_2); } +#[rustfmt::skip] fn do_test_partial_claim_before_restart(persist_both_monitors: bool, double_restart: bool) { // Test what happens if a node receives an MPP payment, claims it, but crashes before // persisting the ChannelManager. If `persist_both_monitors` is false, also crash after only @@ -988,6 +998,7 @@ fn test_partial_claim_before_restart() { do_test_partial_claim_before_restart(true, true); } +#[rustfmt::skip] fn do_forwarded_payment_no_manager_persistence(use_cs_commitment: bool, claim_htlc: bool, use_intercept: bool) { if !use_cs_commitment { assert!(!claim_htlc); } // If we go to forward a payment, and the ChannelMonitor persistence completes, but the @@ -1165,6 +1176,7 @@ fn intercepted_payment_no_manager_persistence() { } #[test] +#[rustfmt::skip] fn removed_payment_no_manager_persistence() { // If an HTLC is failed to us on a channel, and the ChannelMonitor persistence completes, but // the corresponding ChannelManager persistence does not, we need to ensure that the HTLC is @@ -1237,6 +1249,7 @@ fn removed_payment_no_manager_persistence() { } #[test] +#[rustfmt::skip] fn test_reload_partial_funding_batch() { let chanmon_cfgs = create_chanmon_cfgs(3); let node_cfgs = create_node_cfgs(3, &chanmon_cfgs); @@ -1300,6 +1313,7 @@ fn test_reload_partial_funding_batch() { } #[test] +#[rustfmt::skip] fn test_htlc_localremoved_persistence() { // Tests that if we fail an htlc back (update_fail_htlc message) and then restart the node, the node will resend the // exact same fail message. diff --git a/lightning/src/ln/reorg_tests.rs b/lightning/src/ln/reorg_tests.rs index 4d01956e60a..b94b31b1b9b 100644 --- a/lightning/src/ln/reorg_tests.rs +++ b/lightning/src/ln/reorg_tests.rs @@ -1,5 +1,3 @@ -#![cfg_attr(rustfmt, rustfmt_skip)] - // This file is Copyright its original authors, visible in version control // history. // @@ -15,21 +13,22 @@ use crate::chain::chaininterface::LowerBoundedFeeEstimator; use crate::chain::channelmonitor::{ANTI_REORG_DELAY, LATENCY_GRACE_PERIOD_BLOCKS}; use crate::chain::transaction::OutPoint; use crate::chain::Confirm; -use crate::events::{Event, ClosureReason, HTLCHandlingFailureType}; +use crate::events::{ClosureReason, Event, HTLCHandlingFailureType}; use crate::ln::msgs::{BaseMessageHandler, ChannelMessageHandler, Init, MessageSendEvent}; use crate::ln::types::ChannelId; use crate::sign::OutputSpender; use crate::util::ser::Writeable; use crate::util::string::UntrustedString; -use bitcoin::script::Builder; use bitcoin::opcodes; +use bitcoin::script::Builder; use bitcoin::secp256k1::Secp256k1; use crate::prelude::*; use crate::ln::functional_test_utils::*; +#[rustfmt::skip] fn do_test_onchain_htlc_reorg(local_commitment: bool, claim: bool) { // Our on-chain HTLC-claim learning has a few properties worth testing: // * If an upstream HTLC is claimed with a preimage (both against our own commitment @@ -171,6 +170,7 @@ fn test_onchain_htlc_timeout_delay_remote_commitment() { } #[test] +#[rustfmt::skip] fn test_counterparty_revoked_reorg() { // Test what happens when a revoked counterparty transaction is broadcast but then reorg'd out // of the main chain. Specifically, HTLCs in the latest commitment transaction which are not @@ -241,6 +241,7 @@ fn test_counterparty_revoked_reorg() { expect_payment_failed!(nodes[1], payment_hash_4, false); } +#[rustfmt::skip] fn do_test_unconf_chan(reload_node: bool, reorg_after_reload: bool, use_funding_unconfirmed: bool, connect_style: ConnectStyle) { // After creating a chan between nodes, we disconnect all blocks previously seen to force a // channel close on nodes[0] side. We also use this to provide very basic testing of logic @@ -434,6 +435,7 @@ fn test_unconf_chan_via_funding_unconfirmed() { } #[test] +#[rustfmt::skip] fn test_set_outpoints_partial_claiming() { // - remote party claim tx, new bump tx // - disconnect remote claiming tx, new bump @@ -529,6 +531,7 @@ fn test_set_outpoints_partial_claiming() { } } +#[rustfmt::skip] fn do_test_to_remote_after_local_detection(style: ConnectStyle) { // In previous code, detection of to_remote outputs in a counterparty commitment transaction // was dependent on whether a local commitment transaction had been seen on-chain previously. @@ -640,6 +643,7 @@ fn test_to_remote_after_local_detection() { } #[test] +#[rustfmt::skip] fn test_htlc_preimage_claim_holder_commitment_after_counterparty_commitment_reorg() { // We detect a counterparty commitment confirm onchain, followed by a reorg and a confirmation // of a holder commitment. Then, if we learn of the preimage for an HTLC in both commitments, @@ -703,6 +707,7 @@ fn test_htlc_preimage_claim_holder_commitment_after_counterparty_commitment_reor } #[test] +#[rustfmt::skip] fn test_htlc_preimage_claim_prev_counterparty_commitment_after_current_counterparty_commitment_reorg() { // We detect a counterparty commitment confirm onchain, followed by a reorg and a // confirmation of the previous (still unrevoked) counterparty commitment. Then, if we learn @@ -780,6 +785,7 @@ fn test_htlc_preimage_claim_prev_counterparty_commitment_after_current_counterpa assert_eq!(htlc_preimage_tx.input[0].witness.second_to_last().unwrap(), &payment_preimage.0[..]); } +#[rustfmt::skip] fn do_test_retries_own_commitment_broadcast_after_reorg(anchors: bool, revoked_counterparty_commitment: bool) { // Tests that a node will retry broadcasting its own commitment after seeing a confirmed // counterparty commitment be reorged out. diff --git a/lightning/src/ln/shutdown_tests.rs b/lightning/src/ln/shutdown_tests.rs index d5c3fe3c387..662743c5a86 100644 --- a/lightning/src/ln/shutdown_tests.rs +++ b/lightning/src/ln/shutdown_tests.rs @@ -1,5 +1,3 @@ -#![cfg_attr(rustfmt, rustfmt_skip)] - // This file is Copyright its original authors, visible in version control // history. // @@ -12,36 +10,37 @@ //! Tests of our shutdown and closing_signed negotiation logic as well as some assorted force-close //! handling tests. -use crate::sign::{EntropySource, SignerProvider}; -use crate::chain::ChannelMonitorUpdateStatus; use crate::chain::transaction::OutPoint; -use crate::events::{Event, HTLCHandlingFailureType, ClosureReason}; +use crate::chain::ChannelMonitorUpdateStatus; +use crate::events::{ClosureReason, Event, HTLCHandlingFailureType}; use crate::ln::channel_state::{ChannelDetails, ChannelShutdownState}; use crate::ln::channelmanager::{self, PaymentId, RecipientOnionFields, Retry}; -use crate::routing::router::{PaymentParameters, get_route, RouteParameters}; use crate::ln::msgs; -use crate::ln::types::ChannelId; use crate::ln::msgs::{BaseMessageHandler, ChannelMessageHandler, ErrorAction, MessageSendEvent}; use crate::ln::onion_utils::LocalHTLCFailureReason; use crate::ln::script::ShutdownScript; -use crate::util::test_utils; -use crate::util::test_utils::OnGetShutdownScriptpubkey; -use crate::util::errors::APIError; +use crate::ln::types::ChannelId; +use crate::prelude::*; +use crate::routing::router::{get_route, PaymentParameters, RouteParameters}; +use crate::sign::{EntropySource, SignerProvider}; use crate::util::config::UserConfig; +use crate::util::errors::APIError; use crate::util::string::UntrustedString; -use crate::prelude::*; +use crate::util::test_utils; +use crate::util::test_utils::OnGetShutdownScriptpubkey; -use bitcoin::{Transaction, TxOut, WitnessProgram, WitnessVersion}; use bitcoin::amount::Amount; use bitcoin::locktime::absolute::LockTime; -use bitcoin::script::Builder; -use bitcoin::opcodes; use bitcoin::network::Network; +use bitcoin::opcodes; +use bitcoin::script::Builder; use bitcoin::transaction::Version; +use bitcoin::{Transaction, TxOut, WitnessProgram, WitnessVersion}; use crate::ln::functional_test_utils::*; #[test] +#[rustfmt::skip] fn pre_funding_lock_shutdown_test() { // Test sending a shutdown prior to channel_ready after funding generation let chanmon_cfgs = create_chanmon_cfgs(2); @@ -74,6 +73,7 @@ fn pre_funding_lock_shutdown_test() { } #[test] +#[rustfmt::skip] fn expect_channel_shutdown_state() { // Test sending a shutdown prior to channel_ready after funding generation let chanmon_cfgs = create_chanmon_cfgs(2); @@ -119,6 +119,7 @@ fn expect_channel_shutdown_state() { } #[test] +#[rustfmt::skip] fn expect_channel_shutdown_state_with_htlc() { // Test sending a shutdown with outstanding updates pending. let chanmon_cfgs = create_chanmon_cfgs(3); @@ -205,6 +206,7 @@ fn expect_channel_shutdown_state_with_htlc() { } #[test] +#[rustfmt::skip] fn test_lnd_bug_6039() { // LND sends a nonsense error message any time it gets a shutdown if there are still HTLCs // pending. We currently swallow that error to work around LND's bug #6039. This test emulates @@ -260,6 +262,7 @@ fn test_lnd_bug_6039() { } #[test] +#[rustfmt::skip] fn shutdown_on_unfunded_channel() { // Test receiving a shutdown prior to funding generation let chanmon_cfgs = create_chanmon_cfgs(2); @@ -282,6 +285,7 @@ fn shutdown_on_unfunded_channel() { } #[test] +#[rustfmt::skip] fn close_on_unfunded_channel() { // Test the user asking us to close prior to funding generation let chanmon_cfgs = create_chanmon_cfgs(2); @@ -297,6 +301,7 @@ fn close_on_unfunded_channel() { } #[test] +#[rustfmt::skip] fn expect_channel_shutdown_state_with_force_closure() { // Test sending a shutdown prior to channel_ready after funding generation let chanmon_cfgs = create_chanmon_cfgs(2); @@ -330,6 +335,7 @@ fn expect_channel_shutdown_state_with_force_closure() { } #[test] +#[rustfmt::skip] fn updates_shutdown_wait() { // Test sending a shutdown with outstanding updates pending let chanmon_cfgs = create_chanmon_cfgs(3); @@ -426,6 +432,7 @@ fn htlc_fail_async_shutdown() { do_htlc_fail_async_shutdown(false); } +#[rustfmt::skip] fn do_htlc_fail_async_shutdown(blinded_recipient: bool) { // Test HTLCs fail if shutdown starts even if messages are delivered out-of-order let chanmon_cfgs = create_chanmon_cfgs(3); @@ -540,6 +547,7 @@ fn do_htlc_fail_async_shutdown(blinded_recipient: bool) { check_closed_event!(nodes[2], 1, ClosureReason::LocallyInitiatedCooperativeClosure, [nodes[1].node.get_our_node_id()], 100000); } +#[rustfmt::skip] fn do_test_shutdown_rebroadcast(recv_count: u8) { // Test that shutdown/closing_signed is re-sent on reconnect with a variable number of // messages delivered prior to disconnect @@ -731,6 +739,7 @@ fn test_shutdown_rebroadcast() { } #[test] +#[rustfmt::skip] fn test_upfront_shutdown_script() { // BOLT 2 : Option upfront shutdown script, if peer commit its closing_script at channel opening // enforce it at shutdown message @@ -824,6 +833,7 @@ fn test_upfront_shutdown_script() { } #[test] +#[rustfmt::skip] fn test_unsupported_anysegwit_upfront_shutdown_script() { let chanmon_cfgs = create_chanmon_cfgs(2); let mut node_cfgs = create_node_cfgs(2, &chanmon_cfgs); @@ -887,6 +897,7 @@ fn test_unsupported_anysegwit_upfront_shutdown_script() { } #[test] +#[rustfmt::skip] fn test_invalid_upfront_shutdown_script() { let chanmon_cfgs = create_chanmon_cfgs(2); let node_cfgs = create_node_cfgs(2, &chanmon_cfgs); @@ -914,6 +925,7 @@ fn test_invalid_upfront_shutdown_script() { } #[test] +#[rustfmt::skip] fn test_segwit_v0_shutdown_script() { let mut config = UserConfig::default(); config.channel_handshake_config.announce_for_forwarding = true; @@ -949,6 +961,7 @@ fn test_segwit_v0_shutdown_script() { } #[test] +#[rustfmt::skip] fn test_anysegwit_shutdown_script() { let mut config = UserConfig::default(); config.channel_handshake_config.announce_for_forwarding = true; @@ -984,6 +997,7 @@ fn test_anysegwit_shutdown_script() { } #[test] +#[rustfmt::skip] fn test_unsupported_anysegwit_shutdown_script() { let mut config = UserConfig::default(); config.channel_handshake_config.announce_for_forwarding = true; @@ -1029,6 +1043,7 @@ fn test_unsupported_anysegwit_shutdown_script() { } #[test] +#[rustfmt::skip] fn test_invalid_shutdown_script() { let mut config = UserConfig::default(); config.channel_handshake_config.announce_for_forwarding = true; @@ -1056,6 +1071,7 @@ fn test_invalid_shutdown_script() { } #[test] +#[rustfmt::skip] fn test_user_shutdown_script() { let mut config = test_default_channel_config(); config.channel_handshake_config.announce_for_forwarding = true; @@ -1084,6 +1100,7 @@ fn test_user_shutdown_script() { } #[test] +#[rustfmt::skip] fn test_already_set_user_shutdown_script() { let mut config = test_default_channel_config(); config.channel_handshake_config.announce_for_forwarding = true; @@ -1114,6 +1131,7 @@ enum TimeoutStep { NoTimeout, } +#[rustfmt::skip] fn do_test_closing_signed_reinit_timeout(timeout_step: TimeoutStep) { // The range-based closing signed negotiation allows the funder to restart the process with a // new range if the previous range did not overlap. This allows implementations to request user @@ -1218,6 +1236,7 @@ fn test_closing_signed_reinit_timeout() { do_test_closing_signed_reinit_timeout(TimeoutStep::NoTimeout); } +#[rustfmt::skip] fn do_simple_legacy_shutdown_test(high_initiator_fee: bool) { // A simpe test of the legacy shutdown fee negotiation logic. let chanmon_cfgs = create_chanmon_cfgs(2); @@ -1266,6 +1285,7 @@ fn simple_legacy_shutdown_test() { } #[test] +#[rustfmt::skip] fn simple_target_feerate_shutdown() { // Simple test of target in `close_channel_with_target_feerate`. let chanmon_cfgs = create_chanmon_cfgs(2); @@ -1314,6 +1334,7 @@ fn simple_target_feerate_shutdown() { check_closed_event!(nodes[1], 1, ClosureReason::LocallyInitiatedCooperativeClosure, [nodes[0].node.get_our_node_id()], 100000); } +#[rustfmt::skip] fn do_outbound_update_no_early_closing_signed(use_htlc: bool) { // Previously, if we have a pending inbound HTLC (or fee update) on a channel which has // initiated shutdown, we'd send our initial closing_signed immediately after receiving the @@ -1414,6 +1435,7 @@ fn outbound_update_no_early_closing_signed() { } #[test] +#[rustfmt::skip] fn batch_funding_failure() { // Provides test coverage of batch funding failure, which previously deadlocked let chanmon_cfgs = create_chanmon_cfgs(4); @@ -1482,6 +1504,7 @@ fn batch_funding_failure() { } #[test] +#[rustfmt::skip] fn test_force_closure_on_low_stale_fee() { // Check that we force-close channels if they have a low fee and that has gotten stale (without // update). diff --git a/lightning/src/routing/mod.rs b/lightning/src/routing/mod.rs index af9e7c17dba..cb16461dd66 100644 --- a/lightning/src/routing/mod.rs +++ b/lightning/src/routing/mod.rs @@ -1,5 +1,3 @@ -#![cfg_attr(rustfmt, rustfmt_skip)] - // This file is Copyright its original authors, visible in version control // history. // @@ -11,10 +9,10 @@ //! Structs and impls for receiving messages about the network and storing the topology live here. -pub mod utxo; pub mod gossip; +mod log_approx; pub mod router; pub mod scoring; -mod log_approx; #[cfg(test)] pub(crate) mod test_utils; +pub mod utxo; diff --git a/lightning/src/routing/router.rs b/lightning/src/routing/router.rs index 1a76e682668..fa5ed912de6 100644 --- a/lightning/src/routing/router.rs +++ b/lightning/src/routing/router.rs @@ -1,5 +1,3 @@ -#![cfg_attr(rustfmt, rustfmt_skip)] - // This file is Copyright its original authors, visible in version control // history. // @@ -11,33 +9,40 @@ //! The router finds paths within a [`NetworkGraph`] for a payment. -use bitcoin::secp256k1::{PublicKey, Secp256k1, self}; +use bitcoin::secp256k1::{self, PublicKey, Secp256k1}; use lightning_invoice::Bolt11Invoice; +use crate::blinded_path::payment::{ + BlindedPaymentPath, ForwardTlvs, PaymentConstraints, PaymentForwardNode, PaymentRelay, + ReceiveTlvs, +}; use crate::blinded_path::{BlindedHop, Direction, IntroductionNode}; -use crate::blinded_path::payment::{BlindedPaymentPath, ForwardTlvs, PaymentConstraints, PaymentForwardNode, PaymentRelay, ReceiveTlvs}; -use crate::types::payment::{PaymentHash, PaymentPreimage}; +use crate::crypto::chacha20::ChaCha20; use crate::ln::channel_state::ChannelDetails; -use crate::ln::channelmanager::{PaymentId, MIN_FINAL_CLTV_EXPIRY_DELTA, RecipientOnionFields}; -use crate::types::features::{BlindedHopFeatures, Bolt11InvoiceFeatures, Bolt12InvoiceFeatures, ChannelFeatures, NodeFeatures}; +use crate::ln::channelmanager::{PaymentId, RecipientOnionFields, MIN_FINAL_CLTV_EXPIRY_DELTA}; use crate::ln::msgs::{DecodeError, MAX_VALUE_MSAT}; use crate::ln::onion_utils; +use crate::offers::invoice::Bolt12Invoice; #[cfg(async_payments)] use crate::offers::static_invoice::StaticInvoice; -use crate::offers::invoice::Bolt12Invoice; -use crate::routing::gossip::{DirectedChannelInfo, EffectiveCapacity, ReadOnlyNetworkGraph, NetworkGraph, NodeId}; +use crate::routing::gossip::{ + DirectedChannelInfo, EffectiveCapacity, NetworkGraph, NodeId, ReadOnlyNetworkGraph, +}; use crate::routing::scoring::{ChannelUsage, LockableScore, ScoreLookUp}; use crate::sign::EntropySource; use crate::sync::Mutex; -use crate::util::ser::{Writeable, Readable, ReadableArgs, Writer}; +use crate::types::features::{ + BlindedHopFeatures, Bolt11InvoiceFeatures, Bolt12InvoiceFeatures, ChannelFeatures, NodeFeatures, +}; +use crate::types::payment::{PaymentHash, PaymentPreimage}; use crate::util::logger::Logger; -use crate::crypto::chacha20::ChaCha20; +use crate::util::ser::{Readable, ReadableArgs, Writeable, Writer}; use crate::io; use crate::prelude::*; use alloc::collections::BinaryHeap; -use core::{cmp, fmt}; use core::ops::Deref; +use core::{cmp, fmt}; use lightning_types::routing::RoutingFees; @@ -51,9 +56,16 @@ pub use lightning_types::routing::{RouteHint, RouteHintHop}; /// it will create a one-hop path using the recipient as the introduction node if it is a announced /// node. Otherwise, there is no way to find a path to the introduction node in order to send a /// payment, and thus an `Err` is returned. -pub struct DefaultRouter>, L: Deref, ES: Deref, S: Deref, SP: Sized, Sc: ScoreLookUp> where +pub struct DefaultRouter< + G: Deref>, + L: Deref, + ES: Deref, + S: Deref, + SP: Sized, + Sc: ScoreLookUp, +> where L::Target: Logger, - S::Target: for <'a> LockableScore<'a, ScoreLookUp = Sc>, + S::Target: for<'a> LockableScore<'a, ScoreLookUp = Sc>, ES::Target: EntropySource, { network_graph: G, @@ -63,22 +75,41 @@ pub struct DefaultRouter>, L: Deref, ES: Deref score_params: SP, } -impl>, L: Deref, ES: Deref, S: Deref, SP: Sized, Sc: ScoreLookUp> DefaultRouter where +impl< + G: Deref>, + L: Deref, + ES: Deref, + S: Deref, + SP: Sized, + Sc: ScoreLookUp, + > DefaultRouter +where L::Target: Logger, - S::Target: for <'a> LockableScore<'a, ScoreLookUp = Sc>, + S::Target: for<'a> LockableScore<'a, ScoreLookUp = Sc>, ES::Target: EntropySource, { /// Creates a new router. - pub fn new(network_graph: G, logger: L, entropy_source: ES, scorer: S, score_params: SP) -> Self { + pub fn new( + network_graph: G, logger: L, entropy_source: ES, scorer: S, score_params: SP, + ) -> Self { Self { network_graph, logger, entropy_source, scorer, score_params } } } -impl>, L: Deref, ES: Deref, S: Deref, SP: Sized, Sc: ScoreLookUp> Router for DefaultRouter where +impl< + G: Deref>, + L: Deref, + ES: Deref, + S: Deref, + SP: Sized, + Sc: ScoreLookUp, + > Router for DefaultRouter +where L::Target: Logger, - S::Target: for <'a> LockableScore<'a, ScoreLookUp = Sc>, + S::Target: for<'a> LockableScore<'a, ScoreLookUp = Sc>, ES::Target: EntropySource, { + #[rustfmt::skip] fn find_route( &self, payer: &PublicKey, @@ -95,6 +126,7 @@ impl>, L: Deref, ES: Deref, S: Deref, SP: Size ) } + #[rustfmt::skip] fn create_blinded_payment_paths< T: secp256k1::Signing + secp256k1::Verification > ( @@ -206,16 +238,14 @@ impl FixedRouter { impl Router for FixedRouter { fn find_route( &self, _payer: &PublicKey, _route_params: &RouteParameters, - _first_hops: Option<&[&ChannelDetails]>, _inflight_htlcs: InFlightHtlcs + _first_hops: Option<&[&ChannelDetails]>, _inflight_htlcs: InFlightHtlcs, ) -> Result { self.route.lock().unwrap().take().ok_or("Can't use this router to return multiple routes") } - fn create_blinded_payment_paths< - T: secp256k1::Signing + secp256k1::Verification - > ( + fn create_blinded_payment_paths( &self, _recipient: PublicKey, _first_hops: Vec, _tlvs: ReceiveTlvs, - _amount_msats: Option, _secp_ctx: &Secp256k1 + _amount_msats: Option, _secp_ctx: &Secp256k1, ) -> Result, ()> { // Should be unreachable as this router is only intended to provide a one-time payment route. debug_assert!(false); @@ -229,6 +259,7 @@ pub trait Router { /// /// The `payee` and the payment's value are given in [`RouteParameters::payment_params`] /// and [`RouteParameters::final_value_msat`], respectively. + #[rustfmt::skip] fn find_route( &self, payer: &PublicKey, route_params: &RouteParameters, first_hops: Option<&[&ChannelDetails]>, inflight_htlcs: InFlightHtlcs @@ -244,7 +275,7 @@ pub trait Router { fn find_route_with_id( &self, payer: &PublicKey, route_params: &RouteParameters, first_hops: Option<&[&ChannelDetails]>, inflight_htlcs: InFlightHtlcs, - _payment_hash: PaymentHash, _payment_id: PaymentId + _payment_hash: PaymentHash, _payment_id: PaymentId, ) -> Result { self.find_route(payer, route_params, first_hops, inflight_htlcs) } @@ -252,11 +283,9 @@ pub trait Router { /// Creates [`BlindedPaymentPath`]s for payment to the `recipient` node. The channels in `first_hops` /// are assumed to be with the `recipient`'s peers. The payment secret and any constraints are /// given in `tlvs`. - fn create_blinded_payment_paths< - T: secp256k1::Signing + secp256k1::Verification - > ( + fn create_blinded_payment_paths( &self, recipient: PublicKey, first_hops: Vec, tlvs: ReceiveTlvs, - amount_msats: Option, secp_ctx: &Secp256k1 + amount_msats: Option, secp_ctx: &Secp256k1, ) -> Result, ()>; } @@ -266,13 +295,20 @@ pub trait Router { /// [`find_route`]. /// /// [`ScoreLookUp`]: crate::routing::scoring::ScoreLookUp -pub struct ScorerAccountingForInFlightHtlcs<'a, S: Deref> where S::Target: ScoreLookUp { +pub struct ScorerAccountingForInFlightHtlcs<'a, S: Deref> +where + S::Target: ScoreLookUp, +{ scorer: S, // Maps a channel's short channel id and its direction to the liquidity used up. inflight_htlcs: &'a InFlightHtlcs, } -impl<'a, S: Deref> ScorerAccountingForInFlightHtlcs<'a, S> where S::Target: ScoreLookUp { +impl<'a, S: Deref> ScorerAccountingForInFlightHtlcs<'a, S> +where + S::Target: ScoreLookUp, +{ /// Initialize a new `ScorerAccountingForInFlightHtlcs`. + #[rustfmt::skip] pub fn new(scorer: S, inflight_htlcs: &'a InFlightHtlcs) -> Self { ScorerAccountingForInFlightHtlcs { scorer, @@ -281,8 +317,12 @@ impl<'a, S: Deref> ScorerAccountingForInFlightHtlcs<'a, S> where S::Target: Scor } } -impl<'a, S: Deref> ScoreLookUp for ScorerAccountingForInFlightHtlcs<'a, S> where S::Target: ScoreLookUp { +impl<'a, S: Deref> ScoreLookUp for ScorerAccountingForInFlightHtlcs<'a, S> +where + S::Target: ScoreLookUp, +{ type ScoreParams = ::ScoreParams; + #[rustfmt::skip] fn channel_penalty_msat(&self, candidate: &CandidateRouteHop, usage: ChannelUsage, score_params: &Self::ScoreParams) -> u64 { let target = match candidate.target() { Some(target) => target, @@ -316,14 +356,16 @@ pub struct InFlightHtlcs( // is traveling in. The direction boolean is determined by checking if the HTLC source's public // key is less than its destination. See `InFlightHtlcs::used_liquidity_msat` for more // details. - HashMap<(u64, bool), u64> + HashMap<(u64, bool), u64>, ); impl InFlightHtlcs { /// Constructs an empty `InFlightHtlcs`. + #[rustfmt::skip] pub fn new() -> Self { InFlightHtlcs(new_hash_map()) } /// Takes in a path with payer's node id and adds the path's details to `InFlightHtlcs`. + #[rustfmt::skip] pub fn process_path(&mut self, path: &Path, payer_node_id: PublicKey) { if path.hops.is_empty() { return }; @@ -355,7 +397,9 @@ impl InFlightHtlcs { /// Adds a known HTLC given the public key of the HTLC source, target, and short channel /// id. - pub fn add_inflight_htlc(&mut self, source: &NodeId, target: &NodeId, channel_scid: u64, used_msat: u64){ + pub fn add_inflight_htlc( + &mut self, source: &NodeId, target: &NodeId, channel_scid: u64, used_msat: u64, + ) { self.0 .entry((channel_scid, source < target)) .and_modify(|used_liquidity_msat| *used_liquidity_msat += used_msat) @@ -364,12 +408,15 @@ impl InFlightHtlcs { /// Returns liquidity in msat given the public key of the HTLC source, target, and short channel /// id. - pub fn used_liquidity_msat(&self, source: &NodeId, target: &NodeId, channel_scid: u64) -> Option { + pub fn used_liquidity_msat( + &self, source: &NodeId, target: &NodeId, channel_scid: u64, + ) -> Option { self.0.get(&(channel_scid, source < target)).map(|v| *v) } } impl Writeable for InFlightHtlcs { + #[rustfmt::skip] fn write(&self, writer: &mut W) -> Result<(), io::Error> { self.0.write(writer) } } @@ -495,6 +542,7 @@ pub struct Path { impl Path { /// Gets the fees for a given path, excluding any excess paid to the recipient. + #[rustfmt::skip] pub fn fee_msat(&self) -> u64 { match &self.blinded_tail { Some(_) => self.hops.iter().map(|hop| hop.fee_msat).sum::(), @@ -507,6 +555,7 @@ impl Path { } /// Gets the total amount paid on this [`Path`], excluding the fees. + #[rustfmt::skip] pub fn final_value_msat(&self) -> u64 { match &self.blinded_tail { Some(blinded_tail) => blinded_tail.final_value_msat, @@ -515,6 +564,7 @@ impl Path { } /// Gets the final hop's CLTV expiry delta. + #[rustfmt::skip] pub fn final_cltv_expiry_delta(&self) -> Option { match &self.blinded_tail { Some(_) => None, @@ -552,6 +602,7 @@ impl Route { /// [`RouteParameters::final_value_msat`], if we had to reach the [`htlc_minimum_msat`] limits. /// /// [`htlc_minimum_msat`]: https://github.com/lightning/bolts/blob/master/07-routing-gossip.md#the-channel_update-message + #[rustfmt::skip] pub fn get_total_fees(&self) -> u64 { let overpaid_value_msat = self.route_params.as_ref() .map_or(0, |p| self.get_total_amount().saturating_sub(p.final_value_msat)); @@ -579,6 +630,7 @@ const SERIALIZATION_VERSION: u8 = 1; const MIN_SERIALIZATION_VERSION: u8 = 1; impl Writeable for Route { + #[rustfmt::skip] fn write(&self, writer: &mut W) -> Result<(), io::Error> { write_ver_prefix!(writer, SERIALIZATION_VERSION, MIN_SERIALIZATION_VERSION); (self.paths.len() as u64).write(writer)?; @@ -611,6 +663,7 @@ impl Writeable for Route { } impl Readable for Route { + #[rustfmt::skip] fn read(reader: &mut R) -> Result { let _ver = read_ver_prefix!(reader, SERIALIZATION_VERSION); let path_count: u64 = Readable::read(reader)?; @@ -678,12 +731,14 @@ impl RouteParameters { /// Constructs [`RouteParameters`] from the given [`PaymentParameters`] and a payment amount. /// /// [`Self::max_total_routing_fee_msat`] defaults to 1% of the payment amount + 50 sats + #[rustfmt::skip] pub fn from_payment_params_and_value(payment_params: PaymentParameters, final_value_msat: u64) -> Self { Self { payment_params, final_value_msat, max_total_routing_fee_msat: Some(final_value_msat / 100 + 50_000) } } /// Sets the maximum number of hops that can be included in a payment path, based on the provided /// [`RecipientOnionFields`] and blinded paths. + #[rustfmt::skip] pub fn set_max_path_length( &mut self, recipient_onion: &RecipientOnionFields, is_keysend: bool, best_block_height: u32 ) -> Result<(), ()> { @@ -807,6 +862,7 @@ pub struct PaymentParameters { } impl Writeable for PaymentParameters { + #[rustfmt::skip] fn write(&self, writer: &mut W) -> Result<(), io::Error> { let mut clear_hints = &vec![]; let mut blinded_hints = None; @@ -836,6 +892,7 @@ impl Writeable for PaymentParameters { } impl ReadableArgs for PaymentParameters { + #[rustfmt::skip] fn read(reader: &mut R, default_final_cltv_expiry_delta: u32) -> Result { _init_and_read_len_prefixed_tlv_fields!(reader, { (0, payee_pubkey, option), @@ -882,12 +939,12 @@ impl ReadableArgs for PaymentParameters { } } - impl PaymentParameters { /// Creates a payee with the node id of the given `pubkey`. /// /// The `final_cltv_expiry_delta` should match the expected final CLTV delta the recipient has /// provided. + #[rustfmt::skip] pub fn from_node_id(payee_pubkey: PublicKey, final_cltv_expiry_delta: u32) -> Self { Self { payee: Payee::Clear { node_id: payee_pubkey, route_hints: vec![], features: None, final_cltv_expiry_delta }, @@ -912,6 +969,7 @@ impl PaymentParameters { /// [`RecipientOnionFields::secret_only`]. /// /// [`RecipientOnionFields::secret_only`]: crate::ln::channelmanager::RecipientOnionFields::secret_only + #[rustfmt::skip] pub fn for_keysend(payee_pubkey: PublicKey, final_cltv_expiry_delta: u32, allow_mpp: bool) -> Self { Self::from_node_id(payee_pubkey, final_cltv_expiry_delta) .with_bolt11_features(Bolt11InvoiceFeatures::for_keysend(allow_mpp)) @@ -942,6 +1000,7 @@ impl PaymentParameters { /// Creates parameters for paying to a blinded payee from the provided invoice. Sets /// [`Payee::Blinded::route_hints`], [`Payee::Blinded::features`], and /// [`PaymentParameters::expiry_time`]. + #[rustfmt::skip] pub fn from_bolt12_invoice(invoice: &Bolt12Invoice) -> Self { Self::blinded(invoice.payment_paths().to_vec()) .with_bolt12_features(invoice.invoice_features().clone()).unwrap() @@ -952,6 +1011,7 @@ impl PaymentParameters { /// [`Payee::Blinded::route_hints`], [`Payee::Blinded::features`], and /// [`PaymentParameters::expiry_time`]. #[cfg(async_payments)] + #[rustfmt::skip] pub fn from_static_invoice(invoice: &StaticInvoice) -> Self { Self::blinded(invoice.payment_paths().to_vec()) .with_bolt12_features(invoice.invoice_features().clone()).unwrap() @@ -978,6 +1038,7 @@ impl PaymentParameters { /// We *do not* apply `max_total_routing_fee_msat` here, as it is unique to each route. /// Instead, we apply only the parameters that are common across multiple route-finding sessions /// for a payment across retries. + #[rustfmt::skip] pub(crate) fn with_user_config_ignoring_fee_limit(self, params_config: RouteParametersConfig) -> Self { Self { max_total_cltv_expiry_delta: params_config.max_total_cltv_expiry_delta, @@ -991,6 +1052,7 @@ impl PaymentParameters { /// [`PaymentParameters::from_bolt12_invoice`]. /// /// This is not exported to bindings users since bindings don't support move semantics + #[rustfmt::skip] pub fn with_bolt12_features(self, features: Bolt12InvoiceFeatures) -> Result { match self.payee { Payee::Clear { .. } => Err(()), @@ -1003,6 +1065,7 @@ impl PaymentParameters { /// [`PaymentParameters::from_bolt12_invoice`]. /// /// This is not exported to bindings users since bindings don't support move semantics + #[rustfmt::skip] pub fn with_bolt11_features(self, features: Bolt11InvoiceFeatures) -> Result { match self.payee { Payee::Blinded { .. } => Err(()), @@ -1019,6 +1082,7 @@ impl PaymentParameters { /// [`PaymentParameters::from_bolt12_invoice`]. /// /// This is not exported to bindings users since bindings don't support move semantics + #[rustfmt::skip] pub fn with_route_hints(self, route_hints: Vec) -> Result { match self.payee { Payee::Blinded { .. } => Err(()), @@ -1056,10 +1120,13 @@ impl PaymentParameters { /// a power of 1/2. See [`PaymentParameters::max_channel_saturation_power_of_half`]. /// /// This is not exported to bindings users since bindings don't support move semantics - pub fn with_max_channel_saturation_power_of_half(self, max_channel_saturation_power_of_half: u8) -> Self { + pub fn with_max_channel_saturation_power_of_half( + self, max_channel_saturation_power_of_half: u8, + ) -> Self { Self { max_channel_saturation_power_of_half, ..self } } + #[rustfmt::skip] pub(crate) fn insert_previously_failed_blinded_path(&mut self, failed_blinded_tail: &BlindedTail) { let mut found_blinded_tail = false; for (idx, path) in self.payee.blinded_route_hints().iter().enumerate() { @@ -1144,7 +1211,9 @@ impl RouteParametersConfig { /// a power of 1/2. See [`PaymentParameters::max_channel_saturation_power_of_half`]. /// /// This is not exported to bindings users since bindings don't support move semantics - pub fn with_max_channel_saturation_power_of_half(self, max_channel_saturation_power_of_half: u8) -> Self { + pub fn with_max_channel_saturation_power_of_half( + self, max_channel_saturation_power_of_half: u8, + ) -> Self { Self { max_channel_saturation_power_of_half, ..self } } } @@ -1208,6 +1277,7 @@ impl Payee { Self::Blinded { features, .. } => features.as_ref().map(|f| f.to_context()), } } + #[rustfmt::skip] fn supports_basic_mpp(&self) -> bool { match self { Self::Clear { features, .. } => features.as_ref().map_or(false, |f| f.supports_basic_mpp()), @@ -1226,6 +1296,7 @@ impl Payee { _ => None, } } + #[rustfmt::skip] pub(crate) fn blinded_route_hints(&self) -> &[BlindedPaymentPath] { match self { Self::Blinded { route_hints, .. } => &route_hints[..], @@ -1233,6 +1304,7 @@ impl Payee { } } + #[rustfmt::skip] pub(crate) fn blinded_route_hints_mut(&mut self) -> &mut [BlindedPaymentPath] { match self { Self::Blinded { route_hints, .. } => &mut route_hints[..], @@ -1240,6 +1312,7 @@ impl Payee { } } + #[rustfmt::skip] fn unblinded_route_hints(&self) -> &[RouteHint] { match self { Self::Blinded { .. } => &[], @@ -1282,6 +1355,7 @@ impl<'a> Writeable for FeaturesRef<'a> { } impl ReadableArgs for Features { + #[rustfmt::skip] fn read(reader: &mut R, bolt11: bool) -> Result { if bolt11 { return Ok(Self::Bolt11(Readable::read(reader)?)) } Ok(Self::Bolt12(Readable::read(reader)?)) @@ -1336,6 +1410,7 @@ struct RouteGraphNode { } impl cmp::Ord for RouteGraphNode { + #[rustfmt::skip] fn cmp(&self, other: &RouteGraphNode) -> cmp::Ordering { other.score.cmp(&self.score) .then_with(|| self.value_contribution_msat.cmp(&other.value_contribution_msat)) @@ -1558,6 +1633,7 @@ impl<'a> CandidateRouteHop<'a> { /// from the public network graph), and thus the short channel ID we have for this channel is /// globally unique and identifies this channel in a global namespace. #[inline] + #[rustfmt::skip] pub fn globally_unique_short_channel_id(&self) -> Option { match self { CandidateRouteHop::FirstHop(hop) => if hop.details.is_announced { hop.details.short_channel_id } else { None }, @@ -1631,6 +1707,7 @@ impl<'a> CandidateRouteHop<'a> { /// Returns the fees that must be paid to route an HTLC over this channel. #[inline] + #[rustfmt::skip] pub fn fees(&self) -> RoutingFees { match self { CandidateRouteHop::FirstHop(_) => RoutingFees { @@ -1653,6 +1730,7 @@ impl<'a> CandidateRouteHop<'a> { /// /// Note that this may be somewhat expensive, so calls to this should be limited and results /// cached! + #[rustfmt::skip] fn effective_capacity(&self) -> EffectiveCapacity { match self { CandidateRouteHop::FirstHop(hop) => EffectiveCapacity::ExactLiquidity { @@ -1673,6 +1751,7 @@ impl<'a> CandidateRouteHop<'a> { /// /// See the docs on [`CandidateHopId`] for when this is, or is not, unique. #[inline] + #[rustfmt::skip] fn id(&self) -> CandidateHopId { match self { CandidateRouteHop::Blinded(hop) => CandidateHopId::Blinded(hop.hint_idx), @@ -1680,6 +1759,7 @@ impl<'a> CandidateRouteHop<'a> { _ => CandidateHopId::Clear((self.short_channel_id().unwrap(), self.source() < self.target().unwrap())), } } + #[rustfmt::skip] fn blinded_path(&self) -> Option<&'a BlindedPaymentPath> { match self { CandidateRouteHop::Blinded(BlindedPathCandidate { hint, .. }) | CandidateRouteHop::OneHopBlinded(OneHopBlindedPathCandidate { hint, .. }) => { @@ -1688,6 +1768,7 @@ impl<'a> CandidateRouteHop<'a> { _ => None, } } + #[rustfmt::skip] fn blinded_hint_idx(&self) -> Option { match self { Self::Blinded(BlindedPathCandidate { hint_idx, .. }) | @@ -1793,6 +1874,7 @@ impl<'a> NodeCountersBuilder<'a> { counter } + #[rustfmt::skip] fn select_node_counter_for_id(&mut self, node_id: NodeId) -> u32 { // For any node_id, we first have to check if its in the existing network graph, and then // ensure that we always look up in our internal map first. @@ -1805,10 +1887,12 @@ impl<'a> NodeCountersBuilder<'a> { }) } + #[rustfmt::skip] fn build(self) -> NodeCounters<'a> { self.0 } } impl<'a> NodeCounters<'a> { + #[rustfmt::skip] fn max_counter(&self) -> u32 { self.network_graph.max_node_counter() + self.private_node_id_to_node_counter.len() as u32 @@ -1818,6 +1902,7 @@ impl<'a> NodeCounters<'a> { self.private_hop_key_cache.get(pubkey) } + #[rustfmt::skip] fn node_counter_from_id(&self, node_id: &NodeId) -> Option<(&NodeId, u32)> { self.private_node_id_to_node_counter.get_key_value(node_id).map(|(a, b)| (a, *b)) .or_else(|| { @@ -1829,6 +1914,7 @@ impl<'a> NodeCounters<'a> { /// Calculates the introduction point for each blinded path in the given [`PaymentParameters`], if /// they can be found. +#[rustfmt::skip] fn calculate_blinded_path_intro_points<'a, L: Deref>( payment_params: &PaymentParameters, node_counters: &'a NodeCounters, network_graph: &ReadOnlyNetworkGraph, logger: &L, our_node_id: NodeId, @@ -1898,6 +1984,7 @@ where L::Target: Logger { } #[inline] +#[rustfmt::skip] fn max_htlc_from_capacity(capacity: EffectiveCapacity, max_channel_saturation_power_of_half: u8) -> u64 { let saturation_shift: u32 = max_channel_saturation_power_of_half as u32; match capacity { @@ -1914,6 +2001,7 @@ fn max_htlc_from_capacity(capacity: EffectiveCapacity, max_channel_saturation_po } } +#[rustfmt::skip] fn iter_equal(mut iter_a: I1, mut iter_b: I2) -> bool where I1::Item: PartialEq { loop { @@ -1980,9 +2068,11 @@ struct PathBuildingHop<'a> { } const _NODE_MAP_SIZE_TWO_CACHE_LINES: usize = 128 - core::mem::size_of::>(); -const _NODE_MAP_SIZE_EXACTLY_TWO_CACHE_LINES: usize = core::mem::size_of::>() - 128; +const _NODE_MAP_SIZE_EXACTLY_TWO_CACHE_LINES: usize = + core::mem::size_of::>() - 128; impl<'a> core::fmt::Debug for PathBuildingHop<'a> { + #[rustfmt::skip] fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> { let mut debug_struct = f.debug_struct("PathBuildingHop"); debug_struct @@ -2052,6 +2142,7 @@ impl<'a> PaymentPath<'a> { // // Returns the amount that this path contributes to the total payment value, which may be greater // than `value_msat` if we had to overpay to meet the final node's `htlc_minimum_msat`. + #[rustfmt::skip] fn update_value_and_recompute_fees(&mut self, value_msat: u64) -> u64 { let mut extra_contribution_msat = 0; let mut total_fee_paid_msat = 0 as u64; @@ -2128,6 +2219,7 @@ impl<'a> PaymentPath<'a> { /// contribution this path can make to the final value of the payment. /// May be slightly lower than the actual max due to rounding errors when aggregating fees /// along the path. + #[rustfmt::skip] fn max_final_value_msat( &self, used_liquidities: &HashMap, channel_saturation_pow_half: u8 ) -> (usize, u64) { @@ -2169,6 +2261,7 @@ impl<'a> PaymentPath<'a> { #[inline(always)] /// Calculate the fees required to route the given amount over a channel with the given fees. +#[rustfmt::skip] fn compute_fees(amount_msat: u64, channel_fees: RoutingFees) -> Option { amount_msat.checked_mul(channel_fees.proportional_millionths as u64) .and_then(|part| (channel_fees.base_msat as u64).checked_add(part / 1_000_000)) @@ -2177,6 +2270,7 @@ fn compute_fees(amount_msat: u64, channel_fees: RoutingFees) -> Option { #[inline(always)] /// Calculate the fees required to route the given amount over a channel with the given fees, /// saturating to [`u64::max_value`]. +#[rustfmt::skip] fn compute_fees_saturating(amount_msat: u64, channel_fees: RoutingFees) -> u64 { amount_msat.checked_mul(channel_fees.proportional_millionths as u64) .map(|prop| prop / 1_000_000).unwrap_or(u64::max_value()) @@ -2196,6 +2290,7 @@ fn default_node_features() -> NodeFeatures { struct LoggedPayeePubkey(Option); impl fmt::Display for LoggedPayeePubkey { + #[rustfmt::skip] fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self.0 { Some(pk) => { @@ -2211,6 +2306,7 @@ impl fmt::Display for LoggedPayeePubkey { struct LoggedCandidateHop<'a>(&'a CandidateRouteHop<'a>); impl<'a> fmt::Display for LoggedCandidateHop<'a> { + #[rustfmt::skip] fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self.0 { CandidateRouteHop::Blinded(BlindedPathCandidate { hint, .. }) | CandidateRouteHop::OneHopBlinded(OneHopBlindedPathCandidate { hint, .. }) => { @@ -2248,6 +2344,7 @@ impl<'a> fmt::Display for LoggedCandidateHop<'a> { } #[inline] +#[rustfmt::skip] fn sort_first_hop_channels( channels: &mut Vec<&ChannelDetails>, used_liquidities: &HashMap, recommended_value_msat: u64, our_node_pubkey: &PublicKey @@ -2307,6 +2404,7 @@ fn sort_first_hop_channels( /// [`ChannelManager::list_usable_channels`]: crate::ln::channelmanager::ChannelManager::list_usable_channels /// [`Event::PaymentPathFailed`]: crate::events::Event::PaymentPathFailed /// [`NetworkGraph`]: crate::routing::gossip::NetworkGraph +#[rustfmt::skip] pub fn find_route( our_node_pubkey: &PublicKey, route_params: &RouteParameters, network_graph: &NetworkGraph, first_hops: Option<&[&ChannelDetails]>, logger: L, @@ -2320,6 +2418,7 @@ where L::Target: Logger, GL::Target: Logger { Ok(route) } +#[rustfmt::skip] pub(crate) fn get_route( our_node_pubkey: &PublicKey, route_params: &RouteParameters, network_graph: &ReadOnlyNetworkGraph, first_hops: Option<&[&ChannelDetails]>, logger: L, scorer: &S, score_params: &S::ScoreParams, @@ -2981,6 +3080,7 @@ where L::Target: Logger { // $fee_to_target_msat represents how much it costs to reach to this node from the payee, // meaning how much will be paid in fees after this node (to the best of our knowledge). // This data can later be helpful to optimize routing (pay lower fees). + #[rustfmt::skip] macro_rules! add_entries_to_cheapest_to_target_node { ( $node: expr, $node_counter: expr, $node_id: expr, $next_hops_value_contribution: expr, $next_hops_cltv_delta: expr, $next_hops_path_length: expr ) => { @@ -3593,6 +3693,7 @@ where L::Target: Logger { // destination, if the remaining CLTV expiry delta exactly matches a feasible path in the network // graph. In order to improve privacy, this method obfuscates the CLTV expiry deltas along the // payment path by adding a randomized 'shadow route' offset to the final hop. +#[rustfmt::skip] fn add_random_cltv_offset(route: &mut Route, payment_params: &PaymentParameters, network_graph: &ReadOnlyNetworkGraph, random_seed_bytes: &[u8; 32] ) { @@ -3683,6 +3784,7 @@ fn add_random_cltv_offset(route: &mut Route, payment_params: &PaymentParameters, /// exclude the payer, but include the payee). This may be useful, e.g., for probing the chosen path. /// /// Re-uses logic from `find_route`, so the restrictions described there also apply here. +#[rustfmt::skip] pub fn build_route_from_hops( our_node_pubkey: &PublicKey, hops: &[PublicKey], route_params: &RouteParameters, network_graph: &NetworkGraph, logger: L, random_seed_bytes: &[u8; 32] @@ -3695,6 +3797,7 @@ where L::Target: Logger, GL::Target: Logger { Ok(route) } +#[rustfmt::skip] fn build_route_from_hops_internal( our_node_pubkey: &PublicKey, hops: &[PublicKey], route_params: &RouteParameters, network_graph: &ReadOnlyNetworkGraph, logger: L, random_seed_bytes: &[u8; 32], @@ -3727,6 +3830,7 @@ fn build_route_from_hops_internal( impl<'a> Writeable for HopScorer { #[inline] + #[rustfmt::skip] fn write(&self, _w: &mut W) -> Result<(), io::Error> { unreachable!(); } @@ -3749,43 +3853,53 @@ fn build_route_from_hops_internal( #[cfg(test)] mod tests { - use crate::blinded_path::BlindedHop; use crate::blinded_path::payment::{BlindedPayInfo, BlindedPaymentPath}; - use crate::routing::gossip::{NetworkGraph, P2PGossipSync, NodeId, EffectiveCapacity}; - use crate::routing::utxo::UtxoResult; - use crate::routing::router::{get_route, build_route_from_hops_internal, add_random_cltv_offset, default_node_features, - BlindedTail, InFlightHtlcs, Path, PaymentParameters, Route, RouteHint, RouteHintHop, RouteHop, RoutingFees, - DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA, MAX_PATH_LENGTH_ESTIMATE, RouteParameters, CandidateRouteHop, PublicHopCandidate}; - use crate::routing::scoring::{ChannelUsage, FixedPenaltyScorer, ScoreLookUp, ProbabilisticScorer, ProbabilisticScoringFeeParameters, ProbabilisticScoringDecayParameters}; - use crate::routing::test_utils::{add_channel, add_or_update_node, build_graph, build_line_graph, id_to_feature_flags, get_nodes, update_channel}; + use crate::blinded_path::BlindedHop; use crate::chain::transaction::OutPoint; + use crate::crypto::chacha20::ChaCha20; use crate::ln::channel_state::{ChannelCounterparty, ChannelDetails, ChannelShutdownState}; + use crate::ln::channelmanager; + use crate::ln::msgs::{UnsignedChannelUpdate, MAX_VALUE_MSAT}; use crate::ln::types::ChannelId; + use crate::routing::gossip::{EffectiveCapacity, NetworkGraph, NodeId, P2PGossipSync}; + use crate::routing::router::{ + add_random_cltv_offset, build_route_from_hops_internal, default_node_features, get_route, + BlindedTail, CandidateRouteHop, InFlightHtlcs, Path, PaymentParameters, PublicHopCandidate, + Route, RouteHint, RouteHintHop, RouteHop, RouteParameters, RoutingFees, + DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA, MAX_PATH_LENGTH_ESTIMATE, + }; + use crate::routing::scoring::{ + ChannelUsage, FixedPenaltyScorer, ProbabilisticScorer, ProbabilisticScoringDecayParameters, + ProbabilisticScoringFeeParameters, ScoreLookUp, + }; + use crate::routing::test_utils::{ + add_channel, add_or_update_node, build_graph, build_line_graph, get_nodes, + id_to_feature_flags, update_channel, + }; + use crate::routing::utxo::UtxoResult; use crate::types::features::{BlindedHopFeatures, ChannelFeatures, InitFeatures, NodeFeatures}; - use crate::ln::msgs::{UnsignedChannelUpdate, MAX_VALUE_MSAT}; - use crate::ln::channelmanager; use crate::util::config::UserConfig; - use crate::util::test_utils as ln_test_utils; - use crate::crypto::chacha20::ChaCha20; - use crate::util::ser::{FixedLengthReader, Readable, ReadableArgs, Writeable}; #[cfg(c_bindings)] use crate::util::ser::Writer; + use crate::util::ser::{FixedLengthReader, Readable, ReadableArgs, Writeable}; + use crate::util::test_utils as ln_test_utils; use bitcoin::amount::Amount; + use bitcoin::constants::ChainHash; use bitcoin::hashes::Hash; + use bitcoin::hex::FromHex; use bitcoin::network::Network; - use bitcoin::constants::ChainHash; - use bitcoin::script::Builder; use bitcoin::opcodes; - use bitcoin::transaction::TxOut; - use bitcoin::hex::FromHex; - use bitcoin::secp256k1::{PublicKey,SecretKey}; + use bitcoin::script::Builder; use bitcoin::secp256k1::Secp256k1; + use bitcoin::secp256k1::{PublicKey, SecretKey}; + use bitcoin::transaction::TxOut; use crate::io::Cursor; use crate::prelude::*; use crate::sync::Arc; + #[rustfmt::skip] fn get_channel_details(short_channel_id: Option, node_id: PublicKey, features: InitFeatures, outbound_capacity_msat: u64) -> ChannelDetails { #[allow(deprecated)] // TODO: Remove once balance_msat is removed. @@ -3826,6 +3940,7 @@ mod tests { } } + #[rustfmt::skip] fn dummy_blinded_path(intro_node: PublicKey, payinfo: BlindedPayInfo) -> BlindedPaymentPath { BlindedPaymentPath::from_blinded_path_and_payinfo( intro_node, ln_test_utils::pubkey(42), @@ -3837,6 +3952,7 @@ mod tests { ) } + #[rustfmt::skip] fn dummy_one_hop_blinded_path(intro_node: PublicKey, payinfo: BlindedPayInfo) -> BlindedPaymentPath { BlindedPaymentPath::from_blinded_path_and_payinfo( intro_node, ln_test_utils::pubkey(42), @@ -3848,6 +3964,7 @@ mod tests { } #[test] + #[rustfmt::skip] fn simple_route_test() { let (secp_ctx, network_graph, _, _, logger) = build_graph(); let (_, our_id, _, nodes) = get_nodes(&secp_ctx); @@ -3891,6 +4008,7 @@ mod tests { } #[test] + #[rustfmt::skip] fn invalid_first_hop_test() { let (secp_ctx, network_graph, _, _, logger) = build_graph(); let (_, our_id, _, nodes) = get_nodes(&secp_ctx); @@ -3915,6 +4033,7 @@ mod tests { } #[test] + #[rustfmt::skip] fn htlc_minimum_test() { let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph(); let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx); @@ -4054,6 +4173,7 @@ mod tests { } #[test] + #[rustfmt::skip] fn htlc_minimum_overpay_test() { let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph(); let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx); @@ -4209,6 +4329,7 @@ mod tests { } #[test] + #[rustfmt::skip] fn htlc_minimum_recipient_overpay_test() { let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph(); let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx); @@ -4271,6 +4392,7 @@ mod tests { } #[test] + #[rustfmt::skip] fn disable_channels_test() { let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph(); let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx); @@ -4339,6 +4461,7 @@ mod tests { } #[test] + #[rustfmt::skip] fn disable_node_test() { let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph(); let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx); @@ -4389,6 +4512,7 @@ mod tests { } #[test] + #[rustfmt::skip] fn our_chans_test() { let (secp_ctx, network_graph, _, _, logger) = build_graph(); let (_, our_id, _, nodes) = get_nodes(&secp_ctx); @@ -4448,6 +4572,7 @@ mod tests { assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13)); } + #[rustfmt::skip] fn last_hops(nodes: &Vec) -> Vec { let zero_fees = RoutingFees { base_msat: 0, @@ -4481,6 +4606,7 @@ mod tests { }])] } + #[rustfmt::skip] fn last_hops_multi_private_channels(nodes: &Vec) -> Vec { let zero_fees = RoutingFees { base_msat: 0, @@ -4525,6 +4651,7 @@ mod tests { } #[test] + #[rustfmt::skip] fn partial_route_hint_test() { let (secp_ctx, network_graph, _, _, logger) = build_graph(); let (_, our_id, _, nodes) = get_nodes(&secp_ctx); @@ -4607,6 +4734,7 @@ mod tests { assert_eq!(route.paths[0].hops[4].channel_features.le_flags(), &Vec::::new()); // We can't learn any flags from invoices, sadly } + #[rustfmt::skip] fn empty_last_hop(nodes: &Vec) -> Vec { let zero_fees = RoutingFees { base_msat: 0, @@ -4632,6 +4760,7 @@ mod tests { } #[test] + #[rustfmt::skip] fn ignores_empty_last_hops_test() { let (secp_ctx, network_graph, _, _, logger) = build_graph(); let (_, our_id, _, nodes) = get_nodes(&secp_ctx); @@ -4685,6 +4814,7 @@ mod tests { /// Builds a trivial last-hop hint that passes through the two nodes given, with channel 0xff00 /// and 0xff01. + #[rustfmt::skip] fn multi_hop_last_hops_hint(hint_hops: [PublicKey; 2]) -> Vec { let zero_fees = RoutingFees { base_msat: 0, @@ -4711,6 +4841,7 @@ mod tests { } #[test] + #[rustfmt::skip] fn multi_hint_last_hops_test() { let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph(); let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx); @@ -4790,6 +4921,7 @@ mod tests { } #[test] + #[rustfmt::skip] fn private_multi_hint_last_hops_test() { let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph(); let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx); @@ -4865,6 +4997,7 @@ mod tests { assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &Vec::::new()); // We can't learn any flags from invoices, sadly } + #[rustfmt::skip] fn last_hops_with_public_channel(nodes: &Vec) -> Vec { let zero_fees = RoutingFees { base_msat: 0, @@ -4905,6 +5038,7 @@ mod tests { } #[test] + #[rustfmt::skip] fn last_hops_with_public_channel_test() { let (secp_ctx, network_graph, _, _, logger) = build_graph(); let (_, our_id, _, nodes) = get_nodes(&secp_ctx); @@ -4959,6 +5093,7 @@ mod tests { } #[test] + #[rustfmt::skip] fn our_chans_last_hop_connect_test() { let (secp_ctx, network_graph, _, _, logger) = build_graph(); let (_, our_id, _, nodes) = get_nodes(&secp_ctx); @@ -5075,6 +5210,7 @@ mod tests { assert_eq!(route.paths[0].hops[4].channel_features.le_flags(), &Vec::::new()); // We can't learn any flags from invoices, sadly } + #[rustfmt::skip] fn do_unannounced_path_test(last_hop_htlc_max: Option, last_hop_fee_prop: u32, outbound_capacity_msat: u64, route_val: u64) -> Result { let source_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&>::from_hex(&format!("{:02}", 41).repeat(32)).unwrap()[..]).unwrap()); let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&>::from_hex(&format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap()); @@ -5106,6 +5242,7 @@ mod tests { } #[test] + #[rustfmt::skip] fn unannounced_path_test() { // We should be able to send a payment to a destination without any help of a routing graph // if we have a channel with a common counterparty that appears in the first and last hop @@ -5132,6 +5269,7 @@ mod tests { } #[test] + #[rustfmt::skip] fn overflow_unannounced_path_test_liquidity_underflow() { // Previously, when we had a last-hop hint connected directly to a first-hop channel, where // the last-hop had a fee which overflowed a u64, we'd panic. @@ -5143,6 +5281,7 @@ mod tests { } #[test] + #[rustfmt::skip] fn overflow_unannounced_path_test_feerate_overflow() { // This tests for the same case as above, except instead of hitting a subtraction // underflow, we hit a case where the fee charged at a hop overflowed. @@ -5150,6 +5289,7 @@ mod tests { } #[test] + #[rustfmt::skip] fn available_amount_while_routing_test() { // Tests whether we choose the correct available channel amount while routing. @@ -5470,6 +5610,7 @@ mod tests { } #[test] + #[rustfmt::skip] fn available_liquidity_last_hop_test() { // Check that available liquidity properly limits the path even when only // one of the latter hops is limited. @@ -5614,6 +5755,7 @@ mod tests { } #[test] + #[rustfmt::skip] fn ignore_fee_first_hop_test() { let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph(); let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx); @@ -5666,6 +5808,7 @@ mod tests { } #[test] + #[rustfmt::skip] fn simple_mpp_route_test() { let (secp_ctx, _, _, _, _) = build_graph(); let (_, _, _, nodes) = get_nodes(&secp_ctx); @@ -5709,7 +5852,7 @@ mod tests { do_simple_mpp_route_test(two_hop_blinded_payment_params); } - + #[rustfmt::skip] fn do_simple_mpp_route_test(payment_params: PaymentParameters) { let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph(); let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx); @@ -5945,6 +6088,7 @@ mod tests { assert!(do_mpp_route_tests(300_001).is_err()); } + #[rustfmt::skip] fn do_mpp_route_tests(amt: u64) -> Result { let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph(); let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx); @@ -6115,6 +6259,7 @@ mod tests { } #[test] + #[rustfmt::skip] fn fees_on_mpp_route_test() { // This test makes sure that MPP algorithm properly takes into account // fees charged on the channels, by making the fees impactful: @@ -6327,6 +6472,7 @@ mod tests { } #[test] + #[rustfmt::skip] fn mpp_with_last_hops() { // Previously, if we tried to send an MPP payment to a destination which was only reachable // via a single last-hop route hint, we'd fail to route if we first collected routes @@ -6437,6 +6583,7 @@ mod tests { } #[test] + #[rustfmt::skip] fn drop_lowest_channel_mpp_route_test() { // This test checks that low-capacity channel is dropped when after // path finding we realize that we found more capacity than we need. @@ -6589,6 +6736,7 @@ mod tests { } #[test] + #[rustfmt::skip] fn min_criteria_consistency() { // Test that we don't use an inconsistent metric between updating and walking nodes during // our Dijkstra's pass. In the initial version of MPP, the "best source" for a given node @@ -6762,8 +6910,8 @@ mod tests { } } - #[test] + #[rustfmt::skip] fn exact_fee_liquidity_limit() { // Test that if, while walking the graph, we find a hop that has exactly enough liquidity // for us, including later hop fees, we take it. In the first version of our MPP algorithm @@ -6832,6 +6980,7 @@ mod tests { } #[test] + #[rustfmt::skip] fn htlc_max_reduction_below_min() { // Test that if, while walking the graph, we reduce the value being sent to meet an // htlc_maximum_msat, we don't end up undershooting a later htlc_minimum_msat. In the @@ -6905,6 +7054,7 @@ mod tests { } #[test] + #[rustfmt::skip] fn multiple_direct_first_hops() { // Previously we'd only ever considered one first hop path per counterparty. // However, as we don't restrict users to one channel per peer, we really need to support @@ -6988,6 +7138,7 @@ mod tests { } #[test] + #[rustfmt::skip] fn prefers_shorter_route_with_higher_fees() { let (secp_ctx, network_graph, _, _, logger) = build_graph(); let (_, our_id, _, nodes) = get_nodes(&secp_ctx); @@ -7026,10 +7177,12 @@ mod tests { #[cfg(c_bindings)] impl Writeable for BadChannelScorer { + #[rustfmt::skip] fn write(&self, _w: &mut W) -> Result<(), crate::io::Error> { unimplemented!() } } impl ScoreLookUp for BadChannelScorer { type ScoreParams = (); + #[rustfmt::skip] fn channel_penalty_msat(&self, candidate: &CandidateRouteHop, _: ChannelUsage, _score_params:&Self::ScoreParams) -> u64 { if candidate.short_channel_id() == Some(self.short_channel_id) { u64::max_value() } else { 0 } } @@ -7041,17 +7194,20 @@ mod tests { #[cfg(c_bindings)] impl Writeable for BadNodeScorer { + #[rustfmt::skip] fn write(&self, _w: &mut W) -> Result<(), crate::io::Error> { unimplemented!() } } impl ScoreLookUp for BadNodeScorer { type ScoreParams = (); + #[rustfmt::skip] fn channel_penalty_msat(&self, candidate: &CandidateRouteHop, _: ChannelUsage, _score_params:&Self::ScoreParams) -> u64 { if candidate.target() == Some(self.node_id) { u64::max_value() } else { 0 } } } #[test] + #[rustfmt::skip] fn avoids_routing_through_bad_channels_and_nodes() { let (secp_ctx, network, _, _, logger) = build_graph(); let (_, our_id, _, nodes) = get_nodes(&secp_ctx); @@ -7164,6 +7320,7 @@ mod tests { } #[test] + #[rustfmt::skip] fn limits_total_cltv_delta() { let (secp_ctx, network, _, _, logger) = build_graph(); let (_, our_id, _, nodes) = get_nodes(&secp_ctx); @@ -7200,6 +7357,7 @@ mod tests { } #[test] + #[rustfmt::skip] fn avoids_recently_failed_paths() { // Ensure that the router always avoids all of the `previously_failed_channels` channels by // randomly inserting channels into it until we can't find a route anymore. @@ -7235,6 +7393,7 @@ mod tests { } #[test] + #[rustfmt::skip] fn limits_path_length() { let (secp_ctx, network, _, _, logger) = build_line_graph(); let (_, our_id, _, nodes) = get_nodes(&secp_ctx); @@ -7267,6 +7426,7 @@ mod tests { } #[test] + #[rustfmt::skip] fn adds_and_limits_cltv_offset() { let (secp_ctx, network_graph, _, _, logger) = build_graph(); let (_, our_id, _, nodes) = get_nodes(&secp_ctx); @@ -7301,6 +7461,7 @@ mod tests { } #[test] + #[rustfmt::skip] fn adds_plausible_cltv_offset() { let (secp_ctx, network, _, _, logger) = build_graph(); let (_, our_id, _, nodes) = get_nodes(&secp_ctx); @@ -7368,6 +7529,7 @@ mod tests { } #[test] + #[rustfmt::skip] fn builds_correct_path_from_hops() { let (secp_ctx, network, _, _, logger) = build_graph(); let (_, our_id, _, nodes) = get_nodes(&secp_ctx); @@ -7387,6 +7549,7 @@ mod tests { } #[test] + #[rustfmt::skip] fn avoids_saturating_channels() { let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph(); let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx); @@ -7450,6 +7613,7 @@ mod tests { } #[test] + #[rustfmt::skip] fn generate_routes() { use crate::routing::scoring::ProbabilisticScoringFeeParameters; @@ -7469,6 +7633,7 @@ mod tests { } #[test] + #[rustfmt::skip] fn generate_routes_mpp() { use crate::routing::scoring::ProbabilisticScoringFeeParameters; @@ -7488,6 +7653,7 @@ mod tests { } #[test] + #[rustfmt::skip] fn generate_large_mpp_routes() { use crate::routing::scoring::ProbabilisticScoringFeeParameters; @@ -7507,6 +7673,7 @@ mod tests { } #[test] + #[rustfmt::skip] fn honors_manual_penalties() { let (secp_ctx, network_graph, _, _, logger) = build_line_graph(); let (_, our_id, _, nodes) = get_nodes(&secp_ctx); @@ -7553,6 +7720,7 @@ mod tests { } #[test] + #[rustfmt::skip] fn abide_by_route_hint_max_htlc() { // Check that we abide by any htlc_maximum_msat provided in the route hints of the payment // params in the final route. @@ -7611,6 +7779,7 @@ mod tests { } #[test] + #[rustfmt::skip] fn direct_channel_to_hints_with_max_htlc() { // Check that if we have a first hop channel peer that's connected to multiple provided route // hints, that we properly split the payment between the route hints if needed. @@ -7707,6 +7876,7 @@ mod tests { } #[test] + #[rustfmt::skip] fn blinded_route_ser() { // (De)serialize a Route with 1 blinded path out of two total paths. let mut route = Route { paths: vec![Path { @@ -7763,6 +7933,7 @@ mod tests { } #[test] + #[rustfmt::skip] fn blinded_path_inflight_processing() { // Ensure we'll score the channel that's inbound to a blinded path's introduction node, and // account for the blinded tail's final amount_msat. @@ -7800,6 +7971,7 @@ mod tests { } #[test] + #[rustfmt::skip] fn blinded_path_cltv_shadow_offset() { // Make sure we add a shadow offset when sending to blinded paths. let mut route = Route { paths: vec![Path { @@ -7848,6 +8020,7 @@ mod tests { do_simple_blinded_route_hints(3); } + #[rustfmt::skip] fn do_simple_blinded_route_hints(num_blinded_hops: usize) { // Check that we can generate a route to a blinded path with the expected hops. let (secp_ctx, network, _, _, logger) = build_graph(); @@ -7911,6 +8084,7 @@ mod tests { } #[test] + #[rustfmt::skip] fn blinded_path_routing_errors() { // Check that we can generate a route to a blinded path with the expected hops. let (secp_ctx, network, _, _, logger) = build_graph(); @@ -7970,6 +8144,7 @@ mod tests { } #[test] + #[rustfmt::skip] fn matching_intro_node_paths_provided() { // Check that if multiple blinded paths with the same intro node are provided in payment // parameters, we'll return the correct paths in the resulting MPP route. @@ -8027,6 +8202,7 @@ mod tests { } #[test] + #[rustfmt::skip] fn direct_to_intro_node() { // This previously caused a debug panic in the router when asserting // `used_liquidity_msat <= hop_max_msat`, because when adding first_hop<>blinded_route_hint @@ -8111,6 +8287,7 @@ mod tests { } #[test] + #[rustfmt::skip] fn direct_to_matching_intro_nodes() { // This previously caused us to enter `unreachable` code in the following situation: // 1. We add a route candidate for intro_node contributing a high amount @@ -8169,6 +8346,7 @@ mod tests { } #[test] + #[rustfmt::skip] fn we_are_intro_node_candidate_hops() { // This previously led to a panic in the router because we'd generate a Path with only a // BlindedTail and 0 unblinded hops, due to the only candidate hops being blinded route hints @@ -8210,6 +8388,7 @@ mod tests { } #[test] + #[rustfmt::skip] fn we_are_intro_node_bp_in_final_path_fee_calc() { // This previously led to a debug panic in the router because we'd find an invalid Path with // 0 unblinded hops and a blinded tail, leading to the generation of a final @@ -8261,6 +8440,7 @@ mod tests { do_min_htlc_overpay_violates_max_htlc(true); do_min_htlc_overpay_violates_max_htlc(false); } + #[rustfmt::skip] fn do_min_htlc_overpay_violates_max_htlc(blinded_payee: bool) { // Test that if overpaying to meet a later hop's min_htlc and causes us to violate an earlier // hop's max_htlc, we don't consider that candidate hop valid. Previously we would add this hop @@ -8327,11 +8507,13 @@ mod tests { } #[test] + #[rustfmt::skip] fn previously_used_liquidity_violates_max_htlc() { do_previously_used_liquidity_violates_max_htlc(true); do_previously_used_liquidity_violates_max_htlc(false); } + #[rustfmt::skip] fn do_previously_used_liquidity_violates_max_htlc(blinded_payee: bool) { // Test that if a candidate first_hop<>route_hint_src_node channel does not have enough // contribution amount to cover the next hop's min_htlc plus fees, we will not consider that @@ -8405,6 +8587,7 @@ mod tests { } #[test] + #[rustfmt::skip] fn candidate_path_min() { // Test that if a candidate first_hop<>network_node channel does not have enough contribution // amount to cover the next channel's min htlc plus fees, we will not consider that candidate. @@ -8470,6 +8653,7 @@ mod tests { } #[test] + #[rustfmt::skip] fn path_contribution_includes_min_htlc_overpay() { // Previously, the fuzzer hit a debug panic because we wouldn't include the amount overpaid to // meet a last hop's min_htlc in the total collected paths value. We now include this value and @@ -8523,6 +8707,7 @@ mod tests { } #[test] + #[rustfmt::skip] fn first_hop_preferred_over_hint() { // Check that if we have a first hop to a peer we'd always prefer that over a route hint // they gave us, but we'd still consider all subsequent hints if they are more attractive. @@ -8672,6 +8857,7 @@ mod tests { } #[test] + #[rustfmt::skip] fn test_max_final_contribution() { // When `compute_max_final_value_contribution` was added, it had a bug where it would // over-estimate the maximum value contribution of a hop by using `ceil` rather than @@ -8765,6 +8951,7 @@ mod tests { } #[test] + #[rustfmt::skip] fn allow_us_being_first_hint() { // Check that we consider a route hint even if we are the src of the first hop. let secp_ctx = Secp256k1::new(); @@ -8818,21 +9005,22 @@ mod tests { #[cfg(any(test, ldk_bench))] pub(crate) mod bench_utils { use super::*; - use std::fs::File; - use std::io::Read; use bitcoin::hashes::Hash; use bitcoin::secp256k1::SecretKey; + use std::fs::File; + use std::io::Read; use crate::chain::transaction::OutPoint; - use crate::routing::scoring::{ProbabilisticScorer, ScoreUpdate}; use crate::ln::channel_state::{ChannelCounterparty, ChannelShutdownState}; use crate::ln::channelmanager; use crate::ln::types::ChannelId; + use crate::routing::scoring::{ProbabilisticScorer, ScoreUpdate}; + use crate::sync::Arc; use crate::util::config::UserConfig; use crate::util::test_utils::TestLogger; - use crate::sync::Arc; /// Tries to open a network graph file, or panics with a URL to fetch it. + #[rustfmt::skip] pub(crate) fn get_graph_scorer_file() -> Result<(std::fs::File, std::fs::File), &'static str> { let load_file = |fname, err_str| { File::open(fname) // By default we're run in RL/lightning @@ -8876,8 +9064,15 @@ pub(crate) mod bench_utils { return Ok((graph_res?, scorer_res?)); } - pub(crate) fn read_graph_scorer(logger: &TestLogger) - -> Result<(Arc>, ProbabilisticScorer>, &TestLogger>), &'static str> { + pub(crate) fn read_graph_scorer( + logger: &TestLogger, + ) -> Result< + ( + Arc>, + ProbabilisticScorer>, &TestLogger>, + ), + &'static str, + > { let (mut graph_file, mut scorer_file) = get_graph_scorer_file()?; let mut graph_buffer = Vec::new(); let mut scorer_buffer = Vec::new(); @@ -8895,6 +9090,7 @@ pub(crate) mod bench_utils { } #[inline] + #[rustfmt::skip] pub(crate) fn first_hop(node_id: PublicKey) -> ChannelDetails { #[allow(deprecated)] // TODO: Remove once balance_msat is removed. ChannelDetails { @@ -8938,6 +9134,7 @@ pub(crate) mod bench_utils { } } + #[rustfmt::skip] pub(crate) fn generate_test_routes(graph: &NetworkGraph<&TestLogger>, scorer: &mut S, score_params: &S::ScoreParams, features: Bolt11InvoiceFeatures, mut seed: u64, starting_amount: u64, route_count: usize, @@ -8982,11 +9179,11 @@ pub(crate) mod bench_utils { #[cfg(ldk_bench)] pub mod benches { use super::*; - use crate::routing::scoring::{ScoreUpdate, ScoreLookUp}; use crate::ln::channelmanager; - use crate::types::features::Bolt11InvoiceFeatures; use crate::routing::gossip::NetworkGraph; use crate::routing::scoring::{FixedPenaltyScorer, ProbabilisticScoringFeeParameters}; + use crate::routing::scoring::{ScoreLookUp, ScoreUpdate}; + use crate::types::features::Bolt11InvoiceFeatures; use crate::util::config::UserConfig; use crate::util::logger::{Logger, Record}; use crate::util::test_utils::TestLogger; @@ -8998,6 +9195,7 @@ pub mod benches { fn log(&self, _record: Record) {} } + #[rustfmt::skip] pub fn generate_routes_with_zero_penalty_scorer(bench: &mut Criterion) { let logger = TestLogger::new(); let (network_graph, _) = bench_utils::read_graph_scorer(&logger).unwrap(); @@ -9006,6 +9204,7 @@ pub mod benches { Bolt11InvoiceFeatures::empty(), 0, "generate_routes_with_zero_penalty_scorer"); } + #[rustfmt::skip] pub fn generate_mpp_routes_with_zero_penalty_scorer(bench: &mut Criterion) { let logger = TestLogger::new(); let (network_graph, _) = bench_utils::read_graph_scorer(&logger).unwrap(); @@ -9015,6 +9214,7 @@ pub mod benches { "generate_mpp_routes_with_zero_penalty_scorer"); } + #[rustfmt::skip] pub fn generate_routes_with_probabilistic_scorer(bench: &mut Criterion) { let logger = TestLogger::new(); let (network_graph, scorer) = bench_utils::read_graph_scorer(&logger).unwrap(); @@ -9023,6 +9223,7 @@ pub mod benches { "generate_routes_with_probabilistic_scorer"); } + #[rustfmt::skip] pub fn generate_mpp_routes_with_probabilistic_scorer(bench: &mut Criterion) { let logger = TestLogger::new(); let (network_graph, scorer) = bench_utils::read_graph_scorer(&logger).unwrap(); @@ -9032,6 +9233,7 @@ pub mod benches { "generate_mpp_routes_with_probabilistic_scorer"); } + #[rustfmt::skip] pub fn generate_large_mpp_routes_with_probabilistic_scorer(bench: &mut Criterion) { let logger = TestLogger::new(); let (network_graph, scorer) = bench_utils::read_graph_scorer(&logger).unwrap(); @@ -9041,6 +9243,7 @@ pub mod benches { "generate_large_mpp_routes_with_probabilistic_scorer"); } + #[rustfmt::skip] pub fn generate_routes_with_nonlinear_probabilistic_scorer(bench: &mut Criterion) { let logger = TestLogger::new(); let (network_graph, scorer) = bench_utils::read_graph_scorer(&logger).unwrap(); @@ -9051,6 +9254,7 @@ pub mod benches { "generate_routes_with_nonlinear_probabilistic_scorer"); } + #[rustfmt::skip] pub fn generate_mpp_routes_with_nonlinear_probabilistic_scorer(bench: &mut Criterion) { let logger = TestLogger::new(); let (network_graph, scorer) = bench_utils::read_graph_scorer(&logger).unwrap(); @@ -9061,6 +9265,7 @@ pub mod benches { "generate_mpp_routes_with_nonlinear_probabilistic_scorer"); } + #[rustfmt::skip] pub fn generate_large_mpp_routes_with_nonlinear_probabilistic_scorer(bench: &mut Criterion) { let logger = TestLogger::new(); let (network_graph, scorer) = bench_utils::read_graph_scorer(&logger).unwrap(); @@ -9071,6 +9276,7 @@ pub mod benches { "generate_large_mpp_routes_with_nonlinear_probabilistic_scorer"); } + #[rustfmt::skip] fn generate_routes( bench: &mut Criterion, graph: &NetworkGraph<&TestLogger>, mut scorer: S, score_params: &S::ScoreParams, features: Bolt11InvoiceFeatures, starting_amount: u64, @@ -9084,6 +9290,7 @@ pub mod benches { } #[inline(never)] + #[rustfmt::skip] fn do_route_bench( bench: &mut Criterion, graph: &NetworkGraph<&TestLogger>, scorer: S, score_params: &S::ScoreParams, bench_name: &'static str, diff --git a/lightning/src/routing/scoring.rs b/lightning/src/routing/scoring.rs index 245cee4ca71..d780bdb781d 100644 --- a/lightning/src/routing/scoring.rs +++ b/lightning/src/routing/scoring.rs @@ -1,5 +1,3 @@ -#![cfg_attr(rustfmt, rustfmt_skip)] - // This file is Copyright its original authors, visible in version control // history. // @@ -53,24 +51,27 @@ //! //! [`find_route`]: crate::routing::router::find_route +use crate::io::{self, Read}; use crate::ln::msgs::DecodeError; +use crate::prelude::hash_map::Entry; +use crate::prelude::*; use crate::routing::gossip::{DirectedChannelInfo, EffectiveCapacity, NetworkGraph, NodeId}; -use crate::routing::router::{Path, CandidateRouteHop, PublicHopCandidate}; use crate::routing::log_approx; -use crate::util::ser::{Readable, ReadableArgs, Writeable, Writer}; +use crate::routing::router::{CandidateRouteHop, Path, PublicHopCandidate}; +use crate::sync::{RwLock, RwLockReadGuard, RwLockWriteGuard}; use crate::util::logger::Logger; -use crate::prelude::*; -use crate::prelude::hash_map::Entry; -use core::{cmp, fmt, mem}; +use crate::util::ser::{Readable, ReadableArgs, Writeable, Writer}; +use bucketed_history::{ + DirectedHistoricalLiquidityTracker, HistoricalBucketRangeTracker, HistoricalLiquidityTracker, + LegacyHistoricalBucketRangeTracker, +}; use core::ops::{Deref, DerefMut}; use core::time::Duration; -use crate::io::{self, Read}; -use crate::sync::{RwLock, RwLockReadGuard, RwLockWriteGuard}; -use bucketed_history::{LegacyHistoricalBucketRangeTracker, HistoricalBucketRangeTracker, DirectedHistoricalLiquidityTracker, HistoricalLiquidityTracker}; +use core::{cmp, fmt, mem}; #[cfg(not(c_bindings))] use { - core::cell::{RefCell, RefMut, Ref}, crate::sync::{Mutex, MutexGuard}, + core::cell::{Ref, RefCell, RefMut}, }; /// We define Score ever-so-slightly differently based on whether we are being built for C bindings @@ -326,7 +327,8 @@ impl<'a, T: 'a + Score> Deref for MultiThreadedScoreLockRead<'a, T> { #[cfg(c_bindings)] impl<'a, T: Score> ScoreLookUp for MultiThreadedScoreLockRead<'a, T> { type ScoreParams = T::ScoreParams; - fn channel_penalty_msat(&self, candidate:&CandidateRouteHop, usage: ChannelUsage, score_params: &Self::ScoreParams + fn channel_penalty_msat( + &self, candidate: &CandidateRouteHop, usage: ChannelUsage, score_params: &Self::ScoreParams, ) -> u64 { self.0.channel_penalty_msat(candidate, usage, score_params) } @@ -357,7 +359,9 @@ impl<'a, T: 'a + Score> DerefMut for MultiThreadedScoreLockWrite<'a, T> { #[cfg(c_bindings)] impl<'a, T: Score> ScoreUpdate for MultiThreadedScoreLockWrite<'a, T> { - fn payment_path_failed(&mut self, path: &Path, short_channel_id: u64, duration_since_epoch: Duration) { + fn payment_path_failed( + &mut self, path: &Path, short_channel_id: u64, duration_since_epoch: Duration, + ) { self.0.payment_path_failed(path, short_channel_id, duration_since_epoch) } @@ -378,7 +382,6 @@ impl<'a, T: Score> ScoreUpdate for MultiThreadedScoreLockWrite<'a, T> { } } - /// Proposed use of a channel passed as a parameter to [`ScoreLookUp::channel_penalty_msat`]. #[derive(Clone, Copy, Debug, PartialEq)] pub struct ChannelUsage { @@ -408,16 +411,20 @@ impl FixedPenaltyScorer { impl ScoreLookUp for FixedPenaltyScorer { type ScoreParams = (); - fn channel_penalty_msat(&self, _: &CandidateRouteHop, _: ChannelUsage, _score_params: &Self::ScoreParams) -> u64 { + fn channel_penalty_msat( + &self, _: &CandidateRouteHop, _: ChannelUsage, _score_params: &Self::ScoreParams, + ) -> u64 { self.penalty_msat } } impl ScoreUpdate for FixedPenaltyScorer { + #[rustfmt::skip] fn payment_path_failed(&mut self, _path: &Path, _short_channel_id: u64, _duration_since_epoch: Duration) {} fn payment_path_successful(&mut self, _path: &Path, _duration_since_epoch: Duration) {} + #[rustfmt::skip] fn probe_failed(&mut self, _path: &Path, _short_channel_id: u64, _duration_since_epoch: Duration) {} fn probe_successful(&mut self, _path: &Path, _duration_since_epoch: Duration) {} @@ -473,7 +480,9 @@ impl ReadableArgs for FixedPenaltyScorer { /// [`historical_liquidity_penalty_multiplier_msat`]: ProbabilisticScoringFeeParameters::historical_liquidity_penalty_multiplier_msat /// [`historical_liquidity_penalty_amount_multiplier_msat`]: ProbabilisticScoringFeeParameters::historical_liquidity_penalty_amount_multiplier_msat pub struct ProbabilisticScorer>, L: Deref> -where L::Target: Logger { +where + L::Target: Logger, +{ decay_params: ProbabilisticScoringDecayParameters, network_graph: G, logger: L, @@ -491,6 +500,7 @@ impl ChannelLiquidities { Self(new_hash_map()) } + #[rustfmt::skip] fn time_passed(&mut self, duration_since_epoch: Duration, decay_params: ProbabilisticScoringDecayParameters) { self.0.retain(|_scid, liquidity| { liquidity.min_liquidity_offset_msat = @@ -524,7 +534,9 @@ impl ChannelLiquidities { self.0.get(short_channel_id) } - fn insert(&mut self, short_channel_id: u64, liquidity: ChannelLiquidity) -> Option { + fn insert( + &mut self, short_channel_id: u64, liquidity: ChannelLiquidity, + ) -> Option { self.0.insert(short_channel_id, liquidity) } @@ -938,7 +950,11 @@ struct ChannelLiquidity { } /// A snapshot of [`ChannelLiquidity`] in one direction assuming a certain channel capacity. -struct DirectedChannelLiquidity, HT: Deref, T: Deref> { +struct DirectedChannelLiquidity< + L: Deref, + HT: Deref, + T: Deref, +> { min_liquidity_offset_msat: L, max_liquidity_offset_msat: L, liquidity_history: DirectedHistoricalLiquidityTracker, @@ -948,10 +964,15 @@ struct DirectedChannelLiquidity, HT: Deref>, L: Deref> ProbabilisticScorer where L::Target: Logger { +impl>, L: Deref> ProbabilisticScorer +where + L::Target: Logger, +{ /// Creates a new scorer using the given scoring parameters for sending payments from a node /// through a network graph. - pub fn new(decay_params: ProbabilisticScoringDecayParameters, network_graph: G, logger: L) -> Self { + pub fn new( + decay_params: ProbabilisticScoringDecayParameters, network_graph: G, logger: L, + ) -> Self { Self { decay_params, network_graph, @@ -971,6 +992,7 @@ impl>, L: Deref> ProbabilisticScorer whe /// /// Note that this writes roughly one line per channel for which we have a liquidity estimate, /// which may be a substantial amount of log output. + #[rustfmt::skip] pub fn debug_log_liquidity_stats(&self) { let graph = self.network_graph.read_only(); for (scid, liq) in self.channel_liquidities.iter() { @@ -1023,7 +1045,9 @@ impl>, L: Deref> ProbabilisticScorer whe /// Query the estimated minimum and maximum liquidity available for sending a payment over the /// channel with `scid` towards the given `target` node. - pub fn estimated_channel_liquidity_range(&self, scid: u64, target: &NodeId) -> Option<(u64, u64)> { + pub fn estimated_channel_liquidity_range( + &self, scid: u64, target: &NodeId, + ) -> Option<(u64, u64)> { let graph = self.network_graph.read_only(); if let Some(chan) = graph.channels().get(&scid) { @@ -1064,6 +1088,7 @@ impl>, L: Deref> ProbabilisticScorer whe /// /// In order to fetch a single success probability from the buckets provided here, as used in /// the scoring model, see [`Self::historical_estimated_payment_success_probability`]. + #[rustfmt::skip] pub fn historical_estimated_channel_liquidity_probabilities(&self, scid: u64, target: &NodeId) -> Option<([u16; 32], [u16; 32])> { let graph = self.network_graph.read_only(); @@ -1100,6 +1125,7 @@ impl>, L: Deref> ProbabilisticScorer whe /// These are the same bounds as returned by /// [`Self::historical_estimated_channel_liquidity_probabilities`] (but not those returned by /// [`Self::estimated_channel_liquidity_range`]). + #[rustfmt::skip] pub fn historical_estimated_payment_success_probability( &self, scid: u64, target: &NodeId, amount_msat: u64, params: &ProbabilisticScoringFeeParameters, allow_fallback_estimation: bool, @@ -1130,6 +1156,7 @@ impl>, L: Deref> ProbabilisticScorer whe None } + #[rustfmt::skip] fn calc_live_prob( &self, scid: u64, source: &NodeId, target: &NodeId, directed_info: DirectedChannelInfo, amt: u64, params: &ProbabilisticScoringFeeParameters, @@ -1157,6 +1184,7 @@ impl>, L: Deref> ProbabilisticScorer whe /// /// This will return `Some` for any channel which is present in the [`NetworkGraph`], including /// if we have no bound information beside the channel's capacity. + #[rustfmt::skip] pub fn live_estimated_payment_success_probability( &self, scid: u64, target: &NodeId, amount_msat: u64, params: &ProbabilisticScoringFeeParameters, ) -> Option { @@ -1193,6 +1221,7 @@ impl ChannelLiquidity { } } + #[rustfmt::skip] fn merge(&mut self, other: &Self) { // Take average for min/max liquidity offsets. self.min_liquidity_offset_msat = (self.min_liquidity_offset_msat + other.min_liquidity_offset_msat) / 2; @@ -1204,6 +1233,7 @@ impl ChannelLiquidity { /// Returns a view of the channel liquidity directed from `source` to `target` assuming /// `capacity_msat`. + #[rustfmt::skip] fn as_directed( &self, source: &NodeId, target: &NodeId, capacity_msat: u64, ) -> DirectedChannelLiquidity<&u64, &HistoricalLiquidityTracker, &Duration> { @@ -1228,6 +1258,7 @@ impl ChannelLiquidity { /// Returns a mutable view of the channel liquidity directed from `source` to `target` assuming /// `capacity_msat`. + #[rustfmt::skip] fn as_directed_mut( &mut self, source: &NodeId, target: &NodeId, capacity_msat: u64, ) -> DirectedChannelLiquidity<&mut u64, &mut HistoricalLiquidityTracker, &mut Duration> { @@ -1297,6 +1328,7 @@ fn three_f64_pow_9(a: f64, b: f64, c: f64) -> (f64, f64, f64) { const MIN_ZERO_IMPLIES_NO_SUCCESSES_PENALTY_ON_64: u64 = 78; #[inline(always)] +#[rustfmt::skip] fn linear_success_probability( total_inflight_amount_msat: u64, min_liquidity_msat: u64, max_liquidity_msat: u64, min_zero_implies_no_successes: bool, @@ -1316,6 +1348,7 @@ fn linear_success_probability( /// Returns a (numerator, denominator) pair each between 0 and 0.0078125, inclusive. #[inline(always)] +#[rustfmt::skip] fn nonlinear_success_probability( total_inflight_amount_msat: u64, min_liquidity_msat: u64, max_liquidity_msat: u64, capacity_msat: u64, min_zero_implies_no_successes: bool, @@ -1358,6 +1391,7 @@ fn nonlinear_success_probability( /// min_zero_implies_no_successes signals that a `min_liquidity_msat` of 0 means we've not /// (recently) seen an HTLC successfully complete over this channel. #[inline(always)] +#[rustfmt::skip] fn success_probability_float( total_inflight_amount_msat: u64, min_liquidity_msat: u64, max_liquidity_msat: u64, capacity_msat: u64, params: &ProbabilisticScoringFeeParameters, @@ -1379,6 +1413,7 @@ fn success_probability_float( /// Identical to [`success_probability_float`] but returns integer numerator and denominators. /// /// Must not return a numerator or denominator greater than 2^31 for arguments less than 2^31. +#[rustfmt::skip] fn success_probability( total_inflight_amount_msat: u64, min_liquidity_msat: u64, max_liquidity_msat: u64, capacity_msat: u64, params: &ProbabilisticScoringFeeParameters, @@ -1409,10 +1444,15 @@ fn success_probability( } } -impl, HT: Deref, T: Deref> -DirectedChannelLiquidity< L, HT, T> { +impl< + L: Deref, + HT: Deref, + T: Deref, + > DirectedChannelLiquidity +{ /// Returns a liquidity penalty for routing the given HTLC `amount_msat` through the channel in /// this direction. + #[rustfmt::skip] fn penalty_msat( &self, amount_msat: u64, inflight_htlc_msat: u64, last_update_time: Duration, score_params: &ProbabilisticScoringFeeParameters, @@ -1513,6 +1553,7 @@ DirectedChannelLiquidity< L, HT, T> { /// Computes the liquidity penalty from the penalty multipliers. #[inline(always)] + #[rustfmt::skip] fn combined_penalty_msat(amount_msat: u64, mut negative_log10_times_2048: u64, liquidity_penalty_multiplier_msat: u64, liquidity_penalty_amount_multiplier_msat: u64, ) -> u64 { @@ -1537,15 +1578,21 @@ DirectedChannelLiquidity< L, HT, T> { /// Returns the upper bound of the channel liquidity balance in this direction. #[inline(always)] + #[rustfmt::skip] fn max_liquidity_msat(&self) -> u64 { self.capacity_msat .saturating_sub(*self.max_liquidity_offset_msat) } } -impl, HT: DerefMut, T: DerefMut> -DirectedChannelLiquidity { +impl< + L: DerefMut, + HT: DerefMut, + T: DerefMut, + > DirectedChannelLiquidity +{ /// Adjusts the channel liquidity balance bounds when failing to route `amount_msat`. + #[rustfmt::skip] fn failed_at_channel( &mut self, amount_msat: u64, duration_since_epoch: Duration, chan_descr: fmt::Arguments, logger: &Log ) where Log::Target: Logger { @@ -1562,6 +1609,7 @@ DirectedChannelLiquidity { } /// Adjusts the channel liquidity balance bounds when failing to route `amount_msat` downstream. + #[rustfmt::skip] fn failed_downstream( &mut self, amount_msat: u64, duration_since_epoch: Duration, chan_descr: fmt::Arguments, logger: &Log ) where Log::Target: Logger { @@ -1578,6 +1626,7 @@ DirectedChannelLiquidity { } /// Adjusts the channel liquidity balance bounds when successfully routing `amount_msat`. + #[rustfmt::skip] fn successful(&mut self, amount_msat: u64, duration_since_epoch: Duration, chan_descr: fmt::Arguments, logger: &Log ) where Log::Target: Logger { @@ -1620,8 +1669,12 @@ DirectedChannelLiquidity { } } -impl>, L: Deref> ScoreLookUp for ProbabilisticScorer where L::Target: Logger { +impl>, L: Deref> ScoreLookUp for ProbabilisticScorer +where + L::Target: Logger, +{ type ScoreParams = ProbabilisticScoringFeeParameters; + #[rustfmt::skip] fn channel_penalty_msat( &self, candidate: &CandidateRouteHop, usage: ChannelUsage, score_params: &ProbabilisticScoringFeeParameters ) -> u64 { @@ -1671,7 +1724,11 @@ impl>, L: Deref> ScoreLookUp for Probabilistic } } -impl>, L: Deref> ScoreUpdate for ProbabilisticScorer where L::Target: Logger { +impl>, L: Deref> ScoreUpdate for ProbabilisticScorer +where + L::Target: Logger, +{ + #[rustfmt::skip] fn payment_path_failed(&mut self, path: &Path, short_channel_id: u64, duration_since_epoch: Duration) { let amount_msat = path.final_value_msat(); log_trace!(self.logger, "Scoring path through to SCID {} as having failed at {} msat", short_channel_id, amount_msat); @@ -1714,6 +1771,7 @@ impl>, L: Deref> ScoreUpdate for Probabilistic self.last_update_time = duration_since_epoch; } + #[rustfmt::skip] fn payment_path_successful(&mut self, path: &Path, duration_since_epoch: Duration) { let amount_msat = path.final_value_msat(); log_trace!(self.logger, "Scoring path through SCID {} as having succeeded at {} msat.", @@ -1767,13 +1825,20 @@ impl>, L: Deref> ScoreUpdate for Probabilistic /// /// Note that only the locally acquired data is persisted. After a restart, the external scores will be lost and must be /// resupplied. -pub struct CombinedScorer>, L: Deref> where L::Target: Logger { +pub struct CombinedScorer>, L: Deref> +where + L::Target: Logger, +{ local_only_scorer: ProbabilisticScorer, - scorer: ProbabilisticScorer, + scorer: ProbabilisticScorer, } -impl> + Clone, L: Deref + Clone> CombinedScorer where L::Target: Logger { +impl> + Clone, L: Deref + Clone> CombinedScorer +where + L::Target: Logger, +{ /// Create a new combined scorer with the given local scorer. + #[rustfmt::skip] pub fn new(local_scorer: ProbabilisticScorer) -> Self { let decay_params = local_scorer.decay_params; let network_graph = local_scorer.network_graph.clone(); @@ -1789,7 +1854,9 @@ impl> + Clone, L: Deref + Clone> CombinedScore } /// Merge external channel liquidity information into the scorer. - pub fn merge(&mut self, mut external_scores: ChannelLiquidities, duration_since_epoch: Duration) { + pub fn merge( + &mut self, mut external_scores: ChannelLiquidities, duration_since_epoch: Duration, + ) { // Decay both sets of scores to make them comparable and mergeable. self.local_only_scorer.time_passed(duration_since_epoch); external_scores.time_passed(duration_since_epoch, self.local_only_scorer.decay_params); @@ -1811,52 +1878,66 @@ impl> + Clone, L: Deref + Clone> CombinedScore } } -impl>, L: Deref> ScoreLookUp for CombinedScorer where L::Target: Logger { +impl>, L: Deref> ScoreLookUp for CombinedScorer +where + L::Target: Logger, +{ type ScoreParams = ProbabilisticScoringFeeParameters; fn channel_penalty_msat( - &self, candidate: &CandidateRouteHop, usage: ChannelUsage, score_params: &ProbabilisticScoringFeeParameters + &self, candidate: &CandidateRouteHop, usage: ChannelUsage, + score_params: &ProbabilisticScoringFeeParameters, ) -> u64 { self.scorer.channel_penalty_msat(candidate, usage, score_params) } } -impl>, L: Deref> ScoreUpdate for CombinedScorer where L::Target: Logger { - fn payment_path_failed(&mut self,path: &Path,short_channel_id:u64,duration_since_epoch:Duration) { +impl>, L: Deref> ScoreUpdate for CombinedScorer +where + L::Target: Logger, +{ + fn payment_path_failed( + &mut self, path: &Path, short_channel_id: u64, duration_since_epoch: Duration, + ) { self.local_only_scorer.payment_path_failed(path, short_channel_id, duration_since_epoch); self.scorer.payment_path_failed(path, short_channel_id, duration_since_epoch); } - fn payment_path_successful(&mut self,path: &Path,duration_since_epoch:Duration) { + fn payment_path_successful(&mut self, path: &Path, duration_since_epoch: Duration) { self.local_only_scorer.payment_path_successful(path, duration_since_epoch); self.scorer.payment_path_successful(path, duration_since_epoch); } - fn probe_failed(&mut self,path: &Path,short_channel_id:u64,duration_since_epoch:Duration) { + fn probe_failed(&mut self, path: &Path, short_channel_id: u64, duration_since_epoch: Duration) { self.local_only_scorer.probe_failed(path, short_channel_id, duration_since_epoch); self.scorer.probe_failed(path, short_channel_id, duration_since_epoch); } - fn probe_successful(&mut self,path: &Path,duration_since_epoch:Duration) { + fn probe_successful(&mut self, path: &Path, duration_since_epoch: Duration) { self.local_only_scorer.probe_successful(path, duration_since_epoch); self.scorer.probe_successful(path, duration_since_epoch); } - fn time_passed(&mut self,duration_since_epoch:Duration) { + fn time_passed(&mut self, duration_since_epoch: Duration) { self.local_only_scorer.time_passed(duration_since_epoch); self.scorer.time_passed(duration_since_epoch); } } -impl>, L: Deref> Writeable for CombinedScorer where L::Target: Logger { +impl>, L: Deref> Writeable for CombinedScorer +where + L::Target: Logger, +{ fn write(&self, writer: &mut W) -> Result<(), crate::io::Error> { self.local_only_scorer.write(writer) } } #[cfg(c_bindings)] -impl>, L: Deref> Score for ProbabilisticScorer -where L::Target: Logger {} +impl>, L: Deref> Score for ProbabilisticScorer where + L::Target: Logger +{ +} #[cfg(feature = "std")] #[inline] @@ -1891,21 +1972,22 @@ mod bucketed_history { impl BucketStartPos { const fn new() -> Self { Self([ - 0, 1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 3072, 4096, 6144, 8192, 10240, 12288, - 13312, 14336, 15360, 15872, 16128, 16256, 16320, 16352, 16368, 16376, 16380, 16382, 16383, 16384, + 0, 1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 3072, 4096, 6144, 8192, + 10240, 12288, 13312, 14336, 15360, 15872, 16128, 16256, 16320, 16352, 16368, 16376, + 16380, 16382, 16383, 16384, ]) } } impl core::ops::Index for BucketStartPos { type Output = u16; #[inline(always)] + #[rustfmt::skip] fn index(&self, index: usize) -> &u16 { &self.0[index] } } const BUCKET_START_POS: BucketStartPos = BucketStartPos::new(); - const LEGACY_TO_BUCKET_RANGE: [(u8, u8); 8] = [ - (0, 12), (12, 14), (14, 15), (15, 16), (16, 17), (17, 18), (18, 20), (20, 32) - ]; + const LEGACY_TO_BUCKET_RANGE: [(u8, u8); 8] = + [(0, 12), (12, 14), (14, 15), (15, 16), (16, 17), (17, 18), (18, 20), (20, 32)]; const POSITION_TICKS: u16 = 1 << 14; @@ -1921,6 +2003,7 @@ mod bucketed_history { #[cfg(test)] #[test] + #[rustfmt::skip] fn check_bucket_maps() { const BUCKET_WIDTH_IN_16384S: [u16; 32] = [ 1, 1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 1024, 1024, 2048, 2048, @@ -1947,6 +2030,7 @@ mod bucketed_history { } #[inline] + #[rustfmt::skip] fn amount_to_pos(amount_msat: u64, capacity_msat: u64) -> u16 { let pos = if amount_msat < u64::max_value() / (POSITION_TICKS as u64) { (amount_msat * (POSITION_TICKS as u64) / capacity_msat.saturating_add(1)) @@ -2001,6 +2085,7 @@ mod bucketed_history { pub const BUCKET_FIXED_POINT_ONE: u16 = 32; impl HistoricalBucketRangeTracker { + #[rustfmt::skip] pub(super) fn new() -> Self { Self { buckets: [0; 32] } } fn track_datapoint(&mut self, liquidity_offset_msat: u64, capacity_msat: u64) { // We have 32 leaky buckets for min and max liquidity. Each bucket tracks the amount of time @@ -2054,7 +2139,7 @@ mod bucketed_history { impl_writeable_tlv_based!(LegacyHistoricalBucketRangeTracker, { (0, buckets, required) }); #[derive(Clone, Copy)] - #[repr(C)]// Force the fields in memory to be in the order we specify. + #[repr(C)] // Force the fields in memory to be in the order we specify. pub(super) struct HistoricalLiquidityTracker { // This struct sits inside a `(u64, ChannelLiquidity)` in memory, and we first read the // liquidity offsets in `ChannelLiquidity` when calculating the non-historical score. This @@ -2096,6 +2181,7 @@ mod bucketed_history { res } + #[rustfmt::skip] pub(super) fn has_datapoints(&self) -> bool { self.min_liquidity_offset_history.buckets != [0; 32] || self.max_liquidity_offset_history.buckets != [0; 32] @@ -2107,6 +2193,7 @@ mod bucketed_history { self.recalculate_valid_point_count(); } + #[rustfmt::skip] fn recalculate_valid_point_count(&mut self) { let mut total_valid_points_tracked = 0u128; for (min_idx, min_bucket) in self.min_liquidity_offset_history.buckets.iter().enumerate() { @@ -2132,13 +2219,15 @@ mod bucketed_history { &self.max_liquidity_offset_history } - pub(super) fn as_directed<'a>(&'a self, source_less_than_target: bool) - -> DirectedHistoricalLiquidityTracker<&'a HistoricalLiquidityTracker> { + pub(super) fn as_directed<'a>( + &'a self, source_less_than_target: bool, + ) -> DirectedHistoricalLiquidityTracker<&'a HistoricalLiquidityTracker> { DirectedHistoricalLiquidityTracker { source_less_than_target, tracker: self } } - pub(super) fn as_directed_mut<'a>(&'a mut self, source_less_than_target: bool) - -> DirectedHistoricalLiquidityTracker<&'a mut HistoricalLiquidityTracker> { + pub(super) fn as_directed_mut<'a>( + &'a mut self, source_less_than_target: bool, + ) -> DirectedHistoricalLiquidityTracker<&'a mut HistoricalLiquidityTracker> { DirectedHistoricalLiquidityTracker { source_less_than_target, tracker: self } } @@ -2152,12 +2241,15 @@ mod bucketed_history { /// A set of buckets representing the history of where we've seen the minimum- and maximum- /// liquidity bounds for a given channel. - pub(super) struct DirectedHistoricalLiquidityTracker> { + pub(super) struct DirectedHistoricalLiquidityTracker< + D: Deref, + > { source_less_than_target: bool, tracker: D, } impl> DirectedHistoricalLiquidityTracker { + #[rustfmt::skip] pub(super) fn track_datapoint( &mut self, min_offset_msat: u64, max_offset_msat: u64, capacity_msat: u64, ) { @@ -2190,6 +2282,7 @@ mod bucketed_history { } #[inline] + #[rustfmt::skip] pub(super) fn calculate_success_probability_times_billion( &self, params: &ProbabilisticScoringFeeParameters, total_inflight_amount_msat: u64, capacity_msat: u64 @@ -2416,7 +2509,10 @@ mod bucketed_history { } } -impl>, L: Deref> Writeable for ProbabilisticScorer where L::Target: Logger { +impl>, L: Deref> Writeable for ProbabilisticScorer +where + L::Target: Logger, +{ #[inline] fn write(&self, w: &mut W) -> Result<(), io::Error> { self.channel_liquidities.write(w) @@ -2424,8 +2520,12 @@ impl>, L: Deref> Writeable for ProbabilisticSc } impl>, L: Deref> -ReadableArgs<(ProbabilisticScoringDecayParameters, G, L)> for ProbabilisticScorer where L::Target: Logger { + ReadableArgs<(ProbabilisticScoringDecayParameters, G, L)> for ProbabilisticScorer +where + L::Target: Logger, +{ #[inline] + #[rustfmt::skip] fn read( r: &mut R, args: (ProbabilisticScoringDecayParameters, G, L) ) -> Result { @@ -2465,6 +2565,7 @@ impl Writeable for ChannelLiquidity { impl Readable for ChannelLiquidity { #[inline] + #[rustfmt::skip] fn read(r: &mut R) -> Result { let mut min_liquidity_offset_msat = 0; let mut max_liquidity_offset_msat = 0; @@ -2516,26 +2617,35 @@ impl Readable for ChannelLiquidity { #[cfg(test)] mod tests { - use super::{ChannelLiquidity, HistoricalLiquidityTracker, ProbabilisticScorer, ProbabilisticScoringDecayParameters, ProbabilisticScoringFeeParameters}; + use super::{ + ChannelLiquidity, HistoricalLiquidityTracker, ProbabilisticScorer, + ProbabilisticScoringDecayParameters, ProbabilisticScoringFeeParameters, + }; use crate::blinded_path::BlindedHop; use crate::util::config::UserConfig; use crate::ln::channelmanager; - use crate::ln::msgs::{ChannelAnnouncement, ChannelUpdate, UnsignedChannelAnnouncement, UnsignedChannelUpdate}; + use crate::ln::msgs::{ + ChannelAnnouncement, ChannelUpdate, UnsignedChannelAnnouncement, UnsignedChannelUpdate, + }; use crate::routing::gossip::{EffectiveCapacity, NetworkGraph, NodeId}; - use crate::routing::router::{BlindedTail, Path, RouteHop, CandidateRouteHop, PublicHopCandidate}; - use crate::routing::scoring::{ChannelLiquidities, ChannelUsage, CombinedScorer, ScoreLookUp, ScoreUpdate}; + use crate::routing::router::{ + BlindedTail, CandidateRouteHop, Path, PublicHopCandidate, RouteHop, + }; + use crate::routing::scoring::{ + ChannelLiquidities, ChannelUsage, CombinedScorer, ScoreLookUp, ScoreUpdate, + }; use crate::util::ser::{ReadableArgs, Writeable}; use crate::util::test_utils::{self, TestLogger}; + use crate::io; use bitcoin::constants::ChainHash; - use bitcoin::hashes::Hash; use bitcoin::hashes::sha256d::Hash as Sha256dHash; + use bitcoin::hashes::Hash; use bitcoin::network::Network; use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey}; use core::time::Duration; use std::rc::Rc; - use crate::io; fn source_privkey() -> SecretKey { SecretKey::from_slice(&[42; 32]).unwrap() @@ -2595,6 +2705,7 @@ mod tests { network_graph } + #[rustfmt::skip] fn add_channel( network_graph: &mut NetworkGraph<&TestLogger>, short_channel_id: u64, node_1_key: SecretKey, node_2_key: SecretKey @@ -2668,6 +2779,7 @@ mod tests { } } + #[rustfmt::skip] fn payment_path_for_amount(amount_msat: u64) -> Path { Path { hops: vec![ @@ -2679,6 +2791,7 @@ mod tests { } #[test] + #[rustfmt::skip] fn liquidity_bounds_directed_from_lowest_node_id() { let logger = TestLogger::new(); let last_updated = Duration::ZERO; @@ -2759,6 +2872,7 @@ mod tests { } #[test] + #[rustfmt::skip] fn resets_liquidity_upper_bound_when_crossed_by_lower_bound() { let logger = TestLogger::new(); let last_updated = Duration::ZERO; @@ -2820,6 +2934,7 @@ mod tests { } #[test] + #[rustfmt::skip] fn resets_liquidity_lower_bound_when_crossed_by_upper_bound() { let logger = TestLogger::new(); let last_updated = Duration::ZERO; @@ -2881,6 +2996,7 @@ mod tests { } #[test] + #[rustfmt::skip] fn increased_penalty_nearing_liquidity_upper_bound() { let logger = TestLogger::new(); let network_graph = network_graph(&logger); @@ -2933,6 +3049,7 @@ mod tests { } #[test] + #[rustfmt::skip] fn constant_penalty_outside_liquidity_bounds() { let logger = TestLogger::new(); let last_updated = Duration::ZERO; @@ -2976,6 +3093,7 @@ mod tests { } #[test] + #[rustfmt::skip] fn does_not_further_penalize_own_channel() { let logger = TestLogger::new(); let network_graph = network_graph(&logger); @@ -3009,6 +3127,7 @@ mod tests { } #[test] + #[rustfmt::skip] fn sets_liquidity_lower_bound_on_downstream_failure() { let logger = TestLogger::new(); let network_graph = network_graph(&logger); @@ -3048,6 +3167,7 @@ mod tests { } #[test] + #[rustfmt::skip] fn sets_liquidity_upper_bound_on_failure() { let logger = TestLogger::new(); let network_graph = network_graph(&logger); @@ -3088,6 +3208,7 @@ mod tests { } #[test] + #[rustfmt::skip] fn ignores_channels_after_removed_failed_channel() { // Previously, if we'd tried to send over a channel which was removed from the network // graph before we call `payment_path_failed` (which is the default if the we get a "no @@ -3181,6 +3302,7 @@ mod tests { } #[test] + #[rustfmt::skip] fn reduces_liquidity_upper_bound_along_path_on_success() { let logger = TestLogger::new(); let network_graph = network_graph(&logger); @@ -3225,6 +3347,7 @@ mod tests { } #[test] + #[rustfmt::skip] fn decays_liquidity_bounds_over_time() { let logger = TestLogger::new(); let network_graph = network_graph(&logger); @@ -3316,6 +3439,7 @@ mod tests { } #[test] + #[rustfmt::skip] fn restricts_liquidity_bounds_after_decay() { let logger = TestLogger::new(); let network_graph = network_graph(&logger); @@ -3368,6 +3492,7 @@ mod tests { } #[test] + #[rustfmt::skip] fn restores_persisted_liquidity_bounds() { let logger = TestLogger::new(); let network_graph = network_graph(&logger); @@ -3412,6 +3537,7 @@ mod tests { assert_eq!(deserialized_scorer.channel_penalty_msat(&candidate, usage, ¶ms), 300); } + #[rustfmt::skip] fn do_decays_persisted_liquidity_bounds(decay_before_reload: bool) { let logger = TestLogger::new(); let network_graph = network_graph(&logger); @@ -3471,6 +3597,7 @@ mod tests { } #[test] + #[rustfmt::skip] fn scores_realistic_payments() { // Shows the scores of "realistic" sends of 100k sats over channels of 1-10m sats (with a // 50k sat reserve). @@ -3535,6 +3662,7 @@ mod tests { } #[test] + #[rustfmt::skip] fn adds_base_penalty_to_liquidity_penalty() { let logger = TestLogger::new(); let network_graph = network_graph(&logger); @@ -3576,6 +3704,7 @@ mod tests { } #[test] + #[rustfmt::skip] fn adds_amount_penalty_to_liquidity_penalty() { let logger = TestLogger::new(); let network_graph = network_graph(&logger); @@ -3610,6 +3739,7 @@ mod tests { } #[test] + #[rustfmt::skip] fn calculates_log10_without_overflowing_u64_max_value() { let logger = TestLogger::new(); let network_graph = network_graph(&logger); @@ -3635,6 +3765,7 @@ mod tests { } #[test] + #[rustfmt::skip] fn accounts_for_inflight_htlc_usage() { let logger = TestLogger::new(); let network_graph = network_graph(&logger); @@ -3664,6 +3795,7 @@ mod tests { } #[test] + #[rustfmt::skip] fn removes_uncertainity_when_exact_liquidity_known() { let logger = TestLogger::new(); let network_graph = network_graph(&logger); @@ -3694,6 +3826,7 @@ mod tests { } #[test] + #[rustfmt::skip] fn remembers_historical_failures() { let logger = TestLogger::new(); let network_graph = network_graph(&logger); @@ -3855,6 +3988,7 @@ mod tests { } #[test] + #[rustfmt::skip] fn adds_anti_probing_penalty() { let logger = TestLogger::new(); let network_graph = network_graph(&logger); @@ -3906,6 +4040,7 @@ mod tests { } #[test] + #[rustfmt::skip] fn scores_with_blinded_path() { // Make sure we'll account for a blinded path's final_value_msat in scoring let logger = TestLogger::new(); @@ -3955,6 +4090,7 @@ mod tests { } #[test] + #[rustfmt::skip] fn realistic_historical_failures() { // The motivation for the unequal sized buckets came largely from attempting to pay 10k // sats over a one bitcoin channel. This tests that case explicitly, ensuring that we score @@ -4033,6 +4169,7 @@ mod tests { } #[test] + #[rustfmt::skip] fn get_scores() { let logger = TestLogger::new(); let network_graph = network_graph(&logger); @@ -4137,6 +4274,7 @@ mod tests { } #[test] + #[rustfmt::skip] fn probes_for_diversity() { // Tests the probing_diversity_penalty_msat is applied let logger = TestLogger::new(); @@ -4189,10 +4327,11 @@ mod tests { #[cfg(ldk_bench)] pub mod benches { use super::*; - use criterion::Criterion; use crate::routing::router::bench_utils; use crate::util::test_utils::TestLogger; + use criterion::Criterion; + #[rustfmt::skip] pub fn decay_100k_channel_bounds(bench: &mut Criterion) { let logger = TestLogger::new(); let (_, mut scorer) = bench_utils::read_graph_scorer(&logger).unwrap(); diff --git a/lightning/src/routing/test_utils.rs b/lightning/src/routing/test_utils.rs index 14f004cd044..78f56db3c76 100644 --- a/lightning/src/routing/test_utils.rs +++ b/lightning/src/routing/test_utils.rs @@ -1,5 +1,3 @@ -#![cfg_attr(rustfmt, rustfmt_skip)] - // This file is Copyright its original authors, visible in version control // history. // @@ -9,19 +7,22 @@ // You may not use this file except in accordance with one or both of these // licenses. +use crate::ln::msgs::{ + ChannelAnnouncement, ChannelUpdate, NodeAnnouncement, RoutingMessageHandler, SocketAddress, + UnsignedChannelAnnouncement, UnsignedChannelUpdate, UnsignedNodeAnnouncement, MAX_VALUE_MSAT, +}; use crate::routing::gossip::{NetworkGraph, NodeAlias, P2PGossipSync}; use crate::types::features::{ChannelFeatures, NodeFeatures}; -use crate::ln::msgs::{ChannelAnnouncement, ChannelUpdate, MAX_VALUE_MSAT, NodeAnnouncement, RoutingMessageHandler, SocketAddress, UnsignedChannelAnnouncement, UnsignedChannelUpdate, UnsignedNodeAnnouncement}; -use crate::util::test_utils; use crate::util::ser::Writeable; +use crate::util::test_utils; use bitcoin::constants::ChainHash; use bitcoin::hashes::sha256d::Hash as Sha256dHash; use bitcoin::hashes::Hash; use bitcoin::hex::FromHex; use bitcoin::network::Network; -use bitcoin::secp256k1::{PublicKey,SecretKey}; -use bitcoin::secp256k1::{Secp256k1, All}; +use bitcoin::secp256k1::{All, Secp256k1}; +use bitcoin::secp256k1::{PublicKey, SecretKey}; #[allow(unused)] use crate::prelude::*; @@ -58,6 +59,7 @@ pub(crate) fn channel_announcement( } // Using the same keys for LN and BTC ids +#[rustfmt::skip] pub(crate) fn add_channel( gossip_sync: &P2PGossipSync>>, Arc, Arc>, secp_ctx: &Secp256k1, node_1_privkey: &SecretKey, node_2_privkey: &SecretKey, features: ChannelFeatures, short_channel_id: u64 @@ -71,6 +73,7 @@ pub(crate) fn add_channel( }; } +#[rustfmt::skip] pub(crate) fn add_or_update_node( gossip_sync: &P2PGossipSync>>, Arc, Arc>, secp_ctx: &Secp256k1, node_privkey: &SecretKey, features: NodeFeatures, timestamp: u32 @@ -99,6 +102,7 @@ pub(crate) fn add_or_update_node( }; } +#[rustfmt::skip] pub(crate) fn update_channel( gossip_sync: &P2PGossipSync>>, Arc, Arc>, secp_ctx: &Secp256k1, node_privkey: &SecretKey, update: UnsignedChannelUpdate @@ -116,6 +120,7 @@ pub(crate) fn update_channel( }; } +#[rustfmt::skip] pub(super) fn get_nodes(secp_ctx: &Secp256k1) -> (SecretKey, PublicKey, Vec, Vec) { let privkeys: Vec = (2..22).map(|i| { SecretKey::from_slice(&[i; 32]).unwrap() @@ -129,6 +134,7 @@ pub(super) fn get_nodes(secp_ctx: &Secp256k1) -> (SecretKey, PublicKey, Vec (our_privkey, our_id, privkeys, pubkeys) } +#[rustfmt::skip] pub(super) fn id_to_feature_flags(id: u8) -> Vec { // Set the feature flags to the id'th odd (ie non-required) feature bit so that we can // test for it later. @@ -144,6 +150,7 @@ pub(super) fn id_to_feature_flags(id: u8) -> Vec { } } +#[rustfmt::skip] pub(super) fn build_line_graph() -> ( Secp256k1, sync::Arc>>, P2PGossipSync>>, sync::Arc, sync::Arc>, @@ -197,6 +204,7 @@ pub(super) fn build_line_graph() -> ( (secp_ctx, network_graph, gossip_sync, chain_monitor, logger) } +#[rustfmt::skip] pub(super) fn build_graph() -> ( Secp256k1, sync::Arc>>, diff --git a/lightning/src/routing/utxo.rs b/lightning/src/routing/utxo.rs index abe6b9b17a7..4968d6cd7b4 100644 --- a/lightning/src/routing/utxo.rs +++ b/lightning/src/routing/utxo.rs @@ -1,5 +1,3 @@ -#![cfg_attr(rustfmt, rustfmt_skip)] - // This file is Copyright its original authors, visible in version control // history. // @@ -15,21 +13,21 @@ //! channel matches a UTXO on-chain, requiring at least some marginal on-chain transacting in //! order to announce a channel. This module handles that checking. -use bitcoin::TxOut; use bitcoin::amount::Amount; use bitcoin::constants::ChainHash; +use bitcoin::TxOut; use bitcoin::hex::DisplayHex; use crate::ln::chan_utils::make_funding_redeemscript_from_slices; -use crate::ln::msgs::{self, LightningError, ErrorAction, MessageSendEvent}; +use crate::ln::msgs::{self, ErrorAction, LightningError, MessageSendEvent}; use crate::routing::gossip::{NetworkGraph, NodeId, P2PGossipSync}; use crate::util::logger::{Level, Logger}; use crate::prelude::*; +use crate::sync::{LockTestExt, Mutex}; use alloc::sync::{Arc, Weak}; -use crate::sync::{Mutex, LockTestExt}; use core::ops::Deref; /// An error when accessing the chain via [`UtxoLookup`]. @@ -137,6 +135,7 @@ impl UtxoLookup for UtxoResolver { impl UtxoFuture { /// Builds a new future for later resolution. + #[rustfmt::skip] pub fn new() -> Self { Self { state: Arc::new(Mutex::new(UtxoMessages { complete: None, @@ -159,9 +158,11 @@ impl UtxoFuture { /// /// [`processing_queue_high`]: crate::ln::msgs::RoutingMessageHandler::processing_queue_high /// [`PeerManager::process_events`]: crate::ln::peer_handler::PeerManager::process_events - pub fn resolve_without_forwarding(&self, - graph: &NetworkGraph, result: Result) - where L::Target: Logger { + pub fn resolve_without_forwarding( + &self, graph: &NetworkGraph, result: Result, + ) where + L::Target: Logger, + { self.do_resolve(graph, result); } @@ -176,9 +177,17 @@ impl UtxoFuture { /// /// [`processing_queue_high`]: crate::ln::msgs::RoutingMessageHandler::processing_queue_high /// [`PeerManager::process_events`]: crate::ln::peer_handler::PeerManager::process_events - pub fn resolve>, U: Deref, GS: Deref>>(&self, - graph: &NetworkGraph, gossip: GS, result: Result - ) where L::Target: Logger, U::Target: UtxoLookup { + pub fn resolve< + L: Deref, + G: Deref>, + U: Deref, + GS: Deref>, + >( + &self, graph: &NetworkGraph, gossip: GS, result: Result, + ) where + L::Target: Logger, + U::Target: UtxoLookup, + { let mut res = self.do_resolve(graph, result); for msg_opt in res.iter_mut() { if let Some(msg) = msg_opt.take() { @@ -187,6 +196,7 @@ impl UtxoFuture { } } + #[rustfmt::skip] fn do_resolve(&self, graph: &NetworkGraph, result: Result) -> [Option; 5] where L::Target: Logger { let (announcement, node_a, node_b, update_a, update_b) = { @@ -281,6 +291,7 @@ struct PendingChecksContext { } impl PendingChecksContext { + #[rustfmt::skip] fn lookup_completed(&mut self, msg: &msgs::UnsignedChannelAnnouncement, completed_state: &Weak> ) { @@ -307,6 +318,7 @@ pub(super) struct PendingChecks { } impl PendingChecks { + #[rustfmt::skip] pub(super) fn new() -> Self { PendingChecks { internal: Mutex::new(PendingChecksContext { channels: new_hash_map(), nodes: new_hash_map(), @@ -315,6 +327,7 @@ impl PendingChecks { /// Checks if there is a pending `channel_update` UTXO validation for the given channel, /// and, if so, stores the channel message for handling later and returns an `Err`. + #[rustfmt::skip] pub(super) fn check_hold_pending_channel_update( &self, msg: &msgs::UnsignedChannelUpdate, full_msg: Option<&msgs::ChannelUpdate> ) -> Result<(), LightningError> { @@ -351,6 +364,7 @@ impl PendingChecks { /// Checks if there is a pending `node_announcement` UTXO validation for a channel with the /// given node and, if so, stores the channel message for handling later and returns an `Err`. + #[rustfmt::skip] pub(super) fn check_hold_pending_node_announcement( &self, msg: &msgs::UnsignedNodeAnnouncement, full_msg: Option<&msgs::NodeAnnouncement> ) -> Result<(), LightningError> { @@ -396,6 +410,7 @@ impl PendingChecks { Ok(()) } + #[rustfmt::skip] fn check_replace_previous_entry(msg: &msgs::UnsignedChannelAnnouncement, full_msg: Option<&msgs::ChannelAnnouncement>, replacement: Option>>, pending_channels: &mut HashMap>> @@ -454,6 +469,7 @@ impl PendingChecks { Ok(()) } + #[rustfmt::skip] pub(super) fn check_channel_announcement(&self, utxo_lookup: &Option, msg: &msgs::UnsignedChannelAnnouncement, full_msg: Option<&msgs::ChannelAnnouncement> @@ -540,6 +556,7 @@ impl PendingChecks { /// Returns true if there are a large number of async checks pending and future /// `channel_announcement` messages should be delayed. Note that this is only a hint and /// messages already in-flight may still have to be handled for various reasons. + #[rustfmt::skip] pub(super) fn too_many_checks_pending(&self) -> bool { let mut pending_checks = self.internal.lock().unwrap(); if pending_checks.channels.len() > Self::MAX_PENDING_LOOKUPS { @@ -579,6 +596,7 @@ mod tests { (chain_source, network_graph) } + #[rustfmt::skip] fn get_test_objects() -> (msgs::ChannelAnnouncement, TestChainSource, NetworkGraph>, bitcoin::ScriptBuf, msgs::NodeAnnouncement, msgs::NodeAnnouncement, msgs::ChannelUpdate, msgs::ChannelUpdate, msgs::ChannelUpdate) @@ -606,6 +624,7 @@ mod tests { } #[test] + #[rustfmt::skip] fn test_fast_async_lookup() { // Check that async lookups which resolve quicker than the future is returned to the // `get_utxo` call can read it still resolve properly. @@ -621,6 +640,7 @@ mod tests { } #[test] + #[rustfmt::skip] fn test_async_lookup() { // Test a simple async lookup let (valid_announcement, chain_source, network_graph, good_script, @@ -650,6 +670,7 @@ mod tests { } #[test] + #[rustfmt::skip] fn test_invalid_async_lookup() { // Test an async lookup which returns an incorrect script let (valid_announcement, chain_source, network_graph, ..) = get_test_objects(); @@ -668,6 +689,7 @@ mod tests { } #[test] + #[rustfmt::skip] fn test_failing_async_lookup() { // Test an async lookup which returns an error let (valid_announcement, chain_source, network_graph, ..) = get_test_objects(); @@ -685,6 +707,7 @@ mod tests { } #[test] + #[rustfmt::skip] fn test_updates_async_lookup() { // Test async lookups will process pending channel_update/node_announcements once they // complete. @@ -726,6 +749,7 @@ mod tests { } #[test] + #[rustfmt::skip] fn test_latest_update_async_lookup() { // Test async lookups will process the latest channel_update if two are received while // awaiting an async UTXO lookup. @@ -761,6 +785,7 @@ mod tests { } #[test] + #[rustfmt::skip] fn test_no_double_lookups() { // Test that a pending async lookup will prevent a second async lookup from flying, but // only if the channel_announcement message is identical. @@ -803,6 +828,7 @@ mod tests { } #[test] + #[rustfmt::skip] fn test_checks_backpressure() { // Test that too_many_checks_pending returns true when there are many checks pending, and // returns false once they complete. @@ -834,6 +860,7 @@ mod tests { } #[test] + #[rustfmt::skip] fn test_checks_backpressure_drop() { // Test that too_many_checks_pending returns true when there are many checks pending, and // returns false if we drop some of the futures without completion.