From 1abfab8733644e38e06a272d211296c2634b5d37 Mon Sep 17 00:00:00 2001 From: Joost Jager Date: Thu, 29 May 2025 15:13:14 +0200 Subject: [PATCH] Convert file-level rustfmt skip to fn level skips --- lightning/src/chain/chainmonitor.rs | 205 +++++-- lightning/src/chain/channelmonitor.rs | 376 +++++++++--- lightning/src/chain/onchaintx.rs | 72 ++- lightning/src/chain/package.rs | 125 +++- lightning/src/ln/async_signer_tests.rs | 26 +- lightning/src/ln/blinded_payment_tests.rs | 84 ++- lightning/src/ln/chan_utils.rs | 603 ++++++++++++++---- lightning/src/ln/channel.rs | 717 +++++++++++++++++----- lightning/src/ln/functional_test_utils.rs | 371 ++++++++--- lightning/src/ln/monitor_tests.rs | 55 +- lightning/src/ln/offers_tests.rs | 81 ++- lightning/src/ln/onion_payment.rs | 51 +- lightning/src/ln/onion_route_tests.rs | 164 +++-- lightning/src/ln/outbound_payment.rs | 137 ++++- lightning/src/ln/priv_short_conf_tests.rs | 26 +- lightning/src/ln/reload_tests.rs | 36 +- lightning/src/ln/reorg_tests.rs | 14 +- lightning/src/ln/shutdown_tests.rs | 51 +- lightning/src/routing/router.rs | 341 ++++++++-- lightning/src/routing/scoring.rs | 263 ++++++-- lightning/src/routing/test_utils.rs | 20 +- lightning/src/routing/utxo.rs | 49 +- 22 files changed, 2962 insertions(+), 905 deletions(-) diff --git a/lightning/src/chain/chainmonitor.rs b/lightning/src/chain/chainmonitor.rs index 53784a84163..a740fa3dbcb 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,30 +24,33 @@ //! 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::ln::types::ChannelId; +use crate::chain::{ChannelMonitorUpdateStatus, Filter, WatchedOutput}; +use crate::events::{self, Event, EventHandler, ReplayEvent}; +use crate::ln::channel_state::ChannelDetails; use crate::ln::msgs::{self, BaseMessageHandler, Init, MessageSendEvent}; use crate::ln::our_peer_storage::DecryptedOurPeerStorage; +use crate::ln::types::ChannelId; +use crate::prelude::*; use crate::sign::ecdsa::EcdsaChannelSigner; use crate::sign::{EntropySource, PeerStorageKey}; -use crate::events::{self, Event, EventHandler, ReplayEvent}; -use crate::util::logger::{Logger, WithContext}; +use crate::sync::{Mutex, MutexGuard, RwLock, RwLockReadGuard}; +use crate::types::features::{InitFeatures, NodeFeatures}; 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::types::features::{InitFeatures, NodeFeatures}; +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. @@ -125,6 +126,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 @@ -164,6 +166,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. /// @@ -236,13 +239,21 @@ 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, - ES::Target: EntropySource, +pub struct ChainMonitor< + ChannelSigner: EcdsaChannelSigner, + C: Deref, + T: Deref, + F: Deref, + L: Deref, + P: Deref, + ES: Deref, +> where + C::Target: chain::Filter, + T::Target: BroadcasterInterface, + F::Target: FeeEstimator, + L::Target: Logger, + P::Target: Persist, + ES::Target: EntropySource, { monitors: RwLock>>, chain_source: Option, @@ -267,13 +278,22 @@ pub struct ChainMonitor ChainMonitor -where C::Target: chain::Filter, - T::Target: BroadcasterInterface, - F::Target: FeeEstimator, - L::Target: Logger, - P::Target: Persist, - ES::Target: EntropySource, +impl< + ChannelSigner: EcdsaChannelSigner, + C: Deref, + T: Deref, + F: Deref, + L: Deref, + P: Deref, + ES: Deref, + > ChainMonitor +where + C::Target: chain::Filter, + T::Target: BroadcasterInterface, + F::Target: FeeEstimator, + L::Target: Logger, + P::Target: Persist, + ES::Target: EntropySource, { /// 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 @@ -286,6 +306,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 @@ -329,6 +350,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, @@ -411,6 +433,7 @@ where C::Target: chain::Filter, /// [`NodeSigner`]: crate::sign::NodeSigner /// [`NodeSigner::get_peer_storage_key`]: crate::sign::NodeSigner::get_peer_storage_key /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager + #[rustfmt::skip] pub fn new(chain_source: Option, broadcaster: T, logger: L, feeest: F, persister: P, entropy_source: ES, our_peerstorage_encryption_key: PeerStorageKey) -> Self { Self { monitors: RwLock::new(new_hash_map()), @@ -457,7 +480,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 }) @@ -490,13 +515,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 @@ -522,6 +547,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 { @@ -561,6 +587,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; @@ -589,6 +616,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 ) { @@ -624,6 +652,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 { @@ -637,6 +666,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 { @@ -663,6 +693,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() { @@ -696,6 +727,7 @@ where C::Target: chain::Filter, /// This function collects the counterparty node IDs from all monitors into a `HashSet`, /// ensuring unique IDs are returned. + #[rustfmt::skip] fn all_counterparty_node_ids(&self) -> HashSet { let mon = self.monitors.read().unwrap(); mon @@ -704,6 +736,7 @@ where C::Target: chain::Filter, .collect() } + #[rustfmt::skip] fn send_peer_storage(&self, their_node_id: PublicKey) { // TODO: Serialize `ChannelMonitor`s inside `our_peer_storage`. @@ -721,13 +754,22 @@ where C::Target: chain::Filter, } } -impl BaseMessageHandler for ChainMonitor -where C::Target: chain::Filter, - T::Target: BroadcasterInterface, - F::Target: FeeEstimator, - L::Target: Logger, - P::Target: Persist, - ES::Target: EntropySource, +impl< + ChannelSigner: EcdsaChannelSigner, + C: Deref, + T: Deref, + F: Deref, + L: Deref, + P: Deref, + ES: Deref, + > BaseMessageHandler for ChainMonitor +where + C::Target: chain::Filter, + T::Target: BroadcasterInterface, + F::Target: FeeEstimator, + L::Target: Logger, + P::Target: Persist, + ES::Target: EntropySource, { fn get_and_clear_pending_msg_events(&self) -> Vec { let mut pending_events = self.pending_send_only_events.lock().unwrap(); @@ -744,11 +786,19 @@ where C::Target: chain::Filter, InitFeatures::empty() } + #[rustfmt::skip] fn peer_connected(&self, _their_node_id: PublicKey, _msg: &Init, _inbound: bool) -> Result<(), ()> { Ok(()) } } -impl -chain::Listen for ChainMonitor +impl< + ChannelSigner: EcdsaChannelSigner, + C: Deref, + T: Deref, + F: Deref, + L: Deref, + P: Deref, + ES: Deref, + > chain::Listen for ChainMonitor where C::Target: chain::Filter, T::Target: BroadcasterInterface, @@ -757,6 +807,7 @@ where P::Target: Persist, ES::Target: EntropySource, { + #[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| { @@ -773,6 +824,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); @@ -783,8 +835,15 @@ where } } -impl -chain::Confirm for ChainMonitor +impl< + ChannelSigner: EcdsaChannelSigner, + C: Deref, + T: Deref, + F: Deref, + L: Deref, + P: Deref, + ES: Deref, + > chain::Confirm for ChainMonitor where C::Target: chain::Filter, T::Target: BroadcasterInterface, @@ -793,6 +852,7 @@ where P::Target: Persist, ES::Target: EntropySource, { + #[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| { @@ -803,6 +863,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(); @@ -811,6 +872,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| { @@ -844,15 +906,24 @@ where } } -impl -chain::Watch for ChainMonitor -where C::Target: chain::Filter, - T::Target: BroadcasterInterface, - F::Target: FeeEstimator, - L::Target: Logger, - P::Target: Persist, - ES::Target: EntropySource, +impl< + ChannelSigner: EcdsaChannelSigner, + C: Deref, + T: Deref, + F: Deref, + L: Deref, + P: Deref, + ES: Deref, + > chain::Watch for ChainMonitor +where + C::Target: chain::Filter, + T::Target: BroadcasterInterface, + F::Target: FeeEstimator, + L::Target: Logger, + P::Target: Persist, + ES::Target: EntropySource, { + #[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(); @@ -891,6 +962,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`. @@ -969,6 +1041,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() { @@ -984,13 +1057,22 @@ 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, - ES::Target: EntropySource, +impl< + ChannelSigner: EcdsaChannelSigner, + C: Deref, + T: Deref, + F: Deref, + L: Deref, + P: Deref, + ES: Deref, + > events::EventsProvider for ChainMonitor +where + C::Target: chain::Filter, + T::Target: BroadcasterInterface, + F::Target: FeeEstimator, + L::Target: Logger, + P::Target: Persist, + ES::Target: EntropySource, { /// Processes [`SpendableOutputs`] events produced from each [`ChannelMonitor`] upon maturity. /// @@ -1005,6 +1087,7 @@ where C::Target: chain::Filter, /// /// [`SpendableOutputs`]: events::Event::SpendableOutputs /// [`BumpTransaction`]: events::Event::BumpTransaction + #[rustfmt::skip] fn process_pending_events(&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) { @@ -1019,18 +1102,19 @@ where C::Target: chain::Filter, #[cfg(test)] mod tests { - use crate::{check_added_monitors, check_closed_event}; - use crate::{expect_payment_path_successful, get_event_msg}; - use crate::{get_htlc_update_msgs, get_revoke_commit_msgs}; - use crate::chain::{ChannelMonitorUpdateStatus, Watch}; use crate::chain::channelmonitor::ANTI_REORG_DELAY; + use crate::chain::{ChannelMonitorUpdateStatus, Watch}; use crate::events::{ClosureReason, Event}; use crate::ln::functional_test_utils::*; use crate::ln::msgs::{BaseMessageHandler, ChannelMessageHandler, MessageSendEvent}; + use crate::{check_added_monitors, check_closed_event}; + use crate::{expect_payment_path_successful, get_event_msg}; + use crate::{get_htlc_update_msgs, get_revoke_commit_msgs}; const CHAINSYNC_MONITOR_PARTITION_FACTOR: u32 = 5; #[test] + #[rustfmt::skip] fn test_async_ooo_offchain_updates() { // Test that if we have multiple offchain updates being persisted and they complete // out-of-order, the ChainMonitor waits until all have completed before informing the @@ -1136,6 +1220,7 @@ mod tests { } #[test] + #[rustfmt::skip] fn test_chainsync_triggers_distributed_monitor_persistence() { let chanmon_cfgs = create_chanmon_cfgs(3); let node_cfgs = create_node_cfgs(3, &chanmon_cfgs); @@ -1210,6 +1295,7 @@ mod tests { #[test] #[cfg(feature = "std")] + #[rustfmt::skip] fn update_during_chainsync_poisons_channel() { let chanmon_cfgs = create_chanmon_cfgs(2); let node_cfgs = create_node_cfgs(2, &chanmon_cfgs); @@ -1232,4 +1318,3 @@ mod tests { }).is_err()); } } - diff --git a/lightning/src/chain/channelmonitor.rs b/lightning/src/chain/channelmonitor.rs index 41f4751fbd3..5d70e105910 100644 --- a/lightning/src/chain/channelmonitor.rs +++ b/lightning/src/chain/channelmonitor.rs @@ -1,5 +1,3 @@ -#![cfg_attr(rustfmt, rustfmt_skip)] - // This file is Copyright its original authors, visible in version control // history. // @@ -24,46 +22,64 @@ use bitcoin::amount::Amount; use bitcoin::block::Header; -use bitcoin::transaction::{OutPoint as BitcoinOutPoint, TxOut, Transaction}; use bitcoin::script::{Script, ScriptBuf}; +use bitcoin::transaction::{OutPoint as BitcoinOutPoint, Transaction, TxOut}; -use bitcoin::hashes::Hash; +use bitcoin::hash_types::{BlockHash, Txid}; use bitcoin::hashes::sha256::Hash as Sha256; -use bitcoin::hash_types::{Txid, BlockHash}; +use bitcoin::hashes::Hash; use bitcoin::ecdsa::Signature as BitcoinSignature; -use bitcoin::secp256k1::{self, SecretKey, PublicKey, Secp256k1, ecdsa::Signature}; +use bitcoin::secp256k1::{self, ecdsa::Signature, PublicKey, Secp256k1, SecretKey}; +use crate::chain; +use crate::chain::chaininterface::{ + BroadcasterInterface, ConfirmationTarget, FeeEstimator, LowerBoundedFeeEstimator, +}; +use crate::chain::onchaintx::{ClaimEvent, FeerateStrategy, OnchainTxHandler}; +use crate::chain::package::{ + CounterpartyOfferedHTLCOutput, CounterpartyReceivedHTLCOutput, HolderFundingOutput, + HolderHTLCOutput, PackageSolvingData, PackageTemplate, RevokedHTLCOutput, RevokedOutput, +}; +use crate::chain::transaction::{OutPoint, TransactionData}; +use crate::chain::Filter; +use crate::chain::{BestBlock, WatchedOutput}; +use crate::events::bump_transaction::{AnchorDescriptor, BumpTransactionEvent}; +use crate::events::{ClosureReason, Event, EventHandler, ReplayEvent}; +use crate::ln::chan_utils::{ + self, ChannelTransactionParameters, CommitmentTransaction, CounterpartyCommitmentSecrets, + HTLCClaim, HTLCOutputInCommitment, HolderCommitmentTransaction, +}; use crate::ln::channel::INITIAL_COMMITMENT_NUMBER; +use crate::ln::channel_keys::{ + DelayedPaymentBasepoint, DelayedPaymentKey, HtlcBasepoint, HtlcKey, RevocationBasepoint, + RevocationKey, +}; +use crate::ln::channelmanager::{HTLCSource, PaymentClaimDetails, SentHTLCId}; +use crate::ln::msgs::DecodeError; use crate::ln::types::ChannelId; +use crate::sign::{ + ecdsa::EcdsaChannelSigner, ChannelDerivationParameters, DelayedPaymentOutputDescriptor, + EntropySource, HTLCDescriptor, SignerProvider, SpendableOutputDescriptor, + StaticPaymentOutputDescriptor, +}; use crate::types::features::ChannelTypeFeatures; use crate::types::payment::{PaymentHash, PaymentPreimage}; -use crate::ln::msgs::DecodeError; -use crate::ln::channel_keys::{DelayedPaymentKey, DelayedPaymentBasepoint, HtlcBasepoint, HtlcKey, RevocationKey, RevocationBasepoint}; -use crate::ln::chan_utils::{self,CommitmentTransaction, CounterpartyCommitmentSecrets, HTLCOutputInCommitment, HTLCClaim, ChannelTransactionParameters, HolderCommitmentTransaction}; -use crate::ln::channelmanager::{HTLCSource, SentHTLCId, PaymentClaimDetails}; -use crate::chain; -use crate::chain::{BestBlock, WatchedOutput}; -use crate::chain::chaininterface::{BroadcasterInterface, ConfirmationTarget, FeeEstimator, LowerBoundedFeeEstimator}; -use crate::chain::transaction::{OutPoint, TransactionData}; -use crate::sign::{ChannelDerivationParameters, HTLCDescriptor, SpendableOutputDescriptor, StaticPaymentOutputDescriptor, DelayedPaymentOutputDescriptor, ecdsa::EcdsaChannelSigner, SignerProvider, EntropySource}; -use crate::chain::onchaintx::{ClaimEvent, FeerateStrategy, OnchainTxHandler}; -use crate::chain::package::{CounterpartyOfferedHTLCOutput, CounterpartyReceivedHTLCOutput, HolderFundingOutput, HolderHTLCOutput, PackageSolvingData, PackageTemplate, RevokedOutput, RevokedHTLCOutput}; -use crate::chain::Filter; +use crate::util::byte_utils; use crate::util::logger::{Logger, Record}; use crate::util::persist::MonitorName; -use crate::util::ser::{Readable, ReadableArgs, RequiredWrapper, MaybeReadable, UpgradableRequired, Writer, Writeable, U48}; -use crate::util::byte_utils; -use crate::events::{ClosureReason, Event, EventHandler, ReplayEvent}; -use crate::events::bump_transaction::{AnchorDescriptor, BumpTransactionEvent}; +use crate::util::ser::{ + MaybeReadable, Readable, ReadableArgs, RequiredWrapper, UpgradableRequired, Writeable, Writer, + U48, +}; #[allow(unused_imports)] use crate::prelude::*; -use core::{cmp, mem}; use crate::io::{self, Error}; +use crate::sync::{LockTestExt, Mutex}; use core::ops::Deref; -use crate::sync::{Mutex, LockTestExt}; +use core::{cmp, mem}; /// An update generated by the underlying channel itself which contains some new information the /// [`ChannelMonitor`] should be made aware of. @@ -117,6 +133,7 @@ impl Writeable for ChannelMonitorUpdate { } } impl Readable for ChannelMonitorUpdate { + #[rustfmt::skip] fn read(r: &mut R) -> Result { let _ver = read_ver_prefix!(r, SERIALIZATION_VERSION); let update_id: u64 = Readable::read(r)?; @@ -305,6 +322,7 @@ impl_writeable_tlv_based!(HolderSignedTx, { }); // Matches the serialization of `HolderSignedTx` for backwards compatibility reasons. +#[rustfmt::skip] fn write_legacy_holder_commitment_data( writer: &mut W, commitment_tx: &HolderCommitmentTransaction, htlc_data: &CommitmentHTLCData, ) -> Result<(), io::Error> { @@ -384,6 +402,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 @@ -429,6 +448,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 { @@ -480,9 +500,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 { @@ -532,6 +550,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; @@ -624,6 +643,7 @@ pub(crate) enum ChannelMonitorUpdateStep { } impl ChannelMonitorUpdateStep { + #[rustfmt::skip] fn variant_name(&self) -> &'static str { match self { ChannelMonitorUpdateStep::LatestHolderCommitmentTXInfo { .. } => "LatestHolderCommitmentTXInfo", @@ -834,6 +854,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, .. }| @@ -879,6 +900,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; @@ -914,7 +936,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) @@ -937,6 +962,7 @@ impl CommitmentHTLCData { impl TryFrom for CommitmentHTLCData { type Error = (); + #[rustfmt::skip] fn try_from(value: HolderSignedTx) -> Result { // HolderSignedTx tracks all HTLCs included in the commitment (dust included). For // `HolderCommitment`, we'll need to extract the dust HTLCs and their sources, and non-dust @@ -987,7 +1013,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 @@ -1174,6 +1201,7 @@ pub(crate) struct ChannelMonitorImpl { // holding mutable references to `self`. Unfortunately, if these were turned into helper functions, // we'd be unable to mutate `self` while holding an immutable iterator (specifically, returned from // a function) over `self`. +#[rustfmt::skip] macro_rules! holder_commitment_htlcs { ($self: expr, CURRENT) => { $self.funding.current_holder_commitment_tx.nondust_htlcs().iter() @@ -1217,7 +1245,11 @@ macro_rules! holder_commitment_htlcs { /// 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 @@ -1240,6 +1272,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); @@ -1299,6 +1332,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])?; @@ -1439,6 +1473,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 { @@ -1497,14 +1532,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; @@ -1513,11 +1554,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()); @@ -1535,6 +1582,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, @@ -1682,7 +1730,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); @@ -1694,6 +1743,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, @@ -1709,6 +1759,7 @@ impl ChannelMonitor { } #[cfg(test)] + #[rustfmt::skip] fn provide_latest_holder_commitment_tx( &self, holder_commitment_tx: HolderCommitmentTransaction, htlc_outputs: Vec<(HTLCOutputInCommitment, Option, Option)>, @@ -1726,6 +1777,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, @@ -1752,11 +1804,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, @@ -1798,6 +1846,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() @@ -1806,6 +1855,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, @@ -1850,8 +1900,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)) } @@ -1860,11 +1915,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 }) } @@ -1914,7 +1973,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) } @@ -1935,6 +1996,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) } @@ -1975,6 +2037,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 ) @@ -1994,7 +2057,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) @@ -2011,6 +2076,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, @@ -2033,6 +2099,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, @@ -2058,6 +2125,7 @@ impl ChannelMonitor { /// blocks. See [`chain::Confirm`] for calling expectations. /// /// [`block_connected`]: Self::block_connected + #[rustfmt::skip] pub fn transactions_confirmed( &self, header: &Header, @@ -2085,6 +2153,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, @@ -2111,6 +2180,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, @@ -2133,6 +2203,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 @@ -2156,6 +2227,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, ) @@ -2177,13 +2249,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, ) @@ -2222,6 +2294,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; @@ -2251,6 +2324,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; @@ -2320,6 +2394,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 @@ -2520,6 +2595,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(); @@ -2542,6 +2618,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 { @@ -2735,6 +2812,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 @@ -2768,6 +2846,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 @@ -2789,6 +2868,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 { @@ -2848,7 +2928,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() } } @@ -2960,6 +3042,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() } @@ -2967,6 +3050,7 @@ pub fn deliberately_bogus_accepted_htlc_witness() -> Vec> { impl ChannelMonitorImpl { /// Gets the [`ConfirmationTarget`] we should use when selecting feerates for channel closure /// transactions for this channel right now. + #[rustfmt::skip] fn closure_conf_target(&self) -> ConfirmationTarget { // Treat the sweep as urgent as long as there is at least one HTLC which is pending on a // valid commitment transaction. @@ -2993,6 +3077,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"); @@ -3054,6 +3139,7 @@ impl ChannelMonitorImpl { Ok(()) } + #[rustfmt::skip] fn provide_initial_counterparty_commitment_tx( &mut self, commitment_tx: CommitmentTransaction, logger: &WithChannelMonitor, ) where L::Target: Logger { @@ -3072,6 +3158,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>)>, @@ -3116,6 +3203,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, mut holder_commitment_tx: HolderCommitmentTransaction, htlc_outputs: Vec<(HTLCOutputInCommitment, Option, Option)>, @@ -3206,6 +3294,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, @@ -3240,6 +3329,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); @@ -3304,6 +3394,7 @@ impl ChannelMonitorImpl { } } + #[rustfmt::skip] fn generate_claimable_outpoints_and_watch_outputs(&mut self, reason: ClosureReason) -> (Vec, Vec) { let holder_commitment_tx = &self.funding.current_holder_commitment_tx; let funding_outp = HolderFundingOutput::build( @@ -3348,6 +3439,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 ) @@ -3364,6 +3456,7 @@ impl ChannelMonitorImpl { ); } + #[rustfmt::skip] fn update_monitor( &mut self, updates: &ChannelMonitorUpdate, broadcaster: &B, fee_estimator: &F, logger: &WithChannelMonitor ) -> Result<(), ()> @@ -3518,6 +3611,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") @@ -3550,6 +3644,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()); @@ -3632,6 +3727,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, @@ -3642,6 +3738,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. @@ -3676,6 +3773,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 { @@ -3726,6 +3824,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 { @@ -3737,6 +3836,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 { @@ -3853,6 +3953,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(); @@ -3933,6 +4034,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 { @@ -3977,6 +4079,7 @@ impl ChannelMonitorImpl { (claimable_outpoints, outputs_to_watch) } + #[rustfmt::skip] fn get_broadcasted_holder_htlc_descriptors( &self, holder_tx: &HolderCommitmentTransaction, ) -> Vec { @@ -4018,6 +4121,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)>) { @@ -4051,6 +4155,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(); @@ -4071,11 +4176,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; @@ -4095,8 +4206,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, "latest holder", commitment_txid, tx, height, block_hash, - holder_commitment_htlcs!(self, CURRENT_WITH_SOURCES), logger + self, + "latest holder", + commitment_txid, + tx, + height, + block_hash, + holder_commitment_htlcs!(self, CURRENT_WITH_SOURCES), + logger ); } else if let Some(holder_commitment_tx) = &self.funding.prev_holder_commitment_tx { if holder_commitment_tx.trust().txid() == commitment_txid { @@ -4106,8 +4223,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!(self, PREV_WITH_SOURCES).unwrap(), logger + self, + "previous holder", + commitment_txid, + tx, + height, + block_hash, + holder_commitment_htlcs!(self, PREV_WITH_SOURCES).unwrap(), + logger ); } } @@ -4121,6 +4244,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 { @@ -4176,6 +4300,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 { @@ -4213,6 +4338,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, @@ -4228,6 +4354,7 @@ impl ChannelMonitorImpl { self.transactions_confirmed(header, txdata, height, broadcaster, &bounded_fee_estimator, logger) } + #[rustfmt::skip] fn best_block_updated( &mut self, header: &Header, @@ -4259,6 +4386,7 @@ impl ChannelMonitorImpl { } else { Vec::new() } } + #[rustfmt::skip] fn transactions_confirmed( &mut self, header: &Header, @@ -4412,6 +4540,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, @@ -4609,6 +4738,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, @@ -4631,6 +4761,7 @@ impl ChannelMonitorImpl { self.best_block = BestBlock::new(header.prev_blockhash, height - 1); } + #[rustfmt::skip] fn transaction_unconfirmed( &mut self, txid: &Txid, @@ -4668,6 +4799,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)| { @@ -4686,6 +4818,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) { @@ -4718,6 +4851,7 @@ impl ChannelMonitorImpl { false } + #[rustfmt::skip] fn should_broadcast_holder_commitment_txn( &self, logger: &WithChannelMonitor ) -> bool where L::Target: Logger { @@ -4785,8 +4919,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); @@ -4833,6 +4970,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 { @@ -4847,6 +4985,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 { @@ -4893,31 +5032,48 @@ impl ChannelMonitorImpl { } } - if input.previous_output.txid == self.funding.current_holder_commitment_tx.trust().txid() { + if input.previous_output.txid + == self.funding.current_holder_commitment_tx.trust().txid() + { scan_commitment!( holder_commitment_htlcs!(self, CURRENT_WITH_SOURCES), - "our latest holder commitment tx", true + "our latest holder commitment tx", + true ); } - if let Some(prev_holder_commitment_tx) = self.funding.prev_holder_commitment_tx.as_ref() { + if let Some(prev_holder_commitment_tx) = self.funding.prev_holder_commitment_tx.as_ref() + { if input.previous_output.txid == prev_holder_commitment_tx.trust().txid() { scan_commitment!( holder_commitment_htlcs!(self, PREV_WITH_SOURCES).unwrap(), - "our previous holder commitment tx", true + "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, @@ -4937,10 +5093,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()), @@ -4961,7 +5120,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 @@ -4988,6 +5149,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() { @@ -5034,6 +5196,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 { @@ -5055,7 +5218,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, @@ -5094,10 +5258,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) => { @@ -5167,6 +5333,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 { () => { { @@ -5497,50 +5664,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 @@ -5632,6 +5813,7 @@ mod tests { } #[test] + #[rustfmt::skip] fn test_prune_preimages() { let secp_ctx = Secp256k1::new(); let logger = Arc::new(TestLogger::new()); @@ -5651,6 +5833,7 @@ mod tests { let dummy_source = HTLCSource::dummy(); + #[rustfmt::skip] macro_rules! preimages_slice_to_htlcs { ($preimages_slice: expr) => { { @@ -5668,6 +5851,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() @@ -5677,6 +5861,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 { @@ -5797,6 +5982,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. @@ -5806,6 +5992,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 { @@ -5939,6 +6126,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/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 1d660c86989..08695f21361 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/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 b714f76616f..0d4afadab72 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, PeerStorageKey, 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,15 +1655,21 @@ 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 get_peer_storage_key(&self) -> PeerStorageKey { 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()); @@ -1757,6 +1792,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 @@ -1840,6 +1876,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"); @@ -1936,15 +1973,21 @@ 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 get_peer_storage_key(&self) -> PeerStorageKey { 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()); @@ -1983,6 +2026,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(); @@ -2206,6 +2250,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) @@ -2372,6 +2417,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 53c090388af..0f7c44da441 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::*; @@ -94,18 +95,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 @@ -116,6 +115,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; @@ -124,6 +124,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; @@ -147,6 +148,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 { @@ -214,6 +216,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; @@ -222,6 +225,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) + @@ -229,6 +233,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); @@ -258,6 +263,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 { @@ -312,6 +318,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 { @@ -324,11 +331,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) { @@ -383,6 +392,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 { @@ -418,7 +428,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()); @@ -434,6 +446,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 { @@ -533,6 +546,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(), @@ -545,7 +559,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, @@ -562,11 +579,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()) @@ -584,7 +602,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 { @@ -640,6 +660,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 { @@ -717,19 +738,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[..] { @@ -748,6 +773,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)]; @@ -765,6 +791,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 { @@ -777,6 +804,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 { @@ -799,6 +827,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, @@ -843,7 +872,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(); @@ -881,6 +912,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) @@ -894,6 +926,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() @@ -903,7 +936,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)); @@ -967,6 +1002,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 { @@ -979,6 +1015,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 { @@ -987,6 +1024,7 @@ impl ChannelTransactionParameters { } } + #[rustfmt::skip] pub(crate) fn make_funding_redeemscript(&self) -> ScriptBuf { make_funding_redeemscript( &self.holder_pubkeys.funding_pubkey, @@ -1000,6 +1038,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(), @@ -1032,6 +1071,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, { @@ -1050,6 +1090,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); @@ -1135,6 +1176,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 } @@ -1144,6 +1186,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 } } @@ -1177,6 +1220,7 @@ pub struct HolderCommitmentTransaction { impl Deref for HolderCommitmentTransaction { type Target = CommitmentTransaction; + #[rustfmt::skip] fn deref(&self) -> &Self::Target { &self.inner } } @@ -1197,6 +1241,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()); @@ -1234,6 +1279,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, @@ -1243,6 +1289,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(); @@ -1282,13 +1329,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) } @@ -1296,8 +1347,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) } @@ -1319,6 +1373,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, @@ -1358,6 +1413,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, @@ -1404,6 +1460,7 @@ pub struct TrustedClosingTransaction<'a> { impl<'a> Deref for TrustedClosingTransaction<'a> { type Target = ClosingTransaction; + #[rustfmt::skip] fn deref(&self) -> &Self::Target { self.inner } } @@ -1416,6 +1473,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) @@ -1423,7 +1481,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) } @@ -1455,6 +1516,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 && @@ -1472,6 +1534,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, { @@ -1491,6 +1554,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), @@ -1529,6 +1593,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); @@ -1575,6 +1640,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)) @@ -1586,6 +1652,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); @@ -1627,6 +1694,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, @@ -1636,6 +1704,7 @@ impl CommitmentTransaction { } } + #[rustfmt::skip] fn build_outputs_and_htlcs( keys: &TxCreationKeys, to_broadcaster_value_sat: Amount, @@ -1690,6 +1759,7 @@ impl CommitmentTransaction { outputs } + #[rustfmt::skip] fn insert_non_htlc_outputs( keys: &TxCreationKeys, to_broadcaster_value_sat: Amount, @@ -1749,6 +1819,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); @@ -1765,6 +1836,7 @@ impl CommitmentTransaction { txouts } + #[rustfmt::skip] fn build_sorted_htlc_outputs( keys: &TxCreationKeys, nondust_htlcs: &mut Vec, @@ -1800,6 +1872,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(); @@ -1876,6 +1949,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; @@ -1904,6 +1978,7 @@ pub struct TrustedCommitmentTransaction<'a> { impl<'a> Deref for TrustedCommitmentTransaction<'a> { type Target = CommitmentTransaction; + #[rustfmt::skip] fn deref(&self) -> &Self::Target { self.inner } } @@ -1934,6 +2009,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, @@ -1965,6 +2041,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, @@ -1989,6 +2066,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(())?; @@ -2017,7 +2095,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 @@ -2027,8 +2104,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(); @@ -2052,18 +2128,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::*; @@ -2074,10 +2155,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]; @@ -2110,6 +2192,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, @@ -2117,12 +2200,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(); @@ -2206,6 +2292,7 @@ mod tests { } #[test] + #[rustfmt::skip] fn test_building_to_local_justice_tx() { let builder = TestCommitmentTxBuilder::new(); @@ -2246,6 +2333,7 @@ mod tests { let mut secrets: Vec<[u8; 32]> = Vec::new(); let mut monitor; + #[rustfmt::skip] macro_rules! test_secrets { () => { let mut idx = 281474976710655; @@ -2264,42 +2352,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!(); } @@ -2310,13 +2438,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()); } { @@ -2325,23 +2465,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()); } { @@ -2350,23 +2512,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()); } { @@ -2375,43 +2559,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()); } { @@ -2420,33 +2646,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()); } { @@ -2455,43 +2713,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()); } { @@ -2500,43 +2800,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()); } { @@ -2545,43 +2887,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()); } } @@ -2589,6 +2973,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/channel.rs b/lightning/src/ln/channel.rs index f2da485b67a..c779d89ff35 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::{btree_map, 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, @@ -1045,11 +1148,7 @@ impl HTLCCandidate { /// A return value enum for get_update_fulfill_htlc. See UpdateFulfillCommitFetch variants for /// description enum UpdateFulfillFetch { - NewClaim { - monitor_update: ChannelMonitorUpdate, - htlc_value_msat: u64, - update_blocked: bool, - }, + NewClaim { monitor_update: ChannelMonitorUpdate, htlc_value_msat: u64, update_blocked: bool }, DuplicateClaim {}, } @@ -1154,6 +1253,7 @@ enum HolderCommitmentPoint { } impl HolderCommitmentPoint { + #[rustfmt::skip] pub fn new(signer: &ChannelSignerType, secp_ctx: &Secp256k1) -> Option where SP::Target: SignerProvider { @@ -1167,6 +1267,7 @@ impl HolderCommitmentPoint { Some(point) } + #[rustfmt::skip] pub fn is_available(&self) -> bool { if let HolderCommitmentPoint::Available { .. } = self { true } else { false } } @@ -1197,6 +1298,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 +1328,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 +1417,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 +1437,8 @@ enum ChannelPhase where SP::Target: SignerProvider { Funded(FundedChannel), } -impl Channel where +impl Channel +where SP::Target: SignerProvider, ::EcdsaSigner: ChannelSigner, { @@ -1382,6 +1493,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 +1533,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 +1570,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 +1616,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 +1635,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 { @@ -1555,6 +1671,7 @@ impl Channel where } } + #[rustfmt::skip] pub fn maybe_handle_error_without_close( &mut self, chain_hash: ChainHash, fee_estimator: &LowerBoundedFeeEstimator, logger: &L, user_config: &UserConfig, their_features: &InitFeatures, @@ -1587,6 +1704,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> @@ -1619,10 +1737,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); @@ -1632,11 +1750,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> @@ -1693,6 +1814,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 @@ -1714,6 +1836,7 @@ where SP::Target: SignerProvider, ::EcdsaSigner: ChannelSigner, { + #[rustfmt::skip] fn from(channel: OutboundV1Channel) -> Self { Channel { phase: ChannelPhase::UnfundedOutboundV1(channel), @@ -1726,6 +1849,7 @@ where SP::Target: SignerProvider, ::EcdsaSigner: ChannelSigner, { + #[rustfmt::skip] fn from(channel: InboundV1Channel) -> Self { Channel { phase: ChannelPhase::UnfundedInboundV1(channel), @@ -1738,6 +1862,7 @@ where SP::Target: SignerProvider, ::EcdsaSigner: ChannelSigner, { + #[rustfmt::skip] fn from(channel: PendingV2Channel) -> Self { Channel { phase: ChannelPhase::UnfundedV2(channel), @@ -1750,6 +1875,7 @@ where SP::Target: SignerProvider, ::EcdsaSigner: ChannelSigner, { + #[rustfmt::skip] fn from(channel: FundedChannel) -> Self { Channel { phase: ChannelPhase::Funded(channel), @@ -1780,6 +1906,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) @@ -1837,6 +1964,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; @@ -1879,10 +2007,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; @@ -1911,6 +2041,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) @@ -1944,7 +2075,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 @@ -1986,7 +2120,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, @@ -2122,9 +2255,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, @@ -2225,7 +2358,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; @@ -2236,6 +2372,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 { @@ -2258,6 +2395,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, @@ -2351,7 +2489,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 } @@ -2377,7 +2518,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 } @@ -2403,7 +2547,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 } @@ -2424,6 +2571,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 @@ -2437,12 +2585,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, @@ -2527,6 +2679,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( @@ -2538,6 +2691,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( @@ -2549,6 +2703,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( @@ -2560,6 +2715,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( @@ -2571,6 +2727,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, @@ -2593,6 +2750,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> @@ -2687,7 +2845,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, @@ -3030,6 +3192,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, @@ -3288,12 +3451,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() && @@ -3302,6 +3467,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(_) => @@ -3319,6 +3485,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) => @@ -3341,6 +3508,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, @@ -3368,6 +3536,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 @@ -3451,6 +3620,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 } @@ -3475,6 +3645,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, @@ -3665,9 +3836,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) } @@ -3741,6 +3915,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 || @@ -3769,11 +3944,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()) @@ -3786,6 +3963,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, @@ -3899,6 +4077,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; @@ -3999,6 +4178,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 { @@ -4022,6 +4202,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 { @@ -4034,6 +4215,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); @@ -4183,6 +4365,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, @@ -4287,6 +4470,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() { @@ -4337,6 +4521,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() { @@ -4379,6 +4564,7 @@ impl ChannelContext where SP::Target: SignerProvider { outbound_details } + #[rustfmt::skip] fn get_available_balances_for_scope( &self, funding: &FundingScope, fee_estimator: &LowerBoundedFeeEstimator, ) -> AvailableBalances @@ -4541,6 +4727,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 { @@ -4647,6 +4834,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 { @@ -4733,6 +4921,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(), @@ -4759,6 +4948,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) @@ -4781,6 +4971,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 @@ -4839,6 +5030,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, @@ -4878,6 +5070,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, user_config: &UserConfig, their_features: &InitFeatures, @@ -4942,6 +5135,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 || @@ -4951,6 +5145,7 @@ impl ChannelContext where SP::Target: SignerProvider { } } + #[rustfmt::skip] fn get_initial_counterparty_commitment_signature( &self, funding: &FundingScope, logger: &L ) -> Result @@ -4980,6 +5175,7 @@ impl ChannelContext where SP::Target: SignerProvider { } } + #[rustfmt::skip] fn get_initial_commitment_signed( &mut self, funding: &FundingScope, logger: &L ) -> Result @@ -5025,7 +5221,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) @@ -5041,7 +5237,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 { @@ -5060,6 +5258,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)) @@ -5069,7 +5268,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)) } @@ -5091,6 +5292,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, @@ -5123,6 +5325,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, @@ -5196,7 +5399,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, @@ -5241,6 +5447,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 } } @@ -5253,6 +5460,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, @@ -5264,6 +5472,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, @@ -5287,10 +5496,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 @@ -5339,6 +5550,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 @@ -5366,6 +5578,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()); @@ -5422,6 +5635,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 { @@ -5436,6 +5650,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, @@ -5550,6 +5765,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, @@ -5593,8 +5809,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?")) } @@ -5604,14 +5824,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 @@ -5706,6 +5930,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 @@ -5788,6 +6013,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 { @@ -5908,6 +6134,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 { @@ -5932,6 +6159,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())); @@ -5946,6 +6174,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())); @@ -5961,6 +6190,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())); @@ -5976,6 +6206,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> @@ -6013,6 +6244,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 { @@ -6030,6 +6262,7 @@ impl FundedChannel where self.commitment_signed_update_monitor(updates, logger) } + #[rustfmt::skip] pub fn commitment_signed_batch(&mut self, batch: Vec, logger: &L) -> Result, ChannelError> where L::Target: Logger { @@ -6075,6 +6308,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())); @@ -6092,6 +6326,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 { @@ -6212,6 +6447,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)>) @@ -6224,6 +6460,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)>) @@ -6362,6 +6599,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> @@ -6577,6 +6815,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 { @@ -6651,6 +6890,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 { @@ -6738,9 +6978,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?"); @@ -6753,6 +6995,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 @@ -6822,6 +7065,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() { @@ -6917,6 +7161,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)>, @@ -6934,6 +7179,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 @@ -7036,7 +7282,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. @@ -7056,6 +7304,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 { @@ -7089,6 +7338,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..."); @@ -7185,6 +7435,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); @@ -7223,6 +7474,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(); @@ -7304,6 +7556,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()); @@ -7321,6 +7574,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 @@ -7355,6 +7609,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)); @@ -7603,6 +7858,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 @@ -7664,6 +7920,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 { @@ -7675,6 +7932,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> @@ -7722,6 +7980,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; @@ -7749,6 +8008,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> @@ -7860,7 +8120,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 @@ -7883,6 +8145,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 @@ -7911,6 +8174,7 @@ impl FundedChannel where }) } + #[rustfmt::skip] fn shutdown_result_coop_close(&self) -> ShutdownResult { let closure_reason = if self.initiated_shutdown() { ClosureReason::LocallyInitiatedCooperativeClosure @@ -7933,6 +8197,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> @@ -8002,6 +8267,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 { @@ -8087,6 +8353,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> { @@ -8105,6 +8372,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> { @@ -8120,6 +8388,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> @@ -8202,6 +8471,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 } } @@ -8216,6 +8486,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, @@ -8247,6 +8518,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 @@ -8254,6 +8526,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, @@ -8262,6 +8535,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(); @@ -8278,7 +8552,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 { @@ -8303,6 +8579,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!( @@ -8337,6 +8614,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(_)) @@ -8379,6 +8657,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 { @@ -8446,6 +8725,7 @@ impl FundedChannel where self.get_channel_ready(logger) } + #[rustfmt::skip] fn get_channel_ready( &mut self, logger: &L ) -> Option where L::Target: Logger { @@ -8466,6 +8746,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 @@ -8555,6 +8836,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 @@ -8566,6 +8848,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 @@ -8643,6 +8926,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 @@ -8681,6 +8965,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 { @@ -8712,6 +8997,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 @@ -8785,6 +9071,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 { @@ -8821,6 +9108,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 @@ -8851,6 +9139,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 { @@ -8864,6 +9153,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` @@ -8885,6 +9175,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); @@ -8940,6 +9231,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, @@ -8992,8 +9284,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 @@ -9010,6 +9302,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 @@ -9077,6 +9370,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, @@ -9110,6 +9404,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, @@ -9216,6 +9511,7 @@ impl FundedChannel where Ok(Some(res)) } + #[rustfmt::skip] pub(super) fn get_available_balances( &self, fee_estimator: &LowerBoundedFeeEstimator, ) -> AvailableBalances @@ -9236,6 +9532,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 @@ -9310,6 +9607,7 @@ impl FundedChannel where monitor_update } + #[rustfmt::skip] fn build_commitment_no_state_update( &self, funding: &FundingScope, logger: &L, ) -> (Vec<(HTLCOutputInCommitment, Option<&HTLCSource>)>, CommitmentTransaction) @@ -9357,6 +9655,7 @@ impl FundedChannel where .collect::, ChannelError>>() } + #[rustfmt::skip] fn send_commitment_no_state_update_for_funding( &self, funding: &FundingScope, logger: &L, ) -> Result @@ -9425,6 +9724,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, @@ -9447,6 +9747,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, @@ -9463,6 +9764,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> @@ -9562,6 +9864,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| { @@ -9574,6 +9877,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 @@ -9586,6 +9890,7 @@ impl FundedChannel where } #[cfg(any(test, fuzzing))] + #[rustfmt::skip] pub fn propose_quiescence( &mut self, logger: &L, ) -> Result, ChannelError> @@ -9614,6 +9919,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, @@ -9662,6 +9968,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 { @@ -9772,6 +10079,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. @@ -9790,7 +10098,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, @@ -9800,8 +10111,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, @@ -9856,6 +10171,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, @@ -9900,6 +10216,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() { @@ -9939,6 +10256,7 @@ impl OutboundV1Channel where SP::Target: SignerProvider { /// If we receive an error message, it may only be a rejection of the channel type we tried, /// 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. + #[rustfmt::skip] pub(crate) fn maybe_handle_error_without_close( &mut self, chain_hash: ChainHash, fee_estimator: &LowerBoundedFeeEstimator, logger: &L, user_config: &UserConfig, their_features: &InitFeatures, @@ -9954,11 +10272,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 { @@ -10016,6 +10336,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 @@ -10028,6 +10349,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)> @@ -10074,6 +10396,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 { @@ -10108,7 +10431,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, @@ -10117,6 +10443,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 @@ -10151,9 +10478,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, @@ -10211,9 +10542,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?"); } @@ -10235,6 +10567,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 { @@ -10284,11 +10617,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)> @@ -10351,6 +10688,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 { @@ -10370,7 +10708,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, @@ -10381,8 +10722,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, @@ -10455,6 +10800,7 @@ impl PendingV2Channel where SP::Target: SignerProvider { /// If we receive an error message, it may only be a rejection of the channel type we tried, /// 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. + #[rustfmt::skip] pub(crate) fn maybe_handle_error_without_close( &mut self, chain_hash: ChainHash, fee_estimator: &LowerBoundedFeeEstimator, user_config: &UserConfig, their_features: &InitFeatures, @@ -10468,6 +10814,7 @@ impl PendingV2Channel where SP::Target: SignerProvider { 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?"); @@ -10526,6 +10873,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, @@ -10633,6 +10981,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?"); @@ -10705,6 +11054,7 @@ impl PendingV2Channel where SP::Target: SignerProvider { // Unfunded channel utilities +#[rustfmt::skip] pub(super) 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 @@ -10742,7 +11092,6 @@ pub(super) fn get_initial_channel_type(config: &UserConfig, their_features: &Ini 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 @@ -10791,7 +11140,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. @@ -11170,11 +11523,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); @@ -11815,6 +12170,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; @@ -11829,50 +12185,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::chain::chaininterface::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::{ + 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::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, NodeFeatures}; - #[cfg(ldk_test_vectors)] - use crate::types::features::ChannelTypeFeatures; 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::LowerBoundedFeeEstimator; - 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}; + #[cfg(ldk_test_vectors)] + use crate::types::features::ChannelTypeFeatures; + use crate::types::features::{ChannelFeatures, 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::{self, OnGetShutdownScriptpubkey, TestKeysInterface, TestFeeEstimator, TestLogger}; - use bitcoin::secp256k1::{Secp256k1, ecdsa::Signature}; - use bitcoin::secp256k1::ffi::Signature as FFISignature; - use bitcoin::secp256k1::{SecretKey,PublicKey}; + use crate::util::test_utils::{ + self, OnGetShutdownScriptpubkey, TestFeeEstimator, TestKeysInterface, TestLogger, + }; + 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; @@ -11886,6 +12252,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, @@ -11897,6 +12264,7 @@ mod tests { } impl EntropySource for Keys { + #[rustfmt::skip] fn get_secure_random_bytes(&self) -> [u8; 32] { [0; 32] } } @@ -11913,6 +12281,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(); @@ -11920,6 +12289,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(); @@ -11928,12 +12298,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(); @@ -11964,6 +12336,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 fee_est = TestFeeEstimator::new(original_fee); @@ -11986,6 +12359,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. @@ -12076,6 +12450,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 @@ -12125,6 +12500,7 @@ mod tests { } #[test] + #[rustfmt::skip] fn channel_reestablish_no_updates() { let test_est = TestFeeEstimator::new(15000); let feeest = LowerBoundedFeeEstimator::new(&test_est); @@ -12183,6 +12559,7 @@ mod tests { } #[test] + #[rustfmt::skip] fn test_configured_holder_max_htlc_value_in_flight() { let test_est = TestFeeEstimator::new(15000); let feeest = LowerBoundedFeeEstimator::new(&test_est); @@ -12257,6 +12634,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 @@ -12278,6 +12656,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 test_est = TestFeeEstimator::new(15000); let fee_est = LowerBoundedFeeEstimator::new(&test_est); @@ -12316,6 +12695,7 @@ mod tests { } #[test] + #[rustfmt::skip] fn channel_update() { let test_est = TestFeeEstimator::new(15000); let feeest = LowerBoundedFeeEstimator::new(&test_est); @@ -12392,6 +12772,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. @@ -12521,6 +12902,7 @@ mod tests { #[cfg(ldk_test_vectors)] #[test] + #[rustfmt::skip] fn outbound_commitment_test() { assert!(cfg!(not(feature = "grind_signatures"))); @@ -12616,6 +12998,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 } ), * @@ -13253,6 +13636,7 @@ mod tests { } #[test] + #[rustfmt::skip] fn test_per_commitment_secret_gen() { // Test vectors from BOLT 3 Appendix D: @@ -13277,6 +13661,7 @@ mod tests { } #[test] + #[rustfmt::skip] fn test_key_derivation() { // Test vectors from BOLT 3 Appendix E: let secp_ctx = Secp256k1::new(); @@ -13301,6 +13686,7 @@ mod tests { } #[test] + #[rustfmt::skip] fn test_waiting_for_batch() { let test_est = TestFeeEstimator::new(15000); let feeest = LowerBoundedFeeEstimator::new(&test_est); @@ -13431,6 +13817,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; @@ -13467,6 +13854,7 @@ mod tests { } #[cfg(splicing)] + #[rustfmt::skip] fn funding_input_sats(input_value_sats: u64) -> (TxIn, Transaction, Weight) { use crate::sign::P2WPKH_WITNESS_WEIGHT; @@ -13484,6 +13872,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/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/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 ad0a8eea2aa..60a0bb0bf76 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 1beeb3574db..28e5eb93441 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}; @@ -67,13 +68,13 @@ pub(crate) enum PendingOutboundPayment { /// Human Readable Names-originated payments should always specify an explicit amount to /// send up-front, which we track here and enforce once we receive the offer. amount_msats: u64, - payer_note: Option + payer_note: Option, }, AwaitingInvoice { 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. @@ -172,6 +173,7 @@ impl PendingOutboundPayment { attempts.count += 1; } } + #[rustfmt::skip] fn is_auto_retryable_now(&self) -> bool { match self { PendingOutboundPayment::Retryable { @@ -182,6 +184,7 @@ impl PendingOutboundPayment { _ => false, } } + #[rustfmt::skip] fn is_retryable_now(&self) -> bool { match self { PendingOutboundPayment::Retryable { retry_strategy: None, .. } => { @@ -238,6 +241,7 @@ impl PendingOutboundPayment { } } + #[rustfmt::skip] fn payment_hash(&self) -> Option { match self { PendingOutboundPayment::Legacy { .. } => None, @@ -251,6 +255,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 { @@ -268,6 +273,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, .. } => { @@ -295,6 +301,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 } | @@ -328,6 +335,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 } | @@ -360,6 +368,7 @@ impl PendingOutboundPayment { insert_res } + #[rustfmt::skip] pub(super) fn remaining_parts(&self) -> usize { match self { PendingOutboundPayment::Legacy { session_privs } | @@ -407,6 +416,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, .. }) => { @@ -420,6 +430,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() { @@ -493,7 +504,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 @@ -694,6 +708,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() } } @@ -719,6 +734,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; @@ -773,6 +789,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(()); } @@ -812,7 +829,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, @@ -829,6 +848,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, @@ -849,6 +869,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, @@ -873,6 +894,7 @@ impl OutboundPayments { .map(|()| payment_hash) } + #[rustfmt::skip] pub(super) fn pay_for_bolt11_invoice( &self, invoice: &Bolt11Invoice, payment_id: PaymentId, amount_msats: Option, @@ -917,6 +939,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 >( @@ -962,6 +985,7 @@ impl OutboundPayments { ) } + #[rustfmt::skip] fn send_payment_for_bolt12_invoice_internal< R: Deref, ES: Deref, NS: Deref, NL: Deref, IH, SP, L: Deref >( @@ -1073,6 +1097,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, @@ -1160,6 +1185,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 >( @@ -1199,6 +1225,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, @@ -1256,6 +1283,7 @@ impl OutboundPayments { }); } + #[rustfmt::skip] pub(super) fn needs_abandon(&self) -> bool { let outbounds = self.pending_outbound_payments.lock().unwrap(); outbounds.iter().any(|(_, pmt)| @@ -1263,6 +1291,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>, @@ -1317,6 +1346,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, @@ -1361,6 +1391,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, @@ -1410,6 +1441,7 @@ impl OutboundPayments { } } + #[rustfmt::skip] macro_rules! abandon_with_entry { ($payment: expr, $reason: expr) => { $payment.get_mut().mark_abandoned($reason); @@ -1521,6 +1553,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, @@ -1583,6 +1616,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, @@ -1618,6 +1652,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 ) { @@ -1631,6 +1666,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 @@ -1694,7 +1730,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, .. } => { @@ -1705,6 +1741,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 @@ -1712,6 +1749,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, @@ -1732,6 +1770,7 @@ impl OutboundPayments { } } + #[rustfmt::skip] fn create_pending_payment( payment_hash: PaymentHash, recipient_onion: RecipientOnionFields, keysend_preimage: Option, invoice_request: Option, @@ -1776,7 +1815,7 @@ impl OutboundPayments { #[cfg(feature = "dnssec")] pub(super) fn add_new_awaiting_offer( &self, payment_id: PaymentId, expiration: StaleExpiration, retry_strategy: Retry, - route_params_config: RouteParametersConfig, amount_msats: u64, payer_note: Option + route_params_config: RouteParametersConfig, amount_msats: u64, payer_note: Option, ) -> Result<(), ()> { let mut pending_outbounds = self.pending_outbound_payments.lock().unwrap(); match pending_outbounds.entry(payment_id) { @@ -1796,6 +1835,7 @@ impl OutboundPayments { } #[cfg(feature = "dnssec")] + #[rustfmt::skip] pub(super) fn params_for_payment_awaiting_offer(&self, payment_id: PaymentId) -> Result<(u64, Option), ()> { match self.pending_outbound_payments.lock().unwrap().entry(payment_id) { hash_map::Entry::Occupied(entry) => match entry.get() { @@ -1807,6 +1847,7 @@ impl OutboundPayments { } #[cfg(feature = "dnssec")] + #[rustfmt::skip] pub(super) fn received_offer( &self, payment_id: PaymentId, retryable_invoice_request: Option, ) -> Result<(), ()> { @@ -1832,7 +1873,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) { @@ -1853,6 +1895,7 @@ impl OutboundPayments { } } + #[rustfmt::skip] pub(super) fn mark_invoice_received( &self, invoice: &Bolt12Invoice, payment_id: PaymentId ) -> Result<(), Bolt12PaymentError> { @@ -1864,6 +1907,7 @@ impl OutboundPayments { }) } + #[rustfmt::skip] fn mark_invoice_received_and_get_details( &self, invoice: &Bolt12Invoice, payment_id: PaymentId ) -> Result<(PaymentHash, Retry, RouteParametersConfig, bool), Bolt12PaymentError> { @@ -1898,6 +1942,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>, @@ -2012,6 +2057,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, @@ -2030,6 +2076,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(_) @@ -2043,6 +2090,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, @@ -2091,6 +2139,7 @@ impl OutboundPayments { } } + #[rustfmt::skip] pub(super) fn finalize_claims(&self, sources: Vec, pending_events: &Mutex)>>) { @@ -2116,6 +2165,7 @@ impl OutboundPayments { } } + #[rustfmt::skip] pub(super) fn remove_stale_payments( &self, duration_since_epoch: Duration, pending_events: &Mutex)>>) @@ -2204,6 +2254,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, @@ -2336,6 +2387,7 @@ impl OutboundPayments { pending_retry_ev } + #[rustfmt::skip] pub(super) fn abandon_payment( &self, payment_id: PaymentId, reason: PaymentFailureReason, pending_events: &Mutex)>> @@ -2379,6 +2431,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![]; @@ -2407,11 +2460,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 { @@ -2438,11 +2492,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. @@ -2451,13 +2504,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); @@ -2466,16 +2518,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 } @@ -2598,11 +2650,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; @@ -2610,8 +2663,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; @@ -2619,6 +2677,7 @@ mod tests { use alloc::collections::VecDeque; #[test] + #[rustfmt::skip] fn test_recipient_onion_fields_with_custom_tlvs() { let onion_fields = RecipientOnionFields::spontaneous_empty(); @@ -2647,6 +2706,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(); @@ -2691,6 +2751,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(); @@ -2729,6 +2790,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(); @@ -2810,6 +2872,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()); @@ -2864,6 +2927,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()); @@ -2917,6 +2981,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()); @@ -2947,6 +3012,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)); @@ -3001,6 +3067,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)); @@ -3063,6 +3130,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)); @@ -3159,6 +3227,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 {}; @@ -3176,6 +3245,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()); @@ -3224,6 +3294,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/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/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.