From 7d0a9d6debffe11155fd5dc346488c16c1f188a7 Mon Sep 17 00:00:00 2001
From: Joost Jager
Date: Thu, 24 Apr 2025 22:38:36 -0700
Subject: [PATCH 1/2] Cargo fmt everything
---
lightning/src/chain/chaininterface.rs | 30 +-
lightning/src/chain/chainmonitor.rs | 609 +-
lightning/src/chain/channelmonitor.rs | 3428 ++++--
lightning/src/chain/mod.rs | 26 +-
lightning/src/chain/onchaintx.rs | 532 +-
lightning/src/chain/package.rs | 1333 +-
lightning/src/chain/transaction.rs | 31 +-
lightning/src/events/bump_transaction.rs | 488 +-
lightning/src/events/mod.rs | 383 +-
lightning/src/lib.rs | 31 +-
lightning/src/ln/async_signer_tests.rs | 852 +-
lightning/src/ln/blinded_payment_tests.rs | 2224 +++-
lightning/src/ln/chan_utils.rs | 1553 ++-
lightning/src/ln/chanmon_update_fail_tests.rs | 3111 ++++-
lightning/src/ln/channel.rs | 8219 +++++++++----
lightning/src/ln/channelmanager.rs | 10039 +++++++++++-----
lightning/src/ln/functional_test_utils.rs | 3180 +++--
lightning/src/ln/functional_tests.rs | 9004 +++++++++++---
lightning/src/ln/inbound_payment.rs | 200 +-
lightning/src/ln/invoice_utils.rs | 984 +-
.../src/ln/max_payment_path_len_tests.rs | 410 +-
lightning/src/ln/mod.rs | 50 +-
lightning/src/ln/monitor_tests.rs | 2974 +++--
lightning/src/ln/msgs.rs | 1922 ++-
lightning/src/ln/offers_tests.rs | 869 +-
lightning/src/ln/onion_payment.rs | 803 +-
lightning/src/ln/onion_route_tests.rs | 2296 +++-
lightning/src/ln/outbound_payment.rs | 2535 ++--
lightning/src/ln/payment_tests.rs | 3553 ++++--
lightning/src/ln/peer_channel_encryptor.rs | 660 +-
lightning/src/ln/peer_handler.rs | 2325 ++--
lightning/src/ln/priv_short_conf_tests.rs | 973 +-
lightning/src/ln/reload_tests.rs | 1082 +-
lightning/src/ln/reorg_tests.rs | 365 +-
lightning/src/ln/shutdown_tests.rs | 1360 ++-
lightning/src/routing/mod.rs | 4 +-
lightning/src/routing/router.rs | 7967 +++++++-----
lightning/src/routing/scoring.rs | 1687 ++-
lightning/src/routing/test_utils.rs | 837 +-
lightning/src/routing/utxo.rs | 757 +-
40 files changed, 57537 insertions(+), 22149 deletions(-)
diff --git a/lightning/src/chain/chaininterface.rs b/lightning/src/chain/chaininterface.rs
index ebef21657b7..b6198215bcb 100644
--- a/lightning/src/chain/chaininterface.rs
+++ b/lightning/src/chain/chaininterface.rs
@@ -187,25 +187,29 @@ pub const FEERATE_FLOOR_SATS_PER_KW: u32 = 253;
///
/// Note that this does *not* implement [`FeeEstimator`] to make it harder to accidentally mix the
/// two.
-pub(crate) struct LowerBoundedFeeEstimator(pub F) where F::Target: FeeEstimator;
-
-impl LowerBoundedFeeEstimator where F::Target: FeeEstimator {
+pub(crate) struct LowerBoundedFeeEstimator(pub F)
+where
+ F::Target: FeeEstimator;
+
+impl LowerBoundedFeeEstimator
+where
+ F::Target: FeeEstimator,
+{
/// Creates a new `LowerBoundedFeeEstimator` which wraps the provided fee_estimator
pub fn new(fee_estimator: F) -> Self {
LowerBoundedFeeEstimator(fee_estimator)
}
pub fn bounded_sat_per_1000_weight(&self, confirmation_target: ConfirmationTarget) -> u32 {
- cmp::max(
- self.0.get_est_sat_per_1000_weight(confirmation_target),
- FEERATE_FLOOR_SATS_PER_KW,
- )
+ cmp::max(self.0.get_est_sat_per_1000_weight(confirmation_target), FEERATE_FLOOR_SATS_PER_KW)
}
}
#[cfg(test)]
mod tests {
- use super::{FEERATE_FLOOR_SATS_PER_KW, LowerBoundedFeeEstimator, ConfirmationTarget, FeeEstimator};
+ use super::{
+ ConfirmationTarget, FeeEstimator, LowerBoundedFeeEstimator, FEERATE_FLOOR_SATS_PER_KW,
+ };
struct TestFeeEstimator {
sat_per_kw: u32,
@@ -223,7 +227,10 @@ mod tests {
let test_fee_estimator = &TestFeeEstimator { sat_per_kw };
let fee_estimator = LowerBoundedFeeEstimator::new(test_fee_estimator);
- assert_eq!(fee_estimator.bounded_sat_per_1000_weight(ConfirmationTarget::AnchorChannelFee), FEERATE_FLOOR_SATS_PER_KW);
+ assert_eq!(
+ fee_estimator.bounded_sat_per_1000_weight(ConfirmationTarget::AnchorChannelFee),
+ FEERATE_FLOOR_SATS_PER_KW
+ );
}
#[test]
@@ -232,6 +239,9 @@ mod tests {
let test_fee_estimator = &TestFeeEstimator { sat_per_kw };
let fee_estimator = LowerBoundedFeeEstimator::new(test_fee_estimator);
- assert_eq!(fee_estimator.bounded_sat_per_1000_weight(ConfirmationTarget::AnchorChannelFee), sat_per_kw);
+ assert_eq!(
+ fee_estimator.bounded_sat_per_1000_weight(ConfirmationTarget::AnchorChannelFee),
+ sat_per_kw
+ );
}
}
diff --git a/lightning/src/chain/chainmonitor.rs b/lightning/src/chain/chainmonitor.rs
index c2b0a62e2d5..b87ec0a4733 100644
--- a/lightning/src/chain/chainmonitor.rs
+++ b/lightning/src/chain/chainmonitor.rs
@@ -24,27 +24,30 @@
//! servicing [`ChannelMonitor`] updates from the client.
use bitcoin::block::Header;
-use bitcoin::hash_types::{Txid, BlockHash};
+use bitcoin::hash_types::{BlockHash, Txid};
use crate::chain;
-use crate::chain::{ChannelMonitorUpdateStatus, Filter, WatchedOutput};
use crate::chain::chaininterface::{BroadcasterInterface, FeeEstimator};
-use crate::chain::channelmonitor::{ChannelMonitor, ChannelMonitorUpdate, Balance, MonitorEvent, TransactionOutputs, WithChannelMonitor};
+use crate::chain::channelmonitor::{
+ Balance, ChannelMonitor, ChannelMonitorUpdate, MonitorEvent, TransactionOutputs,
+ WithChannelMonitor,
+};
use crate::chain::transaction::{OutPoint, TransactionData};
+use crate::chain::{ChannelMonitorUpdateStatus, Filter, WatchedOutput};
+use crate::events::{self, Event, EventHandler, ReplayEvent};
+use crate::ln::channel_state::ChannelDetails;
use crate::ln::types::ChannelId;
use crate::sign::ecdsa::EcdsaChannelSigner;
-use crate::events::{self, Event, EventHandler, ReplayEvent};
-use crate::util::logger::{Logger, WithContext};
use crate::util::errors::APIError;
+use crate::util::logger::{Logger, WithContext};
use crate::util::persist::MonitorName;
use crate::util::wakers::{Future, Notifier};
-use crate::ln::channel_state::ChannelDetails;
use crate::prelude::*;
-use crate::sync::{RwLock, RwLockReadGuard, Mutex, MutexGuard};
+use crate::sync::{Mutex, MutexGuard, RwLock, RwLockReadGuard};
+use bitcoin::secp256k1::PublicKey;
use core::ops::Deref;
use core::sync::atomic::{AtomicUsize, Ordering};
-use bitcoin::secp256k1::PublicKey;
/// `Persist` defines behavior for persisting channel monitors: this could mean
/// writing once to disk, and/or uploading to one or more backup services.
@@ -120,7 +123,9 @@ pub trait Persist {
///
/// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
/// [`Writeable::write`]: crate::util::ser::Writeable::write
- fn persist_new_channel(&self, monitor_name: MonitorName, monitor: &ChannelMonitor) -> ChannelMonitorUpdateStatus;
+ fn persist_new_channel(
+ &self, monitor_name: MonitorName, monitor: &ChannelMonitor,
+ ) -> ChannelMonitorUpdateStatus;
/// Update one channel's data. The provided [`ChannelMonitor`] has already applied the given
/// update.
@@ -159,7 +164,10 @@ pub trait Persist {
/// [`ChannelMonitorUpdateStatus`] for requirements when returning errors.
///
/// [`Writeable::write`]: crate::util::ser::Writeable::write
- fn update_persisted_channel(&self, monitor_name: MonitorName, monitor_update: Option<&ChannelMonitorUpdate>, monitor: &ChannelMonitor) -> ChannelMonitorUpdateStatus;
+ fn update_persisted_channel(
+ &self, monitor_name: MonitorName, monitor_update: Option<&ChannelMonitorUpdate>,
+ monitor: &ChannelMonitor,
+ ) -> ChannelMonitorUpdateStatus;
/// Prevents the channel monitor from being loaded on startup.
///
/// Archiving the data in a backup location (rather than deleting it fully) is useful for
@@ -231,12 +239,19 @@ impl Deref for LockedChannelMonitor<'_, Chann
/// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
/// [module-level documentation]: crate::chain::chainmonitor
/// [`rebroadcast_pending_claims`]: Self::rebroadcast_pending_claims
-pub struct ChainMonitor
- where C::Target: chain::Filter,
- T::Target: BroadcasterInterface,
- F::Target: FeeEstimator,
- L::Target: Logger,
- P::Target: Persist,
+pub struct ChainMonitor<
+ ChannelSigner: EcdsaChannelSigner,
+ C: Deref,
+ T: Deref,
+ F: Deref,
+ L: Deref,
+ P: Deref,
+> where
+ C::Target: chain::Filter,
+ T::Target: BroadcasterInterface,
+ F::Target: FeeEstimator,
+ L::Target: Logger,
+ P::Target: Persist,
{
monitors: RwLock>>,
chain_source: Option,
@@ -255,12 +270,14 @@ pub struct ChainMonitor ChainMonitor
-where C::Target: chain::Filter,
- T::Target: BroadcasterInterface,
- F::Target: FeeEstimator,
- L::Target: Logger,
- P::Target: Persist,
+impl
+ ChainMonitor
+where
+ C::Target: chain::Filter,
+ T::Target: BroadcasterInterface,
+ F::Target: FeeEstimator,
+ L::Target: Logger,
+ P::Target: Persist,
{
/// Dispatches to per-channel monitors, which are responsible for updating their on-chain view
/// of a channel and reacting accordingly based on transactions in the given chain data. See
@@ -273,9 +290,10 @@ where C::Target: chain::Filter,
/// updated `txdata`.
///
/// Calls which represent a new blockchain tip height should set `best_height`.
- fn process_chain_data(&self, header: &Header, best_height: Option, txdata: &TransactionData, process: FN)
- where
- FN: Fn(&ChannelMonitor, &TransactionData) -> Vec
+ fn process_chain_data(
+ &self, header: &Header, best_height: Option, txdata: &TransactionData, process: FN,
+ ) where
+ FN: Fn(&ChannelMonitor, &TransactionData) -> Vec,
{
let err_str = "ChannelMonitor[Update] persistence failed unrecoverably. This indicates we cannot continue normal operation and must shut down.";
let channel_ids = hash_set_from_iter(self.monitors.read().unwrap().keys().cloned());
@@ -283,7 +301,18 @@ where C::Target: chain::Filter,
for channel_id in channel_ids.iter() {
let monitor_lock = self.monitors.read().unwrap();
if let Some(monitor_state) = monitor_lock.get(channel_id) {
- if self.update_monitor_with_chain_data(header, best_height, txdata, &process, channel_id, &monitor_state, channel_count).is_err() {
+ if self
+ .update_monitor_with_chain_data(
+ header,
+ best_height,
+ txdata,
+ &process,
+ channel_id,
+ &monitor_state,
+ channel_count,
+ )
+ .is_err()
+ {
// Take the monitors lock for writing so that we poison it and any future
// operations going forward fail immediately.
core::mem::drop(monitor_lock);
@@ -298,7 +327,18 @@ where C::Target: chain::Filter,
let monitor_states = self.monitors.write().unwrap();
for (channel_id, monitor_state) in monitor_states.iter() {
if !channel_ids.contains(channel_id) {
- if self.update_monitor_with_chain_data(header, best_height, txdata, &process, channel_id, &monitor_state, channel_count).is_err() {
+ if self
+ .update_monitor_with_chain_data(
+ header,
+ best_height,
+ txdata,
+ &process,
+ channel_id,
+ &monitor_state,
+ channel_count,
+ )
+ .is_err()
+ {
log_error!(self.logger, "{}", err_str);
panic!("{}", err_str);
}
@@ -317,9 +357,12 @@ where C::Target: chain::Filter,
}
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,
- ) -> Result<(), ()> where FN: Fn(&ChannelMonitor, &TransactionData) -> Vec {
+ &self, header: &Header, best_height: Option, txdata: &TransactionData, process: FN,
+ channel_id: &ChannelId, monitor_state: &MonitorHolder, channel_count: usize,
+ ) -> Result<(), ()>
+ where
+ FN: Fn(&ChannelMonitor, &TransactionData) -> Vec,
+ {
let monitor = &monitor_state.monitor;
let logger = WithChannelMonitor::from(&self.logger, &monitor, None);
@@ -327,7 +370,12 @@ where C::Target: chain::Filter,
let get_partition_key = |channel_id: &ChannelId| {
let channel_id_bytes = channel_id.0;
- let channel_id_u32 = u32::from_be_bytes([channel_id_bytes[0], channel_id_bytes[1], channel_id_bytes[2], channel_id_bytes[3]]);
+ let channel_id_u32 = u32::from_be_bytes([
+ channel_id_bytes[0],
+ channel_id_bytes[1],
+ channel_id_bytes[2],
+ channel_id_bytes[3],
+ ]);
channel_id_u32.wrapping_add(best_height.unwrap_or_default())
};
@@ -339,23 +387,33 @@ where C::Target: chain::Filter,
let has_pending_claims = monitor_state.monitor.has_pending_claims();
if has_pending_claims || get_partition_key(channel_id) % partition_factor == 0 {
- log_trace!(logger, "Syncing Channel Monitor for channel {}", log_funding_info!(monitor));
+ log_trace!(
+ logger,
+ "Syncing Channel Monitor for channel {}",
+ log_funding_info!(monitor)
+ );
// Even though we don't track monitor updates from chain-sync as pending, we still want
// updates per-channel to be well-ordered so that users don't see a
// `ChannelMonitorUpdate` after a channel persist for a channel with the same
// `latest_update_id`.
let _pending_monitor_updates = monitor_state.pending_monitor_updates.lock().unwrap();
- match self.persister.update_persisted_channel(monitor.persistence_key(), None, monitor) {
- ChannelMonitorUpdateStatus::Completed =>
- log_trace!(logger, "Finished syncing Channel Monitor for channel {} for block-data",
- log_funding_info!(monitor)
- ),
+ match self.persister.update_persisted_channel(monitor.persistence_key(), None, monitor)
+ {
+ ChannelMonitorUpdateStatus::Completed => log_trace!(
+ logger,
+ "Finished syncing Channel Monitor for channel {} for block-data",
+ log_funding_info!(monitor)
+ ),
ChannelMonitorUpdateStatus::InProgress => {
- log_trace!(logger, "Channel Monitor sync for channel {} in progress.", log_funding_info!(monitor));
- }
+ log_trace!(
+ logger,
+ "Channel Monitor sync for channel {} in progress.",
+ log_funding_info!(monitor)
+ );
+ },
ChannelMonitorUpdateStatus::UnrecoverableError => {
return Err(());
- }
+ },
}
}
@@ -371,7 +429,11 @@ where C::Target: chain::Filter,
outpoint: OutPoint { txid, index: idx as u16 },
script_pubkey: output.script_pubkey,
};
- log_trace!(logger, "Adding monitoring for spends of outpoint {} to the filter", output.outpoint);
+ log_trace!(
+ logger,
+ "Adding monitoring for spends of outpoint {} to the filter",
+ output.outpoint
+ );
chain_source.register_output(output);
}
}
@@ -386,7 +448,9 @@ where C::Target: chain::Filter,
/// pre-filter blocks or only fetch blocks matching a compact filter. Otherwise, clients may
/// always need to fetch full blocks absent another means for determining which blocks contain
/// transactions relevant to the watched channels.
- pub fn new(chain_source: Option, broadcaster: T, logger: L, feeest: F, persister: P) -> Self {
+ pub fn new(
+ chain_source: Option, broadcaster: T, logger: L, feeest: F, persister: P,
+ ) -> Self {
Self {
monitors: RwLock::new(new_hash_map()),
chain_source,
@@ -429,7 +493,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 })
@@ -463,12 +529,16 @@ where C::Target: chain::Filter,
/// 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`].
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()
+ 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
@@ -494,10 +564,16 @@ where C::Target: chain::Filter,
///
/// Returns an [`APIError::APIMisuseError`] if `funding_txo` does not match any currently
/// registered [`ChannelMonitor`]s.
- pub fn channel_monitor_updated(&self, channel_id: ChannelId, completed_update_id: u64) -> Result<(), APIError> {
+ 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 {
- return Err(APIError::APIMisuseError { err: format!("No ChannelMonitor matching channel ID {} found", channel_id) });
+ let monitor_data = if let Some(mon) = monitors.get(&channel_id) {
+ mon
+ } else {
+ return Err(APIError::APIMisuseError {
+ err: format!("No ChannelMonitor matching channel ID {} found", channel_id),
+ });
};
let mut pending_monitor_updates = monitor_data.pending_monitor_updates.lock().unwrap();
pending_monitor_updates.retain(|update_id| *update_id != completed_update_id);
@@ -505,25 +581,33 @@ where C::Target: chain::Filter,
// Note that we only check for pending non-chainsync monitor updates and we don't track monitor
// updates resulting from chainsync in `pending_monitor_updates`.
let monitor_is_pending_updates = monitor_data.has_pending_updates(&pending_monitor_updates);
- log_debug!(self.logger, "Completed off-chain monitor update {} for channel with channel ID {}, {}",
+ log_debug!(
+ self.logger,
+ "Completed off-chain monitor update {} for channel with channel ID {}, {}",
completed_update_id,
channel_id,
if monitor_is_pending_updates {
"still have pending off-chain updates"
} else {
"all off-chain updates complete, returning a MonitorEvent"
- });
+ }
+ );
if monitor_is_pending_updates {
// If there are still monitor updates pending, we cannot yet construct a
// Completed event.
return Ok(());
}
let funding_txo = monitor_data.monitor.get_funding_txo();
- self.pending_monitor_events.lock().unwrap().push((funding_txo, channel_id, vec![MonitorEvent::Completed {
+ self.pending_monitor_events.lock().unwrap().push((
funding_txo,
channel_id,
- monitor_update_id: monitor_data.monitor.get_latest_update_id(),
- }], monitor_data.monitor.get_counterparty_node_id()));
+ vec![MonitorEvent::Completed {
+ funding_txo,
+ channel_id,
+ monitor_update_id: monitor_data.monitor.get_latest_update_id(),
+ }],
+ monitor_data.monitor.get_counterparty_node_id(),
+ ));
self.event_notifier.notify();
Ok(())
@@ -538,11 +622,12 @@ where C::Target: chain::Filter,
let monitor = &monitors.get(&channel_id).unwrap().monitor;
let counterparty_node_id = monitor.get_counterparty_node_id();
let funding_txo = monitor.get_funding_txo();
- self.pending_monitor_events.lock().unwrap().push((funding_txo, channel_id, vec![MonitorEvent::Completed {
+ self.pending_monitor_events.lock().unwrap().push((
funding_txo,
channel_id,
- monitor_update_id,
- }], counterparty_node_id));
+ vec![MonitorEvent::Completed { funding_txo, channel_id, monitor_update_id }],
+ counterparty_node_id,
+ ));
self.event_notifier.notify();
}
@@ -561,8 +646,11 @@ where C::Target: chain::Filter,
/// See the trait-level documentation of [`EventsProvider`] for requirements.
///
/// [`EventsProvider`]: crate::events::EventsProvider
- pub async fn process_pending_events_async>, H: Fn(Event) -> Future>(
- &self, handler: H
+ pub async fn process_pending_events_async<
+ Future: core::future::Future