From 12fc953b277f8248d0c99f417a4fd972a27d2bd9 Mon Sep 17 00:00:00 2001 From: Elias Rohrer Date: Wed, 18 Sep 2024 09:41:12 +0200 Subject: [PATCH] `rustfmt`: Run on `util/test_utils.rs` --- lightning/src/util/test_utils.rs | 660 +++++++++++++++++++++---------- 1 file changed, 452 insertions(+), 208 deletions(-) diff --git a/lightning/src/util/test_utils.rs b/lightning/src/util/test_utils.rs index 59c84317a..5f07cbca2 100644 --- a/lightning/src/util/test_utils.rs +++ b/lightning/src/util/test_utils.rs @@ -11,7 +11,6 @@ use crate::blinded_path::message::MessageContext; use crate::blinded_path::message::{BlindedMessagePath, MessageForwardNode}; use crate::blinded_path::payment::{BlindedPaymentPath, ReceiveTlvs}; use crate::chain; -use crate::chain::WatchedOutput; use crate::chain::chaininterface; use crate::chain::chaininterface::ConfirmationTarget; #[cfg(test)] @@ -20,60 +19,70 @@ use crate::chain::chainmonitor; use crate::chain::channelmonitor; use crate::chain::channelmonitor::MonitorEvent; use crate::chain::transaction::OutPoint; -use crate::routing::router::{CandidateRouteHop, FirstHopCandidate, PublicHopCandidate, PrivateHopCandidate}; -use crate::sign; +use crate::chain::WatchedOutput; use crate::events; -use crate::events::bump_transaction::{WalletSource, Utxo}; -use crate::ln::types::ChannelId; -use crate::ln::channel_state::ChannelDetails; -use crate::ln::channelmanager; +use crate::events::bump_transaction::{Utxo, WalletSource}; #[cfg(test)] use crate::ln::chan_utils::CommitmentTransaction; -use crate::types::features::{ChannelFeatures, InitFeatures, NodeFeatures}; +use crate::ln::channel_state::ChannelDetails; +use crate::ln::channelmanager; use crate::ln::inbound_payment::ExpandedKey; -use crate::ln::{msgs, wire}; use crate::ln::msgs::LightningError; use crate::ln::script::ShutdownScript; +use crate::ln::types::ChannelId; +use crate::ln::{msgs, wire}; use crate::offers::invoice::UnsignedBolt12Invoice; -use crate::onion_message::messenger::{DefaultMessageRouter, Destination, MessageRouter, OnionMessagePath}; +use crate::onion_message::messenger::{ + DefaultMessageRouter, Destination, MessageRouter, OnionMessagePath, +}; use crate::routing::gossip::{EffectiveCapacity, NetworkGraph, NodeId, RoutingFees}; +use crate::routing::router::{ + CandidateRouteHop, FirstHopCandidate, PrivateHopCandidate, PublicHopCandidate, +}; +use crate::routing::router::{ + DefaultRouter, InFlightHtlcs, Path, Route, RouteHintHop, RouteParameters, Router, + ScorerAccountingForInFlightHtlcs, +}; +use crate::routing::scoring::{ChannelUsage, ScoreLookUp, ScoreUpdate}; use crate::routing::utxo::{UtxoLookup, UtxoLookupError, UtxoResult}; -use crate::routing::router::{DefaultRouter, InFlightHtlcs, Path, Route, RouteParameters, RouteHintHop, Router, ScorerAccountingForInFlightHtlcs}; -use crate::routing::scoring::{ChannelUsage, ScoreUpdate, ScoreLookUp}; +use crate::sign; use crate::sync::RwLock; +use crate::types::features::{ChannelFeatures, InitFeatures, NodeFeatures}; use crate::util::config::UserConfig; -use crate::util::test_channel_signer::{TestChannelSigner, EnforcementState}; use crate::util::logger::{Logger, Record}; -use crate::util::ser::{Readable, ReadableArgs, Writer, Writeable}; use crate::util::persist::KVStore; +use crate::util::ser::{Readable, ReadableArgs, Writeable, Writer}; +use crate::util::test_channel_signer::{EnforcementState, TestChannelSigner}; use bitcoin::amount::Amount; -use bitcoin::constants::ChainHash; -use bitcoin::constants::genesis_block; -use bitcoin::transaction::{Transaction, TxOut}; -use bitcoin::script::{Builder, Script, ScriptBuf}; -use bitcoin::opcodes; use bitcoin::block::Block; -use bitcoin::network::Network; +use bitcoin::constants::genesis_block; +use bitcoin::constants::ChainHash; use bitcoin::hash_types::{BlockHash, Txid}; use bitcoin::hashes::Hash; -use bitcoin::sighash::{SighashCache, EcdsaSighashType}; +use bitcoin::network::Network; +use bitcoin::opcodes; +use bitcoin::script::{Builder, Script, ScriptBuf}; +use bitcoin::sighash::{EcdsaSighashType, SighashCache}; +use bitcoin::transaction::{Transaction, TxOut}; -use bitcoin::secp256k1::{PublicKey, Scalar, Secp256k1, SecretKey, self}; use bitcoin::secp256k1::ecdh::SharedSecret; use bitcoin::secp256k1::ecdsa::{RecoverableSignature, Signature}; use bitcoin::secp256k1::schnorr; +use bitcoin::secp256k1::{self, PublicKey, Scalar, Secp256k1, SecretKey}; use lightning_invoice::RawBolt11Invoice; use crate::io; use crate::prelude::*; +use crate::sign::{ + EntropySource, InMemorySigner, NodeSigner, RandomBytes, Recipient, SignerProvider, +}; +use crate::sync::{Arc, Mutex}; use core::cell::RefCell; -use core::time::Duration; -use crate::sync::{Mutex, Arc}; -use core::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; use core::mem; -use crate::sign::{InMemorySigner, RandomBytes, Recipient, EntropySource, NodeSigner, SignerProvider}; +use core::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; +use core::time::Duration; use bitcoin::psbt::Psbt; use bitcoin::Sequence; @@ -105,15 +114,17 @@ impl TestFeeEstimator { pub fn new(sat_per_kw: u32) -> Self { let sat_per_kw = Mutex::new(sat_per_kw); let target_override = Mutex::new(new_hash_map()); - Self { - sat_per_kw, - target_override, - } + Self { sat_per_kw, target_override } } } impl chaininterface::FeeEstimator for TestFeeEstimator { fn get_est_sat_per_1000_weight(&self, conf_target: ConfirmationTarget) -> u32 { - *self.target_override.lock().unwrap().get(&conf_target).unwrap_or(&*self.sat_per_kw.lock().unwrap()) + *self + .target_override + .lock() + .unwrap() + .get(&conf_target) + .unwrap_or(&*self.sat_per_kw.lock().unwrap()) } } @@ -141,7 +152,13 @@ impl<'a> TestRouter<'a> { let next_routes = Mutex::new(VecDeque::new()); let next_blinded_payment_paths = Mutex::new(Vec::new()); Self { - router: DefaultRouter::new(network_graph.clone(), logger, entropy_source, scorer, Default::default()), + router: DefaultRouter::new( + network_graph.clone(), + logger, + entropy_source, + scorer, + Default::default(), + ), network_graph, next_routes, next_blinded_payment_paths, @@ -168,7 +185,7 @@ impl<'a> TestRouter<'a> { impl<'a> Router for TestRouter<'a> { fn find_route( &self, payer: &PublicKey, params: &RouteParameters, first_hops: Option<&[&ChannelDetails]>, - inflight_htlcs: InFlightHtlcs + inflight_htlcs: InFlightHtlcs, ) -> Result { let route_res; let next_route_opt = self.next_routes.lock().unwrap().pop_front(); @@ -192,22 +209,31 @@ impl<'a> Router for TestRouter<'a> { if idx == path.hops.len() - 1 { if let Some(first_hops) = first_hops { - if let Some(idx) = first_hops.iter().position(|h| h.get_outbound_payment_scid() == Some(hop.short_channel_id)) { + if let Some(idx) = first_hops.iter().position(|h| { + h.get_outbound_payment_scid() == Some(hop.short_channel_id) + }) { let node_id = NodeId::from_pubkey(payer); - let candidate = CandidateRouteHop::FirstHop(FirstHopCandidate { - details: first_hops[idx], - payer_node_id: &node_id, - payer_node_counter: u32::max_value(), - target_node_counter: u32::max_value(), - }); - scorer.channel_penalty_msat(&candidate, usage, &Default::default()); + let candidate = + CandidateRouteHop::FirstHop(FirstHopCandidate { + details: first_hops[idx], + payer_node_id: &node_id, + payer_node_counter: u32::max_value(), + target_node_counter: u32::max_value(), + }); + scorer.channel_penalty_msat( + &candidate, + usage, + &Default::default(), + ); continue; } } } let network_graph = self.network_graph.read_only(); if let Some(channel) = network_graph.channel(hop.short_channel_id) { - let (directed, _) = channel.as_directed_to(&NodeId::from_pubkey(&hop.pubkey)).unwrap(); + let (directed, _) = channel + .as_directed_to(&NodeId::from_pubkey(&hop.pubkey)) + .unwrap(); let candidate = CandidateRouteHop::PublicHop(PublicHopCandidate { info: directed, short_channel_id: hop.short_channel_id, @@ -223,12 +249,13 @@ impl<'a> Router for TestRouter<'a> { htlc_minimum_msat: None, htlc_maximum_msat: None, }; - let candidate = CandidateRouteHop::PrivateHop(PrivateHopCandidate { - hint: &route_hint, - target_node_id: &target_node_id, - source_node_counter: u32::max_value(), - target_node_counter: u32::max_value(), - }); + let candidate = + CandidateRouteHop::PrivateHop(PrivateHopCandidate { + hint: &route_hint, + target_node_id: &target_node_id, + source_node_counter: u32::max_value(), + target_node_counter: u32::max_value(), + }); scorer.channel_penalty_msat(&candidate, usage, &Default::default()); } prev_hop_node = &hop.pubkey; @@ -252,16 +279,18 @@ impl<'a> Router for TestRouter<'a> { route_res } - 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, ) -> Result, ()> { let mut expected_paths = self.next_blinded_payment_paths.lock().unwrap(); if expected_paths.is_empty() { self.router.create_blinded_payment_paths( - recipient, first_hops, tlvs, amount_msats, secp_ctx + recipient, + first_hops, + tlvs, + amount_msats, + secp_ctx, ) } else { Ok(core::mem::take(&mut *expected_paths)) @@ -279,32 +308,38 @@ impl<'a> Drop for TestRouter<'a> { } pub struct TestMessageRouter<'a> { - inner: DefaultMessageRouter>, &'a TestLogger, &'a TestKeysInterface>, + inner: DefaultMessageRouter< + Arc>, + &'a TestLogger, + &'a TestKeysInterface, + >, } impl<'a> TestMessageRouter<'a> { - pub fn new(network_graph: Arc>, entropy_source: &'a TestKeysInterface) -> Self { + pub fn new( + network_graph: Arc>, entropy_source: &'a TestKeysInterface, + ) -> Self { Self { inner: DefaultMessageRouter::new(network_graph, entropy_source) } } } impl<'a> MessageRouter for TestMessageRouter<'a> { fn find_path( - &self, sender: PublicKey, peers: Vec, destination: Destination + &self, sender: PublicKey, peers: Vec, destination: Destination, ) -> Result { self.inner.find_path(sender, peers, destination) } fn create_blinded_paths( - &self, recipient: PublicKey, context: MessageContext, - peers: Vec, secp_ctx: &Secp256k1, + &self, recipient: PublicKey, context: MessageContext, peers: Vec, + secp_ctx: &Secp256k1, ) -> Result, ()> { self.inner.create_blinded_paths(recipient, context, peers, secp_ctx) } fn create_compact_blinded_paths( - &self, recipient: PublicKey, context: MessageContext, - peers: Vec, secp_ctx: &Secp256k1, + &self, recipient: PublicKey, context: MessageContext, peers: Vec, + secp_ctx: &Secp256k1, ) -> Result, ()> { self.inner.create_compact_blinded_paths(recipient, context, peers, secp_ctx) } @@ -313,37 +348,55 @@ impl<'a> MessageRouter for TestMessageRouter<'a> { pub struct OnlyReadsKeysInterface {} impl EntropySource for OnlyReadsKeysInterface { - fn get_secure_random_bytes(&self) -> [u8; 32] { [0; 32] }} + fn get_secure_random_bytes(&self) -> [u8; 32] { + [0; 32] + } +} impl SignerProvider for OnlyReadsKeysInterface { type EcdsaSigner = TestChannelSigner; #[cfg(taproot)] type TaprootSigner = TestChannelSigner; - fn generate_channel_keys_id(&self, _inbound: bool, _channel_value_satoshis: u64, _user_channel_id: u128) -> [u8; 32] { unreachable!(); } + fn generate_channel_keys_id( + &self, _inbound: bool, _channel_value_satoshis: u64, _user_channel_id: u128, + ) -> [u8; 32] { + unreachable!(); + } - fn derive_channel_signer(&self, _channel_value_satoshis: u64, _channel_keys_id: [u8; 32]) -> Self::EcdsaSigner { unreachable!(); } + fn derive_channel_signer( + &self, _channel_value_satoshis: u64, _channel_keys_id: [u8; 32], + ) -> Self::EcdsaSigner { + unreachable!(); + } fn read_chan_signer(&self, mut reader: &[u8]) -> Result { let inner: InMemorySigner = ReadableArgs::read(&mut reader, self)?; let state = Arc::new(Mutex::new(EnforcementState::new())); - Ok(TestChannelSigner::new_with_revoked( - inner, - state, - false - )) + Ok(TestChannelSigner::new_with_revoked(inner, state, false)) } - fn get_destination_script(&self, _channel_keys_id: [u8; 32]) -> Result { Err(()) } - fn get_shutdown_scriptpubkey(&self) -> Result { Err(()) } + fn get_destination_script(&self, _channel_keys_id: [u8; 32]) -> Result { + Err(()) + } + fn get_shutdown_scriptpubkey(&self) -> Result { + Err(()) + } } pub struct TestChainMonitor<'a> { pub added_monitors: Mutex)>>, pub monitor_updates: Mutex>>, pub latest_monitor_update_id: Mutex>, - pub chain_monitor: chainmonitor::ChainMonitor>, + pub chain_monitor: chainmonitor::ChainMonitor< + TestChannelSigner, + &'a TestChainSource, + &'a dyn chaininterface::BroadcasterInterface, + &'a TestFeeEstimator, + &'a TestLogger, + &'a dyn chainmonitor::Persist, + >, pub keys_manager: &'a TestKeysInterface, /// If this is set to Some(), the next update_channel call (not watch_channel) must be a /// ChannelForceClosed event for the given channel_id with should_broadcast set to the given @@ -354,7 +407,13 @@ pub struct TestChainMonitor<'a> { pub expect_monitor_round_trip_fail: Mutex>, } impl<'a> TestChainMonitor<'a> { - pub fn new(chain_source: Option<&'a TestChainSource>, broadcaster: &'a dyn chaininterface::BroadcasterInterface, logger: &'a TestLogger, fee_estimator: &'a TestFeeEstimator, persister: &'a dyn chainmonitor::Persist, keys_manager: &'a TestKeysInterface) -> Self { + pub fn new( + chain_source: Option<&'a TestChainSource>, + broadcaster: &'a dyn chaininterface::BroadcasterInterface, logger: &'a TestLogger, + fee_estimator: &'a TestFeeEstimator, + persister: &'a dyn chainmonitor::Persist, + keys_manager: &'a TestKeysInterface, + ) -> Self { let added_monitors = Mutex::new(Vec::new()); let monitor_updates = Mutex::new(new_hash_map()); let latest_monitor_update_id = Mutex::new(new_hash_map()); @@ -364,7 +423,13 @@ impl<'a> TestChainMonitor<'a> { added_monitors, monitor_updates, latest_monitor_update_id, - chain_monitor: chainmonitor::ChainMonitor::new(chain_source, broadcaster, logger, fee_estimator, persister), + chain_monitor: chainmonitor::ChainMonitor::new( + chain_source, + broadcaster, + logger, + fee_estimator, + persister, + ), keys_manager, expect_channel_force_closed, expect_monitor_round_trip_fail, @@ -372,45 +437,71 @@ impl<'a> TestChainMonitor<'a> { } pub fn complete_sole_pending_chan_update(&self, channel_id: &ChannelId) { - let (outpoint, _, latest_update) = self.latest_monitor_update_id.lock().unwrap().get(channel_id).unwrap().clone(); + let (outpoint, _, latest_update) = + self.latest_monitor_update_id.lock().unwrap().get(channel_id).unwrap().clone(); self.chain_monitor.channel_monitor_updated(outpoint, latest_update).unwrap(); } } impl<'a> chain::Watch for TestChainMonitor<'a> { - fn watch_channel(&self, funding_txo: OutPoint, monitor: channelmonitor::ChannelMonitor) -> Result { + fn watch_channel( + &self, funding_txo: OutPoint, monitor: channelmonitor::ChannelMonitor, + ) -> Result { // At every point where we get a monitor update, we should be able to send a useful monitor // to a watchtower and disk... let mut w = TestVecWriter(Vec::new()); monitor.write(&mut w).unwrap(); let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor)>::read( - &mut io::Cursor::new(&w.0), (self.keys_manager, self.keys_manager)).unwrap().1; + &mut io::Cursor::new(&w.0), + (self.keys_manager, self.keys_manager), + ) + .unwrap() + .1; assert!(new_monitor == monitor); - self.latest_monitor_update_id.lock().unwrap().insert(monitor.channel_id(), - (funding_txo, monitor.get_latest_update_id(), monitor.get_latest_update_id())); + self.latest_monitor_update_id.lock().unwrap().insert( + monitor.channel_id(), + (funding_txo, monitor.get_latest_update_id(), monitor.get_latest_update_id()), + ); self.added_monitors.lock().unwrap().push((funding_txo, monitor)); self.chain_monitor.watch_channel(funding_txo, new_monitor) } - fn update_channel(&self, funding_txo: OutPoint, update: &channelmonitor::ChannelMonitorUpdate) -> chain::ChannelMonitorUpdateStatus { + fn update_channel( + &self, funding_txo: OutPoint, update: &channelmonitor::ChannelMonitorUpdate, + ) -> chain::ChannelMonitorUpdateStatus { // Every monitor update should survive roundtrip let mut w = TestVecWriter(Vec::new()); update.write(&mut w).unwrap(); - assert!(channelmonitor::ChannelMonitorUpdate::read( - &mut io::Cursor::new(&w.0)).unwrap() == *update); - let channel_id = update.channel_id.unwrap_or(ChannelId::v1_from_funding_outpoint(funding_txo)); + assert!( + channelmonitor::ChannelMonitorUpdate::read(&mut io::Cursor::new(&w.0)).unwrap() + == *update + ); + let channel_id = + update.channel_id.unwrap_or(ChannelId::v1_from_funding_outpoint(funding_txo)); - self.monitor_updates.lock().unwrap().entry(channel_id).or_insert(Vec::new()).push(update.clone()); + self.monitor_updates + .lock() + .unwrap() + .entry(channel_id) + .or_insert(Vec::new()) + .push(update.clone()); if let Some(exp) = self.expect_channel_force_closed.lock().unwrap().take() { assert_eq!(channel_id, exp.0); assert_eq!(update.updates.len(), 1); - if let channelmonitor::ChannelMonitorUpdateStep::ChannelForceClosed { should_broadcast } = update.updates[0] { + if let channelmonitor::ChannelMonitorUpdateStep::ChannelForceClosed { + should_broadcast, + } = update.updates[0] + { assert_eq!(should_broadcast, exp.1); - } else { panic!(); } + } else { + panic!(); + } } - self.latest_monitor_update_id.lock().unwrap().insert(channel_id, - (funding_txo, update.update_id, update.update_id)); + self.latest_monitor_update_id + .lock() + .unwrap() + .insert(channel_id, (funding_txo, update.update_id, update.update_id)); let update_res = self.chain_monitor.update_channel(funding_txo, update); // At every point where we get a monitor update, we should be able to send a useful monitor // to a watchtower and disk... @@ -418,7 +509,11 @@ impl<'a> chain::Watch for TestChainMonitor<'a> { w.0.clear(); monitor.write(&mut w).unwrap(); let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor)>::read( - &mut io::Cursor::new(&w.0), (self.keys_manager, self.keys_manager)).unwrap().1; + &mut io::Cursor::new(&w.0), + (self.keys_manager, self.keys_manager), + ) + .unwrap() + .1; if let Some(chan_id) = self.expect_monitor_round_trip_fail.lock().unwrap().take() { assert_eq!(chan_id, channel_id); assert!(new_monitor != *monitor); @@ -429,7 +524,9 @@ impl<'a> chain::Watch for TestChainMonitor<'a> { update_res } - fn release_pending_monitor_events(&self) -> Vec<(OutPoint, ChannelId, Vec, Option)> { + fn release_pending_monitor_events( + &self, + ) -> Vec<(OutPoint, ChannelId, Vec, Option)> { return self.chain_monitor.release_pending_monitor_events(); } } @@ -470,42 +567,68 @@ impl WatchtowerPersister { } #[cfg(test)] - pub(crate) fn justice_tx(&self, funding_txo: OutPoint, commitment_txid: &Txid) - -> Option { - self.watchtower_state.lock().unwrap().get(&funding_txo).unwrap().get(commitment_txid).cloned() + pub(crate) fn justice_tx( + &self, funding_txo: OutPoint, commitment_txid: &Txid, + ) -> Option { + self.watchtower_state + .lock() + .unwrap() + .get(&funding_txo) + .unwrap() + .get(commitment_txid) + .cloned() } - fn form_justice_data_from_commitment(&self, counterparty_commitment_tx: &CommitmentTransaction) - -> Option { + fn form_justice_data_from_commitment( + &self, counterparty_commitment_tx: &CommitmentTransaction, + ) -> Option { let trusted_tx = counterparty_commitment_tx.trust(); let output_idx = trusted_tx.revokeable_output_index()?; let built_tx = trusted_tx.built_transaction(); let value = built_tx.transaction.output[output_idx as usize].value; - let justice_tx = trusted_tx.build_to_local_justice_tx( - FEERATE_FLOOR_SATS_PER_KW as u64, self.destination_script.clone()).ok()?; + let justice_tx = trusted_tx + .build_to_local_justice_tx( + FEERATE_FLOOR_SATS_PER_KW as u64, + self.destination_script.clone(), + ) + .ok()?; let commitment_number = counterparty_commitment_tx.commitment_number(); Some(JusticeTxData { justice_tx, value, commitment_number }) } } #[cfg(test)] -impl chainmonitor::Persist for WatchtowerPersister { - fn persist_new_channel(&self, funding_txo: OutPoint, - data: &channelmonitor::ChannelMonitor +impl chainmonitor::Persist + for WatchtowerPersister +{ + fn persist_new_channel( + &self, funding_txo: OutPoint, data: &channelmonitor::ChannelMonitor, ) -> chain::ChannelMonitorUpdateStatus { let res = self.persister.persist_new_channel(funding_txo, data); - assert!(self.unsigned_justice_tx_data.lock().unwrap() - .insert(funding_txo, VecDeque::new()).is_none()); - assert!(self.watchtower_state.lock().unwrap() - .insert(funding_txo, new_hash_map()).is_none()); + assert!(self + .unsigned_justice_tx_data + .lock() + .unwrap() + .insert(funding_txo, VecDeque::new()) + .is_none()); + assert!(self + .watchtower_state + .lock() + .unwrap() + .insert(funding_txo, new_hash_map()) + .is_none()); - let initial_counterparty_commitment_tx = data.initial_counterparty_commitment_tx() - .expect("First and only call expects Some"); - if let Some(justice_data) - = self.form_justice_data_from_commitment(&initial_counterparty_commitment_tx) { - self.unsigned_justice_tx_data.lock().unwrap() - .get_mut(&funding_txo).unwrap() + let initial_counterparty_commitment_tx = + data.initial_counterparty_commitment_tx().expect("First and only call expects Some"); + if let Some(justice_data) = + self.form_justice_data_from_commitment(&initial_counterparty_commitment_tx) + { + self.unsigned_justice_tx_data + .lock() + .unwrap() + .get_mut(&funding_txo) + .unwrap() .push_back(justice_data); } res @@ -513,25 +636,37 @@ impl chainmonitor::Persist for fn update_persisted_channel( &self, funding_txo: OutPoint, update: Option<&channelmonitor::ChannelMonitorUpdate>, - data: &channelmonitor::ChannelMonitor + data: &channelmonitor::ChannelMonitor, ) -> chain::ChannelMonitorUpdateStatus { let res = self.persister.update_persisted_channel(funding_txo, update, data); if let Some(update) = update { let commitment_txs = data.counterparty_commitment_txs_from_update(update); - let justice_datas = commitment_txs.into_iter() + let justice_datas = commitment_txs + .into_iter() .filter_map(|commitment_tx| self.form_justice_data_from_commitment(&commitment_tx)); let mut channels_justice_txs = self.unsigned_justice_tx_data.lock().unwrap(); let channel_state = channels_justice_txs.get_mut(&funding_txo).unwrap(); channel_state.extend(justice_datas); - while let Some(JusticeTxData { justice_tx, value, commitment_number }) = channel_state.front() { + while let Some(JusticeTxData { justice_tx, value, commitment_number }) = + channel_state.front() + { let input_idx = 0; let commitment_txid = justice_tx.input[input_idx].previous_output.txid; - match data.sign_to_local_justice_tx(justice_tx.clone(), input_idx, value.to_sat(), *commitment_number) { + match data.sign_to_local_justice_tx( + justice_tx.clone(), + input_idx, + value.to_sat(), + *commitment_number, + ) { Ok(signed_justice_tx) => { - let dup = self.watchtower_state.lock().unwrap() - .get_mut(&funding_txo).unwrap() + let dup = self + .watchtower_state + .lock() + .unwrap() + .get_mut(&funding_txo) + .unwrap() .insert(commitment_txid, signed_justice_tx); assert!(dup.is_none()); channel_state.pop_front(); @@ -544,7 +679,10 @@ impl chainmonitor::Persist for } fn archive_persisted_channel(&self, funding_txo: OutPoint) { - >::archive_persisted_channel(&self.persister, funding_txo); + >::archive_persisted_channel( + &self.persister, + funding_txo, + ); } } @@ -559,18 +697,14 @@ pub struct TestPersister { pub offchain_monitor_updates: Mutex>>, /// When we get an update_persisted_channel call with no ChannelMonitorUpdate, we insert the /// monitor's funding outpoint here. - pub chain_sync_monitor_persistences: Mutex> + pub chain_sync_monitor_persistences: Mutex>, } impl TestPersister { pub fn new() -> Self { let update_rets = Mutex::new(VecDeque::new()); let offchain_monitor_updates = Mutex::new(new_hash_map()); let chain_sync_monitor_persistences = Mutex::new(VecDeque::new()); - Self { - update_rets, - offchain_monitor_updates, - chain_sync_monitor_persistences - } + Self { update_rets, offchain_monitor_updates, chain_sync_monitor_persistences } } /// Queue an update status to return. @@ -579,21 +713,31 @@ impl TestPersister { } } impl chainmonitor::Persist for TestPersister { - fn persist_new_channel(&self, _funding_txo: OutPoint, _data: &channelmonitor::ChannelMonitor) -> chain::ChannelMonitorUpdateStatus { + fn persist_new_channel( + &self, _funding_txo: OutPoint, _data: &channelmonitor::ChannelMonitor, + ) -> chain::ChannelMonitorUpdateStatus { if let Some(update_ret) = self.update_rets.lock().unwrap().pop_front() { - return update_ret + return update_ret; } chain::ChannelMonitorUpdateStatus::Completed } - fn update_persisted_channel(&self, funding_txo: OutPoint, update: Option<&channelmonitor::ChannelMonitorUpdate>, _data: &channelmonitor::ChannelMonitor) -> chain::ChannelMonitorUpdateStatus { + fn update_persisted_channel( + &self, funding_txo: OutPoint, update: Option<&channelmonitor::ChannelMonitorUpdate>, + _data: &channelmonitor::ChannelMonitor, + ) -> chain::ChannelMonitorUpdateStatus { let mut ret = chain::ChannelMonitorUpdateStatus::Completed; if let Some(update_ret) = self.update_rets.lock().unwrap().pop_front() { ret = update_ret; } if let Some(update) = update { - self.offchain_monitor_updates.lock().unwrap().entry(funding_txo).or_insert(new_hash_set()).insert(update.update_id); + self.offchain_monitor_updates + .lock() + .unwrap() + .entry(funding_txo) + .or_insert(new_hash_set()) + .insert(update.update_id); } else { self.chain_sync_monitor_persistences.lock().unwrap().push_back(funding_txo); } @@ -620,7 +764,9 @@ impl TestStore { } impl KVStore for TestStore { - fn read(&self, primary_namespace: &str, secondary_namespace: &str, key: &str) -> io::Result> { + fn read( + &self, primary_namespace: &str, secondary_namespace: &str, key: &str, + ) -> io::Result> { let persisted_lock = self.persisted_bytes.lock().unwrap(); let prefixed = if secondary_namespace.is_empty() { primary_namespace.to_string() @@ -640,7 +786,9 @@ impl KVStore for TestStore { } } - fn write(&self, primary_namespace: &str, secondary_namespace: &str, key: &str, buf: &[u8]) -> io::Result<()> { + fn write( + &self, primary_namespace: &str, secondary_namespace: &str, key: &str, buf: &[u8], + ) -> io::Result<()> { if self.read_only { return Err(io::Error::new( io::ErrorKind::PermissionDenied, @@ -661,7 +809,9 @@ impl KVStore for TestStore { Ok(()) } - fn remove(&self, primary_namespace: &str, secondary_namespace: &str, key: &str, _lazy: bool) -> io::Result<()> { + fn remove( + &self, primary_namespace: &str, secondary_namespace: &str, key: &str, _lazy: bool, + ) -> io::Result<()> { if self.read_only { return Err(io::Error::new( io::ErrorKind::PermissionDenied, @@ -677,7 +827,7 @@ impl KVStore for TestStore { format!("{}/{}", primary_namespace, secondary_namespace) }; if let Some(outer_ref) = persisted_lock.get_mut(&prefixed) { - outer_ref.remove(&key.to_string()); + outer_ref.remove(&key.to_string()); } Ok(()) @@ -710,10 +860,7 @@ impl TestBroadcaster { pub fn new(network: Network) -> Self { let txn_broadcasted = Mutex::new(Vec::new()); let blocks = Arc::new(Mutex::new(vec![(genesis_block(network), 0)])); - Self { - txn_broadcasted, - blocks, - } + Self { txn_broadcasted, blocks } } pub fn with_blocks(blocks: Arc>>) -> Self { @@ -738,10 +885,15 @@ impl chaininterface::BroadcasterInterface for TestBroadcaster { for tx in txs { let lock_time = tx.lock_time.to_consensus_u32(); assert!(lock_time < 1_500_000_000); - if tx.lock_time.is_block_height() && lock_time > self.blocks.lock().unwrap().last().unwrap().1 { + if tx.lock_time.is_block_height() + && lock_time > self.blocks.lock().unwrap().last().unwrap().1 + { for inp in tx.input.iter() { if inp.sequence != Sequence::MAX { - panic!("We should never broadcast a transaction before its locktime ({})!", tx.lock_time); + panic!( + "We should never broadcast a transaction before its locktime ({})!", + tx.lock_time + ); } } } @@ -780,14 +932,21 @@ impl TestChannelMessageHandler { #[cfg(test)] pub(crate) fn expect_receive_msg(&self, ev: wire::Message<()>) { let mut expected_msgs = self.expected_recv_msgs.lock().unwrap(); - if expected_msgs.is_none() { *expected_msgs = Some(Vec::new()); } + if expected_msgs.is_none() { + *expected_msgs = Some(Vec::new()); + } expected_msgs.as_mut().unwrap().push(ev); } fn received_msg(&self, _ev: wire::Message<()>) { let mut msgs = self.expected_recv_msgs.lock().unwrap(); - if msgs.is_none() { return; } - assert!(!msgs.as_ref().unwrap().is_empty(), "Received message when we weren't expecting one"); + if msgs.is_none() { + return; + } + assert!( + !msgs.as_ref().unwrap().is_empty(), + "Received message when we weren't expecting one" + ); #[cfg(test)] assert_eq!(msgs.as_ref().unwrap()[0], _ev); msgs.as_mut().unwrap().remove(0); @@ -849,7 +1008,9 @@ impl msgs::ChannelMessageHandler for TestChannelMessageHandler { fn handle_update_fail_htlc(&self, _their_node_id: PublicKey, msg: &msgs::UpdateFailHTLC) { self.received_msg(wire::Message::UpdateFailHTLC(msg.clone())); } - fn handle_update_fail_malformed_htlc(&self, _their_node_id: PublicKey, msg: &msgs::UpdateFailMalformedHTLC) { + fn handle_update_fail_malformed_htlc( + &self, _their_node_id: PublicKey, msg: &msgs::UpdateFailMalformedHTLC, + ) { self.received_msg(wire::Message::UpdateFailMalformedHTLC(msg.clone())); } fn handle_commitment_signed(&self, _their_node_id: PublicKey, msg: &msgs::CommitmentSigned) { @@ -864,16 +1025,22 @@ impl msgs::ChannelMessageHandler for TestChannelMessageHandler { fn handle_channel_update(&self, _their_node_id: PublicKey, _msg: &msgs::ChannelUpdate) { // Don't call `received_msg` here as `TestRoutingMessageHandler` generates these sometimes } - fn handle_announcement_signatures(&self, _their_node_id: PublicKey, msg: &msgs::AnnouncementSignatures) { + fn handle_announcement_signatures( + &self, _their_node_id: PublicKey, msg: &msgs::AnnouncementSignatures, + ) { self.received_msg(wire::Message::AnnouncementSignatures(msg.clone())); } - fn handle_channel_reestablish(&self, _their_node_id: PublicKey, msg: &msgs::ChannelReestablish) { + fn handle_channel_reestablish( + &self, _their_node_id: PublicKey, msg: &msgs::ChannelReestablish, + ) { self.received_msg(wire::Message::ChannelReestablish(msg.clone())); } fn peer_disconnected(&self, their_node_id: PublicKey) { assert!(self.connected_peers.lock().unwrap().remove(&their_node_id)); } - fn peer_connected(&self, their_node_id: PublicKey, _msg: &msgs::Init, _inbound: bool) -> Result<(), ()> { + fn peer_connected( + &self, their_node_id: PublicKey, _msg: &msgs::Init, _inbound: bool, + ) -> Result<(), ()> { assert!(self.connected_peers.lock().unwrap().insert(their_node_id.clone())); // Don't bother with `received_msg` for Init as its auto-generated and we don't want to // bother re-generating the expected Init message in all tests. @@ -997,7 +1164,7 @@ fn get_dummy_channel_update(short_chan_id: u64) -> msgs::ChannelUpdate { fee_base_msat: 0, fee_proportional_millionths: 0, excess_data: vec![], - } + }, } } @@ -1022,18 +1189,27 @@ impl TestRoutingMessageHandler { } } impl msgs::RoutingMessageHandler for TestRoutingMessageHandler { - fn handle_node_announcement(&self, _their_node_id: Option, _msg: &msgs::NodeAnnouncement) -> Result { + fn handle_node_announcement( + &self, _their_node_id: Option, _msg: &msgs::NodeAnnouncement, + ) -> Result { Ok(true) } - fn handle_channel_announcement(&self, _their_node_id: Option, _msg: &msgs::ChannelAnnouncement) -> Result { + fn handle_channel_announcement( + &self, _their_node_id: Option, _msg: &msgs::ChannelAnnouncement, + ) -> Result { self.chan_anns_recvd.fetch_add(1, Ordering::AcqRel); Ok(true) } - fn handle_channel_update(&self, _their_node_id: Option, _msg: &msgs::ChannelUpdate) -> Result { + fn handle_channel_update( + &self, _their_node_id: Option, _msg: &msgs::ChannelUpdate, + ) -> Result { self.chan_upds_recvd.fetch_add(1, Ordering::AcqRel); Ok(true) } - fn get_next_channel_announcement(&self, starting_point: u64) -> Option<(msgs::ChannelAnnouncement, Option, Option)> { + fn get_next_channel_announcement( + &self, starting_point: u64, + ) -> Option<(msgs::ChannelAnnouncement, Option, Option)> + { if self.announcement_available_for_sync.load(Ordering::Acquire) { let chan_upd_1 = get_dummy_channel_update(starting_point); let chan_upd_2 = get_dummy_channel_update(starting_point); @@ -1045,11 +1221,15 @@ impl msgs::RoutingMessageHandler for TestRoutingMessageHandler { } } - fn get_next_node_announcement(&self, _starting_point: Option<&NodeId>) -> Option { + fn get_next_node_announcement( + &self, _starting_point: Option<&NodeId>, + ) -> Option { None } - fn peer_connected(&self, their_node_id: PublicKey, init_msg: &msgs::Init, _inbound: bool) -> Result<(), ()> { + fn peer_connected( + &self, their_node_id: PublicKey, init_msg: &msgs::Init, _inbound: bool, + ) -> Result<(), ()> { if !init_msg.features.supports_gossip_queries() { return Ok(()); } @@ -1059,7 +1239,10 @@ impl msgs::RoutingMessageHandler for TestRoutingMessageHandler { #[cfg(feature = "std")] { use std::time::{SystemTime, UNIX_EPOCH}; - gossip_start_time = SystemTime::now().duration_since(UNIX_EPOCH).expect("Time must be > 1970").as_secs(); + gossip_start_time = SystemTime::now() + .duration_since(UNIX_EPOCH) + .expect("Time must be > 1970") + .as_secs(); if self.request_full_sync.load(Ordering::Acquire) { gossip_start_time -= 60 * 60 * 24 * 7 * 2; // 2 weeks ago } else { @@ -1079,19 +1262,27 @@ impl msgs::RoutingMessageHandler for TestRoutingMessageHandler { Ok(()) } - fn handle_reply_channel_range(&self, _their_node_id: PublicKey, _msg: msgs::ReplyChannelRange) -> Result<(), msgs::LightningError> { + fn handle_reply_channel_range( + &self, _their_node_id: PublicKey, _msg: msgs::ReplyChannelRange, + ) -> Result<(), msgs::LightningError> { Ok(()) } - fn handle_reply_short_channel_ids_end(&self, _their_node_id: PublicKey, _msg: msgs::ReplyShortChannelIdsEnd) -> Result<(), msgs::LightningError> { + fn handle_reply_short_channel_ids_end( + &self, _their_node_id: PublicKey, _msg: msgs::ReplyShortChannelIdsEnd, + ) -> Result<(), msgs::LightningError> { Ok(()) } - fn handle_query_channel_range(&self, _their_node_id: PublicKey, _msg: msgs::QueryChannelRange) -> Result<(), msgs::LightningError> { + fn handle_query_channel_range( + &self, _their_node_id: PublicKey, _msg: msgs::QueryChannelRange, + ) -> Result<(), msgs::LightningError> { Ok(()) } - fn handle_query_short_channel_ids(&self, _their_node_id: PublicKey, _msg: msgs::QueryShortChannelIds) -> Result<(), msgs::LightningError> { + fn handle_query_short_channel_ids( + &self, _their_node_id: PublicKey, _msg: msgs::QueryShortChannelIds, + ) -> Result<(), msgs::LightningError> { Ok(()) } @@ -1107,7 +1298,9 @@ impl msgs::RoutingMessageHandler for TestRoutingMessageHandler { features } - fn processing_queue_high(&self) -> bool { false } + fn processing_queue_high(&self) -> bool { + false + } } impl events::MessageSendEventsProvider for TestRoutingMessageHandler { @@ -1132,11 +1325,7 @@ impl TestLogger { pub fn with_id(id: String) -> TestLogger { let lines = Mutex::new(new_hash_map()); let context = Mutex::new(new_hash_map()); - TestLogger { - id, - lines, - context, - } + TestLogger { id, lines, context } } pub fn assert_log(&self, module: &str, line: String, count: usize) { let log_entries = self.lines.lock().unwrap(); @@ -1149,9 +1338,11 @@ impl TestLogger { /// And asserts if the number of occurrences is the same with the given `count` pub fn assert_log_contains(&self, module: &str, line: &str, count: usize) { let log_entries = self.lines.lock().unwrap(); - let l: usize = log_entries.iter().filter(|&(&(ref m, ref l), _c)| { - *m == module && l.contains(line) - }).map(|(_, c) | { c }).sum(); + let l: usize = log_entries + .iter() + .filter(|&(&(ref m, ref l), _c)| *m == module && l.contains(line)) + .map(|(_, c)| c) + .sum(); assert_eq!(l, count) } @@ -1162,14 +1353,17 @@ impl TestLogger { #[cfg(any(test, feature = "_test_utils"))] pub fn assert_log_regex(&self, module: &str, pattern: regex::Regex, count: usize) { let log_entries = self.lines.lock().unwrap(); - let l: usize = log_entries.iter().filter(|&(&(ref m, ref l), _c)| { - *m == module && pattern.is_match(&l) - }).map(|(_, c) | { c }).sum(); + let l: usize = log_entries + .iter() + .filter(|&(&(ref m, ref l), _c)| *m == module && pattern.is_match(&l)) + .map(|(_, c)| c) + .sum(); assert_eq!(l, count) } pub fn assert_log_context_contains( - &self, module: &str, peer_id: Option, channel_id: Option, count: usize + &self, module: &str, peer_id: Option, channel_id: Option, + count: usize, ) { let context_entries = self.context.lock().unwrap(); let l = context_entries.get(&(module, peer_id, channel_id)).unwrap(); @@ -1179,11 +1373,19 @@ impl TestLogger { impl Logger for TestLogger { fn log(&self, record: Record) { - let s = format!("{:<55} {}", - format_args!("{} {} [{}:{}]", self.id, record.level.to_string(), record.module_path, record.line), + let s = format!( + "{:<55} {}", + format_args!( + "{} {} [{}:{}]", + self.id, + record.level.to_string(), + record.module_path, + record.line + ), record.args ); - #[cfg(ldk_bench)] { + #[cfg(ldk_bench)] + { // When benchmarking, we don't actually want to print logs, but we do want to format // them. To make sure LLVM doesn't skip the above entirely we push it through a // volitile read. This may not be super fast, but it shouldn't be worse than anything a @@ -1193,9 +1395,20 @@ impl Logger for TestLogger { let _ = unsafe { core::ptr::read_volatile(&s_bytes[i]) }; } } - #[cfg(not(ldk_bench))] { - *self.lines.lock().unwrap().entry((record.module_path, format!("{}", record.args))).or_insert(0) += 1; - *self.context.lock().unwrap().entry((record.module_path, record.peer_id, record.channel_id)).or_insert(0) += 1; + #[cfg(not(ldk_bench))] + { + *self + .lines + .lock() + .unwrap() + .entry((record.module_path, format!("{}", record.args))) + .or_insert(0) += 1; + *self + .context + .lock() + .unwrap() + .entry((record.module_path, record.peer_id, record.channel_id)) + .or_insert(0) += 1; println!("{}", s); } } @@ -1219,15 +1432,18 @@ impl NodeSigner for TestNodeSigner { fn get_node_id(&self, recipient: Recipient) -> Result { let node_secret = match recipient { Recipient::Node => Ok(&self.node_secret), - Recipient::PhantomNode => Err(()) + Recipient::PhantomNode => Err(()), }?; Ok(PublicKey::from_secret_key(&Secp256k1::signing_only(), node_secret)) } - fn ecdh(&self, recipient: Recipient, other_key: &PublicKey, tweak: Option<&bitcoin::secp256k1::Scalar>) -> Result { + fn ecdh( + &self, recipient: Recipient, other_key: &PublicKey, + tweak: Option<&bitcoin::secp256k1::Scalar>, + ) -> Result { let mut node_secret = match recipient { Recipient::Node => Ok(self.node_secret.clone()), - Recipient::PhantomNode => Err(()) + Recipient::PhantomNode => Err(()), }?; if let Some(tweak) = tweak { node_secret = node_secret.mul_tweak(tweak).map_err(|_| ())?; @@ -1254,7 +1470,7 @@ pub struct TestKeysInterface { pub backing: sign::PhantomKeysManager, pub override_random_bytes: Mutex>, pub disable_revocation_policy_check: bool, - enforcement_states: Mutex>>>, + enforcement_states: Mutex>>>, expectations: Mutex>>, pub unavailable_signers_ops: Mutex>>, pub next_signer_disabled_ops: Mutex>, @@ -1275,7 +1491,9 @@ impl NodeSigner for TestKeysInterface { self.backing.get_node_id(recipient) } - fn ecdh(&self, recipient: Recipient, other_key: &PublicKey, tweak: Option<&Scalar>) -> Result { + fn ecdh( + &self, recipient: Recipient, other_key: &PublicKey, tweak: Option<&Scalar>, + ) -> Result { self.backing.ecdh(recipient, other_key, tweak) } @@ -1283,7 +1501,9 @@ impl NodeSigner for TestKeysInterface { self.backing.get_inbound_payment_key() } - fn sign_invoice(&self, invoice: &RawBolt11Invoice, recipient: Recipient) -> Result { + fn sign_invoice( + &self, invoice: &RawBolt11Invoice, recipient: Recipient, + ) -> Result { self.backing.sign_invoice(invoice, recipient) } @@ -1303,14 +1523,19 @@ impl SignerProvider for TestKeysInterface { #[cfg(taproot)] type TaprootSigner = TestChannelSigner; - fn generate_channel_keys_id(&self, inbound: bool, channel_value_satoshis: u64, user_channel_id: u128) -> [u8; 32] { + fn generate_channel_keys_id( + &self, inbound: bool, channel_value_satoshis: u64, user_channel_id: u128, + ) -> [u8; 32] { self.backing.generate_channel_keys_id(inbound, channel_value_satoshis, user_channel_id) } - fn derive_channel_signer(&self, channel_value_satoshis: u64, channel_keys_id: [u8; 32]) -> TestChannelSigner { + fn derive_channel_signer( + &self, channel_value_satoshis: u64, channel_keys_id: [u8; 32], + ) -> TestChannelSigner { let keys = self.backing.derive_channel_signer(channel_value_satoshis, channel_keys_id); let state = self.make_enforcement_state_cell(keys.commitment_seed); - let signer = TestChannelSigner::new_with_revoked(keys, state, self.disable_revocation_policy_check); + let signer = + TestChannelSigner::new_with_revoked(keys, state, self.disable_revocation_policy_check); #[cfg(test)] if let Some(ops) = self.unavailable_signers_ops.lock().unwrap().get(&channel_keys_id) { for &op in ops { @@ -1330,14 +1555,12 @@ impl SignerProvider for TestKeysInterface { let inner: InMemorySigner = ReadableArgs::read(&mut reader, self)?; let state = self.make_enforcement_state_cell(inner.commitment_seed); - Ok(TestChannelSigner::new_with_revoked( - inner, - state, - self.disable_revocation_policy_check - )) + Ok(TestChannelSigner::new_with_revoked(inner, state, self.disable_revocation_policy_check)) } - fn get_destination_script(&self, channel_keys_id: [u8; 32]) -> Result { self.backing.get_destination_script(channel_keys_id) } + fn get_destination_script(&self, channel_keys_id: [u8; 32]) -> Result { + self.backing.get_destination_script(channel_keys_id) + } fn get_shutdown_scriptpubkey(&self) -> Result { match &mut *self.expectations.lock().unwrap() { @@ -1372,17 +1595,23 @@ impl TestKeysInterface { /// Sets an expectation that [`sign::SignerProvider::get_shutdown_scriptpubkey`] is /// called. pub fn expect(&self, expectation: OnGetShutdownScriptpubkey) -> &Self { - self.expectations.lock().unwrap() + self.expectations + .lock() + .unwrap() .get_or_insert_with(|| VecDeque::new()) .push_back(expectation); self } - pub fn derive_channel_keys(&self, channel_value_satoshis: u64, id: &[u8; 32]) -> TestChannelSigner { + pub fn derive_channel_keys( + &self, channel_value_satoshis: u64, id: &[u8; 32], + ) -> TestChannelSigner { self.derive_channel_signer(channel_value_satoshis, *id) } - fn make_enforcement_state_cell(&self, commitment_seed: [u8; 32]) -> Arc> { + fn make_enforcement_state_cell( + &self, commitment_seed: [u8; 32], + ) -> Arc> { let mut states = self.enforcement_states.lock().unwrap(); if !states.contains_key(&commitment_seed) { let state = EnforcementState::new(); @@ -1431,7 +1660,8 @@ pub struct TestChainSource { impl TestChainSource { pub fn new(network: Network) -> Self { let script_pubkey = Builder::new().push_opcode(opcodes::OP_TRUE).into_script(); - let utxo_ret = Mutex::new(UtxoResult::Sync(Ok(TxOut { value: Amount::MAX, script_pubkey }))); + let utxo_ret = + Mutex::new(UtxoResult::Sync(Ok(TxOut { value: Amount::MAX, script_pubkey }))); let watched_txn = Mutex::new(new_hash_set()); let watched_outputs = Mutex::new(new_hash_set()); Self { @@ -1484,25 +1714,29 @@ pub struct TestScorer { impl TestScorer { pub fn new() -> Self { - Self { - scorer_expectations: RefCell::new(None), - } + Self { scorer_expectations: RefCell::new(None) } } pub fn expect_usage(&self, scid: u64, expectation: ChannelUsage) { - self.scorer_expectations.borrow_mut().get_or_insert_with(|| VecDeque::new()).push_back((scid, expectation)); + self.scorer_expectations + .borrow_mut() + .get_or_insert_with(|| VecDeque::new()) + .push_back((scid, expectation)); } } #[cfg(c_bindings)] impl crate::util::ser::Writeable for TestScorer { - fn write(&self, _: &mut W) -> Result<(), crate::io::Error> { unreachable!(); } + fn write(&self, _: &mut W) -> Result<(), crate::io::Error> { + unreachable!(); + } } impl ScoreLookUp for TestScorer { type ScoreParams = (); fn channel_penalty_msat( - &self, candidate: &CandidateRouteHop, usage: ChannelUsage, _score_params: &Self::ScoreParams + &self, candidate: &CandidateRouteHop, usage: ChannelUsage, + _score_params: &Self::ScoreParams, ) -> u64 { let short_channel_id = match candidate.globally_unique_short_channel_id() { Some(scid) => scid, @@ -1522,7 +1756,11 @@ impl ScoreLookUp for TestScorer { } impl ScoreUpdate for TestScorer { - fn payment_path_failed(&mut self, _actual_path: &Path, _actual_short_channel_id: u64, _duration_since_epoch: Duration) {} + fn payment_path_failed( + &mut self, _actual_path: &Path, _actual_short_channel_id: u64, + _duration_since_epoch: Duration, + ) { + } fn payment_path_successful(&mut self, _actual_path: &Path, _duration_since_epoch: Duration) {} @@ -1558,11 +1796,7 @@ pub struct TestWalletSource { impl TestWalletSource { pub fn new(secret_key: SecretKey) -> Self { - Self { - secret_key, - utxos: RefCell::new(Vec::new()), - secp: Secp256k1::new(), - } + Self { secret_key, utxos: RefCell::new(Vec::new()), secp: Secp256k1::new() } } pub fn add_utxo(&self, outpoint: bitcoin::OutPoint, value: Amount) -> TxOut { @@ -1597,12 +1831,22 @@ impl WalletSource for TestWalletSource { let mut tx = psbt.extract_tx_unchecked_fee_rate(); let utxos = self.utxos.borrow(); for i in 0..tx.input.len() { - if let Some(utxo) = utxos.iter().find(|utxo| utxo.outpoint == tx.input[i].previous_output) { + if let Some(utxo) = + utxos.iter().find(|utxo| utxo.outpoint == tx.input[i].previous_output) + { let sighash = SighashCache::new(&tx) - .legacy_signature_hash(i, &utxo.output.script_pubkey, EcdsaSighashType::All as u32) + .legacy_signature_hash( + i, + &utxo.output.script_pubkey, + EcdsaSighashType::All as u32, + ) .map_err(|_| ())?; - let signature = self.secp.sign_ecdsa(&secp256k1::Message::from_digest(sighash.to_byte_array()), &self.secret_key); - let bitcoin_sig = bitcoin::ecdsa::Signature { signature, sighash_type: EcdsaSighashType::All }; + let signature = self.secp.sign_ecdsa( + &secp256k1::Message::from_digest(sighash.to_byte_array()), + &self.secret_key, + ); + let bitcoin_sig = + bitcoin::ecdsa::Signature { signature, sighash_type: EcdsaSighashType::All }; tx.input[i].script_sig = Builder::new() .push_slice(&bitcoin_sig.serialize()) .push_slice(&self.secret_key.public_key(&self.secp).serialize())