From 30ceb31a89bdca3bfad7a4e2ea285fc536445a0c Mon Sep 17 00:00:00 2001 From: Joost Jager Date: Thu, 29 May 2025 15:13:14 +0200 Subject: [PATCH 1/3] Convert file-level rustfmt skip to fn level skips --- lightning/src/chain/chainmonitor.rs | 205 +++++--- lightning/src/chain/channelmonitor.rs | 322 +++++++++--- lightning/src/chain/onchaintx.rs | 72 +-- lightning/src/chain/package.rs | 125 +++-- lightning/src/ln/chan_utils.rs | 607 ++++++++++++++++++---- lightning/src/ln/channel.rs | 721 ++++++++++++++++++++------ lightning/src/ln/onion_payment.rs | 51 +- lightning/src/ln/outbound_payment.rs | 137 +++-- lightning/src/routing/router.rs | 341 +++++++++--- lightning/src/routing/scoring.rs | 263 +++++++--- lightning/src/routing/utxo.rs | 49 +- 11 files changed, 2226 insertions(+), 667 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..978c15132bc 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 { @@ -4784,6 +4918,7 @@ 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 + #[rustfmt::skip] fn is_resolving_htlc_output( &mut self, tx: &Transaction, height: u32, block_hash: &BlockHash, logger: &WithChannelMonitor, ) where L::Target: Logger { @@ -4833,6 +4968,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 +4983,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 { @@ -4988,6 +5125,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 +5172,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 +5194,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 +5234,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 +5309,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 +5640,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 +5789,7 @@ mod tests { } #[test] + #[rustfmt::skip] fn test_prune_preimages() { let secp_ctx = Secp256k1::new(); let logger = Arc::new(TestLogger::new()); @@ -5651,6 +5809,7 @@ mod tests { let dummy_source = HTLCSource::dummy(); + #[rustfmt::skip] macro_rules! preimages_slice_to_htlcs { ($preimages_slice: expr) => { { @@ -5668,6 +5827,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 +5837,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 +5958,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 +5968,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 +6102,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/chan_utils.rs b/lightning/src/ln/chan_utils.rs index 53c090388af..cae1dfacd61 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, @@ -1778,9 +1850,9 @@ impl CommitmentTransaction { // Also sort the HTLC output data in `nondust_htlcs` in the same order. // // This is insertion sort. In the worst case this is O(n^2) over 2 * 483 HTLCs in the - // channel. We expect people to transition soon to zero-fee-commitment channels, + // channel. We expect people to transition soon to zero-fee-commitment channels, // where n will be 2 * 114. - // + // // These are small numbers, and channels today rarely reach this protocol-max, if ever, // so we accept the performance tradeoff. @@ -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 bb0b8cb6620..5a250c2a385 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_update_add_htlc( &self, funding: &FundingScope, msg: &msgs::UpdateAddHTLC, fee_estimator: &LowerBoundedFeeEstimator, @@ -3872,6 +4050,7 @@ impl ChannelContext where SP::Target: SignerProvider { Ok(()) } + #[rustfmt::skip] fn validate_update_fee( &self, funding: &FundingScope, fee_estimator: &LowerBoundedFeeEstimator, msg: &msgs::UpdateFee, @@ -3894,6 +4073,7 @@ impl ChannelContext where SP::Target: SignerProvider { Ok(()) } + #[rustfmt::skip] fn validate_commitment_signed( &self, funding: &FundingScope, holder_commitment_point: &HolderCommitmentPoint, msg: &msgs::CommitmentSigned, logger: &L, @@ -4004,6 +4184,7 @@ impl ChannelContext where SP::Target: SignerProvider { }) } + #[rustfmt::skip] fn can_send_update_fee( &self, funding: &FundingScope, holder_commitment_point: &HolderCommitmentPoint, feerate_per_kw: u32, fee_estimator: &LowerBoundedFeeEstimator, logger: &L, @@ -4041,6 +4222,7 @@ impl ChannelContext where SP::Target: SignerProvider { return true; } + #[rustfmt::skip] fn can_accept_incoming_htlc( &self, funding: &FundingScope, msg: &msgs::UpdateAddHTLC, dust_exposure_limiting_feerate: u32, logger: &L, @@ -4117,6 +4299,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; @@ -4217,6 +4400,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 { @@ -4240,6 +4424,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 { @@ -4252,6 +4437,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); @@ -4401,6 +4587,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, @@ -4505,6 +4692,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() { @@ -4555,6 +4743,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() { @@ -4597,6 +4786,7 @@ impl ChannelContext where SP::Target: SignerProvider { outbound_details } + #[rustfmt::skip] fn get_available_balances_for_scope( &self, funding: &FundingScope, fee_estimator: &LowerBoundedFeeEstimator, ) -> AvailableBalances @@ -4759,6 +4949,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 { @@ -4865,6 +5056,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 { @@ -4951,6 +5143,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(), @@ -4977,6 +5170,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) @@ -4999,6 +5193,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 @@ -5057,6 +5252,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, @@ -5096,6 +5292,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, @@ -5160,6 +5357,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 || @@ -5169,6 +5367,7 @@ impl ChannelContext where SP::Target: SignerProvider { } } + #[rustfmt::skip] fn get_initial_counterparty_commitment_signature( &self, funding: &FundingScope, logger: &L ) -> Result @@ -5198,6 +5397,7 @@ impl ChannelContext where SP::Target: SignerProvider { } } + #[rustfmt::skip] fn get_initial_commitment_signed( &mut self, funding: &FundingScope, logger: &L ) -> Result @@ -5243,7 +5443,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) @@ -5259,7 +5459,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 { @@ -5278,6 +5480,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)) @@ -5287,7 +5490,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)) } @@ -5309,6 +5514,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, @@ -5341,6 +5547,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, @@ -5414,7 +5621,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, @@ -5459,6 +5669,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 } } @@ -5471,6 +5682,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, @@ -5482,6 +5694,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, @@ -5505,10 +5718,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 @@ -5557,6 +5772,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 @@ -5584,6 +5800,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()); @@ -5640,6 +5857,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 { @@ -5654,6 +5872,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, @@ -5768,6 +5987,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, @@ -5811,8 +6031,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?")) } @@ -5822,14 +6046,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 @@ -5924,6 +6152,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 @@ -6006,6 +6235,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 { @@ -6055,6 +6285,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 { @@ -6079,6 +6310,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())); @@ -6093,6 +6325,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())); @@ -6108,6 +6341,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())); @@ -6123,6 +6357,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> @@ -6160,6 +6395,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 { @@ -6177,6 +6413,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 { @@ -6222,6 +6459,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())); @@ -6239,6 +6477,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 { @@ -6359,6 +6598,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)>) @@ -6371,6 +6611,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)>) @@ -6509,6 +6750,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> @@ -6729,6 +6971,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 { @@ -6803,6 +7046,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 { @@ -6890,9 +7134,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?"); @@ -6905,6 +7151,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 @@ -6955,6 +7202,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() { @@ -7050,6 +7298,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)>, @@ -7067,6 +7316,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 @@ -7169,7 +7419,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. @@ -7189,6 +7441,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 { @@ -7216,6 +7469,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..."); @@ -7312,6 +7566,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); @@ -7350,6 +7605,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(); @@ -7431,6 +7687,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()); @@ -7448,6 +7705,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 @@ -7482,6 +7740,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)); @@ -7730,6 +7989,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 @@ -7791,6 +8051,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 { @@ -7802,6 +8063,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> @@ -7849,6 +8111,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; @@ -7876,6 +8139,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> @@ -7987,7 +8251,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 @@ -8010,6 +8276,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 @@ -8038,6 +8305,7 @@ impl FundedChannel where }) } + #[rustfmt::skip] fn shutdown_result_coop_close(&self) -> ShutdownResult { let closure_reason = if self.initiated_shutdown() { ClosureReason::LocallyInitiatedCooperativeClosure @@ -8060,6 +8328,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> @@ -8129,6 +8398,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 { @@ -8214,6 +8484,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> { @@ -8232,6 +8503,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> { @@ -8247,6 +8519,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> @@ -8269,6 +8542,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 } } @@ -8283,6 +8557,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, @@ -8314,6 +8589,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 @@ -8321,6 +8597,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, @@ -8329,6 +8606,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(); @@ -8345,7 +8623,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 { @@ -8370,6 +8650,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!( @@ -8404,6 +8685,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(_)) @@ -8446,6 +8728,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 { @@ -8513,6 +8796,7 @@ impl FundedChannel where self.get_channel_ready(logger) } + #[rustfmt::skip] fn get_channel_ready( &mut self, logger: &L ) -> Option where L::Target: Logger { @@ -8533,6 +8817,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 @@ -8622,6 +8907,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 @@ -8633,6 +8919,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 @@ -8710,6 +8997,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 @@ -8748,6 +9036,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 { @@ -8779,6 +9068,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 @@ -8852,6 +9142,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 { @@ -8888,6 +9179,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 @@ -8918,6 +9210,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 { @@ -8931,6 +9224,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` @@ -8952,6 +9246,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); @@ -9007,6 +9302,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, @@ -9059,8 +9355,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 @@ -9077,6 +9373,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 @@ -9144,6 +9441,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, @@ -9177,6 +9475,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, @@ -9278,6 +9577,7 @@ impl FundedChannel where Ok(Some(res)) } + #[rustfmt::skip] pub(super) fn get_available_balances( &self, fee_estimator: &LowerBoundedFeeEstimator, ) -> AvailableBalances @@ -9298,6 +9598,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 @@ -9372,6 +9673,7 @@ impl FundedChannel where monitor_update } + #[rustfmt::skip] fn build_commitment_no_state_update( &self, funding: &FundingScope, logger: &L, ) -> (Vec<(HTLCOutputInCommitment, Option<&HTLCSource>)>, CommitmentTransaction) @@ -9419,6 +9721,7 @@ impl FundedChannel where .collect::, ChannelError>>() } + #[rustfmt::skip] fn send_commitment_no_state_update_for_funding( &self, funding: &FundingScope, logger: &L, ) -> Result @@ -9487,6 +9790,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, @@ -9509,6 +9813,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, @@ -9525,6 +9830,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> @@ -9624,6 +9930,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| { @@ -9636,6 +9943,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 @@ -9648,6 +9956,7 @@ impl FundedChannel where } #[cfg(any(test, fuzzing))] + #[rustfmt::skip] pub fn propose_quiescence( &mut self, logger: &L, ) -> Result, ChannelError> @@ -9676,6 +9985,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, @@ -9724,6 +10034,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 { @@ -9834,6 +10145,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. @@ -9852,7 +10164,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, @@ -9862,8 +10177,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, @@ -9918,6 +10237,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, @@ -9962,6 +10282,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() { @@ -10001,6 +10322,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, @@ -10016,11 +10338,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 { @@ -10078,6 +10402,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 @@ -10090,6 +10415,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)> @@ -10136,6 +10462,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 { @@ -10170,7 +10497,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, @@ -10179,6 +10509,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 @@ -10213,9 +10544,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, @@ -10273,9 +10608,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?"); } @@ -10297,6 +10633,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 { @@ -10346,11 +10683,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)> @@ -10413,6 +10754,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 { @@ -10432,7 +10774,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, @@ -10443,8 +10788,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, @@ -10517,6 +10866,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, @@ -10530,6 +10880,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?"); @@ -10588,6 +10939,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, @@ -10695,6 +11047,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?"); @@ -10767,6 +11120,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 @@ -10804,7 +11158,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 @@ -10853,7 +11206,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. @@ -11232,11 +11589,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); @@ -11877,6 +12236,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; @@ -11891,50 +12251,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; @@ -11948,6 +12318,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, @@ -11959,6 +12330,7 @@ mod tests { } impl EntropySource for Keys { + #[rustfmt::skip] fn get_secure_random_bytes(&self) -> [u8; 32] { [0; 32] } } @@ -11975,6 +12347,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(); @@ -11982,6 +12355,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(); @@ -11990,12 +12364,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(); @@ -12026,6 +12402,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); @@ -12048,6 +12425,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. @@ -12138,6 +12516,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 @@ -12187,6 +12566,7 @@ mod tests { } #[test] + #[rustfmt::skip] fn channel_reestablish_no_updates() { let test_est = TestFeeEstimator::new(15000); let feeest = LowerBoundedFeeEstimator::new(&test_est); @@ -12245,6 +12625,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); @@ -12319,6 +12700,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 @@ -12340,6 +12722,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); @@ -12378,6 +12761,7 @@ mod tests { } #[test] + #[rustfmt::skip] fn channel_update() { let test_est = TestFeeEstimator::new(15000); let feeest = LowerBoundedFeeEstimator::new(&test_est); @@ -12454,6 +12838,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. @@ -12583,6 +12968,7 @@ mod tests { #[cfg(ldk_test_vectors)] #[test] + #[rustfmt::skip] fn outbound_commitment_test() { assert!(cfg!(not(feature = "grind_signatures"))); @@ -12678,6 +13064,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 } ), * @@ -13315,6 +13702,7 @@ mod tests { } #[test] + #[rustfmt::skip] fn test_per_commitment_secret_gen() { // Test vectors from BOLT 3 Appendix D: @@ -13339,6 +13727,7 @@ mod tests { } #[test] + #[rustfmt::skip] fn test_key_derivation() { // Test vectors from BOLT 3 Appendix E: let secp_ctx = Secp256k1::new(); @@ -13363,6 +13752,7 @@ mod tests { } #[test] + #[rustfmt::skip] fn test_waiting_for_batch() { let test_est = TestFeeEstimator::new(15000); let feeest = LowerBoundedFeeEstimator::new(&test_est); @@ -13493,6 +13883,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; @@ -13529,6 +13920,7 @@ mod tests { } #[cfg(splicing)] + #[rustfmt::skip] fn funding_input_sats(input_value_sats: u64) -> (TxIn, Transaction, Weight) { use crate::sign::P2WPKH_WITNESS_WEIGHT; @@ -13546,6 +13938,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/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/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/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/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. From 6932d3ef0ffddc1f79c55060f9126dabb20126f7 Mon Sep 17 00:00:00 2001 From: Joost Jager Date: Thu, 12 Jun 2025 20:32:56 +0200 Subject: [PATCH 2/3] Extract hex constants in test_per_commitment_storage Formatting improvement. --- lightning/src/ln/chan_utils.rs | 448 +++++++++------------------------ 1 file changed, 112 insertions(+), 336 deletions(-) diff --git a/lightning/src/ln/chan_utils.rs b/lightning/src/ln/chan_utils.rs index cae1dfacd61..13b74afdd64 100644 --- a/lightning/src/ln/chan_utils.rs +++ b/lightning/src/ln/chan_utils.rs @@ -2351,83 +2351,51 @@ mod tests { monitor = CounterpartyCommitmentSecrets::new(); secrets.clear(); + let hex = "7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc"; 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(hex).unwrap()); monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap(); test_secrets!(); + let hex = "c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964"; 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(hex).unwrap()); monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap(); test_secrets!(); + let hex = "2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8"; 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(hex).unwrap()); monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap(); test_secrets!(); + let hex = "27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116"; 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(hex).unwrap()); monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap(); test_secrets!(); + let hex = "c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd"; 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(hex).unwrap()); monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap(); test_secrets!(); + let hex = "969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2"; 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(hex).unwrap()); monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).unwrap(); test_secrets!(); + let hex = "a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32"; 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(hex).unwrap()); monitor.provide_secret(281474976710649, secrets.last().unwrap().clone()).unwrap(); test_secrets!(); + let hex = "05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17"; 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(hex).unwrap()); monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()).unwrap(); test_secrets!(); } @@ -2437,23 +2405,15 @@ mod tests { monitor = CounterpartyCommitmentSecrets::new(); secrets.clear(); + let hex = "02a40c85b6f28da08dfdbe0926c53fab2de6d28c10301f8f7c4073d5e42e3148"; 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(hex).unwrap()); monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap(); test_secrets!(); + let hex = "c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964"; 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(hex).unwrap()); assert!(monitor .provide_secret(281474976710654, secrets.last().unwrap().clone()) .is_err()); @@ -2464,43 +2424,27 @@ mod tests { monitor = CounterpartyCommitmentSecrets::new(); secrets.clear(); + let hex = "02a40c85b6f28da08dfdbe0926c53fab2de6d28c10301f8f7c4073d5e42e3148"; 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(hex).unwrap()); monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap(); test_secrets!(); + let hex = "dddc3a8d14fddf2b68fa8c7fbad2748274937479dd0f8930d5ebb4ab6bd866a3"; 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(hex).unwrap()); monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap(); test_secrets!(); + let hex = "2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8"; 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(hex).unwrap()); monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap(); test_secrets!(); + let hex = "27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116"; 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(hex).unwrap()); assert!(monitor .provide_secret(281474976710652, secrets.last().unwrap().clone()) .is_err()); @@ -2511,43 +2455,27 @@ mod tests { monitor = CounterpartyCommitmentSecrets::new(); secrets.clear(); + let hex = "7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc"; 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(hex).unwrap()); monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap(); test_secrets!(); + let hex = "c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964"; 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(hex).unwrap()); monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap(); test_secrets!(); + let hex = "c51a18b13e8527e579ec56365482c62f180b7d5760b46e9477dae59e87ed423a"; 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(hex).unwrap()); monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap(); test_secrets!(); + let hex = "27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116"; 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(hex).unwrap()); assert!(monitor .provide_secret(281474976710652, secrets.last().unwrap().clone()) .is_err()); @@ -2558,83 +2486,51 @@ mod tests { monitor = CounterpartyCommitmentSecrets::new(); secrets.clear(); + let hex = "02a40c85b6f28da08dfdbe0926c53fab2de6d28c10301f8f7c4073d5e42e3148"; 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(hex).unwrap()); monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap(); test_secrets!(); + let hex = "dddc3a8d14fddf2b68fa8c7fbad2748274937479dd0f8930d5ebb4ab6bd866a3"; 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(hex).unwrap()); monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap(); test_secrets!(); + let hex = "c51a18b13e8527e579ec56365482c62f180b7d5760b46e9477dae59e87ed423a"; 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(hex).unwrap()); monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap(); test_secrets!(); + let hex = "ba65d7b0ef55a3ba300d4e87af29868f394f8f138d78a7011669c79b37b936f4"; 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(hex).unwrap()); monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap(); test_secrets!(); + let hex = "c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd"; 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(hex).unwrap()); monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap(); test_secrets!(); + let hex = "969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2"; 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(hex).unwrap()); monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).unwrap(); test_secrets!(); + let hex = "a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32"; 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(hex).unwrap()); monitor.provide_secret(281474976710649, secrets.last().unwrap().clone()).unwrap(); test_secrets!(); + let hex = "05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17"; 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(hex).unwrap()); assert!(monitor .provide_secret(281474976710648, secrets.last().unwrap().clone()) .is_err()); @@ -2645,63 +2541,39 @@ mod tests { monitor = CounterpartyCommitmentSecrets::new(); secrets.clear(); + let hex = "7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc"; 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(hex).unwrap()); monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap(); test_secrets!(); + let hex = "c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964"; 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(hex).unwrap()); monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap(); test_secrets!(); + let hex = "2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8"; 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(hex).unwrap()); monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap(); test_secrets!(); + let hex = "27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116"; 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(hex).unwrap()); monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap(); test_secrets!(); + let hex = "631373ad5f9ef654bb3dade742d09504c567edd24320d2fcd68e3cc47e2ff6a6"; 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(hex).unwrap()); monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap(); test_secrets!(); + let hex = "969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2"; 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(hex).unwrap()); assert!(monitor .provide_secret(281474976710650, secrets.last().unwrap().clone()) .is_err()); @@ -2712,83 +2584,51 @@ mod tests { monitor = CounterpartyCommitmentSecrets::new(); secrets.clear(); + let hex = "7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc"; 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(hex).unwrap()); monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap(); test_secrets!(); + let hex = "c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964"; 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(hex).unwrap()); monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap(); test_secrets!(); + let hex = "2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8"; 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(hex).unwrap()); monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap(); test_secrets!(); + let hex = "27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116"; 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(hex).unwrap()); monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap(); test_secrets!(); + let hex = "631373ad5f9ef654bb3dade742d09504c567edd24320d2fcd68e3cc47e2ff6a6"; 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(hex).unwrap()); monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap(); test_secrets!(); + let hex = "b7e76a83668bde38b373970155c868a653304308f9896692f904a23731224bb1"; 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(hex).unwrap()); monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).unwrap(); test_secrets!(); + let hex = "a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32"; 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(hex).unwrap()); monitor.provide_secret(281474976710649, secrets.last().unwrap().clone()).unwrap(); test_secrets!(); + let hex = "05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17"; 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(hex).unwrap()); assert!(monitor .provide_secret(281474976710648, secrets.last().unwrap().clone()) .is_err()); @@ -2799,83 +2639,51 @@ mod tests { monitor = CounterpartyCommitmentSecrets::new(); secrets.clear(); + let hex = "7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc"; 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(hex).unwrap()); monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap(); test_secrets!(); + let hex = "c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964"; 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(hex).unwrap()); monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap(); test_secrets!(); + let hex = "2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8"; 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(hex).unwrap()); monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap(); test_secrets!(); + let hex = "27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116"; 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(hex).unwrap()); monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap(); test_secrets!(); + let hex = "c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd"; 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(hex).unwrap()); monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap(); test_secrets!(); + let hex = "969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2"; 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(hex).unwrap()); monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).unwrap(); test_secrets!(); + let hex = "e7971de736e01da8ed58b94c2fc216cb1dca9e326f3a96e7194fe8ea8af6c0a3"; 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(hex).unwrap()); monitor.provide_secret(281474976710649, secrets.last().unwrap().clone()).unwrap(); test_secrets!(); + let hex = "05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17"; 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(hex).unwrap()); assert!(monitor .provide_secret(281474976710648, secrets.last().unwrap().clone()) .is_err()); @@ -2886,83 +2694,51 @@ mod tests { monitor = CounterpartyCommitmentSecrets::new(); secrets.clear(); + let hex = "7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc"; 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(hex).unwrap()); monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap(); test_secrets!(); + let hex = "c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964"; 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(hex).unwrap()); monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap(); test_secrets!(); + let hex = "2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8"; 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(hex).unwrap()); monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap(); test_secrets!(); + let hex = "27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116"; 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(hex).unwrap()); monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap(); test_secrets!(); + let hex = "c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd"; 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(hex).unwrap()); monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap(); test_secrets!(); + let hex = "969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2"; 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(hex).unwrap()); monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).unwrap(); test_secrets!(); + let hex = "a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32"; 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(hex).unwrap()); monitor.provide_secret(281474976710649, secrets.last().unwrap().clone()).unwrap(); test_secrets!(); + let hex = "a7efbc61aac46d34f77778bac22c8a20c6a46ca460addc49009bda875ec88fa4"; secrets.push([0; 32]); - secrets.last_mut().unwrap()[0..32].clone_from_slice( - &>::from_hex( - "a7efbc61aac46d34f77778bac22c8a20c6a46ca460addc49009bda875ec88fa4", - ) - .unwrap(), - ); + secrets.last_mut().unwrap()[0..32].clone_from_slice(&>::from_hex(hex).unwrap()); assert!(monitor .provide_secret(281474976710648, secrets.last().unwrap().clone()) .is_err()); From ee3d225c0a0d63749ae9825b1232d2a074263987 Mon Sep 17 00:00:00 2001 From: Joost Jager Date: Thu, 12 Jun 2025 21:30:48 +0200 Subject: [PATCH 3/3] Remove redundant skips --- lightning/src/chain/channelmonitor.rs | 14 +------------- lightning/src/chain/onchaintx.rs | 1 - lightning/src/ln/channel.rs | 4 ---- lightning/src/ln/outbound_payment.rs | 2 -- 4 files changed, 1 insertion(+), 20 deletions(-) diff --git a/lightning/src/chain/channelmonitor.rs b/lightning/src/chain/channelmonitor.rs index 978c15132bc..948a8f72971 100644 --- a/lightning/src/chain/channelmonitor.rs +++ b/lightning/src/chain/channelmonitor.rs @@ -2618,7 +2618,6 @@ 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 { @@ -2868,7 +2867,6 @@ 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 { @@ -3329,7 +3327,6 @@ 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); @@ -3836,7 +3833,6 @@ 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 { @@ -4186,13 +4182,12 @@ impl ChannelMonitorImpl { 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; self.broadcasted_holder_revokable_script = $updates.1; watch_outputs.append(&mut $to_watch); - } + }; } // HTLCs set may differ between last and previous holder commitment txn, in case of one them hitting chain, ensure we cancel all HTLCs backward @@ -4968,7 +4963,6 @@ 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 { @@ -4983,7 +4977,6 @@ impl ChannelMonitorImpl { } } - #[rustfmt::skip] macro_rules! scan_commitment { ($htlcs: expr, $tx_info: expr, $holder_tx: expr) => { for (ref htlc_output, source_option) in $htlcs { @@ -5309,7 +5302,6 @@ 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 { () => { { @@ -5809,7 +5801,6 @@ mod tests { let dummy_source = HTLCSource::dummy(); - #[rustfmt::skip] macro_rules! preimages_slice_to_htlcs { ($preimages_slice: expr) => { { @@ -5827,7 +5818,6 @@ 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() @@ -5837,7 +5827,6 @@ 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 { @@ -5968,7 +5957,6 @@ 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 { diff --git a/lightning/src/chain/onchaintx.rs b/lightning/src/chain/onchaintx.rs index b01291f2e69..fd0f0d9abf5 100644 --- a/lightning/src/chain/onchaintx.rs +++ b/lightning/src/chain/onchaintx.rs @@ -942,7 +942,6 @@ impl OnchainTxHandler { } } - #[rustfmt::skip] macro_rules! clean_claim_request_after_safety_delay { () => { let entry = OnchainEventEntry { diff --git a/lightning/src/ln/channel.rs b/lightning/src/ln/channel.rs index 5a250c2a385..5cb94ab95d7 100644 --- a/lightning/src/ln/channel.rs +++ b/lightning/src/ln/channel.rs @@ -4424,7 +4424,6 @@ where 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 { @@ -4437,7 +4436,6 @@ where } } - #[rustfmt::skip] macro_rules! add_htlc_output { ($htlc: expr, $outbound: expr, $source: expr) => { let htlc_in_tx = get_htlc_in_commitment!($htlc, $outbound == local); @@ -6971,7 +6969,6 @@ 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 { @@ -8398,7 +8395,6 @@ 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 { diff --git a/lightning/src/ln/outbound_payment.rs b/lightning/src/ln/outbound_payment.rs index 28e5eb93441..e6dd364b4b0 100644 --- a/lightning/src/ln/outbound_payment.rs +++ b/lightning/src/ln/outbound_payment.rs @@ -1441,7 +1441,6 @@ impl OutboundPayments { } } - #[rustfmt::skip] macro_rules! abandon_with_entry { ($payment: expr, $reason: expr) => { $payment.get_mut().mark_abandoned($reason); @@ -2465,7 +2464,6 @@ impl OutboundPayments { let path_amt = path.final_value_msat(); let path_fee = path.fee_msat(); - #[rustfmt::skip] macro_rules! new_retryable { () => { PendingOutboundPayment::Retryable {