From: Matt Corallo <649246+TheBlueMatt@users.noreply.github.com> Date: Tue, 1 Nov 2022 21:12:30 +0000 (+0000) Subject: Merge pull request #1791 from valentinewallace/2022-10-we-are-intro-node X-Git-Tag: v0.0.113~63 X-Git-Url: http://git.bitcoin.ninja/index.cgi?a=commitdiff_plain;h=6ca49948c169a297144d5d1474a2cef3827237e1;hp=7af02d01748febbe45127e5702c36775c69e326c;p=rust-lightning Merge pull request #1791 from valentinewallace/2022-10-we-are-intro-node Onion messages: fix edge case where we are the intro node --- diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 171c57fc..3a67a681 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -228,7 +228,7 @@ jobs: benchmark: runs-on: ubuntu-latest env: - TOOLCHAIN: nightly + TOOLCHAIN: stable steps: - name: Checkout source code uses: actions/checkout@v3 @@ -273,7 +273,7 @@ jobs: cd .. - name: Run benchmarks on Rust ${{ matrix.toolchain }} run: | - cargo bench --features _bench_unstable + RUSTC_BOOTSTRAP=1 cargo bench --features _bench_unstable check_commits: runs-on: ubuntu-latest diff --git a/CHANGELOG.md b/CHANGELOG.md index 7736ce67..37a70035 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,64 @@ +# 0.0.112 - Oct 25, 2022 - "History Matters" + +## API Updates + * `Result<(), ChannelMonitorUpdateErr>` return values have been replaced with + a `ChannelMonitorUpdateStatus` trinary enum. This better denotes that + `ChannelMonitorUpdateStatus::InProgress` is not an error, but asynchronous + persistence of a monitor update. Note that asynchronous persistence still + has some edge cases and is not yet recommended for production (#1106). + * `ChannelMonitor` persistence failure no longer automatically broadcasts the + latest commitment transaction. See the + `ChannelMonitorUpdateStatus::PermanentFailure` docs for more info (#1106). + * `*Features::known` has been replaced with individual + `*MessageHandler::provided_*_features` methods (#1707). + * `OnionMessenger` now takes a `CustomOnionMessageHandler` implementation, + allowing you to send and receive custom onion messages (#1748). + * `ProbabilisticScorer` now tracks the historical distribution of liquidity + estimates for channels. See new `historical_*` parameters in + `ProbabilisticScoringParameters` for more details (#1625). + * `lightning-block-sync`'s `BlockSource` trait now supports BIP 157/158 + filtering clients by returning only header data for some blocks (#1706). + * `lightning-invoice`'s `Router` trait now accepts an `InFlightHtlcs` to + ensure we do not over-use a remote channel's funds during routing (#1694). + Note that this was previously backported to 0.0.111 for bindings users. + * `NetworkGraph::remove_stale_channels` has been renamed + `NetworkGraph::remove_stale_channels_and_tracking` as `NetworkGraph` now + refuses to re-add nodes and channels that were recently removed (#1649). + * The `lightning-rapid-gossip-sync` crate now supports `no-std` (#1708). + * The default `ProbabilisticScoringParameters::liquidity_offset_half_life` has + been increased to six hours from one (#1754). + * All commitment transaction building logic for anchor outputs now assumes the + no-HTLC-tx-fee variant (#1685). + * A number of missing `Eq` implementations were added (#1763). + +## Bug Fixes + * `lightning-background-processor` now builds without error with the `futures` + feature (#1744). + * `ChannelManager::get_persistable_update_future`'s returned `Future` has been + corrected to not fail to be awoken in some cases (#1758). + * Asynchronously performing the initial `ChannelMonitor` persistence is now + safe (#1678). + * Redundantly applying rapid gossip sync updates no longer `Err`s (#1764). + * Nodes which inform us via payment failures that they should no longer be + used are now removed from the network graph. Some LND nodes spuriously + generate this error and may remove themselves from our graph (#1649). + +In total, this release features 134 files changed, 6598 insertions, 4370 +deletions in 109 commits from 13 authors, in alphabetical order: + * Duncan Dean + * Elias Rohrer + * Gabriel Comte + * Gursharan Singh + * Jeffrey Czyz + * Jurvis Tan + * Matt Corallo + * Max Fang + * Paul Miller + * Valentine Wallace + * Viktor Tigerström + * Wilmer Paulino + * acid-bit + # 0.0.111 - Sep 12, 2022 - "Saturated with Messages" ## API Updates diff --git a/fuzz/src/chanmon_consistency.rs b/fuzz/src/chanmon_consistency.rs index a84dd498..d2145f1b 100644 --- a/fuzz/src/chanmon_consistency.rs +++ b/fuzz/src/chanmon_consistency.rs @@ -292,7 +292,7 @@ fn check_payment_err(send_err: PaymentSendFailure) { } } -type ChanMan = ChannelManager, Arc, Arc, Arc, Arc>; +type ChanMan = ChannelManager, Arc, Arc, Arc, Arc>; #[inline] fn get_payment_secret_hash(dest: &ChanMan, payment_id: &mut u8) -> Option<(PaymentSecret, PaymentHash)> { diff --git a/fuzz/src/full_stack.rs b/fuzz/src/full_stack.rs index c885fc6d..ce8cfbdb 100644 --- a/fuzz/src/full_stack.rs +++ b/fuzz/src/full_stack.rs @@ -163,7 +163,6 @@ impl<'a> std::hash::Hash for Peer<'a> { } type ChannelMan = ChannelManager< - EnforcingSigner, Arc, Arc, Arc, Arc, Arc>>, Arc, Arc, Arc, Arc>; type PeerMan<'a> = PeerManager, Arc, Arc>>, Arc, Arc>>, IgnoringMessageHandler, Arc, IgnoringMessageHandler>; diff --git a/fuzz/src/onion_message.rs b/fuzz/src/onion_message.rs index 5318c0c9..8fa6e423 100644 --- a/fuzz/src/onion_message.rs +++ b/fuzz/src/onion_message.rs @@ -10,7 +10,7 @@ use lightning::ln::msgs::{self, DecodeError, OnionMessageHandler}; use lightning::ln::script::ShutdownScript; use lightning::util::enforcing_trait_impls::EnforcingSigner; use lightning::util::logger::Logger; -use lightning::util::ser::{MaybeReadableArgs, Readable, Writeable, Writer}; +use lightning::util::ser::{Readable, Writeable, Writer}; use lightning::onion_message::{CustomOnionMessageContents, CustomOnionMessageHandler, OnionMessenger}; use crate::utils::test_logger; @@ -67,19 +67,16 @@ impl Writeable for TestCustomMessage { } } -impl MaybeReadableArgs for TestCustomMessage { - fn read(buffer: &mut R, _message_type: u64,) -> Result, DecodeError> where Self: Sized { - let mut buf = Vec::new(); - buffer.read_to_end(&mut buf)?; - return Ok(Some(TestCustomMessage {})) - } -} - struct TestCustomMessageHandler {} impl CustomOnionMessageHandler for TestCustomMessageHandler { type CustomMessage = TestCustomMessage; fn handle_custom_message(&self, _msg: Self::CustomMessage) {} + fn read_custom_message(&self, _message_type: u64, buffer: &mut R) -> Result, msgs::DecodeError> { + let mut buf = Vec::new(); + buffer.read_to_end(&mut buf)?; + return Ok(Some(TestCustomMessage {})) + } } pub struct VecWriter(pub Vec); diff --git a/lightning-background-processor/Cargo.toml b/lightning-background-processor/Cargo.toml index 6dd06b57..8f0fc153 100644 --- a/lightning-background-processor/Cargo.toml +++ b/lightning-background-processor/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lightning-background-processor" -version = "0.0.111" +version = "0.0.112" authors = ["Valentine Wallace "] license = "MIT OR Apache-2.0" repository = "http://github.com/lightningdevkit/rust-lightning" @@ -18,11 +18,11 @@ futures = [ "futures-util" ] [dependencies] bitcoin = "0.29.0" -lightning = { version = "0.0.111", path = "../lightning", features = ["std"] } -lightning-rapid-gossip-sync = { version = "0.0.111", path = "../lightning-rapid-gossip-sync" } +lightning = { version = "0.0.112", path = "../lightning", features = ["std"] } +lightning-rapid-gossip-sync = { version = "0.0.112", path = "../lightning-rapid-gossip-sync" } futures-util = { version = "0.3", default-features = false, features = ["async-await-macro"], optional = true } [dev-dependencies] -lightning = { version = "0.0.111", path = "../lightning", features = ["_test_utils"] } -lightning-invoice = { version = "0.19.0", path = "../lightning-invoice" } -lightning-persister = { version = "0.0.111", path = "../lightning-persister" } +lightning = { version = "0.0.112", path = "../lightning", features = ["_test_utils"] } +lightning-invoice = { version = "0.20.0", path = "../lightning-invoice" } +lightning-persister = { version = "0.0.112", path = "../lightning-persister" } diff --git a/lightning-background-processor/src/lib.rs b/lightning-background-processor/src/lib.rs index 27cd0663..76a7cfc9 100644 --- a/lightning-background-processor/src/lib.rs +++ b/lightning-background-processor/src/lib.rs @@ -382,7 +382,7 @@ pub async fn process_events_async< EH: 'static + EventHandler + Send, PS: 'static + Deref + Send, M: 'static + Deref> + Send + Sync, - CM: 'static + Deref> + Send + Sync, + CM: 'static + Deref> + Send + Sync, PGS: 'static + Deref> + Send + Sync, RGS: 'static + Deref> + Send, UMH: 'static + Deref + Send + Sync, @@ -488,7 +488,7 @@ impl BackgroundProcessor { EH: 'static + EventHandler + Send, PS: 'static + Deref + Send, M: 'static + Deref> + Send + Sync, - CM: 'static + Deref> + Send + Sync, + CM: 'static + Deref> + Send + Sync, PGS: 'static + Deref> + Send + Sync, RGS: 'static + Deref> + Send, UMH: 'static + Deref + Send + Sync, diff --git a/lightning-block-sync/Cargo.toml b/lightning-block-sync/Cargo.toml index afd2a7c3..220de8fa 100644 --- a/lightning-block-sync/Cargo.toml +++ b/lightning-block-sync/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lightning-block-sync" -version = "0.0.111" +version = "0.0.112" authors = ["Jeffrey Czyz", "Matt Corallo"] license = "MIT OR Apache-2.0" repository = "http://github.com/lightningdevkit/rust-lightning" @@ -19,7 +19,7 @@ rpc-client = [ "serde", "serde_json", "chunked_transfer" ] [dependencies] bitcoin = "0.29.0" -lightning = { version = "0.0.111", path = "../lightning" } +lightning = { version = "0.0.112", path = "../lightning" } futures-util = { version = "0.3" } tokio = { version = "1.0", features = [ "io-util", "net", "time" ], optional = true } serde = { version = "1.0", features = ["derive"], optional = true } diff --git a/lightning-block-sync/src/init.rs b/lightning-block-sync/src/init.rs index 7a8fada9..7e1cb3fb 100644 --- a/lightning-block-sync/src/init.rs +++ b/lightning-block-sync/src/init.rs @@ -95,7 +95,7 @@ BlockSourceResult where B::Target: BlockSource { /// config, /// vec![&mut monitor], /// ); -/// <(BlockHash, ChannelManager, &T, &K, &F, &L>)>::read( +/// <(BlockHash, ChannelManager<&ChainMonitor, &T, &K, &F, &L>)>::read( /// &mut Cursor::new(&serialized_manager), read_args).unwrap() /// }; /// diff --git a/lightning-invoice/Cargo.toml b/lightning-invoice/Cargo.toml index 1cc7345b..39ca3a1b 100644 --- a/lightning-invoice/Cargo.toml +++ b/lightning-invoice/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "lightning-invoice" description = "Data structures to parse and serialize BOLT11 lightning invoices" -version = "0.19.0" +version = "0.20.0" authors = ["Sebastian Geisler "] documentation = "https://docs.rs/lightning-invoice/" license = "MIT OR Apache-2.0" @@ -21,7 +21,7 @@ std = ["bitcoin_hashes/std", "num-traits/std", "lightning/std", "bech32/std"] [dependencies] bech32 = { version = "0.9.0", default-features = false } -lightning = { version = "0.0.111", path = "../lightning", default-features = false } +lightning = { version = "0.0.112", path = "../lightning", default-features = false } secp256k1 = { version = "0.24.0", default-features = false, features = ["recovery", "alloc"] } num-traits = { version = "0.2.8", default-features = false } bitcoin_hashes = { version = "0.11", default-features = false } @@ -29,6 +29,6 @@ hashbrown = { version = "0.8", optional = true } serde = { version = "1.0.118", optional = true } [dev-dependencies] -lightning = { version = "0.0.111", path = "../lightning", default-features = false, features = ["_test_utils"] } +lightning = { version = "0.0.112", path = "../lightning", default-features = false, features = ["_test_utils"] } hex = "0.4" serde_json = { version = "1"} diff --git a/lightning-invoice/src/utils.rs b/lightning-invoice/src/utils.rs index 5b16da45..8b45d580 100644 --- a/lightning-invoice/src/utils.rs +++ b/lightning-invoice/src/utils.rs @@ -235,14 +235,14 @@ where /// /// `invoice_expiry_delta_secs` describes the number of seconds that the invoice is valid for /// in excess of the current time. -pub fn create_invoice_from_channelmanager( - channelmanager: &ChannelManager, keys_manager: K, logger: L, +pub fn create_invoice_from_channelmanager( + channelmanager: &ChannelManager, keys_manager: K, logger: L, network: Currency, amt_msat: Option, description: String, invoice_expiry_delta_secs: u32 ) -> Result> where - M::Target: chain::Watch, + M::Target: chain::Watch<::Signer>, T::Target: BroadcasterInterface, - K::Target: KeysInterface, + K::Target: KeysInterface, F::Target: FeeEstimator, L::Target: Logger, { @@ -265,15 +265,15 @@ where /// /// `invoice_expiry_delta_secs` describes the number of seconds that the invoice is valid for /// in excess of the current time. -pub fn create_invoice_from_channelmanager_with_description_hash( - channelmanager: &ChannelManager, keys_manager: K, logger: L, +pub fn create_invoice_from_channelmanager_with_description_hash( + channelmanager: &ChannelManager, keys_manager: K, logger: L, network: Currency, amt_msat: Option, description_hash: Sha256, invoice_expiry_delta_secs: u32 ) -> Result> where - M::Target: chain::Watch, + M::Target: chain::Watch<::Signer>, T::Target: BroadcasterInterface, - K::Target: KeysInterface, + K::Target: KeysInterface, F::Target: FeeEstimator, L::Target: Logger, { @@ -292,15 +292,15 @@ where /// See [`create_invoice_from_channelmanager_with_description_hash`] /// 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_invoice_from_channelmanager_with_description_hash_and_duration_since_epoch( - channelmanager: &ChannelManager, keys_manager: K, logger: L, +pub fn create_invoice_from_channelmanager_with_description_hash_and_duration_since_epoch( + channelmanager: &ChannelManager, keys_manager: K, logger: L, network: Currency, amt_msat: Option, description_hash: Sha256, duration_since_epoch: Duration, invoice_expiry_delta_secs: u32 ) -> Result> where - M::Target: chain::Watch, + M::Target: chain::Watch<::Signer>, T::Target: BroadcasterInterface, - K::Target: KeysInterface, + K::Target: KeysInterface, F::Target: FeeEstimator, L::Target: Logger, { @@ -314,15 +314,15 @@ where /// See [`create_invoice_from_channelmanager`] /// 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_invoice_from_channelmanager_and_duration_since_epoch( - channelmanager: &ChannelManager, keys_manager: K, logger: L, +pub fn create_invoice_from_channelmanager_and_duration_since_epoch( + channelmanager: &ChannelManager, keys_manager: K, logger: L, network: Currency, amt_msat: Option, description: String, duration_since_epoch: Duration, invoice_expiry_delta_secs: u32 ) -> Result> where - M::Target: chain::Watch, + M::Target: chain::Watch<::Signer>, T::Target: BroadcasterInterface, - K::Target: KeysInterface, + K::Target: KeysInterface, F::Target: FeeEstimator, L::Target: Logger, { @@ -335,15 +335,15 @@ where ) } -fn _create_invoice_from_channelmanager_and_duration_since_epoch( - channelmanager: &ChannelManager, keys_manager: K, logger: L, +fn _create_invoice_from_channelmanager_and_duration_since_epoch( + channelmanager: &ChannelManager, keys_manager: K, logger: L, network: Currency, amt_msat: Option, description: InvoiceDescription, duration_since_epoch: Duration, invoice_expiry_delta_secs: u32 ) -> Result> where - M::Target: chain::Watch, + M::Target: chain::Watch<::Signer>, T::Target: BroadcasterInterface, - K::Target: KeysInterface, + K::Target: KeysInterface, F::Target: FeeEstimator, L::Target: Logger, { @@ -585,11 +585,11 @@ impl>, L: Deref, S: Deref> Router for DefaultR } } -impl Payer for ChannelManager +impl Payer for ChannelManager where - M::Target: chain::Watch, + M::Target: chain::Watch<::Signer>, T::Target: BroadcasterInterface, - K::Target: KeysInterface, + K::Target: KeysInterface, F::Target: FeeEstimator, L::Target: Logger, { diff --git a/lightning-net-tokio/Cargo.toml b/lightning-net-tokio/Cargo.toml index b38f400c..3767fe75 100644 --- a/lightning-net-tokio/Cargo.toml +++ b/lightning-net-tokio/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lightning-net-tokio" -version = "0.0.111" +version = "0.0.112" authors = ["Matt Corallo"] license = "MIT OR Apache-2.0" repository = "https://github.com/lightningdevkit/rust-lightning/" @@ -16,7 +16,7 @@ rustdoc-args = ["--cfg", "docsrs"] [dependencies] bitcoin = "0.29.0" -lightning = { version = "0.0.111", path = "../lightning" } +lightning = { version = "0.0.112", path = "../lightning" } tokio = { version = "1.0", features = [ "io-util", "macros", "rt", "sync", "net", "time" ] } [dev-dependencies] diff --git a/lightning-persister/Cargo.toml b/lightning-persister/Cargo.toml index 01c19a21..6b351839 100644 --- a/lightning-persister/Cargo.toml +++ b/lightning-persister/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lightning-persister" -version = "0.0.111" +version = "0.0.112" authors = ["Valentine Wallace", "Matt Corallo"] license = "MIT OR Apache-2.0" repository = "https://github.com/lightningdevkit/rust-lightning/" @@ -18,11 +18,11 @@ _bench_unstable = ["lightning/_bench_unstable"] [dependencies] bitcoin = "0.29.0" -lightning = { version = "0.0.111", path = "../lightning" } +lightning = { version = "0.0.112", path = "../lightning" } libc = "0.2" [target.'cfg(windows)'.dependencies] winapi = { version = "0.3", features = ["winbase"] } [dev-dependencies] -lightning = { version = "0.0.111", path = "../lightning", features = ["_test_utils"] } +lightning = { version = "0.0.112", path = "../lightning", features = ["_test_utils"] } diff --git a/lightning-rapid-gossip-sync/Cargo.toml b/lightning-rapid-gossip-sync/Cargo.toml index 4dec0aa8..6d49d455 100644 --- a/lightning-rapid-gossip-sync/Cargo.toml +++ b/lightning-rapid-gossip-sync/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lightning-rapid-gossip-sync" -version = "0.0.111" +version = "0.0.112" authors = ["Arik Sosman "] license = "MIT OR Apache-2.0" repository = "https://github.com/lightningdevkit/rust-lightning" @@ -16,8 +16,8 @@ std = ["lightning/std"] _bench_unstable = [] [dependencies] -lightning = { version = "0.0.111", path = "../lightning", default-features = false } +lightning = { version = "0.0.112", path = "../lightning", default-features = false } bitcoin = { version = "0.29.0", default-features = false } [dev-dependencies] -lightning = { version = "0.0.111", path = "../lightning", features = ["_test_utils"] } +lightning = { version = "0.0.112", path = "../lightning", features = ["_test_utils"] } diff --git a/lightning/Cargo.toml b/lightning/Cargo.toml index 98e90c41..543c674e 100644 --- a/lightning/Cargo.toml +++ b/lightning/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lightning" -version = "0.0.111" +version = "0.0.112" authors = ["Matt Corallo"] license = "MIT OR Apache-2.0" repository = "https://github.com/lightningdevkit/rust-lightning/" diff --git a/lightning/src/chain/keysinterface.rs b/lightning/src/chain/keysinterface.rs index e3108fd5..b12eee01 100644 --- a/lightning/src/chain/keysinterface.rs +++ b/lightning/src/chain/keysinterface.rs @@ -352,7 +352,7 @@ pub trait BaseSign { /// Computes the signature for a commitment transaction's anchor output used as an /// input within `anchor_tx`, which spends the commitment transaction, at index `input`. fn sign_holder_anchor_input( - &self, anchor_tx: &mut Transaction, input: usize, secp_ctx: &Secp256k1, + &self, anchor_tx: &Transaction, input: usize, secp_ctx: &Secp256k1, ) -> Result; /// Signs a channel announcement message with our funding key and our node secret key (aka @@ -790,7 +790,7 @@ impl BaseSign for InMemorySigner { } fn sign_holder_anchor_input( - &self, anchor_tx: &mut Transaction, input: usize, secp_ctx: &Secp256k1, + &self, anchor_tx: &Transaction, input: usize, secp_ctx: &Secp256k1, ) -> Result { let witness_script = chan_utils::get_anchor_redeemscript(&self.holder_channel_pubkeys.funding_pubkey); let sighash = sighash::SighashCache::new(&*anchor_tx).segwit_signature_hash( diff --git a/lightning/src/ln/chanmon_update_fail_tests.rs b/lightning/src/ln/chanmon_update_fail_tests.rs index f1687525..a78cf50a 100644 --- a/lightning/src/ln/chanmon_update_fail_tests.rs +++ b/lightning/src/ln/chanmon_update_fail_tests.rs @@ -2231,7 +2231,7 @@ fn do_channel_holding_cell_serialize(disconnect: bool, reload_a: bool) { let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]); let persister: test_utils::TestPersister; let new_chain_monitor: test_utils::TestChainMonitor; - let nodes_0_deserialized: ChannelManager; + let nodes_0_deserialized: ChannelManager<&test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>; let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs); let chan_id = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 15_000_000, 7_000_000_000, channelmanager::provided_init_features(), channelmanager::provided_init_features()).2; @@ -2305,7 +2305,7 @@ fn do_channel_holding_cell_serialize(disconnect: bool, reload_a: bool) { nodes_0_deserialized = { let mut channel_monitors = HashMap::new(); channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor); - <(BlockHash, ChannelManager)>::read(&mut nodes_0_read, ChannelManagerReadArgs { + <(BlockHash, ChannelManager<&test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs { default_config: config, keys_manager, fee_estimator: node_cfgs[0].fee_estimator, @@ -2756,7 +2756,7 @@ fn do_test_outbound_reload_without_init_mon(use_0conf: bool) { let persister: test_utils::TestPersister; let new_chain_monitor: test_utils::TestChainMonitor; - let nodes_0_deserialized: ChannelManager; + let nodes_0_deserialized: ChannelManager<&test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>; let mut chan_config = test_default_channel_config(); chan_config.manually_accept_inbound_channels = true; @@ -2834,7 +2834,7 @@ fn do_test_outbound_reload_without_init_mon(use_0conf: bool) { let mut nodes_0_read = &nodes_0_serialized[..]; let config = UserConfig::default(); nodes_0_deserialized = { - <(BlockHash, ChannelManager)>::read(&mut nodes_0_read, ChannelManagerReadArgs { + <(BlockHash, ChannelManager<&test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs { default_config: config, keys_manager, fee_estimator: node_cfgs[0].fee_estimator, @@ -2866,7 +2866,7 @@ fn do_test_inbound_reload_without_init_mon(use_0conf: bool, lock_commitment: boo let persister: test_utils::TestPersister; let new_chain_monitor: test_utils::TestChainMonitor; - let nodes_1_deserialized: ChannelManager; + let nodes_1_deserialized: ChannelManager<&test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>; let mut chan_config = test_default_channel_config(); chan_config.manually_accept_inbound_channels = true; @@ -2940,7 +2940,7 @@ fn do_test_inbound_reload_without_init_mon(use_0conf: bool, lock_commitment: boo let mut nodes_1_read = &nodes_1_serialized[..]; let config = UserConfig::default(); nodes_1_deserialized = { - <(BlockHash, ChannelManager)>::read(&mut nodes_1_read, ChannelManagerReadArgs { + <(BlockHash, ChannelManager<&test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_1_read, ChannelManagerReadArgs { default_config: config, keys_manager, fee_estimator: node_cfgs[1].fee_estimator, diff --git a/lightning/src/ln/channelmanager.rs b/lightning/src/ln/channelmanager.rs index e3128d15..358af825 100644 --- a/lightning/src/ln/channelmanager.rs +++ b/lightning/src/ln/channelmanager.rs @@ -51,7 +51,7 @@ use crate::ln::msgs; use crate::ln::onion_utils; use crate::ln::msgs::{ChannelMessageHandler, DecodeError, LightningError, MAX_VALUE_MSAT}; use crate::ln::wire::Encode; -use crate::chain::keysinterface::{Sign, KeysInterface, KeysManager, InMemorySigner, Recipient}; +use crate::chain::keysinterface::{Sign, KeysInterface, KeysManager, Recipient}; use crate::util::config::{UserConfig, ChannelConfig}; use crate::util::events::{EventHandler, EventsProvider, MessageSendEvent, MessageSendEventsProvider, ClosureReason, HTLCDestination}; use crate::util::{byte_utils, events}; @@ -617,7 +617,7 @@ impl PendingOutboundPayment { /// concrete type of the KeysManager. /// /// (C-not exported) as Arcs don't make sense in bindings -pub type SimpleArcChannelManager = ChannelManager, Arc, Arc, Arc, Arc>; +pub type SimpleArcChannelManager = ChannelManager, Arc, Arc, Arc, Arc>; /// SimpleRefChannelManager is a type alias for a ChannelManager reference, and is the reference /// counterpart to the SimpleArcChannelManager type alias. Use this type by default when you don't @@ -629,7 +629,7 @@ pub type SimpleArcChannelManager = ChannelManager = ChannelManager; +pub type SimpleRefChannelManager<'a, 'b, 'c, 'd, 'e, M, T, F, L> = ChannelManager<&'a M, &'b T, &'c KeysManager, &'d F, &'e L>; /// Manager which keeps track of a number of channels and sends messages to the appropriate /// channel, also tracking HTLC preimages and forwarding onion packets appropriately. @@ -699,10 +699,10 @@ pub type SimpleRefChannelManager<'a, 'b, 'c, 'd, 'e, M, T, F, L> = ChannelManage // | | // | |__`pending_background_events` // -pub struct ChannelManager - where M::Target: chain::Watch, +pub struct ChannelManager + where M::Target: chain::Watch<::Signer>, T::Target: BroadcasterInterface, - K::Target: KeysInterface, + K::Target: KeysInterface, F::Target: FeeEstimator, L::Target: Logger, { @@ -721,9 +721,9 @@ pub struct ChannelManager>, + pub(super) channel_state: Mutex::Signer>>, #[cfg(not(any(test, feature = "_test_utils")))] - channel_state: Mutex>, + channel_state: Mutex::Signer>>, /// Storage for PaymentSecrets and any requirements on future inbound payments before we will /// expose them to users via a PaymentReceived event. HTLCs which do not meet the requirements @@ -1592,10 +1592,10 @@ macro_rules! post_handle_chan_restoration { } } } -impl ChannelManager - where M::Target: chain::Watch, +impl ChannelManager + where M::Target: chain::Watch<::Signer>, T::Target: BroadcasterInterface, - K::Target: KeysInterface, + K::Target: KeysInterface, F::Target: FeeEstimator, L::Target: Logger, { @@ -1761,7 +1761,7 @@ impl ChannelMana Ok(temporary_channel_id) } - fn list_channels_with_filter)) -> bool>(&self, f: Fn) -> Vec { + fn list_channels_with_filter::Signer>)) -> bool>(&self, f: Fn) -> Vec { let mut res = Vec::new(); { let channel_state = self.channel_state.lock().unwrap(); @@ -1843,7 +1843,7 @@ impl ChannelMana } /// Helper function that issues the channel close events - fn issue_channel_close_events(&self, channel: &Channel, closure_reason: ClosureReason) { + fn issue_channel_close_events(&self, channel: &Channel<::Signer>, closure_reason: ClosureReason) { let mut pending_events_lock = self.pending_events.lock().unwrap(); match channel.unbroadcasted_funding() { Some(transaction) => { @@ -2379,7 +2379,7 @@ impl ChannelMana /// [`MessageSendEvent::BroadcastChannelUpdate`] event. /// /// May be called with channel_state already locked! - fn get_channel_update_for_broadcast(&self, chan: &Channel) -> Result { + fn get_channel_update_for_broadcast(&self, chan: &Channel<::Signer>) -> Result { if !chan.should_announce() { return Err(LightningError { err: "Cannot broadcast a channel_update for a private channel".to_owned(), @@ -2398,7 +2398,7 @@ impl ChannelMana /// and thus MUST NOT be called unless the recipient of the resulting message has already /// provided evidence that they know about the existence of the channel. /// May be called with channel_state already locked! - fn get_channel_update_for_unicast(&self, chan: &Channel) -> Result { + fn get_channel_update_for_unicast(&self, chan: &Channel<::Signer>) -> Result { log_trace!(self.logger, "Attempting to generate channel update for channel {}", log_bytes!(chan.channel_id())); let short_channel_id = match chan.get_short_channel_id().or(chan.latest_inbound_scid_alias()) { None => return Err(LightningError{err: "Channel not yet established".to_owned(), action: msgs::ErrorAction::IgnoreError}), @@ -2407,7 +2407,7 @@ impl ChannelMana self.get_channel_update_for_onion(short_channel_id, chan) } - fn get_channel_update_for_onion(&self, short_channel_id: u64, chan: &Channel) -> Result { + fn get_channel_update_for_onion(&self, short_channel_id: u64, chan: &Channel<::Signer>) -> Result { log_trace!(self.logger, "Generating channel update for channel {}", log_bytes!(chan.channel_id())); let were_node_one = PublicKey::from_secret_key(&self.secp_ctx, &self.our_network_key).serialize()[..] < chan.get_counterparty_node_id().serialize()[..]; @@ -2832,7 +2832,7 @@ impl ChannelMana /// Handles the generation of a funding transaction, optionally (for tests) with a function /// which checks the correctness of the funding transaction given the associated channel. - fn funding_transaction_generated_intern, &Transaction) -> Result>( + fn funding_transaction_generated_intern::Signer>, &Transaction) -> Result>( &self, temporary_channel_id: &[u8; 32], _counterparty_node_id: &PublicKey, funding_transaction: Transaction, find_funding_output: FundingOutput ) -> Result<(), APIError> { let (chan, msg) = { @@ -3492,7 +3492,7 @@ impl ChannelMana self.process_background_events(); } - fn update_channel_fee(&self, short_to_chan_info: &mut HashMap, pending_msg_events: &mut Vec, chan_id: &[u8; 32], chan: &mut Channel, new_feerate: u32) -> (bool, NotifyOption, Result<(), MsgHandleErrInternal>) { + fn update_channel_fee(&self, short_to_chan_info: &mut HashMap, pending_msg_events: &mut Vec, chan_id: &[u8; 32], chan: &mut Channel<::Signer>, new_feerate: u32) -> (bool, NotifyOption, Result<(), MsgHandleErrInternal>) { if !chan.is_outbound() { return (true, NotifyOption::SkipPersist, Ok(())); } // If the feerate has decreased by less than half, don't bother if new_feerate <= chan.get_feerate() && new_feerate * 2 > chan.get_feerate() { @@ -3723,7 +3723,7 @@ impl ChannelMana /// /// This is for failures on the channel on which the HTLC was *received*, not failures /// forwarding - fn get_htlc_inbound_temp_fail_err_and_data(&self, desired_err_code: u16, chan: &Channel) -> (u16, Vec) { + fn get_htlc_inbound_temp_fail_err_and_data(&self, desired_err_code: u16, chan: &Channel<::Signer>) -> (u16, Vec) { // We can't be sure what SCID was used when relaying inbound towards us, so we have to // guess somewhat. If its a public channel, we figure best to just use the real SCID (as // we're not leaking that we have a channel with the counterparty), otherwise we try to use @@ -3743,7 +3743,7 @@ impl ChannelMana /// Gets an HTLC onion failure code and error data for an `UPDATE` error, given the error code /// that we want to return and a channel. - fn get_htlc_temp_fail_err_and_data(&self, desired_err_code: u16, scid: u64, chan: &Channel) -> (u16, Vec) { + fn get_htlc_temp_fail_err_and_data(&self, desired_err_code: u16, scid: u64, chan: &Channel<::Signer>) -> (u16, Vec) { debug_assert_eq!(desired_err_code & 0x1000, 0x1000); if let Ok(upd) = self.get_channel_update_for_onion(scid, chan) { let mut enc = VecWriter(Vec::with_capacity(upd.serialized_length() + 6)); @@ -4113,7 +4113,7 @@ impl ChannelMana } } - fn claim_funds_from_hop(&self, channel_state_lock: &mut MutexGuard>, prev_hop: HTLCPreviousHopData, payment_preimage: PaymentPreimage) -> ClaimFundsFromHop { + fn claim_funds_from_hop(&self, channel_state_lock: &mut MutexGuard::Signer>>, prev_hop: HTLCPreviousHopData, payment_preimage: PaymentPreimage) -> ClaimFundsFromHop { //TODO: Delay the claimed_funds relaying just like we do outbound relay! let channel_state = &mut **channel_state_lock; let chan_id = match channel_state.short_to_chan_info.get(&prev_hop.short_channel_id) { @@ -4206,7 +4206,7 @@ impl ChannelMana } } - fn claim_funds_internal(&self, mut channel_state_lock: MutexGuard>, source: HTLCSource, payment_preimage: PaymentPreimage, forwarded_htlc_value_msat: Option, from_onchain: bool, next_channel_id: [u8; 32]) { + fn claim_funds_internal(&self, mut channel_state_lock: MutexGuard::Signer>>, source: HTLCSource, payment_preimage: PaymentPreimage, forwarded_htlc_value_msat: Option, from_onchain: bool, next_channel_id: [u8; 32]) { match source { HTLCSource::OutboundRoute { session_priv, payment_id, path, .. } => { mem::drop(channel_state_lock); @@ -4795,7 +4795,7 @@ impl ChannelMana return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!".to_owned(), msg.channel_id)); } - let create_pending_htlc_status = |chan: &Channel, pending_forward_info: PendingHTLCStatus, error_code: u16| { + let create_pending_htlc_status = |chan: &Channel<::Signer>, pending_forward_info: PendingHTLCStatus, error_code: u16| { // If the update_add is completely bogus, the call will Err and we will close, // but if we've sent a shutdown and they haven't acknowledged it yet, we just // want to reject the new HTLC and fail it backwards instead of forwarding. @@ -5568,10 +5568,10 @@ impl ChannelMana } } -impl MessageSendEventsProvider for ChannelManager - where M::Target: chain::Watch, +impl MessageSendEventsProvider for ChannelManager + where M::Target: chain::Watch<::Signer>, T::Target: BroadcasterInterface, - K::Target: KeysInterface, + K::Target: KeysInterface, F::Target: FeeEstimator, L::Target: Logger, { @@ -5607,11 +5607,11 @@ impl MessageSend } } -impl EventsProvider for ChannelManager +impl EventsProvider for ChannelManager where - M::Target: chain::Watch, + M::Target: chain::Watch<::Signer>, T::Target: BroadcasterInterface, - K::Target: KeysInterface, + K::Target: KeysInterface, F::Target: FeeEstimator, L::Target: Logger, { @@ -5643,11 +5643,11 @@ where } } -impl chain::Listen for ChannelManager +impl chain::Listen for ChannelManager where - M::Target: chain::Watch, + M::Target: chain::Watch<::Signer>, T::Target: BroadcasterInterface, - K::Target: KeysInterface, + K::Target: KeysInterface, F::Target: FeeEstimator, L::Target: Logger, { @@ -5680,11 +5680,11 @@ where } } -impl chain::Confirm for ChannelManager +impl chain::Confirm for ChannelManager where - M::Target: chain::Watch, + M::Target: chain::Watch<::Signer>, T::Target: BroadcasterInterface, - K::Target: KeysInterface, + K::Target: KeysInterface, F::Target: FeeEstimator, L::Target: Logger, { @@ -5782,18 +5782,18 @@ where } } -impl ChannelManager +impl ChannelManager where - M::Target: chain::Watch, + M::Target: chain::Watch<::Signer>, T::Target: BroadcasterInterface, - K::Target: KeysInterface, + K::Target: KeysInterface, F::Target: FeeEstimator, 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 /// the function. - fn do_chain_event) -> Result<(Option, Vec<(HTLCSource, PaymentHash)>, Option), ClosureReason>> + fn do_chain_event::Signer>) -> Result<(Option, Vec<(HTLCSource, PaymentHash)>, Option), ClosureReason>> (&self, height_opt: Option, f: FN) { // Note that we MUST NOT end up calling methods on self.chain_monitor here - we're called // during initialization prior to the chain_monitor being fully configured in some cases. @@ -5951,11 +5951,11 @@ where } } -impl - ChannelMessageHandler for ChannelManager - where M::Target: chain::Watch, +impl + ChannelMessageHandler for ChannelManager + where M::Target: chain::Watch<::Signer>, T::Target: BroadcasterInterface, - K::Target: KeysInterface, + K::Target: KeysInterface, F::Target: FeeEstimator, L::Target: Logger, { @@ -6590,10 +6590,10 @@ impl_writeable_tlv_based_enum_upgradable!(PendingOutboundPayment, }, ); -impl Writeable for ChannelManager - where M::Target: chain::Watch, +impl Writeable for ChannelManager + where M::Target: chain::Watch<::Signer>, T::Target: BroadcasterInterface, - K::Target: KeysInterface, + K::Target: KeysInterface, F::Target: FeeEstimator, L::Target: Logger, { @@ -6839,29 +6839,29 @@ impl<'a, Signer: 'a + Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> // Implement ReadableArgs for an Arc'd ChannelManager to make it a bit easier to work with the // SipmleArcChannelManager type: -impl<'a, Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> - ReadableArgs> for (BlockHash, Arc>) - where M::Target: chain::Watch, +impl<'a, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> + ReadableArgs::Signer, M, T, K, F, L>> for (BlockHash, Arc>) + where M::Target: chain::Watch<::Signer>, T::Target: BroadcasterInterface, - K::Target: KeysInterface, + K::Target: KeysInterface, F::Target: FeeEstimator, L::Target: Logger, { - fn read(reader: &mut R, args: ChannelManagerReadArgs<'a, Signer, M, T, K, F, L>) -> Result { - let (blockhash, chan_manager) = <(BlockHash, ChannelManager)>::read(reader, args)?; + fn read(reader: &mut R, args: ChannelManagerReadArgs<'a, ::Signer, M, T, K, F, L>) -> Result { + let (blockhash, chan_manager) = <(BlockHash, ChannelManager)>::read(reader, args)?; Ok((blockhash, Arc::new(chan_manager))) } } -impl<'a, Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> - ReadableArgs> for (BlockHash, ChannelManager) - where M::Target: chain::Watch, +impl<'a, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> + ReadableArgs::Signer, M, T, K, F, L>> for (BlockHash, ChannelManager) + where M::Target: chain::Watch<::Signer>, T::Target: BroadcasterInterface, - K::Target: KeysInterface, + K::Target: KeysInterface, F::Target: FeeEstimator, L::Target: Logger, { - fn read(reader: &mut R, mut args: ChannelManagerReadArgs<'a, Signer, M, T, K, F, L>) -> Result { + fn read(reader: &mut R, mut args: ChannelManagerReadArgs<'a, ::Signer, M, T, K, F, L>) -> Result { let _ver = read_ver_prefix!(reader, SERIALIZATION_VERSION); let genesis_hash: BlockHash = Readable::read(reader)?; @@ -6877,7 +6877,7 @@ impl<'a, Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> let mut short_to_chan_info = HashMap::with_capacity(cmp::min(channel_count as usize, 128)); let mut channel_closures = Vec::new(); for _ in 0..channel_count { - let mut channel: Channel = Channel::read(reader, (&args.keys_manager, best_block_height))?; + let mut channel: Channel<::Signer> = Channel::read(reader, (&args.keys_manager, best_block_height))?; let funding_txo = channel.get_funding_txo().ok_or(DecodeError::InvalidValue)?; funding_txo_set.insert(funding_txo.clone()); if let Some(ref mut monitor) = args.channel_monitors.get_mut(&funding_txo) { @@ -7893,12 +7893,12 @@ pub mod bench { use test::Bencher; struct NodeHolder<'a, P: Persist> { - node: &'a ChannelManager, &'a test_utils::TestBroadcaster, &'a KeysManager, - &'a test_utils::TestFeeEstimator, &'a test_utils::TestLogger> + &'a test_utils::TestFeeEstimator, &'a test_utils::TestLogger>, } #[cfg(test)] diff --git a/lightning/src/ln/functional_test_utils.rs b/lightning/src/ln/functional_test_utils.rs index 6e6155f6..84fe089d 100644 --- a/lightning/src/ln/functional_test_utils.rs +++ b/lightning/src/ln/functional_test_utils.rs @@ -278,7 +278,7 @@ pub struct Node<'a, 'b: 'a, 'c: 'b> { pub tx_broadcaster: &'c test_utils::TestBroadcaster, pub chain_monitor: &'b test_utils::TestChainMonitor<'c>, pub keys_manager: &'b test_utils::TestKeysInterface, - pub node: &'a ChannelManager, &'c test_utils::TestBroadcaster, &'b test_utils::TestKeysInterface, &'c test_utils::TestFeeEstimator, &'c test_utils::TestLogger>, + pub node: &'a ChannelManager<&'b TestChainMonitor<'c>, &'c test_utils::TestBroadcaster, &'b test_utils::TestKeysInterface, &'c test_utils::TestFeeEstimator, &'c test_utils::TestLogger>, pub network_graph: &'b NetworkGraph<&'c test_utils::TestLogger>, pub gossip_sync: P2PGossipSync<&'b NetworkGraph<&'c test_utils::TestLogger>, &'c test_utils::TestChainSource, &'c test_utils::TestLogger>, pub node_seed: [u8; 32], @@ -378,7 +378,7 @@ impl<'a, 'b, 'c> Drop for Node<'a, 'b, 'c> { let mut w = test_utils::TestVecWriter(Vec::new()); self.node.write(&mut w).unwrap(); - <(BlockHash, ChannelManager)>::read(&mut io::Cursor::new(w.0), ChannelManagerReadArgs { + <(BlockHash, ChannelManager<&test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut io::Cursor::new(w.0), ChannelManagerReadArgs { default_config: *self.node.get_current_default_configuration(), keys_manager: self.keys_manager, fee_estimator: &test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }, @@ -2071,7 +2071,7 @@ pub fn test_default_channel_config() -> UserConfig { default_config } -pub fn create_node_chanmgrs<'a, 'b>(node_count: usize, cfgs: &'a Vec>, node_config: &[Option]) -> Vec, &'b test_utils::TestBroadcaster, &'a test_utils::TestKeysInterface, &'b test_utils::TestFeeEstimator, &'b test_utils::TestLogger>> { +pub fn create_node_chanmgrs<'a, 'b>(node_count: usize, cfgs: &'a Vec>, node_config: &[Option]) -> Vec, &'b test_utils::TestBroadcaster, &'a test_utils::TestKeysInterface, &'b test_utils::TestFeeEstimator, &'b test_utils::TestLogger>> { let mut chanmgrs = Vec::new(); for i in 0..node_count { let network = Network::Testnet; @@ -2087,7 +2087,7 @@ pub fn create_node_chanmgrs<'a, 'b>(node_count: usize, cfgs: &'a Vec chanmgrs } -pub fn create_network<'a, 'b: 'a, 'c: 'b>(node_count: usize, cfgs: &'b Vec>, chan_mgrs: &'a Vec, &'c test_utils::TestBroadcaster, &'b test_utils::TestKeysInterface, &'c test_utils::TestFeeEstimator, &'c test_utils::TestLogger>>) -> Vec> { +pub fn create_network<'a, 'b: 'a, 'c: 'b>(node_count: usize, cfgs: &'b Vec>, chan_mgrs: &'a Vec, &'c test_utils::TestBroadcaster, &'b test_utils::TestKeysInterface, &'c test_utils::TestFeeEstimator, &'c test_utils::TestLogger>>) -> Vec> { let mut nodes = Vec::new(); let chan_count = Rc::new(RefCell::new(0)); let payment_count = Rc::new(RefCell::new(0)); diff --git a/lightning/src/ln/functional_tests.rs b/lightning/src/ln/functional_tests.rs index 5d7049b7..eb6d7032 100644 --- a/lightning/src/ln/functional_tests.rs +++ b/lightning/src/ln/functional_tests.rs @@ -3863,7 +3863,7 @@ fn test_funding_peer_disconnect() { let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]); let persister: test_utils::TestPersister; let new_chain_monitor: test_utils::TestChainMonitor; - let nodes_0_deserialized: ChannelManager; + let nodes_0_deserialized: ChannelManager<&test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>; let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs); let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features()); @@ -4009,7 +4009,7 @@ fn test_funding_peer_disconnect() { let (_, nodes_0_deserialized_tmp) = { let mut channel_monitors = HashMap::new(); channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor); - <(BlockHash, ChannelManager)>::read(&mut nodes_0_read, ChannelManagerReadArgs { + <(BlockHash, ChannelManager<&test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs { default_config: UserConfig::default(), keys_manager, fee_estimator: node_cfgs[0].fee_estimator, @@ -4350,7 +4350,7 @@ fn test_no_txn_manager_serialize_deserialize() { let fee_estimator: test_utils::TestFeeEstimator; let persister: test_utils::TestPersister; let new_chain_monitor: test_utils::TestChainMonitor; - let nodes_0_deserialized: ChannelManager; + let nodes_0_deserialized: ChannelManager<&test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>; let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs); let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features()); @@ -4378,7 +4378,7 @@ fn test_no_txn_manager_serialize_deserialize() { let (_, nodes_0_deserialized_tmp) = { let mut channel_monitors = HashMap::new(); channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor); - <(BlockHash, ChannelManager)>::read(&mut nodes_0_read, ChannelManagerReadArgs { + <(BlockHash, ChannelManager<&test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs { default_config: config, keys_manager, fee_estimator: &fee_estimator, @@ -4428,7 +4428,7 @@ fn test_manager_serialize_deserialize_events() { let persister: test_utils::TestPersister; let logger: test_utils::TestLogger; let new_chain_monitor: test_utils::TestChainMonitor; - let nodes_0_deserialized: ChannelManager; + let nodes_0_deserialized: ChannelManager<&test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>; let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs); // Start creating a channel, but stop right before broadcasting the funding transaction @@ -4489,7 +4489,7 @@ fn test_manager_serialize_deserialize_events() { let (_, nodes_0_deserialized_tmp) = { let mut channel_monitors = HashMap::new(); channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor); - <(BlockHash, ChannelManager)>::read(&mut nodes_0_read, ChannelManagerReadArgs { + <(BlockHash, ChannelManager<&test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs { default_config: config, keys_manager, fee_estimator: &fee_estimator, @@ -4548,7 +4548,7 @@ fn test_simple_manager_serialize_deserialize() { let fee_estimator: test_utils::TestFeeEstimator; let persister: test_utils::TestPersister; let new_chain_monitor: test_utils::TestChainMonitor; - let nodes_0_deserialized: ChannelManager; + let nodes_0_deserialized: ChannelManager<&test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>; let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs); let chan_id = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features()).2; @@ -4576,7 +4576,7 @@ fn test_simple_manager_serialize_deserialize() { let (_, nodes_0_deserialized_tmp) = { let mut channel_monitors = HashMap::new(); channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor); - <(BlockHash, ChannelManager)>::read(&mut nodes_0_read, ChannelManagerReadArgs { + <(BlockHash, ChannelManager<&test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs { default_config: UserConfig::default(), keys_manager, fee_estimator: &fee_estimator, @@ -4610,7 +4610,7 @@ fn test_manager_serialize_deserialize_inconsistent_monitor() { let fee_estimator: test_utils::TestFeeEstimator; let persister: test_utils::TestPersister; let new_chain_monitor: test_utils::TestChainMonitor; - let nodes_0_deserialized: ChannelManager; + let nodes_0_deserialized: ChannelManager<&test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>; let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs); let chan_id_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features()).2; let chan_id_2 = create_announced_chan_between_nodes(&nodes, 2, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features()).2; @@ -4668,7 +4668,7 @@ fn test_manager_serialize_deserialize_inconsistent_monitor() { let mut nodes_0_read = &nodes_0_serialized[..]; if let Err(msgs::DecodeError::InvalidValue) = - <(BlockHash, ChannelManager)>::read(&mut nodes_0_read, ChannelManagerReadArgs { + <(BlockHash, ChannelManager<&test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs { default_config: UserConfig::default(), keys_manager, fee_estimator: &fee_estimator, @@ -4682,7 +4682,7 @@ fn test_manager_serialize_deserialize_inconsistent_monitor() { let mut nodes_0_read = &nodes_0_serialized[..]; let (_, nodes_0_deserialized_tmp) = - <(BlockHash, ChannelManager)>::read(&mut nodes_0_read, ChannelManagerReadArgs { + <(BlockHash, ChannelManager<&test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs { default_config: UserConfig::default(), keys_manager, fee_estimator: &fee_estimator, @@ -7528,7 +7528,7 @@ fn do_test_data_loss_protect(reconnect_panicing: bool) { node_state_0 = { let mut channel_monitors = HashMap::new(); channel_monitors.insert(OutPoint { txid: chan.3.txid(), index: 0 }, &mut chain_monitor); - <(BlockHash, ChannelManager)>::read(&mut io::Cursor::new(previous_node_state), ChannelManagerReadArgs { + <(BlockHash, ChannelManager<&test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut io::Cursor::new(previous_node_state), ChannelManagerReadArgs { keys_manager: keys_manager, fee_estimator: &fee_estimator, chain_monitor: &monitor, @@ -9679,7 +9679,7 @@ fn test_forwardable_regen() { let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]); let persister: test_utils::TestPersister; let new_chain_monitor: test_utils::TestChainMonitor; - let nodes_1_deserialized: ChannelManager; + let nodes_1_deserialized: ChannelManager<&test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>; let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs); let chan_id_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features()).2; let chan_id_2 = create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features()).2; @@ -9741,7 +9741,7 @@ fn test_forwardable_regen() { let mut channel_monitors = HashMap::new(); channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor); channel_monitors.insert(chan_1_monitor.get_funding_txo().0, &mut chan_1_monitor); - <(BlockHash, ChannelManager)>::read(&mut nodes_1_read, ChannelManagerReadArgs { + <(BlockHash, ChannelManager<&test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_1_read, ChannelManagerReadArgs { default_config: UserConfig::default(), keys_manager, fee_estimator: node_cfgs[1].fee_estimator, @@ -10121,7 +10121,7 @@ fn do_test_partial_claim_before_restart(persist_both_monitors: bool) { let persister: test_utils::TestPersister; let new_chain_monitor: test_utils::TestChainMonitor; - let nodes_3_deserialized: ChannelManager; + let nodes_3_deserialized: ChannelManager<&test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>; let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs); @@ -10206,7 +10206,7 @@ fn do_test_partial_claim_before_restart(persist_both_monitors: bool) { for monitor in monitors.iter_mut() { channel_monitors.insert(monitor.get_funding_txo().0, monitor); } - <(BlockHash, ChannelManager)>::read(&mut &original_manager.0[..], ChannelManagerReadArgs { + <(BlockHash, ChannelManager<&test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut &original_manager.0[..], ChannelManagerReadArgs { default_config: config, keys_manager, fee_estimator: node_cfgs[3].fee_estimator, diff --git a/lightning/src/ln/msgs.rs b/lightning/src/ln/msgs.rs index 58339339..8b5a6ac6 100644 --- a/lightning/src/ln/msgs.rs +++ b/lightning/src/ln/msgs.rs @@ -66,8 +66,7 @@ pub enum DecodeError { /// A length descriptor in the packet didn't describe the later data correctly BadLengthDescriptor, /// Error from std::io - Io(/// (C-not exported) as ErrorKind doesn't have a reasonable mapping - io::ErrorKind), + Io(io::ErrorKind), /// The message included zlib-compressed values, which we don't support. UnsupportedCompression, } diff --git a/lightning/src/ln/onion_route_tests.rs b/lightning/src/ln/onion_route_tests.rs index 0b6012f6..97d8de96 100644 --- a/lightning/src/ln/onion_route_tests.rs +++ b/lightning/src/ln/onion_route_tests.rs @@ -766,7 +766,7 @@ fn do_test_onion_failure_stale_channel_update(announced_channel: bool) { channel_monitors.insert(chanmon_1.get_funding_txo().0, &mut chanmon_1); channel_monitors.insert(chanmon_2.get_funding_txo().0, &mut chanmon_2); - let chanmgr = <(_, ChannelManager<_, _, _, _, _, _>)>::read( + let chanmgr = <(_, ChannelManager<_, _, _, _, _>)>::read( &mut &nodes[1].node.encode()[..], ChannelManagerReadArgs { default_config: *nodes[1].node.get_current_default_configuration(), keys_manager: nodes[1].keys_manager, diff --git a/lightning/src/ln/onion_utils.rs b/lightning/src/ln/onion_utils.rs index 598edcf0..95331395 100644 --- a/lightning/src/ln/onion_utils.rs +++ b/lightning/src/ln/onion_utils.rs @@ -589,31 +589,6 @@ pub(super) fn process_onion_failure(secp_ctx: & } else { unreachable!(); } } -/// An input used when decoding an onion packet. -pub(crate) trait DecodeInput { - type Arg; - /// If Some, this is the input when checking the hmac of the onion packet. - fn payment_hash(&self) -> Option<&PaymentHash>; - /// Read argument when decrypting our hop payload. - fn read_arg(self) -> Self::Arg; -} - -impl DecodeInput for PaymentHash { - type Arg = (); - fn payment_hash(&self) -> Option<&PaymentHash> { - Some(self) - } - fn read_arg(self) -> Self::Arg { () } -} - -impl DecodeInput for SharedSecret { - type Arg = SharedSecret; - fn payment_hash(&self) -> Option<&PaymentHash> { - None - } - fn read_arg(self) -> Self::Arg { self } -} - /// Allows `decode_next_hop` to return the next hop packet bytes for either payments or onion /// message forwards. pub(crate) trait NextPacketBytes: AsMut<[u8]> { @@ -664,7 +639,7 @@ pub(crate) enum OnionDecodeErr { } pub(crate) fn decode_next_payment_hop(shared_secret: [u8; 32], hop_data: &[u8], hmac_bytes: [u8; 32], payment_hash: PaymentHash) -> Result { - match decode_next_hop(shared_secret, hop_data, hmac_bytes, payment_hash) { + match decode_next_hop(shared_secret, hop_data, hmac_bytes, Some(payment_hash), ()) { Ok((next_hop_data, None)) => Ok(Hop::Receive(next_hop_data)), Ok((next_hop_data, Some((next_hop_hmac, FixedSizeOnionPacket(new_packet_bytes))))) => { Ok(Hop::Forward { @@ -677,12 +652,16 @@ pub(crate) fn decode_next_payment_hop(shared_secret: [u8; 32], hop_data: &[u8], } } -pub(crate) fn decode_next_hop, N: NextPacketBytes>(shared_secret: [u8; 32], hop_data: &[u8], hmac_bytes: [u8; 32], decode_input: D) -> Result<(R, Option<([u8; 32], N)>), OnionDecodeErr> { +pub(crate) fn decode_next_untagged_hop, N: NextPacketBytes>(shared_secret: [u8; 32], hop_data: &[u8], hmac_bytes: [u8; 32], read_args: T) -> Result<(R, Option<([u8; 32], N)>), OnionDecodeErr> { + decode_next_hop(shared_secret, hop_data, hmac_bytes, None, read_args) +} + +fn decode_next_hop, N: NextPacketBytes>(shared_secret: [u8; 32], hop_data: &[u8], hmac_bytes: [u8; 32], payment_hash: Option, read_args: T) -> Result<(R, Option<([u8; 32], N)>), OnionDecodeErr> { let (rho, mu) = gen_rho_mu_from_shared_secret(&shared_secret); let mut hmac = HmacEngine::::new(&mu); hmac.input(hop_data); - if let Some(payment_hash) = decode_input.payment_hash() { - hmac.input(&payment_hash.0[..]); + if let Some(tag) = payment_hash { + hmac.input(&tag.0[..]); } if !fixed_time_eq(&Hmac::from_engine(hmac).into_inner(), &hmac_bytes) { return Err(OnionDecodeErr::Malformed { @@ -693,7 +672,7 @@ pub(crate) fn decode_next_hop, N: NextPa let mut chacha = ChaCha20::new(&rho, &[0u8; 8]); let mut chacha_stream = ChaChaReader { chacha: &mut chacha, read: Cursor::new(&hop_data[..]) }; - match R::read(&mut chacha_stream, decode_input.read_arg()) { + match R::read(&mut chacha_stream, read_args) { Err(err) => { let error_code = match err { msgs::DecodeError::UnknownVersion => 0x4000 | 1, // unknown realm byte diff --git a/lightning/src/ln/payment_tests.rs b/lightning/src/ln/payment_tests.rs index c22f4611..cdc0b838 100644 --- a/lightning/src/ln/payment_tests.rs +++ b/lightning/src/ln/payment_tests.rs @@ -365,7 +365,7 @@ fn do_retry_with_no_persist(confirm_before_reload: bool) { let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]); let persister: test_utils::TestPersister; let new_chain_monitor: test_utils::TestChainMonitor; - let nodes_0_deserialized: ChannelManager; + let nodes_0_deserialized: ChannelManager<&test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>; let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs); let chan_id = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features()).2; @@ -423,7 +423,7 @@ fn do_retry_with_no_persist(confirm_before_reload: bool) { let (_, nodes_0_deserialized_tmp) = { let mut channel_monitors = HashMap::new(); channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor); - <(BlockHash, ChannelManager)>::read(&mut nodes_0_read, ChannelManagerReadArgs { + <(BlockHash, ChannelManager<&test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs { default_config: test_default_channel_config(), keys_manager, fee_estimator: node_cfgs[0].fee_estimator, @@ -574,13 +574,13 @@ fn do_test_completed_payment_not_retryable_on_reload(use_dust: bool) { let first_persister: test_utils::TestPersister; let first_new_chain_monitor: test_utils::TestChainMonitor; - let first_nodes_0_deserialized: ChannelManager; + let first_nodes_0_deserialized: ChannelManager<&test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>; let second_persister: test_utils::TestPersister; let second_new_chain_monitor: test_utils::TestChainMonitor; - let second_nodes_0_deserialized: ChannelManager; + let second_nodes_0_deserialized: ChannelManager<&test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>; let third_persister: test_utils::TestPersister; let third_new_chain_monitor: test_utils::TestChainMonitor; - let third_nodes_0_deserialized: ChannelManager; + let third_nodes_0_deserialized: ChannelManager<&test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>; let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs); @@ -631,7 +631,7 @@ fn do_test_completed_payment_not_retryable_on_reload(use_dust: bool) { let mut nodes_0_read = &nodes_0_serialized[..]; let (_, nodes_0_deserialized_tmp) = { - <(BlockHash, ChannelManager)>::read(&mut nodes_0_read, ChannelManagerReadArgs { + <(BlockHash, ChannelManager<&test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs { default_config: test_default_channel_config(), keys_manager, fee_estimator: node_cfgs[0].fee_estimator, @@ -799,7 +799,7 @@ fn do_test_dup_htlc_onchain_fails_on_reload(persist_manager_post_event: bool, co let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]); let persister: test_utils::TestPersister; let new_chain_monitor: test_utils::TestChainMonitor; - let nodes_0_deserialized: ChannelManager; + let nodes_0_deserialized: ChannelManager<&test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>; let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs); let (_, _, chan_id, funding_tx) = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features()); @@ -915,7 +915,7 @@ fn do_test_dup_htlc_onchain_fails_on_reload(persist_manager_post_event: bool, co let (_, nodes_0_deserialized_tmp) = { let mut channel_monitors = HashMap::new(); channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor); - <(BlockHash, ChannelManager)> + <(BlockHash, ChannelManager<&test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)> ::read(&mut io::Cursor::new(&chan_manager_serialized.0[..]), ChannelManagerReadArgs { default_config: Default::default(), keys_manager, @@ -972,7 +972,7 @@ fn test_fulfill_restart_failure() { let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]); let persister: test_utils::TestPersister; let new_chain_monitor: test_utils::TestChainMonitor; - let nodes_1_deserialized: ChannelManager; + let nodes_1_deserialized: ChannelManager<&test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>; let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs); let chan_id = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features()).2; @@ -1006,7 +1006,7 @@ fn test_fulfill_restart_failure() { let (_, nodes_1_deserialized_tmp) = { let mut channel_monitors = HashMap::new(); channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor); - <(BlockHash, ChannelManager)> + <(BlockHash, ChannelManager<&test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)> ::read(&mut io::Cursor::new(&chan_manager_serialized.0[..]), ChannelManagerReadArgs { default_config: Default::default(), keys_manager, diff --git a/lightning/src/ln/peer_handler.rs b/lightning/src/ln/peer_handler.rs index 228c2491..351f5142 100644 --- a/lightning/src/ln/peer_handler.rs +++ b/lightning/src/ln/peer_handler.rs @@ -21,7 +21,7 @@ use crate::ln::features::{InitFeatures, NodeFeatures}; use crate::ln::msgs; use crate::ln::msgs::{ChannelMessageHandler, LightningError, NetAddress, OnionMessageHandler, RoutingMessageHandler}; use crate::ln::channelmanager::{SimpleArcChannelManager, SimpleRefChannelManager}; -use crate::util::ser::{MaybeReadableArgs, VecWriter, Writeable, Writer}; +use crate::util::ser::{VecWriter, Writeable, Writer}; use crate::ln::peer_channel_encryptor::{PeerChannelEncryptor,NextNoiseStep}; use crate::ln::wire; use crate::ln::wire::Encode; @@ -97,13 +97,11 @@ impl OnionMessageHandler for IgnoringMessageHandler { } impl CustomOnionMessageHandler for IgnoringMessageHandler { type CustomMessage = Infallible; - fn handle_custom_message(&self, _msg: Self::CustomMessage) { + fn handle_custom_message(&self, _msg: Infallible) { // Since we always return `None` in the read the handle method should never be called. unreachable!(); } -} -impl MaybeReadableArgs for Infallible { - fn read(_buffer: &mut R, _msg_type: u64) -> Result, msgs::DecodeError> where Self: Sized { + fn read_custom_message(&self, _msg_type: u64, _buffer: &mut R) -> Result, msgs::DecodeError> where Self: Sized { Ok(None) } } diff --git a/lightning/src/ln/priv_short_conf_tests.rs b/lightning/src/ln/priv_short_conf_tests.rs index cea6f37c..1f8ffbbf 100644 --- a/lightning/src/ln/priv_short_conf_tests.rs +++ b/lightning/src/ln/priv_short_conf_tests.rs @@ -51,7 +51,7 @@ fn test_priv_forwarding_rejection() { let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, Some(no_announce_cfg), None]); let persister: test_utils::TestPersister; let new_chain_monitor: test_utils::TestChainMonitor; - let nodes_1_deserialized: ChannelManager; + let nodes_1_deserialized: ChannelManager<&test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>; let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs); let chan_id_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 500_000_000, channelmanager::provided_init_features(), channelmanager::provided_init_features()).2; @@ -124,7 +124,7 @@ fn test_priv_forwarding_rejection() { let mut channel_monitors = HashMap::new(); channel_monitors.insert(monitor_a.get_funding_txo().0, &mut monitor_a); channel_monitors.insert(monitor_b.get_funding_txo().0, &mut monitor_b); - <(BlockHash, ChannelManager)>::read(&mut nodes_1_read, ChannelManagerReadArgs { + <(BlockHash, ChannelManager<&test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_1_read, ChannelManagerReadArgs { default_config: no_announce_cfg, keys_manager, fee_estimator: node_cfgs[1].fee_estimator, diff --git a/lightning/src/ln/reorg_tests.rs b/lightning/src/ln/reorg_tests.rs index 9d02009f..a80a1659 100644 --- a/lightning/src/ln/reorg_tests.rs +++ b/lightning/src/ln/reorg_tests.rs @@ -267,7 +267,7 @@ fn do_test_unconf_chan(reload_node: bool, reorg_after_reload: bool, use_funding_ let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]); let persister: test_utils::TestPersister; let new_chain_monitor: test_utils::TestChainMonitor; - let nodes_0_deserialized: ChannelManager; + let nodes_0_deserialized: ChannelManager<&test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>; let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs); *nodes[0].connect_style.borrow_mut() = connect_style; @@ -321,7 +321,7 @@ fn do_test_unconf_chan(reload_node: bool, reorg_after_reload: bool, use_funding_ nodes_0_deserialized = { let mut channel_monitors = HashMap::new(); channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor); - <(BlockHash, ChannelManager)>::read( &mut nodes_0_read, ChannelManagerReadArgs { default_config: *nodes[0].node.get_current_default_configuration(), diff --git a/lightning/src/onion_message/functional_tests.rs b/lightning/src/onion_message/functional_tests.rs index 81826a62..bd0a884a 100644 --- a/lightning/src/onion_message/functional_tests.rs +++ b/lightning/src/onion_message/functional_tests.rs @@ -14,7 +14,7 @@ use crate::ln::features::InitFeatures; use crate::ln::msgs::{self, DecodeError, OnionMessageHandler}; use super::{BlindedRoute, CustomOnionMessageContents, CustomOnionMessageHandler, Destination, OnionMessageContents, OnionMessenger, SendError}; use crate::util::enforcing_trait_impls::EnforcingSigner; -use crate::util::ser::{MaybeReadableArgs, Writeable, Writer}; +use crate::util::ser::{ Writeable, Writer}; use crate::util::test_utils; use bitcoin::network::constants::Network; @@ -54,8 +54,12 @@ impl Writeable for TestCustomMessage { } } -impl MaybeReadableArgs for TestCustomMessage { - fn read(buffer: &mut R, message_type: u64) -> Result, DecodeError> where Self: Sized { +struct TestCustomMessageHandler {} + +impl CustomOnionMessageHandler for TestCustomMessageHandler { + type CustomMessage = TestCustomMessage; + fn handle_custom_message(&self, _msg: Self::CustomMessage) {} + fn read_custom_message(&self, message_type: u64, buffer: &mut R) -> Result, DecodeError> where Self: Sized { if message_type == CUSTOM_MESSAGE_TYPE { let mut buf = Vec::new(); buffer.read_to_end(&mut buf)?; @@ -66,13 +70,6 @@ impl MaybeReadableArgs for TestCustomMessage { } } -struct TestCustomMessageHandler {} - -impl CustomOnionMessageHandler for TestCustomMessageHandler { - type CustomMessage = TestCustomMessage; - fn handle_custom_message(&self, _msg: Self::CustomMessage) {} -} - fn create_nodes(num_messengers: u8) -> Vec { let mut nodes = Vec::new(); for i in 0..num_messengers { @@ -253,12 +250,6 @@ fn invalid_custom_message_type() { fn write(&self, _w: &mut W) -> Result<(), io::Error> { unreachable!() } } - impl MaybeReadableArgs for InvalidCustomMessage { - fn read(_buffer: &mut R, _message_type: u64) -> Result, DecodeError> where Self: Sized { - unreachable!() - } - } - let test_msg = OnionMessageContents::Custom(InvalidCustomMessage {}); let err = nodes[0].messenger.send_onion_message(&[], Destination::Node(nodes[1].get_node_pk()), test_msg, None).unwrap_err(); assert_eq!(err, SendError::InvalidMessage); diff --git a/lightning/src/onion_message/messenger.rs b/lightning/src/onion_message/messenger.rs index 70a0842c..a09c942b 100644 --- a/lightning/src/onion_message/messenger.rs +++ b/lightning/src/onion_message/messenger.rs @@ -29,6 +29,7 @@ use crate::util::logger::Logger; use crate::util::ser::Writeable; use core::ops::Deref; +use crate::io; use crate::sync::{Arc, Mutex}; use crate::prelude::*; @@ -47,7 +48,7 @@ use crate::prelude::*; /// # use lightning::ln::peer_handler::IgnoringMessageHandler; /// # use lightning::onion_message::{BlindedRoute, CustomOnionMessageContents, Destination, OnionMessageContents, OnionMessenger}; /// # use lightning::util::logger::{Logger, Record}; -/// # use lightning::util::ser::{MaybeReadableArgs, Writeable, Writer}; +/// # use lightning::util::ser::{Writeable, Writer}; /// # use lightning::io; /// # use std::sync::Arc; /// # struct FakeLogger {}; @@ -81,13 +82,6 @@ use crate::prelude::*; /// your_custom_message_type /// } /// } -/// impl MaybeReadableArgs for YourCustomMessage { -/// fn read(r: &mut R, message_type: u64) -> Result, DecodeError> { -/// # unreachable!() -/// // Read your custom onion message of type `message_type` from `r`, or return `None` -/// // if the message type is unknown -/// } -/// } /// // Send a custom onion message to a node id. /// let intermediate_hops = [hop_node_id1, hop_node_id2]; /// let reply_path = None; @@ -187,6 +181,9 @@ pub trait CustomOnionMessageHandler { type CustomMessage: CustomOnionMessageContents; /// Called with the custom message that was received. fn handle_custom_message(&self, msg: Self::CustomMessage); + /// Read a custom message of type `message_type` from `buffer`, returning `Ok(None)` if the + /// message type is unknown. + fn read_custom_message(&self, message_type: u64, buffer: &mut R) -> Result, msgs::DecodeError>; } impl OnionMessenger @@ -301,7 +298,7 @@ fn outbound_buffer_full(peer_node_id: &PublicKey, buffer: &HashMap OnionMessageHandler for OnionMessenger where K::Target: KeysInterface, L::Target: Logger, - CMH::Target: CustomOnionMessageHandler, + CMH::Target: CustomOnionMessageHandler + Sized, { /// Handle an incoming onion message. Currently, if a message was destined for us we will log, but /// soon we'll delegate the onion message to a handler that can generate invoices or send @@ -330,8 +327,8 @@ impl OnionMessageHandler for Onion } } }; - match onion_utils::decode_next_hop(onion_decode_ss, &msg.onion_routing_packet.hop_data[..], - msg.onion_routing_packet.hmac, control_tlvs_ss) + match onion_utils::decode_next_untagged_hop(onion_decode_ss, &msg.onion_routing_packet.hop_data[..], + msg.onion_routing_packet.hmac, (control_tlvs_ss, &*self.custom_handler)) { Ok((Payload::Receive::<<::Target as CustomOnionMessageHandler>::CustomMessage> { message, control_tlvs: ReceiveControlTlvs::Unblinded(ReceiveTlvs { path_id }), reply_path, diff --git a/lightning/src/onion_message/packet.rs b/lightning/src/onion_message/packet.rs index da8dd561..73f58036 100644 --- a/lightning/src/onion_message/packet.rs +++ b/lightning/src/onion_message/packet.rs @@ -15,8 +15,9 @@ use bitcoin::secp256k1::ecdh::SharedSecret; use crate::ln::msgs::DecodeError; use crate::ln::onion_utils; use super::blinded_route::{BlindedRoute, ForwardTlvs, ReceiveTlvs}; +use super::messenger::CustomOnionMessageHandler; use crate::util::chacha20poly1305rfc::{ChaChaPolyReadAdapter, ChaChaPolyWriteAdapter}; -use crate::util::ser::{BigSize, FixedLengthReader, LengthRead, LengthReadable, LengthReadableArgs, MaybeReadableArgs, Readable, ReadableArgs, Writeable, Writer}; +use crate::util::ser::{BigSize, FixedLengthReader, LengthRead, LengthReadable, LengthReadableArgs, Readable, ReadableArgs, Writeable, Writer}; use core::cmp; use crate::io::{self, Read}; @@ -106,7 +107,7 @@ pub(super) enum Payload { #[derive(Debug)] /// The contents of an onion message. In the context of offers, this would be the invoice, invoice /// request, or invoice error. -pub enum OnionMessageContents where T: CustomOnionMessageContents { +pub enum OnionMessageContents { // Coming soon: // Invoice, // InvoiceRequest, @@ -115,7 +116,7 @@ pub enum OnionMessageContents where T: CustomOnionMessageContents { Custom(T), } -impl OnionMessageContents where T: CustomOnionMessageContents { +impl OnionMessageContents { /// Returns the type that was used to decode the message payload. pub fn tlv_type(&self) -> u64 { match self { @@ -132,9 +133,8 @@ impl Writeable for OnionMessageContents { } } -/// The contents of a custom onion message. Must implement `MaybeReadableArgs` where the `u64` -/// is the custom TLV type attempting to be read, and return `Ok(None)` if the TLV type is unknown. -pub trait CustomOnionMessageContents: Writeable + MaybeReadableArgs { +/// The contents of a custom onion message. +pub trait CustomOnionMessageContents: Writeable { /// Returns the TLV type identifying the message contents. MUST be >= 64. fn tlv_type(&self) -> u64; } @@ -198,8 +198,10 @@ impl Writeable for (Payload, [u8; 32]) { } // Uses the provided secret to simultaneously decode and decrypt the control TLVs and data TLV. -impl ReadableArgs for Payload { - fn read(r: &mut R, encrypted_tlvs_ss: SharedSecret) -> Result { +impl ReadableArgs<(SharedSecret, &H)> for Payload<::CustomMessage> { + fn read(r: &mut R, args: (SharedSecret, &H)) -> Result { + let (encrypted_tlvs_ss, handler) = args; + let v: BigSize = Readable::read(r)?; let mut rd = FixedLengthReader::new(r, v.0); let mut reply_path: Option = None; @@ -216,7 +218,7 @@ impl ReadableArgs for Payload { if message_type.is_some() { return Err(DecodeError::InvalidValue) } message_type = Some(msg_type); - match T::read(msg_reader, msg_type) { + match handler.read_custom_message(msg_type, msg_reader) { Ok(Some(msg)) => { message = Some(msg); Ok(true) diff --git a/lightning/src/routing/gossip.rs b/lightning/src/routing/gossip.rs index 1706e069..14df033b 100644 --- a/lightning/src/routing/gossip.rs +++ b/lightning/src/routing/gossip.rs @@ -750,7 +750,7 @@ impl ChannelInfo { return None; } }; - Some((DirectedChannelInfo::new(self, direction), source)) + direction.map(|dir| (DirectedChannelInfo::new(self, dir), source)) } /// Returns a [`DirectedChannelInfo`] for the channel directed from the given `source` to a @@ -765,7 +765,7 @@ impl ChannelInfo { return None; } }; - Some((DirectedChannelInfo::new(self, direction), target)) + direction.map(|dir| (DirectedChannelInfo::new(self, dir), target)) } /// Returns a [`ChannelUpdateInfo`] based on the direction implied by the channel_flag. @@ -860,29 +860,23 @@ impl Readable for ChannelInfo { #[derive(Clone)] pub struct DirectedChannelInfo<'a> { channel: &'a ChannelInfo, - direction: Option<&'a ChannelUpdateInfo>, + direction: &'a ChannelUpdateInfo, htlc_maximum_msat: u64, effective_capacity: EffectiveCapacity, } impl<'a> DirectedChannelInfo<'a> { #[inline] - fn new(channel: &'a ChannelInfo, direction: Option<&'a ChannelUpdateInfo>) -> Self { - let htlc_maximum_msat = direction.map(|direction| direction.htlc_maximum_msat); + fn new(channel: &'a ChannelInfo, direction: &'a ChannelUpdateInfo) -> Self { + let mut htlc_maximum_msat = direction.htlc_maximum_msat; let capacity_msat = channel.capacity_sats.map(|capacity_sats| capacity_sats * 1000); - let (htlc_maximum_msat, effective_capacity) = match (htlc_maximum_msat, capacity_msat) { - (Some(amount_msat), Some(capacity_msat)) => { - let htlc_maximum_msat = cmp::min(amount_msat, capacity_msat); - (htlc_maximum_msat, EffectiveCapacity::Total { capacity_msat, htlc_maximum_msat: Some(htlc_maximum_msat) }) + let effective_capacity = match capacity_msat { + Some(capacity_msat) => { + htlc_maximum_msat = cmp::min(htlc_maximum_msat, capacity_msat); + EffectiveCapacity::Total { capacity_msat, htlc_maximum_msat: htlc_maximum_msat } }, - (Some(amount_msat), None) => { - (amount_msat, EffectiveCapacity::MaximumHTLC { amount_msat }) - }, - (None, Some(capacity_msat)) => { - (capacity_msat, EffectiveCapacity::Total { capacity_msat, htlc_maximum_msat: None }) - }, - (None, None) => (EffectiveCapacity::Unknown.as_msat(), EffectiveCapacity::Unknown), + None => EffectiveCapacity::MaximumHTLC { amount_msat: htlc_maximum_msat }, }; Self { @@ -891,12 +885,11 @@ impl<'a> DirectedChannelInfo<'a> { } /// Returns information for the channel. + #[inline] pub fn channel(&self) -> &'a ChannelInfo { self.channel } - /// Returns information for the direction. - pub fn direction(&self) -> Option<&'a ChannelUpdateInfo> { self.direction } - /// Returns the maximum HTLC amount allowed over the channel in the direction. + #[inline] pub fn htlc_maximum_msat(&self) -> u64 { self.htlc_maximum_msat } @@ -910,13 +903,9 @@ impl<'a> DirectedChannelInfo<'a> { self.effective_capacity } - /// Returns `Some` if [`ChannelUpdateInfo`] is available in the direction. - pub(super) fn with_update(self) -> Option> { - match self.direction { - Some(_) => Some(DirectedChannelInfoWithUpdate { inner: self }), - None => None, - } - } + /// Returns information for the direction. + #[inline] + pub(super) fn direction(&self) -> &'a ChannelUpdateInfo { self.direction } } impl<'a> fmt::Debug for DirectedChannelInfo<'a> { @@ -927,32 +916,6 @@ impl<'a> fmt::Debug for DirectedChannelInfo<'a> { } } -/// A [`DirectedChannelInfo`] with [`ChannelUpdateInfo`] available in its direction. -#[derive(Clone)] -pub(super) struct DirectedChannelInfoWithUpdate<'a> { - inner: DirectedChannelInfo<'a>, -} - -impl<'a> DirectedChannelInfoWithUpdate<'a> { - /// Returns information for the channel. - #[inline] - pub(super) fn channel(&self) -> &'a ChannelInfo { &self.inner.channel } - - /// Returns information for the direction. - #[inline] - pub(super) fn direction(&self) -> &'a ChannelUpdateInfo { self.inner.direction.unwrap() } - - /// Returns the [`EffectiveCapacity`] of the channel in the direction. - #[inline] - pub(super) fn effective_capacity(&self) -> EffectiveCapacity { self.inner.effective_capacity() } -} - -impl<'a> fmt::Debug for DirectedChannelInfoWithUpdate<'a> { - fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { - self.inner.fmt(f) - } -} - /// The effective capacity of a channel for routing purposes. /// /// While this may be smaller than the actual channel capacity, amounts greater than @@ -976,7 +939,7 @@ pub enum EffectiveCapacity { /// The funding amount denominated in millisatoshi. capacity_msat: u64, /// The maximum HTLC amount denominated in millisatoshi. - htlc_maximum_msat: Option + htlc_maximum_msat: u64 }, /// A capacity sufficient to route any payment, typically used for private channels provided by /// an invoice. diff --git a/lightning/src/routing/router.rs b/lightning/src/routing/router.rs index 0d37744d..cd75654b 100644 --- a/lightning/src/routing/router.rs +++ b/lightning/src/routing/router.rs @@ -17,7 +17,7 @@ use bitcoin::secp256k1::PublicKey; use crate::ln::channelmanager::ChannelDetails; use crate::ln::features::{ChannelFeatures, InvoiceFeatures, NodeFeatures}; use crate::ln::msgs::{DecodeError, ErrorAction, LightningError, MAX_VALUE_MSAT}; -use crate::routing::gossip::{DirectedChannelInfoWithUpdate, EffectiveCapacity, ReadOnlyNetworkGraph, NetworkGraph, NodeId, RoutingFees}; +use crate::routing::gossip::{DirectedChannelInfo, EffectiveCapacity, ReadOnlyNetworkGraph, NetworkGraph, NodeId, RoutingFees}; use crate::routing::scoring::{ChannelUsage, Score}; use crate::util::ser::{Writeable, Readable, Writer}; use crate::util::logger::{Level, Logger}; @@ -421,7 +421,7 @@ enum CandidateRouteHop<'a> { }, /// A hop found in the [`ReadOnlyNetworkGraph`], where the channel capacity may be unknown. PublicHop { - info: DirectedChannelInfoWithUpdate<'a>, + info: DirectedChannelInfo<'a>, short_channel_id: u64, }, /// A hop to the payee found in the payment invoice, though not necessarily a direct channel. @@ -494,10 +494,8 @@ fn max_htlc_from_capacity(capacity: EffectiveCapacity, max_channel_saturation_po EffectiveCapacity::Unknown => EffectiveCapacity::Unknown.as_msat(), EffectiveCapacity::MaximumHTLC { amount_msat } => amount_msat.checked_shr(saturation_shift).unwrap_or(0), - EffectiveCapacity::Total { capacity_msat, htlc_maximum_msat: None } => - capacity_msat.checked_shr(saturation_shift).unwrap_or(0), - EffectiveCapacity::Total { capacity_msat, htlc_maximum_msat: Some(htlc_max) } => - cmp::min(capacity_msat.checked_shr(saturation_shift).unwrap_or(0), htlc_max), + EffectiveCapacity::Total { capacity_msat, htlc_maximum_msat } => + cmp::min(capacity_msat.checked_shr(saturation_shift).unwrap_or(0), htlc_maximum_msat), } } @@ -1276,13 +1274,11 @@ where L::Target: Logger { for chan_id in $node.channels.iter() { let chan = network_channels.get(chan_id).unwrap(); if !chan.features.requires_unknown_bits() { - let (directed_channel, source) = - chan.as_directed_to(&$node_id).expect("inconsistent NetworkGraph"); - if first_hops.is_none() || *source != our_node_id { - if let Some(direction) = directed_channel.direction() { - if direction.enabled { + if let Some((directed_channel, source)) = chan.as_directed_to(&$node_id) { + if first_hops.is_none() || *source != our_node_id { + if directed_channel.direction().enabled { let candidate = CandidateRouteHop::PublicHop { - info: directed_channel.with_update().unwrap(), + info: directed_channel, short_channel_id: *chan_id, }; add_entry!(candidate, *source, $node_id, @@ -1367,8 +1363,7 @@ where L::Target: Logger { let candidate = network_channels .get(&hop.short_channel_id) .and_then(|channel| channel.as_directed_to(&target)) - .and_then(|(channel, _)| channel.with_update()) - .map(|info| CandidateRouteHop::PublicHop { + .map(|(info, _)| CandidateRouteHop::PublicHop { info, short_channel_id: hop.short_channel_id, }) @@ -1816,10 +1811,8 @@ fn add_random_cltv_offset(route: &mut Route, payment_params: &PaymentParameters, random_channel.as_directed_from(&cur_node_id).map(|(dir_info, next_id)| { if !nodes_to_avoid.iter().any(|x| x == next_id) { nodes_to_avoid[random_hop] = *next_id; - dir_info.direction().map(|channel_update_info| { - random_hop_offset = channel_update_info.cltv_expiry_delta.into(); - cur_hop = Some(*next_id); - }); + random_hop_offset = dir_info.direction().cltv_expiry_delta.into(); + cur_hop = Some(*next_id); } }); } @@ -5214,14 +5207,12 @@ mod tests { for channel_id in &cur_node.channels { if let Some(channel_info) = network_channels.get(&channel_id) { if let Some((dir_info, next_id)) = channel_info.as_directed_from(&cur_node_id) { - if let Some(channel_update_info) = dir_info.direction() { - let next_cltv_expiry_delta = channel_update_info.cltv_expiry_delta as u32; - if cur_path_cltv_deltas.iter().sum::() - .saturating_add(next_cltv_expiry_delta) <= observed_cltv_expiry_delta { - let mut new_path_cltv_deltas = cur_path_cltv_deltas.clone(); - new_path_cltv_deltas.push(next_cltv_expiry_delta); - candidates.push_back((*next_id, new_path_cltv_deltas)); - } + let next_cltv_expiry_delta = dir_info.direction().cltv_expiry_delta as u32; + if cur_path_cltv_deltas.iter().sum::() + .saturating_add(next_cltv_expiry_delta) <= observed_cltv_expiry_delta { + let mut new_path_cltv_deltas = cur_path_cltv_deltas.clone(); + new_path_cltv_deltas.push(next_cltv_expiry_delta); + candidates.push_back((*next_id, new_path_cltv_deltas)); } } } @@ -5398,7 +5389,7 @@ mod tests { let usage = ChannelUsage { amount_msat: 0, inflight_htlc_msat: 0, - effective_capacity: EffectiveCapacity::Total { capacity_msat: 1_024_000, htlc_maximum_msat: Some(1_000) }, + effective_capacity: EffectiveCapacity::Total { capacity_msat: 1_024_000, htlc_maximum_msat: 1_000 }, }; scorer.set_manual_penalty(&NodeId::from_pubkey(&nodes[3]), 123); scorer.set_manual_penalty(&NodeId::from_pubkey(&nodes[4]), 456); diff --git a/lightning/src/routing/scoring.rs b/lightning/src/routing/scoring.rs index 1c13771b..5b829f61 100644 --- a/lightning/src/routing/scoring.rs +++ b/lightning/src/routing/scoring.rs @@ -1113,7 +1113,7 @@ impl>, L: Deref, T: Time> Score for Probabilis return base_penalty_msat; } }, - EffectiveCapacity::Total { capacity_msat, htlc_maximum_msat: Some(htlc_maximum_msat) } => { + EffectiveCapacity::Total { capacity_msat, htlc_maximum_msat } => { if htlc_maximum_msat >= capacity_msat/2 { anti_probing_penalty_msat = self.params.anti_probing_penalty_msat; } @@ -1985,7 +1985,7 @@ mod tests { let usage = ChannelUsage { amount_msat: 1_024, inflight_htlc_msat: 0, - effective_capacity: EffectiveCapacity::Total { capacity_msat: 1_024_000, htlc_maximum_msat: Some(1_000) }, + effective_capacity: EffectiveCapacity::Total { capacity_msat: 1_024_000, htlc_maximum_msat: 1_000 }, }; assert_eq!(scorer.channel_penalty_msat(42, &source, &target, usage), 0); let usage = ChannelUsage { amount_msat: 10_240, ..usage }; @@ -1998,7 +1998,7 @@ mod tests { let usage = ChannelUsage { amount_msat: 128, inflight_htlc_msat: 0, - effective_capacity: EffectiveCapacity::Total { capacity_msat: 1_024, htlc_maximum_msat: Some(1_000) }, + effective_capacity: EffectiveCapacity::Total { capacity_msat: 1_024, htlc_maximum_msat: 1_000 }, }; assert_eq!(scorer.channel_penalty_msat(42, &source, &target, usage), 58); let usage = ChannelUsage { amount_msat: 256, ..usage }; @@ -2038,7 +2038,7 @@ mod tests { let usage = ChannelUsage { amount_msat: 39, inflight_htlc_msat: 0, - effective_capacity: EffectiveCapacity::Total { capacity_msat: 100, htlc_maximum_msat: Some(1_000) }, + effective_capacity: EffectiveCapacity::Total { capacity_msat: 100, htlc_maximum_msat: 1_000 }, }; assert_eq!(scorer.channel_penalty_msat(42, &source, &target, usage), 0); let usage = ChannelUsage { amount_msat: 50, ..usage }; @@ -2062,7 +2062,7 @@ mod tests { let usage = ChannelUsage { amount_msat: 500, inflight_htlc_msat: 0, - effective_capacity: EffectiveCapacity::Total { capacity_msat: 1_000, htlc_maximum_msat: Some(1_000) }, + effective_capacity: EffectiveCapacity::Total { capacity_msat: 1_000, htlc_maximum_msat: 1_000 }, }; let failed_path = payment_path_for_amount(500); let successful_path = payment_path_for_amount(200); @@ -2092,7 +2092,7 @@ mod tests { let usage = ChannelUsage { amount_msat: 250, inflight_htlc_msat: 0, - effective_capacity: EffectiveCapacity::Total { capacity_msat: 1_000, htlc_maximum_msat: Some(1_000) }, + effective_capacity: EffectiveCapacity::Total { capacity_msat: 1_000, htlc_maximum_msat: 1_000 }, }; assert_eq!(scorer.channel_penalty_msat(42, &source, &target, usage), 128); let usage = ChannelUsage { amount_msat: 500, ..usage }; @@ -2127,7 +2127,7 @@ mod tests { let usage = ChannelUsage { amount_msat: 250, inflight_htlc_msat: 0, - effective_capacity: EffectiveCapacity::Total { capacity_msat: 1_000, htlc_maximum_msat: Some(1_000) }, + effective_capacity: EffectiveCapacity::Total { capacity_msat: 1_000, htlc_maximum_msat: 1_000 }, }; assert_eq!(scorer.channel_penalty_msat(42, &source, &target, usage), 128); let usage = ChannelUsage { amount_msat: 500, ..usage }; @@ -2161,7 +2161,7 @@ mod tests { let usage = ChannelUsage { amount_msat: 250, inflight_htlc_msat: 0, - effective_capacity: EffectiveCapacity::Total { capacity_msat: 1_000, htlc_maximum_msat: Some(1_000) }, + effective_capacity: EffectiveCapacity::Total { capacity_msat: 1_000, htlc_maximum_msat: 1_000 }, }; let path = payment_path_for_amount(500); @@ -2193,7 +2193,7 @@ mod tests { let usage = ChannelUsage { amount_msat: 0, inflight_htlc_msat: 0, - effective_capacity: EffectiveCapacity::Total { capacity_msat: 1_024, htlc_maximum_msat: Some(1_024) }, + effective_capacity: EffectiveCapacity::Total { capacity_msat: 1_024, htlc_maximum_msat: 1_024 }, }; assert_eq!(scorer.channel_penalty_msat(42, &source, &target, usage), 0); let usage = ChannelUsage { amount_msat: 1_023, ..usage }; @@ -2271,7 +2271,7 @@ mod tests { let usage = ChannelUsage { amount_msat: 256, inflight_htlc_msat: 0, - effective_capacity: EffectiveCapacity::Total { capacity_msat: 1_024, htlc_maximum_msat: Some(1_000) }, + effective_capacity: EffectiveCapacity::Total { capacity_msat: 1_024, htlc_maximum_msat: 1_000 }, }; assert_eq!(scorer.channel_penalty_msat(42, &source, &target, usage), 125); @@ -2302,7 +2302,7 @@ mod tests { let usage = ChannelUsage { amount_msat: 512, inflight_htlc_msat: 0, - effective_capacity: EffectiveCapacity::Total { capacity_msat: 1_024, htlc_maximum_msat: Some(1_000) }, + effective_capacity: EffectiveCapacity::Total { capacity_msat: 1_024, htlc_maximum_msat: 1_000 }, }; assert_eq!(scorer.channel_penalty_msat(42, &source, &target, usage), 300); @@ -2347,7 +2347,7 @@ mod tests { let usage = ChannelUsage { amount_msat: 500, inflight_htlc_msat: 0, - effective_capacity: EffectiveCapacity::Total { capacity_msat: 1_000, htlc_maximum_msat: Some(1_000) }, + effective_capacity: EffectiveCapacity::Total { capacity_msat: 1_000, htlc_maximum_msat: 1_000 }, }; scorer.payment_path_failed(&payment_path_for_amount(500).iter().collect::>(), 42); @@ -2384,7 +2384,7 @@ mod tests { let usage = ChannelUsage { amount_msat: 500, inflight_htlc_msat: 0, - effective_capacity: EffectiveCapacity::Total { capacity_msat: 1_000, htlc_maximum_msat: Some(1_000) }, + effective_capacity: EffectiveCapacity::Total { capacity_msat: 1_000, htlc_maximum_msat: 1_000 }, }; scorer.payment_path_failed(&payment_path_for_amount(500).iter().collect::>(), 42); @@ -2421,47 +2421,47 @@ mod tests { let usage = ChannelUsage { amount_msat: 100_000_000, inflight_htlc_msat: 0, - effective_capacity: EffectiveCapacity::Total { capacity_msat: 950_000_000, htlc_maximum_msat: Some(1_000) }, + effective_capacity: EffectiveCapacity::Total { capacity_msat: 950_000_000, htlc_maximum_msat: 1_000 }, }; assert_eq!(scorer.channel_penalty_msat(42, &source, &target, usage), 4375); let usage = ChannelUsage { - effective_capacity: EffectiveCapacity::Total { capacity_msat: 1_950_000_000, htlc_maximum_msat: Some(1_000) }, ..usage + effective_capacity: EffectiveCapacity::Total { capacity_msat: 1_950_000_000, htlc_maximum_msat: 1_000 }, ..usage }; assert_eq!(scorer.channel_penalty_msat(42, &source, &target, usage), 2739); let usage = ChannelUsage { - effective_capacity: EffectiveCapacity::Total { capacity_msat: 2_950_000_000, htlc_maximum_msat: Some(1_000) }, ..usage + effective_capacity: EffectiveCapacity::Total { capacity_msat: 2_950_000_000, htlc_maximum_msat: 1_000 }, ..usage }; assert_eq!(scorer.channel_penalty_msat(42, &source, &target, usage), 2236); let usage = ChannelUsage { - effective_capacity: EffectiveCapacity::Total { capacity_msat: 3_950_000_000, htlc_maximum_msat: Some(1_000) }, ..usage + effective_capacity: EffectiveCapacity::Total { capacity_msat: 3_950_000_000, htlc_maximum_msat: 1_000 }, ..usage }; assert_eq!(scorer.channel_penalty_msat(42, &source, &target, usage), 1983); let usage = ChannelUsage { - effective_capacity: EffectiveCapacity::Total { capacity_msat: 4_950_000_000, htlc_maximum_msat: Some(1_000) }, ..usage + effective_capacity: EffectiveCapacity::Total { capacity_msat: 4_950_000_000, htlc_maximum_msat: 1_000 }, ..usage }; assert_eq!(scorer.channel_penalty_msat(42, &source, &target, usage), 1637); let usage = ChannelUsage { - effective_capacity: EffectiveCapacity::Total { capacity_msat: 5_950_000_000, htlc_maximum_msat: Some(1_000) }, ..usage + effective_capacity: EffectiveCapacity::Total { capacity_msat: 5_950_000_000, htlc_maximum_msat: 1_000 }, ..usage }; assert_eq!(scorer.channel_penalty_msat(42, &source, &target, usage), 1606); let usage = ChannelUsage { - effective_capacity: EffectiveCapacity::Total { capacity_msat: 6_950_000_000, htlc_maximum_msat: Some(1_000) }, ..usage + effective_capacity: EffectiveCapacity::Total { capacity_msat: 6_950_000_000, htlc_maximum_msat: 1_000 }, ..usage }; assert_eq!(scorer.channel_penalty_msat(42, &source, &target, usage), 1331); let usage = ChannelUsage { - effective_capacity: EffectiveCapacity::Total { capacity_msat: 7_450_000_000, htlc_maximum_msat: Some(1_000) }, ..usage + effective_capacity: EffectiveCapacity::Total { capacity_msat: 7_450_000_000, htlc_maximum_msat: 1_000 }, ..usage }; assert_eq!(scorer.channel_penalty_msat(42, &source, &target, usage), 1387); let usage = ChannelUsage { - effective_capacity: EffectiveCapacity::Total { capacity_msat: 7_950_000_000, htlc_maximum_msat: Some(1_000) }, ..usage + effective_capacity: EffectiveCapacity::Total { capacity_msat: 7_950_000_000, htlc_maximum_msat: 1_000 }, ..usage }; assert_eq!(scorer.channel_penalty_msat(42, &source, &target, usage), 1379); let usage = ChannelUsage { - effective_capacity: EffectiveCapacity::Total { capacity_msat: 8_950_000_000, htlc_maximum_msat: Some(1_000) }, ..usage + effective_capacity: EffectiveCapacity::Total { capacity_msat: 8_950_000_000, htlc_maximum_msat: 1_000 }, ..usage }; assert_eq!(scorer.channel_penalty_msat(42, &source, &target, usage), 1363); let usage = ChannelUsage { - effective_capacity: EffectiveCapacity::Total { capacity_msat: 9_950_000_000, htlc_maximum_msat: Some(1_000) }, ..usage + effective_capacity: EffectiveCapacity::Total { capacity_msat: 9_950_000_000, htlc_maximum_msat: 1_000 }, ..usage }; assert_eq!(scorer.channel_penalty_msat(42, &source, &target, usage), 1355); } @@ -2475,7 +2475,7 @@ mod tests { let usage = ChannelUsage { amount_msat: 128, inflight_htlc_msat: 0, - effective_capacity: EffectiveCapacity::Total { capacity_msat: 1_024, htlc_maximum_msat: Some(1_000) }, + effective_capacity: EffectiveCapacity::Total { capacity_msat: 1_024, htlc_maximum_msat: 1_000 }, }; let params = ProbabilisticScoringParameters { @@ -2511,7 +2511,7 @@ mod tests { let usage = ChannelUsage { amount_msat: 512_000, inflight_htlc_msat: 0, - effective_capacity: EffectiveCapacity::Total { capacity_msat: 1_024_000, htlc_maximum_msat: Some(1_000) }, + effective_capacity: EffectiveCapacity::Total { capacity_msat: 1_024_000, htlc_maximum_msat: 1_000 }, }; let params = ProbabilisticScoringParameters { @@ -2566,7 +2566,7 @@ mod tests { let usage = ChannelUsage { amount_msat: 750, inflight_htlc_msat: 0, - effective_capacity: EffectiveCapacity::Total { capacity_msat: 1_000, htlc_maximum_msat: Some(1_000) }, + effective_capacity: EffectiveCapacity::Total { capacity_msat: 1_000, htlc_maximum_msat: 1_000 }, }; assert_ne!(scorer.channel_penalty_msat(42, &source, &target, usage), u64::max_value()); @@ -2615,7 +2615,7 @@ mod tests { let usage = ChannelUsage { amount_msat: 100, inflight_htlc_msat: 0, - effective_capacity: EffectiveCapacity::Total { capacity_msat: 1_024, htlc_maximum_msat: Some(1_024) }, + effective_capacity: EffectiveCapacity::Total { capacity_msat: 1_024, htlc_maximum_msat: 1_024 }, }; // With no historical data the normal liquidity penalty calculation is used. assert_eq!(scorer.channel_penalty_msat(42, &source, &target, usage), 47); @@ -2650,7 +2650,7 @@ mod tests { let usage = ChannelUsage { amount_msat: 512_000, inflight_htlc_msat: 0, - effective_capacity: EffectiveCapacity::Total { capacity_msat: 1_024_000, htlc_maximum_msat: Some(1_000) }, + effective_capacity: EffectiveCapacity::Total { capacity_msat: 1_024_000, htlc_maximum_msat: 1_000 }, }; assert_eq!(scorer.channel_penalty_msat(42, &source, &target, usage), 0); @@ -2658,7 +2658,7 @@ mod tests { let usage = ChannelUsage { amount_msat: 512_000, inflight_htlc_msat: 0, - effective_capacity: EffectiveCapacity::Total { capacity_msat: 1_024_000, htlc_maximum_msat: Some(1_024_000) }, + effective_capacity: EffectiveCapacity::Total { capacity_msat: 1_024_000, htlc_maximum_msat: 1_024_000 }, }; assert_eq!(scorer.channel_penalty_msat(42, &source, &target, usage), 500); @@ -2666,7 +2666,7 @@ mod tests { let usage = ChannelUsage { amount_msat: 512_000, inflight_htlc_msat: 0, - effective_capacity: EffectiveCapacity::Total { capacity_msat: 1_024_000, htlc_maximum_msat: Some(512_000) }, + effective_capacity: EffectiveCapacity::Total { capacity_msat: 1_024_000, htlc_maximum_msat: 512_000 }, }; assert_eq!(scorer.channel_penalty_msat(42, &source, &target, usage), 500); @@ -2674,7 +2674,7 @@ mod tests { let usage = ChannelUsage { amount_msat: 512_000, inflight_htlc_msat: 0, - effective_capacity: EffectiveCapacity::Total { capacity_msat: 1_024_000, htlc_maximum_msat: Some(511_999) }, + effective_capacity: EffectiveCapacity::Total { capacity_msat: 1_024_000, htlc_maximum_msat: 511_999 }, }; assert_eq!(scorer.channel_penalty_msat(42, &source, &target, usage), 0); } diff --git a/lightning/src/util/enforcing_trait_impls.rs b/lightning/src/util/enforcing_trait_impls.rs index 8344f9f3..6317b43d 100644 --- a/lightning/src/util/enforcing_trait_impls.rs +++ b/lightning/src/util/enforcing_trait_impls.rs @@ -201,7 +201,7 @@ impl BaseSign for EnforcingSigner { } fn sign_holder_anchor_input( - &self, anchor_tx: &mut Transaction, input: usize, secp_ctx: &Secp256k1, + &self, anchor_tx: &Transaction, input: usize, secp_ctx: &Secp256k1, ) -> Result { debug_assert!(MIN_CHAN_DUST_LIMIT_SATOSHIS > ANCHOR_OUTPUT_VALUE_SATOSHI); // As long as our minimum dust limit is enforced and is greater than our anchor output diff --git a/lightning/src/util/events.rs b/lightning/src/util/events.rs index f4490d68..37a146c3 100644 --- a/lightning/src/util/events.rs +++ b/lightning/src/util/events.rs @@ -205,6 +205,7 @@ impl_writeable_tlv_based_enum_upgradable!(HTLCDestination, } ); +#[cfg(anchors)] /// A descriptor used to sign for a commitment transaction's anchor output. #[derive(Clone, Debug)] pub struct AnchorDescriptor { @@ -224,6 +225,7 @@ pub struct AnchorDescriptor { pub outpoint: OutPoint, } +#[cfg(anchors)] /// Represents the different types of transactions, originating from LDK, to be bumped. #[derive(Clone, Debug)] pub enum BumpTransactionEvent { diff --git a/lightning/src/util/persist.rs b/lightning/src/util/persist.rs index 9e81a340..bccdb629 100644 --- a/lightning/src/util/persist.rs +++ b/lightning/src/util/persist.rs @@ -34,7 +34,7 @@ pub trait Persister<'a, Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: L::Target: 'static + Logger, { /// Persist the given ['ChannelManager'] to disk, returning an error if persistence failed. - fn persist_manager(&self, channel_manager: &ChannelManager) -> Result<(), io::Error>; + fn persist_manager(&self, channel_manager: &ChannelManager) -> Result<(), io::Error>; /// Persist the given [`NetworkGraph`] to disk, returning an error if persistence failed. fn persist_graph(&self, network_graph: &NetworkGraph) -> Result<(), io::Error>; @@ -51,7 +51,7 @@ impl<'a, A: KVStorePersister, Signer: Sign, M: Deref, T: Deref, K: Deref, F: Der L::Target: 'static + Logger, { /// Persist the given ['ChannelManager'] to disk with the name "manager", returning an error if persistence failed. - fn persist_manager(&self, channel_manager: &ChannelManager) -> Result<(), io::Error> { + fn persist_manager(&self, channel_manager: &ChannelManager) -> Result<(), io::Error> { self.persist("manager", channel_manager) } diff --git a/lightning/src/util/ser.rs b/lightning/src/util/ser.rs index 1bf30fa9..5ff6dc86 100644 --- a/lightning/src/util/ser.rs +++ b/lightning/src/util/ser.rs @@ -269,15 +269,6 @@ impl MaybeReadable for T { } } -/// A trait that various rust-lightning types implement allowing them to (maybe) be read in from a -/// Read, given some additional set of arguments which is required to deserialize. -/// -/// (C-not exported) as we only export serialization to/from byte arrays instead -pub trait MaybeReadableArgs

{ - /// Reads a Self in from the given Read - fn read(reader: &mut R, params: P) -> Result, DecodeError> where Self: Sized; -} - pub(crate) struct OptionDeserWrapper(pub Option); impl Readable for OptionDeserWrapper { #[inline]