diff --git a/lightning-background-processor/Cargo.toml b/lightning-background-processor/Cargo.toml index ef0a9840613..7fe68bc1933 100644 --- a/lightning-background-processor/Cargo.toml +++ b/lightning-background-processor/Cargo.toml @@ -26,14 +26,14 @@ bitcoin_hashes = { version = "0.14.0", default-features = false } bitcoin-io = { version = "0.1.2", default-features = false } lightning = { version = "0.3.0", path = "../lightning", default-features = false } lightning-rapid-gossip-sync = { version = "0.2.0", path = "../lightning-rapid-gossip-sync", default-features = false } -lightning-liquidity = { version = "0.2.0", path = "../lightning-liquidity", default-features = false } +lightning-liquidity = { version = "0.3.0", path = "../lightning-liquidity", default-features = false } possiblyrandom = { version = "0.2", path = "../possiblyrandom", default-features = false } [dev-dependencies] tokio = { version = "1.35", features = [ "macros", "rt", "rt-multi-thread", "sync", "time" ] } lightning = { version = "0.3.0", path = "../lightning", features = ["_test_utils"] } lightning-invoice = { version = "0.34.0", path = "../lightning-invoice" } -lightning-liquidity = { version = "0.2.0", path = "../lightning-liquidity", default-features = false, features = ["_test_utils"] } +lightning-liquidity = { version = "0.3.0", path = "../lightning-liquidity", default-features = false, features = ["_test_utils"] } lightning-persister = { version = "0.2.0", path = "../lightning-persister" } [lints] diff --git a/lightning-background-processor/src/lib.rs b/lightning-background-processor/src/lib.rs index c38d6dfe080..81281cf16a8 100644 --- a/lightning-background-processor/src/lib.rs +++ b/lightning-background-processor/src/lib.rs @@ -201,10 +201,9 @@ pub enum GossipSync< R: Deref>, G: Deref>, U: Deref, - L: Deref, + L: Logger, > where U::Target: UtxoLookup, - L::Target: Logger, { /// Gossip sync via the lightning peer-to-peer network as defined by BOLT 7. P2P(P), @@ -219,11 +218,10 @@ impl< R: Deref>, G: Deref>, U: Deref, - L: Deref, + L: Logger, > GossipSync where U::Target: UtxoLookup, - L::Target: Logger, { fn network_graph(&self) -> Option<&G> { match self { @@ -261,11 +259,10 @@ impl< P: Deref>, G: Deref>, U: Deref, - L: Deref, + L: Logger, > GossipSync, G, U, L> where U::Target: UtxoLookup, - L::Target: Logger, { /// Initializes a new [`GossipSync::P2P`] variant. pub fn p2p(gossip_sync: P) -> Self { @@ -278,7 +275,7 @@ impl< 'a, R: Deref>, G: Deref>, - L: Deref, + L: Logger, > GossipSync< &P2PGossipSync, @@ -286,8 +283,7 @@ impl< G, &'a (dyn UtxoLookup + Send + Sync), L, - > where - L::Target: Logger, + > { /// Initializes a new [`GossipSync::Rapid`] variant. pub fn rapid(gossip_sync: R) -> Self { @@ -296,15 +292,14 @@ impl< } /// This is not exported to bindings users as the bindings concretize everything and have constructors for us -impl<'a, L: Deref> +impl<'a, L: Logger> GossipSync< &P2PGossipSync<&'a NetworkGraph, &'a (dyn UtxoLookup + Send + Sync), L>, &RapidGossipSync<&'a NetworkGraph, L>, &'a NetworkGraph, &'a (dyn UtxoLookup + Send + Sync), L, - > where - L::Target: Logger, + > { /// Initializes a new [`GossipSync::None`] variant. pub fn none() -> Self { @@ -312,10 +307,7 @@ impl<'a, L: Deref> } } -fn handle_network_graph_update(network_graph: &NetworkGraph, event: &Event) -where - L::Target: Logger, -{ +fn handle_network_graph_update(network_graph: &NetworkGraph, event: &Event) { if let Event::PaymentPathFailed { failure: PathFailure::OnPath { network_update: Some(ref upd) }, .. @@ -420,24 +412,15 @@ type DynChannelManager = lightning::ln::channelmanager::ChannelManager< pub const NO_ONION_MESSENGER: Option< Arc< dyn AOnionMessenger< - EntropySource = dyn EntropySource + Send + Sync, - ES = &(dyn EntropySource + Send + Sync), - NodeSigner = dyn lightning::sign::NodeSigner + Send + Sync, - NS = &(dyn lightning::sign::NodeSigner + Send + Sync), - Logger = dyn Logger + Send + Sync, - L = &'static (dyn Logger + Send + Sync), - NodeIdLookUp = DynChannelManager, + EntropySource = &(dyn EntropySource + Send + Sync), + NodeSigner = &(dyn lightning::sign::NodeSigner + Send + Sync), + Logger = &'static (dyn Logger + Send + Sync), NL = &'static DynChannelManager, - MessageRouter = DynMessageRouter, - MR = &'static DynMessageRouter, - OffersMessageHandler = lightning::ln::peer_handler::IgnoringMessageHandler, - OMH = &'static lightning::ln::peer_handler::IgnoringMessageHandler, - AsyncPaymentsMessageHandler = lightning::ln::peer_handler::IgnoringMessageHandler, - APH = &'static lightning::ln::peer_handler::IgnoringMessageHandler, - DNSResolverMessageHandler = lightning::ln::peer_handler::IgnoringMessageHandler, - DRH = &'static lightning::ln::peer_handler::IgnoringMessageHandler, - CustomOnionMessageHandler = lightning::ln::peer_handler::IgnoringMessageHandler, - CMH = &'static lightning::ln::peer_handler::IgnoringMessageHandler, + MessageRouter = &'static DynMessageRouter, + OMH = lightning::ln::peer_handler::IgnoringMessageHandler, + APH = lightning::ln::peer_handler::IgnoringMessageHandler, + DRH = lightning::ln::peer_handler::IgnoringMessageHandler, + CMH = lightning::ln::peer_handler::IgnoringMessageHandler, > + Send + Sync, >, @@ -480,22 +463,18 @@ impl KVStore for DummyKVStore { pub const NO_LIQUIDITY_MANAGER: Option< Arc< dyn ALiquidityManager< - EntropySource = dyn EntropySource + Send + Sync, - ES = &(dyn EntropySource + Send + Sync), - NodeSigner = dyn lightning::sign::NodeSigner + Send + Sync, - NS = &(dyn lightning::sign::NodeSigner + Send + Sync), + EntropySource = &(dyn EntropySource + Send + Sync), + NodeSigner = &(dyn lightning::sign::NodeSigner + Send + Sync), AChannelManager = DynChannelManager, CM = &DynChannelManager, Filter = dyn chain::Filter + Send + Sync, C = &(dyn chain::Filter + Send + Sync), - KVStore = DummyKVStore, K = &DummyKVStore, TimeProvider = dyn lightning_liquidity::utils::time::TimeProvider + Send + Sync, TP = &(dyn lightning_liquidity::utils::time::TimeProvider + Send + Sync), - BroadcasterInterface = dyn lightning::chain::chaininterface::BroadcasterInterface - + Send - + Sync, - T = &(dyn BroadcasterInterface + Send + Sync), + BroadcasterInterface = &(dyn lightning::chain::chaininterface::BroadcasterInterface + + Send + + Sync), > + Send + Sync, >, @@ -507,10 +486,8 @@ pub const NO_LIQUIDITY_MANAGER: Option< pub const NO_LIQUIDITY_MANAGER_SYNC: Option< Arc< dyn ALiquidityManagerSync< - EntropySource = dyn EntropySource + Send + Sync, - ES = &(dyn EntropySource + Send + Sync), - NodeSigner = dyn lightning::sign::NodeSigner + Send + Sync, - NS = &(dyn lightning::sign::NodeSigner + Send + Sync), + EntropySource = &(dyn EntropySource + Send + Sync), + NodeSigner = &(dyn lightning::sign::NodeSigner + Send + Sync), AChannelManager = DynChannelManager, CM = &DynChannelManager, Filter = dyn chain::Filter + Send + Sync, @@ -519,10 +496,9 @@ pub const NO_LIQUIDITY_MANAGER_SYNC: Option< KS = &(dyn lightning::util::persist::KVStoreSync + Send + Sync), TimeProvider = dyn lightning_liquidity::utils::time::TimeProvider + Send + Sync, TP = &(dyn lightning_liquidity::utils::time::TimeProvider + Send + Sync), - BroadcasterInterface = dyn lightning::chain::chaininterface::BroadcasterInterface - + Send - + Sync, - T = &(dyn BroadcasterInterface + Send + Sync), + BroadcasterInterface = &(dyn lightning::chain::chaininterface::BroadcasterInterface + + Send + + Sync), > + Send + Sync, >, @@ -956,14 +932,14 @@ pub async fn process_events_async< 'a, UL: Deref, CF: Deref, - T: Deref, - F: Deref, + T: BroadcasterInterface, + F: FeeEstimator, G: Deref>, - L: Deref, + L: Logger, P: Deref, EventHandlerFuture: core::future::Future>, EventHandler: Fn(Event) -> EventHandlerFuture, - ES: Deref, + ES: EntropySource, M: Deref::Signer, CF, T, F, L, P, ES>>, CM: Deref, OM: Deref, @@ -973,7 +949,7 @@ pub async fn process_events_async< LM: Deref, D: Deref, O: Deref, - K: Deref, + K: KVStore, OS: Deref>, S: Deref, SC: for<'b> WriteableScore<'b>, @@ -989,18 +965,13 @@ pub async fn process_events_async< where UL::Target: UtxoLookup, CF::Target: chain::Filter, - T::Target: BroadcasterInterface, - F::Target: FeeEstimator, - L::Target: Logger, P::Target: Persist<::Signer>, - ES::Target: EntropySource, CM::Target: AChannelManager, OM::Target: AOnionMessenger, PM::Target: APeerManager, LM::Target: ALiquidityManager, O::Target: OutputSpender, D::Target: ChangeDestinationSource, - K::Target: KVStore, { let async_event_handler = |event| { let network_graph = gossip_sync.network_graph(); @@ -1457,14 +1428,14 @@ fn check_and_reset_sleeper< pub async fn process_events_async_with_kv_store_sync< UL: Deref, CF: Deref, - T: Deref, - F: Deref, + T: BroadcasterInterface, + F: FeeEstimator, G: Deref>, - L: Deref, + L: Logger, P: Deref, EventHandlerFuture: core::future::Future>, EventHandler: Fn(Event) -> EventHandlerFuture, - ES: Deref, + ES: EntropySource, M: Deref::Signer, CF, T, F, L, P, ES>>, CM: Deref, OM: Deref, @@ -1490,11 +1461,7 @@ pub async fn process_events_async_with_kv_store_sync< where UL::Target: UtxoLookup, CF::Target: chain::Filter, - T::Target: BroadcasterInterface, - F::Target: FeeEstimator, - L::Target: Logger, P::Target: Persist<::Signer>, - ES::Target: EntropySource, CM::Target: AChannelManager, OM::Target: AOnionMessenger, PM::Target: APeerManager, @@ -1571,8 +1538,8 @@ impl BackgroundProcessor { 'a, UL: 'static + Deref, CF: 'static + Deref, - T: 'static + Deref, - F: 'static + Deref + Send, + T: 'static + BroadcasterInterface, + F: 'static + FeeEstimator + Send, G: 'static + Deref>, L: 'static + Deref + Send, P: 'static + Deref, @@ -1604,8 +1571,6 @@ impl BackgroundProcessor { where UL::Target: 'static + UtxoLookup, CF::Target: 'static + chain::Filter, - T::Target: 'static + BroadcasterInterface, - F::Target: 'static + FeeEstimator, L::Target: 'static + Logger, P::Target: 'static + Persist<::Signer>, ES::Target: 'static + EntropySource, diff --git a/lightning-dns-resolver/src/lib.rs b/lightning-dns-resolver/src/lib.rs index 3c1c51b1fcf..f43e954636a 100644 --- a/lightning-dns-resolver/src/lib.rs +++ b/lightning-dns-resolver/src/lib.rs @@ -6,7 +6,6 @@ #![deny(rustdoc::private_intra_doc_links)] use std::net::SocketAddr; -use std::ops::Deref; use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::{Arc, Mutex}; @@ -30,10 +29,7 @@ const WE_REQUIRE_32_OR_64_BIT_USIZE: u8 = 424242; /// A resolver which implements [`DNSResolverMessageHandler`] and replies to [`DNSSECQuery`] /// messages with with [`DNSSECProof`]s. -pub struct OMDomainResolver -where - PH::Target: DNSResolverMessageHandler, -{ +pub struct OMDomainResolver { state: Arc, proof_handler: Option, runtime_handle: Mutex>, @@ -56,10 +52,7 @@ impl OMDomainResolver { } } -impl OMDomainResolver -where - PH::Target: DNSResolverMessageHandler, -{ +impl OMDomainResolver { /// Creates a new [`OMDomainResolver`] given the [`SocketAddr`] of a DNS resolver listening on /// TCP (e.g. 8.8.8.8:53, 1.1.1.1:53 or your local DNS resolver). /// @@ -103,10 +96,7 @@ where } } -impl DNSResolverMessageHandler for OMDomainResolver -where - PH::Target: DNSResolverMessageHandler, -{ +impl DNSResolverMessageHandler for OMDomainResolver { fn handle_dnssec_proof(&self, proof: DNSSECProof, context: DNSResolverContext) { if let Some(proof_handler) = &self.proof_handler { proof_handler.handle_dnssec_proof(proof, context); @@ -169,7 +159,6 @@ mod test { use lightning::ln::msgs::{ BaseMessageHandler, ChannelMessageHandler, Init, OnionMessageHandler, }; - use lightning::ln::peer_handler::IgnoringMessageHandler; use lightning::offers::offer::Offer; use lightning::onion_message::dns_resolution::{HumanReadableName, OMNameResolver}; use lightning::onion_message::messenger::{ @@ -195,12 +184,6 @@ mod test { eprintln!("{:<8} {}", self.node, record); } } - impl Deref for TestLogger { - type Target = TestLogger; - fn deref(&self) -> &TestLogger { - self - } - } struct DummyNodeLookup {} impl NodeIdLookUp for DummyNodeLookup { @@ -208,12 +191,6 @@ mod test { None } } - impl Deref for DummyNodeLookup { - type Target = DummyNodeLookup; - fn deref(&self) -> &DummyNodeLookup { - self - } - } struct DirectlyConnectedRouter {} impl MessageRouter for DirectlyConnectedRouter { @@ -242,12 +219,6 @@ mod test { )]) } } - impl Deref for DirectlyConnectedRouter { - type Target = DirectlyConnectedRouter; - fn deref(&self) -> &DirectlyConnectedRouter { - self - } - } struct URIResolver { resolved_uri: Mutex>, diff --git a/lightning-liquidity/Cargo.toml b/lightning-liquidity/Cargo.toml index 2f83077cabc..67e82a5fbf8 100644 --- a/lightning-liquidity/Cargo.toml +++ b/lightning-liquidity/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lightning-liquidity" -version = "0.2.0+git" +version = "0.3.0+git" authors = ["John Cantrell ", "Elias Rohrer "] homepage = "https://lightningdevkit.org/" license = "MIT OR Apache-2.0" diff --git a/lightning-liquidity/src/events/event_queue.rs b/lightning-liquidity/src/events/event_queue.rs index 0d6e3a0ec54..9fb8a250a9a 100644 --- a/lightning-liquidity/src/events/event_queue.rs +++ b/lightning-liquidity/src/events/event_queue.rs @@ -12,7 +12,6 @@ use alloc::collections::VecDeque; use alloc::vec::Vec; use core::future::Future; -use core::ops::Deref; use core::task::{Poll, Waker}; use lightning::ln::msgs::DecodeError; @@ -25,10 +24,7 @@ use lightning::util::wakers::Notifier; /// The maximum queue size we allow before starting to drop events. pub const MAX_EVENT_QUEUE_SIZE: usize = 1000; -pub(crate) struct EventQueue -where - K::Target: KVStore, -{ +pub(crate) struct EventQueue { state: Mutex, waker: Mutex>, #[cfg(feature = "std")] @@ -37,10 +33,7 @@ where persist_notifier: Arc, } -impl EventQueue -where - K::Target: KVStore, -{ +impl EventQueue { pub fn new( queue: VecDeque, kv_store: K, persist_notifier: Arc, ) -> Self { @@ -164,14 +157,9 @@ struct QueueState { // A guard type that will notify about new events when dropped. #[must_use] -pub(crate) struct EventQueueNotifierGuard<'a, K: Deref + Clone>(&'a EventQueue) -where - K::Target: KVStore; - -impl<'a, K: Deref + Clone> EventQueueNotifierGuard<'a, K> -where - K::Target: KVStore, -{ +pub(crate) struct EventQueueNotifierGuard<'a, K: KVStore + Clone>(&'a EventQueue); + +impl<'a, K: KVStore + Clone> EventQueueNotifierGuard<'a, K> { pub fn enqueue>(&self, event: E) { let mut state_lock = self.0.state.lock().unwrap(); if state_lock.queue.len() < MAX_EVENT_QUEUE_SIZE { @@ -183,10 +171,7 @@ where } } -impl<'a, K: Deref + Clone> Drop for EventQueueNotifierGuard<'a, K> -where - K::Target: KVStore, -{ +impl<'a, K: KVStore + Clone> Drop for EventQueueNotifierGuard<'a, K> { fn drop(&mut self) { let (should_notify, should_persist_notify) = { let state_lock = self.0.state.lock().unwrap(); @@ -208,14 +193,9 @@ where } } -struct EventFuture<'a, K: Deref + Clone>(&'a EventQueue) -where - K::Target: KVStore; +struct EventFuture<'a, K: KVStore + Clone>(&'a EventQueue); -impl Future for EventFuture<'_, K> -where - K::Target: KVStore, -{ +impl Future for EventFuture<'_, K> { type Output = LiquidityEvent; fn poll( diff --git a/lightning-liquidity/src/lsps0/client.rs b/lightning-liquidity/src/lsps0/client.rs index d300936e2b2..298cb304b51 100644 --- a/lightning-liquidity/src/lsps0/client.rs +++ b/lightning-liquidity/src/lsps0/client.rs @@ -22,24 +22,14 @@ use lightning::util::persist::KVStore; use bitcoin::secp256k1::PublicKey; -use core::ops::Deref; - /// A message handler capable of sending and handling bLIP-50 / LSPS0 messages. -pub struct LSPS0ClientHandler -where - ES::Target: EntropySource, - K::Target: KVStore, -{ +pub struct LSPS0ClientHandler { entropy_source: ES, pending_messages: Arc, pending_events: Arc>, } -impl LSPS0ClientHandler -where - ES::Target: EntropySource, - K::Target: KVStore, -{ +impl LSPS0ClientHandler { /// Returns a new instance of [`LSPS0ClientHandler`]. pub(crate) fn new( entropy_source: ES, pending_messages: Arc, pending_events: Arc>, @@ -89,10 +79,8 @@ where } } -impl LSPSProtocolMessageHandler for LSPS0ClientHandler -where - ES::Target: EntropySource, - K::Target: KVStore, +impl LSPSProtocolMessageHandler + for LSPS0ClientHandler { type ProtocolMessage = LSPS0Message; const PROTOCOL_NUMBER: Option = None; diff --git a/lightning-liquidity/src/lsps1/client.rs b/lightning-liquidity/src/lsps1/client.rs index 4a79fb64887..2cbfb04c86a 100644 --- a/lightning-liquidity/src/lsps1/client.rs +++ b/lightning-liquidity/src/lsps1/client.rs @@ -30,8 +30,6 @@ use lightning::util::persist::KVStore; use bitcoin::secp256k1::PublicKey; use bitcoin::Address; -use core::ops::Deref; - /// Client-side configuration options for bLIP-51 / LSPS1 channel requests. #[derive(Clone, Debug)] pub struct LSPS1ClientConfig { @@ -47,11 +45,7 @@ struct PeerState { } /// The main object allowing to send and receive bLIP-51 / LSPS1 messages. -pub struct LSPS1ClientHandler -where - ES::Target: EntropySource, - K::Target: KVStore, -{ +pub struct LSPS1ClientHandler { entropy_source: ES, pending_messages: Arc, pending_events: Arc>, @@ -59,11 +53,7 @@ where config: LSPS1ClientConfig, } -impl LSPS1ClientHandler -where - ES::Target: EntropySource, - K::Target: KVStore, -{ +impl LSPS1ClientHandler { /// Constructs an `LSPS1ClientHandler`. pub(crate) fn new( entropy_source: ES, pending_messages: Arc, @@ -432,10 +422,8 @@ where } } -impl LSPSProtocolMessageHandler for LSPS1ClientHandler -where - ES::Target: EntropySource, - K::Target: KVStore, +impl LSPSProtocolMessageHandler + for LSPS1ClientHandler { type ProtocolMessage = LSPS1Message; const PROTOCOL_NUMBER: Option = Some(1); diff --git a/lightning-liquidity/src/lsps1/service.rs b/lightning-liquidity/src/lsps1/service.rs index 8afea1b4345..154c6f5d527 100644 --- a/lightning-liquidity/src/lsps1/service.rs +++ b/lightning-liquidity/src/lsps1/service.rs @@ -132,12 +132,10 @@ impl PeerState { } /// The main object allowing to send and receive bLIP-51 / LSPS1 messages. -pub struct LSPS1ServiceHandler +pub struct LSPS1ServiceHandler where - ES::Target: EntropySource, CM::Target: AChannelManager, C::Target: Filter, - K::Target: KVStore, { entropy_source: ES, channel_manager: CM, @@ -148,13 +146,11 @@ where config: LSPS1ServiceConfig, } -impl LSPS1ServiceHandler +impl + LSPS1ServiceHandler where - ES::Target: EntropySource, CM::Target: AChannelManager, C::Target: Filter, - ES::Target: EntropySource, - K::Target: KVStore, { /// Constructs a `LSPS1ServiceHandler`. pub(crate) fn new( @@ -421,13 +417,11 @@ where } } -impl LSPSProtocolMessageHandler +impl LSPSProtocolMessageHandler for LSPS1ServiceHandler where - ES::Target: EntropySource, CM::Target: AChannelManager, C::Target: Filter, - K::Target: KVStore, { type ProtocolMessage = LSPS1Message; const PROTOCOL_NUMBER: Option = Some(1); diff --git a/lightning-liquidity/src/lsps2/client.rs b/lightning-liquidity/src/lsps2/client.rs index 83aa7e3e99f..21b57162010 100644 --- a/lightning-liquidity/src/lsps2/client.rs +++ b/lightning-liquidity/src/lsps2/client.rs @@ -13,7 +13,6 @@ use alloc::string::{String, ToString}; use lightning::util::persist::KVStore; use core::default::Default; -use core::ops::Deref; use crate::events::EventQueue; use crate::lsps0::ser::{LSPSProtocolMessageHandler, LSPSRequestId, LSPSResponseError}; @@ -68,11 +67,7 @@ impl PeerState { /// opened. Please refer to the [`bLIP-52 / LSPS2 specification`] for more information. /// /// [`bLIP-52 / LSPS2 specification`]: https://github.com/lightning/blips/blob/master/blip-0052.md#trust-models -pub struct LSPS2ClientHandler -where - ES::Target: EntropySource, - K::Target: KVStore, -{ +pub struct LSPS2ClientHandler { entropy_source: ES, pending_messages: Arc, pending_events: Arc>, @@ -80,11 +75,7 @@ where config: LSPS2ClientConfig, } -impl LSPS2ClientHandler -where - ES::Target: EntropySource, - K::Target: KVStore, -{ +impl LSPS2ClientHandler { /// Constructs an `LSPS2ClientHandler`. pub(crate) fn new( entropy_source: ES, pending_messages: Arc, @@ -375,10 +366,8 @@ where } } -impl LSPSProtocolMessageHandler for LSPS2ClientHandler -where - ES::Target: EntropySource, - K::Target: KVStore, +impl LSPSProtocolMessageHandler + for LSPS2ClientHandler { type ProtocolMessage = LSPS2Message; const PROTOCOL_NUMBER: Option = Some(2); diff --git a/lightning-liquidity/src/lsps2/service.rs b/lightning-liquidity/src/lsps2/service.rs index 1b5bf964996..00f68aff696 100644 --- a/lightning-liquidity/src/lsps2/service.rs +++ b/lightning-liquidity/src/lsps2/service.rs @@ -702,11 +702,9 @@ macro_rules! get_or_insert_peer_state_entry { } /// The main object allowing to send and receive bLIP-52 / LSPS2 messages. -pub struct LSPS2ServiceHandler +pub struct LSPS2ServiceHandler where CM::Target: AChannelManager, - K::Target: KVStore, - T::Target: BroadcasterInterface, { channel_manager: CM, kv_store: K, @@ -721,11 +719,9 @@ where persistence_in_flight: AtomicUsize, } -impl LSPS2ServiceHandler +impl LSPS2ServiceHandler where CM::Target: AChannelManager, - K::Target: KVStore, - T::Target: BroadcasterInterface, { /// Constructs a `LSPS2ServiceHandler`. pub(crate) fn new( @@ -2044,12 +2040,10 @@ where } } -impl LSPSProtocolMessageHandler +impl LSPSProtocolMessageHandler for LSPS2ServiceHandler where CM::Target: AChannelManager, - K::Target: KVStore, - T::Target: BroadcasterInterface, { type ProtocolMessage = LSPS2Message; const PROTOCOL_NUMBER: Option = Some(2); @@ -2119,20 +2113,21 @@ fn calculate_amount_to_forward_per_htlc( /// A synchroneous wrapper around [`LSPS2ServiceHandler`] to be used in contexts where async is not /// available. -pub struct LSPS2ServiceHandlerSync<'a, CM: Deref, K: Deref + Clone, T: Deref + Clone> -where +pub struct LSPS2ServiceHandlerSync< + 'a, + CM: Deref, + K: KVStore + Clone, + T: BroadcasterInterface + Clone, +> where CM::Target: AChannelManager, - K::Target: KVStore, - T::Target: BroadcasterInterface, { inner: &'a LSPS2ServiceHandler, } -impl<'a, CM: Deref, K: Deref + Clone, T: Deref + Clone> LSPS2ServiceHandlerSync<'a, CM, K, T> +impl<'a, CM: Deref, K: KVStore + Clone, T: BroadcasterInterface + Clone> + LSPS2ServiceHandlerSync<'a, CM, K, T> where CM::Target: AChannelManager, - K::Target: KVStore, - T::Target: BroadcasterInterface, { pub(crate) fn from_inner(inner: &'a LSPS2ServiceHandler) -> Self { Self { inner } diff --git a/lightning-liquidity/src/lsps5/client.rs b/lightning-liquidity/src/lsps5/client.rs index 1c6f8b8a250..26c0b180421 100644 --- a/lightning-liquidity/src/lsps5/client.rs +++ b/lightning-liquidity/src/lsps5/client.rs @@ -35,8 +35,6 @@ use alloc::collections::VecDeque; use alloc::string::String; use lightning::util::persist::KVStore; -use core::ops::Deref; - impl PartialEq for (LSPSRequestId, (LSPS5AppName, LSPS5WebhookUrl)) { fn eq(&self, other: &LSPSRequestId) -> bool { &self.0 == other @@ -125,11 +123,7 @@ impl PeerState { /// [`lsps5.list_webhooks`]: super::msgs::LSPS5Request::ListWebhooks /// [`lsps5.remove_webhook`]: super::msgs::LSPS5Request::RemoveWebhook /// [`LSPS5Validator`]: super::validator::LSPS5Validator -pub struct LSPS5ClientHandler -where - ES::Target: EntropySource, - K::Target: KVStore, -{ +pub struct LSPS5ClientHandler { pending_messages: Arc, pending_events: Arc>, entropy_source: ES, @@ -137,11 +131,7 @@ where _config: LSPS5ClientConfig, } -impl LSPS5ClientHandler -where - ES::Target: EntropySource, - K::Target: KVStore, -{ +impl LSPS5ClientHandler { /// Constructs an `LSPS5ClientHandler`. pub(crate) fn new( entropy_source: ES, pending_messages: Arc, @@ -426,10 +416,8 @@ where } } -impl LSPSProtocolMessageHandler for LSPS5ClientHandler -where - ES::Target: EntropySource, - K::Target: KVStore, +impl LSPSProtocolMessageHandler + for LSPS5ClientHandler { type ProtocolMessage = LSPS5Message; const PROTOCOL_NUMBER: Option = Some(5); diff --git a/lightning-liquidity/src/lsps5/service.rs b/lightning-liquidity/src/lsps5/service.rs index 53fa96ee565..4678d38dc9a 100644 --- a/lightning-liquidity/src/lsps5/service.rs +++ b/lightning-liquidity/src/lsps5/service.rs @@ -125,11 +125,9 @@ impl Default for LSPS5ServiceConfig { /// [`LSPS5ServiceEvent::SendWebhookNotification`]: super::event::LSPS5ServiceEvent::SendWebhookNotification /// [`app_name`]: super::msgs::LSPS5AppName /// [`lsps5.webhook_registered`]: super::msgs::WebhookNotificationMethod::LSPS5WebhookRegistered -pub struct LSPS5ServiceHandler +pub struct LSPS5ServiceHandler where CM::Target: AChannelManager, - NS::Target: NodeSigner, - K::Target: KVStore, TP::Target: TimeProvider, { config: LSPS5ServiceConfig, @@ -144,11 +142,9 @@ where persistence_in_flight: AtomicUsize, } -impl LSPS5ServiceHandler +impl LSPS5ServiceHandler where CM::Target: AChannelManager, - NS::Target: NodeSigner, - K::Target: KVStore, TP::Target: TimeProvider, { /// Constructs a `LSPS5ServiceHandler` using the given time provider. @@ -694,12 +690,10 @@ where } } -impl LSPSProtocolMessageHandler +impl LSPSProtocolMessageHandler for LSPS5ServiceHandler where CM::Target: AChannelManager, - NS::Target: NodeSigner, - K::Target: KVStore, TP::Target: TimeProvider, { type ProtocolMessage = LSPS5Message; diff --git a/lightning-liquidity/src/manager.rs b/lightning-liquidity/src/manager.rs index 0b4f5efaa3c..c3e9fa48cca 100644 --- a/lightning-liquidity/src/manager.rs +++ b/lightning-liquidity/src/manager.rs @@ -104,13 +104,9 @@ pub struct LiquidityClientConfig { /// languages. pub trait ALiquidityManager { /// A type implementing [`EntropySource`] - type EntropySource: EntropySource + ?Sized; - /// A type that may be dereferenced to [`Self::EntropySource`]. - type ES: Deref + Clone; + type EntropySource: EntropySource + Clone; /// A type implementing [`NodeSigner`] - type NodeSigner: NodeSigner + ?Sized; - /// A type that may be dereferenced to [`Self::NodeSigner`]. - type NS: Deref + Clone; + type NodeSigner: NodeSigner + Clone; /// A type implementing [`AChannelManager`] type AChannelManager: AChannelManager + ?Sized; /// A type that may be dereferenced to [`Self::AChannelManager`]. @@ -120,55 +116,51 @@ pub trait ALiquidityManager { /// A type that may be dereferenced to [`Self::Filter`]. type C: Deref + Clone; /// A type implementing [`KVStore`]. - type KVStore: KVStore + ?Sized; - /// A type that may be dereferenced to [`Self::KVStore`]. - type K: Deref + Clone; + type K: KVStore + Clone; /// A type implementing [`TimeProvider`]. type TimeProvider: TimeProvider + ?Sized; /// A type that may be dereferenced to [`Self::TimeProvider`]. type TP: Deref + Clone; /// A type implementing [`BroadcasterInterface`]. - type BroadcasterInterface: BroadcasterInterface + ?Sized; - /// A type that may be dereferenced to [`Self::BroadcasterInterface`]. - type T: Deref + Clone; + type BroadcasterInterface: BroadcasterInterface + Clone; /// Returns a reference to the actual [`LiquidityManager`] object. fn get_lm( &self, - ) -> &LiquidityManager; + ) -> &LiquidityManager< + Self::EntropySource, + Self::NodeSigner, + Self::CM, + Self::C, + Self::K, + Self::TP, + Self::BroadcasterInterface, + >; } impl< - ES: Deref + Clone, - NS: Deref + Clone, + ES: EntropySource + Clone, + NS: NodeSigner + Clone, CM: Deref + Clone, C: Deref + Clone, - K: Deref + Clone, + K: KVStore + Clone, TP: Deref + Clone, - T: Deref + Clone, + T: BroadcasterInterface + Clone, > ALiquidityManager for LiquidityManager where - ES::Target: EntropySource, - NS::Target: NodeSigner, CM::Target: AChannelManager, C::Target: Filter, - K::Target: KVStore, TP::Target: TimeProvider, - T::Target: BroadcasterInterface, { - type EntropySource = ES::Target; - type ES = ES; - type NodeSigner = NS::Target; - type NS = NS; + type EntropySource = ES; + type NodeSigner = NS; type AChannelManager = CM::Target; type CM = CM; type Filter = C::Target; type C = C; - type KVStore = K::Target; type K = K; type TimeProvider = TP::Target; type TP = TP; - type BroadcasterInterface = T::Target; - type T = T; + type BroadcasterInterface = T; fn get_lm(&self) -> &LiquidityManager { self } @@ -180,13 +172,9 @@ where /// languages. pub trait ALiquidityManagerSync { /// A type implementing [`EntropySource`] - type EntropySource: EntropySource + ?Sized; - /// A type that may be dereferenced to [`Self::EntropySource`]. - type ES: Deref + Clone; + type EntropySource: EntropySource + Clone; /// A type implementing [`NodeSigner`] - type NodeSigner: NodeSigner + ?Sized; - /// A type that may be dereferenced to [`Self::NodeSigner`]. - type NS: Deref + Clone; + type NodeSigner: NodeSigner + Clone; /// A type implementing [`AChannelManager`] type AChannelManager: AChannelManager + ?Sized; /// A type that may be dereferenced to [`Self::AChannelManager`]. @@ -204,50 +192,51 @@ pub trait ALiquidityManagerSync { /// A type that may be dereferenced to [`Self::TimeProvider`]. type TP: Deref + Clone; /// A type implementing [`BroadcasterInterface`]. - type BroadcasterInterface: BroadcasterInterface + ?Sized; - /// A type that may be dereferenced to [`Self::BroadcasterInterface`]. - type T: Deref + Clone; + type BroadcasterInterface: BroadcasterInterface + Clone; /// Returns the inner async [`LiquidityManager`] for testing purposes. #[cfg(any(test, feature = "_test_utils"))] fn get_lm_async( &self, ) -> &LiquidityManager< - Self::ES, - Self::NS, + Self::EntropySource, + Self::NodeSigner, Self::CM, Self::C, KVStoreSyncWrapper, Self::TP, - Self::T, + Self::BroadcasterInterface, >; /// Returns a reference to the actual [`LiquidityManager`] object. fn get_lm( &self, - ) -> &LiquidityManagerSync; + ) -> &LiquidityManagerSync< + Self::EntropySource, + Self::NodeSigner, + Self::CM, + Self::C, + Self::KS, + Self::TP, + Self::BroadcasterInterface, + >; } impl< - ES: Deref + Clone, - NS: Deref + Clone, + ES: EntropySource + Clone, + NS: NodeSigner + Clone, CM: Deref + Clone, C: Deref + Clone, KS: Deref + Clone, TP: Deref + Clone, - T: Deref + Clone, + T: BroadcasterInterface + Clone, > ALiquidityManagerSync for LiquidityManagerSync where - ES::Target: EntropySource, - NS::Target: NodeSigner, CM::Target: AChannelManager, C::Target: Filter, KS::Target: KVStoreSync, TP::Target: TimeProvider, - T::Target: BroadcasterInterface, { - type EntropySource = ES::Target; - type ES = ES; - type NodeSigner = NS::Target; - type NS = NS; + type EntropySource = ES; + type NodeSigner = NS; type AChannelManager = CM::Target; type CM = CM; type Filter = C::Target; @@ -256,20 +245,19 @@ where type KS = KS; type TimeProvider = TP::Target; type TP = TP; - type BroadcasterInterface = T::Target; - type T = T; + type BroadcasterInterface = T; /// Returns the inner async [`LiquidityManager`] for testing purposes. #[cfg(any(test, feature = "_test_utils"))] fn get_lm_async( &self, ) -> &LiquidityManager< - Self::ES, - Self::NS, + Self::EntropySource, + Self::NodeSigner, Self::CM, Self::C, KVStoreSyncWrapper, Self::TP, - Self::T, + Self::BroadcasterInterface, > { &self.inner } @@ -298,21 +286,17 @@ where /// [`Event::HTLCHandlingFailed`]: lightning::events::Event::HTLCHandlingFailed /// [`Event::PaymentForwarded`]: lightning::events::Event::PaymentForwarded pub struct LiquidityManager< - ES: Deref + Clone, - NS: Deref + Clone, + ES: EntropySource + Clone, + NS: NodeSigner + Clone, CM: Deref + Clone, C: Deref + Clone, - K: Deref + Clone, + K: KVStore + Clone, TP: Deref + Clone, - T: Deref + Clone, + T: BroadcasterInterface + Clone, > where - ES::Target: EntropySource, - NS::Target: NodeSigner, CM::Target: AChannelManager, C::Target: Filter, - K::Target: KVStore, TP::Target: TimeProvider, - T::Target: BroadcasterInterface, { pending_messages: Arc, pending_events: Arc>, @@ -337,20 +321,16 @@ pub struct LiquidityManager< #[cfg(feature = "time")] impl< - ES: Deref + Clone, - NS: Deref + Clone, + ES: EntropySource + Clone, + NS: NodeSigner + Clone, CM: Deref + Clone, C: Deref + Clone, - K: Deref + Clone, - T: Deref + Clone, + K: KVStore + Clone, + T: BroadcasterInterface + Clone, > LiquidityManager where - ES::Target: EntropySource, - NS::Target: NodeSigner, CM::Target: AChannelManager, C::Target: Filter, - K::Target: KVStore, - T::Target: BroadcasterInterface, { /// Constructor for the [`LiquidityManager`] using the default system clock /// @@ -378,22 +358,18 @@ where } impl< - ES: Deref + Clone, - NS: Deref + Clone, + ES: EntropySource + Clone, + NS: NodeSigner + Clone, CM: Deref + Clone, C: Deref + Clone, - K: Deref + Clone, + K: KVStore + Clone, TP: Deref + Clone, - T: Deref + Clone, + T: BroadcasterInterface + Clone, > LiquidityManager where - ES::Target: EntropySource, - NS::Target: NodeSigner, CM::Target: AChannelManager, C::Target: Filter, - K::Target: KVStore, TP::Target: TimeProvider, - T::Target: BroadcasterInterface, { /// Constructor for the [`LiquidityManager`] with a custom time provider. /// @@ -805,22 +781,18 @@ where } impl< - ES: Deref + Clone, - NS: Deref + Clone, + ES: EntropySource + Clone, + NS: NodeSigner + Clone, CM: Deref + Clone, C: Deref + Clone, - K: Deref + Clone, + K: KVStore + Clone, TP: Deref + Clone, - T: Deref + Clone, + T: BroadcasterInterface + Clone, > CustomMessageReader for LiquidityManager where - ES::Target: EntropySource, - NS::Target: NodeSigner, CM::Target: AChannelManager, C::Target: Filter, - K::Target: KVStore, TP::Target: TimeProvider, - T::Target: BroadcasterInterface, { type CustomMessage = RawLSPSMessage; @@ -837,22 +809,18 @@ where } impl< - ES: Deref + Clone, - NS: Deref + Clone, + ES: EntropySource + Clone, + NS: NodeSigner + Clone, CM: Deref + Clone, C: Deref + Clone, - K: Deref + Clone, + K: KVStore + Clone, TP: Deref + Clone, - T: Deref + Clone, + T: BroadcasterInterface + Clone, > CustomMessageHandler for LiquidityManager where - ES::Target: EntropySource, - NS::Target: NodeSigner, CM::Target: AChannelManager, C::Target: Filter, - K::Target: KVStore, TP::Target: TimeProvider, - T::Target: BroadcasterInterface, { fn handle_custom_message( &self, msg: Self::CustomMessage, sender_node_id: PublicKey, @@ -971,22 +939,18 @@ where } impl< - ES: Deref + Clone, - NS: Deref + Clone, + ES: EntropySource + Clone, + NS: NodeSigner + Clone, CM: Deref + Clone, C: Deref + Clone, - K: Deref + Clone, + K: KVStore + Clone, TP: Deref + Clone, - T: Deref + Clone, + T: BroadcasterInterface + Clone, > Listen for LiquidityManager where - ES::Target: EntropySource, - NS::Target: NodeSigner, CM::Target: AChannelManager, C::Target: Filter, - K::Target: KVStore, TP::Target: TimeProvider, - T::Target: BroadcasterInterface, { fn filtered_block_connected( &self, header: &bitcoin::block::Header, txdata: &chain::transaction::TransactionData, @@ -1017,22 +981,18 @@ where } impl< - ES: Deref + Clone, - NS: Deref + Clone, + ES: EntropySource + Clone, + NS: NodeSigner + Clone, CM: Deref + Clone, C: Deref + Clone, - K: Deref + Clone, + K: KVStore + Clone, TP: Deref + Clone, - T: Deref + Clone, + T: BroadcasterInterface + Clone, > Confirm for LiquidityManager where - ES::Target: EntropySource, - NS::Target: NodeSigner, CM::Target: AChannelManager, C::Target: Filter, - K::Target: KVStore, TP::Target: TimeProvider, - T::Target: BroadcasterInterface, { fn transactions_confirmed( &self, _header: &bitcoin::block::Header, _txdata: &chain::transaction::TransactionData, @@ -1063,41 +1023,35 @@ where /// A synchroneous wrapper around [`LiquidityManager`] to be used in contexts where async is not /// available. pub struct LiquidityManagerSync< - ES: Deref + Clone, - NS: Deref + Clone, + ES: EntropySource + Clone, + NS: NodeSigner + Clone, CM: Deref + Clone, C: Deref + Clone, KS: Deref + Clone, TP: Deref + Clone, - T: Deref + Clone, + T: BroadcasterInterface + Clone, > where - ES::Target: EntropySource, - NS::Target: NodeSigner, CM::Target: AChannelManager, C::Target: Filter, KS::Target: KVStoreSync, TP::Target: TimeProvider, - T::Target: BroadcasterInterface, { inner: LiquidityManager, TP, T>, } #[cfg(feature = "time")] impl< - ES: Deref + Clone, - NS: Deref + Clone, + ES: EntropySource + Clone, + NS: NodeSigner + Clone, CM: Deref + Clone, C: Deref + Clone, KS: Deref + Clone, - T: Deref + Clone, + T: BroadcasterInterface + Clone, > LiquidityManagerSync where - ES::Target: EntropySource, - NS::Target: NodeSigner, CM::Target: AChannelManager, KS::Target: KVStoreSync, C::Target: Filter, - T::Target: BroadcasterInterface, { /// Constructor for the [`LiquidityManagerSync`] using the default system clock /// @@ -1136,22 +1090,19 @@ where } impl< - ES: Deref + Clone, - NS: Deref + Clone, + ES: EntropySource + Clone, + NS: NodeSigner + Clone, CM: Deref + Clone, C: Deref + Clone, KS: Deref + Clone, TP: Deref + Clone, - T: Deref + Clone, + T: BroadcasterInterface + Clone, > LiquidityManagerSync where - ES::Target: EntropySource, - NS::Target: NodeSigner, CM::Target: AChannelManager, C::Target: Filter, KS::Target: KVStoreSync, TP::Target: TimeProvider, - T::Target: BroadcasterInterface, { /// Constructor for the [`LiquidityManagerSync`] with a custom time provider. /// @@ -1306,22 +1257,19 @@ where } impl< - ES: Deref + Clone, - NS: Deref + Clone, + ES: EntropySource + Clone, + NS: NodeSigner + Clone, CM: Deref + Clone, C: Deref + Clone, KS: Deref + Clone, TP: Deref + Clone, - T: Deref + Clone, + T: BroadcasterInterface + Clone, > CustomMessageReader for LiquidityManagerSync where - ES::Target: EntropySource, - NS::Target: NodeSigner, CM::Target: AChannelManager, C::Target: Filter, KS::Target: KVStoreSync, TP::Target: TimeProvider, - T::Target: BroadcasterInterface, { type CustomMessage = RawLSPSMessage; @@ -1333,22 +1281,19 @@ where } impl< - ES: Deref + Clone, - NS: Deref + Clone, + ES: EntropySource + Clone, + NS: NodeSigner + Clone, CM: Deref + Clone, C: Deref + Clone, KS: Deref + Clone, TP: Deref + Clone, - T: Deref + Clone, + T: BroadcasterInterface + Clone, > CustomMessageHandler for LiquidityManagerSync where - ES::Target: EntropySource, - NS::Target: NodeSigner, CM::Target: AChannelManager, C::Target: Filter, KS::Target: KVStoreSync, TP::Target: TimeProvider, - T::Target: BroadcasterInterface, { fn handle_custom_message( &self, msg: Self::CustomMessage, sender_node_id: PublicKey, @@ -1380,22 +1325,19 @@ where } impl< - ES: Deref + Clone, - NS: Deref + Clone, + ES: EntropySource + Clone, + NS: NodeSigner + Clone, CM: Deref + Clone, C: Deref + Clone, KS: Deref + Clone, TP: Deref + Clone, - T: Deref + Clone, + T: BroadcasterInterface + Clone, > Listen for LiquidityManagerSync where - ES::Target: EntropySource, - NS::Target: NodeSigner, CM::Target: AChannelManager, C::Target: Filter, KS::Target: KVStoreSync, TP::Target: TimeProvider, - T::Target: BroadcasterInterface, { fn filtered_block_connected( &self, header: &bitcoin::block::Header, txdata: &chain::transaction::TransactionData, @@ -1410,22 +1352,19 @@ where } impl< - ES: Deref + Clone, - NS: Deref + Clone, + ES: EntropySource + Clone, + NS: NodeSigner + Clone, CM: Deref + Clone, C: Deref + Clone, KS: Deref + Clone, TP: Deref + Clone, - T: Deref + Clone, + T: BroadcasterInterface + Clone, > Confirm for LiquidityManagerSync where - ES::Target: EntropySource, - NS::Target: NodeSigner, CM::Target: AChannelManager, C::Target: Filter, KS::Target: KVStoreSync, TP::Target: TimeProvider, - T::Target: BroadcasterInterface, { fn transactions_confirmed( &self, header: &bitcoin::block::Header, txdata: &chain::transaction::TransactionData, diff --git a/lightning-liquidity/src/persist.rs b/lightning-liquidity/src/persist.rs index ec0d5a6ddd3..d0199440514 100644 --- a/lightning-liquidity/src/persist.rs +++ b/lightning-liquidity/src/persist.rs @@ -22,8 +22,6 @@ use lightning::util::ser::Readable; use bitcoin::secp256k1::PublicKey; use alloc::collections::VecDeque; - -use core::ops::Deref; use core::str::FromStr; /// The primary namespace under which the [`LiquidityManager`] will be persisted. @@ -51,12 +49,9 @@ pub const LSPS2_SERVICE_PERSISTENCE_SECONDARY_NAMESPACE: &str = "lsps2_service"; /// [`LSPS5ServiceHandler`]: crate::lsps5::service::LSPS5ServiceHandler pub const LSPS5_SERVICE_PERSISTENCE_SECONDARY_NAMESPACE: &str = "lsps5_service"; -pub(crate) async fn read_event_queue( +pub(crate) async fn read_event_queue( kv_store: K, -) -> Result>, lightning::io::Error> -where - K::Target: KVStore, -{ +) -> Result>, lightning::io::Error> { let read_fut = kv_store.read( LIQUIDITY_MANAGER_PERSISTENCE_PRIMARY_NAMESPACE, LIQUIDITY_MANAGER_EVENT_QUEUE_PERSISTENCE_SECONDARY_NAMESPACE, @@ -85,12 +80,9 @@ where Ok(Some(queue.0)) } -pub(crate) async fn read_lsps2_service_peer_states( +pub(crate) async fn read_lsps2_service_peer_states( kv_store: K, -) -> Result>, lightning::io::Error> -where - K::Target: KVStore, -{ +) -> Result>, lightning::io::Error> { let mut res = new_hash_map(); for stored_key in kv_store @@ -129,12 +121,9 @@ where Ok(res) } -pub(crate) async fn read_lsps5_service_peer_states( +pub(crate) async fn read_lsps5_service_peer_states( kv_store: K, -) -> Result, lightning::io::Error> -where - K::Target: KVStore, -{ +) -> Result, lightning::io::Error> { let mut res = new_hash_map(); for stored_key in kv_store diff --git a/lightning-liquidity/src/utils/mod.rs b/lightning-liquidity/src/utils/mod.rs index b66d3eb7ead..32b50443350 100644 --- a/lightning-liquidity/src/utils/mod.rs +++ b/lightning-liquidity/src/utils/mod.rs @@ -1,7 +1,7 @@ //! Utilities for LSPS5 service. use alloc::string::String; -use core::{fmt::Write, ops::Deref}; +use core::fmt::Write; use lightning::sign::EntropySource; @@ -23,10 +23,7 @@ pub fn scid_from_human_readable_string(human_readable_scid: &str) -> Result(entropy_source: &ES) -> LSPSRequestId -where - ES::Target: EntropySource, -{ +pub(crate) fn generate_request_id(entropy_source: &ES) -> LSPSRequestId { let bytes = entropy_source.get_secure_random_bytes(); LSPSRequestId(hex_str(&bytes[0..16])) } diff --git a/lightning-rapid-gossip-sync/src/lib.rs b/lightning-rapid-gossip-sync/src/lib.rs index 429a3560be0..a9653754655 100644 --- a/lightning-rapid-gossip-sync/src/lib.rs +++ b/lightning-rapid-gossip-sync/src/lib.rs @@ -132,19 +132,13 @@ impl From for GraphSyncError { /// See [crate-level documentation] for usage. /// /// [crate-level documentation]: crate -pub struct RapidGossipSync>, L: Deref> -where - L::Target: Logger, -{ +pub struct RapidGossipSync>, L: Logger> { network_graph: NG, logger: L, is_initial_sync_complete: AtomicBool, } -impl>, L: Deref> RapidGossipSync -where - L::Target: Logger, -{ +impl>, L: Logger> RapidGossipSync { /// Instantiate a new [`RapidGossipSync`] instance. pub fn new(network_graph: NG, logger: L) -> Self { Self { network_graph, logger, is_initial_sync_complete: AtomicBool::new(false) } diff --git a/lightning-rapid-gossip-sync/src/processing.rs b/lightning-rapid-gossip-sync/src/processing.rs index 8319506b574..9d3287969f2 100644 --- a/lightning-rapid-gossip-sync/src/processing.rs +++ b/lightning-rapid-gossip-sync/src/processing.rs @@ -37,10 +37,7 @@ const MAX_INITIAL_NODE_ID_VECTOR_CAPACITY: u32 = 50_000; /// suggestion. const STALE_RGS_UPDATE_AGE_LIMIT_SECS: u64 = 60 * 60 * 24 * 14; -impl>, L: Deref> RapidGossipSync -where - L::Target: Logger, -{ +impl>, L: Logger> RapidGossipSync { #[cfg(feature = "std")] pub(crate) fn update_network_graph_from_byte_stream( &self, read_cursor: &mut R, diff --git a/lightning-transaction-sync/src/electrum.rs b/lightning-transaction-sync/src/electrum.rs index 47489df69bb..762f1686c75 100644 --- a/lightning-transaction-sync/src/electrum.rs +++ b/lightning-transaction-sync/src/electrum.rs @@ -37,20 +37,14 @@ use std::time::Instant; /// [`ChainMonitor`]: lightning::chain::chainmonitor::ChainMonitor /// [`Watch::watch_channel`]: lightning::chain::Watch::watch_channel /// [`Filter`]: lightning::chain::Filter -pub struct ElectrumSyncClient -where - L::Target: Logger, -{ +pub struct ElectrumSyncClient { sync_state: Mutex, queue: Mutex, client: Arc, logger: L, } -impl ElectrumSyncClient -where - L::Target: Logger, -{ +impl ElectrumSyncClient { /// Returns a new [`ElectrumSyncClient`] object. pub fn new(server_url: String, logger: L) -> Result { let client = Arc::new(ElectrumClient::new(&server_url).map_err(|e| { @@ -494,10 +488,7 @@ where } } -impl Filter for ElectrumSyncClient -where - L::Target: Logger, -{ +impl Filter for ElectrumSyncClient { fn register_tx(&self, txid: &Txid, _script_pubkey: &Script) { let mut locked_queue = self.queue.lock().unwrap(); locked_queue.transactions.insert(*txid); diff --git a/lightning-transaction-sync/src/esplora.rs b/lightning-transaction-sync/src/esplora.rs index a191260bc01..6caf7a6a7ee 100644 --- a/lightning-transaction-sync/src/esplora.rs +++ b/lightning-transaction-sync/src/esplora.rs @@ -42,20 +42,14 @@ use std::collections::HashSet; /// [`ChainMonitor`]: lightning::chain::chainmonitor::ChainMonitor /// [`Watch::watch_channel`]: lightning::chain::Watch::watch_channel /// [`Filter`]: lightning::chain::Filter -pub struct EsploraSyncClient -where - L::Target: Logger, -{ +pub struct EsploraSyncClient { sync_state: MutexType, queue: std::sync::Mutex, client: EsploraClientType, logger: L, } -impl EsploraSyncClient -where - L::Target: Logger, -{ +impl EsploraSyncClient { /// Returns a new [`EsploraSyncClient`] object. pub fn new(server_url: String, logger: L) -> Self { let builder = Builder::new(&server_url); @@ -472,10 +466,7 @@ type EsploraClientType = AsyncClient; #[cfg(not(feature = "async-interface"))] type EsploraClientType = BlockingClient; -impl Filter for EsploraSyncClient -where - L::Target: Logger, -{ +impl Filter for EsploraSyncClient { fn register_tx(&self, txid: &Txid, _script_pubkey: &Script) { let mut locked_queue = self.queue.lock().unwrap(); locked_queue.transactions.insert(*txid); diff --git a/lightning/src/blinded_path/message.rs b/lightning/src/blinded_path/message.rs index 84a42ff1be2..7bcbe80a965 100644 --- a/lightning/src/blinded_path/message.rs +++ b/lightning/src/blinded_path/message.rs @@ -31,7 +31,6 @@ use crate::types::payment::PaymentHash; use crate::util::scid_utils; use crate::util::ser::{FixedLengthReader, LengthReadableArgs, Readable, Writeable, Writer}; -use core::ops::Deref; use core::time::Duration; use core::{cmp, mem}; @@ -58,14 +57,11 @@ impl BlindedMessagePath { /// `compact_padding` selects between space-inefficient padding which better hides contents and /// a space-constrained padding which does very little to hide the contents, especially for the /// last hop. It should only be set when the blinded path needs to be as compact as possible. - pub fn one_hop( + pub fn one_hop( recipient_node_id: PublicKey, local_node_receive_key: ReceiveAuthKey, context: MessageContext, compact_padding: bool, entropy_source: ES, secp_ctx: &Secp256k1, - ) -> Self - where - ES::Target: EntropySource, - { + ) -> Self { Self::new( &[], recipient_node_id, @@ -82,14 +78,11 @@ impl BlindedMessagePath { /// `compact_padding` selects between space-inefficient padding which better hides contents and /// a space-constrained padding which does very little to hide the contents, especially for the /// last hop. It should only be set when the blinded path needs to be as compact as possible. - pub fn new( + pub fn new( intermediate_nodes: &[MessageForwardNode], recipient_node_id: PublicKey, local_node_receive_key: ReceiveAuthKey, context: MessageContext, compact_padding: bool, entropy_source: ES, secp_ctx: &Secp256k1, - ) -> Self - where - ES::Target: EntropySource, - { + ) -> Self { BlindedMessagePath::new_with_dummy_hops( intermediate_nodes, recipient_node_id, @@ -109,14 +102,14 @@ impl BlindedMessagePath { /// last hop. It should only be set when the blinded path needs to be as compact as possible. /// /// Note: At most [`MAX_DUMMY_HOPS_COUNT`] dummy hops can be added to the blinded path. - pub fn new_with_dummy_hops( + pub fn new_with_dummy_hops< + ES: EntropySource, + T: secp256k1::Signing + secp256k1::Verification, + >( intermediate_nodes: &[MessageForwardNode], recipient_node_id: PublicKey, dummy_hop_count: usize, local_node_receive_key: ReceiveAuthKey, context: MessageContext, compact_padding: bool, entropy_source: ES, secp_ctx: &Secp256k1, - ) -> Self - where - ES::Target: EntropySource, - { + ) -> Self { let introduction_node = IntroductionNode::NodeId( intermediate_nodes.first().map_or(recipient_node_id, |n| n.node_id), ); @@ -198,12 +191,10 @@ impl BlindedMessagePath { /// introduction node. /// /// Will only modify `self` when returning `Ok`. - pub fn advance_path_by_one( + pub fn advance_path_by_one( &mut self, node_signer: &NS, node_id_lookup: &NL, secp_ctx: &Secp256k1, ) -> Result<(), ()> where - NS::Target: NodeSigner, - NL::Target: NodeIdLookUp, T: secp256k1::Signing + secp256k1::Verification, { let control_tlvs_ss = node_signer.ecdh(Recipient::Node, &self.0.blinding_point, None)?; diff --git a/lightning/src/blinded_path/mod.rs b/lightning/src/blinded_path/mod.rs index 2f9b1b9a411..d1f58c8c1d9 100644 --- a/lightning/src/blinded_path/mod.rs +++ b/lightning/src/blinded_path/mod.rs @@ -88,10 +88,9 @@ impl NodeIdLookUp for EmptyNodeIdLookUp { } } -impl Deref for EmptyNodeIdLookUp { - type Target = EmptyNodeIdLookUp; - fn deref(&self) -> &Self { - self +impl> NodeIdLookUp for N { + fn next_node_id(&self, short_channel_id: u64) -> Option { + self.deref().next_node_id(short_channel_id) } } diff --git a/lightning/src/blinded_path/payment.rs b/lightning/src/blinded_path/payment.rs index 13ade222f5b..b9aa6d4cac6 100644 --- a/lightning/src/blinded_path/payment.rs +++ b/lightning/src/blinded_path/payment.rs @@ -34,7 +34,6 @@ use crate::util::ser::{ }; use core::mem; -use core::ops::Deref; #[allow(unused_imports)] use crate::prelude::*; @@ -88,13 +87,10 @@ pub struct BlindedPaymentPath { impl BlindedPaymentPath { /// Create a one-hop blinded path for a payment. - pub fn one_hop( + pub fn one_hop( payee_node_id: PublicKey, local_node_receive_key: ReceiveAuthKey, payee_tlvs: ReceiveTlvs, min_final_cltv_expiry_delta: u16, entropy_source: ES, secp_ctx: &Secp256k1, - ) -> Result - where - ES::Target: EntropySource, - { + ) -> Result { // This value is not considered in pathfinding for 1-hop blinded paths, because it's intended to // be in relation to a specific channel. let htlc_maximum_msat = u64::max_value(); @@ -116,14 +112,11 @@ impl BlindedPaymentPath { /// * [`BlindedPayInfo`] calculation results in an integer overflow /// * any unknown features are required in the provided [`ForwardTlvs`] // TODO: make all payloads the same size with padding + add dummy hops - pub fn new( + pub fn new( intermediate_nodes: &[PaymentForwardNode], payee_node_id: PublicKey, local_node_receive_key: ReceiveAuthKey, payee_tlvs: ReceiveTlvs, htlc_maximum_msat: u64, min_final_cltv_expiry_delta: u16, entropy_source: ES, secp_ctx: &Secp256k1, - ) -> Result - where - ES::Target: EntropySource, - { + ) -> Result { let introduction_node = IntroductionNode::NodeId( intermediate_nodes.first().map_or(payee_node_id, |n| n.node_id), ); @@ -183,15 +176,13 @@ impl BlindedPaymentPath { /// introduction node. /// /// Will only modify `self` when returning `Ok`. - pub fn advance_path_by_one( + pub fn advance_path_by_one( &mut self, node_signer: &NS, node_id_lookup: &NL, secp_ctx: &Secp256k1, ) -> Result<(), ()> where - NS::Target: NodeSigner, - NL::Target: NodeIdLookUp, T: secp256k1::Signing + secp256k1::Verification, { - match self.decrypt_intro_payload::(node_signer) { + match self.decrypt_intro_payload(node_signer) { Ok(( BlindedPaymentTlvs::Forward(ForwardTlvs { short_channel_id, .. }), control_tlvs_ss, @@ -215,12 +206,9 @@ impl BlindedPaymentPath { } } - pub(crate) fn decrypt_intro_payload( + pub(crate) fn decrypt_intro_payload( &self, node_signer: &NS, - ) -> Result<(BlindedPaymentTlvs, SharedSecret), ()> - where - NS::Target: NodeSigner, - { + ) -> Result<(BlindedPaymentTlvs, SharedSecret), ()> { let control_tlvs_ss = node_signer.ecdh(Recipient::Node, &self.inner_path.blinding_point, None)?; let rho = onion_utils::gen_rho_from_shared_secret(&control_tlvs_ss.secret_bytes()); diff --git a/lightning/src/chain/chaininterface.rs b/lightning/src/chain/chaininterface.rs index 117e9b3af05..7e71d960e67 100644 --- a/lightning/src/chain/chaininterface.rs +++ b/lightning/src/chain/chaininterface.rs @@ -48,6 +48,12 @@ pub trait BroadcasterInterface { fn broadcast_transactions(&self, txs: &[&Transaction]); } +impl> BroadcasterInterface for B { + fn broadcast_transactions(&self, txs: &[&Transaction]) { + self.deref().broadcast_transactions(txs) + } +} + /// An enum that represents the priority at which we want a transaction to confirm used for feerate /// estimation. #[derive(Clone, Copy, Debug, Hash, PartialEq, Eq)] @@ -181,6 +187,12 @@ pub trait FeeEstimator { fn get_est_sat_per_1000_weight(&self, confirmation_target: ConfirmationTarget) -> u32; } +impl> FeeEstimator for F { + fn get_est_sat_per_1000_weight(&self, confirmation_target: ConfirmationTarget) -> u32 { + self.deref().get_est_sat_per_1000_weight(confirmation_target) + } +} + /// Minimum relay fee as required by bitcoin network mempool policy. pub const INCREMENTAL_RELAY_FEE_SAT_PER_1000_WEIGHT: u64 = 253; /// Minimum feerate that takes a sane approach to bitcoind weight-to-vbytes rounding. @@ -188,19 +200,14 @@ pub const INCREMENTAL_RELAY_FEE_SAT_PER_1000_WEIGHT: u64 = 253; /// pub const FEERATE_FLOOR_SATS_PER_KW: u32 = 253; -/// Wraps a `Deref` to a `FeeEstimator` so that any fee estimations provided by it -/// are bounded below by `FEERATE_FLOOR_SATS_PER_KW` (253 sats/KW). +/// Wraps a [`FeeEstimator`] so that any fee estimations provided by it are bounded below by +/// `FEERATE_FLOOR_SATS_PER_KW` (253 sats/KW). /// /// 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); + +impl LowerBoundedFeeEstimator { /// Creates a new `LowerBoundedFeeEstimator` which wraps the provided fee_estimator pub fn new(fee_estimator: F) -> Self { LowerBoundedFeeEstimator(fee_estimator) diff --git a/lightning/src/chain/chainmonitor.rs b/lightning/src/chain/chainmonitor.rs index 9fd6383cf7e..3b34bfb1ba6 100644 --- a/lightning/src/chain/chainmonitor.rs +++ b/lightning/src/chain/chainmonitor.rs @@ -256,41 +256,27 @@ impl Deref for LockedChannelMonitor<'_, Chann /// /// This is not exported to bindings users as async is not supported outside of Rust. pub struct AsyncPersister< - K: Deref + MaybeSend + MaybeSync + 'static, + K: KVStore + MaybeSend + MaybeSync + 'static, S: FutureSpawner, - L: Deref + MaybeSend + MaybeSync + 'static, - ES: Deref + MaybeSend + MaybeSync + 'static, - SP: Deref + MaybeSend + MaybeSync + 'static, - BI: Deref + MaybeSend + MaybeSync + 'static, - FE: Deref + MaybeSend + MaybeSync + 'static, -> where - K::Target: KVStore + MaybeSync, - L::Target: Logger, - ES::Target: EntropySource + Sized, - SP::Target: SignerProvider + Sized, - BI::Target: BroadcasterInterface, - FE::Target: FeeEstimator, -{ + L: Logger + MaybeSend + MaybeSync + 'static, + ES: EntropySource + MaybeSend + MaybeSync + 'static, + SP: SignerProvider + MaybeSend + MaybeSync + 'static, + BI: BroadcasterInterface + MaybeSend + MaybeSync + 'static, + FE: FeeEstimator + MaybeSend + MaybeSync + 'static, +> { persister: MonitorUpdatingPersisterAsync, event_notifier: Arc, } impl< - K: Deref + MaybeSend + MaybeSync + 'static, + K: KVStore + MaybeSend + MaybeSync + 'static, S: FutureSpawner, - L: Deref + MaybeSend + MaybeSync + 'static, - ES: Deref + MaybeSend + MaybeSync + 'static, - SP: Deref + MaybeSend + MaybeSync + 'static, - BI: Deref + MaybeSend + MaybeSync + 'static, - FE: Deref + MaybeSend + MaybeSync + 'static, + L: Logger + MaybeSend + MaybeSync + 'static, + ES: EntropySource + MaybeSend + MaybeSync + 'static, + SP: SignerProvider + MaybeSend + MaybeSync + 'static, + BI: BroadcasterInterface + MaybeSend + MaybeSync + 'static, + FE: FeeEstimator + MaybeSend + MaybeSync + 'static, > Deref for AsyncPersister -where - K::Target: KVStore + MaybeSync, - L::Target: Logger, - ES::Target: EntropySource + Sized, - SP::Target: SignerProvider + Sized, - BI::Target: BroadcasterInterface, - FE::Target: FeeEstimator, { type Target = Self; fn deref(&self) -> &Self { @@ -299,26 +285,20 @@ where } impl< - K: Deref + MaybeSend + MaybeSync + 'static, + K: KVStore + MaybeSend + MaybeSync + 'static, S: FutureSpawner, - L: Deref + MaybeSend + MaybeSync + 'static, - ES: Deref + MaybeSend + MaybeSync + 'static, - SP: Deref + MaybeSend + MaybeSync + 'static, - BI: Deref + MaybeSend + MaybeSync + 'static, - FE: Deref + MaybeSend + MaybeSync + 'static, - > Persist<::EcdsaSigner> for AsyncPersister + L: Logger + MaybeSend + MaybeSync + 'static, + ES: EntropySource + MaybeSend + MaybeSync + 'static, + SP: SignerProvider + MaybeSend + MaybeSync + 'static, + BI: BroadcasterInterface + MaybeSend + MaybeSync + 'static, + FE: FeeEstimator + MaybeSend + MaybeSync + 'static, + > Persist<::EcdsaSigner> for AsyncPersister where - K::Target: KVStore + MaybeSync, - L::Target: Logger, - ES::Target: EntropySource + Sized, - SP::Target: SignerProvider + Sized, - BI::Target: BroadcasterInterface, - FE::Target: FeeEstimator, - ::EcdsaSigner: MaybeSend + 'static, + ::EcdsaSigner: MaybeSend + 'static, { fn persist_new_channel( &self, monitor_name: MonitorName, - monitor: &ChannelMonitor<::EcdsaSigner>, + monitor: &ChannelMonitor<::EcdsaSigner>, ) -> ChannelMonitorUpdateStatus { let notifier = Arc::clone(&self.event_notifier); self.persister.spawn_async_persist_new_channel(monitor_name, monitor, notifier); @@ -327,7 +307,7 @@ where fn update_persisted_channel( &self, monitor_name: MonitorName, monitor_update: Option<&ChannelMonitorUpdate>, - monitor: &ChannelMonitor<::EcdsaSigner>, + monitor: &ChannelMonitor<::EcdsaSigner>, ) -> ChannelMonitorUpdateStatus { let notifier = Arc::clone(&self.event_notifier); self.persister.spawn_async_update_channel(monitor_name, monitor_update, monitor, notifier); @@ -362,18 +342,14 @@ where pub struct ChainMonitor< ChannelSigner: EcdsaChannelSigner, C: Deref, - T: Deref, - F: Deref, - L: Deref, + T: BroadcasterInterface, + F: FeeEstimator, + L: Logger, P: Deref, - ES: Deref, + ES: EntropySource, > 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, @@ -400,17 +376,17 @@ pub struct ChainMonitor< } impl< - K: Deref + MaybeSend + MaybeSync + 'static, + K: KVStore + MaybeSend + MaybeSync + 'static, S: FutureSpawner, - SP: Deref + MaybeSend + MaybeSync + 'static, + SP: SignerProvider + MaybeSend + MaybeSync + 'static, C: Deref, - T: Deref + MaybeSend + MaybeSync + 'static, - F: Deref + MaybeSend + MaybeSync + 'static, - L: Deref + MaybeSend + MaybeSync + 'static, - ES: Deref + MaybeSend + MaybeSync + 'static, + T: BroadcasterInterface + MaybeSend + MaybeSync + 'static, + F: FeeEstimator + MaybeSend + MaybeSync + 'static, + L: Logger + MaybeSend + MaybeSync + 'static, + ES: EntropySource + MaybeSend + MaybeSync + 'static, > ChainMonitor< - ::EcdsaSigner, + ::EcdsaSigner, C, T, F, @@ -418,14 +394,8 @@ impl< AsyncPersister, ES, > where - K::Target: KVStore + MaybeSync, - SP::Target: SignerProvider + Sized, C::Target: chain::Filter, - T::Target: BroadcasterInterface, - F::Target: FeeEstimator, - L::Target: Logger, - ES::Target: EntropySource + Sized, - ::EcdsaSigner: MaybeSend + 'static, + ::EcdsaSigner: MaybeSend + 'static, { /// Creates a new `ChainMonitor` used to watch on-chain activity pertaining to channels. /// @@ -462,19 +432,15 @@ impl< impl< ChannelSigner: EcdsaChannelSigner, C: Deref, - T: Deref, - F: Deref, - L: Deref, + T: BroadcasterInterface, + F: FeeEstimator, + L: Logger, P: Deref, - ES: Deref, + ES: EntropySource, > 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 @@ -895,8 +861,8 @@ where let monitors = self.monitors.read().unwrap(); for (_, monitor_holder) in &*monitors { monitor_holder.monitor.rebroadcast_pending_claims( - &*self.broadcaster, - &*self.fee_estimator, + &self.broadcaster, + &self.fee_estimator, &self.logger, ) } @@ -911,16 +877,16 @@ where if let Some(channel_id) = monitor_opt { if let Some(monitor_holder) = monitors.get(&channel_id) { monitor_holder.monitor.signer_unblocked( - &*self.broadcaster, - &*self.fee_estimator, + &self.broadcaster, + &self.fee_estimator, &self.logger, ) } } else { for (_, monitor_holder) in &*monitors { monitor_holder.monitor.signer_unblocked( - &*self.broadcaster, - &*self.fee_estimator, + &self.broadcaster, + &self.fee_estimator, &self.logger, ) } @@ -1109,19 +1075,15 @@ where impl< ChannelSigner: EcdsaChannelSigner, C: Deref, - T: Deref, - F: Deref, - L: Deref, + T: BroadcasterInterface, + F: FeeEstimator, + L: Logger, P: Deref, - ES: Deref, + ES: EntropySource, > 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(); @@ -1148,38 +1110,30 @@ where impl< ChannelSigner: EcdsaChannelSigner, C: Deref, - T: Deref, - F: Deref, - L: Deref, + T: BroadcasterInterface, + F: FeeEstimator, + L: Logger, P: Deref, - ES: Deref, + ES: EntropySource, > SendOnlyMessageHandler 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, + T: BroadcasterInterface, + F: FeeEstimator, + L: Logger, P: Deref, - ES: Deref, + ES: EntropySource, > chain::Listen for ChainMonitor where C::Target: chain::Filter, - T::Target: BroadcasterInterface, - F::Target: FeeEstimator, - L::Target: Logger, P::Target: Persist, - ES::Target: EntropySource, { fn filtered_block_connected(&self, header: &Header, txdata: &TransactionData, height: u32) { log_debug!( @@ -1193,8 +1147,8 @@ where header, txdata, height, - &*self.broadcaster, - &*self.fee_estimator, + &self.broadcaster, + &self.fee_estimator, &self.logger, ) }); @@ -1220,8 +1174,8 @@ where for monitor_state in monitor_states.values() { monitor_state.monitor.blocks_disconnected( fork_point, - &*self.broadcaster, - &*self.fee_estimator, + &self.broadcaster, + &self.fee_estimator, &self.logger, ); } @@ -1231,19 +1185,15 @@ where impl< ChannelSigner: EcdsaChannelSigner, C: Deref, - T: Deref, - F: Deref, - L: Deref, + T: BroadcasterInterface, + F: FeeEstimator, + L: Logger, P: Deref, - ES: Deref, + ES: EntropySource, > chain::Confirm for ChainMonitor where C::Target: chain::Filter, - T::Target: BroadcasterInterface, - F::Target: FeeEstimator, - L::Target: Logger, P::Target: Persist, - ES::Target: EntropySource, { fn transactions_confirmed(&self, header: &Header, txdata: &TransactionData, height: u32) { log_debug!( @@ -1258,8 +1208,8 @@ where header, txdata, height, - &*self.broadcaster, - &*self.fee_estimator, + &self.broadcaster, + &self.fee_estimator, &self.logger, ) }); @@ -1273,8 +1223,8 @@ where for monitor_state in monitor_states.values() { monitor_state.monitor.transaction_unconfirmed( txid, - &*self.broadcaster, - &*self.fee_estimator, + &self.broadcaster, + &self.fee_estimator, &self.logger, ); } @@ -1294,8 +1244,8 @@ where monitor.best_block_updated( header, height, - &*self.broadcaster, - &*self.fee_estimator, + &self.broadcaster, + &self.fee_estimator, &self.logger, ) }); @@ -1326,19 +1276,15 @@ where impl< ChannelSigner: EcdsaChannelSigner, C: Deref, - T: Deref, - F: Deref, - L: Deref, + T: BroadcasterInterface, + F: FeeEstimator, + L: Logger, P: Deref, - ES: Deref, + ES: EntropySource, > chain::Watch for ChainMonitor where C::Target: chain::Filter, - T::Target: BroadcasterInterface, - F::Target: FeeEstimator, - L::Target: Logger, P::Target: Persist, - ES::Target: EntropySource, { fn watch_channel( &self, channel_id: ChannelId, monitor: ChannelMonitor, @@ -1522,19 +1468,15 @@ where impl< ChannelSigner: EcdsaChannelSigner, C: Deref, - T: Deref, - F: Deref, - L: Deref, + T: BroadcasterInterface, + F: FeeEstimator, + L: Logger, P: Deref, - ES: Deref, + ES: EntropySource, > 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. /// diff --git a/lightning/src/chain/channelmonitor.rs b/lightning/src/chain/channelmonitor.rs index 515a3dc5f1d..f6d54c958d6 100644 --- a/lightning/src/chain/channelmonitor.rs +++ b/lightning/src/chain/channelmonitor.rs @@ -1825,20 +1825,14 @@ 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: 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: Logger> Logger for WithChannelMonitor<'a, L> { fn log(&self, mut record: Record) { record.peer_id = self.peer_id; record.channel_id = self.channel_id; @@ -1847,10 +1841,7 @@ where } } -impl<'a, L: Deref> WithChannelMonitor<'a, L> -where - L::Target: Logger, -{ +impl<'a, L: Logger> WithChannelMonitor<'a, L> { pub(crate) fn from( logger: &'a L, monitor: &ChannelMonitor, payment_hash: Option, ) -> Self { @@ -2076,18 +2067,14 @@ impl ChannelMonitor { /// /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager #[rustfmt::skip] - pub(crate) fn provide_payment_preimage_unsafe_legacy( + pub(crate) fn provide_payment_preimage_unsafe_legacy( &self, payment_hash: &PaymentHash, payment_preimage: &PaymentPreimage, broadcaster: &B, fee_estimator: &LowerBoundedFeeEstimator, logger: &L, - ) where - B::Target: BroadcasterInterface, - F::Target: FeeEstimator, - L::Target: Logger, - { + ) { let mut inner = self.inner.lock().unwrap(); let logger = WithChannelMonitor::from_impl(logger, &*inner, Some(*payment_hash)); // Note that we don't pass any MPP claim parts here. This is generally not okay but in this @@ -2101,14 +2088,9 @@ impl ChannelMonitor { /// itself. /// /// panics if the given update is not the next update by update_id. - pub fn update_monitor( + pub fn update_monitor( &self, updates: &ChannelMonitorUpdate, broadcaster: &B, fee_estimator: &F, logger: &L, - ) -> Result<(), ()> - where - B::Target: BroadcasterInterface, - F::Target: FeeEstimator, - L::Target: Logger, - { + ) -> Result<(), ()> { let mut inner = self.inner.lock().unwrap(); let logger = WithChannelMonitor::from_impl(logger, &*inner, None); inner.update_monitor(updates, broadcaster, fee_estimator, &logger) @@ -2158,10 +2140,8 @@ impl ChannelMonitor { /// 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, - { + pub fn load_outputs_to_watch(&self, filter: &F, logger: &L) + where F::Target: chain::Filter { let lock = self.inner.lock().unwrap(); let logger = WithChannelMonitor::from_impl(logger, &*lock, None); for funding in core::iter::once(&lock.funding).chain(&lock.pending_funding) { @@ -2205,12 +2185,11 @@ impl ChannelMonitor { /// /// [`SpendableOutputs`]: crate::events::Event::SpendableOutputs /// [`BumpTransaction`]: crate::events::Event::BumpTransaction - pub fn process_pending_events( + 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)) @@ -2222,13 +2201,10 @@ impl ChannelMonitor { pub async fn process_pending_events_async< Future: core::future::Future>, H: Fn(Event) -> Future, - L: Deref, + L: Logger, >( &self, handler: &H, logger: &L, - ) -> Result<(), ReplayEvent> - where - L::Target: Logger, - { + ) -> Result<(), ReplayEvent> { let mut ev; process_events_body!(Some(self), logger, ev, { handler(ev).await }) } @@ -2356,15 +2332,15 @@ impl ChannelMonitor { /// transactions that cannot be confirmed until the funding transaction is visible. /// /// [`Event::BumpTransaction`]: crate::events::Event::BumpTransaction - pub fn broadcast_latest_holder_commitment_txn( + pub fn broadcast_latest_holder_commitment_txn< + B: BroadcasterInterface, + F: FeeEstimator, + L: Logger, + >( &self, broadcaster: &B, fee_estimator: &F, logger: &L, - ) where - B::Target: BroadcasterInterface, - F::Target: FeeEstimator, - L::Target: Logger, - { + ) { let mut inner = self.inner.lock().unwrap(); - let fee_estimator = LowerBoundedFeeEstimator::new(&**fee_estimator); + let fee_estimator = LowerBoundedFeeEstimator::new(fee_estimator); let logger = WithChannelMonitor::from_impl(logger, &*inner, None); inner.queue_latest_holder_commitment_txn_for_broadcast( @@ -2379,10 +2355,9 @@ impl ChannelMonitor { /// to bypass HolderCommitmentTransaction state update lockdown after signature and generate /// 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, - { + pub fn unsafe_get_latest_holder_commitment_txn( + &self, logger: &L, + ) -> Vec { let mut inner = self.inner.lock().unwrap(); let logger = WithChannelMonitor::from_impl(logger, &*inner, None); inner.unsafe_get_latest_holder_commitment_txn(&logger) @@ -2400,7 +2375,7 @@ impl ChannelMonitor { /// /// [`get_outputs_to_watch`]: #method.get_outputs_to_watch #[rustfmt::skip] - pub fn block_connected( + pub fn block_connected( &self, header: &Header, txdata: &TransactionData, @@ -2408,12 +2383,7 @@ impl ChannelMonitor { broadcaster: B, fee_estimator: F, logger: &L, - ) -> Vec - where - B::Target: BroadcasterInterface, - F::Target: FeeEstimator, - L::Target: Logger, - { + ) -> Vec { let mut inner = self.inner.lock().unwrap(); let logger = WithChannelMonitor::from_impl(logger, &*inner, None); inner.block_connected( @@ -2422,13 +2392,9 @@ impl ChannelMonitor { /// Determines if the disconnected block contained any transactions of interest and updates /// appropriately. - pub fn blocks_disconnected( + pub fn blocks_disconnected( &self, fork_point: BestBlock, broadcaster: B, fee_estimator: F, logger: &L, - ) where - B::Target: BroadcasterInterface, - F::Target: FeeEstimator, - L::Target: Logger, - { + ) { let mut inner = self.inner.lock().unwrap(); let logger = WithChannelMonitor::from_impl(logger, &*inner, None); inner.blocks_disconnected(fork_point, broadcaster, fee_estimator, &logger) @@ -2442,7 +2408,7 @@ impl ChannelMonitor { /// /// [`block_connected`]: Self::block_connected #[rustfmt::skip] - pub fn transactions_confirmed( + pub fn transactions_confirmed( &self, header: &Header, txdata: &TransactionData, @@ -2450,12 +2416,7 @@ impl ChannelMonitor { broadcaster: B, fee_estimator: F, logger: &L, - ) -> Vec - where - B::Target: BroadcasterInterface, - F::Target: FeeEstimator, - L::Target: Logger, - { + ) -> Vec { let bounded_fee_estimator = LowerBoundedFeeEstimator::new(fee_estimator); let mut inner = self.inner.lock().unwrap(); let logger = WithChannelMonitor::from_impl(logger, &*inner, None); @@ -2470,17 +2431,13 @@ impl ChannelMonitor { /// /// [`blocks_disconnected`]: Self::blocks_disconnected #[rustfmt::skip] - pub fn transaction_unconfirmed( + pub fn transaction_unconfirmed( &self, txid: &Txid, broadcaster: B, fee_estimator: F, logger: &L, - ) where - B::Target: BroadcasterInterface, - F::Target: FeeEstimator, - L::Target: Logger, - { + ) { let bounded_fee_estimator = LowerBoundedFeeEstimator::new(fee_estimator); let mut inner = self.inner.lock().unwrap(); let logger = WithChannelMonitor::from_impl(logger, &*inner, None); @@ -2497,19 +2454,14 @@ impl ChannelMonitor { /// /// [`block_connected`]: Self::block_connected #[rustfmt::skip] - pub fn best_block_updated( + pub fn best_block_updated( &self, header: &Header, height: u32, broadcaster: B, fee_estimator: F, logger: &L, - ) -> Vec - where - B::Target: BroadcasterInterface, - F::Target: FeeEstimator, - L::Target: Logger, - { + ) -> Vec { let bounded_fee_estimator = LowerBoundedFeeEstimator::new(fee_estimator); let mut inner = self.inner.lock().unwrap(); let logger = WithChannelMonitor::from_impl(logger, &*inner, None); @@ -2544,14 +2496,9 @@ impl ChannelMonitor { /// 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( + pub fn rebroadcast_pending_claims( &self, broadcaster: B, fee_estimator: F, logger: &L, - ) - where - B::Target: BroadcasterInterface, - F::Target: FeeEstimator, - L::Target: Logger, - { + ) { let fee_estimator = LowerBoundedFeeEstimator::new(fee_estimator); let mut lock = self.inner.lock().unwrap(); let inner = &mut *lock; @@ -2572,14 +2519,9 @@ impl ChannelMonitor { /// Triggers rebroadcasts of pending claims from a force-closed channel after a transaction /// signature generation failure. #[rustfmt::skip] - pub fn signer_unblocked( + pub fn signer_unblocked( &self, broadcaster: B, fee_estimator: F, logger: &L, - ) - where - B::Target: BroadcasterInterface, - F::Target: FeeEstimator, - L::Target: Logger, - { + ) { let fee_estimator = LowerBoundedFeeEstimator::new(fee_estimator); let mut lock = self.inner.lock().unwrap(); let inner = &mut *lock; @@ -3826,14 +3768,11 @@ impl ChannelMonitorImpl { /// /// Note that this is often called multiple times for the same payment and must be idempotent. #[rustfmt::skip] - fn provide_payment_preimage( + fn provide_payment_preimage( &mut self, payment_hash: &PaymentHash, payment_preimage: &PaymentPreimage, payment_info: &Option, broadcaster: &B, - fee_estimator: &LowerBoundedFeeEstimator, logger: &WithChannelMonitor) - where B::Target: BroadcasterInterface, - F::Target: FeeEstimator, - L::Target: Logger, - { + fee_estimator: &LowerBoundedFeeEstimator, logger: &WithChannelMonitor + ) { self.payment_preimages.entry(payment_hash.clone()) .and_modify(|(_, payment_infos)| { if let Some(payment_info) = payment_info { @@ -4005,15 +3944,10 @@ impl ChannelMonitorImpl { /// See also [`ChannelMonitor::broadcast_latest_holder_commitment_txn`]. /// /// [`ChannelMonitor::broadcast_latest_holder_commitment_txn`]: crate::chain::channelmonitor::ChannelMonitor::broadcast_latest_holder_commitment_txn - pub(crate) fn queue_latest_holder_commitment_txn_for_broadcast( + pub(crate) fn queue_latest_holder_commitment_txn_for_broadcast( &mut self, broadcaster: &B, fee_estimator: &LowerBoundedFeeEstimator, logger: &WithChannelMonitor, require_funding_seen: bool, - ) - where - B::Target: BroadcasterInterface, - F::Target: FeeEstimator, - L::Target: Logger, - { + ) { let reason = ClosureReason::HolderForceClosed { broadcasted_latest_txn: Some(true), message: "ChannelMonitor-initiated commitment transaction broadcast".to_owned(), @@ -4033,15 +3967,12 @@ impl ChannelMonitorImpl { ); } - fn renegotiated_funding( + fn renegotiated_funding( &mut self, logger: &WithChannelMonitor, channel_parameters: &ChannelTransactionParameters, alternative_holder_commitment_tx: &HolderCommitmentTransaction, alternative_counterparty_commitment_tx: &CommitmentTransaction, - ) -> Result<(), ()> - where - L::Target: Logger, - { + ) -> Result<(), ()> { let alternative_counterparty_commitment_txid = alternative_counterparty_commitment_tx.trust().txid(); @@ -4209,13 +4140,9 @@ impl ChannelMonitorImpl { } #[rustfmt::skip] - fn update_monitor( + fn update_monitor( &mut self, updates: &ChannelMonitorUpdate, broadcaster: &B, fee_estimator: &F, logger: &WithChannelMonitor - ) -> Result<(), ()> - where B::Target: BroadcasterInterface, - F::Target: FeeEstimator, - L::Target: Logger, - { + ) -> Result<(), ()> { if self.latest_update_id == LEGACY_CLOSED_CHANNEL_UPDATE_ID && updates.update_id == LEGACY_CLOSED_CHANNEL_UPDATE_ID { log_info!(logger, "Applying pre-0.1 post-force-closed update to monitor {} with {} change(s).", log_funding_info!(self), updates.updates.len()); @@ -4256,7 +4183,7 @@ impl ChannelMonitorImpl { } } let mut ret = Ok(()); - let bounded_fee_estimator = LowerBoundedFeeEstimator::new(&**fee_estimator); + let bounded_fee_estimator = LowerBoundedFeeEstimator::new(fee_estimator); for update in updates.updates.iter() { match update { ChannelMonitorUpdateStep::LatestHolderCommitmentTXInfo { commitment_tx, htlc_outputs, claimed_htlcs, nondust_htlc_sources } => { @@ -4677,9 +4604,9 @@ 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, commitment_txid: Txid, commitment_tx: &Transaction, height: u32, block_hash: &BlockHash, logger: &L) + fn check_spend_counterparty_transaction(&mut self, commitment_txid: Txid, commitment_tx: &Transaction, height: u32, block_hash: &BlockHash, logger: &L) -> (Vec, CommitmentTxCounterpartyOutputInfo) - where L::Target: Logger { + { // Most secp and related errors trying to create keys means we have no hope of constructing // a spend transaction...so we return no transactions to broadcast let mut claimable_outpoints = Vec::new(); @@ -4967,9 +4894,9 @@ impl ChannelMonitorImpl { /// Attempts to claim a counterparty HTLC-Success/HTLC-Timeout's outputs using the revocation key #[rustfmt::skip] - fn check_spend_counterparty_htlc( + 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 { + ) -> (Vec, Option) { let secret = if let Some(secret) = self.get_secret(commitment_number) { secret } else { return (Vec::new(), None); }; let per_commitment_key = match SecretKey::from_slice(&secret) { Ok(key) => key, @@ -5110,13 +5037,10 @@ 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( + fn check_spend_holder_transaction( &mut self, commitment_txid: Txid, commitment_tx: &Transaction, height: u32, block_hash: &BlockHash, logger: &L, - ) -> Option<(Vec, TransactionOutputs)> - where - L::Target: Logger, - { + ) -> Option<(Vec, TransactionOutputs)> { let funding_spent = get_confirmed_funding_scope!(self); // HTLCs set may differ between last and previous holder commitment txn, in case of one them hitting chain, ensure we cancel all HTLCs backward @@ -5179,9 +5103,9 @@ 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( + pub fn cancel_prev_commitment_claims( &mut self, logger: &L, confirmed_commitment_txid: &Txid - ) where L::Target: Logger { + ) { for (counterparty_commitment_txid, _) in &self.counterparty_commitment_txn_on_chain { // Cancel any pending claims for counterparty commitments we've seen confirm. if counterparty_commitment_txid == confirmed_commitment_txid { @@ -5253,9 +5177,9 @@ 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( + fn unsafe_get_latest_holder_commitment_txn( &mut self, logger: &WithChannelMonitor - ) -> Vec where L::Target: Logger { + ) -> Vec { log_debug!(logger, "Getting signed copy of latest holder commitment transaction!"); let commitment_tx = { let sig = self.onchain_tx_handler.signer.unsafe_sign_holder_commitment( @@ -5305,14 +5229,10 @@ impl ChannelMonitorImpl { } #[rustfmt::skip] - fn block_connected( + fn block_connected( &mut self, header: &Header, txdata: &TransactionData, height: u32, broadcaster: B, fee_estimator: F, logger: &WithChannelMonitor, - ) -> Vec - where B::Target: BroadcasterInterface, - F::Target: FeeEstimator, - L::Target: Logger, - { + ) -> Vec { let block_hash = header.block_hash(); self.best_block = BestBlock::new(block_hash, height); @@ -5321,19 +5241,14 @@ impl ChannelMonitorImpl { } #[rustfmt::skip] - fn best_block_updated( + fn best_block_updated( &mut self, header: &Header, height: u32, broadcaster: B, fee_estimator: &LowerBoundedFeeEstimator, logger: &WithChannelMonitor, - ) -> Vec - where - B::Target: BroadcasterInterface, - F::Target: FeeEstimator, - L::Target: Logger, - { + ) -> Vec { let block_hash = header.block_hash(); if height > self.best_block.height { @@ -5353,7 +5268,7 @@ impl ChannelMonitorImpl { } #[rustfmt::skip] - fn transactions_confirmed( + fn transactions_confirmed( &mut self, header: &Header, txdata: &TransactionData, @@ -5361,12 +5276,7 @@ impl ChannelMonitorImpl { broadcaster: B, fee_estimator: &LowerBoundedFeeEstimator, logger: &WithChannelMonitor, - ) -> Vec - where - B::Target: BroadcasterInterface, - F::Target: FeeEstimator, - L::Target: Logger, - { + ) -> Vec { let funding_seen_before = self.funding_seen_onchain; let txn_matched = self.filter_block(txdata); @@ -5638,7 +5548,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( + fn block_confirmed( &mut self, conf_height: u32, conf_hash: BlockHash, @@ -5648,12 +5558,7 @@ impl ChannelMonitorImpl { broadcaster: &B, fee_estimator: &LowerBoundedFeeEstimator, logger: &WithChannelMonitor, - ) -> Vec - where - B::Target: BroadcasterInterface, - F::Target: FeeEstimator, - L::Target: Logger, - { + ) -> Vec { log_trace!(logger, "Processing {} matched transactions for block at height {}.", txn_matched.len(), conf_height); debug_assert!(self.best_block.height >= conf_height); @@ -5866,12 +5771,9 @@ impl ChannelMonitorImpl { } #[rustfmt::skip] - fn blocks_disconnected( + fn blocks_disconnected( &mut self, fork_point: BestBlock, broadcaster: B, fee_estimator: F, logger: &WithChannelMonitor - ) where B::Target: BroadcasterInterface, - F::Target: FeeEstimator, - L::Target: Logger, - { + ) { let new_height = fork_point.height; log_trace!(logger, "Block(s) disconnected to height {}", new_height); assert!(self.best_block.height > fork_point.height, @@ -5915,17 +5817,13 @@ impl ChannelMonitorImpl { } #[rustfmt::skip] - fn transaction_unconfirmed( + fn transaction_unconfirmed( &mut self, txid: &Txid, broadcaster: B, fee_estimator: &LowerBoundedFeeEstimator, logger: &WithChannelMonitor, - ) where - B::Target: BroadcasterInterface, - F::Target: FeeEstimator, - L::Target: Logger, - { + ) { let mut removed_height = None; for entry in self.onchain_events_awaiting_threshold_conf.iter() { if entry.txid == *txid { @@ -6030,9 +5928,9 @@ impl ChannelMonitorImpl { } #[rustfmt::skip] - fn should_broadcast_holder_commitment_txn( + fn should_broadcast_holder_commitment_txn( &self, logger: &WithChannelMonitor - ) -> Option where L::Target: Logger { + ) -> Option { // There's no need to broadcast our commitment transaction if we've seen one confirmed (even // with 1 confirmation) as it'll be rejected as duplicate/conflicting. if self.funding_spend_confirmed.is_some() || @@ -6097,9 +5995,9 @@ 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( + fn is_resolving_htlc_output( &mut self, tx: &Transaction, height: u32, block_hash: &BlockHash, logger: &WithChannelMonitor, - ) where L::Target: Logger { + ) { let funding_spent = get_confirmed_funding_scope!(self); 'outer_loop: for input in &tx.input { @@ -6354,9 +6252,9 @@ 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( + fn check_tx_and_push_spendable_outputs( &mut self, tx: &Transaction, height: u32, block_hash: &BlockHash, logger: &WithChannelMonitor, - ) where L::Target: Logger { + ) { let funding_spent = get_confirmed_funding_scope!(self); for spendable_output in self.get_spendable_outputs(funding_spent, tx) { let entry = OnchainEventEntry { @@ -6376,39 +6274,33 @@ impl ChannelMonitorImpl { } } -impl chain::Listen +impl chain::Listen for (ChannelMonitor, T, F, L) -where - T::Target: BroadcasterInterface, - F::Target: FeeEstimator, - L::Target: Logger, { fn filtered_block_connected(&self, header: &Header, txdata: &TransactionData, height: u32) { - self.0.block_connected(header, txdata, height, &*self.1, &*self.2, &self.3); + self.0.block_connected(header, txdata, height, &self.1, &self.2, &self.3); } fn blocks_disconnected(&self, fork_point: BestBlock) { - self.0.blocks_disconnected(fork_point, &*self.1, &*self.2, &self.3); + self.0.blocks_disconnected(fork_point, &self.1, &self.2, &self.3); } } -impl chain::Confirm for (M, T, F, L) +impl + chain::Confirm for (M, T, F, L) where M: Deref>, - T::Target: BroadcasterInterface, - F::Target: FeeEstimator, - L::Target: Logger, { fn transactions_confirmed(&self, header: &Header, txdata: &TransactionData, height: u32) { - self.0.transactions_confirmed(header, txdata, height, &*self.1, &*self.2, &self.3); + self.0.transactions_confirmed(header, txdata, height, &self.1, &self.2, &self.3); } fn transaction_unconfirmed(&self, txid: &Txid) { - self.0.transaction_unconfirmed(txid, &*self.1, &*self.2, &self.3); + self.0.transaction_unconfirmed(txid, &self.1, &self.2, &self.3); } fn best_block_updated(&self, header: &Header, height: u32) { - self.0.best_block_updated(header, height, &*self.1, &*self.2, &self.3); + self.0.best_block_updated(header, height, &self.1, &self.2, &self.3); } fn get_relevant_txids(&self) -> Vec<(Txid, u32, Option)> { diff --git a/lightning/src/chain/mod.rs b/lightning/src/chain/mod.rs index b4cc6a302ae..9f5c9653f65 100644 --- a/lightning/src/chain/mod.rs +++ b/lightning/src/chain/mod.rs @@ -25,6 +25,8 @@ use crate::ln::types::ChannelId; use crate::sign::ecdsa::EcdsaChannelSigner; use crate::sign::HTLCDescriptor; +use core::ops::Deref; + #[allow(unused_imports)] use crate::prelude::*; @@ -346,6 +348,28 @@ pub trait Watch { ) -> Vec<(OutPoint, ChannelId, Vec, PublicKey)>; } +impl + ?Sized, W: Deref> + Watch for W +{ + fn watch_channel( + &self, channel_id: ChannelId, monitor: ChannelMonitor, + ) -> Result { + self.deref().watch_channel(channel_id, monitor) + } + + fn update_channel( + &self, channel_id: ChannelId, update: &ChannelMonitorUpdate, + ) -> ChannelMonitorUpdateStatus { + self.deref().update_channel(channel_id, update) + } + + fn release_pending_monitor_events( + &self, + ) -> Vec<(OutPoint, ChannelId, Vec, PublicKey)> { + self.deref().release_pending_monitor_events() + } +} + /// The `Filter` trait defines behavior for indicating chain activity of interest pertaining to /// channels. /// diff --git a/lightning/src/chain/onchaintx.rs b/lightning/src/chain/onchaintx.rs index fb65aa0f157..cfee63beefd 100644 --- a/lightning/src/chain/onchaintx.rs +++ b/lightning/src/chain/onchaintx.rs @@ -45,7 +45,6 @@ use alloc::collections::BTreeMap; use core::cmp; use core::mem::replace; use core::mem::swap; -use core::ops::Deref; const MAX_ALLOC_SIZE: usize = 64 * 1024; @@ -485,15 +484,11 @@ impl OnchainTxHandler { /// 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( + pub(super) fn rebroadcast_pending_claims( &mut self, current_height: u32, feerate_strategy: FeerateStrategy, broadcaster: &B, conf_target: ConfirmationTarget, destination_script: &Script, fee_estimator: &LowerBoundedFeeEstimator, logger: &L, - ) - where - B::Target: BroadcasterInterface, - F::Target: FeeEstimator, - { + ) { let mut bump_requests = Vec::with_capacity(self.pending_claim_requests.len()); for (claim_id, request) in self.pending_claim_requests.iter() { let inputs = request.outpoints(); @@ -554,13 +549,11 @@ 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( + fn generate_claim( &mut self, cur_height: u32, cached_request: &PackageTemplate, feerate_strategy: &FeerateStrategy, conf_target: ConfirmationTarget, destination_script: &Script, fee_estimator: &LowerBoundedFeeEstimator, logger: &L, - ) -> Option<(u32, u64, OnchainClaim)> - where F::Target: FeeEstimator, - { + ) -> Option<(u32, u64, OnchainClaim)> { let request_outpoints = cached_request.outpoints(); if request_outpoints.is_empty() { // Don't prune pending claiming request yet, we may have to resurrect HTLCs. Untractable @@ -761,14 +754,11 @@ impl OnchainTxHandler { /// 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( + 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, - fee_estimator: &LowerBoundedFeeEstimator, logger: &L - ) where - B::Target: BroadcasterInterface, - F::Target: FeeEstimator, - { + fee_estimator: &LowerBoundedFeeEstimator, logger: &L, + ) { if !requests.is_empty() { log_debug!(logger, "Updating claims view at height {} with {} claim requests", cur_height, requests.len()); } @@ -912,14 +902,11 @@ impl OnchainTxHandler { /// 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( + 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, - destination_script: &Script, fee_estimator: &LowerBoundedFeeEstimator, logger: &L - ) where - B::Target: BroadcasterInterface, - F::Target: FeeEstimator, - { + destination_script: &Script, fee_estimator: &LowerBoundedFeeEstimator, logger: &L, + ) { let mut have_logged_intro = false; let mut maybe_log_intro = || { if !have_logged_intro { @@ -1110,7 +1097,7 @@ impl OnchainTxHandler { } #[rustfmt::skip] - pub(super) fn transaction_unconfirmed( + pub(super) fn transaction_unconfirmed( &mut self, txid: &Txid, broadcaster: &B, @@ -1118,10 +1105,7 @@ impl OnchainTxHandler { destination_script: &Script, fee_estimator: &LowerBoundedFeeEstimator, logger: &L, - ) where - B::Target: BroadcasterInterface, - F::Target: FeeEstimator, - { + ) { let mut height = None; for entry in self.onchain_events_awaiting_threshold_conf.iter() { if entry.txid == *txid { @@ -1138,13 +1122,10 @@ impl OnchainTxHandler { } #[rustfmt::skip] - pub(super) fn blocks_disconnected( + pub(super) fn blocks_disconnected( &mut self, new_best_height: u32, broadcaster: &B, conf_target: ConfirmationTarget, destination_script: &Script, fee_estimator: &LowerBoundedFeeEstimator, logger: &L, - ) - where B::Target: BroadcasterInterface, - F::Target: FeeEstimator, - { + ) { let mut bump_candidates = new_hash_map(); let onchain_events_awaiting_threshold_conf = self.onchain_events_awaiting_threshold_conf.drain(..).collect::>(); diff --git a/lightning/src/chain/package.rs b/lightning/src/chain/package.rs index db46f3be60d..0abe3534341 100644 --- a/lightning/src/chain/package.rs +++ b/lightning/src/chain/package.rs @@ -46,7 +46,6 @@ use crate::util::ser::{Readable, ReadableArgs, RequiredWrapper, Writeable, Write use crate::io; use core::cmp; -use core::ops::Deref; #[allow(unused_imports)] use crate::prelude::*; @@ -1512,12 +1511,10 @@ impl PackageTemplate { /// 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( + 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, - ) -> Option<(u64, u64)> - where F::Target: FeeEstimator, - { + ) -> Option<(u64, u64)> { debug_assert!(matches!(self.malleability, PackageMalleability::Malleable(..)), "The package output is fixed for non-malleable packages"); let input_amounts = self.package_amount(); @@ -1540,10 +1537,10 @@ impl PackageTemplate { /// Computes a feerate based on the given confirmation target and feerate strategy. #[rustfmt::skip] - pub(crate) fn compute_package_feerate( + pub(crate) fn compute_package_feerate( &self, fee_estimator: &LowerBoundedFeeEstimator, conf_target: ConfirmationTarget, feerate_strategy: &FeerateStrategy, - ) -> u32 where F::Target: FeeEstimator { + ) -> u32 { let feerate_estimate = fee_estimator.bounded_sat_per_1000_weight(conf_target); if self.feerate_previous != 0 { let previous_feerate = self.feerate_previous.try_into().unwrap_or(u32::max_value()); @@ -1675,11 +1672,9 @@ impl Readable for PackageTemplate { /// 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( +fn compute_fee_from_spent_amounts( input_amounts: u64, predicted_weight: u64, conf_target: ConfirmationTarget, fee_estimator: &LowerBoundedFeeEstimator, logger: &L -) -> Option<(u64, u64)> - where F::Target: FeeEstimator, -{ +) -> Option<(u64, u64)> { let sweep_feerate = fee_estimator.bounded_sat_per_1000_weight(conf_target); let fee_rate = cmp::min(sweep_feerate, compute_feerate_sat_per_1000_weight(input_amounts / 2, predicted_weight)); let fee = fee_rate as u64 * (predicted_weight) / 1000; @@ -1701,14 +1696,11 @@ fn compute_fee_from_spent_amounts( /// respect BIP125 rules 3) and 4) and if required adjust the new fee to meet the RBF policy /// requirement. #[rustfmt::skip] -fn feerate_bump( +fn feerate_bump( predicted_weight: u64, input_amounts: u64, dust_limit_sats: u64, previous_feerate: u64, feerate_strategy: &FeerateStrategy, conf_target: ConfirmationTarget, fee_estimator: &LowerBoundedFeeEstimator, logger: &L, -) -> Option<(u64, u64)> -where - F::Target: FeeEstimator, -{ +) -> Option<(u64, u64)> { let previous_fee = previous_feerate * predicted_weight / 1000; // If old feerate inferior to actual one given back by Fee Estimator, use it to compute new fee... diff --git a/lightning/src/crypto/utils.rs b/lightning/src/crypto/utils.rs index b59cc6002d9..1570b3a0b2f 100644 --- a/lightning/src/crypto/utils.rs +++ b/lightning/src/crypto/utils.rs @@ -5,8 +5,6 @@ use bitcoin::secp256k1::{ecdsa::Signature, Message, Secp256k1, SecretKey, Signin use crate::sign::EntropySource; -use core::ops::Deref; - macro_rules! hkdf_extract_expand { ($salt: expr, $ikm: expr) => {{ let mut hmac = HmacEngine::::new($salt); @@ -72,12 +70,9 @@ pub fn sign(ctx: &Secp256k1, msg: &Message, sk: &SecretKey) -> Si #[inline] #[allow(unused_variables)] -pub fn sign_with_aux_rand( +pub fn sign_with_aux_rand( ctx: &Secp256k1, msg: &Message, sk: &SecretKey, entropy_source: &ES, -) -> Signature -where - ES::Target: EntropySource, -{ +) -> Signature { #[cfg(feature = "grind_signatures")] let sig = loop { let sig = ctx.sign_ecdsa_with_noncedata(msg, sk, &entropy_source.get_secure_random_bytes()); diff --git a/lightning/src/events/bump_transaction/mod.rs b/lightning/src/events/bump_transaction/mod.rs index e141d9b8abc..1b3496c5eab 100644 --- a/lightning/src/events/bump_transaction/mod.rs +++ b/lightning/src/events/bump_transaction/mod.rs @@ -442,10 +442,9 @@ pub trait WalletSource { /// /// This is not exported to bindings users as async is only supported in Rust. // Note that updates to documentation on this struct should be copied to the synchronous version. -pub struct Wallet +pub struct Wallet where W::Target: WalletSource + MaybeSend, - L::Target: Logger + MaybeSend, { source: W, logger: L, @@ -455,10 +454,9 @@ where locked_utxos: Mutex>, } -impl Wallet +impl Wallet where W::Target: WalletSource + MaybeSend, - L::Target: Logger + MaybeSend, { /// Returns a new instance backed by the given [`WalletSource`] that serves as an implementation /// of [`CoinSelectionSource`]. @@ -617,11 +615,10 @@ where } } -impl CoinSelectionSource +impl CoinSelectionSource for Wallet where W::Target: WalletSource + MaybeSend + MaybeSync, - L::Target: Logger + MaybeSend + MaybeSync, { fn select_confirmed_utxos<'a>( &'a self, claim_id: ClaimId, must_spend: Vec, must_pay_to: &'a [TxOut], @@ -694,12 +691,13 @@ where /// /// [`Event::BumpTransaction`]: crate::events::Event::BumpTransaction // Note that updates to documentation on this struct should be copied to the synchronous version. -pub struct BumpTransactionEventHandler -where - B::Target: BroadcasterInterface, +pub struct BumpTransactionEventHandler< + B: BroadcasterInterface, + C: Deref, + SP: SignerProvider, + L: Logger, +> where C::Target: CoinSelectionSource, - SP::Target: SignerProvider, - L::Target: Logger, { broadcaster: B, utxo_source: C, @@ -708,12 +706,10 @@ where secp: Secp256k1, } -impl BumpTransactionEventHandler +impl + BumpTransactionEventHandler where - B::Target: BroadcasterInterface, C::Target: CoinSelectionSource, - SP::Target: SignerProvider, - L::Target: Logger, { /// Returns a new instance capable of handling [`Event::BumpTransaction`] events. /// diff --git a/lightning/src/events/bump_transaction/sync.rs b/lightning/src/events/bump_transaction/sync.rs index 1328c2c1b3a..5c90b7ed43c 100644 --- a/lightning/src/events/bump_transaction/sync.rs +++ b/lightning/src/events/bump_transaction/sync.rs @@ -100,18 +100,16 @@ where /// /// For an asynchronous version of this wrapper, see [`Wallet`]. // Note that updates to documentation on this struct should be copied to the asynchronous version. -pub struct WalletSync +pub struct WalletSync where W::Target: WalletSourceSync + MaybeSend, - L::Target: Logger + MaybeSend, { wallet: Wallet, L>, } -impl WalletSync +impl WalletSync where W::Target: WalletSourceSync + MaybeSend, - L::Target: Logger + MaybeSend, { /// Constructs a new [`WalletSync`] instance. pub fn new(source: W, logger: L) -> Self { @@ -119,11 +117,10 @@ where } } -impl CoinSelectionSourceSync +impl CoinSelectionSourceSync for WalletSync where W::Target: WalletSourceSync + MaybeSend + MaybeSync, - L::Target: Logger + MaybeSend + MaybeSync, { fn select_confirmed_utxos( &self, claim_id: ClaimId, must_spend: Vec, must_pay_to: &[TxOut], @@ -267,23 +264,19 @@ where /// /// [`Event::BumpTransaction`]: crate::events::Event::BumpTransaction // Note that updates to documentation on this struct should be copied to the synchronous version. -pub struct BumpTransactionEventHandlerSync +pub struct BumpTransactionEventHandlerSync where B::Target: BroadcasterInterface, C::Target: CoinSelectionSourceSync, - SP::Target: SignerProvider, - L::Target: Logger, { bump_transaction_event_handler: BumpTransactionEventHandler, SP, L>, } -impl BumpTransactionEventHandlerSync +impl BumpTransactionEventHandlerSync where B::Target: BroadcasterInterface, C::Target: CoinSelectionSourceSync, - SP::Target: SignerProvider, - L::Target: Logger, { /// Constructs a new instance of [`BumpTransactionEventHandlerSync`]. pub fn new(broadcaster: B, utxo_source: C, signer_provider: SP, logger: L) -> Self { diff --git a/lightning/src/ln/chan_utils.rs b/lightning/src/ln/chan_utils.rs index 431fdd2859c..4bb8ffac9ef 100644 --- a/lightning/src/ln/chan_utils.rs +++ b/lightning/src/ln/chan_utils.rs @@ -320,12 +320,9 @@ pub(crate) fn htlc_tx_fees_sat(feerate_per_kw: u32, num_accepted_htlcs: usize, n /// Returns a fee estimate for the commitment transaction that we would ideally like to set, /// depending on channel type. -pub(super) fn selected_commitment_sat_per_1000_weight( +pub(super) fn selected_commitment_sat_per_1000_weight( fee_estimator: &LowerBoundedFeeEstimator, channel_type: &ChannelTypeFeatures, -) -> u32 -where - F::Target: FeeEstimator, -{ +) -> u32 { if channel_type.supports_anchor_zero_fee_commitments() { 0 } else if channel_type.supports_anchors_zero_fee_htlc_tx() { @@ -1452,13 +1449,10 @@ impl BuiltCommitmentTransaction { } /// Signs the holder commitment transaction because we are about to broadcast it. - pub fn sign_holder_commitment( + 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, - { + ) -> Signature { let sighash = self.get_sighash_all(funding_redeemscript, channel_value_satoshis); sign_with_aux_rand(secp_ctx, &sighash, funding_key, entropy_source) } @@ -2139,10 +2133,10 @@ impl<'a> TrustedCommitmentTransaction<'a> { /// /// This function is only valid in the holder commitment context, it always uses EcdsaSighashType::All. #[rustfmt::skip] - pub fn get_htlc_sigs( + pub fn get_htlc_sigs( &self, htlc_base_key: &SecretKey, channel_parameters: &DirectedChannelTransactionParameters, entropy_source: &ES, secp_ctx: &Secp256k1, - ) -> Result, ()> where ES::Target: EntropySource { + ) -> Result, ()> { let inner = self.inner; let keys = &inner.keys; let txid = inner.built.txid; diff --git a/lightning/src/ln/channel.rs b/lightning/src/ln/channel.rs index 659735cc0a2..344847ebd6b 100644 --- a/lightning/src/ln/channel.rs +++ b/lightning/src/ln/channel.rs @@ -93,7 +93,6 @@ use crate::prelude::*; use crate::sign::type_resolver::ChannelSignerType; #[cfg(any(test, fuzzing, debug_assertions))] use crate::sync::Mutex; -use core::ops::Deref; use core::time::Duration; use core::{cmp, fmt, mem}; @@ -985,20 +984,14 @@ impl ChannelError { } } -pub(super) struct WithChannelContext<'a, L: Deref> -where - L::Target: Logger, -{ +pub(super) struct WithChannelContext<'a, L: 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: Logger> Logger for WithChannelContext<'a, L> { fn log(&self, mut record: Record) { record.peer_id = self.peer_id; record.channel_id = self.channel_id; @@ -1007,16 +1000,10 @@ where } } -impl<'a, 'b, L: Deref> WithChannelContext<'a, L> -where - L::Target: Logger, -{ - pub(super) fn from( +impl<'a, 'b, L: Logger> WithChannelContext<'a, L> { + pub(super) fn from( logger: &'a L, context: &'b ChannelContext, payment_hash: Option, - ) -> Self - where - S::Target: SignerProvider, - { + ) -> Self { WithChannelContext { logger, peer_id: Some(context.counterparty_node_id), @@ -1251,9 +1238,7 @@ struct HolderCommitmentPoint { impl HolderCommitmentPoint { #[rustfmt::skip] - pub fn new(signer: &ChannelSignerType, secp_ctx: &Secp256k1) -> Option - where SP::Target: SignerProvider - { + pub fn new(signer: &ChannelSignerType, secp_ctx: &Secp256k1) -> Option { Some(HolderCommitmentPoint { next_transaction_number: INITIAL_COMMITMENT_NUMBER, previous_revoked_point: None, @@ -1294,12 +1279,9 @@ impl HolderCommitmentPoint { /// If we are pending advancing the next commitment point, this method tries asking the signer /// again. - pub fn try_resolve_pending( + pub fn try_resolve_pending( &mut self, signer: &ChannelSignerType, secp_ctx: &Secp256k1, logger: &L, - ) where - SP::Target: SignerProvider, - L::Target: Logger, - { + ) { if !self.can_advance() { let pending_next_point = signer .as_ref() @@ -1331,13 +1313,9 @@ impl HolderCommitmentPoint { /// /// If our signer is ready to provide the next commitment point, the next call to `advance` will /// succeed. - pub fn advance( + pub fn advance( &mut self, signer: &ChannelSignerType, secp_ctx: &Secp256k1, logger: &L, - ) -> Result<(), ()> - where - SP::Target: SignerProvider, - L::Target: Logger, - { + ) -> Result<(), ()> { if let Some(next_point) = self.pending_next_point { *self = Self { next_transaction_number: self.next_transaction_number - 1, @@ -1453,19 +1431,13 @@ 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 { 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 { Undefined, UnfundedOutboundV1(OutboundV1Channel), UnfundedInboundV1(InboundV1Channel), @@ -1473,10 +1445,9 @@ where Funded(FundedChannel), } -impl Channel +impl Channel where - SP::Target: SignerProvider, - ::EcdsaSigner: ChannelSigner, + ::EcdsaSigner: ChannelSigner, { pub fn context(&self) -> &ChannelContext { match &self.phase { @@ -1619,9 +1590,9 @@ where } #[rustfmt::skip] - pub fn signer_maybe_unblocked( + pub fn signer_maybe_unblocked( &mut self, chain_hash: ChainHash, logger: &L, path_for_release_htlc: CBP - ) -> Result, ChannelError> where L::Target: Logger, CBP: Fn(u64) -> BlindedMessagePath { + ) -> Result, ChannelError> where CBP: Fn(u64) -> BlindedMessagePath { match &mut self.phase { ChannelPhase::Undefined => unreachable!(), ChannelPhase::Funded(chan) => chan.signer_maybe_unblocked(logger, path_for_release_htlc).map(|r| Some(r)), @@ -1664,10 +1635,7 @@ 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. - pub fn peer_disconnected_is_resumable(&mut self, logger: &L) -> DisconnectResult - where - L::Target: Logger, - { + pub fn peer_disconnected_is_resumable(&mut self, logger: &L) -> DisconnectResult { let is_resumable = match &mut self.phase { ChannelPhase::Undefined => unreachable!(), ChannelPhase::Funded(chan) => { @@ -1721,9 +1689,9 @@ 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( + pub fn peer_connected_get_handshake( &mut self, chain_hash: ChainHash, logger: &L, - ) -> ReconnectionMsg where L::Target: Logger { + ) -> ReconnectionMsg { match &mut self.phase { ChannelPhase::Undefined => unreachable!(), ChannelPhase::Funded(chan) => @@ -1757,14 +1725,10 @@ where } #[rustfmt::skip] - pub fn maybe_handle_error_without_close( + pub fn maybe_handle_error_without_close( &mut self, chain_hash: ChainHash, fee_estimator: &LowerBoundedFeeEstimator, logger: &L, user_config: &UserConfig, their_features: &InitFeatures, - ) -> Result, ()> - where - F::Target: FeeEstimator, - L::Target: Logger, - { + ) -> Result, ()> { match &mut self.phase { ChannelPhase::Undefined => unreachable!(), ChannelPhase::Funded(_) => Ok(None), @@ -1797,12 +1761,9 @@ where } } - fn fail_interactive_tx_negotiation( + fn fail_interactive_tx_negotiation( &mut self, reason: AbortReason, logger: &L, - ) -> (ChannelError, Option) - where - L::Target: Logger, - { + ) -> (ChannelError, Option) { let logger = WithChannelContext::from(logger, &self.context(), None); log_info!(logger, "Failed interactive transaction negotiation: {reason}"); @@ -1826,12 +1787,9 @@ where (ChannelError::Abort(reason), splice_funding_failed) } - pub fn tx_add_input( + pub fn tx_add_input( &mut self, msg: &msgs::TxAddInput, logger: &L, - ) -> Result)> - where - L::Target: Logger, - { + ) -> Result)> { match self.interactive_tx_constructor_mut() { Some(interactive_tx_constructor) => interactive_tx_constructor .handle_tx_add_input(msg) @@ -1845,12 +1803,9 @@ where } } - pub fn tx_add_output( + pub fn tx_add_output( &mut self, msg: &msgs::TxAddOutput, logger: &L, - ) -> Result)> - where - L::Target: Logger, - { + ) -> Result)> { match self.interactive_tx_constructor_mut() { Some(interactive_tx_constructor) => interactive_tx_constructor .handle_tx_add_output(msg) @@ -1864,12 +1819,9 @@ where } } - pub fn tx_remove_input( + pub fn tx_remove_input( &mut self, msg: &msgs::TxRemoveInput, logger: &L, - ) -> Result)> - where - L::Target: Logger, - { + ) -> Result)> { match self.interactive_tx_constructor_mut() { Some(interactive_tx_constructor) => interactive_tx_constructor .handle_tx_remove_input(msg) @@ -1883,12 +1835,9 @@ where } } - pub fn tx_remove_output( + pub fn tx_remove_output( &mut self, msg: &msgs::TxRemoveOutput, logger: &L, - ) -> Result)> - where - L::Target: Logger, - { + ) -> Result)> { match self.interactive_tx_constructor_mut() { Some(interactive_tx_constructor) => interactive_tx_constructor .handle_tx_remove_output(msg) @@ -1902,15 +1851,12 @@ where } } - pub fn tx_complete( + pub fn tx_complete( &mut self, msg: &msgs::TxComplete, logger: &L, ) -> Result< (Option, Option), (ChannelError, Option), - > - where - L::Target: Logger, - { + > { let tx_complete_action = match self.interactive_tx_constructor_mut() { Some(interactive_tx_constructor) => interactive_tx_constructor .handle_tx_complete(msg) @@ -1943,12 +1889,9 @@ where Ok((interactive_tx_msg_send, Some(commitment_signed))) } - pub fn tx_abort( + pub fn tx_abort( &mut self, msg: &msgs::TxAbort, logger: &L, - ) -> Result<(Option, Option), ChannelError> - where - L::Target: Logger, - { + ) -> Result<(Option, Option), ChannelError> { // If we have not sent a `tx_abort` message for this negotiation previously, we need to echo // back a tx_abort message according to the spec: // https://github.com/lightning/bolts/blob/247e83d/02-peer-protocol.md?plain=1#L560-L561 @@ -2015,12 +1958,9 @@ where } #[rustfmt::skip] - pub fn funding_signed( + pub fn funding_signed( &mut self, msg: &msgs::FundingSigned, best_block: BestBlock, signer_provider: &SP, logger: &L - ) -> Result<(&mut FundedChannel, ChannelMonitor<::EcdsaSigner>), ChannelError> - where - L::Target: Logger - { + ) -> Result<(&mut FundedChannel, ChannelMonitor<::EcdsaSigner>), ChannelError> { let phase = core::mem::replace(&mut self.phase, ChannelPhase::Undefined); let result = if let ChannelPhase::UnfundedOutboundV1(chan) = phase { let channel_state = chan.context.channel_state; @@ -2046,12 +1986,9 @@ where result.map(|monitor| (self.as_funded_mut().expect("Channel should be funded"), monitor)) } - fn funding_tx_constructed( + fn funding_tx_constructed( &mut self, funding_outpoint: OutPoint, logger: &L, - ) -> Result - where - L::Target: Logger, - { + ) -> Result { let logger = WithChannelContext::from(logger, self.context(), None); let (interactive_tx_constructor, commitment_signed) = match &mut self.phase { ChannelPhase::UnfundedV2(chan) => { @@ -2168,13 +2105,9 @@ where } #[rustfmt::skip] - pub fn commitment_signed( + pub fn commitment_signed( &mut self, msg: &msgs::CommitmentSigned, best_block: BestBlock, signer_provider: &SP, fee_estimator: &LowerBoundedFeeEstimator, logger: &L - ) -> Result<(Option::EcdsaSigner>>, Option), ChannelError> - where - F::Target: FeeEstimator, - L::Target: Logger - { + ) -> Result<(Option::EcdsaSigner>>, Option), ChannelError> { let phase = core::mem::replace(&mut self.phase, ChannelPhase::Undefined); match phase { ChannelPhase::UnfundedV2(chan) => { @@ -2246,12 +2179,9 @@ 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. - pub fn get_available_balances( + pub fn get_available_balances( &self, fee_estimator: &LowerBoundedFeeEstimator, - ) -> AvailableBalances - where - F::Target: FeeEstimator, - { + ) -> AvailableBalances { match &self.phase { ChannelPhase::Undefined => unreachable!(), ChannelPhase::Funded(chan) => chan.get_available_balances(fee_estimator), @@ -2272,40 +2202,36 @@ where } } -impl From> for Channel +impl From> for Channel where - SP::Target: SignerProvider, - ::EcdsaSigner: ChannelSigner, + ::EcdsaSigner: ChannelSigner, { fn from(channel: OutboundV1Channel) -> Self { Channel { phase: ChannelPhase::UnfundedOutboundV1(channel) } } } -impl From> for Channel +impl From> for Channel where - SP::Target: SignerProvider, - ::EcdsaSigner: ChannelSigner, + ::EcdsaSigner: ChannelSigner, { fn from(channel: InboundV1Channel) -> Self { Channel { phase: ChannelPhase::UnfundedInboundV1(channel) } } } -impl From> for Channel +impl From> for Channel where - SP::Target: SignerProvider, - ::EcdsaSigner: ChannelSigner, + ::EcdsaSigner: ChannelSigner, { fn from(channel: PendingV2Channel) -> Self { Channel { phase: ChannelPhase::UnfundedV2(channel) } } } -impl From> for Channel +impl From> for Channel where - SP::Target: SignerProvider, - ::EcdsaSigner: ChannelSigner, + ::EcdsaSigner: ChannelSigner, { fn from(channel: FundedChannel) -> Self { Channel { phase: ChannelPhase::Funded(channel) } @@ -2557,14 +2483,11 @@ impl FundingScope { } /// Constructs a `FundingScope` for splicing a channel. - fn for_splice( + fn for_splice( prev_funding: &Self, context: &ChannelContext, our_funding_contribution: SignedAmount, their_funding_contribution: SignedAmount, counterparty_funding_pubkey: PublicKey, our_new_holder_keys: ChannelPublicKeys, - ) -> Self - where - SP::Target: SignerProvider, - { + ) -> Self { debug_assert!(our_funding_contribution.abs() <= SignedAmount::MAX_MONEY); debug_assert!(their_funding_contribution.abs() <= SignedAmount::MAX_MONEY); @@ -2741,12 +2664,9 @@ impl FundingNegotiation { } impl PendingFunding { - fn check_get_splice_locked( + fn check_get_splice_locked( &mut self, context: &ChannelContext, confirmed_funding_index: usize, height: u32, - ) -> Option - where - SP::Target: SignerProvider, - { + ) -> Option { debug_assert!(confirmed_funding_index < self.negotiated_candidates.len()); let funding = &self.negotiated_candidates[confirmed_funding_index]; @@ -2852,10 +2772,7 @@ impl<'a> From<&'a Transaction> for ConfirmedTransaction<'a> { /// Contains everything about the channel including state, and various flags. #[cfg_attr(test, derive(Debug))] -pub(super) struct ChannelContext -where - SP::Target: SignerProvider, -{ +pub(super) struct ChannelContext { config: LegacyChannelConfig, // Track the previous `ChannelConfig` so that we can continue forwarding HTLCs that were @@ -3143,10 +3060,7 @@ where /// A channel struct implementing this trait can receive an initial counterparty commitment /// transaction signature. -trait InitialRemoteCommitmentReceiver -where - SP::Target: SignerProvider, -{ +trait InitialRemoteCommitmentReceiver { fn context(&self) -> &ChannelContext; fn context_mut(&mut self) -> &mut ChannelContext; @@ -3158,9 +3072,9 @@ where fn received_msg(&self) -> &'static str; #[rustfmt::skip] - fn check_counterparty_commitment_signature( + fn check_counterparty_commitment_signature( &self, sig: &Signature, holder_commitment_point: &HolderCommitmentPoint, logger: &L - ) -> Result where L::Target: Logger { + ) -> Result { let funding_script = self.funding().get_funding_redeemscript(); let commitment_data = self.context().build_commitment_transaction(self.funding(), @@ -3181,13 +3095,10 @@ where } #[rustfmt::skip] - fn initial_commitment_signed( + 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, - ) -> Result<(ChannelMonitor<::EcdsaSigner>, CommitmentTransaction), ChannelError> - where - L::Target: Logger - { + ) -> Result<(ChannelMonitor<::EcdsaSigner>, CommitmentTransaction), ChannelError> { let initial_commitment_tx = match self.check_counterparty_commitment_signature(&counterparty_signature, holder_commitment_point, logger) { Ok(res) => res, Err(ChannelError::Close(e)) => { @@ -3275,10 +3186,7 @@ where fn is_v2_established(&self) -> bool; } -impl InitialRemoteCommitmentReceiver for OutboundV1Channel -where - SP::Target: SignerProvider, -{ +impl InitialRemoteCommitmentReceiver for OutboundV1Channel { fn context(&self) -> &ChannelContext { &self.context } @@ -3304,10 +3212,7 @@ where } } -impl InitialRemoteCommitmentReceiver for InboundV1Channel -where - SP::Target: SignerProvider, -{ +impl InitialRemoteCommitmentReceiver for InboundV1Channel { fn context(&self) -> &ChannelContext { &self.context } @@ -3333,10 +3238,7 @@ where } } -impl InitialRemoteCommitmentReceiver for FundedChannel -where - SP::Target: SignerProvider, -{ +impl InitialRemoteCommitmentReceiver for FundedChannel { fn context(&self) -> &ChannelContext { &self.context } @@ -3371,12 +3273,9 @@ where } } -impl ChannelContext -where - SP::Target: SignerProvider, -{ +impl ChannelContext { #[rustfmt::skip] - fn new_for_inbound_channel<'a, ES: Deref, F: Deref, L: Deref>( + fn new_for_inbound_channel<'a, ES: EntropySource, F: FeeEstimator, L: Logger>( fee_estimator: &'a LowerBoundedFeeEstimator, entropy_source: &'a ES, signer_provider: &'a SP, @@ -3394,13 +3293,7 @@ where msg_channel_reserve_satoshis: u64, msg_push_msat: u64, open_channel_fields: msgs::CommonOpenChannelFields, - ) -> Result<(FundingScope, ChannelContext), ChannelError> - where - ES::Target: EntropySource, - F::Target: FeeEstimator, - L::Target: Logger, - SP::Target: SignerProvider, - { + ) -> Result<(FundingScope, ChannelContext), ChannelError> { let logger = WithContext::from(logger, Some(counterparty_node_id), Some(open_channel_fields.temporary_channel_id), None); let announce_for_forwarding = if (open_channel_fields.channel_flags & 1) == 1 { true } else { false }; @@ -3720,7 +3613,7 @@ where } #[rustfmt::skip] - fn new_for_outbound_channel<'a, ES: Deref, F: Deref, L: Deref>( + fn new_for_outbound_channel<'a, ES: EntropySource, F: FeeEstimator, L: Logger>( fee_estimator: &'a LowerBoundedFeeEstimator, entropy_source: &'a ES, signer_provider: &'a SP, @@ -3735,15 +3628,9 @@ where temporary_channel_id_fn: Option ChannelId>, holder_selected_channel_reserve_satoshis: u64, channel_keys_id: [u8; 32], - holder_signer: ::EcdsaSigner, + holder_signer: ::EcdsaSigner, _logger: L, - ) -> Result<(FundingScope, ChannelContext), APIError> - where - ES::Target: EntropySource, - F::Target: FeeEstimator, - SP::Target: SignerProvider, - L::Target: Logger, - { + ) -> Result<(FundingScope, ChannelContext), APIError> { // This will be updated with the counterparty contribution if this is a dual-funded channel let channel_value_satoshis = funding_satoshis; @@ -4350,12 +4237,9 @@ where /// Returns a maximum "sane" fee rate used to reason about our dust exposure. /// Will be Some if the `channel_type`'s dust exposure depends on its commitment fee rate, and /// None otherwise. - fn get_dust_exposure_limiting_feerate( + fn get_dust_exposure_limiting_feerate( &self, fee_estimator: &LowerBoundedFeeEstimator, channel_type: &ChannelTypeFeatures, - ) -> Option - where - F::Target: FeeEstimator, - { + ) -> Option { if channel_type.supports_anchor_zero_fee_commitments() { None } else { @@ -4752,13 +4636,10 @@ where Ok(ret) } - fn validate_update_add_htlc( + fn validate_update_add_htlc( &self, funding: &FundingScope, msg: &msgs::UpdateAddHTLC, fee_estimator: &LowerBoundedFeeEstimator, - ) -> Result<(), ChannelError> - where - F::Target: FeeEstimator, - { + ) -> Result<(), ChannelError> { if msg.amount_msat > funding.get_value_satoshis() * 1000 { return Err(ChannelError::close( "Remote side tried to send more than the total value of the channel".to_owned(), @@ -4870,13 +4751,10 @@ where Ok(()) } - fn validate_update_fee( + fn validate_update_fee( &self, funding: &FundingScope, fee_estimator: &LowerBoundedFeeEstimator, new_feerate_per_kw: u32, - ) -> Result<(), ChannelError> - where - F::Target: FeeEstimator, - { + ) -> Result<(), ChannelError> { // Check that we won't be pushed over our dust exposure limit by the feerate increase. let dust_exposure_limiting_feerate = self.get_dust_exposure_limiting_feerate(&fee_estimator, funding.get_channel_type()); @@ -4948,17 +4826,13 @@ where Ok(()) } - fn validate_commitment_signed( + fn validate_commitment_signed( &self, funding: &FundingScope, transaction_number: u64, commitment_point: PublicKey, msg: &msgs::CommitmentSigned, fee_estimator: &LowerBoundedFeeEstimator, logger: &L, ) -> Result< (HolderCommitmentTransaction, Vec<(HTLCOutputInCommitment, Option<&HTLCSource>)>), ChannelError, - > - where - F::Target: FeeEstimator, - L::Target: Logger, - { + > { let funding_script = funding.get_funding_redeemscript(); let commitment_data = self.build_commitment_transaction( @@ -5080,14 +4954,10 @@ where Ok((holder_commitment_tx, commitment_data.htlcs_included)) } - fn can_send_update_fee( + fn can_send_update_fee( &self, funding: &FundingScope, feerate_per_kw: u32, fee_estimator: &LowerBoundedFeeEstimator, logger: &L, - ) -> bool - where - F::Target: FeeEstimator, - L::Target: Logger, - { + ) -> bool { // Before proposing a feerate update, check that we can actually afford the new fee. let dust_exposure_limiting_feerate = self.get_dust_exposure_limiting_feerate(&fee_estimator, funding.get_channel_type()); @@ -5162,12 +5032,9 @@ where return true; } - fn can_accept_incoming_htlc( + fn can_accept_incoming_htlc( &self, funding: &FundingScope, dust_exposure_limiting_feerate: Option, logger: &L, - ) -> Result<(), LocalHTLCFailureReason> - where - L::Target: Logger, - { + ) -> Result<(), LocalHTLCFailureReason> { // The fee spike buffer (an additional nondust HTLC) we keep for the remote if the channel // is not zero fee. This deviates from the spec because the fee spike buffer requirement // doesn't exist on the receiver's side, only on the sender's. @@ -5293,9 +5160,7 @@ where /// 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 - { + fn build_commitment_transaction(&self, funding: &FundingScope, commitment_number: u64, per_commitment_point: &PublicKey, local: bool, generated_by_local: bool, logger: &L) -> CommitmentData<'_> { let broadcaster_dust_limit_sat = if local { self.holder_dust_limit_satoshis } else { self.counterparty_dust_limit_satoshis }; let feerate_per_kw = self.get_commitment_feerate(funding, generated_by_local); @@ -5667,12 +5532,9 @@ where } #[rustfmt::skip] - fn get_available_balances_for_scope( + fn get_available_balances_for_scope( &self, funding: &FundingScope, fee_estimator: &LowerBoundedFeeEstimator, - ) -> AvailableBalances - where - F::Target: FeeEstimator, - { + ) -> AvailableBalances { let context = &self; // Note that we have to handle overflow due to the case mentioned in the docs in general // here. @@ -6151,10 +6013,10 @@ where /// Only allowed after [`FundingScope::channel_transaction_parameters`] is set. #[rustfmt::skip] - fn get_funding_signed_msg( + fn get_funding_signed_msg( &mut self, channel_parameters: &ChannelTransactionParameters, logger: &L, counterparty_initial_commitment_tx: CommitmentTransaction, - ) -> Option where L::Target: Logger { + ) -> Option { let counterparty_trusted_tx = counterparty_initial_commitment_tx.trust(); let counterparty_initial_bitcoin_tx = counterparty_trusted_tx.built_transaction(); log_trace!(logger, "Initial counterparty tx for channel {} is: txid {} tx {}", @@ -6191,13 +6053,10 @@ where /// 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( + pub(crate) fn maybe_downgrade_channel_features( &mut self, funding: &mut FundingScope, fee_estimator: &LowerBoundedFeeEstimator, user_config: &UserConfig, their_features: &InitFeatures, - ) -> Result<(), ()> - where - F::Target: FeeEstimator - { + ) -> Result<(), ()> { if !funding.is_outbound() || !matches!( self.channel_state, ChannelState::NegotiatingFunding(flags) @@ -6259,13 +6118,9 @@ where } } - fn get_initial_counterparty_commitment_signatures( + fn get_initial_counterparty_commitment_signatures( &self, funding: &FundingScope, logger: &L, - ) -> Option<(Signature, Vec)> - where - SP::Target: SignerProvider, - L::Target: Logger, - { + ) -> Option<(Signature, Vec)> { let mut commitment_number = self.counterparty_next_commitment_transaction_number; let mut commitment_point = self.counterparty_next_commitment_point.unwrap(); @@ -6304,13 +6159,9 @@ where } } - fn get_initial_commitment_signed_v2( + fn get_initial_commitment_signed_v2( &self, funding: &FundingScope, logger: &L, - ) -> Option - where - SP::Target: SignerProvider, - L::Target: Logger, - { + ) -> Option { let signatures = self.get_initial_counterparty_commitment_signatures(funding, logger); if let Some((signature, htlc_signatures)) = signatures { log_info!(logger, "Generated commitment_signed for peer",); @@ -6356,13 +6207,10 @@ where } #[rustfmt::skip] - fn check_for_funding_tx_confirmed( + fn check_for_funding_tx_confirmed( &mut self, funding: &mut FundingScope, block_hash: &BlockHash, height: u32, index_in_block: usize, tx: &mut ConfirmedTransaction, logger: &L, - ) -> Result - where - L::Target: Logger, - { + ) -> Result { let funding_txo = match funding.get_funding_txo() { Some(funding_txo) => funding_txo, None => { @@ -6651,14 +6499,10 @@ pub(super) struct FundingNegotiationContext { impl FundingNegotiationContext { /// Prepare and start interactive transaction negotiation. /// If error occurs, it is caused by our side, not the counterparty. - fn into_interactive_tx_constructor( + fn into_interactive_tx_constructor( mut self, context: &ChannelContext, funding: &FundingScope, signer_provider: &SP, entropy_source: &ES, holder_node_id: PublicKey, - ) -> Result - where - SP::Target: SignerProvider, - ES::Target: EntropySource, - { + ) -> Result { debug_assert_eq!( self.shared_funding_input.is_some(), funding.channel_transaction_parameters.splice_parent_funding_txid.is_some(), @@ -6762,10 +6606,7 @@ impl FundingNegotiationContext { // Holder designates channel data owned for the benefit of the user client. // Counterparty designates channel data owned by the another channel participant entity. #[cfg_attr(test, derive(Debug))] -pub(super) struct FundedChannel -where - SP::Target: SignerProvider, -{ +pub(super) struct FundedChannel { pub funding: FundingScope, pub context: ChannelContext, holder_commitment_point: HolderCommitmentPoint, @@ -6948,10 +6789,9 @@ pub struct SpliceFundingPromotion { pub discarded_funding: Vec, } -impl FundedChannel +impl FundedChannel where - SP::Target: SignerProvider, - ::EcdsaSigner: EcdsaChannelSigner, + ::EcdsaSigner: EcdsaChannelSigner, { pub fn context(&self) -> &ChannelContext { &self.context @@ -7118,11 +6958,10 @@ where } #[rustfmt::skip] - fn check_remote_fee( + fn check_remote_fee( channel_type: &ChannelTypeFeatures, fee_estimator: &LowerBoundedFeeEstimator, feerate_per_kw: u32, cur_feerate_per_kw: Option, logger: &L - ) -> Result<(), ChannelError> where F::Target: FeeEstimator, L::Target: Logger, - { + ) -> Result<(), ChannelError> { if channel_type.supports_anchor_zero_fee_commitments() { if feerate_per_kw != 0 { let err = "Zero Fee Channels must never attempt to use a fee".to_owned(); @@ -7272,11 +7111,9 @@ where /// /// The HTLC claim will end up in the holding cell (because the caller must ensure the peer is /// disconnected). - pub fn claim_htlc_while_disconnected_dropping_mon_update_legacy( + 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, - { + ) { // Assert that we'll add the HTLC claim to the holding cell in `get_update_fulfill_htlc` // (see equivalent if condition there). assert!(!self.context.channel_state.can_generate_new_commitment()); @@ -7289,14 +7126,11 @@ where } } - fn get_update_fulfill_htlc( + fn get_update_fulfill_htlc( &mut self, htlc_id_arg: u64, payment_preimage_arg: PaymentPreimage, payment_info: Option, attribution_data: Option, logger: &L, - ) -> UpdateFulfillFetch - where - L::Target: Logger, - { + ) -> UpdateFulfillFetch { // Either ChannelReady got set (which means it won't be unset) or there is no way any // caller thought we could have something claimed (cause we wouldn't have accepted in an // incoming HTLC anyway). If we got to ShutdownComplete, callers aren't allowed to call us, @@ -7443,14 +7277,11 @@ where UpdateFulfillFetch::NewClaim { monitor_update, htlc_value_msat, update_blocked: false } } - pub fn get_update_fulfill_htlc_and_commit( + pub fn get_update_fulfill_htlc_and_commit( &mut self, htlc_id: u64, payment_preimage: PaymentPreimage, payment_info: Option, attribution_data: Option, logger: &L, - ) -> UpdateFulfillCommitFetch - where - L::Target: Logger, - { + ) -> UpdateFulfillCommitFetch { let release_cs_monitor = self.context.blocked_monitor_updates.is_empty(); match self.get_update_fulfill_htlc( htlc_id, @@ -7510,12 +7341,9 @@ 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( + pub fn queue_fail_htlc( &mut self, htlc_id_arg: u64, err_packet: msgs::OnionErrorPacket, logger: &L, - ) -> Result<(), ChannelError> - where - L::Target: Logger, - { + ) -> Result<(), ChannelError> { self.fail_htlc(htlc_id_arg, err_packet, true, logger) .map(|msg_opt| assert!(msg_opt.is_none(), "We forced holding cell?")) } @@ -7524,12 +7352,9 @@ where /// want to fail blinded HTLCs where we are not the intro node. /// /// See [`Self::queue_fail_htlc`] for more info. - pub fn queue_fail_malformed_htlc( + 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, - { + ) -> Result<(), ChannelError> { 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?")) } @@ -7537,10 +7362,10 @@ where /// 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( + fn fail_htlc( &mut self, htlc_id_arg: u64, err_contents: E, mut force_holding_cell: bool, logger: &L - ) -> Result, ChannelError> where L::Target: Logger { + ) -> Result, ChannelError> { if !matches!(self.context.channel_state, ChannelState::ChannelReady(_)) { panic!("Was asked to fail an HTLC when channel was not in an operational state"); } @@ -7647,14 +7472,10 @@ where /// and the channel is now usable (and public), this may generate an announcement_signatures to /// reply with. #[rustfmt::skip] - pub fn channel_ready( + pub fn channel_ready( &mut self, msg: &msgs::ChannelReady, node_signer: &NS, chain_hash: ChainHash, user_config: &UserConfig, best_block: &BestBlock, logger: &L - ) -> Result, ChannelError> - where - NS::Target: NodeSigner, - L::Target: Logger - { + ) -> Result, ChannelError> { if self.context.channel_state.is_peer_disconnected() { self.context.workaround_lnd_bug_4006 = Some(msg.clone()); return Err(ChannelError::Ignore("Peer sent channel_ready when we needed a channel_reestablish. The peer is likely lnd, see https://github.com/lightningnetwork/lnd/issues/4006".to_owned())); @@ -7729,9 +7550,9 @@ where } #[rustfmt::skip] - pub fn update_add_htlc( + pub fn update_add_htlc( &mut self, msg: &msgs::UpdateAddHTLC, fee_estimator: &LowerBoundedFeeEstimator, - ) -> Result<(), ChannelError> where F::Target: FeeEstimator { + ) -> Result<(), ChannelError> { if self.context.channel_state.is_remote_stfu_sent() || self.context.channel_state.is_quiescent() { return Err(ChannelError::WarnAndDisconnect("Got add HTLC message while quiescent".to_owned())); } @@ -7883,13 +7704,10 @@ where Ok(()) } - pub fn initial_commitment_signed_v2( + pub fn initial_commitment_signed_v2( &mut self, msg: &msgs::CommitmentSigned, best_block: BestBlock, signer_provider: &SP, logger: &L, - ) -> Result::EcdsaSigner>, ChannelError> - where - L::Target: Logger, - { + ) -> Result::EcdsaSigner>, ChannelError> { if let Some(signing_session) = self.context.interactive_tx_signing_session.as_ref() { if signing_session.has_received_tx_signatures() { let msg = "Received initial commitment_signed after peer's tx_signatures received!"; @@ -7953,14 +7771,10 @@ where /// Note that our `commitment_signed` send did not include a monitor update. This is due to: /// 1. Updates cannot be made since the state machine is paused until `tx_signatures`. /// 2. We're still able to abort negotiation until `tx_signatures`. - fn splice_initial_commitment_signed( + fn splice_initial_commitment_signed( &mut self, msg: &msgs::CommitmentSigned, fee_estimator: &LowerBoundedFeeEstimator, logger: &L, - ) -> Result, ChannelError> - where - F::Target: FeeEstimator, - L::Target: Logger, - { + ) -> Result, ChannelError> { debug_assert!(self .context .interactive_tx_signing_session @@ -8070,14 +7884,10 @@ where (nondust_htlc_sources, dust_htlcs) } - pub fn commitment_signed( + pub fn commitment_signed( &mut self, msg: &msgs::CommitmentSigned, fee_estimator: &LowerBoundedFeeEstimator, logger: &L, - ) -> Result, ChannelError> - where - F::Target: FeeEstimator, - L::Target: Logger, - { + ) -> Result, ChannelError> { self.commitment_signed_check_state()?; if !self.pending_funding().is_empty() { @@ -8114,14 +7924,10 @@ where self.commitment_signed_update_monitor(update, logger) } - pub fn commitment_signed_batch( + pub fn commitment_signed_batch( &mut self, batch: Vec, fee_estimator: &LowerBoundedFeeEstimator, logger: &L, - ) -> Result, ChannelError> - where - F::Target: FeeEstimator, - L::Target: Logger, - { + ) -> Result, ChannelError> { self.commitment_signed_check_state()?; let mut messages = BTreeMap::new(); @@ -8219,12 +8025,9 @@ where Ok(()) } - fn commitment_signed_update_monitor( + fn commitment_signed_update_monitor( &mut self, mut update: ChannelMonitorUpdateStep, logger: &L, - ) -> Result, ChannelError> - where - L::Target: Logger, - { + ) -> Result, ChannelError> { if self .holder_commitment_point .advance(&self.context.holder_signer, &self.context.secp_ctx, logger) @@ -8368,13 +8171,9 @@ 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())`. - pub fn maybe_free_holding_cell_htlcs( + pub fn maybe_free_holding_cell_htlcs( &mut self, fee_estimator: &LowerBoundedFeeEstimator, logger: &L, - ) -> (Option, Vec<(HTLCSource, PaymentHash)>) - where - F::Target: FeeEstimator, - L::Target: Logger, - { + ) -> (Option, Vec<(HTLCSource, PaymentHash)>) { if matches!(self.context.channel_state, ChannelState::ChannelReady(_)) && self.context.channel_state.can_generate_new_commitment() { @@ -8386,13 +8185,9 @@ where /// Frees any pending commitment updates in the holding cell, generating the relevant messages /// for our counterparty. - fn free_holding_cell_htlcs( + fn free_holding_cell_htlcs( &mut self, fee_estimator: &LowerBoundedFeeEstimator, logger: &L, - ) -> (Option, Vec<(HTLCSource, PaymentHash)>) - where - F::Target: FeeEstimator, - L::Target: Logger, - { + ) -> (Option, Vec<(HTLCSource, PaymentHash)>) { assert!(matches!(self.context.channel_state, ChannelState::ChannelReady(_))); assert!(!self.context.channel_state.is_monitor_update_in_progress()); assert!(!self.context.channel_state.is_quiescent()); @@ -8595,7 +8390,7 @@ where /// /// [`HeldHtlcAvailable`]: crate::onion_message::async_payments::HeldHtlcAvailable /// [`ReleaseHeldHtlc`]: crate::onion_message::async_payments::ReleaseHeldHtlc - pub fn revoke_and_ack( + pub fn revoke_and_ack( &mut self, msg: &msgs::RevokeAndACK, fee_estimator: &LowerBoundedFeeEstimator, logger: &L, hold_mon_update: bool, ) -> Result< @@ -8605,11 +8400,7 @@ where Option, ), ChannelError, - > - where - F::Target: FeeEstimator, - L::Target: Logger, - { + > { if self.context.channel_state.is_quiescent() { return Err(ChannelError::WarnAndDisconnect( "Got revoke_and_ack message while quiescent".to_owned(), @@ -9020,13 +8811,10 @@ where } } - fn on_tx_signatures_exchange<'a, L: Deref>( + fn on_tx_signatures_exchange<'a, L: Logger>( &mut self, funding_tx: Transaction, best_block_height: u32, logger: &WithChannelContext<'a, L>, - ) -> (Option, Option) - where - L::Target: Logger, - { + ) -> (Option, Option) { debug_assert!(!self.context.channel_state.is_monitor_update_in_progress()); debug_assert!(!self.context.channel_state.is_awaiting_remote_revoke()); @@ -9078,13 +8866,10 @@ where } } - pub fn funding_transaction_signed( + pub fn funding_transaction_signed( &mut self, funding_txid_signed: Txid, witnesses: Vec, best_block_height: u32, logger: &L, - ) -> Result - where - L::Target: Logger, - { + ) -> Result { let signing_session = if let Some(signing_session) = self.context.interactive_tx_signing_session.as_mut() { if let Some(pending_splice) = self.pending_splice.as_ref() { @@ -9179,12 +8964,9 @@ where Ok(FundingTxSigned { tx_signatures, funding_tx, splice_negotiated, splice_locked }) } - pub fn tx_signatures( + pub fn tx_signatures( &mut self, msg: &msgs::TxSignatures, best_block_height: u32, logger: &L, - ) -> Result - where - L::Target: Logger, - { + ) -> Result { let signing_session = if let Some(signing_session) = self.context.interactive_tx_signing_session.as_mut() { @@ -9254,12 +9036,9 @@ 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( + 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?"); } @@ -9272,12 +9051,10 @@ 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( + fn send_update_fee( &mut self, feerate_per_kw: u32, mut force_holding_cell: bool, fee_estimator: &LowerBoundedFeeEstimator, logger: &L - ) -> Option - where F::Target: FeeEstimator, L::Target: Logger - { + ) -> Option { if !self.funding.is_outbound() { panic!("Cannot send fee from inbound channel"); } @@ -9327,7 +9104,7 @@ where /// 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 { + fn remove_uncommitted_htlcs_and_mark_paused(&mut self, logger: &L) -> Result<(), ()> { assert!(!matches!(self.context.channel_state, ChannelState::ShutdownComplete)); if !self.context.can_resume_on_reconnect() { return Err(()) @@ -9413,14 +9190,12 @@ where /// [`ChannelManager`]: super::channelmanager::ChannelManager /// [`chain::Watch`]: crate::chain::Watch /// [`ChannelMonitorUpdateStatus::InProgress`]: crate::chain::ChannelMonitorUpdateStatus::InProgress - fn monitor_updating_paused( + fn monitor_updating_paused( &mut self, resend_raa: bool, resend_commitment: bool, resend_channel_ready: bool, pending_forwards: Vec<(PendingHTLCInfo, u64)>, pending_fails: Vec<(HTLCSource, PaymentHash, HTLCFailReason)>, pending_finalized_claimed_htlcs: Vec<(HTLCSource, Option)>, logger: &L, - ) where - L::Target: Logger, - { + ) { log_trace!(logger, "Pausing channel monitor updates"); self.context.monitor_pending_revoke_and_ack |= resend_raa; @@ -9436,13 +9211,11 @@ where /// successfully and we should restore normal operation. Returns messages which should be sent /// to the remote side. #[rustfmt::skip] - pub fn monitor_updating_restored( + pub fn monitor_updating_restored( &mut self, logger: &L, node_signer: &NS, chain_hash: ChainHash, user_config: &UserConfig, best_block_height: u32, path_for_release_htlc: CBP ) -> MonitorRestoreUpdates where - L::Target: Logger, - NS::Target: NodeSigner, CBP: Fn(u64) -> BlindedMessagePath { assert!(self.context.channel_state.is_monitor_update_in_progress()); @@ -9571,9 +9344,7 @@ 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 - { + pub fn update_fee(&mut self, fee_estimator: &LowerBoundedFeeEstimator, msg: &msgs::UpdateFee, logger: &L) -> Result<(), ChannelError> { if self.funding.is_outbound() { return Err(ChannelError::close("Non-funding remote tried to update channel fee".to_owned())); } @@ -9599,9 +9370,9 @@ 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( + pub fn signer_maybe_unblocked( &mut self, logger: &L, path_for_release_htlc: CBP - ) -> Result where L::Target: Logger, CBP: Fn(u64) -> BlindedMessagePath { + ) -> Result where CBP: Fn(u64) -> BlindedMessagePath { if let Some((commitment_number, commitment_secret)) = self.context.signer_pending_stale_state_verification.clone() { if let Ok(expected_point) = self.context.holder_signer.as_ref() .get_per_commitment_point(commitment_number, &self.context.secp_ctx) @@ -9711,11 +9482,10 @@ where }) } - fn get_last_revoke_and_ack( + fn get_last_revoke_and_ack( &mut self, path_for_release_htlc: CBP, logger: &L, ) -> Option where - L::Target: Logger, CBP: Fn(u64) -> BlindedMessagePath, { debug_assert!( @@ -9770,12 +9540,9 @@ where } /// Gets the last commitment update for immediate sending to our peer. - fn get_last_commitment_update_for_send( + fn get_last_commitment_update_for_send( &mut self, logger: &L, - ) -> Result - where - L::Target: Logger, - { + ) -> Result { let mut update_add_htlcs = Vec::new(); let mut update_fulfill_htlcs = Vec::new(); let mut update_fail_htlcs = Vec::new(); @@ -9887,10 +9654,7 @@ where } } - fn panic_on_stale_state(logger: &L) - where - L::Target: Logger, - { + fn panic_on_stale_state(logger: &L) { macro_rules! log_and_panic { ($err_msg: expr) => { log_error!(logger, $err_msg); @@ -9909,14 +9673,12 @@ where /// May panic if some calls other than message-handling calls (which will all Err immediately) /// have been called between remove_uncommitted_htlcs_and_mark_paused and this call. #[rustfmt::skip] - pub fn channel_reestablish( + pub fn channel_reestablish( &mut self, msg: &msgs::ChannelReestablish, logger: &L, node_signer: &NS, chain_hash: ChainHash, user_config: &UserConfig, best_block: &BestBlock, path_for_release_htlc: CBP, ) -> Result where - L::Target: Logger, - NS::Target: NodeSigner, CBP: Fn(u64) -> BlindedMessagePath { if !self.context.channel_state.is_peer_disconnected() { @@ -10295,12 +10057,9 @@ 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. - fn calculate_closing_fee_limits( + fn calculate_closing_fee_limits( &mut self, fee_estimator: &LowerBoundedFeeEstimator, - ) -> (u64, u64) - where - F::Target: FeeEstimator, - { + ) -> (u64, u64) { if let Some((min, max)) = self.context.closing_fee_limits { return (min, max); } @@ -10387,12 +10146,9 @@ where Ok(()) } - pub fn maybe_propose_closing_signed( + pub fn maybe_propose_closing_signed( &mut self, fee_estimator: &LowerBoundedFeeEstimator, logger: &L, ) -> Result<(Option, Option<(Transaction, ShutdownResult)>), ChannelError> - where - F::Target: FeeEstimator, - L::Target: Logger, { // If we're waiting on a monitor persistence, that implies we're also waiting to send some // message to our counterparty (probably a `revoke_and_ack`). In such a case, we shouldn't @@ -10472,16 +10228,13 @@ where } } - pub fn shutdown( + pub fn shutdown( &mut self, logger: &L, signer_provider: &SP, their_features: &InitFeatures, msg: &msgs::Shutdown, ) -> Result< (Option, Option, Vec<(HTLCSource, PaymentHash)>), ChannelError, - > - where - L::Target: Logger, - { + > { if self.context.channel_state.is_peer_disconnected() { return Err(ChannelError::close( "Peer sent shutdown when we needed a channel_reestablish".to_owned(), @@ -10653,13 +10406,10 @@ where tx } - fn get_closing_signed_msg( + 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, - ) -> Option - where - L::Target: Logger, - { + ) -> Option { let sig = match &self.context.holder_signer { ChannelSignerType::Ecdsa(ecdsa) => ecdsa .sign_closing_transaction( @@ -10714,13 +10464,10 @@ where } } - pub fn closing_signed( + pub fn closing_signed( &mut self, fee_estimator: &LowerBoundedFeeEstimator, msg: &msgs::ClosingSigned, logger: &L, ) -> Result<(Option, Option<(Transaction, ShutdownResult)>), ChannelError> - where - F::Target: FeeEstimator, - L::Target: Logger, { if self.is_shutdown_pending_signature() { return Err(ChannelError::Warn(String::from("Remote end sent us a closing_signed while fully shutdown and just waiting on the final closing signature"))); @@ -10964,13 +10711,9 @@ 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( + pub fn can_accept_incoming_htlc( &self, fee_estimator: &LowerBoundedFeeEstimator, logger: L - ) -> Result<(), LocalHTLCFailureReason> - where - F::Target: FeeEstimator, - L::Target: Logger - { + ) -> Result<(), LocalHTLCFailureReason> { if self.context.channel_state.is_local_shutdown_sent() { return Err(LocalHTLCFailureReason::ChannelClosed) } @@ -11181,9 +10924,7 @@ where } #[rustfmt::skip] - fn check_get_channel_ready(&mut self, height: u32, logger: &L) -> Option - where L::Target: Logger - { + fn check_get_channel_ready(&mut self, height: u32, logger: &L) -> Option { // Called: // * always when a new block/transactions are confirmed with the new height // * when funding is signed with a height of 0 @@ -11240,9 +10981,9 @@ where } #[rustfmt::skip] - fn get_channel_ready( + fn get_channel_ready( &mut self, logger: &L - ) -> Option where L::Target: Logger { + ) -> Option { if self.holder_commitment_point.can_advance() { self.context.signer_pending_channel_ready = false; Some(msgs::ChannelReady { @@ -11262,14 +11003,10 @@ where } /// Returns `Some` if a splice [`FundingScope`] was promoted. - fn maybe_promote_splice_funding( + fn maybe_promote_splice_funding( &mut self, node_signer: &NS, chain_hash: ChainHash, user_config: &UserConfig, block_height: u32, logger: &L, - ) -> Option - where - NS::Target: NodeSigner, - L::Target: Logger, - { + ) -> Option { debug_assert!(self.pending_splice.is_some()); let pending_splice = self.pending_splice.as_mut().unwrap(); @@ -11383,14 +11120,10 @@ where /// 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( + pub fn transactions_confirmed( &mut self, block_hash: &BlockHash, height: u32, txdata: &TransactionData, chain_hash: ChainHash, node_signer: &NS, user_config: &UserConfig, logger: &L - ) -> Result<(Option, Option), ClosureReason> - where - NS::Target: NodeSigner, - L::Target: Logger - { + ) -> Result<(Option, Option), ClosureReason> { for &(index_in_block, tx) in txdata.iter() { let mut confirmed_tx = ConfirmedTransaction::from(tx); @@ -11481,14 +11214,10 @@ where /// /// May return some HTLCs (and their payment_hash) which have timed out and should be failed /// back. - pub fn best_block_updated( + pub fn best_block_updated( &mut self, height: u32, highest_header_time: Option, chain_hash: ChainHash, node_signer: &NS, user_config: &UserConfig, logger: &L, - ) -> Result - where - NS::Target: NodeSigner, - L::Target: Logger, - { + ) -> Result { self.do_best_block_updated( height, highest_header_time, @@ -11498,14 +11227,10 @@ where } #[rustfmt::skip] - fn do_best_block_updated( + fn do_best_block_updated( &mut self, height: u32, highest_header_time: Option, chain_node_signer: Option<(ChainHash, &NS, &UserConfig)>, logger: &L - ) -> Result<(Option, Vec<(HTLCSource, PaymentHash)>, Option), ClosureReason> - where - NS::Target: NodeSigner, - L::Target: Logger - { + ) -> Result<(Option, Vec<(HTLCSource, PaymentHash)>, Option), ClosureReason> { let mut timed_out_htlcs = Vec::new(); // This mirrors the check in ChannelManager::decode_update_add_htlc_onion, refusing to // forward an HTLC when our counterparty should almost certainly just fail it for expiring @@ -11681,12 +11406,9 @@ where /// before the channel has reached channel_ready or splice_locked, and we can just wait for more /// blocks. #[rustfmt::skip] - pub fn transaction_unconfirmed( + pub fn transaction_unconfirmed( &mut self, txid: &Txid, logger: &L, - ) -> Result<(), ClosureReason> - where - L::Target: Logger, - { + ) -> Result<(), ClosureReason> { let unconfirmed_funding = self .funding_and_pending_funding_iter_mut() .find(|funding| funding.get_funding_txid() == Some(*txid)); @@ -11731,9 +11453,9 @@ where /// /// [`ChannelReady`]: crate::ln::msgs::ChannelReady #[rustfmt::skip] - fn get_channel_announcement( + fn get_channel_announcement( &self, node_signer: &NS, chain_hash: ChainHash, user_config: &UserConfig, - ) -> Result where NS::Target: NodeSigner { + ) -> Result { if !self.context.config.announce_for_forwarding { return Err(ChannelError::Ignore("Channel is not available for public announcements".to_owned())); } @@ -11763,14 +11485,10 @@ where } #[rustfmt::skip] - fn get_announcement_sigs( + fn get_announcement_sigs( &mut self, node_signer: &NS, chain_hash: ChainHash, user_config: &UserConfig, best_block_height: u32, logger: &L - ) -> Option - where - NS::Target: NodeSigner, - L::Target: Logger - { + ) -> Option { if self.funding.funding_tx_confirmation_height == 0 || self.funding.funding_tx_confirmation_height + 5 > best_block_height { return None; } @@ -11837,9 +11555,9 @@ where /// Signs the given channel announcement, returning a ChannelError::Ignore if no keys are /// available. #[rustfmt::skip] - fn sign_channel_announcement( + fn sign_channel_announcement( &self, node_signer: &NS, announcement: msgs::UnsignedChannelAnnouncement - ) -> Result where NS::Target: NodeSigner { + ) -> Result { if let Some((their_node_sig, their_bitcoin_sig)) = self.context.announcement_sigs { let our_node_key = NodeId::from_pubkey(&node_signer.get_node_id(Recipient::Node) .map_err(|_| ChannelError::Ignore("Signer failed to retrieve own public key".to_owned()))?); @@ -11874,10 +11592,10 @@ where /// 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( + pub fn announcement_signatures( &mut self, node_signer: &NS, chain_hash: ChainHash, best_block_height: u32, msg: &msgs::AnnouncementSignatures, user_config: &UserConfig - ) -> Result where NS::Target: NodeSigner { + ) -> Result { let announcement = self.get_channel_announcement(node_signer, chain_hash, user_config)?; let msghash = hash_to_message!(&Sha256d::hash(&announcement.encode()[..])[..]); @@ -11905,9 +11623,9 @@ 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( + 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 { + ) -> Option { if self.funding.funding_tx_confirmation_height == 0 || self.funding.funding_tx_confirmation_height + 5 > best_block_height { return None; } @@ -11977,7 +11695,7 @@ 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 { + fn get_channel_reestablish(&mut self, logger: &L) -> msgs::ChannelReestablish { assert!(self.context.channel_state.is_peer_disconnected()); assert_ne!(self.context.counterparty_next_commitment_transaction_number, INITIAL_COMMITMENT_NUMBER); // This is generally the first function which gets called on any given channel once we're @@ -12034,13 +11752,10 @@ where /// Includes the witness weight for this input (e.g. P2WPKH_WITNESS_WEIGHT=109 for typical P2WPKH inputs). /// - `change_script`: an option change output script. If `None` and needed, one will be /// generated by `SignerProvider::get_destination_script`. - pub fn splice_channel( + pub fn splice_channel( &mut self, contribution: SpliceContribution, funding_feerate_per_kw: u32, locktime: u32, logger: &L, - ) -> Result, APIError> - where - L::Target: Logger, - { + ) -> Result, APIError> { if self.holder_commitment_point.current_point().is_none() { return Err(APIError::APIMisuseError { err: format!( @@ -12383,14 +12098,10 @@ where Ok(()) } - pub(crate) fn splice_init( + pub(crate) fn splice_init( &mut self, msg: &msgs::SpliceInit, our_funding_contribution_satoshis: i64, signer_provider: &SP, entropy_source: &ES, holder_node_id: &PublicKey, logger: &L, - ) -> Result - where - ES::Target: EntropySource, - L::Target: Logger, - { + ) -> Result { let our_funding_contribution = SignedAmount::from_sat(our_funding_contribution_satoshis); let splice_funding = self.validate_splice_init(msg, our_funding_contribution)?; @@ -12454,14 +12165,10 @@ where }) } - pub(crate) fn splice_ack( + pub(crate) fn splice_ack( &mut self, msg: &msgs::SpliceAck, signer_provider: &SP, entropy_source: &ES, holder_node_id: &PublicKey, logger: &L, - ) -> Result, ChannelError> - where - ES::Target: EntropySource, - L::Target: Logger, - { + ) -> Result, ChannelError> { let splice_funding = self.validate_splice_ack(msg)?; log_info!( @@ -12608,14 +12315,10 @@ where Ok((holder_balance_floor, counterparty_balance_floor)) } - pub fn splice_locked( + pub fn splice_locked( &mut self, msg: &msgs::SpliceLocked, node_signer: &NS, chain_hash: ChainHash, user_config: &UserConfig, block_height: u32, logger: &L, - ) -> Result, ChannelError> - where - NS::Target: NodeSigner, - L::Target: Logger, - { + ) -> Result, ChannelError> { log_info!(logger, "Received splice_locked txid {} from our peer", msg.splice_txid,); let pending_splice = match self.pending_splice.as_mut() { @@ -12656,16 +12359,12 @@ 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. - pub fn queue_add_htlc( + 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, blinding_point: Option, accountable: bool, fee_estimator: &LowerBoundedFeeEstimator, logger: &L, - ) -> Result<(), (LocalHTLCFailureReason, String)> - where - F::Target: FeeEstimator, - L::Target: Logger, - { + ) -> Result<(), (LocalHTLCFailureReason, String)> { self.send_htlc( amount_msat, payment_hash, @@ -12705,16 +12404,12 @@ where /// on this [`FundedChannel`] if `force_holding_cell` is false. /// /// `Err`'s will always be temporary channel failures. - fn send_htlc( + 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, skimmed_fee_msat: Option, blinding_point: Option, hold_htlc: bool, accountable: bool, fee_estimator: &LowerBoundedFeeEstimator, logger: &L, - ) -> Result - where - F::Target: FeeEstimator, - L::Target: Logger, - { + ) -> Result { if !matches!(self.context.channel_state, ChannelState::ChannelReady(_)) || self.context.channel_state.is_local_shutdown_sent() || self.context.channel_state.is_remote_shutdown_sent() @@ -12822,12 +12517,9 @@ where } #[rustfmt::skip] - pub(super) fn get_available_balances( + pub(super) fn get_available_balances( &self, fee_estimator: &LowerBoundedFeeEstimator, - ) -> AvailableBalances - where - F::Target: FeeEstimator, - { + ) -> AvailableBalances { core::iter::once(&self.funding) .chain(self.pending_funding().iter()) .map(|funding| self.context.get_available_balances_for_scope(funding, fee_estimator)) @@ -12842,10 +12534,7 @@ where .expect("At least one FundingScope is always provided") } - fn build_commitment_no_status_check(&mut self, logger: &L) -> ChannelMonitorUpdate - where - L::Target: Logger, - { + fn build_commitment_no_status_check(&mut self, logger: &L) -> ChannelMonitorUpdate { 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 // fail to generate this, we still are at least at a position where upgrading their status @@ -12963,12 +12652,9 @@ where } #[rustfmt::skip] - fn build_commitment_no_state_update( + fn build_commitment_no_state_update( &self, funding: &FundingScope, logger: &L, - ) -> (Vec<(HTLCOutputInCommitment, Option<&HTLCSource>)>, CommitmentTransaction) - where - L::Target: Logger, - { + ) -> (Vec<(HTLCOutputInCommitment, Option<&HTLCSource>)>, CommitmentTransaction) { let commitment_data = self.context.build_commitment_transaction( funding, self.context.counterparty_next_commitment_transaction_number, &self.context.counterparty_next_commitment_point.unwrap(), false, true, logger, @@ -12980,12 +12666,9 @@ where /// Only fails in case of signer rejection. Used for channel_reestablish commitment_signed /// generation when we shouldn't change HTLC/channel state. - fn send_commitment_no_state_update( + fn send_commitment_no_state_update( &self, logger: &L, - ) -> Result, ChannelError> - where - L::Target: Logger, - { + ) -> Result, ChannelError> { core::iter::once(&self.funding) .chain(self.pending_funding().iter()) .map(|funding| self.send_commitment_no_state_update_for_funding(funding, logger)) @@ -12993,12 +12676,9 @@ where } #[rustfmt::skip] - fn send_commitment_no_state_update_for_funding( + fn send_commitment_no_state_update_for_funding( &self, funding: &FundingScope, logger: &L, - ) -> Result - where - L::Target: Logger, - { + ) -> Result { // Get the fee tests from `build_commitment_no_state_update` #[cfg(any(test, fuzzing))] self.build_commitment_no_state_update(funding, logger); @@ -13061,16 +12741,12 @@ 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. - pub fn send_htlc_and_commit( + 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, hold_htlc: bool, accountable: bool, fee_estimator: &LowerBoundedFeeEstimator, logger: &L, - ) -> Result, ChannelError> - where - F::Target: FeeEstimator, - L::Target: Logger, - { + ) -> Result, ChannelError> { let send_res = self.send_htlc( amount_msat, payment_hash, @@ -13123,17 +12799,14 @@ where /// Begins the shutdown process, getting a message for the remote peer and returning all /// holding cell HTLCs for payment failure. - pub fn get_shutdown( + pub fn get_shutdown( &mut self, signer_provider: &SP, their_features: &InitFeatures, target_feerate_sats_per_kw: Option, override_shutdown_script: Option, logger: &L, ) -> Result< (msgs::Shutdown, Option, Vec<(HTLCSource, PaymentHash)>), APIError, - > - where - L::Target: Logger, - { + > { let logger = WithChannelContext::from(logger, &self.context, None); if self.context.channel_state.is_local_stfu_sent() @@ -13285,12 +12958,9 @@ where } #[rustfmt::skip] - pub fn propose_quiescence( + pub fn propose_quiescence( &mut self, logger: &L, action: QuiescentAction, - ) -> Result, &'static str> - where - L::Target: Logger, - { + ) -> Result, &'static str> { log_debug!(logger, "Attempting to initiate quiescence"); if !self.context.is_usable() { @@ -13326,10 +12996,7 @@ 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, - { + pub fn send_stfu(&mut self, logger: &L) -> Result { debug_assert!(!self.context.channel_state.is_local_stfu_sent()); debug_assert!( self.context.channel_state.is_awaiting_quiescence() @@ -13364,9 +13031,9 @@ where } #[rustfmt::skip] - pub fn stfu( + pub fn stfu( &mut self, msg: &msgs::Stfu, logger: &L - ) -> Result, ChannelError> where L::Target: Logger { + ) -> Result, ChannelError> { if self.context.channel_state.is_quiescent() { return Err(ChannelError::Warn("Channel is already quiescent".to_owned())); } @@ -13467,12 +13134,9 @@ where Ok(None) } - pub fn try_send_stfu( + pub fn try_send_stfu( &mut self, logger: &L, - ) -> Result, ChannelError> - where - L::Target: Logger, - { + ) -> Result, ChannelError> { // We must never see both stfu flags set, we always set the quiescent flag instead. debug_assert!( !(self.context.channel_state.is_local_stfu_sent() @@ -13543,10 +13207,7 @@ 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 { pub funding: FundingScope, pub context: ChannelContext, pub unfunded_context: UnfundedChannelContext, @@ -13556,25 +13217,18 @@ where pub signer_pending_open_channel: bool, } -impl OutboundV1Channel -where - SP::Target: SignerProvider, -{ +impl OutboundV1Channel { pub fn abandon_unfunded_chan(&mut self, closure_reason: ClosureReason) -> ShutdownResult { self.context.force_shutdown(&self.funding, closure_reason) } #[allow(dead_code)] // TODO(dual_funding): Remove once opending V2 channels is enabled. #[rustfmt::skip] - pub fn new( + 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, outbound_scid_alias: u64, temporary_channel_id: Option, logger: L - ) -> Result, APIError> - where ES::Target: EntropySource, - F::Target: FeeEstimator, - L::Target: Logger, - { + ) -> Result, APIError> { let holder_selected_channel_reserve_satoshis = get_holder_selected_channel_reserve_satoshis(channel_value_satoshis, config); if holder_selected_channel_reserve_satoshis < MIN_CHAN_DUST_LIMIT_SATOSHIS { // Protocol level safety check in place, although it should never happen because @@ -13621,7 +13275,7 @@ where /// 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 { + fn get_funding_created_msg(&mut self, logger: &L) -> Option { let commitment_data = self.context.build_commitment_transaction(&self.funding, self.context.counterparty_next_commitment_transaction_number, &self.context.counterparty_next_commitment_point.unwrap(), false, false, logger); @@ -13666,8 +13320,8 @@ where /// 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 { + pub fn get_funding_created(&mut self, funding_transaction: Transaction, funding_txo: OutPoint, is_batch_funding: bool, logger: &L) + -> Result, (Self, ChannelError)> { if !self.funding.is_outbound() { panic!("Tried to create outbound funding_created message on an inbound channel!"); } @@ -13706,14 +13360,10 @@ where /// 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( + pub(crate) fn maybe_handle_error_without_close( &mut self, chain_hash: ChainHash, fee_estimator: &LowerBoundedFeeEstimator, logger: &L, user_config: &UserConfig, their_features: &InitFeatures, - ) -> Result - where - F::Target: FeeEstimator, - L::Target: Logger, - { + ) -> Result { self.context.maybe_downgrade_channel_features( &mut self.funding, fee_estimator, user_config, their_features, )?; @@ -13727,9 +13377,9 @@ where } #[rustfmt::skip] - pub fn get_open_channel( + pub fn get_open_channel( &mut self, chain_hash: ChainHash, _logger: &L - ) -> Option where L::Target: Logger { + ) -> Option { if !self.funding.is_outbound() { panic!("Tried to open a channel for an inbound channel?"); } @@ -13799,16 +13449,13 @@ where /// Handles a funding_signed message from the remote end. /// If this call is successful, broadcast the funding transaction (and not before!) - pub fn funding_signed( + pub fn funding_signed( mut self, msg: &msgs::FundingSigned, best_block: BestBlock, signer_provider: &SP, logger: &L, ) -> Result< - (FundedChannel, ChannelMonitor<::EcdsaSigner>), + (FundedChannel, ChannelMonitor<::EcdsaSigner>), (OutboundV1Channel, ChannelError), - > - where - L::Target: Logger, - { + > { if !self.funding.is_outbound() { let err = "Received funding_signed for an inbound channel?"; return Err((self, ChannelError::close(err.to_owned()))); @@ -13872,9 +13519,9 @@ 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( + pub fn signer_maybe_unblocked( &mut self, chain_hash: ChainHash, logger: &L - ) -> (Option, Option) where L::Target: Logger { + ) -> (Option, Option) { // If we were pending a commitment point, retry the signer and advance to an // available state. if self.unfunded_context.holder_commitment_point.is_none() { @@ -13910,10 +13557,7 @@ where } /// A not-yet-funded inbound (from counterparty) channel using V1 channel establishment. -pub(super) struct InboundV1Channel -where - SP::Target: SignerProvider, -{ +pub(super) struct InboundV1Channel { pub funding: FundingScope, pub context: ChannelContext, pub unfunded_context: UnfundedChannelContext, @@ -13951,23 +13595,16 @@ pub(super) fn channel_type_from_open_channel( Ok(channel_type.clone()) } -impl InboundV1Channel -where - SP::Target: SignerProvider, -{ +impl InboundV1Channel { /// 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( + pub fn new( fee_estimator: &LowerBoundedFeeEstimator, entropy_source: &ES, signer_provider: &SP, counterparty_node_id: PublicKey, our_supported_features: &ChannelTypeFeatures, their_features: &InitFeatures, msg: &msgs::OpenChannel, user_id: u128, config: &UserConfig, current_chain_height: u32, logger: &L, is_0conf: bool, - ) -> Result, ChannelError> - where ES::Target: EntropySource, - F::Target: FeeEstimator, - L::Target: Logger, - { + ) -> Result, ChannelError> { let logger = WithContext::from(logger, Some(counterparty_node_id), Some(msg.common_fields.temporary_channel_id), None); // First check the channel type is known, failing before we do anything else if we don't @@ -14015,10 +13652,7 @@ where /// 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 { if self.funding.is_outbound() { panic!("Tried to send accept_channel for an outbound channel?"); } @@ -14041,9 +13675,9 @@ where /// /// [`msgs::AcceptChannel`]: crate::ln::msgs::AcceptChannel #[rustfmt::skip] - fn generate_accept_channel_message( + fn generate_accept_channel_message( &mut self, _logger: &L - ) -> Option where L::Target: Logger { + ) -> Option { let first_per_commitment_point = match self.unfunded_context.holder_commitment_point { Some(holder_commitment_point) if holder_commitment_point.can_advance() => { self.signer_pending_accept_channel = false; @@ -14089,29 +13723,23 @@ where /// /// [`msgs::AcceptChannel`]: crate::ln::msgs::AcceptChannel #[cfg(test)] - pub fn get_accept_channel_message( + pub fn get_accept_channel_message( &mut self, logger: &L, - ) -> Option - where - L::Target: Logger, - { + ) -> Option { self.generate_accept_channel_message(logger) } - pub fn funding_created( + pub fn funding_created( mut self, msg: &msgs::FundingCreated, best_block: BestBlock, signer_provider: &SP, logger: &L, ) -> Result< ( FundedChannel, Option, - ChannelMonitor<::EcdsaSigner>, + ChannelMonitor<::EcdsaSigner>, ), (Self, ChannelError), - > - where - L::Target: Logger, - { + > { if self.funding.is_outbound() { let err = "Received funding_created for an outbound channel?"; return Err((self, ChannelError::close(err.to_owned()))); @@ -14195,9 +13823,9 @@ 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( + pub fn signer_maybe_unblocked( &mut self, logger: &L - ) -> Option where L::Target: Logger { + ) -> Option { if self.unfunded_context.holder_commitment_point.is_none() { self.unfunded_context.holder_commitment_point = HolderCommitmentPoint::new(&self.context.holder_signer, &self.context.secp_ctx); } @@ -14214,10 +13842,7 @@ where } // A not-yet-funded channel using V2 channel establishment. -pub(super) struct PendingV2Channel -where - SP::Target: SignerProvider, -{ +pub(super) struct PendingV2Channel { pub funding: FundingScope, pub context: ChannelContext, pub unfunded_context: UnfundedChannelContext, @@ -14226,23 +13851,16 @@ where pub interactive_tx_constructor: Option, } -impl PendingV2Channel -where - SP::Target: SignerProvider, -{ +impl PendingV2Channel { #[allow(dead_code)] // TODO(dual_funding): Remove once creating V2 channels is enabled. #[rustfmt::skip] - pub fn new_outbound( + pub fn new_outbound( fee_estimator: &LowerBoundedFeeEstimator, entropy_source: &ES, signer_provider: &SP, counterparty_node_id: PublicKey, their_features: &InitFeatures, funding_satoshis: u64, funding_inputs: Vec, user_id: u128, config: &UserConfig, current_chain_height: u32, outbound_scid_alias: u64, funding_confirmation_target: ConfirmationTarget, logger: L, - ) -> Result - where ES::Target: EntropySource, - F::Target: FeeEstimator, - L::Target: Logger, - { + ) -> Result { let channel_keys_id = signer_provider.generate_channel_keys_id(false, user_id); let holder_signer = signer_provider.derive_channel_signer(channel_keys_id); @@ -14305,13 +13923,10 @@ where /// 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. - pub(crate) fn maybe_handle_error_without_close( + pub(crate) fn maybe_handle_error_without_close( &mut self, chain_hash: ChainHash, fee_estimator: &LowerBoundedFeeEstimator, user_config: &UserConfig, their_features: &InitFeatures, - ) -> Result - where - F::Target: FeeEstimator, - { + ) -> Result { self.context.maybe_downgrade_channel_features( &mut self.funding, fee_estimator, @@ -14381,16 +13996,12 @@ where /// 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( + 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, their_features: &InitFeatures, msg: &msgs::OpenChannelV2, user_id: u128, config: &UserConfig, current_chain_height: u32, logger: &L, - ) -> Result - where ES::Target: EntropySource, - F::Target: FeeEstimator, - L::Target: Logger, - { + ) -> Result { // TODO(dual_funding): Take these as input once supported let (our_funding_contribution, our_funding_contribution_sats) = (SignedAmount::ZERO, 0u64); let our_funding_inputs = Vec::new(); @@ -14647,10 +14258,7 @@ impl Readable for AnnouncementSigsState { } } -impl Writeable for FundedChannel -where - SP::Target: SignerProvider, -{ +impl Writeable for FundedChannel { 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. @@ -15135,11 +14743,8 @@ where } } -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: EntropySource, SP: SignerProvider> + ReadableArgs<(&'a ES, &'b SP, &'c ChannelTypeFeatures)> for FundedChannel { fn read( reader: &mut R, args: (&'a ES, &'b SP, &'c ChannelTypeFeatures), diff --git a/lightning/src/ln/channel_state.rs b/lightning/src/ln/channel_state.rs index d10327b259a..86e53ba3262 100644 --- a/lightning/src/ln/channel_state.rs +++ b/lightning/src/ln/channel_state.rs @@ -22,8 +22,6 @@ use crate::types::features::{ChannelTypeFeatures, InitFeatures}; use crate::types::payment::PaymentHash; use crate::util::config::ChannelConfig; -use core::ops::Deref; - /// Exposes the state of pending inbound HTLCs. /// /// At a high level, an HTLC being forwarded from one Lightning node to another Lightning node goes @@ -524,14 +522,10 @@ impl ChannelDetails { } } - pub(super) fn from_channel( + pub(super) fn from_channel( channel: &Channel, best_block_height: u32, latest_features: InitFeatures, fee_estimator: &LowerBoundedFeeEstimator, - ) -> Self - where - SP::Target: SignerProvider, - F::Target: FeeEstimator, - { + ) -> Self { let context = channel.context(); let funding = channel.funding(); let balance = channel.get_available_balances(fee_estimator); diff --git a/lightning/src/ln/channelmanager.rs b/lightning/src/ln/channelmanager.rs index 69a2d2f19a6..4f8b0760c64 100644 --- a/lightning/src/ln/channelmanager.rs +++ b/lightning/src/ln/channelmanager.rs @@ -1169,12 +1169,10 @@ impl ClaimablePayments { /// /// If no payment is found, `Err(Vec::new())` is returned. #[rustfmt::skip] - fn begin_claiming_payment( + fn begin_claiming_payment( &mut self, payment_hash: PaymentHash, node_signer: &S, logger: &L, inbound_payment_id_secret: &[u8; 32], custom_tlvs_known: bool, - ) -> Result<(Vec, ClaimingPayment), Vec> - where L::Target: Logger, S::Target: NodeSigner, - { + ) -> Result<(Vec, ClaimingPayment), Vec> { match self.claimable_payments.remove(&payment_hash) { Some(payment) => { let mut receiver_node_id = node_signer.get_node_id(Recipient::Node) @@ -1538,10 +1536,7 @@ impl Readable for Option { } /// State we hold per-peer. -pub(super) struct PeerState -where - SP::Target: SignerProvider, -{ +pub(super) struct PeerState { /// `channel_id` -> `Channel` /// /// Holds all channels where the peer is the counterparty. @@ -1616,10 +1611,7 @@ where peer_storage: Vec, } -impl PeerState -where - SP::Target: SignerProvider, -{ +impl PeerState { /// Indicates that a peer meets the criteria where we're ok to remove it from our storage. /// If true is passed for `require_disconnected`, the function will return false if we haven't /// disconnected from the node already, ie. `PeerState::is_connected` is set to `true`. @@ -1772,100 +1764,63 @@ pub type SimpleRefChannelManager<'a, 'b, 'c, 'd, 'e, 'f, 'g, 'h, 'i, M, T, F, L> /// languages. pub trait AChannelManager { /// A type implementing [`chain::Watch`]. - type Watch: chain::Watch + ?Sized; - /// A type that may be dereferenced to [`Self::Watch`]. - type M: Deref; + type Watch: chain::Watch; /// A type implementing [`BroadcasterInterface`]. - type Broadcaster: BroadcasterInterface + ?Sized; - /// A type that may be dereferenced to [`Self::Broadcaster`]. - type T: Deref; + type Broadcaster: BroadcasterInterface; /// A type implementing [`EntropySource`]. - type EntropySource: EntropySource + ?Sized; - /// A type that may be dereferenced to [`Self::EntropySource`]. - type ES: Deref; + type EntropySource: EntropySource; /// A type implementing [`NodeSigner`]. - type NodeSigner: NodeSigner + ?Sized; - /// A type that may be dereferenced to [`Self::NodeSigner`]. - type NS: Deref; + type NodeSigner: NodeSigner; /// A type implementing [`EcdsaChannelSigner`]. type Signer: EcdsaChannelSigner + Sized; /// A type implementing [`SignerProvider`] for [`Self::Signer`]. - type SignerProvider: SignerProvider + ?Sized; - /// A type that may be dereferenced to [`Self::SignerProvider`]. - type SP: Deref; + type SP: SignerProvider; /// A type implementing [`FeeEstimator`]. - type FeeEstimator: FeeEstimator + ?Sized; - /// A type that may be dereferenced to [`Self::FeeEstimator`]. - type F: Deref; + type FeeEstimator: FeeEstimator; /// A type implementing [`Router`]. - type Router: Router + ?Sized; - /// A type that may be dereferenced to [`Self::Router`]. - type R: Deref; + type Router: Router; /// A type implementing [`MessageRouter`]. - type MessageRouter: MessageRouter + ?Sized; - /// A type that may be dereferenced to [`Self::MessageRouter`]. - type MR: Deref; + type MessageRouter: MessageRouter; /// A type implementing [`Logger`]. - type Logger: Logger + ?Sized; - /// A type that may be dereferenced to [`Self::Logger`]. - type L: Deref; + type Logger: Logger; /// Returns a reference to the actual [`ChannelManager`] object. fn get_cm( &self, ) -> &ChannelManager< - Self::M, - Self::T, - Self::ES, - Self::NS, + Self::Watch, + Self::Broadcaster, + Self::EntropySource, + Self::NodeSigner, Self::SP, - Self::F, - Self::R, - Self::MR, - Self::L, + Self::FeeEstimator, + Self::Router, + Self::MessageRouter, + Self::Logger, >; } impl< - M: Deref, - T: Deref, - ES: Deref, - NS: Deref, - SP: Deref, - F: Deref, - R: Deref, - MR: Deref, - L: Deref, + M: chain::Watch<::EcdsaSigner>, + T: BroadcasterInterface, + ES: EntropySource, + NS: NodeSigner, + SP: SignerProvider, + F: FeeEstimator, + R: Router, + MR: MessageRouter, + L: Logger, > AChannelManager for ChannelManager -where - M::Target: chain::Watch<::EcdsaSigner>, - T::Target: BroadcasterInterface, - ES::Target: EntropySource, - NS::Target: NodeSigner, - SP::Target: SignerProvider, - F::Target: FeeEstimator, - R::Target: Router, - MR::Target: MessageRouter, - L::Target: Logger, { - type Watch = M::Target; - type M = M; - type Broadcaster = T::Target; - type T = T; - type EntropySource = ES::Target; - type ES = ES; - type NodeSigner = NS::Target; - type NS = NS; - type Signer = ::EcdsaSigner; - type SignerProvider = SP::Target; + type Watch = M; + type Broadcaster = T; + type EntropySource = ES; + type NodeSigner = NS; + type Signer = ::EcdsaSigner; type SP = SP; - type FeeEstimator = F::Target; - type F = F; - type Router = R::Target; - type R = R; - type MessageRouter = MR::Target; - type MR = MR; - type Logger = L::Target; - type L = L; + type FeeEstimator = F; + type Router = R; + type MessageRouter = MR; + type Logger = L; fn get_cm(&self) -> &ChannelManager { self } @@ -2651,26 +2606,16 @@ where // |__`pending_background_events` // pub struct ChannelManager< - M: Deref, - T: Deref, - ES: Deref, - NS: Deref, - SP: Deref, - F: Deref, - R: Deref, - MR: Deref, - L: Deref, -> where - M::Target: chain::Watch<::EcdsaSigner>, - T::Target: BroadcasterInterface, - ES::Target: EntropySource, - NS::Target: NodeSigner, - SP::Target: SignerProvider, - F::Target: FeeEstimator, - R::Target: Router, - MR::Target: MessageRouter, - L::Target: Logger, -{ + M: chain::Watch<::EcdsaSigner>, + T: BroadcasterInterface, + ES: EntropySource, + NS: NodeSigner, + SP: SignerProvider, + F: FeeEstimator, + R: Router, + MR: MessageRouter, + L: Logger, +> { config: RwLock, chain_hash: ChainHash, fee_estimator: LowerBoundedFeeEstimator, @@ -3727,26 +3672,16 @@ fn create_htlc_intercepted_event( } impl< - M: Deref, - T: Deref, - ES: Deref, - NS: Deref, - SP: Deref, - F: Deref, - R: Deref, - MR: Deref, - L: Deref, + M: chain::Watch<::EcdsaSigner>, + T: BroadcasterInterface, + ES: EntropySource, + NS: NodeSigner, + SP: SignerProvider, + F: FeeEstimator, + R: Router, + MR: MessageRouter, + L: Logger, > ChannelManager -where - M::Target: chain::Watch<::EcdsaSigner>, - T::Target: BroadcasterInterface, - ES::Target: EntropySource, - NS::Target: NodeSigner, - SP::Target: SignerProvider, - F::Target: FeeEstimator, - R::Target: Router, - MR::Target: MessageRouter, - L::Target: Logger, { /// Constructs a new `ChannelManager` to hold several channels and route between them. /// @@ -3984,7 +3919,7 @@ where }; match OutboundV1Channel::new(&self.fee_estimator, &self.entropy_source, &self.signer_provider, their_network_key, their_features, channel_value_satoshis, push_msat, user_channel_id, config, - self.best_block.read().unwrap().height, outbound_scid_alias, temporary_channel_id, &*self.logger) + self.best_block.read().unwrap().height, outbound_scid_alias, temporary_channel_id, &self.logger) { Ok(res) => res, Err(e) => { @@ -4757,10 +4692,7 @@ where /// The same closure semantics as described in [`ChannelManager::locked_handle_force_close`] apply. fn locked_handle_unfunded_close( &self, err: ChannelError, chan: &mut Channel, - ) -> (bool, MsgHandleErrInternal) - where - SP::Target: SignerProvider, - { + ) -> (bool, MsgHandleErrInternal) { let chan_id = chan.context().channel_id(); convert_channel_err_internal(err, chan_id, |reason, msg| { let logger = WithChannelContext::from(&self.logger, chan.context(), None); @@ -5778,7 +5710,7 @@ where fn check_refresh_async_receive_offer_cache(&self, timer_tick_occurred: bool) { let peers = self.get_peers_for_blinded_path(); let channels = self.list_usable_channels(); - let router = &*self.router; + let router = &self.router; let refresh_res = self.flow.check_refresh_async_receive_offer_cache( peers, channels, @@ -5836,7 +5768,7 @@ where features, best_block_height, self.duration_since_epoch(), - &*self.entropy_source, + &self.entropy_source, &self.pending_events, ); match outbound_pmts_res { @@ -5969,7 +5901,7 @@ where intercept_id, prev_outbound_scid_alias, htlc_id, - &*self.entropy_source, + &self.entropy_source, ) } @@ -7087,8 +7019,8 @@ where let (next_hop, next_packet_details_opt) = match decode_incoming_update_add_htlc_onion( &update_add_htlc, - &*self.node_signer, - &*self.logger, + &self.node_signer, + &self.logger, &self.secp_ctx, ) { Ok(decoded_onion) => decoded_onion, @@ -7437,7 +7369,7 @@ where onion_packet.hmac, payment_hash, None, - &*self.node_signer, + &self.node_signer, ); let next_hop = match decode_res { Ok(res) => res, @@ -13060,7 +12992,7 @@ macro_rules! create_offer_builder { ($self: ident, $builder: ty) => { /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest pub fn create_offer_builder(&$self) -> Result<$builder, Bolt12SemanticError> { let builder = $self.flow.create_offer_builder( - &*$self.entropy_source, $self.get_peers_for_blinded_path() + &$self.entropy_source, $self.get_peers_for_blinded_path() )?; Ok(builder.into()) @@ -13077,15 +13009,12 @@ macro_rules! create_offer_builder { ($self: ident, $builder: ty) => { /// [`BlindedMessagePath`]: crate::blinded_path::message::BlindedMessagePath /// [`Offer`]: crate::offers::offer::Offer /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest - pub fn create_offer_builder_using_router( + pub fn create_offer_builder_using_router( &$self, router: ME, - ) -> Result<$builder, Bolt12SemanticError> - where - ME::Target: MessageRouter, - { + ) -> Result<$builder, Bolt12SemanticError> { let builder = $self.flow.create_offer_builder_using_router( - router, &*$self.entropy_source, $self.get_peers_for_blinded_path() + router, &$self.entropy_source, $self.get_peers_for_blinded_path() )?; Ok(builder.into()) @@ -13137,7 +13066,7 @@ macro_rules! create_refund_builder { ($self: ident, $builder: ty) => { &$self, amount_msats: u64, absolute_expiry: Duration, payment_id: PaymentId, retry_strategy: Retry, route_params_config: RouteParametersConfig ) -> Result<$builder, Bolt12SemanticError> { - let entropy = &*$self.entropy_source; + let entropy = &$self.entropy_source; let builder = $self.flow.create_refund_builder( entropy, amount_msats, absolute_expiry, @@ -13174,14 +13103,11 @@ macro_rules! create_refund_builder { ($self: ident, $builder: ty) => { /// [`Refund`]: crate::offers::refund::Refund /// [`BlindedMessagePath`]: crate::blinded_path::message::BlindedMessagePath /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice - pub fn create_refund_builder_using_router( + pub fn create_refund_builder_using_router( &$self, router: ME, amount_msats: u64, absolute_expiry: Duration, payment_id: PaymentId, retry_strategy: Retry, route_params_config: RouteParametersConfig - ) -> Result<$builder, Bolt12SemanticError> - where - ME::Target: MessageRouter, - { - let entropy = &*$self.entropy_source; + ) -> Result<$builder, Bolt12SemanticError> { + let entropy = &$self.entropy_source; let builder = $self.flow.create_refund_builder_using_router( router, entropy, amount_msats, absolute_expiry, @@ -13202,26 +13128,16 @@ macro_rules! create_refund_builder { ($self: ident, $builder: ty) => { } } impl< - M: Deref, - T: Deref, - ES: Deref, - NS: Deref, - SP: Deref, - F: Deref, - R: Deref, - MR: Deref, - L: Deref, + M: chain::Watch<::EcdsaSigner>, + T: BroadcasterInterface, + ES: EntropySource, + NS: NodeSigner, + SP: SignerProvider, + F: FeeEstimator, + R: Router, + MR: MessageRouter, + L: Logger, > ChannelManager -where - M::Target: chain::Watch<::EcdsaSigner>, - T::Target: BroadcasterInterface, - ES::Target: EntropySource, - NS::Target: NodeSigner, - SP::Target: SignerProvider, - F::Target: FeeEstimator, - R::Target: Router, - MR::Target: MessageRouter, - L::Target: Logger, { #[cfg(not(c_bindings))] create_offer_builder!(self, OfferBuilder<'_, DerivedMetadata, secp256k1::All>); @@ -13411,7 +13327,7 @@ where payer_note: Option, payment_id: PaymentId, human_readable_name: Option, create_pending_payment: CPP, ) -> Result<(), Bolt12SemanticError> { - let entropy = &*self.entropy_source; + let entropy = &self.entropy_source; let nonce = Nonce::from_entropy_source(entropy); let builder = self.flow.create_invoice_request_builder( @@ -13479,7 +13395,7 @@ where &self, refund: &Refund, ) -> Result { let secp_ctx = &self.secp_ctx; - let entropy = &*self.entropy_source; + let entropy = &self.entropy_source; let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self); @@ -13544,7 +13460,7 @@ where optional_params: OptionalOfferPaymentParams, dns_resolvers: Vec, ) -> Result<(), ()> { let (onion_message, context) = - self.flow.hrn_resolver.resolve_name(payment_id, name, &*self.entropy_source)?; + self.flow.hrn_resolver.resolve_name(payment_id, name, &self.entropy_source)?; let expiration = StaleExpiration::TimerTicks(1); self.pending_outbound_payments.add_new_awaiting_offer( @@ -14054,26 +13970,16 @@ where } impl< - M: Deref, - T: Deref, - ES: Deref, - NS: Deref, - SP: Deref, - F: Deref, - R: Deref, - MR: Deref, - L: Deref, + M: chain::Watch<::EcdsaSigner>, + T: BroadcasterInterface, + ES: EntropySource, + NS: NodeSigner, + SP: SignerProvider, + F: FeeEstimator, + R: Router, + MR: MessageRouter, + L: Logger, > BaseMessageHandler for ChannelManager -where - M::Target: chain::Watch<::EcdsaSigner>, - T::Target: BroadcasterInterface, - ES::Target: EntropySource, - NS::Target: NodeSigner, - SP::Target: SignerProvider, - F::Target: FeeEstimator, - R::Target: Router, - MR::Target: MessageRouter, - L::Target: Logger, { fn provided_node_features(&self) -> NodeFeatures { provided_node_features(&self.config.read().unwrap()) @@ -14412,26 +14318,16 @@ where } impl< - M: Deref, - T: Deref, - ES: Deref, - NS: Deref, - SP: Deref, - F: Deref, - R: Deref, - MR: Deref, - L: Deref, + M: chain::Watch<::EcdsaSigner>, + T: BroadcasterInterface, + ES: EntropySource, + NS: NodeSigner, + SP: SignerProvider, + F: FeeEstimator, + R: Router, + MR: MessageRouter, + L: Logger, > EventsProvider for ChannelManager -where - M::Target: chain::Watch<::EcdsaSigner>, - T::Target: BroadcasterInterface, - ES::Target: EntropySource, - NS::Target: NodeSigner, - SP::Target: SignerProvider, - F::Target: FeeEstimator, - R::Target: Router, - MR::Target: MessageRouter, - L::Target: Logger, { /// Processes events that must be periodically handled. /// @@ -14447,26 +14343,16 @@ where } impl< - M: Deref, - T: Deref, - ES: Deref, - NS: Deref, - SP: Deref, - F: Deref, - R: Deref, - MR: Deref, - L: Deref, + M: chain::Watch<::EcdsaSigner>, + T: BroadcasterInterface, + ES: EntropySource, + NS: NodeSigner, + SP: SignerProvider, + F: FeeEstimator, + R: Router, + MR: MessageRouter, + L: Logger, > chain::Listen for ChannelManager -where - M::Target: chain::Watch<::EcdsaSigner>, - T::Target: BroadcasterInterface, - ES::Target: EntropySource, - NS::Target: NodeSigner, - SP::Target: SignerProvider, - F::Target: FeeEstimator, - R::Target: Router, - MR::Target: MessageRouter, - L::Target: Logger, { fn filtered_block_connected(&self, header: &Header, txdata: &TransactionData, height: u32) { { @@ -14508,26 +14394,16 @@ where } impl< - M: Deref, - T: Deref, - ES: Deref, - NS: Deref, - SP: Deref, - F: Deref, - R: Deref, - MR: Deref, - L: Deref, + M: chain::Watch<::EcdsaSigner>, + T: BroadcasterInterface, + ES: EntropySource, + NS: NodeSigner, + SP: SignerProvider, + F: FeeEstimator, + R: Router, + MR: MessageRouter, + L: Logger, > chain::Confirm for ChannelManager -where - M::Target: chain::Watch<::EcdsaSigner>, - T::Target: BroadcasterInterface, - ES::Target: EntropySource, - NS::Target: NodeSigner, - SP::Target: SignerProvider, - F::Target: FeeEstimator, - R::Target: Router, - MR::Target: MessageRouter, - L::Target: Logger, { #[rustfmt::skip] fn transactions_confirmed(&self, header: &Header, txdata: &TransactionData, height: u32) { @@ -14681,26 +14557,16 @@ pub(super) enum FundingConfirmedMessage { } impl< - M: Deref, - T: Deref, - ES: Deref, - NS: Deref, - SP: Deref, - F: Deref, - R: Deref, - MR: Deref, - L: Deref, + M: chain::Watch<::EcdsaSigner>, + T: BroadcasterInterface, + ES: EntropySource, + NS: NodeSigner, + SP: SignerProvider, + F: FeeEstimator, + R: Router, + MR: MessageRouter, + L: Logger, > ChannelManager -where - M::Target: chain::Watch<::EcdsaSigner>, - T::Target: BroadcasterInterface, - ES::Target: EntropySource, - NS::Target: NodeSigner, - SP::Target: SignerProvider, - F::Target: FeeEstimator, - R::Target: Router, - MR::Target: MessageRouter, - L::Target: Logger, { /// Calls a function which handles an on-chain event (blocks dis/connected, transactions /// un/confirmed, etc) on each channel, handling any resulting errors or messages generated by @@ -15043,26 +14909,16 @@ where } impl< - M: Deref, - T: Deref, - ES: Deref, - NS: Deref, - SP: Deref, - F: Deref, - R: Deref, - MR: Deref, - L: Deref, + M: chain::Watch<::EcdsaSigner>, + T: BroadcasterInterface, + ES: EntropySource, + NS: NodeSigner, + SP: SignerProvider, + F: FeeEstimator, + R: Router, + MR: MessageRouter, + L: Logger, > ChannelMessageHandler for ChannelManager -where - M::Target: chain::Watch<::EcdsaSigner>, - T::Target: BroadcasterInterface, - ES::Target: EntropySource, - NS::Target: NodeSigner, - SP::Target: SignerProvider, - F::Target: FeeEstimator, - R::Target: Router, - MR::Target: MessageRouter, - L::Target: Logger, { fn handle_open_channel(&self, counterparty_node_id: PublicKey, message: &msgs::OpenChannel) { // Note that we never need to persist the updated ChannelManager for an inbound @@ -15618,26 +15474,16 @@ where } impl< - M: Deref, - T: Deref, - ES: Deref, - NS: Deref, - SP: Deref, - F: Deref, - R: Deref, - MR: Deref, - L: Deref, + M: chain::Watch<::EcdsaSigner>, + T: BroadcasterInterface, + ES: EntropySource, + NS: NodeSigner, + SP: SignerProvider, + F: FeeEstimator, + R: Router, + MR: MessageRouter, + L: Logger, > OffersMessageHandler for ChannelManager -where - M::Target: chain::Watch<::EcdsaSigner>, - T::Target: BroadcasterInterface, - ES::Target: EntropySource, - NS::Target: NodeSigner, - SP::Target: SignerProvider, - F::Target: FeeEstimator, - R::Target: Router, - MR::Target: MessageRouter, - L::Target: Logger, { #[rustfmt::skip] fn handle_message( @@ -15836,26 +15682,16 @@ where } impl< - M: Deref, - T: Deref, - ES: Deref, - NS: Deref, - SP: Deref, - F: Deref, - R: Deref, - MR: Deref, - L: Deref, + M: chain::Watch<::EcdsaSigner>, + T: BroadcasterInterface, + ES: EntropySource, + NS: NodeSigner, + SP: SignerProvider, + F: FeeEstimator, + R: Router, + MR: MessageRouter, + L: Logger, > AsyncPaymentsMessageHandler for ChannelManager -where - M::Target: chain::Watch<::EcdsaSigner>, - T::Target: BroadcasterInterface, - ES::Target: EntropySource, - NS::Target: NodeSigner, - SP::Target: SignerProvider, - F::Target: FeeEstimator, - R::Target: Router, - MR::Target: MessageRouter, - L::Target: Logger, { fn handle_offer_paths_request( &self, message: OfferPathsRequest, context: AsyncPaymentsContext, @@ -15883,8 +15719,8 @@ where responder.clone(), self.get_peers_for_blinded_path(), self.list_usable_channels(), - &*self.entropy_source, - &*self.router, + &self.entropy_source, + &self.router, ) { Some((msg, ctx)) => (msg, ctx), None => return None, @@ -16038,26 +15874,16 @@ where #[cfg(feature = "dnssec")] impl< - M: Deref, - T: Deref, - ES: Deref, - NS: Deref, - SP: Deref, - F: Deref, - R: Deref, - MR: Deref, - L: Deref, + M: chain::Watch<::EcdsaSigner>, + T: BroadcasterInterface, + ES: EntropySource, + NS: NodeSigner, + SP: SignerProvider, + F: FeeEstimator, + R: Router, + MR: MessageRouter, + L: Logger, > DNSResolverMessageHandler for ChannelManager -where - M::Target: chain::Watch<::EcdsaSigner>, - T::Target: BroadcasterInterface, - ES::Target: EntropySource, - NS::Target: NodeSigner, - SP::Target: SignerProvider, - F::Target: FeeEstimator, - R::Target: Router, - MR::Target: MessageRouter, - L::Target: Logger, { fn handle_dnssec_query( &self, _message: DNSSECQuery, _responder: Option, @@ -16106,26 +15932,16 @@ where } impl< - M: Deref, - T: Deref, - ES: Deref, - NS: Deref, - SP: Deref, - F: Deref, - R: Deref, - MR: Deref, - L: Deref, + M: chain::Watch<::EcdsaSigner>, + T: BroadcasterInterface, + ES: EntropySource, + NS: NodeSigner, + SP: SignerProvider, + F: FeeEstimator, + R: Router, + MR: MessageRouter, + L: Logger, > NodeIdLookUp for ChannelManager -where - M::Target: chain::Watch<::EcdsaSigner>, - T::Target: BroadcasterInterface, - ES::Target: EntropySource, - NS::Target: NodeSigner, - SP::Target: SignerProvider, - F::Target: FeeEstimator, - R::Target: Router, - MR::Target: MessageRouter, - L::Target: Logger, { fn next_node_id(&self, short_channel_id: u64) -> Option { self.short_to_chan_info.read().unwrap().get(&short_channel_id).map(|(pubkey, _)| *pubkey) @@ -16622,26 +16438,16 @@ impl_writeable_tlv_based!(PendingInboundPayment, { }); impl< - M: Deref, - T: Deref, - ES: Deref, - NS: Deref, - SP: Deref, - F: Deref, - R: Deref, - MR: Deref, - L: Deref, + M: chain::Watch<::EcdsaSigner>, + T: BroadcasterInterface, + ES: EntropySource, + NS: NodeSigner, + SP: SignerProvider, + F: FeeEstimator, + R: Router, + MR: MessageRouter, + L: Logger, > Writeable for ChannelManager -where - M::Target: chain::Watch<::EcdsaSigner>, - T::Target: BroadcasterInterface, - ES::Target: EntropySource, - NS::Target: NodeSigner, - SP::Target: SignerProvider, - F::Target: FeeEstimator, - R::Target: Router, - MR::Target: MessageRouter, - L::Target: Logger, { #[rustfmt::skip] fn write(&self, writer: &mut W) -> Result<(), io::Error> { @@ -16989,26 +16795,16 @@ impl Readable for VecDeque<(Event, Option)> { /// [`ChainMonitor::load_existing_monitor`]: crate::chain::chainmonitor::ChainMonitor::load_existing_monitor pub struct ChannelManagerReadArgs< 'a, - M: Deref, - T: Deref, - ES: Deref, - NS: Deref, - SP: Deref, - F: Deref, - R: Deref, - MR: Deref, - L: Deref + Clone, -> where - M::Target: chain::Watch<::EcdsaSigner>, - T::Target: BroadcasterInterface, - ES::Target: EntropySource, - NS::Target: NodeSigner, - SP::Target: SignerProvider, - F::Target: FeeEstimator, - R::Target: Router, - MR::Target: MessageRouter, - L::Target: Logger, -{ + M: chain::Watch<::EcdsaSigner>, + T: BroadcasterInterface, + ES: EntropySource, + NS: NodeSigner, + SP: SignerProvider, + F: FeeEstimator, + R: Router, + MR: MessageRouter, + L: Logger + Clone, +> { /// A cryptographically secure source of entropy. pub entropy_source: ES, @@ -17064,31 +16860,21 @@ pub struct ChannelManagerReadArgs< /// /// This is not exported to bindings users because we have no HashMap bindings pub channel_monitors: - HashMap::EcdsaSigner>>, + HashMap::EcdsaSigner>>, } impl< 'a, - M: Deref, - T: Deref, - ES: Deref, - NS: Deref, - SP: Deref, - F: Deref, - R: Deref, - MR: Deref, - L: Deref + Clone, + M: chain::Watch<::EcdsaSigner>, + T: BroadcasterInterface, + ES: EntropySource, + NS: NodeSigner, + SP: SignerProvider, + F: FeeEstimator, + R: Router, + MR: MessageRouter, + L: Logger + Clone, > ChannelManagerReadArgs<'a, M, T, ES, NS, SP, F, R, MR, L> -where - M::Target: chain::Watch<::EcdsaSigner>, - T::Target: BroadcasterInterface, - ES::Target: EntropySource, - NS::Target: NodeSigner, - SP::Target: SignerProvider, - F::Target: FeeEstimator, - R::Target: Router, - MR::Target: MessageRouter, - L::Target: Logger, { /// Simple utility function to create a ChannelManagerReadArgs which creates the monitor /// HashMap for you. This is primarily useful for C bindings where it is not practical to @@ -17097,7 +16883,7 @@ where entropy_source: ES, node_signer: NS, signer_provider: SP, fee_estimator: F, chain_monitor: M, tx_broadcaster: T, router: R, message_router: MR, logger: L, config: UserConfig, - mut channel_monitors: Vec<&'a ChannelMonitor<::EcdsaSigner>>, + mut channel_monitors: Vec<&'a ChannelMonitor<::EcdsaSigner>>, ) -> Self { Self { entropy_source, @@ -17119,12 +16905,10 @@ where // If the HTLC corresponding to `prev_hop_data` is present in `decode_update_add_htlcs`, remove it // from the map as it is already being stored and processed elsewhere. -fn dedup_decode_update_add_htlcs( +fn dedup_decode_update_add_htlcs( decode_update_add_htlcs: &mut HashMap>, prev_hop_data: &HTLCPreviousHopData, removal_reason: &'static str, logger: &L, -) where - L::Target: Logger, -{ +) { match decode_update_add_htlcs.entry(prev_hop_data.prev_outbound_scid_alias) { hash_map::Entry::Occupied(mut update_add_htlcs) => { update_add_htlcs.get_mut().retain(|update_add| { @@ -17157,27 +16941,17 @@ fn dedup_decode_update_add_htlcs( // SipmleArcChannelManager type: impl< 'a, - M: Deref, - T: Deref, - ES: Deref, - NS: Deref, - SP: Deref, - F: Deref, - R: Deref, - MR: Deref, - L: Deref + Clone, + M: chain::Watch<::EcdsaSigner>, + T: BroadcasterInterface, + ES: EntropySource, + NS: NodeSigner, + SP: SignerProvider, + F: FeeEstimator, + R: Router, + MR: MessageRouter, + L: Logger + Clone, > ReadableArgs> for (BlockHash, Arc>) -where - M::Target: chain::Watch<::EcdsaSigner>, - T::Target: BroadcasterInterface, - ES::Target: EntropySource, - NS::Target: NodeSigner, - SP::Target: SignerProvider, - F::Target: FeeEstimator, - R::Target: Router, - MR::Target: MessageRouter, - L::Target: Logger, { fn read( reader: &mut Reader, args: ChannelManagerReadArgs<'a, M, T, ES, NS, SP, F, R, MR, L>, @@ -17190,27 +16964,17 @@ where impl< 'a, - M: Deref, - T: Deref, - ES: Deref, - NS: Deref, - SP: Deref, - F: Deref, - R: Deref, - MR: Deref, - L: Deref + Clone, + M: chain::Watch<::EcdsaSigner>, + T: BroadcasterInterface, + ES: EntropySource, + NS: NodeSigner, + SP: SignerProvider, + F: FeeEstimator, + R: Router, + MR: MessageRouter, + L: Logger + Clone, > ReadableArgs> for (BlockHash, ChannelManager) -where - M::Target: chain::Watch<::EcdsaSigner>, - T::Target: BroadcasterInterface, - ES::Target: EntropySource, - NS::Target: NodeSigner, - SP::Target: SignerProvider, - F::Target: FeeEstimator, - R::Target: Router, - MR::Target: MessageRouter, - L::Target: Logger, { fn read( reader: &mut Reader, mut args: ChannelManagerReadArgs<'a, M, T, ES, NS, SP, F, R, MR, L>, diff --git a/lightning/src/ln/functional_test_utils.rs b/lightning/src/ln/functional_test_utils.rs index 00fbca201cd..89ab92d74dc 100644 --- a/lightning/src/ln/functional_test_utils.rs +++ b/lightning/src/ln/functional_test_utils.rs @@ -731,15 +731,15 @@ pub trait NodeHolder { fn node( &self, ) -> &ChannelManager< - ::M, - ::T, - ::ES, - ::NS, + ::Watch, + ::Broadcaster, + ::EntropySource, + ::NodeSigner, ::SP, - ::F, - ::R, - ::MR, - ::L, + ::FeeEstimator, + ::Router, + ::MessageRouter, + ::Logger, >; fn chain_monitor(&self) -> Option<&test_utils::TestChainMonitor<'_>>; } @@ -748,15 +748,15 @@ impl NodeHolder for &H { fn node( &self, ) -> &ChannelManager< - ::M, - ::T, - ::ES, - ::NS, + ::Watch, + ::Broadcaster, + ::EntropySource, + ::NodeSigner, ::SP, - ::F, - ::R, - ::MR, - ::L, + ::FeeEstimator, + ::Router, + ::MessageRouter, + ::Logger, > { (*self).node() } diff --git a/lightning/src/ln/inbound_payment.rs b/lightning/src/ln/inbound_payment.rs index 17c2526e78d..51f8b7bfce9 100644 --- a/lightning/src/ln/inbound_payment.rs +++ b/lightning/src/ln/inbound_payment.rs @@ -27,8 +27,6 @@ use crate::util::logger::Logger; #[allow(unused_imports)] use crate::prelude::*; -use core::ops::Deref; - pub(crate) const IV_LEN: usize = 16; const METADATA_LEN: usize = 16; const METADATA_KEY_LEN: usize = 32; @@ -143,13 +141,10 @@ fn min_final_cltv_expiry_delta_from_metadata(bytes: [u8; METADATA_LEN]) -> u16 { /// /// [phantom node payments]: crate::sign::PhantomKeysManager /// [`NodeSigner::get_expanded_key`]: crate::sign::NodeSigner::get_expanded_key -pub fn create( +pub fn create( keys: &ExpandedKey, min_value_msat: Option, invoice_expiry_delta_secs: u32, entropy_source: &ES, current_time: u64, min_final_cltv_expiry_delta: Option, -) -> Result<(PaymentHash, PaymentSecret), ()> -where - ES::Target: EntropySource, -{ +) -> Result<(PaymentHash, PaymentSecret), ()> { let metadata_bytes = construct_metadata_bytes( min_value_msat, if min_final_cltv_expiry_delta.is_some() { @@ -345,13 +340,10 @@ fn construct_payment_secret( /// [`NodeSigner::get_expanded_key`]: crate::sign::NodeSigner::get_expanded_key /// [`create_inbound_payment`]: crate::ln::channelmanager::ChannelManager::create_inbound_payment /// [`create_inbound_payment_for_hash`]: crate::ln::channelmanager::ChannelManager::create_inbound_payment_for_hash -pub(super) fn verify( +pub(super) fn verify( payment_hash: PaymentHash, payment_data: &msgs::FinalOnionHopData, highest_seen_timestamp: u64, keys: &ExpandedKey, logger: &L, -) -> Result<(Option, Option), ()> -where - L::Target: Logger, -{ +) -> Result<(Option, Option), ()> { let (iv_bytes, metadata_bytes) = decrypt_metadata(payment_data.payment_secret, keys); let payment_type_res = diff --git a/lightning/src/ln/interactivetxs.rs b/lightning/src/ln/interactivetxs.rs index 4340aad420a..712a73d0700 100644 --- a/lightning/src/ln/interactivetxs.rs +++ b/lightning/src/ln/interactivetxs.rs @@ -39,7 +39,6 @@ use crate::ln::types::ChannelId; use crate::sign::{EntropySource, P2TR_KEY_PATH_WITNESS_WEIGHT, P2WPKH_WITNESS_WEIGHT}; use core::fmt::Display; -use core::ops::Deref; /// The number of received `tx_add_input` messages during a negotiation at which point the /// negotiation MUST be failed. @@ -1990,10 +1989,9 @@ macro_rules! do_state_transition { }}; } -fn generate_holder_serial_id(entropy_source: &ES, is_initiator: bool) -> SerialId -where - ES::Target: EntropySource, -{ +fn generate_holder_serial_id( + entropy_source: &ES, is_initiator: bool, +) -> SerialId { let rand_bytes = entropy_source.get_secure_random_bytes(); let mut serial_id_bytes = [0u8; 8]; serial_id_bytes.copy_from_slice(&rand_bytes[..8]); @@ -2009,10 +2007,7 @@ pub(super) enum HandleTxCompleteValue { NegotiationComplete(Option, OutPoint), } -pub(super) struct InteractiveTxConstructorArgs<'a, ES: Deref> -where - ES::Target: EntropySource, -{ +pub(super) struct InteractiveTxConstructorArgs<'a, ES: EntropySource> { pub entropy_source: &'a ES, pub holder_node_id: PublicKey, pub counterparty_node_id: PublicKey, @@ -2031,10 +2026,9 @@ impl InteractiveTxConstructor { /// /// If the holder is the initiator, they need to send the first message which is a `TxAddInput` /// message. - pub fn new(args: InteractiveTxConstructorArgs) -> Result - where - ES::Target: EntropySource, - { + pub fn new( + args: InteractiveTxConstructorArgs, + ) -> Result { let InteractiveTxConstructorArgs { entropy_source, holder_node_id, @@ -2420,7 +2414,6 @@ mod tests { OutPoint, PubkeyHash, ScriptBuf, Sequence, SignedAmount, Transaction, TxIn, TxOut, WPubkeyHash, }; - use core::ops::Deref; use super::{ get_output_weight, ConstructedTransaction, InteractiveTxSigningSession, TxInMetadata, @@ -2490,19 +2483,15 @@ mod tests { do_test_interactive_tx_constructor_internal(session, &&entropy_source); } - fn do_test_interactive_tx_constructor_with_entropy_source( + fn do_test_interactive_tx_constructor_with_entropy_source( session: TestSession, entropy_source: ES, - ) where - ES::Target: EntropySource, - { + ) { do_test_interactive_tx_constructor_internal(session, &entropy_source); } - fn do_test_interactive_tx_constructor_internal( + fn do_test_interactive_tx_constructor_internal( session: TestSession, entropy_source: &ES, - ) where - ES::Target: EntropySource, - { + ) { let channel_id = ChannelId(entropy_source.get_secure_random_bytes()); let funding_tx_locktime = AbsoluteLockTime::from_height(1337).unwrap(); let holder_node_id = PublicKey::from_secret_key( diff --git a/lightning/src/ln/invoice_utils.rs b/lightning/src/ln/invoice_utils.rs index 425cc4d7eb6..ff22d77273c 100644 --- a/lightning/src/ln/invoice_utils.rs +++ b/lightning/src/ln/invoice_utils.rs @@ -22,7 +22,6 @@ use bitcoin::hashes::Hash; use bitcoin::secp256k1::PublicKey; #[cfg(not(feature = "std"))] use core::iter::Iterator; -use core::ops::Deref; use core::time::Duration; /// Utility to create an invoice that can be paid to one of multiple nodes, or a "phantom invoice." @@ -67,17 +66,12 @@ use core::time::Duration; feature = "std", doc = "This can be used in a `no_std` environment, where [`std::time::SystemTime`] is not available and the current time is supplied by the caller." )] -pub fn create_phantom_invoice( +pub fn create_phantom_invoice( amt_msat: Option, payment_hash: Option, description: String, invoice_expiry_delta_secs: u32, phantom_route_hints: Vec, entropy_source: ES, node_signer: NS, logger: L, network: Currency, min_final_cltv_expiry_delta: Option, duration_since_epoch: Duration, -) -> Result> -where - ES::Target: EntropySource, - NS::Target: NodeSigner, - L::Target: Logger, -{ +) -> Result> { let description = Description::new(description).map_err(SignOrCreationError::CreationError)?; let description = Bolt11InvoiceDescription::Direct(description); _create_phantom_invoice::( @@ -135,17 +129,16 @@ where feature = "std", doc = "This version can be used in a `no_std` environment, where [`std::time::SystemTime`] is not available and the current time is supplied by the caller." )] -pub fn create_phantom_invoice_with_description_hash( +pub fn create_phantom_invoice_with_description_hash< + ES: EntropySource, + NS: NodeSigner, + L: Logger, +>( amt_msat: Option, payment_hash: Option, invoice_expiry_delta_secs: u32, description_hash: Sha256, phantom_route_hints: Vec, entropy_source: ES, node_signer: NS, logger: L, network: Currency, min_final_cltv_expiry_delta: Option, duration_since_epoch: Duration, -) -> Result> -where - ES::Target: EntropySource, - NS::Target: NodeSigner, - L::Target: Logger, -{ +) -> Result> { _create_phantom_invoice::( amt_msat, payment_hash, @@ -163,17 +156,12 @@ where const MAX_CHANNEL_HINTS: usize = 3; -fn _create_phantom_invoice( +fn _create_phantom_invoice( amt_msat: Option, payment_hash: Option, description: Bolt11InvoiceDescription, invoice_expiry_delta_secs: u32, phantom_route_hints: Vec, entropy_source: ES, node_signer: NS, logger: L, network: Currency, min_final_cltv_expiry_delta: Option, duration_since_epoch: Duration, -) -> Result> -where - ES::Target: EntropySource, - NS::Target: NodeSigner, - L::Target: Logger, -{ +) -> Result> { if phantom_route_hints.is_empty() { return Err(SignOrCreationError::CreationError(CreationError::MissingRouteHints)); } @@ -268,12 +256,9 @@ where /// * Select one hint from each node, up to three hints or until we run out of hints. /// /// [`PhantomKeysManager`]: crate::sign::PhantomKeysManager -fn select_phantom_hints( +fn select_phantom_hints( amt_msat: Option, phantom_route_hints: Vec, logger: L, -) -> impl Iterator -where - L::Target: Logger, -{ +) -> impl Iterator { let mut phantom_hints: Vec<_> = Vec::new(); for PhantomRouteHints { channels, phantom_scid, real_node_pubkey } in phantom_route_hints { @@ -369,12 +354,9 @@ fn rotate_through_iterators>(mut vecs: Vec) -> impl /// * Limited to a total of 3 channels. /// * Sorted by lowest inbound capacity if an online channel with the minimum amount requested exists, /// otherwise sort by highest inbound capacity to give the payment the best chance of succeeding. -pub(super) fn sort_and_filter_channels( +pub(super) fn sort_and_filter_channels( channels: Vec, min_inbound_capacity_msat: Option, logger: &L, -) -> impl ExactSizeIterator -where - L::Target: Logger, -{ +) -> impl ExactSizeIterator { let mut filtered_channels: BTreeMap = BTreeMap::new(); let min_inbound_capacity = min_inbound_capacity_msat.unwrap_or(0); let mut min_capacity_channel_exists = false; @@ -580,20 +562,14 @@ fn prefer_current_channel( } /// Adds relevant context to a [`Record`] before passing it to the wrapped [`Logger`]. -struct WithChannelDetails<'a, 'b, L: Deref> -where - L::Target: Logger, -{ +struct WithChannelDetails<'a, 'b, L: Logger> { /// The logger to delegate to after adding context to the record. logger: &'a L, /// The [`ChannelDetails`] for adding relevant context to the logged record. details: &'b ChannelDetails, } -impl<'a, 'b, L: Deref> Logger for WithChannelDetails<'a, 'b, L> -where - L::Target: Logger, -{ +impl<'a, 'b, L: Logger> Logger for WithChannelDetails<'a, 'b, L> { fn log(&self, mut record: Record) { record.peer_id = Some(self.details.counterparty.node_id); record.channel_id = Some(self.details.channel_id); @@ -601,10 +577,7 @@ where } } -impl<'a, 'b, L: Deref> WithChannelDetails<'a, 'b, L> -where - L::Target: Logger, -{ +impl<'a, 'b, L: Logger> WithChannelDetails<'a, 'b, L> { fn from(logger: &'a L, details: &'b ChannelDetails) -> Self { Self { logger, details } } diff --git a/lightning/src/ln/msgs.rs b/lightning/src/ln/msgs.rs index dd9c8ff7756..cc9b4953b41 100644 --- a/lightning/src/ln/msgs.rs +++ b/lightning/src/ln/msgs.rs @@ -2075,6 +2075,26 @@ pub trait BaseMessageHandler { -> Result<(), ()>; } +impl> BaseMessageHandler for B { + fn get_and_clear_pending_msg_events(&self) -> Vec { + self.deref().get_and_clear_pending_msg_events() + } + fn peer_disconnected(&self, their_node_id: PublicKey) { + self.deref().peer_disconnected(their_node_id) + } + fn provided_node_features(&self) -> NodeFeatures { + self.deref().provided_node_features() + } + fn provided_init_features(&self, their_node_id: PublicKey) -> InitFeatures { + self.deref().provided_init_features(their_node_id) + } + fn peer_connected( + &self, their_node_id: PublicKey, msg: &Init, inbound: bool, + ) -> Result<(), ()> { + self.deref().peer_connected(their_node_id, msg, inbound) + } +} + /// A trait to describe an object which can receive channel messages. /// /// Messages MAY be called in parallel when they originate from different `their_node_ids`, however @@ -2215,6 +2235,137 @@ pub trait ChannelMessageHandler: BaseMessageHandler { fn message_received(&self); } +impl> ChannelMessageHandler for C { + fn handle_open_channel(&self, their_node_id: PublicKey, msg: &OpenChannel) { + self.deref().handle_open_channel(their_node_id, msg) + } + fn handle_open_channel_v2(&self, their_node_id: PublicKey, msg: &OpenChannelV2) { + self.deref().handle_open_channel_v2(their_node_id, msg) + } + fn handle_accept_channel(&self, their_node_id: PublicKey, msg: &AcceptChannel) { + self.deref().handle_accept_channel(their_node_id, msg) + } + fn handle_accept_channel_v2(&self, their_node_id: PublicKey, msg: &AcceptChannelV2) { + self.deref().handle_accept_channel_v2(their_node_id, msg) + } + fn handle_funding_created(&self, their_node_id: PublicKey, msg: &FundingCreated) { + self.deref().handle_funding_created(their_node_id, msg) + } + fn handle_funding_signed(&self, their_node_id: PublicKey, msg: &FundingSigned) { + self.deref().handle_funding_signed(their_node_id, msg) + } + fn handle_channel_ready(&self, their_node_id: PublicKey, msg: &ChannelReady) { + self.deref().handle_channel_ready(their_node_id, msg) + } + fn handle_peer_storage(&self, their_node_id: PublicKey, msg: PeerStorage) { + self.deref().handle_peer_storage(their_node_id, msg) + } + fn handle_peer_storage_retrieval(&self, their_node_id: PublicKey, msg: PeerStorageRetrieval) { + self.deref().handle_peer_storage_retrieval(their_node_id, msg) + } + fn handle_shutdown(&self, their_node_id: PublicKey, msg: &Shutdown) { + self.deref().handle_shutdown(their_node_id, msg) + } + fn handle_closing_signed(&self, their_node_id: PublicKey, msg: &ClosingSigned) { + self.deref().handle_closing_signed(their_node_id, msg) + } + #[cfg(simple_close)] + fn handle_closing_complete(&self, their_node_id: PublicKey, msg: ClosingComplete) { + self.deref().handle_closing_complete(their_node_id, msg) + } + #[cfg(simple_close)] + fn handle_closing_sig(&self, their_node_id: PublicKey, msg: ClosingSig) { + self.deref().handle_closing_sig(their_node_id, msg) + } + fn handle_stfu(&self, their_node_id: PublicKey, msg: &Stfu) { + self.deref().handle_stfu(their_node_id, msg) + } + fn handle_splice_init(&self, their_node_id: PublicKey, msg: &SpliceInit) { + self.deref().handle_splice_init(their_node_id, msg) + } + fn handle_splice_ack(&self, their_node_id: PublicKey, msg: &SpliceAck) { + self.deref().handle_splice_ack(their_node_id, msg) + } + fn handle_splice_locked(&self, their_node_id: PublicKey, msg: &SpliceLocked) { + self.deref().handle_splice_locked(their_node_id, msg) + } + fn handle_tx_add_input(&self, their_node_id: PublicKey, msg: &TxAddInput) { + self.deref().handle_tx_add_input(their_node_id, msg) + } + fn handle_tx_add_output(&self, their_node_id: PublicKey, msg: &TxAddOutput) { + self.deref().handle_tx_add_output(their_node_id, msg) + } + fn handle_tx_remove_input(&self, their_node_id: PublicKey, msg: &TxRemoveInput) { + self.deref().handle_tx_remove_input(their_node_id, msg) + } + fn handle_tx_remove_output(&self, their_node_id: PublicKey, msg: &TxRemoveOutput) { + self.deref().handle_tx_remove_output(their_node_id, msg) + } + fn handle_tx_complete(&self, their_node_id: PublicKey, msg: &TxComplete) { + self.deref().handle_tx_complete(their_node_id, msg) + } + fn handle_tx_signatures(&self, their_node_id: PublicKey, msg: &TxSignatures) { + self.deref().handle_tx_signatures(their_node_id, msg) + } + fn handle_tx_init_rbf(&self, their_node_id: PublicKey, msg: &TxInitRbf) { + self.deref().handle_tx_init_rbf(their_node_id, msg) + } + fn handle_tx_ack_rbf(&self, their_node_id: PublicKey, msg: &TxAckRbf) { + self.deref().handle_tx_ack_rbf(their_node_id, msg) + } + fn handle_tx_abort(&self, their_node_id: PublicKey, msg: &TxAbort) { + self.deref().handle_tx_abort(their_node_id, msg) + } + fn handle_update_add_htlc(&self, their_node_id: PublicKey, msg: &UpdateAddHTLC) { + self.deref().handle_update_add_htlc(their_node_id, msg) + } + fn handle_update_fulfill_htlc(&self, their_node_id: PublicKey, msg: UpdateFulfillHTLC) { + self.deref().handle_update_fulfill_htlc(their_node_id, msg) + } + fn handle_update_fail_htlc(&self, their_node_id: PublicKey, msg: &UpdateFailHTLC) { + self.deref().handle_update_fail_htlc(their_node_id, msg) + } + fn handle_update_fail_malformed_htlc( + &self, their_node_id: PublicKey, msg: &UpdateFailMalformedHTLC, + ) { + self.deref().handle_update_fail_malformed_htlc(their_node_id, msg) + } + fn handle_commitment_signed(&self, their_node_id: PublicKey, msg: &CommitmentSigned) { + self.deref().handle_commitment_signed(their_node_id, msg) + } + fn handle_commitment_signed_batch( + &self, their_node_id: PublicKey, channel_id: ChannelId, batch: Vec, + ) { + self.deref().handle_commitment_signed_batch(their_node_id, channel_id, batch) + } + fn handle_revoke_and_ack(&self, their_node_id: PublicKey, msg: &RevokeAndACK) { + self.deref().handle_revoke_and_ack(their_node_id, msg) + } + fn handle_update_fee(&self, their_node_id: PublicKey, msg: &UpdateFee) { + self.deref().handle_update_fee(their_node_id, msg) + } + fn handle_announcement_signatures( + &self, their_node_id: PublicKey, msg: &AnnouncementSignatures, + ) { + self.deref().handle_announcement_signatures(their_node_id, msg) + } + fn handle_channel_reestablish(&self, their_node_id: PublicKey, msg: &ChannelReestablish) { + self.deref().handle_channel_reestablish(their_node_id, msg) + } + fn handle_channel_update(&self, their_node_id: PublicKey, msg: &ChannelUpdate) { + self.deref().handle_channel_update(their_node_id, msg) + } + fn handle_error(&self, their_node_id: PublicKey, msg: &ErrorMessage) { + self.deref().handle_error(their_node_id, msg) + } + fn get_chain_hashes(&self) -> Option> { + self.deref().get_chain_hashes() + } + fn message_received(&self) { + self.deref().message_received() + } +} + /// A trait to describe an object which can receive routing messages. /// /// # Implementor DoS Warnings @@ -2289,6 +2440,57 @@ pub trait RoutingMessageHandler: BaseMessageHandler { fn processing_queue_high(&self) -> bool; } +impl> RoutingMessageHandler for R { + fn handle_node_announcement( + &self, their_node_id: Option, msg: &NodeAnnouncement, + ) -> Result { + self.deref().handle_node_announcement(their_node_id, msg) + } + fn handle_channel_announcement( + &self, their_node_id: Option, msg: &ChannelAnnouncement, + ) -> Result { + self.deref().handle_channel_announcement(their_node_id, msg) + } + fn handle_channel_update( + &self, their_node_id: Option, msg: &ChannelUpdate, + ) -> Result, LightningError> { + self.deref().handle_channel_update(their_node_id, msg) + } + fn get_next_channel_announcement( + &self, starting_point: u64, + ) -> Option<(ChannelAnnouncement, Option, Option)> { + self.deref().get_next_channel_announcement(starting_point) + } + fn get_next_node_announcement( + &self, starting_point: Option<&NodeId>, + ) -> Option { + self.deref().get_next_node_announcement(starting_point) + } + fn handle_reply_channel_range( + &self, their_node_id: PublicKey, msg: ReplyChannelRange, + ) -> Result<(), LightningError> { + self.deref().handle_reply_channel_range(their_node_id, msg) + } + fn handle_reply_short_channel_ids_end( + &self, their_node_id: PublicKey, msg: ReplyShortChannelIdsEnd, + ) -> Result<(), LightningError> { + self.deref().handle_reply_short_channel_ids_end(their_node_id, msg) + } + fn handle_query_channel_range( + &self, their_node_id: PublicKey, msg: QueryChannelRange, + ) -> Result<(), LightningError> { + self.deref().handle_query_channel_range(their_node_id, msg) + } + fn handle_query_short_channel_ids( + &self, their_node_id: PublicKey, msg: QueryShortChannelIds, + ) -> Result<(), LightningError> { + self.deref().handle_query_short_channel_ids(their_node_id, msg) + } + fn processing_queue_high(&self) -> bool { + self.deref().processing_queue_high() + } +} + /// A handler for received [`OnionMessage`]s and for providing generated ones to send. pub trait OnionMessageHandler: BaseMessageHandler { /// Handle an incoming `onion_message` message from the given peer. @@ -2305,6 +2507,18 @@ pub trait OnionMessageHandler: BaseMessageHandler { fn timer_tick_occurred(&self); } +impl> OnionMessageHandler for O { + fn handle_onion_message(&self, peer_node_id: PublicKey, msg: &OnionMessage) { + self.deref().handle_onion_message(peer_node_id, msg) + } + fn next_onion_message_for_peer(&self, peer_node_id: PublicKey) -> Option { + self.deref().next_onion_message_for_peer(peer_node_id) + } + fn timer_tick_occurred(&self) { + self.deref().timer_tick_occurred() + } +} + /// A handler which can only be used to send messages. /// /// This is implemented by [`ChainMonitor`]. @@ -2312,6 +2526,8 @@ pub trait OnionMessageHandler: BaseMessageHandler { /// [`ChainMonitor`]: crate::chain::chainmonitor::ChainMonitor pub trait SendOnlyMessageHandler: BaseMessageHandler {} +impl> SendOnlyMessageHandler for S {} + #[derive(Clone, Debug, PartialEq, Eq)] /// Information communicated in the onion to the recipient for multi-part tracking and proof that /// the payment is associated with an invoice. @@ -3631,10 +3847,7 @@ impl<'a> Writeable for OutboundTrampolinePayload<'a> { } } -impl ReadableArgs<(Option, NS)> for InboundOnionPayload -where - NS::Target: NodeSigner, -{ +impl ReadableArgs<(Option, NS)> for InboundOnionPayload { fn read(r: &mut R, args: (Option, NS)) -> Result { let (update_add_blinding_point, node_signer) = args; @@ -3799,10 +4012,7 @@ where } } -impl ReadableArgs<(Option, NS)> for InboundTrampolinePayload -where - NS::Target: NodeSigner, -{ +impl ReadableArgs<(Option, NS)> for InboundTrampolinePayload { fn read(r: &mut R, args: (Option, NS)) -> Result { let (update_add_blinding_point, node_signer) = args; let receive_auth_key = node_signer.get_receive_auth_key(); diff --git a/lightning/src/ln/onion_payment.rs b/lightning/src/ln/onion_payment.rs index 6c841f5e17e..b116ca3d49a 100644 --- a/lightning/src/ln/onion_payment.rs +++ b/lightning/src/ln/onion_payment.rs @@ -26,8 +26,6 @@ use crate::util::logger::Logger; #[allow(unused_imports)] use crate::prelude::*; -use core::ops::Deref; - /// Invalid inbound onion payment. #[derive(Clone, Debug, Hash, PartialEq, Eq)] pub struct InboundHTLCErr { @@ -471,14 +469,10 @@ pub(super) fn create_recv_pending_htlc_info( /// /// [`Event::PaymentClaimable`]: crate::events::Event::PaymentClaimable #[rustfmt::skip] -pub fn peel_payment_onion( +pub fn peel_payment_onion( msg: &msgs::UpdateAddHTLC, node_signer: NS, logger: L, secp_ctx: &Secp256k1, cur_height: u32, allow_skimmed_fees: bool, -) -> Result -where - NS::Target: NodeSigner, - L::Target: Logger, -{ +) -> Result { let (hop, next_packet_details_opt) = decode_incoming_update_add_htlc_onion(msg, node_signer, logger, secp_ctx ).map_err(|(msg, failure_reason)| { @@ -545,13 +539,9 @@ pub(super) struct NextPacketDetails { } #[rustfmt::skip] -pub(super) fn decode_incoming_update_add_htlc_onion( +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)> -where - NS::Target: NodeSigner, - L::Target: Logger, -{ +) -> Result<(onion_utils::Hop, Option), (HTLCFailureMsg, LocalHTLCFailureReason)> { let encode_malformed_error = |message: &str, failure_reason: LocalHTLCFailureReason| { log_info!(logger, "Failed to accept/forward incoming HTLC: {}", message); let (sha256_of_onion, failure_reason) = if msg.blinding_point.is_some() || failure_reason == LocalHTLCFailureReason::InvalidOnionBlinding { diff --git a/lightning/src/ln/onion_utils.rs b/lightning/src/ln/onion_utils.rs index dbc2ebc9d48..3cd4e77d73d 100644 --- a/lightning/src/ln/onion_utils.rs +++ b/lightning/src/ln/onion_utils.rs @@ -39,7 +39,6 @@ use bitcoin::secp256k1::ecdh::SharedSecret; use bitcoin::secp256k1::{PublicKey, Scalar, Secp256k1, SecretKey}; use crate::io::{Cursor, Read}; -use core::ops::Deref; #[allow(unused_imports)] use crate::prelude::*; @@ -982,13 +981,10 @@ mod fuzzy_onion_utils { pub(crate) attribution_failed_channel: Option, } - pub fn process_onion_failure( + pub fn process_onion_failure( secp_ctx: &Secp256k1, logger: &L, htlc_source: &HTLCSource, encrypted_packet: OnionErrorPacket, - ) -> DecodedOnionFailure - where - L::Target: Logger, - { + ) -> DecodedOnionFailure { let (path, session_priv) = match htlc_source { HTLCSource::OutboundRoute { ref path, ref session_priv, .. } => (path, session_priv), _ => unreachable!(), @@ -998,13 +994,10 @@ mod fuzzy_onion_utils { } /// Decodes the attribution data that we got back from upstream on a payment we sent. - pub fn decode_fulfill_attribution_data( + pub fn decode_fulfill_attribution_data( secp_ctx: &Secp256k1, logger: &L, path: &Path, outer_session_priv: &SecretKey, mut attribution_data: AttributionData, - ) -> Vec - where - L::Target: Logger, - { + ) -> Vec { let mut hold_times = Vec::new(); // Only consider hops in the regular path for attribution data. Blinded path attribution data isn't accessible. @@ -1056,13 +1049,10 @@ pub(crate) use self::fuzzy_onion_utils::*; /// Process failure we got back from upstream on a payment we sent (implying htlc_source is an /// OutboundRoute). -fn process_onion_failure_inner( +fn process_onion_failure_inner( secp_ctx: &Secp256k1, logger: &L, path: &Path, session_priv: &SecretKey, trampoline_session_priv_override: Option, mut encrypted_packet: OnionErrorPacket, -) -> DecodedOnionFailure -where - L::Target: Logger, -{ +) -> DecodedOnionFailure { // Check that there is at least enough data for an hmac, otherwise none of the checking that we may do makes sense. // Also prevent slice out of bounds further down. if encrypted_packet.data.len() < 32 { @@ -2122,12 +2112,9 @@ impl HTLCFailReason { } } - pub(super) fn decode_onion_failure( + pub(super) fn decode_onion_failure( &self, secp_ctx: &Secp256k1, logger: &L, htlc_source: &HTLCSource, - ) -> DecodedOnionFailure - where - L::Target: Logger, - { + ) -> DecodedOnionFailure { match self.0 { HTLCFailReasonRepr::LightningError { ref err, .. } => { process_onion_failure(secp_ctx, logger, &htlc_source, err.clone()) @@ -2308,13 +2295,10 @@ pub(crate) enum OnionDecodeErr { }, } -pub(crate) fn decode_next_payment_hop( +pub(crate) fn decode_next_payment_hop( recipient: Recipient, hop_pubkey: &PublicKey, hop_data: &[u8], hmac_bytes: [u8; 32], payment_hash: PaymentHash, blinding_point: Option, node_signer: NS, -) -> Result -where - NS::Target: NodeSigner, -{ +) -> Result { let blinded_node_id_tweak = blinding_point.map(|bp| { let blinded_tlvs_ss = node_signer.ecdh(recipient, &bp, None).unwrap().secret_bytes(); let mut hmac = HmacEngine::::new(b"blinded_node_id"); @@ -2329,7 +2313,7 @@ where hop_data, hmac_bytes, Some(payment_hash), - (blinding_point, &(*node_signer)), + (blinding_point, &node_signer), ); match decoded_hop { Ok((next_hop_data, Some((next_hop_hmac, FixedSizeOnionPacket(new_packet_bytes))))) => { @@ -2397,7 +2381,7 @@ where &hop_data.trampoline_packet.hop_data, hop_data.trampoline_packet.hmac, Some(payment_hash), - (blinding_point, node_signer), + (blinding_point, &node_signer), ); match decoded_trampoline_hop { Ok(( diff --git a/lightning/src/ln/outbound_payment.rs b/lightning/src/ln/outbound_payment.rs index 75fe55bfeac..aaf27fff582 100644 --- a/lightning/src/ln/outbound_payment.rs +++ b/lightning/src/ln/outbound_payment.rs @@ -837,20 +837,14 @@ pub(super) struct SendAlongPathArgs<'a> { pub hold_htlc_at_next_hop: bool, } -pub(super) struct OutboundPayments -where - L::Target: Logger, -{ +pub(super) struct OutboundPayments { pub(super) pending_outbound_payments: Mutex>, awaiting_invoice: AtomicBool, retry_lock: Mutex<()>, logger: L, } -impl OutboundPayments -where - L::Target: Logger, -{ +impl OutboundPayments { pub(super) fn new( pending_outbound_payments: HashMap, logger: L, ) -> Self { @@ -872,7 +866,7 @@ where } #[rustfmt::skip] - pub(super) fn send_payment( + pub(super) fn send_payment( &self, payment_hash: PaymentHash, recipient_onion: RecipientOnionFields, payment_id: PaymentId, retry_strategy: Retry, route_params: RouteParameters, router: &R, first_hops: Vec, compute_inflight_htlcs: IH, entropy_source: &ES, @@ -880,9 +874,6 @@ where pending_events: &Mutex)>>, send_payment_along_path: SP, ) -> Result<(), RetryableSendFailure> where - R::Target: Router, - ES::Target: EntropySource, - NS::Target: NodeSigner, IH: Fn() -> InFlightHtlcs, SP: Fn(SendAlongPathArgs) -> Result<(), APIError>, { @@ -892,7 +883,7 @@ where } #[rustfmt::skip] - pub(super) fn send_spontaneous_payment( + pub(super) fn send_spontaneous_payment( &self, payment_preimage: Option, recipient_onion: RecipientOnionFields, payment_id: PaymentId, retry_strategy: Retry, route_params: RouteParameters, router: &R, first_hops: Vec, inflight_htlcs: IH, entropy_source: &ES, @@ -900,9 +891,6 @@ where pending_events: &Mutex)>>, send_payment_along_path: SP ) -> Result where - R::Target: Router, - ES::Target: EntropySource, - NS::Target: NodeSigner, IH: Fn() -> InFlightHtlcs, SP: Fn(SendAlongPathArgs) -> Result<(), APIError>, { @@ -916,7 +904,7 @@ where } #[rustfmt::skip] - pub(super) fn pay_for_bolt11_invoice( + pub(super) fn pay_for_bolt11_invoice( &self, invoice: &Bolt11Invoice, payment_id: PaymentId, amount_msats: Option, route_params_config: RouteParametersConfig, @@ -927,9 +915,6 @@ where pending_events: &Mutex)>>, send_payment_along_path: SP, ) -> Result<(), Bolt11PaymentError> where - R::Target: Router, - ES::Target: EntropySource, - NS::Target: NodeSigner, IH: Fn() -> InFlightHtlcs, SP: Fn(SendAlongPathArgs) -> Result<(), APIError>, { @@ -963,7 +948,7 @@ where #[rustfmt::skip] pub(super) fn send_payment_for_bolt12_invoice< - R: Deref, ES: Deref, NS: Deref, NL: Deref, IH, SP + R: Router, ES: EntropySource, NS: NodeSigner, NL: NodeIdLookUp, IH, SP >( &self, invoice: &Bolt12Invoice, payment_id: PaymentId, router: &R, first_hops: Vec, features: Bolt12InvoiceFeatures, inflight_htlcs: IH, @@ -973,10 +958,6 @@ where send_payment_along_path: SP, ) -> Result<(), Bolt12PaymentError> where - R::Target: Router, - ES::Target: EntropySource, - NS::Target: NodeSigner, - NL::Target: NodeIdLookUp, IH: Fn() -> InFlightHtlcs, SP: Fn(SendAlongPathArgs) -> Result<(), APIError>, { @@ -1008,7 +989,7 @@ where #[rustfmt::skip] fn send_payment_for_bolt12_invoice_internal< - R: Deref, ES: Deref, NS: Deref, NL: Deref, IH, SP + R: Router, ES: EntropySource, NS: NodeSigner, NL: NodeIdLookUp, IH, SP >( &self, payment_id: PaymentId, payment_hash: PaymentHash, keysend_preimage: Option, invoice_request: Option<&InvoiceRequest>, @@ -1020,10 +1001,6 @@ where send_payment_along_path: SP, ) -> Result<(), Bolt12PaymentError> where - R::Target: Router, - ES::Target: EntropySource, - NS::Target: NodeSigner, - NL::Target: NodeIdLookUp, IH: Fn() -> InFlightHtlcs, SP: Fn(SendAlongPathArgs) -> Result<(), APIError>, { @@ -1115,14 +1092,11 @@ where Ok(()) } - pub(super) fn static_invoice_received( + 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, pending_events: &Mutex)>>, - ) -> Result<(), Bolt12PaymentError> - where - ES::Target: EntropySource, - { + ) -> Result<(), Bolt12PaymentError> { macro_rules! abandon_with_entry { ($payment: expr, $reason: expr) => { assert!( @@ -1225,9 +1199,9 @@ where } pub(super) fn send_payment_for_static_invoice< - R: Deref, - ES: Deref, - NS: Deref, + R: Router, + ES: EntropySource, + NS: NodeSigner, NL: Deref, IH, SP, @@ -1239,9 +1213,6 @@ where send_payment_along_path: SP, ) -> Result<(), Bolt12PaymentError> where - R::Target: Router, - ES::Target: EntropySource, - NS::Target: NodeSigner, NL::Target: NodeIdLookUp, IH: Fn() -> InFlightHtlcs, SP: Fn(SendAlongPathArgs) -> Result<(), APIError>, @@ -1307,16 +1278,13 @@ where } // Returns whether the data changed and needs to be repersisted. - pub(super) fn check_retry_payments( + 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, pending_events: &Mutex)>>, send_payment_along_path: SP, ) -> bool where - R::Target: Router, - ES::Target: EntropySource, - NS::Target: NodeSigner, SP: Fn(SendAlongPathArgs) -> Result<(), APIError>, IH: Fn() -> InFlightHtlcs, FH: Fn() -> Vec, @@ -1414,16 +1382,13 @@ where } #[rustfmt::skip] - fn find_initial_route( + fn find_initial_route( &self, payment_id: PaymentId, payment_hash: PaymentHash, recipient_onion: &RecipientOnionFields, keysend_preimage: Option, invoice_request: Option<&InvoiceRequest>, route_params: &mut RouteParameters, router: &R, first_hops: &Vec, inflight_htlcs: &IH, node_signer: &NS, best_block_height: u32, ) -> Result where - R::Target: Router, - NS::Target: NodeSigner, - L::Target: Logger, IH: Fn() -> InFlightHtlcs, { #[cfg(feature = "std")] { @@ -1469,7 +1434,7 @@ where /// [`Event::PaymentPathFailed`]: crate::events::Event::PaymentPathFailed /// [`Event::PaymentFailed`]: crate::events::Event::PaymentFailed #[rustfmt::skip] - fn send_payment_for_non_bolt12_invoice( + 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, router: &R, first_hops: Vec, inflight_htlcs: IH, entropy_source: &ES, @@ -1477,10 +1442,6 @@ where pending_events: &Mutex)>>, send_payment_along_path: SP, ) -> Result<(), RetryableSendFailure> where - R::Target: Router, - ES::Target: EntropySource, - NS::Target: NodeSigner, - L::Target: Logger, IH: Fn() -> InFlightHtlcs, SP: Fn(SendAlongPathArgs) -> Result<(), APIError>, { @@ -1514,17 +1475,13 @@ where } #[rustfmt::skip] - fn find_route_and_send_payment( + 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, node_signer: &NS, best_block_height: u32, pending_events: &Mutex)>>, send_payment_along_path: &SP, ) where - R::Target: Router, - ES::Target: EntropySource, - NS::Target: NodeSigner, - L::Target: Logger, IH: Fn() -> InFlightHtlcs, SP: Fn(SendAlongPathArgs) -> Result<(), APIError>, { @@ -1675,7 +1632,7 @@ where } #[rustfmt::skip] - fn handle_pay_route_err( + 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, first_hops: Vec, inflight_htlcs: &IH, entropy_source: &ES, node_signer: &NS, @@ -1684,9 +1641,6 @@ where send_payment_along_path: &SP, ) where - R::Target: Router, - ES::Target: EntropySource, - NS::Target: NodeSigner, IH: Fn() -> InFlightHtlcs, SP: Fn(SendAlongPathArgs) -> Result<(), APIError>, { @@ -1792,13 +1746,11 @@ where } #[rustfmt::skip] - pub(super) fn send_probe( + 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 ) -> Result<(PaymentHash, PaymentId), ProbeSendFailure> where - ES::Target: EntropySource, - NS::Target: NodeSigner, F: Fn(SendAlongPathArgs) -> Result<(), APIError>, { let payment_id = PaymentId(entropy_source.get_secure_random_bytes()); @@ -1867,20 +1819,20 @@ where #[cfg(any(test, feature = "_externalize_tests"))] #[rustfmt::skip] - pub(super) fn test_add_new_pending_payment( + 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 - ) -> Result, PaymentSendFailure> where ES::Target: EntropySource { + ) -> Result, PaymentSendFailure> { 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( + 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, payment_params: Option, entropy_source: &ES, best_block_height: u32, bolt12_invoice: Option - ) -> Result, PaymentSendFailure> where ES::Target: EntropySource { + ) -> Result, PaymentSendFailure> { let mut pending_outbounds = self.pending_outbound_payments.lock().unwrap(); match pending_outbounds.entry(payment_id) { hash_map::Entry::Occupied(_) => Err(PaymentSendFailure::DuplicatePayment), @@ -1896,15 +1848,12 @@ where } #[rustfmt::skip] - fn create_pending_payment( + fn create_pending_payment( payment_hash: PaymentHash, recipient_onion: RecipientOnionFields, keysend_preimage: Option, invoice_request: Option, bolt12_invoice: Option, route: &Route, retry_strategy: Option, payment_params: Option, entropy_source: &ES, best_block_height: u32 - ) -> (PendingOutboundPayment, Vec<[u8; 32]>) - where - ES::Target: EntropySource, - { + ) -> (PendingOutboundPayment, Vec<[u8; 32]>) { let mut onion_session_privs = Vec::with_capacity(route.paths.len()); for _ in 0..route.paths.len() { onion_session_privs.push(entropy_source.get_secure_random_bytes()); @@ -2068,14 +2017,13 @@ where } #[rustfmt::skip] - fn pay_route_internal( + fn pay_route_internal( &self, route: &Route, payment_hash: PaymentHash, recipient_onion: &RecipientOnionFields, keysend_preimage: Option, invoice_request: Option<&InvoiceRequest>, bolt12_invoice: Option<&PaidBolt12Invoice>, payment_id: PaymentId, recv_value_msat: Option, onion_session_privs: &Vec<[u8; 32]>, hold_htlcs_at_next_hop: bool, node_signer: &NS, best_block_height: u32, send_payment_along_path: &F ) -> Result<(), PaymentSendFailure> where - NS::Target: NodeSigner, F: Fn(SendAlongPathArgs) -> Result<(), APIError>, { if route.paths.len() < 1 { @@ -2183,14 +2131,13 @@ where #[cfg(any(test, feature = "_externalize_tests"))] #[rustfmt::skip] - pub(super) fn test_send_payment_internal( + pub(super) fn test_send_payment_internal( &self, route: &Route, payment_hash: PaymentHash, recipient_onion: RecipientOnionFields, keysend_preimage: Option, payment_id: PaymentId, recv_value_msat: Option, onion_session_privs: Vec<[u8; 32]>, node_signer: &NS, best_block_height: u32, send_payment_along_path: F ) -> Result<(), PaymentSendFailure> where - NS::Target: NodeSigner, F: Fn(SendAlongPathArgs) -> Result<(), APIError>, { self.pay_route_internal(route, payment_hash, &recipient_onion, diff --git a/lightning/src/ln/peer_channel_encryptor.rs b/lightning/src/ln/peer_channel_encryptor.rs index 894de045b14..5554c5a8c19 100644 --- a/lightning/src/ln/peer_channel_encryptor.rs +++ b/lightning/src/ln/peer_channel_encryptor.rs @@ -30,8 +30,6 @@ use crate::crypto::chacha20poly1305rfc::ChaCha20Poly1305RFC; use crate::crypto::utils::hkdf_extract_expand_twice; use crate::util::ser::VecWriter; -use core::ops::Deref; - /// Maximum Lightning message data length according to /// [BOLT-8](https://github.com/lightning/bolts/blob/v1.0/08-transport.md#lightning-message-specification) /// and [BOLT-1](https://github.com/lightning/bolts/blob/master/01-messaging.md#lightning-message-format): @@ -52,10 +50,7 @@ const NOISE_H: [u8; 32] = [ 0x4b, 0xb4, 0x20, 0xd8, 0x9d, 0x2a, 0x04, 0x8a, 0x3c, 0x4f, 0x4c, 0x09, 0x2e, 0x37, 0xb6, 0x76, ]; -enum NoiseSecretKey<'a, 'b, NS: Deref> -where - NS::Target: NodeSigner, -{ +enum NoiseSecretKey<'a, 'b, NS: NodeSigner> { InMemory(&'a SecretKey), NodeSigner(&'b NS), } @@ -130,10 +125,7 @@ impl PeerChannelEncryptor { } } - pub fn new_inbound(node_signer: &NS) -> PeerChannelEncryptor - where - NS::Target: NodeSigner, - { + pub fn new_inbound(node_signer: &NS) -> PeerChannelEncryptor { let mut sha = Sha256::engine(); sha.input(&NOISE_H); let our_node_id = node_signer.get_node_id(Recipient::Node).unwrap(); @@ -248,12 +240,9 @@ impl PeerChannelEncryptor { } #[inline] - fn inbound_noise_act<'a, 'b, NS: Deref>( + fn inbound_noise_act<'a, 'b, NS: NodeSigner>( state: &mut BidirectionalNoiseState, act: &[u8], secret_key: NoiseSecretKey<'a, 'b, NS>, - ) -> Result<(PublicKey, [u8; 32]), LightningError> - where - NS::Target: NodeSigner, - { + ) -> Result<(PublicKey, [u8; 32]), LightningError> { assert_eq!(act.len(), 50); if act[0] != 0 { @@ -327,13 +316,10 @@ impl PeerChannelEncryptor { } } - pub fn process_act_one_with_keys( + pub fn process_act_one_with_keys( &mut self, act_one: &[u8], node_signer: &NS, our_ephemeral: SecretKey, secp_ctx: &Secp256k1, - ) -> Result<[u8; 50], LightningError> - where - NS::Target: NodeSigner, - { + ) -> Result<[u8; 50], LightningError> { assert_eq!(act_one.len(), 50); match self.noise_state { @@ -372,12 +358,9 @@ impl PeerChannelEncryptor { } } - pub fn process_act_two( + pub fn process_act_two( &mut self, act_two: &[u8], node_signer: &NS, - ) -> Result<([u8; 66], PublicKey), LightningError> - where - NS::Target: NodeSigner, - { + ) -> Result<([u8; 66], PublicKey), LightningError> { assert_eq!(act_two.len(), 50); let final_hkdf; diff --git a/lightning/src/ln/peer_handler.rs b/lightning/src/ln/peer_handler.rs index 4d1dff9cd52..8840a8edd83 100644 --- a/lightning/src/ln/peer_handler.rs +++ b/lightning/src/ln/peer_handler.rs @@ -48,12 +48,11 @@ use crate::types::features::{InitFeatures, NodeFeatures}; use crate::types::string::PrintableString; use crate::util::atomic_counter::AtomicCounter; use crate::util::logger::{Level, Logger, WithContext}; -use crate::util::ser::{VecWriter, Writeable, Writer}; +use crate::util::ser::{LengthLimitedRead, VecWriter, Writeable, Writer}; #[allow(unused_imports)] use crate::prelude::*; -use super::wire::CustomMessageReader; use crate::io; use crate::sync::{FairRwLock, Mutex, MutexGuard}; use core::convert::Infallible; @@ -126,6 +125,40 @@ pub trait CustomMessageHandler: wire::CustomMessageReader { fn provided_init_features(&self, their_node_id: PublicKey) -> InitFeatures; } +impl> wire::CustomMessageReader for C { + type CustomMessage = T::CustomMessage; + fn read( + &self, message_type: u16, buffer: &mut R, + ) -> Result, msgs::DecodeError> { + self.deref().read(message_type, buffer) + } +} + +impl> CustomMessageHandler for C { + fn handle_custom_message( + &self, msg: Self::CustomMessage, sender_node_id: PublicKey, + ) -> Result<(), LightningError> { + self.deref().handle_custom_message(msg, sender_node_id) + } + fn get_and_clear_pending_msg(&self) -> Vec<(PublicKey, Self::CustomMessage)> { + self.deref().get_and_clear_pending_msg() + } + fn peer_disconnected(&self, their_node_id: PublicKey) { + self.deref().peer_disconnected(their_node_id) + } + fn peer_connected( + &self, their_node_id: PublicKey, msg: &Init, inbound: bool, + ) -> Result<(), ()> { + self.deref().peer_connected(their_node_id, msg, inbound) + } + fn provided_node_features(&self) -> NodeFeatures { + self.deref().provided_node_features() + } + fn provided_init_features(&self, their_node_id: PublicKey) -> InitFeatures { + self.deref().provided_init_features(their_node_id) + } +} + /// A dummy struct which implements `RoutingMessageHandler` without storing any routing information /// or doing any processing. You can provide one of these as the route_handler in a MessageHandler. pub struct IgnoringMessageHandler {} @@ -288,13 +321,6 @@ impl OnionMessageContents for Infallible { } } -impl Deref for IgnoringMessageHandler { - type Target = IgnoringMessageHandler; - fn deref(&self) -> &Self { - self - } -} - // Implement Type for Infallible, note that it cannot be constructed, and thus you can never call a // method that takes self for it. impl wire::Type for Infallible { @@ -568,22 +594,14 @@ impl ChannelMessageHandler for ErroringMessageHandler { fn message_received(&self) {} } -impl Deref for ErroringMessageHandler { - type Target = ErroringMessageHandler; - fn deref(&self) -> &Self { - self - } -} - /// Provides references to trait impls which handle different types of messages. -pub struct MessageHandler -where - CM::Target: ChannelMessageHandler, - RM::Target: RoutingMessageHandler, - OM::Target: OnionMessageHandler, - CustomM::Target: CustomMessageHandler, - SM::Target: SendOnlyMessageHandler, -{ +pub struct MessageHandler< + CM: ChannelMessageHandler, + RM: RoutingMessageHandler, + OM: OnionMessageHandler, + CustomM: CustomMessageHandler, + SM: SendOnlyMessageHandler, +> { /// A message handler which handles messages specific to channels. Usually this is just a /// [`ChannelManager`] object or an [`ErroringMessageHandler`]. /// @@ -971,20 +989,13 @@ pub type SimpleRefPeerManager< #[allow(missing_docs)] pub trait APeerManager { type Descriptor: SocketDescriptor; - type CMT: ChannelMessageHandler + ?Sized; - type CM: Deref; - type RMT: RoutingMessageHandler + ?Sized; - type RM: Deref; - type OMT: OnionMessageHandler + ?Sized; - type OM: Deref; - type LT: Logger + ?Sized; - type L: Deref; - type CMHT: CustomMessageHandler + ?Sized; - type CMH: Deref; - type NST: NodeSigner + ?Sized; - type NS: Deref; - type SMT: SendOnlyMessageHandler + ?Sized; - type SM: Deref; + type CM: ChannelMessageHandler; + type RM: RoutingMessageHandler; + type OM: OnionMessageHandler; + type Logger: Logger; + type CMH: CustomMessageHandler; + type NodeSigner: NodeSigner; + type SM: SendOnlyMessageHandler; /// Gets a reference to the underlying [`PeerManager`]. fn as_ref( &self, @@ -993,46 +1004,31 @@ pub trait APeerManager { Self::CM, Self::RM, Self::OM, - Self::L, + Self::Logger, Self::CMH, - Self::NS, + Self::NodeSigner, Self::SM, >; } impl< Descriptor: SocketDescriptor, - CM: Deref, - RM: Deref, - OM: Deref, - L: Deref, - CMH: Deref, - NS: Deref, - SM: Deref, + CM: ChannelMessageHandler, + RM: RoutingMessageHandler, + OM: OnionMessageHandler, + L: Logger, + CMH: CustomMessageHandler, + NS: NodeSigner, + SM: SendOnlyMessageHandler, > APeerManager for PeerManager -where - CM::Target: ChannelMessageHandler, - RM::Target: RoutingMessageHandler, - OM::Target: OnionMessageHandler, - L::Target: Logger, - CMH::Target: CustomMessageHandler, - NS::Target: NodeSigner, - SM::Target: SendOnlyMessageHandler, { type Descriptor = Descriptor; - type CMT = ::Target; type CM = CM; - type RMT = ::Target; type RM = RM; - type OMT = ::Target; type OM = OM; - type LT = ::Target; - type L = L; - type CMHT = ::Target; + type Logger = L; type CMH = CMH; - type NST = ::Target; - type NS = NS; - type SMT = ::Target; + type NodeSigner = NS; type SM = SM; fn as_ref(&self) -> &PeerManager { self @@ -1060,22 +1056,14 @@ where /// [`read_event`]: PeerManager::read_event pub struct PeerManager< Descriptor: SocketDescriptor, - CM: Deref, - RM: Deref, - OM: Deref, - L: Deref, - CMH: Deref, - NS: Deref, - SM: Deref, -> where - CM::Target: ChannelMessageHandler, - RM::Target: RoutingMessageHandler, - OM::Target: OnionMessageHandler, - L::Target: Logger, - CMH::Target: CustomMessageHandler, - NS::Target: NodeSigner, - SM::Target: SendOnlyMessageHandler, -{ + CM: ChannelMessageHandler, + RM: RoutingMessageHandler, + OM: OnionMessageHandler, + L: Logger, + CMH: CustomMessageHandler, + NS: NodeSigner, + SM: SendOnlyMessageHandler, +> { message_handler: MessageHandler, /// Connection state for each connected peer - we have an outer read-write lock which is taken /// as read while we're doing processing for a peer and taken write when a peer is being added @@ -1151,14 +1139,14 @@ fn encode_message(message: wire::Message) -> Vec { buffer.0 } -impl - PeerManager -where - CM::Target: ChannelMessageHandler, - OM::Target: OnionMessageHandler, - L::Target: Logger, - NS::Target: NodeSigner, - SM::Target: SendOnlyMessageHandler, +impl< + Descriptor: SocketDescriptor, + CM: ChannelMessageHandler, + OM: OnionMessageHandler, + L: Logger, + NS: NodeSigner, + SM: SendOnlyMessageHandler, + > PeerManager { /// Constructs a new `PeerManager` with the given `ChannelMessageHandler` and /// `OnionMessageHandler`. No routing message handler is used and network graph messages are @@ -1194,7 +1182,7 @@ where } } -impl +impl PeerManager< Descriptor, ErroringMessageHandler, @@ -1204,10 +1192,7 @@ impl IgnoringMessageHandler, NS, IgnoringMessageHandler, - > where - RM::Target: RoutingMessageHandler, - L::Target: Logger, - NS::Target: NodeSigner, + > { /// Constructs a new `PeerManager` with the given `RoutingMessageHandler`. No channel message /// handler or onion message handler is used and onion and channel messages will be ignored (or @@ -1293,22 +1278,14 @@ fn filter_addresses(ip_address: Option) -> Option impl< Descriptor: SocketDescriptor, - CM: Deref, - RM: Deref, - OM: Deref, - L: Deref, - CMH: Deref, - NS: Deref, - SM: Deref, + CM: ChannelMessageHandler, + RM: RoutingMessageHandler, + OM: OnionMessageHandler, + L: Logger, + CMH: CustomMessageHandler, + NS: NodeSigner, + SM: SendOnlyMessageHandler, > PeerManager -where - CM::Target: ChannelMessageHandler, - RM::Target: RoutingMessageHandler, - OM::Target: OnionMessageHandler, - L::Target: Logger, - CMH::Target: CustomMessageHandler, - NS::Target: NodeSigner, - SM::Target: SendOnlyMessageHandler, { /// Constructs a new `PeerManager` with the given message handlers. /// @@ -1735,10 +1712,7 @@ where } /// Append a message to a peer's pending outbound/write buffer - fn enqueue_message( - &self, peer: &mut Peer, - message: Message<::CustomMessage>, - ) { + fn enqueue_message(&self, peer: &mut Peer, message: Message) { let their_node_id = peer.their_node_id.map(|p| p.0); if their_node_id.is_some() { let logger = WithContext::from(&self.logger, their_node_id, None, None); @@ -1954,7 +1928,7 @@ where let message_result = wire::read( &mut &peer.pending_read_buffer [..peer.pending_read_buffer.len() - 16], - &*self.message_handler.custom_message_handler, + &self.message_handler.custom_message_handler, ); // Reset read buffer @@ -2081,7 +2055,7 @@ where /// Returns the message back if it needs to be broadcasted to all other peers. fn handle_message( &self, peer_mutex: &Mutex, peer_lock: MutexGuard, - message: Message<<::Target as wire::CustomMessageReader>::CustomMessage>, + message: Message, ) -> Result, MessageHandlingError> { let their_node_id = peer_lock .their_node_id @@ -2121,15 +2095,9 @@ where // Returns `None` if the message was fully processed and otherwise returns the message back to // allow it to be subsequently processed by `do_handle_message_without_peer_lock`. fn do_handle_message_holding_peer_lock<'a>( - &self, mut peer_lock: MutexGuard, - message: Message<<::Target as wire::CustomMessageReader>::CustomMessage>, + &self, mut peer_lock: MutexGuard, message: Message, their_node_id: PublicKey, logger: &WithContext<'a, L>, - ) -> Result< - Option< - LogicalMessage<<::Target as wire::CustomMessageReader>::CustomMessage>, - >, - MessageHandlingError, - > { + ) -> Result>, MessageHandlingError> { peer_lock.received_message_since_timer_tick = true; // Need an Init as first message @@ -2401,8 +2369,7 @@ where // // Returns the message back if it needs to be broadcasted to all other peers. fn do_handle_message_without_peer_lock<'a>( - &self, peer_mutex: &Mutex, - message: Message<<::Target as wire::CustomMessageReader>::CustomMessage>, + &self, peer_mutex: &Mutex, message: Message, their_node_id: PublicKey, logger: &WithContext<'a, L>, ) -> Result, MessageHandlingError> { if is_gossip_msg(message.type_id()) { @@ -2671,8 +2638,7 @@ where let scid = msg.contents.short_channel_id; let node_id_1 = msg.contents.node_id_1; let node_id_2 = msg.contents.node_id_2; - let msg: Message<::CustomMessage> = - Message::ChannelAnnouncement(msg); + let msg: Message = Message::ChannelAnnouncement(msg); let encoded_msg = encode_message(msg); for (_, peer_mutex) in peers.iter() { let mut peer = peer_mutex.lock().unwrap(); @@ -2718,8 +2684,7 @@ where let our_announcement = self.our_node_id == msg.contents.node_id; let msg_node_id = msg.contents.node_id; - let msg: Message<::CustomMessage> = - Message::NodeAnnouncement(msg); + let msg: Message = Message::NodeAnnouncement(msg); let encoded_msg = encode_message(msg); for (_, peer_mutex) in peers.iter() { let mut peer = peer_mutex.lock().unwrap(); @@ -2764,8 +2729,7 @@ where ); let our_channel = self.our_node_id == node_id_1 || self.our_node_id == node_id_2; let scid = msg.contents.short_channel_id; - let msg: Message<::CustomMessage> = - Message::ChannelUpdate(msg); + let msg: Message = Message::ChannelUpdate(msg); let encoded_msg = encode_message(msg); for (_, peer_mutex) in peers.iter() { let mut peer = peer_mutex.lock().unwrap(); @@ -3299,9 +3263,8 @@ where // We do not have the peers write lock, so we just store that we're // about to disconnect the peer and do it after we finish // processing most messages. - let msg = msg.map(|msg| { - Message::<<::Target as wire::CustomMessageReader>::CustomMessage>::Error(msg) - }); + let msg = + msg.map(|msg| Message::::Error(msg)); peers_to_disconnect.insert(node_id, msg); }, msgs::ErrorAction::DisconnectPeerWithWarning { msg } => { @@ -3571,8 +3534,7 @@ where if peer.awaiting_pong_timer_tick_intervals == 0 { peer.awaiting_pong_timer_tick_intervals = -1; let ping = msgs::Ping { ponglen: 0, byteslen: 64 }; - let msg: Message<::CustomMessage> = - Message::Ping(ping); + let msg: Message = Message::Ping(ping); self.enqueue_message(peer, msg); } } diff --git a/lightning/src/ln/types.rs b/lightning/src/ln/types.rs index 5d72ba685cb..fd8ccbae382 100644 --- a/lightning/src/ln/types.rs +++ b/lightning/src/ln/types.rs @@ -24,7 +24,6 @@ use bitcoin::hashes::{sha256::Hash as Sha256, Hash as _, HashEngine as _}; use bitcoin::hex::display::impl_fmt_traits; use core::borrow::Borrow; -use core::ops::Deref; /// A unique 32-byte identifier for a channel. /// Depending on how the ID is generated, several varieties are distinguished @@ -53,10 +52,7 @@ impl ChannelId { } /// Create a _temporary_ channel ID randomly, based on an entropy source. - pub fn temporary_from_entropy_source(entropy_source: &ES) -> Self - where - ES::Target: EntropySource, - { + pub fn temporary_from_entropy_source(entropy_source: &ES) -> Self { Self(entropy_source.get_secure_random_bytes()) } diff --git a/lightning/src/offers/flow.rs b/lightning/src/offers/flow.rs index 8b03f0ea081..0bb98777227 100644 --- a/lightning/src/offers/flow.rs +++ b/lightning/src/offers/flow.rs @@ -10,7 +10,6 @@ //! Provides data structures and functions for creating and managing Offers messages, //! facilitating communication, and handling BOLT12 messages and payments. -use core::ops::Deref; use core::sync::atomic::{AtomicUsize, Ordering}; use core::time::Duration; @@ -74,11 +73,7 @@ use { /// /// [`OffersMessageFlow`] is parameterized by a [`MessageRouter`], which is responsible /// for finding message paths when initiating and retrying onion messages. -pub struct OffersMessageFlow -where - MR::Target: MessageRouter, - L::Target: Logger, -{ +pub struct OffersMessageFlow { chain_hash: ChainHash, best_block: RwLock, @@ -107,11 +102,7 @@ where logger: L, } -impl OffersMessageFlow -where - MR::Target: MessageRouter, - L::Target: Logger, -{ +impl OffersMessageFlow { /// Creates a new [`OffersMessageFlow`] pub fn new( chain_hash: ChainHash, best_block: BestBlock, our_network_pubkey: PublicKey, @@ -266,11 +257,7 @@ const DEFAULT_ASYNC_RECEIVE_OFFER_EXPIRY: Duration = Duration::from_secs(365 * 2 pub(crate) const TEST_DEFAULT_ASYNC_RECEIVE_OFFER_EXPIRY: Duration = DEFAULT_ASYNC_RECEIVE_OFFER_EXPIRY; -impl OffersMessageFlow -where - MR::Target: MessageRouter, - L::Target: Logger, -{ +impl OffersMessageFlow { /// [`BlindedMessagePath`]s for an async recipient to communicate with this node and interactively /// build [`Offer`]s and [`StaticInvoice`]s for receiving async payments. /// @@ -317,14 +304,11 @@ where /// Creates multi-hop blinded payment paths for the given `amount_msats` by delegating to /// [`Router::create_blinded_payment_paths`]. - fn create_blinded_payment_paths( + fn create_blinded_payment_paths( &self, router: &R, usable_channels: Vec, amount_msats: Option, payment_secret: PaymentSecret, payment_context: PaymentContext, relative_expiry_seconds: u32, - ) -> Result, ()> - where - R::Target: Router, - { + ) -> Result, ()> { let secp_ctx = &self.secp_ctx; let receive_auth_key = self.receive_auth_key; @@ -356,14 +340,11 @@ where #[cfg(test)] /// Creates multi-hop blinded payment paths for the given `amount_msats` by delegating to /// [`Router::create_blinded_payment_paths`]. - pub(crate) fn test_create_blinded_payment_paths( + pub(crate) fn test_create_blinded_payment_paths( &self, router: &R, usable_channels: Vec, amount_msats: Option, payment_secret: PaymentSecret, payment_context: PaymentContext, relative_expiry_seconds: u32, - ) -> Result, ()> - where - R::Target: Router, - { + ) -> Result, ()> { self.create_blinded_payment_paths( router, usable_channels, @@ -436,11 +417,7 @@ pub enum HeldHtlcReplyPath { }, } -impl OffersMessageFlow -where - MR::Target: MessageRouter, - L::Target: Logger, -{ +impl OffersMessageFlow { /// Verifies an [`InvoiceRequest`] using the provided [`OffersContext`] or the [`InvoiceRequest::metadata`]. /// /// - If an [`OffersContext::InvoiceRequest`] with a `nonce` is provided, verification is performed using recipient context data. @@ -550,11 +527,10 @@ where } } - fn create_offer_builder_intern( + fn create_offer_builder_intern( &self, entropy_source: ES, make_paths: PF, ) -> Result<(OfferBuilder<'_, DerivedMetadata, secp256k1::All>, Nonce), Bolt12SemanticError> where - ES::Target: EntropySource, PF: FnOnce( PublicKey, MessageContext, @@ -607,13 +583,10 @@ where /// This is not exported to bindings users as builder patterns don't map outside of move semantics. /// /// [`DefaultMessageRouter`]: crate::onion_message::messenger::DefaultMessageRouter - pub fn create_offer_builder( + pub fn create_offer_builder( &self, entropy_source: ES, peers: Vec, - ) -> Result, Bolt12SemanticError> - where - ES::Target: EntropySource, - { - self.create_offer_builder_intern(&*entropy_source, |_, context, _| { + ) -> Result, Bolt12SemanticError> { + self.create_offer_builder_intern(&entropy_source, |_, context, _| { self.create_blinded_paths(peers, context) .map(|paths| paths.into_iter().take(1)) .map_err(|_| Bolt12SemanticError::MissingPaths) @@ -630,15 +603,11 @@ where /// This is not exported to bindings users as builder patterns don't map outside of move semantics. /// /// See [`Self::create_offer_builder`] for more details on usage. - pub fn create_offer_builder_using_router( + pub fn create_offer_builder_using_router( &self, router: ME, entropy_source: ES, peers: Vec, - ) -> Result, Bolt12SemanticError> - where - ME::Target: MessageRouter, - ES::Target: EntropySource, - { + ) -> Result, Bolt12SemanticError> { let receive_key = self.get_receive_auth_key(); - self.create_offer_builder_intern(&*entropy_source, |node_id, context, secp_ctx| { + self.create_offer_builder_intern(&entropy_source, |node_id, context, secp_ctx| { router .create_blinded_paths(node_id, receive_key, context, peers, secp_ctx) .map(|paths| paths.into_iter().take(1)) @@ -657,23 +626,19 @@ where /// aforementioned always-online node. /// /// This is not exported to bindings users as builder patterns don't map outside of move semantics. - pub fn create_async_receive_offer_builder( + pub fn create_async_receive_offer_builder( &self, entropy_source: ES, message_paths_to_always_online_node: Vec, - ) -> Result<(OfferBuilder<'_, DerivedMetadata, secp256k1::All>, Nonce), Bolt12SemanticError> - where - ES::Target: EntropySource, - { - self.create_offer_builder_intern(&*entropy_source, |_, _, _| { + ) -> Result<(OfferBuilder<'_, DerivedMetadata, secp256k1::All>, Nonce), Bolt12SemanticError> { + self.create_offer_builder_intern(&entropy_source, |_, _, _| { Ok(message_paths_to_always_online_node) }) } - fn create_refund_builder_intern( + fn create_refund_builder_intern( &self, entropy_source: ES, make_paths: PF, amount_msats: u64, absolute_expiry: Duration, payment_id: PaymentId, ) -> Result, Bolt12SemanticError> where - ES::Target: EntropySource, PF: FnOnce( PublicKey, MessageContext, @@ -683,7 +648,7 @@ where { let node_id = self.get_our_node_id(); let expanded_key = &self.inbound_payment_key; - let entropy = &*entropy_source; + let entropy = &entropy_source; let secp_ctx = &self.secp_ctx; let nonce = Nonce::from_entropy_source(entropy); @@ -744,15 +709,12 @@ where /// /// [`Event::PaymentFailed`]: crate::events::Event::PaymentFailed /// [`RouteParameters::from_payment_params_and_value`]: crate::routing::router::RouteParameters::from_payment_params_and_value - pub fn create_refund_builder( + pub fn create_refund_builder( &self, entropy_source: ES, amount_msats: u64, absolute_expiry: Duration, payment_id: PaymentId, peers: Vec, - ) -> Result, Bolt12SemanticError> - where - ES::Target: EntropySource, - { + ) -> Result, Bolt12SemanticError> { self.create_refund_builder_intern( - &*entropy_source, + &entropy_source, |_, context, _| { self.create_blinded_paths(peers, context) .map(|paths| paths.into_iter().take(1)) @@ -785,17 +747,13 @@ where /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice /// [`Event::PaymentFailed`]: crate::events::Event::PaymentFailed /// [`RouteParameters::from_payment_params_and_value`]: crate::routing::router::RouteParameters::from_payment_params_and_value - pub fn create_refund_builder_using_router( + pub fn create_refund_builder_using_router( &self, router: ME, entropy_source: ES, amount_msats: u64, absolute_expiry: Duration, payment_id: PaymentId, peers: Vec, - ) -> Result, Bolt12SemanticError> - where - ME::Target: MessageRouter, - ES::Target: EntropySource, - { + ) -> Result, Bolt12SemanticError> { let receive_key = self.get_receive_auth_key(); self.create_refund_builder_intern( - &*entropy_source, + &entropy_source, |node_id, context, secp_ctx| { router .create_blinded_paths(node_id, receive_key, context, peers, secp_ctx) @@ -834,14 +792,11 @@ where /// created via [`Self::create_async_receive_offer_builder`]. /// /// This is not exported to bindings users as builder patterns don't map outside of move semantics. - pub fn create_static_invoice_builder<'a, R: Deref>( + pub fn create_static_invoice_builder<'a, R: Router>( &self, router: &R, offer: &'a Offer, offer_nonce: Nonce, payment_secret: PaymentSecret, relative_expiry_secs: u32, usable_channels: Vec, peers: Vec, - ) -> Result, Bolt12SemanticError> - where - R::Target: Router, - { + ) -> Result, Bolt12SemanticError> { let expanded_key = &self.inbound_payment_key; let secp_ctx = &self.secp_ctx; @@ -905,13 +860,11 @@ where /// blinded path can be constructed. /// /// This is not exported to bindings users as builder patterns don't map outside of move semantics. - pub fn create_invoice_builder_from_refund<'a, ES: Deref, R: Deref, F>( + pub fn create_invoice_builder_from_refund<'a, ES: EntropySource, R: Router, F>( &'a self, router: &R, entropy_source: ES, refund: &'a Refund, usable_channels: Vec, get_payment_info: F, ) -> Result, Bolt12SemanticError> where - ES::Target: EntropySource, - R::Target: Router, F: Fn(u64, u32) -> Result<(PaymentHash, PaymentSecret), Bolt12SemanticError>, { if refund.chain() != self.chain_hash { @@ -919,7 +872,7 @@ where } let expanded_key = &self.inbound_payment_key; - let entropy = &*entropy_source; + let entropy = &entropy_source; let amount_msats = refund.amount_msats(); let relative_expiry = DEFAULT_RELATIVE_EXPIRY.as_secs() as u32; @@ -974,12 +927,11 @@ where /// Returns a [`Bolt12SemanticError`] if: /// - Valid blinded payment paths could not be generated for the [`Bolt12Invoice`]. /// - The [`InvoiceBuilder`] could not be created from the [`InvoiceRequest`]. - pub fn create_invoice_builder_from_invoice_request_with_keys<'a, R: Deref, F>( + pub fn create_invoice_builder_from_invoice_request_with_keys<'a, R: Router, F>( &self, router: &R, invoice_request: &'a VerifiedInvoiceRequest, usable_channels: Vec, get_payment_info: F, ) -> Result<(InvoiceBuilder<'a, DerivedSigningPubkey>, MessageContext), Bolt12SemanticError> where - R::Target: Router, F: Fn(u64, u32) -> Result<(PaymentHash, PaymentSecret), Bolt12SemanticError>, { let relative_expiry = DEFAULT_RELATIVE_EXPIRY.as_secs() as u32; @@ -1034,12 +986,11 @@ where /// Returns a [`Bolt12SemanticError`] if: /// - Valid blinded payment paths could not be generated for the [`Bolt12Invoice`]. /// - The [`InvoiceBuilder`] could not be created from the [`InvoiceRequest`]. - pub fn create_invoice_builder_from_invoice_request_without_keys<'a, R: Deref, F>( + pub fn create_invoice_builder_from_invoice_request_without_keys<'a, R: Router, F>( &self, router: &R, invoice_request: &'a VerifiedInvoiceRequest, usable_channels: Vec, get_payment_info: F, ) -> Result<(InvoiceBuilder<'a, ExplicitSigningPubkey>, MessageContext), Bolt12SemanticError> where - R::Target: Router, F: Fn(u64, u32) -> Result<(PaymentHash, PaymentSecret), Bolt12SemanticError>, { let relative_expiry = DEFAULT_RELATIVE_EXPIRY.as_secs() as u32; @@ -1282,12 +1233,9 @@ where /// received to our node. /// /// [`ReleaseHeldHtlc`]: crate::onion_message::async_payments::ReleaseHeldHtlc - pub fn path_for_release_held_htlc( + pub fn path_for_release_held_htlc( &self, intercept_id: InterceptId, prev_outbound_scid_alias: u64, htlc_id: u64, entropy: ES, - ) -> BlindedMessagePath - where - ES::Target: EntropySource, - { + ) -> BlindedMessagePath { // In the future, we should support multi-hop paths here. let context = MessageContext::AsyncPayments(AsyncPaymentsContext::ReleaseHeldHtlc { intercept_id, @@ -1302,7 +1250,7 @@ where self.receive_auth_key, context, false, - &*entropy, + &entropy, &self.secp_ctx, ) } @@ -1389,13 +1337,10 @@ where /// the cache can self-regulate the number of messages sent out. /// /// Errors if we failed to create blinded reply paths when sending an [`OfferPathsRequest`] message. - pub fn check_refresh_async_receive_offer_cache( + pub fn check_refresh_async_receive_offer_cache( &self, peers: Vec, usable_channels: Vec, router: R, timer_tick_occurred: bool, - ) -> Result<(), ()> - where - R::Target: Router, - { + ) -> Result<(), ()> { // Terminate early if this node does not intend to receive async payments. { let cache = self.async_receive_offer_cache.lock().unwrap(); @@ -1464,11 +1409,9 @@ where /// Enqueue onion messages that will used to request invoice refresh from the static invoice /// server, based on the offers provided by the cache. - fn check_refresh_static_invoices( + fn check_refresh_static_invoices( &self, peers: Vec, usable_channels: Vec, router: R, - ) where - R::Target: Router, - { + ) { let mut serve_static_invoice_msgs = Vec::new(); { let duration_since_epoch = self.duration_since_epoch(); @@ -1481,7 +1424,7 @@ where offer_nonce, peers.clone(), usable_channels.clone(), - &*router, + &router, ) { Ok((invoice, path)) => (invoice, path), Err(()) => continue, @@ -1589,15 +1532,11 @@ where /// /// Returns `None` if we have enough offers cached already, verification of `message` fails, or we /// fail to create blinded paths. - pub fn handle_offer_paths( + pub fn handle_offer_paths( &self, message: OfferPaths, context: AsyncPaymentsContext, responder: Responder, peers: Vec, usable_channels: Vec, entropy: ES, router: R, - ) -> Option<(ServeStaticInvoice, MessageContext)> - where - ES::Target: EntropySource, - R::Target: Router, - { + ) -> Option<(ServeStaticInvoice, MessageContext)> { let duration_since_epoch = self.duration_since_epoch(); let invoice_slot = match context { AsyncPaymentsContext::OfferPaths { invoice_slot, path_absolute_expiry } => { @@ -1624,7 +1563,7 @@ where } let (mut offer_builder, offer_nonce) = - match self.create_async_receive_offer_builder(&*entropy, message.paths) { + match self.create_async_receive_offer_builder(&entropy, message.paths) { Ok((builder, nonce)) => (builder, nonce), Err(_) => return None, // Only reachable if OfferPaths::paths is empty }; @@ -1680,13 +1619,10 @@ where /// Creates a [`StaticInvoice`] and a blinded path for the server to forward invoice requests from /// payers to our node. - fn create_static_invoice_for_server( + fn create_static_invoice_for_server( &self, offer: &Offer, offer_nonce: Nonce, peers: Vec, usable_channels: Vec, router: R, - ) -> Result<(StaticInvoice, BlindedMessagePath), ()> - where - R::Target: Router, - { + ) -> Result<(StaticInvoice, BlindedMessagePath), ()> { let expanded_key = &self.inbound_payment_key; let duration_since_epoch = self.duration_since_epoch(); let secp_ctx = &self.secp_ctx; diff --git a/lightning/src/offers/nonce.rs b/lightning/src/offers/nonce.rs index 0675414125f..8c99a464abc 100644 --- a/lightning/src/offers/nonce.rs +++ b/lightning/src/offers/nonce.rs @@ -13,7 +13,6 @@ use crate::io::{self, Read}; use crate::ln::msgs::DecodeError; use crate::sign::EntropySource; use crate::util::ser::{Readable, Writeable, Writer}; -use core::ops::Deref; #[allow(unused_imports)] use crate::prelude::*; @@ -34,10 +33,7 @@ impl Nonce { pub const LENGTH: usize = 16; /// Creates a `Nonce` from the given [`EntropySource`]. - pub fn from_entropy_source(entropy_source: ES) -> Self - where - ES::Target: EntropySource, - { + pub fn from_entropy_source(entropy_source: ES) -> Self { let mut bytes = [0u8; Self::LENGTH]; let rand_bytes = entropy_source.get_secure_random_bytes(); bytes.copy_from_slice(&rand_bytes[..Self::LENGTH]); diff --git a/lightning/src/offers/refund.rs b/lightning/src/offers/refund.rs index dd2c3e2a92e..c0fd9dfdd3e 100644 --- a/lightning/src/offers/refund.rs +++ b/lightning/src/offers/refund.rs @@ -110,7 +110,6 @@ use bitcoin::constants::ChainHash; use bitcoin::network::Network; use bitcoin::secp256k1::{self, PublicKey, Secp256k1}; use core::hash::{Hash, Hasher}; -use core::ops::Deref; use core::str::FromStr; use core::time::Duration; @@ -624,13 +623,10 @@ macro_rules! respond_with_derived_signing_pubkey_methods { ($self: ident, $build /// /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice #[cfg(feature = "std")] - pub fn respond_using_derived_keys( + pub fn respond_using_derived_keys( &$self, payment_paths: Vec, payment_hash: PaymentHash, expanded_key: &ExpandedKey, entropy_source: ES - ) -> Result<$builder, Bolt12SemanticError> - where - ES::Target: EntropySource, - { + ) -> Result<$builder, Bolt12SemanticError> { let created_at = std::time::SystemTime::now() .duration_since(std::time::SystemTime::UNIX_EPOCH) .expect("SystemTime::now() should come after SystemTime::UNIX_EPOCH"); @@ -648,13 +644,10 @@ macro_rules! respond_with_derived_signing_pubkey_methods { ($self: ident, $build /// This is not exported to bindings users as builder patterns don't map outside of move semantics. /// /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice - pub fn respond_using_derived_keys_no_std( + pub fn respond_using_derived_keys_no_std( &$self, payment_paths: Vec, payment_hash: PaymentHash, created_at: core::time::Duration, expanded_key: &ExpandedKey, entropy_source: ES - ) -> Result<$builder, Bolt12SemanticError> - where - ES::Target: EntropySource, - { + ) -> Result<$builder, Bolt12SemanticError> { if $self.features().requires_unknown_bits() { return Err(Bolt12SemanticError::UnknownRequiredFeatures); } diff --git a/lightning/src/onion_message/async_payments.rs b/lightning/src/onion_message/async_payments.rs index 127126e150f..41108cdccd7 100644 --- a/lightning/src/onion_message/async_payments.rs +++ b/lightning/src/onion_message/async_payments.rs @@ -17,6 +17,7 @@ use crate::onion_message::messenger::{MessageSendInstructions, Responder, Respon use crate::onion_message::packet::OnionMessageContents; use crate::prelude::*; use crate::util::ser::{Readable, ReadableArgs, Writeable, Writer}; +use core::ops::Deref; // TLV record types for the `onionmsg_tlv` TLV stream as defined in BOLT 4. const OFFER_PATHS_REQ_TLV_TYPE: u64 = 75540; @@ -89,6 +90,45 @@ pub trait AsyncPaymentsMessageHandler { } } +impl> AsyncPaymentsMessageHandler + for A +{ + fn handle_offer_paths_request( + &self, message: OfferPathsRequest, context: AsyncPaymentsContext, + responder: Option, + ) -> Option<(OfferPaths, ResponseInstruction)> { + self.deref().handle_offer_paths_request(message, context, responder) + } + fn handle_offer_paths( + &self, message: OfferPaths, context: AsyncPaymentsContext, responder: Option, + ) -> Option<(ServeStaticInvoice, ResponseInstruction)> { + self.deref().handle_offer_paths(message, context, responder) + } + fn handle_serve_static_invoice( + &self, message: ServeStaticInvoice, context: AsyncPaymentsContext, + responder: Option, + ) { + self.deref().handle_serve_static_invoice(message, context, responder) + } + fn handle_static_invoice_persisted( + &self, message: StaticInvoicePersisted, context: AsyncPaymentsContext, + ) { + self.deref().handle_static_invoice_persisted(message, context) + } + fn handle_held_htlc_available( + &self, message: HeldHtlcAvailable, context: AsyncPaymentsContext, + responder: Option, + ) -> Option<(ReleaseHeldHtlc, ResponseInstruction)> { + self.deref().handle_held_htlc_available(message, context, responder) + } + fn handle_release_held_htlc(&self, message: ReleaseHeldHtlc, context: AsyncPaymentsContext) { + self.deref().handle_release_held_htlc(message, context) + } + fn release_pending_messages(&self) -> Vec<(AsyncPaymentsMessage, MessageSendInstructions)> { + self.deref().release_pending_messages() + } +} + /// Possible async payment messages sent and received via an [`OnionMessage`]. /// /// [`OnionMessage`]: crate::ln::msgs::OnionMessage diff --git a/lightning/src/onion_message/dns_resolution.rs b/lightning/src/onion_message/dns_resolution.rs index 47d4bc09e04..e857a359c78 100644 --- a/lightning/src/onion_message/dns_resolution.rs +++ b/lightning/src/onion_message/dns_resolution.rs @@ -37,6 +37,7 @@ use dnssec_prover::rr::Name; use lightning_types::features::NodeFeatures; use core::fmt; +use core::ops::Deref; use crate::blinded_path::message::DNSResolverContext; use crate::io; @@ -89,6 +90,23 @@ pub trait DNSResolverMessageHandler { } } +impl> DNSResolverMessageHandler for D { + fn handle_dnssec_query( + &self, message: DNSSECQuery, responder: Option, + ) -> Option<(DNSResolverMessage, ResponseInstruction)> { + self.deref().handle_dnssec_query(message, responder) + } + fn handle_dnssec_proof(&self, message: DNSSECProof, context: DNSResolverContext) { + self.deref().handle_dnssec_proof(message, context) + } + fn provided_node_features(&self) -> NodeFeatures { + self.deref().provided_node_features() + } + fn release_pending_messages(&self) -> Vec<(DNSResolverMessage, MessageSendInstructions)> { + self.deref().release_pending_messages() + } +} + #[derive(Clone, Debug, Hash, PartialEq, Eq)] /// An enum containing the possible onion messages which are used uses to request and receive /// DNSSEC proofs. diff --git a/lightning/src/onion_message/messenger.rs b/lightning/src/onion_message/messenger.rs index dbeab3937d0..e688c020ac6 100644 --- a/lightning/src/onion_message/messenger.rs +++ b/lightning/src/onion_message/messenger.rs @@ -66,50 +66,32 @@ pub(super) const MAX_TIMER_TICKS: usize = 2; /// languages. pub trait AOnionMessenger { /// A type implementing [`EntropySource`] - type EntropySource: EntropySource + ?Sized; - /// A type that may be dereferenced to [`Self::EntropySource`] - type ES: Deref; + type EntropySource: EntropySource; /// A type implementing [`NodeSigner`] - type NodeSigner: NodeSigner + ?Sized; - /// A type that may be dereferenced to [`Self::NodeSigner`] - type NS: Deref; + type NodeSigner: NodeSigner; /// A type implementing [`Logger`] - type Logger: Logger + ?Sized; - /// A type that may be dereferenced to [`Self::Logger`] - type L: Deref; + type Logger: Logger; /// A type implementing [`NodeIdLookUp`] - type NodeIdLookUp: NodeIdLookUp + ?Sized; - /// A type that may be dereferenced to [`Self::NodeIdLookUp`] - type NL: Deref; + type NL: NodeIdLookUp; /// A type implementing [`MessageRouter`] - type MessageRouter: MessageRouter + ?Sized; - /// A type that may be dereferenced to [`Self::MessageRouter`] - type MR: Deref; + type MessageRouter: MessageRouter; /// A type implementing [`OffersMessageHandler`] - type OffersMessageHandler: OffersMessageHandler + ?Sized; - /// A type that may be dereferenced to [`Self::OffersMessageHandler`] - type OMH: Deref; + type OMH: OffersMessageHandler; /// A type implementing [`AsyncPaymentsMessageHandler`] - type AsyncPaymentsMessageHandler: AsyncPaymentsMessageHandler + ?Sized; - /// A type that may be dereferenced to [`Self::AsyncPaymentsMessageHandler`] - type APH: Deref; + type APH: AsyncPaymentsMessageHandler; /// A type implementing [`DNSResolverMessageHandler`] - type DNSResolverMessageHandler: DNSResolverMessageHandler + ?Sized; - /// A type that may be dereferenced to [`Self::DNSResolverMessageHandler`] - type DRH: Deref; + type DRH: DNSResolverMessageHandler; /// A type implementing [`CustomOnionMessageHandler`] - type CustomOnionMessageHandler: CustomOnionMessageHandler + ?Sized; - /// A type that may be dereferenced to [`Self::CustomOnionMessageHandler`] - type CMH: Deref; + type CMH: CustomOnionMessageHandler; /// Returns a reference to the actual [`OnionMessenger`] object. fn get_om( &self, ) -> &OnionMessenger< - Self::ES, - Self::NS, - Self::L, + Self::EntropySource, + Self::NodeSigner, + Self::Logger, Self::NL, - Self::MR, + Self::MessageRouter, Self::OMH, Self::APH, Self::DRH, @@ -118,44 +100,25 @@ pub trait AOnionMessenger { } impl< - ES: Deref, - NS: Deref, - L: Deref, - NL: Deref, - MR: Deref, - OMH: Deref, - APH: Deref, - DRH: Deref, - CMH: Deref, + ES: EntropySource, + NS: NodeSigner, + L: Logger, + NL: NodeIdLookUp, + MR: MessageRouter, + OMH: OffersMessageHandler, + APH: AsyncPaymentsMessageHandler, + DRH: DNSResolverMessageHandler, + CMH: CustomOnionMessageHandler, > AOnionMessenger for OnionMessenger -where - ES::Target: EntropySource, - NS::Target: NodeSigner, - L::Target: Logger, - NL::Target: NodeIdLookUp, - MR::Target: MessageRouter, - OMH::Target: OffersMessageHandler, - APH::Target: AsyncPaymentsMessageHandler, - DRH::Target: DNSResolverMessageHandler, - CMH::Target: CustomOnionMessageHandler, { - type EntropySource = ES::Target; - type ES = ES; - type NodeSigner = NS::Target; - type NS = NS; - type Logger = L::Target; - type L = L; - type NodeIdLookUp = NL::Target; + type EntropySource = ES; + type NodeSigner = NS; + type Logger = L; type NL = NL; - type MessageRouter = MR::Target; - type MR = MR; - type OffersMessageHandler = OMH::Target; + type MessageRouter = MR; type OMH = OMH; - type AsyncPaymentsMessageHandler = APH::Target; type APH = APH; - type DNSResolverMessageHandler = DRH::Target; type DRH = DRH; - type CustomOnionMessageHandler = CMH::Target; type CMH = CMH; fn get_om(&self) -> &OnionMessenger { self @@ -284,26 +247,16 @@ where /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice pub struct OnionMessenger< - ES: Deref, - NS: Deref, - L: Deref, - NL: Deref, - MR: Deref, - OMH: Deref, - APH: Deref, - DRH: Deref, - CMH: Deref, -> where - ES::Target: EntropySource, - NS::Target: NodeSigner, - L::Target: Logger, - NL::Target: NodeIdLookUp, - MR::Target: MessageRouter, - OMH::Target: OffersMessageHandler, - APH::Target: AsyncPaymentsMessageHandler, - DRH::Target: DNSResolverMessageHandler, - CMH::Target: CustomOnionMessageHandler, -{ + ES: EntropySource, + NS: NodeSigner, + L: Logger, + NL: NodeIdLookUp, + MR: MessageRouter, + OMH: OffersMessageHandler, + APH: AsyncPaymentsMessageHandler, + DRH: DNSResolverMessageHandler, + CMH: CustomOnionMessageHandler, +> { entropy_source: ES, #[cfg(test)] pub(super) node_signer: NS, @@ -522,6 +475,27 @@ pub trait MessageRouter { ) -> Result, ()>; } +impl> MessageRouter for R { + fn find_path( + &self, sender: PublicKey, peers: Vec, destination: Destination, + ) -> Result { + self.deref().find_path(sender, peers, destination) + } + + fn create_blinded_paths( + &self, recipient: PublicKey, local_node_receive_key: ReceiveAuthKey, + context: MessageContext, peers: Vec, secp_ctx: &Secp256k1, + ) -> Result, ()> { + self.deref().create_blinded_paths( + recipient, + local_node_receive_key, + context, + peers, + secp_ctx, + ) + } +} + /// A [`MessageRouter`] that can only route to a directly connected [`Destination`]. /// /// [`DefaultMessageRouter`] tries to construct compact or private [`BlindedMessagePath`]s based on @@ -549,11 +523,7 @@ pub trait MessageRouter { /// node. Otherwise, there is no way to find a path to the introduction node in order to send a /// message, and thus an `Err` is returned. The impact of this may be somewhat muted when /// additional dummy hops are added to the blinded path, but this protection is not complete. -pub struct DefaultMessageRouter>, L: Deref, ES: Deref> -where - L::Target: Logger, - ES::Target: EntropySource, -{ +pub struct DefaultMessageRouter>, L: Logger, ES: EntropySource> { network_graph: G, entropy_source: ES, } @@ -569,10 +539,8 @@ pub(crate) const DUMMY_HOPS_PATH_LENGTH: usize = 4; // We add dummy hops until the path reaches this length (including the recipient). pub(crate) const QR_CODED_DUMMY_HOPS_PATH_LENGTH: usize = 2; -impl>, L: Deref, ES: Deref> DefaultMessageRouter -where - L::Target: Logger, - ES::Target: EntropySource, +impl>, L: Logger, ES: EntropySource> + DefaultMessageRouter { /// Creates a [`DefaultMessageRouter`] using the given [`NetworkGraph`]. pub fn new(network_graph: G, entropy_source: ES) -> Self { @@ -660,7 +628,7 @@ where local_node_receive_key, context.clone(), size_constrained, - &**entropy_source, + &entropy_source, secp_ctx, ) }; @@ -738,11 +706,8 @@ where } } -impl>, L: Deref, ES: Deref> MessageRouter +impl>, L: Logger, ES: EntropySource> MessageRouter for DefaultMessageRouter -where - L::Target: Logger, - ES::Target: EntropySource, { fn find_path( &self, sender: PublicKey, peers: Vec, destination: Destination, @@ -784,19 +749,13 @@ where /// node. Otherwise, there is no way to find a path to the introduction node in order to send a /// message, and thus an `Err` is returned. The impact of this may be somewhat muted when /// additional dummy hops are added to the blinded path, but this protection is not complete. -pub struct NodeIdMessageRouter>, L: Deref, ES: Deref> -where - L::Target: Logger, - ES::Target: EntropySource, -{ +pub struct NodeIdMessageRouter>, L: Logger, ES: EntropySource> { network_graph: G, entropy_source: ES, } -impl>, L: Deref, ES: Deref> NodeIdMessageRouter -where - L::Target: Logger, - ES::Target: EntropySource, +impl>, L: Logger, ES: EntropySource> + NodeIdMessageRouter { /// Creates a [`NodeIdMessageRouter`] using the given [`NetworkGraph`]. pub fn new(network_graph: G, entropy_source: ES) -> Self { @@ -804,11 +763,8 @@ where } } -impl>, L: Deref, ES: Deref> MessageRouter +impl>, L: Logger, ES: EntropySource> MessageRouter for NodeIdMessageRouter -where - L::Target: Logger, - ES::Target: EntropySource, { fn find_path( &self, sender: PublicKey, peers: Vec, destination: Destination, @@ -1029,6 +985,25 @@ pub trait CustomOnionMessageHandler { ) -> Vec<(Self::CustomMessage, MessageSendInstructions)>; } +impl> CustomOnionMessageHandler for C { + type CustomMessage = T::CustomMessage; + fn handle_custom_message( + &self, message: Self::CustomMessage, context: Option>, responder: Option, + ) -> Option<(Self::CustomMessage, ResponseInstruction)> { + self.deref().handle_custom_message(message, context, responder) + } + fn read_custom_message( + &self, message_type: u64, buffer: &mut R, + ) -> Result, msgs::DecodeError> { + self.deref().read_custom_message(message_type, buffer) + } + fn release_pending_custom_messages( + &self, + ) -> Vec<(Self::CustomMessage, MessageSendInstructions)> { + self.deref().release_pending_custom_messages() + } +} + /// A processed incoming onion message, containing either a Forward (another onion message) /// or a Receive payload with decrypted contents. #[derive(Clone, Debug)] @@ -1052,20 +1027,15 @@ pub enum PeeledOnion { /// Returns the node id of the peer to send the message to, the message itself, and any addresses /// needed to connect to the first node. pub fn create_onion_message_resolving_destination< - ES: Deref, - NS: Deref, - NL: Deref, + ES: EntropySource, + NS: NodeSigner, + NL: NodeIdLookUp, T: OnionMessageContents, >( entropy_source: &ES, node_signer: &NS, node_id_lookup: &NL, network_graph: &ReadOnlyNetworkGraph, secp_ctx: &Secp256k1, mut path: OnionMessagePath, contents: T, reply_path: Option, -) -> Result<(PublicKey, OnionMessage, Vec), SendError> -where - ES::Target: EntropySource, - NS::Target: NodeSigner, - NL::Target: NodeIdLookUp, -{ +) -> Result<(PublicKey, OnionMessage, Vec), SendError> { path.destination.resolve(network_graph); create_onion_message( entropy_source, @@ -1089,16 +1059,16 @@ where /// - unless it can be resolved by [`NodeIdLookUp::next_node_id`]. /// Use [`create_onion_message_resolving_destination`] instead to resolve the introduction node /// first with a [`ReadOnlyNetworkGraph`]. -pub fn create_onion_message( +pub fn create_onion_message< + ES: EntropySource, + NS: NodeSigner, + NL: NodeIdLookUp, + T: OnionMessageContents, +>( entropy_source: &ES, node_signer: &NS, node_id_lookup: &NL, secp_ctx: &Secp256k1, path: OnionMessagePath, contents: T, reply_path: Option, -) -> Result<(PublicKey, OnionMessage, Vec), SendError> -where - ES::Target: EntropySource, - NS::Target: NodeSigner, - NL::Target: NodeIdLookUp, -{ +) -> Result<(PublicKey, OnionMessage, Vec), SendError> { let OnionMessagePath { intermediate_nodes, mut destination, first_node_addresses } = path; if let Destination::BlindedPath(ref path) = destination { if path.blinded_hops().is_empty() { @@ -1171,15 +1141,10 @@ where /// /// Returns either the next layer of the onion for forwarding or the decrypted content for the /// receiver. -pub fn peel_onion_message( +pub fn peel_onion_message( msg: &OnionMessage, secp_ctx: &Secp256k1, node_signer: NS, logger: L, custom_handler: CMH, -) -> Result::Target as CustomOnionMessageHandler>::CustomMessage>, ()> -where - NS::Target: NodeSigner, - L::Target: Logger, - CMH::Target: CustomOnionMessageHandler, -{ +) -> Result, ()> { let control_tlvs_ss = match node_signer.ecdh(Recipient::Node, &msg.blinding_point, None) { Ok(ss) => ss, Err(e) => { @@ -1208,7 +1173,7 @@ where onion_decode_ss, &msg.onion_routing_packet.hop_data[..], msg.onion_routing_packet.hmac, - (control_tlvs_ss, custom_handler.deref(), receiving_context_auth_key, logger.deref()), + (control_tlvs_ss, &custom_handler, receiving_context_auth_key, &logger), ); // Constructs the next onion message using packet data and blinding logic. @@ -1394,26 +1359,16 @@ macro_rules! drop_handled_events_and_abort { } impl< - ES: Deref, - NS: Deref, - L: Deref, - NL: Deref, - MR: Deref, - OMH: Deref, - APH: Deref, - DRH: Deref, - CMH: Deref, + ES: EntropySource, + NS: NodeSigner, + L: Logger, + NL: NodeIdLookUp, + MR: MessageRouter, + OMH: OffersMessageHandler, + APH: AsyncPaymentsMessageHandler, + DRH: DNSResolverMessageHandler, + CMH: CustomOnionMessageHandler, > OnionMessenger -where - ES::Target: EntropySource, - NS::Target: NodeSigner, - L::Target: Logger, - NL::Target: NodeIdLookUp, - MR::Target: MessageRouter, - OMH::Target: OffersMessageHandler, - APH::Target: AsyncPaymentsMessageHandler, - DRH::Target: DNSResolverMessageHandler, - CMH::Target: CustomOnionMessageHandler, { /// Constructs a new `OnionMessenger` to send, forward, and delegate received onion messages to /// their respective handlers. @@ -1804,13 +1759,13 @@ where pub(crate) fn peel_onion_message( &self, msg: &OnionMessage, - ) -> Result::Target as CustomOnionMessageHandler>::CustomMessage>, ()> { + ) -> Result, ()> { peel_onion_message( msg, &self.secp_ctx, - &*self.node_signer, - &*self.logger, - &*self.custom_handler, + &self.node_signer, + &self.logger, + &self.custom_handler, ) } @@ -2038,26 +1993,16 @@ fn outbound_buffer_full( } impl< - ES: Deref, - NS: Deref, - L: Deref, - NL: Deref, - MR: Deref, - OMH: Deref, - APH: Deref, - DRH: Deref, - CMH: Deref, + ES: EntropySource, + NS: NodeSigner, + L: Logger, + NL: NodeIdLookUp, + MR: MessageRouter, + OMH: OffersMessageHandler, + APH: AsyncPaymentsMessageHandler, + DRH: DNSResolverMessageHandler, + CMH: CustomOnionMessageHandler, > EventsProvider for OnionMessenger -where - ES::Target: EntropySource, - NS::Target: NodeSigner, - L::Target: Logger, - NL::Target: NodeIdLookUp, - MR::Target: MessageRouter, - OMH::Target: OffersMessageHandler, - APH::Target: AsyncPaymentsMessageHandler, - DRH::Target: DNSResolverMessageHandler, - CMH::Target: CustomOnionMessageHandler, { fn process_pending_events(&self, handler: H) where @@ -2159,26 +2104,16 @@ where } impl< - ES: Deref, - NS: Deref, - L: Deref, - NL: Deref, - MR: Deref, - OMH: Deref, - APH: Deref, - DRH: Deref, - CMH: Deref, + ES: EntropySource, + NS: NodeSigner, + L: Logger, + NL: NodeIdLookUp, + MR: MessageRouter, + OMH: OffersMessageHandler, + APH: AsyncPaymentsMessageHandler, + DRH: DNSResolverMessageHandler, + CMH: CustomOnionMessageHandler, > BaseMessageHandler for OnionMessenger -where - ES::Target: EntropySource, - NS::Target: NodeSigner, - L::Target: Logger, - NL::Target: NodeIdLookUp, - MR::Target: MessageRouter, - OMH::Target: OffersMessageHandler, - APH::Target: AsyncPaymentsMessageHandler, - DRH::Target: DNSResolverMessageHandler, - CMH::Target: CustomOnionMessageHandler, { fn provided_node_features(&self) -> NodeFeatures { let mut features = NodeFeatures::empty(); @@ -2231,26 +2166,16 @@ where } impl< - ES: Deref, - NS: Deref, - L: Deref, - NL: Deref, - MR: Deref, - OMH: Deref, - APH: Deref, - DRH: Deref, - CMH: Deref, + ES: EntropySource, + NS: NodeSigner, + L: Logger, + NL: NodeIdLookUp, + MR: MessageRouter, + OMH: OffersMessageHandler, + APH: AsyncPaymentsMessageHandler, + DRH: DNSResolverMessageHandler, + CMH: CustomOnionMessageHandler, > OnionMessageHandler for OnionMessenger -where - ES::Target: EntropySource, - NS::Target: NodeSigner, - L::Target: Logger, - NL::Target: NodeIdLookUp, - MR::Target: MessageRouter, - OMH::Target: OffersMessageHandler, - APH::Target: AsyncPaymentsMessageHandler, - DRH::Target: DNSResolverMessageHandler, - CMH::Target: CustomOnionMessageHandler, { fn handle_onion_message(&self, peer_node_id: PublicKey, msg: &OnionMessage) { let logger = WithContext::from(&self.logger, Some(peer_node_id), None, None); diff --git a/lightning/src/onion_message/offers.rs b/lightning/src/onion_message/offers.rs index 06988d4db8f..8e3afdfa977 100644 --- a/lightning/src/onion_message/offers.rs +++ b/lightning/src/onion_message/offers.rs @@ -22,6 +22,7 @@ use crate::onion_message::packet::OnionMessageContents; use crate::util::logger::Logger; use crate::util::ser::{Readable, ReadableArgs, Writeable, Writer}; use core::fmt; +use core::ops::Deref; use crate::prelude::*; @@ -63,6 +64,17 @@ pub trait OffersMessageHandler { } } +impl> OffersMessageHandler for O { + fn handle_message( + &self, message: OffersMessage, context: Option, responder: Option, + ) -> Option<(OffersMessage, ResponseInstruction)> { + self.deref().handle_message(message, context, responder) + } + fn release_pending_messages(&self) -> Vec<(OffersMessage, MessageSendInstructions)> { + self.deref().release_pending_messages() + } +} + /// Possible BOLT 12 Offers messages sent and received via an [`OnionMessage`]. /// /// [`OnionMessage`]: crate::ln::msgs::OnionMessage diff --git a/lightning/src/routing/gossip.rs b/lightning/src/routing/gossip.rs index 040a28cddae..2dcce844b2b 100644 --- a/lightning/src/routing/gossip.rs +++ b/lightning/src/routing/gossip.rs @@ -184,10 +184,7 @@ impl FromStr for NodeId { } /// Represents the network as nodes and channels between them -pub struct NetworkGraph -where - L::Target: Logger, -{ +pub struct NetworkGraph { secp_ctx: Secp256k1, last_rapid_gossip_sync_timestamp: Mutex>, chain_hash: ChainHash, @@ -322,10 +319,9 @@ impl MaybeReadable for NetworkUpdate { /// This network graph is then used for routing payments. /// Provides interface to help with initial routing sync by /// serving historical announcements. -pub struct P2PGossipSync>, U: Deref, L: Deref> +pub struct P2PGossipSync>, U: Deref, L: Logger> where U::Target: UtxoLookup, - L::Target: Logger, { network_graph: G, #[cfg(any(feature = "_test_utils", test))] @@ -337,10 +333,9 @@ where logger: L, } -impl>, U: Deref, L: Deref> P2PGossipSync +impl>, U: Deref, L: Logger> P2PGossipSync where U::Target: UtxoLookup, - L::Target: Logger, { /// Creates a new tracker of the actual state of the network of channels and nodes, /// assuming an existing [`NetworkGraph`]. @@ -426,10 +421,7 @@ where } } -impl NetworkGraph -where - L::Target: Logger, -{ +impl NetworkGraph { /// Handles any network updates originating from [`Event`]s. /// /// [`Event`]: crate::events::Event @@ -542,11 +534,10 @@ pub fn verify_channel_announcement( Ok(()) } -impl>, U: Deref, L: Deref> RoutingMessageHandler +impl>, U: Deref, L: Logger> RoutingMessageHandler for P2PGossipSync where U::Target: UtxoLookup, - L::Target: Logger, { fn handle_node_announcement( &self, _their_node_id: Option, msg: &msgs::NodeAnnouncement, @@ -770,11 +761,10 @@ where } } -impl>, U: Deref, L: Deref> BaseMessageHandler +impl>, U: Deref, L: Logger> BaseMessageHandler for P2PGossipSync where U::Target: UtxoLookup, - L::Target: Logger, { /// Initiates a stateless sync of routing gossip information with a peer /// using [`gossip_queries`]. The default strategy used by this implementation @@ -1644,10 +1634,7 @@ impl Readable for NodeInfo { const SERIALIZATION_VERSION: u8 = 1; const MIN_SERIALIZATION_VERSION: u8 = 1; -impl Writeable for NetworkGraph -where - L::Target: Logger, -{ +impl Writeable for NetworkGraph { fn write(&self, writer: &mut W) -> Result<(), io::Error> { self.test_node_counter_consistency(); @@ -1675,10 +1662,7 @@ where } } -impl ReadableArgs for NetworkGraph -where - L::Target: Logger, -{ +impl ReadableArgs for NetworkGraph { fn read(reader: &mut R, logger: L) -> Result, DecodeError> { let _ver = read_ver_prefix!(reader, SERIALIZATION_VERSION); @@ -1732,10 +1716,7 @@ where } } -impl fmt::Display for NetworkGraph -where - L::Target: Logger, -{ +impl fmt::Display for NetworkGraph { fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { writeln!(f, "Network map\n[Channels]")?; for (key, val) in self.channels.read().unwrap().unordered_iter() { @@ -1749,11 +1730,8 @@ where } } -impl Eq for NetworkGraph where L::Target: Logger {} -impl PartialEq for NetworkGraph -where - L::Target: Logger, -{ +impl Eq for NetworkGraph {} +impl PartialEq for NetworkGraph { fn eq(&self, other: &Self) -> bool { // For a total lockorder, sort by position in memory and take the inner locks in that order. // (Assumes that we can't move within memory while a lock is held). @@ -1781,10 +1759,7 @@ const CHAN_COUNT_ESTIMATE: usize = 60_000; // too low const NODE_COUNT_ESTIMATE: usize = 20_000; -impl NetworkGraph -where - L::Target: Logger, -{ +impl NetworkGraph { /// Creates a new, empty, network graph. pub fn new(network: Network, logger: L) -> NetworkGraph { Self { diff --git a/lightning/src/routing/router.rs b/lightning/src/routing/router.rs index 40580a09c8c..703a8173d8f 100644 --- a/lightning/src/routing/router.rs +++ b/lightning/src/routing/router.rs @@ -57,15 +57,13 @@ pub use lightning_types::routing::{RouteHint, RouteHintHop}; /// payment, and thus an `Err` is returned. pub struct DefaultRouter< G: Deref>, - L: Deref, - ES: Deref, + L: Logger, + ES: EntropySource, S: Deref, SP: Sized, Sc: ScoreLookUp, > where - L::Target: Logger, S::Target: for<'a> LockableScore<'a, ScoreLookUp = Sc>, - ES::Target: EntropySource, { network_graph: G, logger: L, @@ -76,16 +74,14 @@ pub struct DefaultRouter< impl< G: Deref>, - L: Deref, - ES: Deref, + L: Logger, + ES: EntropySource, S: Deref, SP: Sized, Sc: ScoreLookUp, > DefaultRouter where - L::Target: Logger, S::Target: for<'a> LockableScore<'a, ScoreLookUp = Sc>, - ES::Target: EntropySource, { /// Creates a new router. pub fn new( @@ -97,16 +93,14 @@ where impl< G: Deref>, - L: Deref, - ES: Deref, + L: Logger, + ES: EntropySource, S: Deref, SP: Sized, Sc: ScoreLookUp, > Router for DefaultRouter where - L::Target: Logger, S::Target: for<'a> LockableScore<'a, ScoreLookUp = Sc>, - ES::Target: EntropySource, { #[rustfmt::skip] fn find_route( @@ -118,7 +112,7 @@ where ) -> Result { let random_seed_bytes = self.entropy_source.get_secure_random_bytes(); find_route( - payer, params, &self.network_graph, first_hops, &*self.logger, + payer, params, &self.network_graph, first_hops, &self.logger, &ScorerAccountingForInFlightHtlcs::new(self.scorer.read_lock(), &inflight_htlcs), &self.score_params, &random_seed_bytes @@ -200,7 +194,7 @@ where .map(|forward_node| { BlindedPaymentPath::new( &[forward_node], recipient, local_node_receive_key, tlvs.clone(), u64::MAX, MIN_FINAL_CLTV_EXPIRY_DELTA, - &*self.entropy_source, secp_ctx + &self.entropy_source, secp_ctx ) }) .take(MAX_PAYMENT_PATHS) @@ -211,7 +205,7 @@ where _ => { if network_graph.nodes().contains_key(&NodeId::from_pubkey(&recipient)) { BlindedPaymentPath::new( - &[], recipient, local_node_receive_key, tlvs, u64::MAX, MIN_FINAL_CLTV_EXPIRY_DELTA, &*self.entropy_source, + &[], recipient, local_node_receive_key, tlvs, u64::MAX, MIN_FINAL_CLTV_EXPIRY_DELTA, &self.entropy_source, secp_ctx ).map(|path| vec![path]) } else { @@ -292,6 +286,45 @@ pub trait Router { ) -> Result, ()>; } +impl> Router for R { + fn find_route( + &self, payer: &PublicKey, route_params: &RouteParameters, + first_hops: Option<&[&ChannelDetails]>, inflight_htlcs: InFlightHtlcs, + ) -> Result { + self.deref().find_route(payer, route_params, first_hops, inflight_htlcs) + } + + fn find_route_with_id( + &self, payer: &PublicKey, route_params: &RouteParameters, + first_hops: Option<&[&ChannelDetails]>, inflight_htlcs: InFlightHtlcs, + payment_hash: PaymentHash, payment_id: PaymentId, + ) -> Result { + self.deref().find_route_with_id( + payer, + route_params, + first_hops, + inflight_htlcs, + payment_hash, + payment_id, + ) + } + + fn create_blinded_payment_paths( + &self, recipient: PublicKey, local_node_receive_key: ReceiveAuthKey, + first_hops: Vec, tlvs: ReceiveTlvs, amount_msats: Option, + secp_ctx: &Secp256k1, + ) -> Result, ()> { + self.deref().create_blinded_payment_paths( + recipient, + local_node_receive_key, + first_hops, + tlvs, + amount_msats, + secp_ctx, + ) + } +} + /// [`ScoreLookUp`] implementation that factors in in-flight HTLC liquidity. /// /// Useful for custom [`Router`] implementations to wrap their [`ScoreLookUp`] on-the-fly when calling @@ -1945,12 +1978,11 @@ 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>( +fn calculate_blinded_path_intro_points<'a, L: Logger>( payment_params: &PaymentParameters, node_counters: &'a NodeCounters, network_graph: &ReadOnlyNetworkGraph, logger: &L, our_node_id: NodeId, first_hop_targets: &HashMap, u32)>, -) -> Result>, &'static str> -where L::Target: Logger { +) -> Result>, &'static str> { let introduction_node_id_cache = payment_params.payee.blinded_route_hints().iter() .map(|path| { match path.introduction_node() { @@ -2451,12 +2483,11 @@ fn sort_first_hop_channels( /// [`Event::PaymentPathFailed`]: crate::events::Event::PaymentPathFailed /// [`NetworkGraph`]: crate::routing::gossip::NetworkGraph #[rustfmt::skip] -pub fn find_route( +pub fn find_route( our_node_pubkey: &PublicKey, route_params: &RouteParameters, network_graph: &NetworkGraph, first_hops: Option<&[&ChannelDetails]>, logger: L, scorer: &S, score_params: &S::ScoreParams, random_seed_bytes: &[u8; 32] -) -> Result -where L::Target: Logger, GL::Target: Logger { +) -> Result { let graph_lock = network_graph.read_only(); let mut route = get_route(our_node_pubkey, &route_params, &graph_lock, first_hops, logger, scorer, score_params, random_seed_bytes)?; @@ -2465,12 +2496,11 @@ where L::Target: Logger, GL::Target: Logger { } #[rustfmt::skip] -pub(crate) fn get_route( +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, _random_seed_bytes: &[u8; 32] -) -> Result -where L::Target: Logger { +) -> Result { let payment_params = &route_params.payment_params; let max_path_length = core::cmp::min(payment_params.max_path_length, MAX_PATH_LENGTH_ESTIMATE); @@ -3854,11 +3884,10 @@ fn add_random_cltv_offset(route: &mut Route, payment_params: &PaymentParameters, /// /// Re-uses logic from `find_route`, so the restrictions described there also apply here. #[rustfmt::skip] -pub fn build_route_from_hops( +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] -) -> Result -where L::Target: Logger, GL::Target: Logger { +) -> Result { let graph_lock = network_graph.read_only(); let mut route = build_route_from_hops_internal(our_node_pubkey, hops, &route_params, &graph_lock, logger, random_seed_bytes)?; @@ -3867,10 +3896,10 @@ where L::Target: Logger, GL::Target: Logger { } #[rustfmt::skip] -fn build_route_from_hops_internal( +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], -) -> Result where L::Target: Logger { +) -> Result { struct HopScorer { our_node_id: NodeId, diff --git a/lightning/src/routing/scoring.rs b/lightning/src/routing/scoring.rs index d741adf58d3..47621e37380 100644 --- a/lightning/src/routing/scoring.rs +++ b/lightning/src/routing/scoring.rs @@ -479,10 +479,7 @@ impl ReadableArgs for FixedPenaltyScorer { /// [`liquidity_offset_half_life`]: ProbabilisticScoringDecayParameters::liquidity_offset_half_life /// [`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, -{ +pub struct ProbabilisticScorer>, L: Logger> { decay_params: ProbabilisticScoringDecayParameters, network_graph: G, logger: L, @@ -964,10 +961,7 @@ struct DirectedChannelLiquidity< last_datapoint_time: T, } -impl>, L: Deref> ProbabilisticScorer -where - L::Target: Logger, -{ +impl>, L: Logger> ProbabilisticScorer { /// Creates a new scorer using the given scoring parameters for sending payments from a node /// through a network graph. pub fn new( @@ -1593,9 +1587,9 @@ impl< { /// Adjusts the channel liquidity balance bounds when failing to route `amount_msat`. #[rustfmt::skip] - fn failed_at_channel( + fn failed_at_channel( &mut self, amount_msat: u64, duration_since_epoch: Duration, chan_descr: fmt::Arguments, logger: &Log - ) where Log::Target: Logger { + ) { let existing_max_msat = self.max_liquidity_msat(); if amount_msat < existing_max_msat { log_debug!(logger, "Setting max liquidity of {} from {} to {}", chan_descr, existing_max_msat, amount_msat); @@ -1610,9 +1604,9 @@ impl< /// Adjusts the channel liquidity balance bounds when failing to route `amount_msat` downstream. #[rustfmt::skip] - fn failed_downstream( + fn failed_downstream( &mut self, amount_msat: u64, duration_since_epoch: Duration, chan_descr: fmt::Arguments, logger: &Log - ) where Log::Target: Logger { + ) { let existing_min_msat = self.min_liquidity_msat(); if amount_msat > existing_min_msat { log_debug!(logger, "Setting min liquidity of {} from {} to {}", existing_min_msat, chan_descr, amount_msat); @@ -1627,9 +1621,9 @@ impl< /// Adjusts the channel liquidity balance bounds when successfully routing `amount_msat`. #[rustfmt::skip] - fn successful(&mut self, + fn successful(&mut self, amount_msat: u64, duration_since_epoch: Duration, chan_descr: fmt::Arguments, logger: &Log - ) where Log::Target: Logger { + ) { let max_liquidity_msat = self.max_liquidity_msat().checked_sub(amount_msat).unwrap_or(0); log_debug!(logger, "Subtracting {} from max liquidity of {} (setting it to {})", amount_msat, chan_descr, max_liquidity_msat); self.set_max_liquidity_msat(max_liquidity_msat, duration_since_epoch); @@ -1669,10 +1663,7 @@ impl< } } -impl>, L: Deref> ScoreLookUp for ProbabilisticScorer -where - L::Target: Logger, -{ +impl>, L: Logger> ScoreLookUp for ProbabilisticScorer { type ScoreParams = ProbabilisticScoringFeeParameters; #[rustfmt::skip] fn channel_penalty_msat( @@ -1735,10 +1726,7 @@ where } } -impl>, L: Deref> ScoreUpdate for ProbabilisticScorer -where - L::Target: Logger, -{ +impl>, L: Logger> ScoreUpdate for ProbabilisticScorer { #[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(); @@ -1836,18 +1824,12 @@ where /// /// 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: Logger> { local_only_scorer: ProbabilisticScorer, scorer: ProbabilisticScorer, } -impl> + Clone, L: Deref + Clone> CombinedScorer -where - L::Target: Logger, -{ +impl> + Clone, L: Logger + Clone> CombinedScorer { /// Create a new combined scorer with the given local scorer. #[rustfmt::skip] pub fn new(local_scorer: ProbabilisticScorer) -> Self { @@ -1889,10 +1871,7 @@ where } } -impl>, L: Deref> ScoreLookUp for CombinedScorer -where - L::Target: Logger, -{ +impl>, L: Logger> ScoreLookUp for CombinedScorer { type ScoreParams = ProbabilisticScoringFeeParameters; fn channel_penalty_msat( @@ -1903,10 +1882,7 @@ where } } -impl>, L: Deref> ScoreUpdate for CombinedScorer -where - L::Target: Logger, -{ +impl>, L: Logger> ScoreUpdate for CombinedScorer { fn payment_path_failed( &mut self, path: &Path, short_channel_id: u64, duration_since_epoch: Duration, ) { @@ -1935,20 +1911,14 @@ where } } -impl>, L: Deref> Writeable for CombinedScorer -where - L::Target: Logger, -{ +impl>, L: Logger> Writeable for CombinedScorer { 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: Logger> Score for ProbabilisticScorer {} #[cfg(feature = "std")] #[inline] @@ -2520,20 +2490,15 @@ mod bucketed_history { } } -impl>, L: Deref> Writeable for ProbabilisticScorer -where - L::Target: Logger, -{ +impl>, L: Logger> Writeable for ProbabilisticScorer { #[inline] fn write(&self, w: &mut W) -> Result<(), io::Error> { self.channel_liquidities.write(w) } } -impl>, L: Deref> +impl>, L: Logger> ReadableArgs<(ProbabilisticScoringDecayParameters, G, L)> for ProbabilisticScorer -where - L::Target: Logger, { #[inline] #[rustfmt::skip] diff --git a/lightning/src/routing/utxo.rs b/lightning/src/routing/utxo.rs index f46160f1f14..31f4de5dee0 100644 --- a/lightning/src/routing/utxo.rs +++ b/lightning/src/routing/utxo.rs @@ -439,12 +439,10 @@ impl PendingChecks { } } - fn resolve_single_future( + fn resolve_single_future( &self, graph: &NetworkGraph, entry: Arc>, new_messages: &mut Vec, - ) where - L::Target: Logger, - { + ) { let (announcement, result, announce_a, announce_b, update_a, update_b); { let mut state = entry.lock().unwrap(); @@ -529,12 +527,9 @@ impl PendingChecks { } } - pub(super) fn check_resolved_futures( + pub(super) fn check_resolved_futures( &self, graph: &NetworkGraph, - ) -> Vec - where - L::Target: Logger, - { + ) -> Vec { let mut completed_states = Vec::new(); { let mut lck = self.internal.lock().unwrap(); diff --git a/lightning/src/sign/mod.rs b/lightning/src/sign/mod.rs index 26252c74dd2..b05f11b35a9 100644 --- a/lightning/src/sign/mod.rs +++ b/lightning/src/sign/mod.rs @@ -878,6 +878,12 @@ pub trait EntropySource { fn get_secure_random_bytes(&self) -> [u8; 32]; } +impl> EntropySource for E { + fn get_secure_random_bytes(&self) -> [u8; 32] { + self.deref().get_secure_random_bytes() + } +} + /// A trait that can handle cryptographic operations at the scope level of a node. pub trait NodeSigner { /// Get the [`ExpandedKey`] which provides cryptographic material for various Lightning Network operations. @@ -992,6 +998,42 @@ pub trait NodeSigner { fn sign_message(&self, msg: &[u8]) -> Result; } +impl> NodeSigner for N { + fn get_expanded_key(&self) -> ExpandedKey { + self.deref().get_expanded_key() + } + fn get_peer_storage_key(&self) -> PeerStorageKey { + self.deref().get_peer_storage_key() + } + fn get_receive_auth_key(&self) -> ReceiveAuthKey { + self.deref().get_receive_auth_key() + } + fn get_node_id(&self, recipient: Recipient) -> Result { + self.deref().get_node_id(recipient) + } + fn ecdh( + &self, recipient: Recipient, other_key: &PublicKey, tweak: Option<&Scalar>, + ) -> Result { + self.deref().ecdh(recipient, other_key, tweak) + } + fn sign_invoice( + &self, invoice: &RawBolt11Invoice, recipient: Recipient, + ) -> Result { + self.deref().sign_invoice(invoice, recipient) + } + fn sign_bolt12_invoice( + &self, invoice: &UnsignedBolt12Invoice, + ) -> Result { + self.deref().sign_bolt12_invoice(invoice) + } + fn sign_gossip_message(&self, msg: UnsignedGossipMessage) -> Result { + self.deref().sign_gossip_message(msg) + } + fn sign_message(&self, msg: &[u8]) -> Result { + self.deref().sign_message(msg) + } +} + /// A trait that describes a wallet capable of creating a spending [`Transaction`] from a set of /// [`SpendableOutputDescriptor`]s. pub trait OutputSpender { @@ -1076,6 +1118,28 @@ pub trait SignerProvider { fn get_shutdown_scriptpubkey(&self) -> Result; } +impl> SignerProvider for SP { + type EcdsaSigner = T::EcdsaSigner; + #[cfg(taproot)] + type TaprootSigner = T::TaprootSigner; + + fn generate_channel_keys_id(&self, inbound: bool, user_channel_id: u128) -> [u8; 32] { + self.deref().generate_channel_keys_id(inbound, user_channel_id) + } + + fn derive_channel_signer(&self, channel_keys_id: [u8; 32]) -> Self::EcdsaSigner { + self.deref().derive_channel_signer(channel_keys_id) + } + + fn get_destination_script(&self, channel_keys_id: [u8; 32]) -> Result { + self.deref().get_destination_script(channel_keys_id) + } + + fn get_shutdown_scriptpubkey(&self) -> Result { + self.deref().get_shutdown_scriptpubkey() + } +} + /// A helper trait that describes an on-chain wallet capable of returning a (change) destination /// script. /// diff --git a/lightning/src/sign/tx_builder.rs b/lightning/src/sign/tx_builder.rs index 74941ec8a87..27b8b1a9a2b 100644 --- a/lightning/src/sign/tx_builder.rs +++ b/lightning/src/sign/tx_builder.rs @@ -2,7 +2,6 @@ #![allow(dead_code)] use core::cmp; -use core::ops::Deref; use bitcoin::secp256k1::{self, PublicKey, Secp256k1}; @@ -169,14 +168,12 @@ pub(crate) trait TxBuilder { &self, is_outbound_from_holder: bool, value_to_self_after_htlcs: u64, value_to_remote_after_htlcs: u64, channel_type: &ChannelTypeFeatures, ) -> (u64, u64); - fn build_commitment_transaction( + fn build_commitment_transaction( &self, local: bool, commitment_number: u64, per_commitment_point: &PublicKey, channel_parameters: &ChannelTransactionParameters, secp_ctx: &Secp256k1, value_to_self_msat: u64, htlcs_in_tx: Vec, feerate_per_kw: u32, broadcaster_dust_limit_satoshis: u64, logger: &L, - ) -> (CommitmentTransaction, CommitmentStats) - where - L::Target: Logger; + ) -> (CommitmentTransaction, CommitmentStats); } pub(crate) struct SpecTxBuilder {} @@ -322,15 +319,12 @@ impl TxBuilder for SpecTxBuilder { (local_balance_before_fee_msat, remote_balance_before_fee_msat) } - fn build_commitment_transaction( + fn build_commitment_transaction( &self, local: bool, commitment_number: u64, per_commitment_point: &PublicKey, channel_parameters: &ChannelTransactionParameters, secp_ctx: &Secp256k1, value_to_self_msat: u64, mut htlcs_in_tx: Vec, feerate_per_kw: u32, broadcaster_dust_limit_satoshis: u64, logger: &L, - ) -> (CommitmentTransaction, CommitmentStats) - where - L::Target: Logger, - { + ) -> (CommitmentTransaction, CommitmentStats) { let mut local_htlc_total_msat = 0; let mut remote_htlc_total_msat = 0; let channel_type = &channel_parameters.channel_type_features; diff --git a/lightning/src/sign/type_resolver.rs b/lightning/src/sign/type_resolver.rs index a84886cdee0..02048ca4baa 100644 --- a/lightning/src/sign/type_resolver.rs +++ b/lightning/src/sign/type_resolver.rs @@ -1,32 +1,21 @@ use crate::sign::{ChannelSigner, SignerProvider}; -use core::ops::Deref; -pub(crate) enum ChannelSignerType -where - SP::Target: SignerProvider, -{ +pub(crate) enum ChannelSignerType { // in practice, this will only ever be an EcdsaChannelSigner (specifically, Writeable) - Ecdsa(::EcdsaSigner), + Ecdsa(::EcdsaSigner), #[cfg(taproot)] #[allow(unused)] - Taproot(::TaprootSigner), + Taproot(::TaprootSigner), } #[cfg(test)] -impl std::fmt::Debug for ChannelSignerType -where - SP: Deref, - SP::Target: SignerProvider, -{ +impl std::fmt::Debug for ChannelSignerType { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("ChannelSignerType").finish() } } -impl ChannelSignerType -where - SP::Target: SignerProvider, -{ +impl ChannelSignerType { pub(crate) fn as_ref(&self) -> &dyn ChannelSigner { match self { ChannelSignerType::Ecdsa(ecs) => ecs, @@ -37,7 +26,7 @@ where } #[allow(unused)] - pub(crate) fn as_ecdsa(&self) -> Option<&::EcdsaSigner> { + pub(crate) fn as_ecdsa(&self) -> Option<&::EcdsaSigner> { match self { ChannelSignerType::Ecdsa(ecs) => Some(ecs), _ => None, @@ -45,9 +34,7 @@ where } #[allow(unused)] - pub(crate) fn as_mut_ecdsa( - &mut self, - ) -> Option<&mut ::EcdsaSigner> { + pub(crate) fn as_mut_ecdsa(&mut self) -> Option<&mut ::EcdsaSigner> { match self { ChannelSignerType::Ecdsa(ecs) => Some(ecs), _ => None, diff --git a/lightning/src/util/anchor_channel_reserves.rs b/lightning/src/util/anchor_channel_reserves.rs index e50e103211f..cf4b11a3b3d 100644 --- a/lightning/src/util/anchor_channel_reserves.rs +++ b/lightning/src/util/anchor_channel_reserves.rs @@ -273,8 +273,8 @@ pub fn can_support_additional_anchor_channel< AChannelManagerRef: Deref, ChannelSigner: EcdsaChannelSigner, FilterRef: Deref, - BroadcasterRef: Deref, - EstimatorRef: Deref, + Broadcaster: BroadcasterInterface, + EstimatorRef: FeeEstimator, LoggerRef: Deref, PersistRef: Deref, EntropySourceRef: Deref, @@ -282,7 +282,7 @@ pub fn can_support_additional_anchor_channel< Target = ChainMonitor< ChannelSigner, FilterRef, - BroadcasterRef, + Broadcaster, EstimatorRef, LoggerRef, PersistRef, @@ -296,8 +296,6 @@ pub fn can_support_additional_anchor_channel< where AChannelManagerRef::Target: AChannelManager, FilterRef::Target: Filter, - BroadcasterRef::Target: BroadcasterInterface, - EstimatorRef::Target: FeeEstimator, LoggerRef::Target: Logger, PersistRef::Target: Persist, EntropySourceRef::Target: EntropySource, diff --git a/lightning/src/util/logger.rs b/lightning/src/util/logger.rs index b49cd32c131..6f36bce0ab0 100644 --- a/lightning/src/util/logger.rs +++ b/lightning/src/util/logger.rs @@ -287,14 +287,17 @@ pub trait Logger { fn log(&self, record: Record); } +impl> Logger for L { + fn log(&self, record: Record) { + self.deref().log(record) + } +} + /// Adds relevant context to a [`Record`] before passing it to the wrapped [`Logger`]. /// /// This is not exported to bindings users as lifetimes are problematic and there's little reason /// for this to be used downstream anyway. -pub struct WithContext<'a, L: Deref> -where - L::Target: Logger, -{ +pub struct WithContext<'a, L: Logger> { /// The logger to delegate to after adding context to the record. logger: &'a L, /// The node id of the peer pertaining to the logged record. @@ -305,10 +308,7 @@ where payment_hash: Option, } -impl<'a, L: Deref> Logger for WithContext<'a, L> -where - L::Target: Logger, -{ +impl<'a, L: Logger> Logger for WithContext<'a, L> { fn log(&self, mut record: Record) { if self.peer_id.is_some() { record.peer_id = self.peer_id @@ -323,10 +323,7 @@ where } } -impl<'a, L: Deref> WithContext<'a, L> -where - L::Target: Logger, -{ +impl<'a, L: Logger> WithContext<'a, L> { /// Wraps the given logger, providing additional context to any logged records. pub fn from( logger: &'a L, peer_id: Option, channel_id: Option, diff --git a/lightning/src/util/persist.rs b/lightning/src/util/persist.rs index 2e1e8805d0a..00ccaef4966 100644 --- a/lightning/src/util/persist.rs +++ b/lightning/src/util/persist.rs @@ -202,16 +202,6 @@ pub struct KVStoreSyncWrapper(pub K) where K::Target: KVStoreSync; -impl Deref for KVStoreSyncWrapper -where - K::Target: KVStoreSync, -{ - type Target = Self; - fn deref(&self) -> &Self::Target { - self - } -} - /// This is not exported to bindings users as async is only supported in Rust. impl KVStore for KVStoreSyncWrapper where @@ -347,6 +337,32 @@ pub trait KVStore { ) -> impl Future, io::Error>> + 'static + MaybeSend; } +impl> KVStore for K { + fn read( + &self, primary_namespace: &str, secondary_namespace: &str, key: &str, + ) -> impl Future, io::Error>> + 'static + MaybeSend { + self.deref().read(primary_namespace, secondary_namespace, key) + } + + fn write( + &self, primary_namespace: &str, secondary_namespace: &str, key: &str, buf: Vec, + ) -> impl Future> + 'static + MaybeSend { + self.deref().write(primary_namespace, secondary_namespace, key, buf) + } + + fn remove( + &self, primary_namespace: &str, secondary_namespace: &str, key: &str, lazy: bool, + ) -> impl Future> + 'static + MaybeSend { + self.deref().remove(primary_namespace, secondary_namespace, key, lazy) + } + + fn list( + &self, primary_namespace: &str, secondary_namespace: &str, + ) -> impl Future, io::Error>> + 'static + MaybeSend { + self.deref().list(primary_namespace, secondary_namespace) + } +} + /// Provides additional interface methods that are required for [`KVStore`]-to-[`KVStore`] /// data migration. pub trait MigratableKVStore: KVStoreSync { @@ -445,13 +461,11 @@ impl Persist( +pub fn read_channel_monitors( kv_store: K, entropy_source: ES, signer_provider: SP, -) -> Result::EcdsaSigner>)>, io::Error> +) -> Result::EcdsaSigner>)>, io::Error> where K::Target: KVStoreSync, - ES::Target: EntropySource + Sized, - SP::Target: SignerProvider + Sized, { let mut res = Vec::new(); @@ -459,13 +473,13 @@ where CHANNEL_MONITOR_PERSISTENCE_PRIMARY_NAMESPACE, CHANNEL_MONITOR_PERSISTENCE_SECONDARY_NAMESPACE, )? { - match ::EcdsaSigner>)>>::read( + match ::EcdsaSigner>)>>::read( &mut io::Cursor::new(kv_store.read( CHANNEL_MONITOR_PERSISTENCE_PRIMARY_NAMESPACE, CHANNEL_MONITOR_PERSISTENCE_SECONDARY_NAMESPACE, &stored_key, )?), - (&*entropy_source, &*signer_provider), + (&entropy_source, &signer_provider), ) { Ok(Some((block_hash, channel_monitor))) => { let monitor_name = MonitorName::from_str(&stored_key)?; @@ -588,26 +602,27 @@ fn poll_sync_future(future: F) -> F::Output { /// If you have many stale updates stored (such as after a crash with pending lazy deletes), and /// would like to get rid of them, consider using the /// [`MonitorUpdatingPersister::cleanup_stale_updates`] function. -pub struct MonitorUpdatingPersister( - MonitorUpdatingPersisterAsync, PanicingSpawner, L, ES, SP, BI, FE>, -) +pub struct MonitorUpdatingPersister< + K: Deref, + L: Logger, + ES: EntropySource, + SP: SignerProvider, + BI: BroadcasterInterface, + FE: FeeEstimator, +>(MonitorUpdatingPersisterAsync, PanicingSpawner, L, ES, SP, BI, FE>) where - K::Target: KVStoreSync, - L::Target: Logger, - ES::Target: EntropySource + Sized, - SP::Target: SignerProvider + Sized, - BI::Target: BroadcasterInterface, - FE::Target: FeeEstimator; - -impl - MonitorUpdatingPersister + K::Target: KVStoreSync; + +impl< + K: Deref, + L: Logger, + ES: EntropySource, + SP: SignerProvider, + BI: BroadcasterInterface, + FE: FeeEstimator, + > MonitorUpdatingPersister where K::Target: KVStoreSync, - L::Target: Logger, - ES::Target: EntropySource + Sized, - SP::Target: SignerProvider + Sized, - BI::Target: BroadcasterInterface, - FE::Target: FeeEstimator, { /// Constructs a new [`MonitorUpdatingPersister`]. /// @@ -651,10 +666,7 @@ where /// Reads all stored channel monitors, along with any stored updates for them. pub fn read_all_channel_monitors_with_updates( &self, - ) -> Result< - Vec<(BlockHash, ChannelMonitor<::EcdsaSigner>)>, - io::Error, - > { + ) -> Result::EcdsaSigner>)>, io::Error> { poll_sync_future(self.0.read_all_channel_monitors_with_updates()) } @@ -675,8 +687,7 @@ where /// function to accomplish this. Take care to limit the number of parallel readers. pub fn read_channel_monitor_with_updates( &self, monitor_key: &str, - ) -> Result<(BlockHash, ChannelMonitor<::EcdsaSigner>), io::Error> - { + ) -> Result<(BlockHash, ChannelMonitor<::EcdsaSigner>), io::Error> { poll_sync_future(self.0.read_channel_monitor_with_updates(monitor_key)) } @@ -694,19 +705,14 @@ where impl< ChannelSigner: EcdsaChannelSigner, K: Deref, - L: Deref, - ES: Deref, - SP: Deref, - BI: Deref, - FE: Deref, + L: Logger, + ES: EntropySource, + SP: SignerProvider, + BI: BroadcasterInterface, + FE: FeeEstimator, > Persist for MonitorUpdatingPersister where K::Target: KVStoreSync, - L::Target: Logger, - ES::Target: EntropySource + Sized, - SP::Target: SignerProvider + Sized, - BI::Target: BroadcasterInterface, - FE::Target: FeeEstimator, { /// Persists a new channel. This means writing the entire monitor to the /// parametrized [`KVStoreSync`]. @@ -778,38 +784,24 @@ where /// [`ChainMonitor`]: crate::chain::chainmonitor::ChainMonitor /// [`ChainMonitor::new_async_beta`]: crate::chain::chainmonitor::ChainMonitor::new_async_beta pub struct MonitorUpdatingPersisterAsync< - K: Deref, + K: KVStore, S: FutureSpawner, - L: Deref, - ES: Deref, - SP: Deref, - BI: Deref, - FE: Deref, ->(Arc>) -where - K::Target: KVStore, - L::Target: Logger, - ES::Target: EntropySource + Sized, - SP::Target: SignerProvider + Sized, - BI::Target: BroadcasterInterface, - FE::Target: FeeEstimator; + L: Logger, + ES: EntropySource, + SP: SignerProvider, + BI: BroadcasterInterface, + FE: FeeEstimator, +>(Arc>); struct MonitorUpdatingPersisterAsyncInner< - K: Deref, + K: KVStore, S: FutureSpawner, - L: Deref, - ES: Deref, - SP: Deref, - BI: Deref, - FE: Deref, -> where - K::Target: KVStore, - L::Target: Logger, - ES::Target: EntropySource + Sized, - SP::Target: SignerProvider + Sized, - BI::Target: BroadcasterInterface, - FE::Target: FeeEstimator, -{ + L: Logger, + ES: EntropySource, + SP: SignerProvider, + BI: BroadcasterInterface, + FE: FeeEstimator, +> { kv_store: K, async_completed_updates: Mutex>, future_spawner: S, @@ -821,15 +813,15 @@ struct MonitorUpdatingPersisterAsyncInner< fee_estimator: FE, } -impl - MonitorUpdatingPersisterAsync -where - K::Target: KVStore, - L::Target: Logger, - ES::Target: EntropySource + Sized, - SP::Target: SignerProvider + Sized, - BI::Target: BroadcasterInterface, - FE::Target: FeeEstimator, +impl< + K: KVStore, + S: FutureSpawner, + L: Logger, + ES: EntropySource, + SP: SignerProvider, + BI: BroadcasterInterface, + FE: FeeEstimator, + > MonitorUpdatingPersisterAsync { /// Constructs a new [`MonitorUpdatingPersisterAsync`]. /// @@ -862,10 +854,7 @@ where /// deserialization as well. pub async fn read_all_channel_monitors_with_updates( &self, - ) -> Result< - Vec<(BlockHash, ChannelMonitor<::EcdsaSigner>)>, - io::Error, - > { + ) -> Result::EcdsaSigner>)>, io::Error> { let primary = CHANNEL_MONITOR_PERSISTENCE_PRIMARY_NAMESPACE; let secondary = CHANNEL_MONITOR_PERSISTENCE_SECONDARY_NAMESPACE; let monitor_list = self.0.kv_store.list(primary, secondary).await?; @@ -896,10 +885,7 @@ where /// `Arc` that can live for `'static` and be sent and accessed across threads. pub async fn read_all_channel_monitors_with_updates_parallel( self: &Arc, - ) -> Result< - Vec<(BlockHash, ChannelMonitor<::EcdsaSigner>)>, - io::Error, - > + ) -> Result::EcdsaSigner>)>, io::Error> where K: MaybeSend + MaybeSync + 'static, L: MaybeSend + MaybeSync + 'static, @@ -907,7 +893,7 @@ where SP: MaybeSend + MaybeSync + 'static, BI: MaybeSend + MaybeSync + 'static, FE: MaybeSend + MaybeSync + 'static, - ::EcdsaSigner: MaybeSend, + ::EcdsaSigner: MaybeSend, { let primary = CHANNEL_MONITOR_PERSISTENCE_PRIMARY_NAMESPACE; let secondary = CHANNEL_MONITOR_PERSISTENCE_SECONDARY_NAMESPACE; @@ -949,8 +935,7 @@ where /// function to accomplish this. Take care to limit the number of parallel readers. pub async fn read_channel_monitor_with_updates( &self, monitor_key: &str, - ) -> Result<(BlockHash, ChannelMonitor<::EcdsaSigner>), io::Error> - { + ) -> Result<(BlockHash, ChannelMonitor<::EcdsaSigner>), io::Error> { self.0.read_channel_monitor_with_updates(monitor_key).await } @@ -966,27 +951,20 @@ where } impl< - K: Deref + MaybeSend + MaybeSync + 'static, + K: KVStore + MaybeSend + MaybeSync + 'static, S: FutureSpawner, - L: Deref + MaybeSend + MaybeSync + 'static, - ES: Deref + MaybeSend + MaybeSync + 'static, - SP: Deref + MaybeSend + MaybeSync + 'static, - BI: Deref + MaybeSend + MaybeSync + 'static, - FE: Deref + MaybeSend + MaybeSync + 'static, + L: Logger + MaybeSend + MaybeSync + 'static, + ES: EntropySource + MaybeSend + MaybeSync + 'static, + SP: SignerProvider + MaybeSend + MaybeSync + 'static, + BI: BroadcasterInterface + MaybeSend + MaybeSync + 'static, + FE: FeeEstimator + MaybeSend + MaybeSync + 'static, > MonitorUpdatingPersisterAsync where - K::Target: KVStore + MaybeSync, - L::Target: Logger, - ES::Target: EntropySource + Sized, - SP::Target: SignerProvider + Sized, - BI::Target: BroadcasterInterface, - FE::Target: FeeEstimator, - ::EcdsaSigner: MaybeSend + 'static, + ::EcdsaSigner: MaybeSend + 'static, { pub(crate) fn spawn_async_persist_new_channel( &self, monitor_name: MonitorName, - monitor: &ChannelMonitor<::EcdsaSigner>, - notifier: Arc, + monitor: &ChannelMonitor<::EcdsaSigner>, notifier: Arc, ) { let inner = Arc::clone(&self.0); // Note that `persist_new_channel` is a sync method which calls all the way through to the @@ -1012,8 +990,7 @@ where pub(crate) fn spawn_async_update_channel( &self, monitor_name: MonitorName, update: Option<&ChannelMonitorUpdate>, - monitor: &ChannelMonitor<::EcdsaSigner>, - notifier: Arc, + monitor: &ChannelMonitor<::EcdsaSigner>, notifier: Arc, ) { let inner = Arc::clone(&self.0); // Note that `update_persisted_channel` is a sync method which calls all the way through to @@ -1057,20 +1034,19 @@ where trait MaybeSendableFuture: Future> + MaybeSend {} impl> + MaybeSend> MaybeSendableFuture for F {} -impl - MonitorUpdatingPersisterAsyncInner -where - K::Target: KVStore, - L::Target: Logger, - ES::Target: EntropySource + Sized, - SP::Target: SignerProvider + Sized, - BI::Target: BroadcasterInterface, - FE::Target: FeeEstimator, +impl< + K: KVStore, + S: FutureSpawner, + L: Logger, + ES: EntropySource, + SP: SignerProvider, + BI: BroadcasterInterface, + FE: FeeEstimator, + > MonitorUpdatingPersisterAsyncInner { pub async fn read_channel_monitor_with_updates( &self, monitor_key: &str, - ) -> Result<(BlockHash, ChannelMonitor<::EcdsaSigner>), io::Error> - { + ) -> Result<(BlockHash, ChannelMonitor<::EcdsaSigner>), io::Error> { match self.maybe_read_channel_monitor_with_updates(monitor_key).await? { Some(res) => Ok(res), None => Err(io::Error::new( @@ -1087,10 +1063,8 @@ where async fn maybe_read_channel_monitor_with_updates( &self, monitor_key: &str, - ) -> Result< - Option<(BlockHash, ChannelMonitor<::EcdsaSigner>)>, - io::Error, - > { + ) -> Result::EcdsaSigner>)>, io::Error> + { let monitor_name = MonitorName::from_str(monitor_key)?; let read_future = pin!(self.maybe_read_monitor(&monitor_name, monitor_key)); let list_future = pin!(self @@ -1134,10 +1108,8 @@ where /// Read a channel monitor. async fn maybe_read_monitor( &self, monitor_name: &MonitorName, monitor_key: &str, - ) -> Result< - Option<(BlockHash, ChannelMonitor<::EcdsaSigner>)>, - io::Error, - > { + ) -> Result::EcdsaSigner>)>, io::Error> + { let primary = CHANNEL_MONITOR_PERSISTENCE_PRIMARY_NAMESPACE; let secondary = CHANNEL_MONITOR_PERSISTENCE_SECONDARY_NAMESPACE; let monitor_bytes = self.kv_store.read(primary, secondary, monitor_key).await?; @@ -1146,9 +1118,9 @@ where if monitor_cursor.get_ref().starts_with(MONITOR_UPDATING_PERSISTER_PREPEND_SENTINEL) { monitor_cursor.set_position(MONITOR_UPDATING_PERSISTER_PREPEND_SENTINEL.len() as u64); } - match ::EcdsaSigner>)>>::read( + match ::EcdsaSigner>)>>::read( &mut monitor_cursor, - (&*self.entropy_source, &*self.signer_provider), + (&self.entropy_source, &self.signer_provider), ) { Ok(None) => Ok(None), Ok(Some((blockhash, channel_monitor))) => { diff --git a/lightning/src/util/scid_utils.rs b/lightning/src/util/scid_utils.rs index b9dcc4688e8..d57c529a41a 100644 --- a/lightning/src/util/scid_utils.rs +++ b/lightning/src/util/scid_utils.rs @@ -80,8 +80,6 @@ pub(crate) mod fake_scid { use bitcoin::constants::ChainHash; use bitcoin::Network; - use core::ops::Deref; - const TEST_SEGWIT_ACTIVATION_HEIGHT: u32 = 1; const MAINNET_SEGWIT_ACTIVATION_HEIGHT: u32 = 481_824; const MAX_TX_INDEX: u32 = 2_500; @@ -110,13 +108,10 @@ pub(crate) mod fake_scid { /// between segwit activation and the current best known height, and the tx index and output /// index are also selected from a "reasonable" range. We add this logic because it makes it /// non-obvious at a glance that the scid is fake, e.g. if it appears in invoice route hints. - pub(crate) fn get_fake_scid( + pub(crate) fn get_fake_scid( &self, highest_seen_blockheight: u32, chain_hash: &ChainHash, fake_scid_rand_bytes: &[u8; 32], entropy_source: &ES, - ) -> u64 - where - ES::Target: EntropySource, - { + ) -> u64 { // Ensure we haven't created a namespace that doesn't fit into the 3 bits we've allocated for // namespaces. assert!((*self as u8) < MAX_NAMESPACES); diff --git a/lightning/src/util/sweep.rs b/lightning/src/util/sweep.rs index bf048efdae1..2d22244cb17 100644 --- a/lightning/src/util/sweep.rs +++ b/lightning/src/util/sweep.rs @@ -337,14 +337,17 @@ impl_writeable_tlv_based_enum!(OutputSpendStatus, /// /// [`Event::SpendableOutputs`]: crate::events::Event::SpendableOutputs // Note that updates to documentation on this struct should be copied to the synchronous version. -pub struct OutputSweeper -where - B::Target: BroadcasterInterface, +pub struct OutputSweeper< + B: BroadcasterInterface, + D: Deref, + E: FeeEstimator, + F: Deref, + K: KVStore, + L: Logger, + O: Deref, +> where D::Target: ChangeDestinationSource, - E::Target: FeeEstimator, F::Target: Filter, - K::Target: KVStore, - L::Target: Logger, O::Target: OutputSpender, { sweeper_state: Mutex, @@ -358,15 +361,18 @@ where logger: L, } -impl - OutputSweeper +impl< + B: BroadcasterInterface, + D: Deref, + E: FeeEstimator, + F: Deref, + K: KVStore, + L: Logger, + O: Deref, + > OutputSweeper where - B::Target: BroadcasterInterface, D::Target: ChangeDestinationSource, - E::Target: FeeEstimator, F::Target: Filter, - K::Target: KVStore, - L::Target: Logger, O::Target: OutputSpender, { /// Constructs a new [`OutputSweeper`]. @@ -710,15 +716,18 @@ where } } -impl Listen - for OutputSweeper +impl< + B: BroadcasterInterface, + D: Deref, + E: FeeEstimator, + F: Deref, + K: KVStore, + L: Logger, + O: Deref, + > Listen for OutputSweeper where - B::Target: BroadcasterInterface, D::Target: ChangeDestinationSource, - E::Target: FeeEstimator, F::Target: Filter + Sync + Send, - K::Target: KVStore, - L::Target: Logger, O::Target: OutputSpender, { fn filtered_block_connected( @@ -751,15 +760,18 @@ where } } -impl Confirm - for OutputSweeper +impl< + B: BroadcasterInterface, + D: Deref, + E: FeeEstimator, + F: Deref, + K: KVStore, + L: Logger, + O: Deref, + > Confirm for OutputSweeper where - B::Target: BroadcasterInterface, D::Target: ChangeDestinationSource, - E::Target: FeeEstimator, F::Target: Filter + Sync + Send, - K::Target: KVStore, - L::Target: Logger, O::Target: OutputSpender, { fn transactions_confirmed( @@ -848,15 +860,18 @@ pub enum SpendingDelay { }, } -impl - ReadableArgs<(B, E, Option, O, D, K, L)> for (BestBlock, OutputSweeper) +impl< + B: BroadcasterInterface, + D: Deref, + E: FeeEstimator, + F: Deref, + K: KVStore, + L: Logger, + O: Deref, + > ReadableArgs<(B, E, Option, O, D, K, L)> for (BestBlock, OutputSweeper) where - B::Target: BroadcasterInterface, D::Target: ChangeDestinationSource, - E::Target: FeeEstimator, F::Target: Filter + Sync + Send, - K::Target: KVStore, - L::Target: Logger, O::Target: OutputSpender, { #[inline] @@ -918,29 +933,37 @@ where /// /// [`Event::SpendableOutputs`]: crate::events::Event::SpendableOutputs // Note that updates to documentation on this struct should be copied to the asynchronous version. -pub struct OutputSweeperSync -where - B::Target: BroadcasterInterface, +pub struct OutputSweeperSync< + B: BroadcasterInterface, + D: Deref, + E: FeeEstimator, + F: Deref, + K: Deref, + L: Logger, + O: Deref, +> where D::Target: ChangeDestinationSourceSync, - E::Target: FeeEstimator, F::Target: Filter, K::Target: KVStoreSync, - L::Target: Logger, O::Target: OutputSpender, { sweeper: OutputSweeper, E, F, KVStoreSyncWrapper, L, O>, } -impl - OutputSweeperSync +impl< + B: BroadcasterInterface, + D: Deref, + E: FeeEstimator, + F: Deref, + K: Deref, + L: Logger, + O: Deref, + > OutputSweeperSync where - B::Target: BroadcasterInterface, D::Target: ChangeDestinationSourceSync, - E::Target: FeeEstimator, F::Target: Filter, K::Target: KVStoreSync, - L::Target: Logger, O::Target: OutputSpender, { /// Constructs a new [`OutputSweeperSync`] instance. @@ -1052,15 +1075,19 @@ where } } -impl Listen - for OutputSweeperSync +impl< + B: BroadcasterInterface, + D: Deref, + E: FeeEstimator, + F: Deref, + K: Deref, + L: Logger, + O: Deref, + > Listen for OutputSweeperSync where - B::Target: BroadcasterInterface, D::Target: ChangeDestinationSourceSync, - E::Target: FeeEstimator, F::Target: Filter + Sync + Send, K::Target: KVStoreSync, - L::Target: Logger, O::Target: OutputSpender, { fn filtered_block_connected( @@ -1074,15 +1101,19 @@ where } } -impl Confirm - for OutputSweeperSync +impl< + B: BroadcasterInterface, + D: Deref, + E: FeeEstimator, + F: Deref, + K: Deref, + L: Logger, + O: Deref, + > Confirm for OutputSweeperSync where - B::Target: BroadcasterInterface, D::Target: ChangeDestinationSourceSync, - E::Target: FeeEstimator, F::Target: Filter + Sync + Send, K::Target: KVStoreSync, - L::Target: Logger, O::Target: OutputSpender, { fn transactions_confirmed( @@ -1104,15 +1135,20 @@ where } } -impl - ReadableArgs<(B, E, Option, O, D, K, L)> for (BestBlock, OutputSweeperSync) +impl< + B: BroadcasterInterface, + D: Deref, + E: FeeEstimator, + F: Deref, + K: Deref, + L: Logger, + O: Deref, + > ReadableArgs<(B, E, Option, O, D, K, L)> + for (BestBlock, OutputSweeperSync) where - B::Target: BroadcasterInterface, D::Target: ChangeDestinationSourceSync, - E::Target: FeeEstimator, F::Target: Filter + Sync + Send, K::Target: KVStoreSync, - L::Target: Logger, O::Target: OutputSpender, { #[inline]