diff --git a/.github/workflows/audit.yml b/.github/workflows/audit.yml index 790fd0f26e9..7ef278a94d9 100644 --- a/.github/workflows/audit.yml +++ b/.github/workflows/audit.yml @@ -15,9 +15,3 @@ jobs: - uses: rustsec/audit-check@v1.4.1 with: token: ${{ secrets.GITHUB_TOKEN }} - ignore: "RUSTSEC-2021-0145" - # RUSTSEC-2021-0145 pertains `atty`, which is a depencency of - # `criterion`. While the latter removed the depencency in its - # newest version, it would also require a higher `rustc`. We - # therefore avoid bumping it to allow benchmarking with our - # `rustc` 1.63 MSRV. diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 5862302bd00..56b248791da 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -215,7 +215,7 @@ jobs: fuzz_sanity: runs-on: self-hosted env: - TOOLCHAIN: 1.75 + TOOLCHAIN: 1.85.0 steps: - name: Checkout source code uses: actions/checkout@v4 @@ -232,7 +232,7 @@ jobs: fuzz: runs-on: self-hosted env: - TOOLCHAIN: 1.75 + TOOLCHAIN: 1.85.0 steps: - name: Checkout source code uses: actions/checkout@v4 @@ -317,7 +317,7 @@ jobs: rustfmt: runs-on: ubuntu-latest env: - TOOLCHAIN: 1.75.0 + TOOLCHAIN: 1.85.0 steps: - name: Checkout source code uses: actions/checkout@v4 @@ -336,7 +336,7 @@ jobs: tor-connect: runs-on: ubuntu-latest env: - TOOLCHAIN: 1.75.0 + TOOLCHAIN: 1.85.0 steps: - name: Checkout source code uses: actions/checkout@v4 diff --git a/.github/workflows/ci-build.yml b/.github/workflows/ci-build.yml index 4c56619d3ad..df5abc5f132 100644 --- a/.github/workflows/ci-build.yml +++ b/.github/workflows/ci-build.yml @@ -19,11 +19,11 @@ jobs: || fromJSON('["self-hosted"]') }} toolchain: >- ${{ github.event_name == 'push' && github.ref == 'refs/heads/main' - && fromJSON('["stable","beta","1.75.0"]') - || fromJSON('["1.75.0"]') }} + && fromJSON('["stable","beta","1.85.0"]') + || fromJSON('["1.85.0"]') }} exclude: - platform: windows-latest - toolchain: 1.75.0 + toolchain: 1.85.0 - platform: windows-latest toolchain: beta - platform: macos-latest @@ -40,7 +40,7 @@ jobs: shell: bash run: echo "RUSTFLAGS=-C linker=rust-lld" >> "$GITHUB_ENV" - name: Set RUSTFLAGS to deny warnings - if: "matrix.toolchain == '1.75.0'" + if: "matrix.toolchain == '1.85.0'" run: echo "RUSTFLAGS=-D warnings" >> "$GITHUB_ENV" - name: Install no-std-check dependencies for ARM Embedded if: matrix.platform == 'self-hosted' diff --git a/CLAUDE.md b/CLAUDE.md index cecd79c4981..e1c414cbf6e 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -11,11 +11,11 @@ See [README.md](README.md) for the workspace layout and [ARCH.md](ARCH.md) for s ## Development Rules - Always ensure tests pass before committing. To this end, you should run - `cargo +1.75.0 test` for all affected crates and/or features. Upon completion + `cargo +1.85.0 test` for all affected crates and/or features. Upon completion of the full task you might prompt the user whether they want you to run the full CI tests via `./ci/ci-tests.sh`. Note however that this script will run for a very long time, so please don't timeout when you do. -- Run `cargo +1.75.0 fmt --all` before committing code changes. If rust 1.75.0 is +- Run `cargo +1.85.0 fmt --all` before committing code changes. If rust 1.85.0 is not installed, skip this step. - Never add new dependencies unless explicitly requested - Please always disclose the use of any AI tools in commit messages and PR descriptions using a `Co-Authored-By:` line. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index ad25fb10558..321e052fd97 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -88,7 +88,7 @@ be covered by functional tests. When refactoring, structure your PR to make it easy to review and don't hesitate to split it into multiple small, focused PRs. -The Minimum Supported Rust Version (MSRV) currently is 1.75.0 (enforced by +The Minimum Supported Rust Version (MSRV) currently is 1.85.0 (enforced by our GitHub Actions). We support reading serialized LDK objects written by any version of LDK 0.0.99 and above. We support LDK versions 0.0.113 and above reading serialized LDK objects written by modern LDK. Any expected issues with @@ -124,7 +124,7 @@ display fine at any tab-length display setting. We use `rustfmt` to establish uniform coding standards throughout the codebase. Please run ```bash -cargo +1.75.0 fmt +cargo +1.85.0 fmt ``` before committing and pushing any changes, as compliance will also be checked diff --git a/bench/Cargo.toml b/bench/Cargo.toml index 5bf14377917..f58f0eaa57b 100644 --- a/bench/Cargo.toml +++ b/bench/Cargo.toml @@ -2,7 +2,7 @@ name = "lightning-bench" version = "0.0.1" authors = ["Matt Corallo"] -edition = "2021" +edition = "2024" [[bench]] name = "bench" @@ -12,7 +12,7 @@ harness = false lightning = { path = "../lightning", features = ["_test_utils", "criterion"] } lightning-persister = { path = "../lightning-persister", features = ["criterion"] } lightning-rapid-gossip-sync = { path = "../lightning-rapid-gossip-sync", features = ["criterion"] } -criterion = { version = "0.4", default-features = false } +criterion = { version = "0.5", default-features = false } [profile.release] opt-level = 3 diff --git a/ci/ci-tests-common.sh b/ci/ci-tests-common.sh index 9631689fcdd..565b176e9cb 100755 --- a/ci/ci-tests-common.sh +++ b/ci/ci-tests-common.sh @@ -3,8 +3,6 @@ # Source this file; do not execute it directly. # shellcheck disable=SC2002,SC2207 -RUSTC_MINOR_VERSION=$(rustc --version | awk '{ split($2,a,"."); print a[2] }') - # Some crates require pinning to meet our MSRV even for our downstream users, # which we do here. # Further crates which appear only as dev-dependencies are pinned further down. @@ -14,13 +12,4 @@ function PIN_RELEASE_DEPS { PIN_RELEASE_DEPS # pin the release dependencies in our main workspace -# The backtrace v0.3.75 crate relies on rustc 1.82 -[ "$RUSTC_MINOR_VERSION" -lt 82 ] && cargo update -p backtrace --precise "0.3.74" --quiet - -# Starting with version 1.2.0, the `idna_adapter` crate has an MSRV of rustc 1.81.0. -[ "$RUSTC_MINOR_VERSION" -lt 81 ] && cargo update -p idna_adapter --precise "1.1.0" --quiet - -# Starting with version 0.27.8, the `hyper-rustls` crate has an MSRV of rustc 1.85.0. -[ "$RUSTC_MINOR_VERSION" -lt 85 ] && cargo update -p hyper-rustls --precise "0.27.7" --quiet - export RUST_BACKTRACE=1 diff --git a/ext-functional-test-demo/Cargo.toml b/ext-functional-test-demo/Cargo.toml index 85bd5a658cc..9230d738eb3 100644 --- a/ext-functional-test-demo/Cargo.toml +++ b/ext-functional-test-demo/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "ext-functional-tester" version = "0.1.0" -edition = "2021" +edition = "2024" [features] test-broken = [] diff --git a/fuzz/Cargo.toml b/fuzz/Cargo.toml index 274b19d8ee4..7d6744acba7 100644 --- a/fuzz/Cargo.toml +++ b/fuzz/Cargo.toml @@ -3,7 +3,7 @@ name = "lightning-fuzz" version = "0.0.1" authors = ["Automatically generated"] publish = false -edition = "2021" +edition = "2024" [dependencies] lightning = { path = "../lightning", features = ["regex", "_test_utils"] } diff --git a/fuzz/fuzz-fake-hashes/Cargo.toml b/fuzz/fuzz-fake-hashes/Cargo.toml index d027540a056..ca331d74540 100644 --- a/fuzz/fuzz-fake-hashes/Cargo.toml +++ b/fuzz/fuzz-fake-hashes/Cargo.toml @@ -3,7 +3,7 @@ name = "lightning-fuzz-fake-hashes" version = "0.0.1" authors = ["Automatically generated"] publish = false -edition = "2021" +edition = "2024" [package.metadata] cargo-fuzz = true diff --git a/fuzz/fuzz-real-hashes/Cargo.toml b/fuzz/fuzz-real-hashes/Cargo.toml index a6d77d28137..8b8d7361dae 100644 --- a/fuzz/fuzz-real-hashes/Cargo.toml +++ b/fuzz/fuzz-real-hashes/Cargo.toml @@ -3,7 +3,7 @@ name = "lightning-fuzz-real-hashes" version = "0.0.1" authors = ["Automatically generated"] publish = false -edition = "2021" +edition = "2024" [package.metadata] cargo-fuzz = true diff --git a/fuzz/src/base32.rs b/fuzz/src/base32.rs index c0d71dd7b33..7d8e870407e 100644 --- a/fuzz/src/base32.rs +++ b/fuzz/src/base32.rs @@ -52,7 +52,7 @@ pub fn base32_test(data: &[u8], _out: Out) { do_test(data); } -#[no_mangle] +#[unsafe(no_mangle)] pub extern "C" fn base32_run(data: *const u8, datalen: usize) { do_test(unsafe { std::slice::from_raw_parts(data, datalen) }); } diff --git a/fuzz/src/bech32_parse.rs b/fuzz/src/bech32_parse.rs index ff465ceea39..a53342d2c33 100644 --- a/fuzz/src/bech32_parse.rs +++ b/fuzz/src/bech32_parse.rs @@ -51,7 +51,7 @@ pub fn bech32_parse_test(data: &[u8], out: Out) { do_test(data, out); } -#[no_mangle] +#[unsafe(no_mangle)] pub extern "C" fn bech32_parse_run(data: *const u8, datalen: usize) { do_test(unsafe { std::slice::from_raw_parts(data, datalen) }, test_logger::DevNull {}); } diff --git a/fuzz/src/bolt11_deser.rs b/fuzz/src/bolt11_deser.rs index 92dde80aa66..3cfc89ab6e6 100644 --- a/fuzz/src/bolt11_deser.rs +++ b/fuzz/src/bolt11_deser.rs @@ -70,7 +70,7 @@ pub fn bolt11_deser_test(data: &[u8], out: Out) { do_test(data, out); } -#[no_mangle] +#[unsafe(no_mangle)] pub extern "C" fn bolt11_deser_run(data: *const u8, datalen: usize) { do_test(unsafe { std::slice::from_raw_parts(data, datalen) }, test_logger::DevNull {}); } diff --git a/fuzz/src/chanmon_consistency.rs b/fuzz/src/chanmon_consistency.rs index d678d97918f..1664f89b8e9 100644 --- a/fuzz/src/chanmon_consistency.rs +++ b/fuzz/src/chanmon_consistency.rs @@ -18,6 +18,7 @@ //! send-side handling is correct, other peers. We consider it a failure if any action results in a //! channel being force-closed. +use bitcoin::FeeRate; use bitcoin::amount::Amount; use bitcoin::constants::genesis_block; use bitcoin::locktime::absolute::LockTime; @@ -26,14 +27,13 @@ use bitcoin::opcodes; use bitcoin::script::{Builder, ScriptBuf}; use bitcoin::transaction::Version; use bitcoin::transaction::{Transaction, TxOut}; -use bitcoin::FeeRate; +use bitcoin::WPubkeyHash; use bitcoin::block::Header; use bitcoin::hash_types::Txid; +use bitcoin::hashes::Hash as TraitImport; use bitcoin::hashes::sha256::Hash as Sha256; use bitcoin::hashes::sha256d::Hash as Sha256dHash; -use bitcoin::hashes::Hash as TraitImport; -use bitcoin::WPubkeyHash; use lightning::blinded_path::message::{BlindedMessagePath, MessageContext, MessageForwardNode}; use lightning::blinded_path::payment::{BlindedPaymentPath, ReceiveTlvs}; @@ -44,7 +44,7 @@ use lightning::chain::chaininterface::{ use lightning::chain::channelmonitor::{ChannelMonitor, MonitorEvent}; use lightning::chain::transaction::OutPoint; use lightning::chain::{ - chainmonitor, channelmonitor, BlockLocator, ChannelMonitorUpdateStatus, Confirm, Watch, + BlockLocator, ChannelMonitorUpdateStatus, Confirm, Watch, chainmonitor, channelmonitor, }; use lightning::events; use lightning::ln::channel::{ @@ -1348,7 +1348,7 @@ pub fn do_test(data: &[u8], out: Out) { } for (idx, node_event) in node_events.iter().enumerate() { for event in node_event { - if let MessageSendEvent::SendChannelReady { ref node_id, ref msg } = event { + if let MessageSendEvent::SendChannelReady { node_id, msg } = event { for node in $nodes.iter() { if node.get_our_node_id() == *node_id { node.handle_channel_ready($nodes[idx].get_our_node_id(), msg); @@ -1606,93 +1606,173 @@ pub fn do_test(data: &[u8], out: Out) { loop { // Push any events from Node B onto ba_events and bc_events macro_rules! push_excess_b_events { - ($excess_events: expr, $expect_drop_node: expr) => { { + ($excess_events: expr, $expect_drop_node: expr) => {{ let a_id = nodes[0].get_our_node_id(); let expect_drop_node: Option = $expect_drop_node; - let expect_drop_id = if let Some(id) = expect_drop_node { Some(nodes[id].get_our_node_id()) } else { None }; + let expect_drop_id = if let Some(id) = expect_drop_node { + Some(nodes[id].get_our_node_id()) + } else { + None + }; for event in $excess_events { let push_a = match event { MessageSendEvent::UpdateHTLCs { ref node_id, .. } => { - if Some(*node_id) == expect_drop_id { panic!("peer_disconnected should drop msgs bound for the disconnected peer"); } + if Some(*node_id) == expect_drop_id { + panic!( + "peer_disconnected should drop msgs bound for the disconnected peer" + ); + } *node_id == a_id }, MessageSendEvent::SendRevokeAndACK { ref node_id, .. } => { - if Some(*node_id) == expect_drop_id { panic!("peer_disconnected should drop msgs bound for the disconnected peer"); } + if Some(*node_id) == expect_drop_id { + panic!( + "peer_disconnected should drop msgs bound for the disconnected peer" + ); + } *node_id == a_id }, MessageSendEvent::SendChannelReestablish { ref node_id, .. } => { - if Some(*node_id) == expect_drop_id { panic!("peer_disconnected should drop msgs bound for the disconnected peer"); } + if Some(*node_id) == expect_drop_id { + panic!( + "peer_disconnected should drop msgs bound for the disconnected peer" + ); + } *node_id == a_id }, MessageSendEvent::SendStfu { ref node_id, .. } => { - if Some(*node_id) == expect_drop_id { panic!("peer_disconnected should drop msgs bound for the disconnected peer"); } + if Some(*node_id) == expect_drop_id { + panic!( + "peer_disconnected should drop msgs bound for the disconnected peer" + ); + } *node_id == a_id }, MessageSendEvent::SendSpliceInit { ref node_id, .. } => { - if Some(*node_id) == expect_drop_id { panic!("peer_disconnected should drop msgs bound for the disconnected peer"); } + if Some(*node_id) == expect_drop_id { + panic!( + "peer_disconnected should drop msgs bound for the disconnected peer" + ); + } *node_id == a_id }, MessageSendEvent::SendSpliceAck { ref node_id, .. } => { - if Some(*node_id) == expect_drop_id { panic!("peer_disconnected should drop msgs bound for the disconnected peer"); } + if Some(*node_id) == expect_drop_id { + panic!( + "peer_disconnected should drop msgs bound for the disconnected peer" + ); + } *node_id == a_id }, MessageSendEvent::SendSpliceLocked { ref node_id, .. } => { - if Some(*node_id) == expect_drop_id { panic!("peer_disconnected should drop msgs bound for the disconnected peer"); } + if Some(*node_id) == expect_drop_id { + panic!( + "peer_disconnected should drop msgs bound for the disconnected peer" + ); + } *node_id == a_id }, MessageSendEvent::SendTxAddInput { ref node_id, .. } => { - if Some(*node_id) == expect_drop_id { panic!("peer_disconnected should drop msgs bound for the disconnected peer"); } + if Some(*node_id) == expect_drop_id { + panic!( + "peer_disconnected should drop msgs bound for the disconnected peer" + ); + } *node_id == a_id }, MessageSendEvent::SendTxAddOutput { ref node_id, .. } => { - if Some(*node_id) == expect_drop_id { panic!("peer_disconnected should drop msgs bound for the disconnected peer"); } + if Some(*node_id) == expect_drop_id { + panic!( + "peer_disconnected should drop msgs bound for the disconnected peer" + ); + } *node_id == a_id }, MessageSendEvent::SendTxRemoveInput { ref node_id, .. } => { - if Some(*node_id) == expect_drop_id { panic!("peer_disconnected should drop msgs bound for the disconnected peer"); } + if Some(*node_id) == expect_drop_id { + panic!( + "peer_disconnected should drop msgs bound for the disconnected peer" + ); + } *node_id == a_id }, MessageSendEvent::SendTxRemoveOutput { ref node_id, .. } => { - if Some(*node_id) == expect_drop_id { panic!("peer_disconnected should drop msgs bound for the disconnected peer"); } + if Some(*node_id) == expect_drop_id { + panic!( + "peer_disconnected should drop msgs bound for the disconnected peer" + ); + } *node_id == a_id }, MessageSendEvent::SendTxComplete { ref node_id, .. } => { - if Some(*node_id) == expect_drop_id { panic!("peer_disconnected should drop msgs bound for the disconnected peer"); } + if Some(*node_id) == expect_drop_id { + panic!( + "peer_disconnected should drop msgs bound for the disconnected peer" + ); + } *node_id == a_id }, MessageSendEvent::SendTxAbort { ref node_id, .. } => { - if Some(*node_id) == expect_drop_id { panic!("peer_disconnected should drop msgs bound for the disconnected peer"); } + if Some(*node_id) == expect_drop_id { + panic!( + "peer_disconnected should drop msgs bound for the disconnected peer" + ); + } *node_id == a_id }, MessageSendEvent::SendTxInitRbf { ref node_id, .. } => { - if Some(*node_id) == expect_drop_id { panic!("peer_disconnected should drop msgs bound for the disconnected peer"); } + if Some(*node_id) == expect_drop_id { + panic!( + "peer_disconnected should drop msgs bound for the disconnected peer" + ); + } *node_id == a_id }, MessageSendEvent::SendTxAckRbf { ref node_id, .. } => { - if Some(*node_id) == expect_drop_id { panic!("peer_disconnected should drop msgs bound for the disconnected peer"); } + if Some(*node_id) == expect_drop_id { + panic!( + "peer_disconnected should drop msgs bound for the disconnected peer" + ); + } *node_id == a_id }, MessageSendEvent::SendTxSignatures { ref node_id, .. } => { - if Some(*node_id) == expect_drop_id { panic!("peer_disconnected should drop msgs bound for the disconnected peer"); } + if Some(*node_id) == expect_drop_id { + panic!( + "peer_disconnected should drop msgs bound for the disconnected peer" + ); + } *node_id == a_id }, MessageSendEvent::SendChannelReady { .. } => continue, MessageSendEvent::SendAnnouncementSignatures { .. } => continue, MessageSendEvent::BroadcastChannelUpdate { .. } => continue, MessageSendEvent::SendChannelUpdate { ref node_id, .. } => { - if Some(*node_id) == expect_drop_id { panic!("peer_disconnected should drop msgs bound for the disconnected peer"); } + if Some(*node_id) == expect_drop_id { + panic!( + "peer_disconnected should drop msgs bound for the disconnected peer" + ); + } *node_id == a_id }, MessageSendEvent::HandleError { ref action, ref node_id } => { assert_action_timeout_awaiting_response(action); - if Some(*node_id) == expect_drop_id { panic!("peer_disconnected should drop msgs bound for the disconnected peer"); } + if Some(*node_id) == expect_drop_id { + panic!( + "peer_disconnected should drop msgs bound for the disconnected peer" + ); + } *node_id == a_id }, _ => panic!("Unhandled message event {:?}", event), }; - if push_a { ba_events.push(event); } else { bc_events.push(event); } + if push_a { + ba_events.push(event); + } else { + bc_events.push(event); + } } - } } + }}; } // While delivering messages, we select across three possible message selection processes @@ -1713,7 +1793,7 @@ pub fn do_test(data: &[u8], out: Out) { } macro_rules! process_msg_events { - ($node: expr, $corrupt_forward: expr, $limit_events: expr) => { { + ($node: expr, $corrupt_forward: expr, $limit_events: expr) => {{ let mut events = if $node == 1 { let mut new_events = Vec::new(); mem::swap(&mut new_events, &mut ba_events); @@ -1739,13 +1819,34 @@ pub fn do_test(data: &[u8], out: Out) { for event in &mut events_iter { had_events = true; match event { - MessageSendEvent::UpdateHTLCs { node_id, channel_id, updates: CommitmentUpdate { update_add_htlcs, update_fail_htlcs, update_fulfill_htlcs, update_fail_malformed_htlcs, update_fee, commitment_signed } } => { + MessageSendEvent::UpdateHTLCs { + node_id, + channel_id, + updates: + CommitmentUpdate { + update_add_htlcs, + update_fail_htlcs, + update_fulfill_htlcs, + update_fail_malformed_htlcs, + update_fee, + commitment_signed, + }, + } => { for (idx, dest) in nodes.iter().enumerate() { if dest.get_our_node_id() == node_id { for update_add in update_add_htlcs.iter() { - out.locked_write(format!("Delivering update_add_htlc from node {} to node {}.\n", $node, idx).as_bytes()); + out.locked_write( + format!( + "Delivering update_add_htlc from node {} to node {}.\n", + $node, idx + ) + .as_bytes(), + ); if !$corrupt_forward { - dest.handle_update_add_htlc(nodes[$node].get_our_node_id(), update_add); + dest.handle_update_add_htlc( + nodes[$node].get_our_node_id(), + update_add, + ); } else { // Corrupt the update_add_htlc message so that its HMAC // check will fail and we generate a @@ -1753,42 +1854,103 @@ pub fn do_test(data: &[u8], out: Out) { // update_fail_htlc as we do when we reject a payment. let mut msg_ser = update_add.encode(); msg_ser[1000] ^= 0xff; - let new_msg = UpdateAddHTLC::read_from_fixed_length_buffer(&mut &msg_ser[..]).unwrap(); - dest.handle_update_add_htlc(nodes[$node].get_our_node_id(), &new_msg); + let new_msg = + UpdateAddHTLC::read_from_fixed_length_buffer( + &mut &msg_ser[..], + ) + .unwrap(); + dest.handle_update_add_htlc( + nodes[$node].get_our_node_id(), + &new_msg, + ); } } - let processed_change = !update_add_htlcs.is_empty() || !update_fulfill_htlcs.is_empty() || - !update_fail_htlcs.is_empty() || !update_fail_malformed_htlcs.is_empty(); + let processed_change = !update_add_htlcs.is_empty() + || !update_fulfill_htlcs.is_empty() + || !update_fail_htlcs.is_empty() + || !update_fail_malformed_htlcs.is_empty(); for update_fulfill in update_fulfill_htlcs { - out.locked_write(format!("Delivering update_fulfill_htlc from node {} to node {}.\n", $node, idx).as_bytes()); - dest.handle_update_fulfill_htlc(nodes[$node].get_our_node_id(), update_fulfill); + out.locked_write( + format!( + "Delivering update_fulfill_htlc from node {} to node {}.\n", + $node, idx + ) + .as_bytes(), + ); + dest.handle_update_fulfill_htlc( + nodes[$node].get_our_node_id(), + update_fulfill, + ); } for update_fail in update_fail_htlcs.iter() { - out.locked_write(format!("Delivering update_fail_htlc from node {} to node {}.\n", $node, idx).as_bytes()); - dest.handle_update_fail_htlc(nodes[$node].get_our_node_id(), update_fail); + out.locked_write( + format!( + "Delivering update_fail_htlc from node {} to node {}.\n", + $node, idx + ) + .as_bytes(), + ); + dest.handle_update_fail_htlc( + nodes[$node].get_our_node_id(), + update_fail, + ); } - for update_fail_malformed in update_fail_malformed_htlcs.iter() { - out.locked_write(format!("Delivering update_fail_malformed_htlc from node {} to node {}.\n", $node, idx).as_bytes()); - dest.handle_update_fail_malformed_htlc(nodes[$node].get_our_node_id(), update_fail_malformed); + for update_fail_malformed in update_fail_malformed_htlcs.iter() + { + out.locked_write( + format!( + "Delivering update_fail_malformed_htlc from node {} to node {}.\n", + $node, idx + ) + .as_bytes(), + ); + dest.handle_update_fail_malformed_htlc( + nodes[$node].get_our_node_id(), + update_fail_malformed, + ); } if let Some(msg) = update_fee { - out.locked_write(format!("Delivering update_fee from node {} to node {}.\n", $node, idx).as_bytes()); - dest.handle_update_fee(nodes[$node].get_our_node_id(), &msg); + out.locked_write( + format!( + "Delivering update_fee from node {} to node {}.\n", + $node, idx + ) + .as_bytes(), + ); + dest.handle_update_fee( + nodes[$node].get_our_node_id(), + &msg, + ); } - if $limit_events != ProcessMessages::AllMessages && processed_change { + if $limit_events != ProcessMessages::AllMessages + && processed_change + { // If we only want to process some messages, don't deliver the CS until later. - extra_ev = Some(MessageSendEvent::UpdateHTLCs { node_id, channel_id, updates: CommitmentUpdate { - update_add_htlcs: Vec::new(), - update_fail_htlcs: Vec::new(), - update_fulfill_htlcs: Vec::new(), - update_fail_malformed_htlcs: Vec::new(), - update_fee: None, - commitment_signed - } }); + extra_ev = Some(MessageSendEvent::UpdateHTLCs { + node_id, + channel_id, + updates: CommitmentUpdate { + update_add_htlcs: Vec::new(), + update_fail_htlcs: Vec::new(), + update_fulfill_htlcs: Vec::new(), + update_fail_malformed_htlcs: Vec::new(), + update_fee: None, + commitment_signed, + }, + }); break; } - out.locked_write(format!("Delivering commitment_signed from node {} to node {}.\n", $node, idx).as_bytes()); - dest.handle_commitment_signed_batch_test(nodes[$node].get_our_node_id(), &commitment_signed); + out.locked_write( + format!( + "Delivering commitment_signed from node {} to node {}.\n", + $node, idx + ) + .as_bytes(), + ); + dest.handle_commitment_signed_batch_test( + nodes[$node].get_our_node_id(), + &commitment_signed, + ); break; } } @@ -1796,7 +1958,13 @@ pub fn do_test(data: &[u8], out: Out) { MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => { for (idx, dest) in nodes.iter().enumerate() { if dest.get_our_node_id() == *node_id { - out.locked_write(format!("Delivering revoke_and_ack from node {} to node {}.\n", $node, idx).as_bytes()); + out.locked_write( + format!( + "Delivering revoke_and_ack from node {} to node {}.\n", + $node, idx + ) + .as_bytes(), + ); dest.handle_revoke_and_ack(nodes[$node].get_our_node_id(), msg); } } @@ -1804,15 +1972,30 @@ pub fn do_test(data: &[u8], out: Out) { MessageSendEvent::SendChannelReestablish { ref node_id, ref msg } => { for (idx, dest) in nodes.iter().enumerate() { if dest.get_our_node_id() == *node_id { - out.locked_write(format!("Delivering channel_reestablish from node {} to node {}.\n", $node, idx).as_bytes()); - dest.handle_channel_reestablish(nodes[$node].get_our_node_id(), msg); + out.locked_write( + format!( + "Delivering channel_reestablish from node {} to node {}.\n", + $node, idx + ) + .as_bytes(), + ); + dest.handle_channel_reestablish( + nodes[$node].get_our_node_id(), + msg, + ); } } }, MessageSendEvent::SendStfu { ref node_id, ref msg } => { for (idx, dest) in nodes.iter().enumerate() { if dest.get_our_node_id() == *node_id { - out.locked_write(format!("Delivering stfu from node {} to node {}.\n", $node, idx).as_bytes()); + out.locked_write( + format!( + "Delivering stfu from node {} to node {}.\n", + $node, idx + ) + .as_bytes(), + ); dest.handle_stfu(nodes[$node].get_our_node_id(), msg); } } @@ -1820,7 +2003,13 @@ pub fn do_test(data: &[u8], out: Out) { MessageSendEvent::SendTxAddInput { ref node_id, ref msg } => { for (idx, dest) in nodes.iter().enumerate() { if dest.get_our_node_id() == *node_id { - out.locked_write(format!("Delivering tx_add_input from node {} to node {}.\n", $node, idx).as_bytes()); + out.locked_write( + format!( + "Delivering tx_add_input from node {} to node {}.\n", + $node, idx + ) + .as_bytes(), + ); dest.handle_tx_add_input(nodes[$node].get_our_node_id(), msg); } } @@ -1828,7 +2017,13 @@ pub fn do_test(data: &[u8], out: Out) { MessageSendEvent::SendTxAddOutput { ref node_id, ref msg } => { for (idx, dest) in nodes.iter().enumerate() { if dest.get_our_node_id() == *node_id { - out.locked_write(format!("Delivering tx_add_output from node {} to node {}.\n", $node, idx).as_bytes()); + out.locked_write( + format!( + "Delivering tx_add_output from node {} to node {}.\n", + $node, idx + ) + .as_bytes(), + ); dest.handle_tx_add_output(nodes[$node].get_our_node_id(), msg); } } @@ -1836,23 +2031,47 @@ pub fn do_test(data: &[u8], out: Out) { MessageSendEvent::SendTxRemoveInput { ref node_id, ref msg } => { for (idx, dest) in nodes.iter().enumerate() { if dest.get_our_node_id() == *node_id { - out.locked_write(format!("Delivering tx_remove_input from node {} to node {}.\n", $node, idx).as_bytes()); - dest.handle_tx_remove_input(nodes[$node].get_our_node_id(), msg); + out.locked_write( + format!( + "Delivering tx_remove_input from node {} to node {}.\n", + $node, idx + ) + .as_bytes(), + ); + dest.handle_tx_remove_input( + nodes[$node].get_our_node_id(), + msg, + ); } } }, MessageSendEvent::SendTxRemoveOutput { ref node_id, ref msg } => { for (idx, dest) in nodes.iter().enumerate() { if dest.get_our_node_id() == *node_id { - out.locked_write(format!("Delivering tx_remove_output from node {} to node {}.\n", $node, idx).as_bytes()); - dest.handle_tx_remove_output(nodes[$node].get_our_node_id(), msg); + out.locked_write( + format!( + "Delivering tx_remove_output from node {} to node {}.\n", + $node, idx + ) + .as_bytes(), + ); + dest.handle_tx_remove_output( + nodes[$node].get_our_node_id(), + msg, + ); } } }, MessageSendEvent::SendTxComplete { ref node_id, ref msg } => { for (idx, dest) in nodes.iter().enumerate() { if dest.get_our_node_id() == *node_id { - out.locked_write(format!("Delivering tx_complete from node {} to node {}.\n", $node, idx).as_bytes()); + out.locked_write( + format!( + "Delivering tx_complete from node {} to node {}.\n", + $node, idx + ) + .as_bytes(), + ); dest.handle_tx_complete(nodes[$node].get_our_node_id(), msg); } } @@ -1860,7 +2079,13 @@ pub fn do_test(data: &[u8], out: Out) { MessageSendEvent::SendTxAbort { ref node_id, ref msg } => { for (idx, dest) in nodes.iter().enumerate() { if dest.get_our_node_id() == *node_id { - out.locked_write(format!("Delivering tx_abort from node {} to node {}.\n", $node, idx).as_bytes()); + out.locked_write( + format!( + "Delivering tx_abort from node {} to node {}.\n", + $node, idx + ) + .as_bytes(), + ); dest.handle_tx_abort(nodes[$node].get_our_node_id(), msg); } } @@ -1868,7 +2093,13 @@ pub fn do_test(data: &[u8], out: Out) { MessageSendEvent::SendTxInitRbf { ref node_id, ref msg } => { for (idx, dest) in nodes.iter().enumerate() { if dest.get_our_node_id() == *node_id { - out.locked_write(format!("Delivering tx_init_rbf from node {} to node {}.\n", $node, idx).as_bytes()); + out.locked_write( + format!( + "Delivering tx_init_rbf from node {} to node {}.\n", + $node, idx + ) + .as_bytes(), + ); dest.handle_tx_init_rbf(nodes[$node].get_our_node_id(), msg); } } @@ -1876,7 +2107,13 @@ pub fn do_test(data: &[u8], out: Out) { MessageSendEvent::SendTxAckRbf { ref node_id, ref msg } => { for (idx, dest) in nodes.iter().enumerate() { if dest.get_our_node_id() == *node_id { - out.locked_write(format!("Delivering tx_ack_rbf from node {} to node {}.\n", $node, idx).as_bytes()); + out.locked_write( + format!( + "Delivering tx_ack_rbf from node {} to node {}.\n", + $node, idx + ) + .as_bytes(), + ); dest.handle_tx_ack_rbf(nodes[$node].get_our_node_id(), msg); } } @@ -1884,7 +2121,13 @@ pub fn do_test(data: &[u8], out: Out) { MessageSendEvent::SendTxSignatures { ref node_id, ref msg } => { for (idx, dest) in nodes.iter().enumerate() { if dest.get_our_node_id() == *node_id { - out.locked_write(format!("Delivering tx_signatures from node {} to node {}.\n", $node, idx).as_bytes()); + out.locked_write( + format!( + "Delivering tx_signatures from node {} to node {}.\n", + $node, idx + ) + .as_bytes(), + ); dest.handle_tx_signatures(nodes[$node].get_our_node_id(), msg); } } @@ -1892,7 +2135,13 @@ pub fn do_test(data: &[u8], out: Out) { MessageSendEvent::SendSpliceInit { ref node_id, ref msg } => { for (idx, dest) in nodes.iter().enumerate() { if dest.get_our_node_id() == *node_id { - out.locked_write(format!("Delivering splice_init from node {} to node {}.\n", $node, idx).as_bytes()); + out.locked_write( + format!( + "Delivering splice_init from node {} to node {}.\n", + $node, idx + ) + .as_bytes(), + ); dest.handle_splice_init(nodes[$node].get_our_node_id(), msg); } } @@ -1900,7 +2149,13 @@ pub fn do_test(data: &[u8], out: Out) { MessageSendEvent::SendSpliceAck { ref node_id, ref msg } => { for (idx, dest) in nodes.iter().enumerate() { if dest.get_our_node_id() == *node_id { - out.locked_write(format!("Delivering splice_ack from node {} to node {}.\n", $node, idx).as_bytes()); + out.locked_write( + format!( + "Delivering splice_ack from node {} to node {}.\n", + $node, idx + ) + .as_bytes(), + ); dest.handle_splice_ack(nodes[$node].get_our_node_id(), msg); } } @@ -1908,7 +2163,13 @@ pub fn do_test(data: &[u8], out: Out) { MessageSendEvent::SendSpliceLocked { ref node_id, ref msg } => { for (idx, dest) in nodes.iter().enumerate() { if dest.get_our_node_id() == *node_id { - out.locked_write(format!("Delivering splice_locked from node {} to node {}.\n", $node, idx).as_bytes()); + out.locked_write( + format!( + "Delivering splice_locked from node {} to node {}.\n", + $node, idx + ) + .as_bytes(), + ); dest.handle_splice_locked(nodes[$node].get_our_node_id(), msg); } } @@ -1938,14 +2199,22 @@ pub fn do_test(data: &[u8], out: Out) { if $node == 1 { push_excess_b_events!(extra_ev.into_iter().chain(events_iter), None); } else if $node == 0 { - if let Some(ev) = extra_ev { ab_events.push(ev); } - for event in events_iter { ab_events.push(event); } + if let Some(ev) = extra_ev { + ab_events.push(ev); + } + for event in events_iter { + ab_events.push(event); + } } else { - if let Some(ev) = extra_ev { cb_events.push(ev); } - for event in events_iter { cb_events.push(event); } + if let Some(ev) = extra_ev { + cb_events.push(ev); + } + for event in events_iter { + cb_events.push(event); + } } had_events - } } + }}; } macro_rules! process_msg_noret { @@ -2976,7 +3245,7 @@ pub fn chanmon_consistency_test(data: &[u8] do_test(data, out); } -#[no_mangle] +#[unsafe(no_mangle)] pub extern "C" fn chanmon_consistency_run(data: *const u8, datalen: usize) { do_test(unsafe { std::slice::from_raw_parts(data, datalen) }, test_logger::DevNull {}); } diff --git a/fuzz/src/chanmon_deser.rs b/fuzz/src/chanmon_deser.rs index 3206db0b143..597328c2538 100644 --- a/fuzz/src/chanmon_deser.rs +++ b/fuzz/src/chanmon_deser.rs @@ -1,7 +1,7 @@ // This file is auto-generated by gen_target.sh based on msg_target_template.txt // To modify it, modify msg_target_template.txt and run gen_target.sh instead. -use lightning::chain::{channelmonitor, BlockLocator}; +use lightning::chain::{BlockLocator, channelmonitor}; use lightning::util::ser::{ReadableArgs, Writeable, Writer}; use lightning::util::test_channel_signer::TestChannelSigner; use lightning::util::test_utils::OnlyReadsKeysInterface; @@ -42,7 +42,7 @@ pub fn chanmon_deser_test(data: &[u8], out: Out) { do_test(data, out); } -#[no_mangle] +#[unsafe(no_mangle)] pub extern "C" fn chanmon_deser_run(data: *const u8, datalen: usize) { do_test(unsafe { std::slice::from_raw_parts(data, datalen) }, test_logger::DevNull {}); } diff --git a/fuzz/src/feature_flags.rs b/fuzz/src/feature_flags.rs index af1f49626b1..86fb5a2e918 100644 --- a/fuzz/src/feature_flags.rs +++ b/fuzz/src/feature_flags.rs @@ -91,7 +91,7 @@ pub fn feature_flags_test(data: &[u8], _out: Out) { do_test(data); } -#[no_mangle] +#[unsafe(no_mangle)] pub extern "C" fn feature_flags_run(data: *const u8, datalen: usize) { do_test(unsafe { std::slice::from_raw_parts(data, datalen) }); } diff --git a/fuzz/src/fromstr_to_netaddress.rs b/fuzz/src/fromstr_to_netaddress.rs index 384ea56a8ef..5a521e3fbde 100644 --- a/fuzz/src/fromstr_to_netaddress.rs +++ b/fuzz/src/fromstr_to_netaddress.rs @@ -23,7 +23,7 @@ pub fn fromstr_to_netaddress_test(data: &[u8], _out: O do_test(data); } -#[no_mangle] +#[unsafe(no_mangle)] pub extern "C" fn fromstr_to_netaddress_run(data: *const u8, datalen: usize) { do_test(unsafe { std::slice::from_raw_parts(data, datalen) }); } diff --git a/fuzz/src/fs_store.rs b/fuzz/src/fs_store.rs index 4d86ffce2e6..2a382309742 100644 --- a/fuzz/src/fs_store.rs +++ b/fuzz/src/fs_store.rs @@ -178,7 +178,7 @@ pub fn fs_store_test(data: &[u8], out: Out) { } /// Method that needs to be added manually, {name}_run -#[no_mangle] +#[unsafe(no_mangle)] pub extern "C" fn fs_store_run(data: *const u8, datalen: usize) { do_test(unsafe { std::slice::from_raw_parts(data, datalen) }, test_logger::DevNull {}); } diff --git a/fuzz/src/full_stack.rs b/fuzz/src/full_stack.rs index 405d615e6f0..1ddf0839bbc 100644 --- a/fuzz/src/full_stack.rs +++ b/fuzz/src/full_stack.rs @@ -13,6 +13,7 @@ //! or payments to send/ways to handle events generated. //! This test has been very useful, though due to its complexity good starting inputs are critical. +use bitcoin::FeeRate; use bitcoin::amount::Amount; use bitcoin::consensus::encode::deserialize; use bitcoin::constants::genesis_block; @@ -22,14 +23,13 @@ use bitcoin::opcodes; use bitcoin::script::{Builder, ScriptBuf}; use bitcoin::transaction::Version; use bitcoin::transaction::{Transaction, TxIn, TxOut}; -use bitcoin::FeeRate; +use bitcoin::WPubkeyHash; use bitcoin::hash_types::{BlockHash, Txid}; +use bitcoin::hashes::Hash as _; use bitcoin::hashes::sha256::Hash as Sha256; use bitcoin::hashes::sha256d::Hash as Sha256dHash; -use bitcoin::hashes::Hash as _; use bitcoin::hex::FromHex; -use bitcoin::WPubkeyHash; use lightning::blinded_path::message::{BlindedMessagePath, MessageContext, MessageForwardNode}; use lightning::blinded_path::payment::{BlindedPaymentPath, ReceiveTlvs}; @@ -1166,7 +1166,7 @@ pub fn full_stack_test(data: & do_test(data, &logger); } -#[no_mangle] +#[unsafe(no_mangle)] pub extern "C" fn full_stack_run(data: *const u8, datalen: usize) { let logger: Arc = Arc::new(test_logger::TestLogger::new("".to_owned(), test_logger::DevNull {})); @@ -1192,7 +1192,10 @@ fn two_peer_forwarding_seed() -> Vec { // our network key ext_from_hex("0100000000000000000000000000000000000000000000000000000000000000", &mut test); // config - ext_from_hex("000000000090000000000000000064000100000000000100ffff00000000000000ffffffffffffffffff0000000000000000ffffffffffffffff000000ffffffff00ffff1a000400010000020400000000040200000a08ffffffffffffffff0001000000000000", &mut test); + ext_from_hex( + "000000000090000000000000000064000100000000000100ffff00000000000000ffffffffffffffffff0000000000000000ffffffffffffffff000000ffffffff00ffff1a000400010000020400000000040200000a08ffffffffffffffff0001000000000000", + &mut test, + ); // new outbound connection with id 0 ext_from_hex("00", &mut test); @@ -1201,7 +1204,10 @@ fn two_peer_forwarding_seed() -> Vec { // inbound read from peer id 0 of len 50 ext_from_hex("030032", &mut test); // noise act two (0||pubkey||mac) - ext_from_hex("00 030000000000000000000000000000000000000000000000000000000000000002 03000000000000000000000000000000", &mut test); + ext_from_hex( + "00 030000000000000000000000000000000000000000000000000000000000000002 03000000000000000000000000000000", + &mut test, + ); // inbound read from peer id 0 of len 18 ext_from_hex("030012", &mut test); @@ -1219,11 +1225,17 @@ fn two_peer_forwarding_seed() -> Vec { // inbound read from peer id 0 of len 254 ext_from_hex("0300fe", &mut test); // beginning of open_channel message - ext_from_hex("0020 6fe28c0ab6f1b372c1a6a246ae63f74f931e8365e15a089c68d6190000000000 ff4f00f805273c1b203bb5ebf8436bfde57b3be8c2f5e95d9491dbb181909679 000000000000c350 0000000000000000 0000000000000162 ffffffffffffffff 0000000000000222 0000000000000000 000000fd 0006 01e3 030000000000000000000000000000000000000000000000000000000000000001 030000000000000000000000000000000000000000000000000000000000000002 030000000000000000000000000000000000000000000000000000000000000003 030000000000000000000000000000000000000000000000000000000000000004", &mut test); + ext_from_hex( + "0020 6fe28c0ab6f1b372c1a6a246ae63f74f931e8365e15a089c68d6190000000000 ff4f00f805273c1b203bb5ebf8436bfde57b3be8c2f5e95d9491dbb181909679 000000000000c350 0000000000000000 0000000000000162 ffffffffffffffff 0000000000000222 0000000000000000 000000fd 0006 01e3 030000000000000000000000000000000000000000000000000000000000000001 030000000000000000000000000000000000000000000000000000000000000002 030000000000000000000000000000000000000000000000000000000000000003 030000000000000000000000000000000000000000000000000000000000000004", + &mut test, + ); // inbound read from peer id 0 of len 89 ext_from_hex("030059", &mut test); // rest of open_channel and mac - ext_from_hex("030000000000000000000000000000000000000000000000000000000000000005 020900000000000000000000000000000000000000000000000000000000000000 01 0000 01021000 03000000000000000000000000000000", &mut test); + ext_from_hex( + "030000000000000000000000000000000000000000000000000000000000000005 020900000000000000000000000000000000000000000000000000000000000000 01 0000 01021000 03000000000000000000000000000000", + &mut test, + ); // client should now respond with accept_channel (CHECK 1: type 33 to peer 03000000) @@ -1234,13 +1246,19 @@ fn two_peer_forwarding_seed() -> Vec { // inbound read from peer id 0 of len 148 ext_from_hex("030094", &mut test); // funding_created and mac - ext_from_hex("0022 ff4f00f805273c1b203bb5ebf8436bfde57b3be8c2f5e95d9491dbb181909679 c000000000000000000000000000000000000000000000000000000000000000 0000 00000000000000000000000000000000000000000000000000000000000000dc0100000000000000000000000000000000000000000000000000000000000000 03000000000000000000000000000000", &mut test); + ext_from_hex( + "0022 ff4f00f805273c1b203bb5ebf8436bfde57b3be8c2f5e95d9491dbb181909679 c000000000000000000000000000000000000000000000000000000000000000 0000 00000000000000000000000000000000000000000000000000000000000000dc0100000000000000000000000000000000000000000000000000000000000000 03000000000000000000000000000000", + &mut test, + ); // client should now respond with funding_signed (CHECK 2: type 35 to peer 03000000) // connect a block with one transaction of len 94 ext_from_hex("0c005e", &mut test); // the funding transaction - ext_from_hex("020000000100000000000000000000000000000000000000000000000000000000000000000000000000ffffffff0150c3000000000000220020530000000000000000000000000000000000000000000000000000000000000000000000", &mut test); + ext_from_hex( + "020000000100000000000000000000000000000000000000000000000000000000000000000000000000ffffffff0150c3000000000000220020530000000000000000000000000000000000000000000000000000000000000000000000", + &mut test, + ); // connect a block with no transactions, one per line ext_from_hex("0c0000", &mut test); ext_from_hex("0c0000", &mut test); @@ -1263,18 +1281,27 @@ fn two_peer_forwarding_seed() -> Vec { // inbound read from peer id 0 of len 83 ext_from_hex("030053", &mut test); // channel_ready and mac - ext_from_hex("0024 c000000000000000000000000000000000000000000000000000000000000000 020800000000000000000000000000000000000000000000000000000000000000 03000000000000000000000000000000", &mut test); + ext_from_hex( + "0024 c000000000000000000000000000000000000000000000000000000000000000 020800000000000000000000000000000000000000000000000000000000000000 03000000000000000000000000000000", + &mut test, + ); // new inbound connection with id 1 ext_from_hex("01", &mut test); // inbound read from peer id 1 of len 50 ext_from_hex("030132", &mut test); // inbound noise act 1 - ext_from_hex("0003000000000000000000000000000000000000000000000000000000000000000703000000000000000000000000000000", &mut test); + ext_from_hex( + "0003000000000000000000000000000000000000000000000000000000000000000703000000000000000000000000000000", + &mut test, + ); // inbound read from peer id 1 of len 66 ext_from_hex("030142", &mut test); // inbound noise act 3 - ext_from_hex("000302000000000000000000000000000000000000000000000000000000000000000300000000000000000000000000000003000000000000000000000000000000", &mut test); + ext_from_hex( + "000302000000000000000000000000000000000000000000000000000000000000000300000000000000000000000000000003000000000000000000000000000000", + &mut test, + ); // inbound read from peer id 1 of len 18 ext_from_hex("030112", &mut test); @@ -1298,7 +1325,10 @@ fn two_peer_forwarding_seed() -> Vec { // inbound read from peer id 1 of len 255 ext_from_hex("0301ff", &mut test); // beginning of accept_channel - ext_from_hex("0021 2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a 0000000000000162 00000000004c4b40 00000000000003e8 00000000000003e8 00000002 03f0 0005 030000000000000000000000000000000000000000000000000000000000000100 030000000000000000000000000000000000000000000000000000000000000200 030000000000000000000000000000000000000000000000000000000000000300 030000000000000000000000000000000000000000000000000000000000000400 030000000000000000000000000000000000000000000000000000000000000500 02660000000000000000000000000000", &mut test); + ext_from_hex( + "0021 2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a 0000000000000162 00000000004c4b40 00000000000003e8 00000000000003e8 00000002 03f0 0005 030000000000000000000000000000000000000000000000000000000000000100 030000000000000000000000000000000000000000000000000000000000000200 030000000000000000000000000000000000000000000000000000000000000300 030000000000000000000000000000000000000000000000000000000000000400 030000000000000000000000000000000000000000000000000000000000000500 02660000000000000000000000000000", + &mut test, + ); // inbound read from peer id 1 of len 39 ext_from_hex("030127", &mut test); // rest of accept_channel and mac @@ -1317,7 +1347,10 @@ fn two_peer_forwarding_seed() -> Vec { // inbound read from peer id 1 of len 114 ext_from_hex("030172", &mut test); // funding_signed message and mac - ext_from_hex("0023 c400000000000000000000000000000000000000000000000000000000000000 00000000000000000000000000000000000000000000000000000000000000310001000000000000000000000000000000000000000000000000000000000000 01000000000000000000000000000000", &mut test); + ext_from_hex( + "0023 c400000000000000000000000000000000000000000000000000000000000000 00000000000000000000000000000000000000000000000000000000000000310001000000000000000000000000000000000000000000000000000000000000 01000000000000000000000000000000", + &mut test, + ); // broadcast funding transaction ext_from_hex("0b", &mut test); @@ -1330,7 +1363,10 @@ fn two_peer_forwarding_seed() -> Vec { // inbound read from peer id 1 of len 83 ext_from_hex("030153", &mut test); // channel_ready and mac - ext_from_hex("0024 c400000000000000000000000000000000000000000000000000000000000000 026700000000000000000000000000000000000000000000000000000000000000 01000000000000000000000000000000", &mut test); + ext_from_hex( + "0024 c400000000000000000000000000000000000000000000000000000000000000 026700000000000000000000000000000000000000000000000000000000000000 01000000000000000000000000000000", + &mut test, + ); // inbound read from peer id 0 of len 18 ext_from_hex("030012", &mut test); @@ -1339,23 +1375,41 @@ fn two_peer_forwarding_seed() -> Vec { // inbound read from peer id 0 of len 255 ext_from_hex("0300ff", &mut test); // beginning of update_add_htlc from 0 to 1 via client - ext_from_hex("0080 c000000000000000000000000000000000000000000000000000000000000000 0000000000000000 0000000000003e80 ff00000000000000000000000000000000000000000000000000000000000000 000003f0 00 030000000000000000000000000000000000000000000000000000000000000555 11 020203e8 0401a0 060800000e0000010000 0a00000000000000000000000000000000000000000000000000000000000000 ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", &mut test); + ext_from_hex( + "0080 c000000000000000000000000000000000000000000000000000000000000000 0000000000000000 0000000000003e80 ff00000000000000000000000000000000000000000000000000000000000000 000003f0 00 030000000000000000000000000000000000000000000000000000000000000555 11 020203e8 0401a0 060800000e0000010000 0a00000000000000000000000000000000000000000000000000000000000000 ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", + &mut test, + ); // inbound read from peer id 0 of len 255 ext_from_hex("0300ff", &mut test); - ext_from_hex("ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", &mut test); + ext_from_hex( + "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", + &mut test, + ); // inbound read from peer id 0 of len 255 ext_from_hex("0300ff", &mut test); - ext_from_hex("ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", &mut test); + ext_from_hex( + "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", + &mut test, + ); // inbound read from peer id 0 of len 255 ext_from_hex("0300ff", &mut test); - ext_from_hex("ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", &mut test); + ext_from_hex( + "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", + &mut test, + ); // inbound read from peer id 0 of len 255 ext_from_hex("0300ff", &mut test); - ext_from_hex("ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", &mut test); + ext_from_hex( + "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", + &mut test, + ); // inbound read from peer id 0 of len 193 ext_from_hex("0300c1", &mut test); // end of update_add_htlc from 0 to 1 via client and mac - ext_from_hex("ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff ab00000000000000000000000000000000000000000000000000000000000000 03000000000000000000000000000000", &mut test); + ext_from_hex( + "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff ab00000000000000000000000000000000000000000000000000000000000000 03000000000000000000000000000000", + &mut test, + ); // inbound read from peer id 0 of len 18 ext_from_hex("030012", &mut test); @@ -1364,7 +1418,10 @@ fn two_peer_forwarding_seed() -> Vec { // inbound read from peer id 0 of len 116 ext_from_hex("030074", &mut test); // commitment_signed and mac - ext_from_hex("0084 c000000000000000000000000000000000000000000000000000000000000000 00000000000000000000000000000000000000000000000000000000000000cd0100000000000000000000000000000000000000000000000000000000000000 0000 03000000000000000000000000000000", &mut test); + ext_from_hex( + "0084 c000000000000000000000000000000000000000000000000000000000000000 00000000000000000000000000000000000000000000000000000000000000cd0100000000000000000000000000000000000000000000000000000000000000 0000 03000000000000000000000000000000", + &mut test, + ); // client should now respond with revoke_and_ack and commitment_signed (CHECK 5/6: types 133 and 132 to peer 03000000) // inbound read from peer id 0 of len 18 @@ -1374,7 +1431,10 @@ fn two_peer_forwarding_seed() -> Vec { // inbound read from peer id 0 of len 115 ext_from_hex("030073", &mut test); // revoke_and_ack and mac - ext_from_hex("0085 c000000000000000000000000000000000000000000000000000000000000000 0900000000000000000000000000000000000000000000000000000000000000 020b00000000000000000000000000000000000000000000000000000000000000 03000000000000000000000000000000", &mut test); + ext_from_hex( + "0085 c000000000000000000000000000000000000000000000000000000000000000 0900000000000000000000000000000000000000000000000000000000000000 020b00000000000000000000000000000000000000000000000000000000000000 03000000000000000000000000000000", + &mut test, + ); // process the now-pending HTLC forward ext_from_hex("07", &mut test); @@ -1388,7 +1448,10 @@ fn two_peer_forwarding_seed() -> Vec { // inbound read from peer id 1 of len 116 ext_from_hex("030174", &mut test); // commitment_signed and mac - ext_from_hex("0084 c400000000000000000000000000000000000000000000000000000000000000 00000000000000000000000000000000000000000000000000000000000000720001000000000000000000000000000000000000000000000000000000000000 0000 01000000000000000000000000000000", &mut test); + ext_from_hex( + "0084 c400000000000000000000000000000000000000000000000000000000000000 00000000000000000000000000000000000000000000000000000000000000720001000000000000000000000000000000000000000000000000000000000000 0000 01000000000000000000000000000000", + &mut test, + ); // // inbound read from peer id 1 of len 18 ext_from_hex("030112", &mut test); @@ -1397,7 +1460,10 @@ fn two_peer_forwarding_seed() -> Vec { // inbound read from peer id 1 of len 115 ext_from_hex("030173", &mut test); // revoke_and_ack and mac - ext_from_hex("0085 c400000000000000000000000000000000000000000000000000000000000000 6600000000000000000000000000000000000000000000000000000000000000 026400000000000000000000000000000000000000000000000000000000000000 01000000000000000000000000000000", &mut test); + ext_from_hex( + "0085 c400000000000000000000000000000000000000000000000000000000000000 6600000000000000000000000000000000000000000000000000000000000000 026400000000000000000000000000000000000000000000000000000000000000 01000000000000000000000000000000", + &mut test, + ); // // inbound read from peer id 1 of len 18 ext_from_hex("030112", &mut test); @@ -1406,7 +1472,10 @@ fn two_peer_forwarding_seed() -> Vec { // inbound read from peer id 1 of len 90 ext_from_hex("03015a", &mut test); // update_fulfill_htlc and mac - ext_from_hex("0082 c400000000000000000000000000000000000000000000000000000000000000 0000000000000000 ff00888888888888888888888888888888888888888888888888888888888888 01000000000000000000000000000000", &mut test); + ext_from_hex( + "0082 c400000000000000000000000000000000000000000000000000000000000000 0000000000000000 ff00888888888888888888888888888888888888888888888888888888888888 01000000000000000000000000000000", + &mut test, + ); // client should immediately claim the pending HTLC from peer 0 (CHECK 8: SendFulfillHTLCs for node 03000000 with preimage ff00888888 for channel c0000000) // inbound read from peer id 1 of len 18 @@ -1416,7 +1485,10 @@ fn two_peer_forwarding_seed() -> Vec { // inbound read from peer id 1 of len 116 ext_from_hex("030174", &mut test); // commitment_signed and mac - ext_from_hex("0084 c400000000000000000000000000000000000000000000000000000000000000 00000000000000000000000000000000000000000000000000000000000000700001000000000000000000000000000000000000000000000000000000000000 0000 01000000000000000000000000000000", &mut test); + ext_from_hex( + "0084 c400000000000000000000000000000000000000000000000000000000000000 00000000000000000000000000000000000000000000000000000000000000700001000000000000000000000000000000000000000000000000000000000000 0000 01000000000000000000000000000000", + &mut test, + ); // inbound read from peer id 1 of len 18 ext_from_hex("030112", &mut test); @@ -1425,7 +1497,10 @@ fn two_peer_forwarding_seed() -> Vec { // inbound read from peer id 1 of len 115 ext_from_hex("030173", &mut test); // revoke_and_ack and mac - ext_from_hex("0085 c400000000000000000000000000000000000000000000000000000000000000 6700000000000000000000000000000000000000000000000000000000000000 026500000000000000000000000000000000000000000000000000000000000000 01000000000000000000000000000000", &mut test); + ext_from_hex( + "0085 c400000000000000000000000000000000000000000000000000000000000000 6700000000000000000000000000000000000000000000000000000000000000 026500000000000000000000000000000000000000000000000000000000000000 01000000000000000000000000000000", + &mut test, + ); // before responding to the commitment_signed generated above, send a new HTLC // inbound read from peer id 0 of len 18 @@ -1435,23 +1510,41 @@ fn two_peer_forwarding_seed() -> Vec { // inbound read from peer id 0 of len 255 ext_from_hex("0300ff", &mut test); // beginning of update_add_htlc from 0 to 1 via client - ext_from_hex("0080 c000000000000000000000000000000000000000000000000000000000000000 0000000000000001 0000000000003e80 ff00000000000000000000000000000000000000000000000000000000000000 000003f0 00 030000000000000000000000000000000000000000000000000000000000000555 11 020203e8 0401a0 060800000e0000010000 0a00000000000000000000000000000000000000000000000000000000000000 ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", &mut test); + ext_from_hex( + "0080 c000000000000000000000000000000000000000000000000000000000000000 0000000000000001 0000000000003e80 ff00000000000000000000000000000000000000000000000000000000000000 000003f0 00 030000000000000000000000000000000000000000000000000000000000000555 11 020203e8 0401a0 060800000e0000010000 0a00000000000000000000000000000000000000000000000000000000000000 ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", + &mut test, + ); // inbound read from peer id 0 of len 255 ext_from_hex("0300ff", &mut test); - ext_from_hex("ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", &mut test); + ext_from_hex( + "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", + &mut test, + ); // inbound read from peer id 0 of len 255 ext_from_hex("0300ff", &mut test); - ext_from_hex("ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", &mut test); + ext_from_hex( + "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", + &mut test, + ); // inbound read from peer id 0 of len 255 ext_from_hex("0300ff", &mut test); - ext_from_hex("ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", &mut test); + ext_from_hex( + "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", + &mut test, + ); // inbound read from peer id 0 of len 255 ext_from_hex("0300ff", &mut test); - ext_from_hex("ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", &mut test); + ext_from_hex( + "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", + &mut test, + ); // inbound read from peer id 0 of len 193 ext_from_hex("0300c1", &mut test); // end of update_add_htlc from 0 to 1 via client and mac - ext_from_hex("ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff ab00000000000000000000000000000000000000000000000000000000000000 03000000000000000000000000000000", &mut test); + ext_from_hex( + "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff ab00000000000000000000000000000000000000000000000000000000000000 03000000000000000000000000000000", + &mut test, + ); // now respond to the update_fulfill_htlc+commitment_signed messages the client sent to peer 0 // inbound read from peer id 0 of len 18 @@ -1461,7 +1554,10 @@ fn two_peer_forwarding_seed() -> Vec { // inbound read from peer id 0 of len 115 ext_from_hex("030073", &mut test); // revoke_and_ack and mac - ext_from_hex("0085 c000000000000000000000000000000000000000000000000000000000000000 0800000000000000000000000000000000000000000000000000000000000000 020a00000000000000000000000000000000000000000000000000000000000000 03000000000000000000000000000000", &mut test); + ext_from_hex( + "0085 c000000000000000000000000000000000000000000000000000000000000000 0800000000000000000000000000000000000000000000000000000000000000 020a00000000000000000000000000000000000000000000000000000000000000 03000000000000000000000000000000", + &mut test, + ); // client should now respond with revoke_and_ack and commitment_signed (CHECK 5/6 duplicates) // inbound read from peer id 0 of len 18 @@ -1471,7 +1567,10 @@ fn two_peer_forwarding_seed() -> Vec { // inbound read from peer id 0 of len 116 ext_from_hex("030074", &mut test); // commitment_signed and mac - ext_from_hex("0084 c000000000000000000000000000000000000000000000000000000000000000 000000000000000000000000000000000000000000000000000000000000003e0100000000000000000000000000000000000000000000000000000000000000 0000 03000000000000000000000000000000", &mut test); + ext_from_hex( + "0084 c000000000000000000000000000000000000000000000000000000000000000 000000000000000000000000000000000000000000000000000000000000003e0100000000000000000000000000000000000000000000000000000000000000 0000 03000000000000000000000000000000", + &mut test, + ); // inbound read from peer id 0 of len 18 ext_from_hex("030012", &mut test); @@ -1480,7 +1579,10 @@ fn two_peer_forwarding_seed() -> Vec { // inbound read from peer id 0 of len 115 ext_from_hex("030073", &mut test); // revoke_and_ack and mac - ext_from_hex("0085 c000000000000000000000000000000000000000000000000000000000000000 0b00000000000000000000000000000000000000000000000000000000000000 020d00000000000000000000000000000000000000000000000000000000000000 03000000000000000000000000000000", &mut test); + ext_from_hex( + "0085 c000000000000000000000000000000000000000000000000000000000000000 0b00000000000000000000000000000000000000000000000000000000000000 020d00000000000000000000000000000000000000000000000000000000000000 03000000000000000000000000000000", + &mut test, + ); // process the now-pending HTLC forward ext_from_hex("07", &mut test); @@ -1495,7 +1597,10 @@ fn two_peer_forwarding_seed() -> Vec { // inbound read from peer id 1 of len 116 ext_from_hex("030174", &mut test); // commitment_signed and mac - ext_from_hex("0084 c400000000000000000000000000000000000000000000000000000000000000 000000000000000000000000000000000000000000000000000000000000007e0001000000000000000000000000000000000000000000000000000000000000 0000 01000000000000000000000000000000", &mut test); + ext_from_hex( + "0084 c400000000000000000000000000000000000000000000000000000000000000 000000000000000000000000000000000000000000000000000000000000007e0001000000000000000000000000000000000000000000000000000000000000 0000 01000000000000000000000000000000", + &mut test, + ); // inbound read from peer id 1 of len 18 ext_from_hex("030112", &mut test); @@ -1504,7 +1609,10 @@ fn two_peer_forwarding_seed() -> Vec { // inbound read from peer id 1 of len 115 ext_from_hex("030173", &mut test); // revoke_and_ack and mac - ext_from_hex("0085 c400000000000000000000000000000000000000000000000000000000000000 6400000000000000000000000000000000000000000000000000000000000000 027000000000000000000000000000000000000000000000000000000000000000 01000000000000000000000000000000", &mut test); + ext_from_hex( + "0085 c400000000000000000000000000000000000000000000000000000000000000 6400000000000000000000000000000000000000000000000000000000000000 027000000000000000000000000000000000000000000000000000000000000000 01000000000000000000000000000000", + &mut test, + ); // inbound read from peer id 1 of len 18 ext_from_hex("030112", &mut test); @@ -1513,7 +1621,10 @@ fn two_peer_forwarding_seed() -> Vec { // inbound read from peer id 1 of len 60 ext_from_hex("03013c", &mut test); // update_fail_htlc and mac - ext_from_hex("0083 c400000000000000000000000000000000000000000000000000000000000000 0000000000000001 0000 01000000000000000000000000000000", &mut test); + ext_from_hex( + "0083 c400000000000000000000000000000000000000000000000000000000000000 0000000000000001 0000 01000000000000000000000000000000", + &mut test, + ); // inbound read from peer id 1 of len 18 ext_from_hex("030112", &mut test); @@ -1522,7 +1633,10 @@ fn two_peer_forwarding_seed() -> Vec { // inbound read from peer id 1 of len 116 ext_from_hex("030174", &mut test); // commitment_signed and mac - ext_from_hex("0084 c400000000000000000000000000000000000000000000000000000000000000 00000000000000000000000000000000000000000000000000000000000000410001000000000000000000000000000000000000000000000000000000000000 0000 01000000000000000000000000000000", &mut test); + ext_from_hex( + "0084 c400000000000000000000000000000000000000000000000000000000000000 00000000000000000000000000000000000000000000000000000000000000410001000000000000000000000000000000000000000000000000000000000000 0000 01000000000000000000000000000000", + &mut test, + ); // inbound read from peer id 1 of len 18 ext_from_hex("030112", &mut test); @@ -1531,7 +1645,10 @@ fn two_peer_forwarding_seed() -> Vec { // inbound read from peer id 1 of len 115 ext_from_hex("030173", &mut test); // revoke_and_ack and mac - ext_from_hex("0085 c400000000000000000000000000000000000000000000000000000000000000 6500000000000000000000000000000000000000000000000000000000000000 027100000000000000000000000000000000000000000000000000000000000000 01000000000000000000000000000000", &mut test); + ext_from_hex( + "0085 c400000000000000000000000000000000000000000000000000000000000000 6500000000000000000000000000000000000000000000000000000000000000 027100000000000000000000000000000000000000000000000000000000000000 01000000000000000000000000000000", + &mut test, + ); // process the now-pending HTLC forward ext_from_hex("07", &mut test); @@ -1545,7 +1662,10 @@ fn two_peer_forwarding_seed() -> Vec { // inbound read from peer id 0 of len 115 ext_from_hex("030073", &mut test); // revoke_and_ack and mac - ext_from_hex("0085 c000000000000000000000000000000000000000000000000000000000000000 0a00000000000000000000000000000000000000000000000000000000000000 020c00000000000000000000000000000000000000000000000000000000000000 03000000000000000000000000000000", &mut test); + ext_from_hex( + "0085 c000000000000000000000000000000000000000000000000000000000000000 0a00000000000000000000000000000000000000000000000000000000000000 020c00000000000000000000000000000000000000000000000000000000000000 03000000000000000000000000000000", + &mut test, + ); // inbound read from peer id 0 of len 18 ext_from_hex("030012", &mut test); @@ -1554,7 +1674,10 @@ fn two_peer_forwarding_seed() -> Vec { // inbound read from peer id 0 of len 116 ext_from_hex("030074", &mut test); // commitment_signed and mac - ext_from_hex("0084 c000000000000000000000000000000000000000000000000000000000000000 00000000000000000000000000000000000000000000000000000000000000cf0100000000000000000000000000000000000000000000000000000000000000 0000 03000000000000000000000000000000", &mut test); + ext_from_hex( + "0084 c000000000000000000000000000000000000000000000000000000000000000 00000000000000000000000000000000000000000000000000000000000000cf0100000000000000000000000000000000000000000000000000000000000000 0000 03000000000000000000000000000000", + &mut test, + ); // client should now respond with revoke_and_ack (CHECK 5 duplicate) // inbound read from peer id 0 of len 18 @@ -1564,23 +1687,41 @@ fn two_peer_forwarding_seed() -> Vec { // inbound read from peer id 0 of len 255 ext_from_hex("0300ff", &mut test); // beginning of update_add_htlc from 0 to 1 via client - ext_from_hex("0080 c000000000000000000000000000000000000000000000000000000000000000 0000000000000002 00000000000b0838 ff00000000000000000000000000000000000000000000000000000000000000 000003f0 00 030000000000000000000000000000000000000000000000000000000000000555 12 02030927c1 0401a0 060800000e0000010000 0a00000000000000000000000000000000000000000000000000000000000000 ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", &mut test); + ext_from_hex( + "0080 c000000000000000000000000000000000000000000000000000000000000000 0000000000000002 00000000000b0838 ff00000000000000000000000000000000000000000000000000000000000000 000003f0 00 030000000000000000000000000000000000000000000000000000000000000555 12 02030927c1 0401a0 060800000e0000010000 0a00000000000000000000000000000000000000000000000000000000000000 ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", + &mut test, + ); // inbound read from peer id 0 of len 255 ext_from_hex("0300ff", &mut test); - ext_from_hex("ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", &mut test); + ext_from_hex( + "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", + &mut test, + ); // inbound read from peer id 0 of len 255 ext_from_hex("0300ff", &mut test); - ext_from_hex("ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", &mut test); + ext_from_hex( + "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", + &mut test, + ); // inbound read from peer id 0 of len 255 ext_from_hex("0300ff", &mut test); - ext_from_hex("ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", &mut test); + ext_from_hex( + "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", + &mut test, + ); // inbound read from peer id 0 of len 255 ext_from_hex("0300ff", &mut test); - ext_from_hex("ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", &mut test); + ext_from_hex( + "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", + &mut test, + ); // inbound read from peer id 0 of len 193 ext_from_hex("0300c1", &mut test); // end of update_add_htlc from 0 to 1 via client and mac - ext_from_hex("ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff 5200000000000000000000000000000000000000000000000000000000000000 03000000000000000000000000000000", &mut test); + ext_from_hex( + "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff 5200000000000000000000000000000000000000000000000000000000000000 03000000000000000000000000000000", + &mut test, + ); // inbound read from peer id 0 of len 18 ext_from_hex("030012", &mut test); @@ -1589,7 +1730,10 @@ fn two_peer_forwarding_seed() -> Vec { // inbound read from peer id 0 of len 180 ext_from_hex("0300b4", &mut test); // commitment_signed and mac - ext_from_hex("0084 c000000000000000000000000000000000000000000000000000000000000000 00000000000000000000000000000000000000000000000000000000000000f60100000000000000000000000000000000000000000000000000000000000000 0001 000000000000000000000000000000000000000000000000000000000000009b05000000000000000000000000000000000000000000000000000000000000fb 03000000000000000000000000000000", &mut test); + ext_from_hex( + "0084 c000000000000000000000000000000000000000000000000000000000000000 00000000000000000000000000000000000000000000000000000000000000f60100000000000000000000000000000000000000000000000000000000000000 0001 000000000000000000000000000000000000000000000000000000000000009b05000000000000000000000000000000000000000000000000000000000000fb 03000000000000000000000000000000", + &mut test, + ); // client should now respond with revoke_and_ack and commitment_signed (CHECK 5/6 duplicates) // inbound read from peer id 0 of len 18 @@ -1599,7 +1743,10 @@ fn two_peer_forwarding_seed() -> Vec { // inbound read from peer id 0 of len 115 ext_from_hex("030073", &mut test); // revoke_and_ack and mac - ext_from_hex("0085 c000000000000000000000000000000000000000000000000000000000000000 0d00000000000000000000000000000000000000000000000000000000000000 020f00000000000000000000000000000000000000000000000000000000000000 03000000000000000000000000000000", &mut test); + ext_from_hex( + "0085 c000000000000000000000000000000000000000000000000000000000000000 0d00000000000000000000000000000000000000000000000000000000000000 020f00000000000000000000000000000000000000000000000000000000000000 03000000000000000000000000000000", + &mut test, + ); // process the now-pending HTLC forward ext_from_hex("07", &mut test); @@ -1608,12 +1755,18 @@ fn two_peer_forwarding_seed() -> Vec { // connect a block with one transaction of len 125 ext_from_hex("0c007d", &mut test); // the commitment transaction for channel c400000000000000000000000000000000000000000000000000000000000000 - ext_from_hex("0200000001c400000000000000000000000000000000000000000000000000000000000000000000000000000080025802000000000000220020940000000000000000000000000000000000000000000000000000000000000013c0000000000000160014d60000000000000000000000000000000000000005000020", &mut test); + ext_from_hex( + "0200000001c400000000000000000000000000000000000000000000000000000000000000000000000000000080025802000000000000220020940000000000000000000000000000000000000000000000000000000000000013c0000000000000160014d60000000000000000000000000000000000000005000020", + &mut test, + ); // // connect a block with one transaction of len 94 ext_from_hex("0c005e", &mut test); // the HTLC timeout transaction - ext_from_hex("0200000001ab0000000000000000000000000000000000000000000000000000000000000000000000000000000001a7010000000000002200206c0000000000000000000000000000000000000000000000000000000000000000000000", &mut test); + ext_from_hex( + "0200000001ab0000000000000000000000000000000000000000000000000000000000000000000000000000000001a7010000000000002200206c0000000000000000000000000000000000000000000000000000000000000000000000", + &mut test, + ); // connect a block with no transactions ext_from_hex("0c0000", &mut test); // connect a block with no transactions @@ -1646,7 +1799,10 @@ fn gossip_exchange_seed() -> Vec { // our network key ext_from_hex("0100000000000000000000000000000000000000000000000000000000000000", &mut test); // config - ext_from_hex("000000000090000000000000000064000100000000000100ffff00000000000000ffffffffffffffffff0000000000000000ffffffffffffffff000000ffffffff00ffff1a000400010000020400000000040200000a08ffffffffffffffff0001000000000000", &mut test); + ext_from_hex( + "000000000090000000000000000064000100000000000100ffff00000000000000ffffffffffffffffff0000000000000000ffffffffffffffff000000ffffffff00ffff1a000400010000020400000000040200000a08ffffffffffffffff0001000000000000", + &mut test, + ); // new outbound connection with id 0 ext_from_hex("00", &mut test); @@ -1655,7 +1811,10 @@ fn gossip_exchange_seed() -> Vec { // inbound read from peer id 0 of len 50 ext_from_hex("030032", &mut test); // noise act two (0||pubkey||mac) - ext_from_hex("00 030000000000000000000000000000000000000000000000000000000000000002 03000000000000000000000000000000", &mut test); + ext_from_hex( + "00 030000000000000000000000000000000000000000000000000000000000000002 03000000000000000000000000000000", + &mut test, + ); // inbound read from peer id 0 of len 18 ext_from_hex("030012", &mut test); @@ -1671,11 +1830,17 @@ fn gossip_exchange_seed() -> Vec { // inbound read from peer id 1 of len 50 ext_from_hex("030132", &mut test); // inbound noise act 1 - ext_from_hex("0003000000000000000000000000000000000000000000000000000000000000000703000000000000000000000000000000", &mut test); + ext_from_hex( + "0003000000000000000000000000000000000000000000000000000000000000000703000000000000000000000000000000", + &mut test, + ); // inbound read from peer id 1 of len 66 ext_from_hex("030142", &mut test); // inbound noise act 3 - ext_from_hex("000302000000000000000000000000000000000000000000000000000000000000000300000000000000000000000000000003000000000000000000000000000000", &mut test); + ext_from_hex( + "000302000000000000000000000000000000000000000000000000000000000000000300000000000000000000000000000003000000000000000000000000000000", + &mut test, + ); // inbound read from peer id 1 of len 18 ext_from_hex("030112", &mut test); @@ -1693,11 +1858,17 @@ fn gossip_exchange_seed() -> Vec { // inbound read from peer id 0 of len 255 ext_from_hex("0300ff", &mut test); // First part of channel_announcement (type 256) - ext_from_hex("0100 00000000000000000000000000000000000000000000000000000000000000b20303030303030303030303030303030303030303030303030303030303030303 00000000000000000000000000000000000000000000000000000000000000b20202020202020202020202020202020202020202020202020202020202020202 00000000000000000000000000000000000000000000000000000000000000b20303030303030303030303030303030303030303030303030303030303030303 00000000000000000000000000000000000000000000000000000000000000b20202020202020202020202020202020202020202020202020202020202", &mut test); + ext_from_hex( + "0100 00000000000000000000000000000000000000000000000000000000000000b20303030303030303030303030303030303030303030303030303030303030303 00000000000000000000000000000000000000000000000000000000000000b20202020202020202020202020202020202020202020202020202020202020202 00000000000000000000000000000000000000000000000000000000000000b20303030303030303030303030303030303030303030303030303030303030303 00000000000000000000000000000000000000000000000000000000000000b20202020202020202020202020202020202020202020202020202020202", + &mut test, + ); // inbound read from peer id 0 of len 193 ext_from_hex("0300c1", &mut test); // Last part of channel_announcement and mac - ext_from_hex("020202 00006fe28c0ab6f1b372c1a6a246ae63f74f931e8365e15a089c68d6190000000000000000000000002a030303030303030303030303030303030303030303030303030303030303030303020202020202020202020202020202020202020202020202020202020202020202030303030303030303030303030303030303030303030303030303030303030303020202020202020202020202020202020202020202020202020202020202020202 03000000000000000000000000000000", &mut test); + ext_from_hex( + "020202 00006fe28c0ab6f1b372c1a6a246ae63f74f931e8365e15a089c68d6190000000000000000000000002a030303030303030303030303030303030303030303030303030303030303030303020202020202020202020202020202020202020202020202020202020202020202030303030303030303030303030303030303030303030303030303030303030303020202020202020202020202020202020202020202020202020202020202020202 03000000000000000000000000000000", + &mut test, + ); // inbound read from peer id 0 of len 18 ext_from_hex("030012", &mut test); @@ -1706,7 +1877,10 @@ fn gossip_exchange_seed() -> Vec { // inbound read from peer id 0 of len 154 ext_from_hex("03009a", &mut test); // channel_update (type 258) and mac - ext_from_hex("0102 00000000000000000000000000000000000000000000000000000000000000a60303030303030303030303030303030303030303030303030303030303030303 6fe28c0ab6f1b372c1a6a246ae63f74f931e8365e15a089c68d6190000000000 000000000000002a0000002c01000028000000000000000000000000000000000000000005f5e100 03000000000000000000000000000000", &mut test); + ext_from_hex( + "0102 00000000000000000000000000000000000000000000000000000000000000a60303030303030303030303030303030303030303030303030303030303030303 6fe28c0ab6f1b372c1a6a246ae63f74f931e8365e15a089c68d6190000000000 000000000000002a0000002c01000028000000000000000000000000000000000000000005f5e100 03000000000000000000000000000000", + &mut test, + ); // inbound read from peer id 0 of len 18 ext_from_hex("030012", &mut test); @@ -1715,7 +1889,10 @@ fn gossip_exchange_seed() -> Vec { // inbound read from peer id 0 of len 158 ext_from_hex("03009e", &mut test); // node_announcement (type 257) and mac - ext_from_hex("0101 00000000000000000000000000000000000000000000000000000000000000280303030303030303030303030303030303030303030303030303030303030303 00000000002b03030303030303030303030303030303030303030303030303030303030303030300000000000000000000000000000000000000000000000000000000000000000000000000 03000000000000000000000000000000", &mut test); + ext_from_hex( + "0101 00000000000000000000000000000000000000000000000000000000000000280303030303030303030303030303030303030303030303030303030303030303 00000000002b03030303030303030303030303030303030303030303030303030303030303030300000000000000000000000000000000000000000000000000000000000000000000000000 03000000000000000000000000000000", + &mut test, + ); test } @@ -1728,7 +1905,10 @@ fn splice_seed() -> Vec { // our network key ext_from_hex("0100000000000000000000000000000000000000000000000000000000000000", &mut test); // config - ext_from_hex("000000000090000000000000000064000100000000000100ffff00000000000000ffffffffffffffffff0000000000000000ffffffffffffffff000000ffffffff00ffff1a000400010000020400000000040200000a08ffffffffffffffff0001000000000000", &mut test); + ext_from_hex( + "000000000090000000000000000064000100000000000100ffff00000000000000ffffffffffffffffff0000000000000000ffffffffffffffff000000ffffffff00ffff1a000400010000020400000000040200000a08ffffffffffffffff0001000000000000", + &mut test, + ); // new outbound connection with id 0 ext_from_hex("00", &mut test); @@ -1737,7 +1917,10 @@ fn splice_seed() -> Vec { // inbound read from peer id 0 of len 50 ext_from_hex("030032", &mut test); // noise act two (0||pubkey||mac) - ext_from_hex("00 030000000000000000000000000000000000000000000000000000000000000002 03000000000000000000000000000000", &mut test); + ext_from_hex( + "00 030000000000000000000000000000000000000000000000000000000000000002 03000000000000000000000000000000", + &mut test, + ); // inbound read from peer id 0 of len 18 ext_from_hex("030012", &mut test); @@ -1750,7 +1933,10 @@ fn splice_seed() -> Vec { // Features: 20 bytes with bit 155 (splicing) and bit 35 (quiescence) set // Wire format (big-endian): 0x08 at byte 0 for bit 155, zeros for bytes 1-11, original 8 bytes at 12-19 // 20 bytes = 08 + 11 zeros + 8 original bytes = 080000000000000000000000 + aaa210aa2a0a9aaa - ext_from_hex("0010 00021aaa 0014 080000000000000000000000aaa210aa2a0a9aaa 03000000000000000000000000000000", &mut test); + ext_from_hex( + "0010 00021aaa 0014 080000000000000000000000aaa210aa2a0a9aaa 03000000000000000000000000000000", + &mut test, + ); // inbound read from peer id 0 of len 18 ext_from_hex("030012", &mut test); @@ -1759,11 +1945,17 @@ fn splice_seed() -> Vec { // inbound read from peer id 0 of len 254 ext_from_hex("0300fe", &mut test); // beginning of open_channel message - ext_from_hex("0020 6fe28c0ab6f1b372c1a6a246ae63f74f931e8365e15a089c68d6190000000000 ff4f00f805273c1b203bb5ebf8436bfde57b3be8c2f5e95d9491dbb181909679 000000000000c350 0000000000000000 0000000000000162 ffffffffffffffff 0000000000000222 0000000000000000 000000fd 0006 01e3 030000000000000000000000000000000000000000000000000000000000000001 030000000000000000000000000000000000000000000000000000000000000002 030000000000000000000000000000000000000000000000000000000000000003 030000000000000000000000000000000000000000000000000000000000000004", &mut test); + ext_from_hex( + "0020 6fe28c0ab6f1b372c1a6a246ae63f74f931e8365e15a089c68d6190000000000 ff4f00f805273c1b203bb5ebf8436bfde57b3be8c2f5e95d9491dbb181909679 000000000000c350 0000000000000000 0000000000000162 ffffffffffffffff 0000000000000222 0000000000000000 000000fd 0006 01e3 030000000000000000000000000000000000000000000000000000000000000001 030000000000000000000000000000000000000000000000000000000000000002 030000000000000000000000000000000000000000000000000000000000000003 030000000000000000000000000000000000000000000000000000000000000004", + &mut test, + ); // inbound read from peer id 0 of len 89 ext_from_hex("030059", &mut test); // rest of open_channel and mac - ext_from_hex("030000000000000000000000000000000000000000000000000000000000000005 020900000000000000000000000000000000000000000000000000000000000000 01 0000 01021000 03000000000000000000000000000000", &mut test); + ext_from_hex( + "030000000000000000000000000000000000000000000000000000000000000005 020900000000000000000000000000000000000000000000000000000000000000 01 0000 01021000 03000000000000000000000000000000", + &mut test, + ); // client should now respond with accept_channel @@ -1774,13 +1966,19 @@ fn splice_seed() -> Vec { // inbound read from peer id 0 of len 148 ext_from_hex("030094", &mut test); // funding_created and mac - ext_from_hex("0022 ff4f00f805273c1b203bb5ebf8436bfde57b3be8c2f5e95d9491dbb181909679 c000000000000000000000000000000000000000000000000000000000000000 0000 00000000000000000000000000000000000000000000000000000000000000dc0100000000000000000000000000000000000000000000000000000000000000 03000000000000000000000000000000", &mut test); + ext_from_hex( + "0022 ff4f00f805273c1b203bb5ebf8436bfde57b3be8c2f5e95d9491dbb181909679 c000000000000000000000000000000000000000000000000000000000000000 0000 00000000000000000000000000000000000000000000000000000000000000dc0100000000000000000000000000000000000000000000000000000000000000 03000000000000000000000000000000", + &mut test, + ); // client should now respond with funding_signed // connect a block with one transaction of len 94 ext_from_hex("0c005e", &mut test); // the funding transaction - ext_from_hex("020000000100000000000000000000000000000000000000000000000000000000000000000000000000ffffffff0150c3000000000000220020530000000000000000000000000000000000000000000000000000000000000000000000", &mut test); + ext_from_hex( + "020000000100000000000000000000000000000000000000000000000000000000000000000000000000ffffffff0150c3000000000000220020530000000000000000000000000000000000000000000000000000000000000000000000", + &mut test, + ); // connect blocks to confirm the funding transaction (need minimum_depth confirmations) for _ in 0..12 { ext_from_hex("0c0000", &mut test); @@ -1794,7 +1992,10 @@ fn splice_seed() -> Vec { // inbound read from peer id 0 of len 83 ext_from_hex("030053", &mut test); // channel_ready and mac - ext_from_hex("0024 c000000000000000000000000000000000000000000000000000000000000000 020800000000000000000000000000000000000000000000000000000000000000 03000000000000000000000000000000", &mut test); + ext_from_hex( + "0024 c000000000000000000000000000000000000000000000000000000000000000 020800000000000000000000000000000000000000000000000000000000000000 03000000000000000000000000000000", + &mut test, + ); // Channel is now established and ready for splicing! @@ -1813,7 +2014,10 @@ fn splice_seed() -> Vec { ext_from_hex("030033", &mut test); // stfu message (type 2): channel_id (32 bytes) + initiator (1 byte) + mac // channel_id = c000...0000, initiator = 0 (peer is not initiator, responding to our stfu) - ext_from_hex("0002 c000000000000000000000000000000000000000000000000000000000000000 00 03000000000000000000000000000000", &mut test); + ext_from_hex( + "0002 c000000000000000000000000000000000000000000000000000000000000000 00 03000000000000000000000000000000", + &mut test, + ); // After receiving peer's stfu, we send SpliceInit. Peer responds with SpliceAck. // Message type IDs: SpliceAck = 81 (0x0051) @@ -1825,7 +2029,10 @@ fn splice_seed() -> Vec { ext_from_hex("03005b", &mut test); // SpliceAck message (type 81 = 0x0051): channel_id + funding_contribution + funding_pubkey + mac // channel_id = c000...0000, funding_contribution = 0 (i64), funding_pubkey = valid 33-byte compressed pubkey - ext_from_hex("0051 c000000000000000000000000000000000000000000000000000000000000000 0000000000000000 030000000000000000000000000000000000000000000000000000000000000001 03000000000000000000000000000000", &mut test); + ext_from_hex( + "0051 c000000000000000000000000000000000000000000000000000000000000000 0000000000000000 030000000000000000000000000000000000000000000000000000000000000001 03000000000000000000000000000000", + &mut test, + ); // Now we're in interactive tx negotiation. We send TxAddInput for our new funding input. // Peer responds with TxComplete (they have no inputs/outputs to add). @@ -1837,7 +2044,10 @@ fn splice_seed() -> Vec { // inbound read from peer id 0 of len 50 (34 message + 16 MAC) ext_from_hex("030032", &mut test); // TxComplete message (type 70 = 0x0046): channel_id + mac - ext_from_hex("0046 c000000000000000000000000000000000000000000000000000000000000000 03000000000000000000000000000000", &mut test); + ext_from_hex( + "0046 c000000000000000000000000000000000000000000000000000000000000000 03000000000000000000000000000000", + &mut test, + ); // After peer's first TxComplete, we send another TxAddInput (for the shared input - existing funding). // We also send TxAddOutput for the new funding output. @@ -1849,7 +2059,10 @@ fn splice_seed() -> Vec { // inbound read from peer id 0 of len 50 (34 message + 16 MAC) ext_from_hex("030032", &mut test); // TxComplete message - ext_from_hex("0046 c000000000000000000000000000000000000000000000000000000000000000 03000000000000000000000000000000", &mut test); + ext_from_hex( + "0046 c000000000000000000000000000000000000000000000000000000000000000 03000000000000000000000000000000", + &mut test, + ); // We continue sending our inputs/outputs, peer continues with TxComplete. // inbound read from peer id 0 of len 18 @@ -1859,7 +2072,10 @@ fn splice_seed() -> Vec { // inbound read from peer id 0 of len 50 (34 message + 16 MAC) ext_from_hex("030032", &mut test); // TxComplete message - ext_from_hex("0046 c000000000000000000000000000000000000000000000000000000000000000 03000000000000000000000000000000", &mut test); + ext_from_hex( + "0046 c000000000000000000000000000000000000000000000000000000000000000 03000000000000000000000000000000", + &mut test, + ); // More TxComplete responses as we add our outputs // inbound read from peer id 0 of len 18 @@ -1869,7 +2085,10 @@ fn splice_seed() -> Vec { // inbound read from peer id 0 of len 50 (34 message + 16 MAC) ext_from_hex("030032", &mut test); // TxComplete message - ext_from_hex("0046 c000000000000000000000000000000000000000000000000000000000000000 03000000000000000000000000000000", &mut test); + ext_from_hex( + "0046 c000000000000000000000000000000000000000000000000000000000000000 03000000000000000000000000000000", + &mut test, + ); // After we send our TxComplete, the interactive tx negotiation completes. // Both sides now need to exchange commitment_signed messages. @@ -1887,7 +2106,10 @@ fn splice_seed() -> Vec { // signature r encodes sighash first byte f7, s follows the pattern from funding_created // TLV type 1 (odd/optional) for funding_txid as per impl_writeable_msg!(CommitmentSigned, ...) // Note: txid is encoded in reverse byte order (Bitcoin standard), so to get display 0000...0031, encode 3100...0000 - ext_from_hex("0084 c000000000000000000000000000000000000000000000000000000000000000 00000000000000000000000000000000000000000000000000000000000000f7 0100000000000000000000000000000000000000000000000000000000000000 0000 01 20 3100000000000000000000000000000000000000000000000000000000000000 03000000000000000000000000000000", &mut test); + ext_from_hex( + "0084 c000000000000000000000000000000000000000000000000000000000000000 00000000000000000000000000000000000000000000000000000000000000f7 0100000000000000000000000000000000000000000000000000000000000000 0000 01 20 3100000000000000000000000000000000000000000000000000000000000000 03000000000000000000000000000000", + &mut test, + ); // After commitment_signed exchange, we need to exchange tx_signatures. // Message type IDs: TxSignatures = 71 (0x0047) @@ -1902,7 +2124,10 @@ fn splice_seed() -> Vec { // TxSignatures message with shared_input_signature TLV (type 0) // txid must match the splice funding txid (0x31 in reverse byte order) // shared_input_signature: 64-byte fuzz signature for the shared input - ext_from_hex("0047 c000000000000000000000000000000000000000000000000000000000000000 3100000000000000000000000000000000000000000000000000000000000000 0000 00 40 00000000000000000000000000000000000000000000000000000000000000dc 0100000000000000000000000000000000000000000000000000000000000000 03000000000000000000000000000000", &mut test); + ext_from_hex( + "0047 c000000000000000000000000000000000000000000000000000000000000000 3100000000000000000000000000000000000000000000000000000000000000 0000 00 40 00000000000000000000000000000000000000000000000000000000000000dc 0100000000000000000000000000000000000000000000000000000000000000 03000000000000000000000000000000", + &mut test, + ); // Connect a block with the splice funding transaction to confirm it // The splice funding tx: version(4) + input_count(1) + txid(32) + vout(4) + script_len(1) + sequence(4) @@ -1912,7 +2137,10 @@ fn splice_seed() -> Vec { // - Output: 115538 sats to OP_0 PUSH32 6e00...00 // - Locktime: 13 ext_from_hex("0c005e", &mut test); - ext_from_hex("02000000 01 c000000000000000000000000000000000000000000000000000000000000000 00000000 00 fdffffff 01 52c3010000000000 22 00206e00000000000000000000000000000000000000000000000000000000000000 0d000000", &mut test); + ext_from_hex( + "02000000 01 c000000000000000000000000000000000000000000000000000000000000000 00000000 00 fdffffff 01 52c3010000000000 22 00206e00000000000000000000000000000000000000000000000000000000000000 0d000000", + &mut test, + ); // Connect additional blocks to reach minimum_depth confirmations for _ in 0..5 { @@ -1930,7 +2158,10 @@ fn splice_seed() -> Vec { ext_from_hex("030052", &mut test); // SpliceLocked message (type 77 = 0x004d): channel_id + splice_txid + mac // splice_txid must match the splice funding txid (0x31 in reverse byte order) - ext_from_hex("004d c000000000000000000000000000000000000000000000000000000000000000 3100000000000000000000000000000000000000000000000000000000000000 03000000000000000000000000000000", &mut test); + ext_from_hex( + "004d c000000000000000000000000000000000000000000000000000000000000000 3100000000000000000000000000000000000000000000000000000000000000 03000000000000000000000000000000", + &mut test, + ); test } diff --git a/fuzz/src/gossip_discovery.rs b/fuzz/src/gossip_discovery.rs index 8eee8dc482b..a094703336a 100644 --- a/fuzz/src/gossip_discovery.rs +++ b/fuzz/src/gossip_discovery.rs @@ -13,11 +13,11 @@ //! announcements, channel updates, query messages, and pruning channels and nodes. Both valid //! and malformed messages are generated to exercise error paths. +use bitcoin::TxOut; use bitcoin::amount::Amount; use bitcoin::constants::ChainHash; use bitcoin::network::Network; use bitcoin::secp256k1::PublicKey; -use bitcoin::TxOut; use lightning::ln::chan_utils::make_funding_redeemscript; use lightning::ln::msgs::{self, BaseMessageHandler, MessageSendEvent, RoutingMessageHandler}; @@ -240,10 +240,9 @@ fn do_test(data: &[u8], out: Out) { is_permanent: true, }); - assert!(network_graph - .read_only() - .node(&NodeId::from_pubkey(&peer_node_id)) - .is_none()); + assert!( + network_graph.read_only().node(&NodeId::from_pubkey(&peer_node_id)).is_none() + ); }, // Remove stale channels and tracking. 6 => { @@ -259,7 +258,7 @@ pub fn gossip_discovery_test(data: &[u8], out: Out) { do_test(data, out); } -#[no_mangle] +#[unsafe(no_mangle)] pub extern "C" fn gossip_discovery_run(data: *const u8, datalen: usize) { do_test(unsafe { std::slice::from_raw_parts(data, datalen) }, test_logger::DevNull {}); } diff --git a/fuzz/src/indexedmap.rs b/fuzz/src/indexedmap.rs index ee21f04619f..c5766bbee65 100644 --- a/fuzz/src/indexedmap.rs +++ b/fuzz/src/indexedmap.rs @@ -9,7 +9,7 @@ use lightning::util::hash_tables::*; use lightning::util::indexed_map::{self, IndexedMap}; -use std::collections::{btree_map, BTreeMap}; +use std::collections::{BTreeMap, btree_map}; use crate::utils::test_logger; @@ -177,7 +177,7 @@ pub fn indexedmap_test(data: &[u8], _out: Out) { do_test(data); } -#[no_mangle] +#[unsafe(no_mangle)] pub extern "C" fn indexedmap_run(data: *const u8, datalen: usize) { do_test(unsafe { std::slice::from_raw_parts(data, datalen) }); } diff --git a/fuzz/src/invoice_deser.rs b/fuzz/src/invoice_deser.rs index 34bb955e2a7..0ba75fd507a 100644 --- a/fuzz/src/invoice_deser.rs +++ b/fuzz/src/invoice_deser.rs @@ -25,7 +25,7 @@ pub fn invoice_deser_test(data: &[u8], out: Out) { do_test(data, out); } -#[no_mangle] +#[unsafe(no_mangle)] pub extern "C" fn invoice_deser_run(data: *const u8, datalen: usize) { do_test(unsafe { std::slice::from_raw_parts(data, datalen) }, test_logger::DevNull {}); } diff --git a/fuzz/src/invoice_request_deser.rs b/fuzz/src/invoice_request_deser.rs index a21303debd7..7ef0edfe7ef 100644 --- a/fuzz/src/invoice_request_deser.rs +++ b/fuzz/src/invoice_request_deser.rs @@ -151,7 +151,7 @@ pub fn invoice_request_deser_test(data: &[u8], out: Ou do_test(data, out); } -#[no_mangle] +#[unsafe(no_mangle)] pub extern "C" fn invoice_request_deser_run(data: *const u8, datalen: usize) { do_test(unsafe { std::slice::from_raw_parts(data, datalen) }, test_logger::DevNull {}); } diff --git a/fuzz/src/lsps_message.rs b/fuzz/src/lsps_message.rs index 83fa5ddab6d..7d7ba7b7356 100644 --- a/fuzz/src/lsps_message.rs +++ b/fuzz/src/lsps_message.rs @@ -1,12 +1,12 @@ use crate::utils::test_logger; +use bitcoin::Network; use bitcoin::blockdata::constants::genesis_block; -use bitcoin::hashes::{sha256, Hash}; +use bitcoin::hashes::{Hash, sha256}; use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey}; -use bitcoin::Network; use lightning::chain::Filter; -use lightning::chain::{chainmonitor, BlockLocator}; +use lightning::chain::{BlockLocator, chainmonitor}; use lightning::ln::channelmanager::{ChainParameters, ChannelManager}; use lightning::ln::peer_handler::CustomMessageHandler; use lightning::ln::wire::CustomMessageReader; @@ -20,8 +20,8 @@ use lightning::util::test_utils::{ TestBroadcaster, TestChainSource, TestFeeEstimator, TestLogger, TestScorer, TestStore, }; -use lightning_liquidity::lsps0::ser::LSPS_MESSAGE_TYPE_ID; use lightning_liquidity::LiquidityManagerSync; +use lightning_liquidity::lsps0::ser::LSPS_MESSAGE_TYPE_ID; use core::time::Duration; @@ -103,7 +103,7 @@ pub fn lsps_message_test(data: &[u8], _out: Out) { do_test(data); } -#[no_mangle] +#[unsafe(no_mangle)] pub extern "C" fn lsps_message_run(data: *const u8, datalen: usize) { do_test(unsafe { core::slice::from_raw_parts(data, datalen) }); } diff --git a/fuzz/src/msg_targets/msg_accept_channel.rs b/fuzz/src/msg_targets/msg_accept_channel.rs index 216fe7c59bd..b10cc503e9c 100644 --- a/fuzz/src/msg_targets/msg_accept_channel.rs +++ b/fuzz/src/msg_targets/msg_accept_channel.rs @@ -20,7 +20,7 @@ pub fn msg_accept_channel_test(data: &[u8], _out: Out) test_msg_simple!(lightning::ln::msgs::AcceptChannel, data); } -#[no_mangle] +#[unsafe(no_mangle)] pub extern "C" fn msg_accept_channel_run(data: *const u8, datalen: usize) { let data = unsafe { std::slice::from_raw_parts(data, datalen) }; test_msg_simple!(lightning::ln::msgs::AcceptChannel, data); diff --git a/fuzz/src/msg_targets/msg_accept_channel_v2.rs b/fuzz/src/msg_targets/msg_accept_channel_v2.rs index c1d7fb55c9b..917e3c4073d 100644 --- a/fuzz/src/msg_targets/msg_accept_channel_v2.rs +++ b/fuzz/src/msg_targets/msg_accept_channel_v2.rs @@ -20,7 +20,7 @@ pub fn msg_accept_channel_v2_test(data: &[u8], _out: O test_msg_simple!(lightning::ln::msgs::AcceptChannelV2, data); } -#[no_mangle] +#[unsafe(no_mangle)] pub extern "C" fn msg_accept_channel_v2_run(data: *const u8, datalen: usize) { let data = unsafe { std::slice::from_raw_parts(data, datalen) }; test_msg_simple!(lightning::ln::msgs::AcceptChannelV2, data); diff --git a/fuzz/src/msg_targets/msg_announcement_signatures.rs b/fuzz/src/msg_targets/msg_announcement_signatures.rs index 6010e6001b6..1d46c78749e 100644 --- a/fuzz/src/msg_targets/msg_announcement_signatures.rs +++ b/fuzz/src/msg_targets/msg_announcement_signatures.rs @@ -20,7 +20,7 @@ pub fn msg_announcement_signatures_test(data: &[u8], _ test_msg_simple!(lightning::ln::msgs::AnnouncementSignatures, data); } -#[no_mangle] +#[unsafe(no_mangle)] pub extern "C" fn msg_announcement_signatures_run(data: *const u8, datalen: usize) { let data = unsafe { std::slice::from_raw_parts(data, datalen) }; test_msg_simple!(lightning::ln::msgs::AnnouncementSignatures, data); diff --git a/fuzz/src/msg_targets/msg_blinded_message_path.rs b/fuzz/src/msg_targets/msg_blinded_message_path.rs index 901ab206c9c..eb47b4d31b7 100644 --- a/fuzz/src/msg_targets/msg_blinded_message_path.rs +++ b/fuzz/src/msg_targets/msg_blinded_message_path.rs @@ -20,7 +20,7 @@ pub fn msg_blinded_message_path_test(data: &[u8], _out test_msg_simple!(lightning::blinded_path::message::BlindedMessagePath, data); } -#[no_mangle] +#[unsafe(no_mangle)] pub extern "C" fn msg_blinded_message_path_run(data: *const u8, datalen: usize) { let data = unsafe { std::slice::from_raw_parts(data, datalen) }; test_msg_simple!(lightning::blinded_path::message::BlindedMessagePath, data); diff --git a/fuzz/src/msg_targets/msg_channel_announcement.rs b/fuzz/src/msg_targets/msg_channel_announcement.rs index d4084c61893..4abcc66ccd4 100644 --- a/fuzz/src/msg_targets/msg_channel_announcement.rs +++ b/fuzz/src/msg_targets/msg_channel_announcement.rs @@ -20,7 +20,7 @@ pub fn msg_channel_announcement_test(data: &[u8], _out test_msg_exact!(lightning::ln::msgs::ChannelAnnouncement, data); } -#[no_mangle] +#[unsafe(no_mangle)] pub extern "C" fn msg_channel_announcement_run(data: *const u8, datalen: usize) { let data = unsafe { std::slice::from_raw_parts(data, datalen) }; test_msg_exact!(lightning::ln::msgs::ChannelAnnouncement, data); diff --git a/fuzz/src/msg_targets/msg_channel_details.rs b/fuzz/src/msg_targets/msg_channel_details.rs index eb9f8beee47..a874a354638 100644 --- a/fuzz/src/msg_targets/msg_channel_details.rs +++ b/fuzz/src/msg_targets/msg_channel_details.rs @@ -20,7 +20,7 @@ pub fn msg_channel_details_test(data: &[u8], _out: Out test_msg_simple!(lightning::ln::channel_state::ChannelDetails, data); } -#[no_mangle] +#[unsafe(no_mangle)] pub extern "C" fn msg_channel_details_run(data: *const u8, datalen: usize) { let data = unsafe { std::slice::from_raw_parts(data, datalen) }; test_msg_simple!(lightning::ln::channel_state::ChannelDetails, data); diff --git a/fuzz/src/msg_targets/msg_channel_ready.rs b/fuzz/src/msg_targets/msg_channel_ready.rs index 3180928905d..669d29261bb 100644 --- a/fuzz/src/msg_targets/msg_channel_ready.rs +++ b/fuzz/src/msg_targets/msg_channel_ready.rs @@ -20,7 +20,7 @@ pub fn msg_channel_ready_test(data: &[u8], _out: Out) test_msg_simple!(lightning::ln::msgs::ChannelReady, data); } -#[no_mangle] +#[unsafe(no_mangle)] pub extern "C" fn msg_channel_ready_run(data: *const u8, datalen: usize) { let data = unsafe { std::slice::from_raw_parts(data, datalen) }; test_msg_simple!(lightning::ln::msgs::ChannelReady, data); diff --git a/fuzz/src/msg_targets/msg_channel_reestablish.rs b/fuzz/src/msg_targets/msg_channel_reestablish.rs index f766892a2e2..a10e016512a 100644 --- a/fuzz/src/msg_targets/msg_channel_reestablish.rs +++ b/fuzz/src/msg_targets/msg_channel_reestablish.rs @@ -20,7 +20,7 @@ pub fn msg_channel_reestablish_test(data: &[u8], _out: test_msg_simple!(lightning::ln::msgs::ChannelReestablish, data); } -#[no_mangle] +#[unsafe(no_mangle)] pub extern "C" fn msg_channel_reestablish_run(data: *const u8, datalen: usize) { let data = unsafe { std::slice::from_raw_parts(data, datalen) }; test_msg_simple!(lightning::ln::msgs::ChannelReestablish, data); diff --git a/fuzz/src/msg_targets/msg_channel_update.rs b/fuzz/src/msg_targets/msg_channel_update.rs index 4dc8c140345..edc1a2d6011 100644 --- a/fuzz/src/msg_targets/msg_channel_update.rs +++ b/fuzz/src/msg_targets/msg_channel_update.rs @@ -20,7 +20,7 @@ pub fn msg_channel_update_test(data: &[u8], _out: Out) test_msg_exact!(lightning::ln::msgs::ChannelUpdate, data); } -#[no_mangle] +#[unsafe(no_mangle)] pub extern "C" fn msg_channel_update_run(data: *const u8, datalen: usize) { let data = unsafe { std::slice::from_raw_parts(data, datalen) }; test_msg_exact!(lightning::ln::msgs::ChannelUpdate, data); diff --git a/fuzz/src/msg_targets/msg_closing_complete.rs b/fuzz/src/msg_targets/msg_closing_complete.rs index 922a3f3c67d..07a3280bf58 100644 --- a/fuzz/src/msg_targets/msg_closing_complete.rs +++ b/fuzz/src/msg_targets/msg_closing_complete.rs @@ -20,7 +20,7 @@ pub fn msg_closing_complete_test(data: &[u8], _out: Ou test_msg_simple!(lightning::ln::msgs::ClosingComplete, data); } -#[no_mangle] +#[unsafe(no_mangle)] pub extern "C" fn msg_closing_complete_run(data: *const u8, datalen: usize) { let data = unsafe { std::slice::from_raw_parts(data, datalen) }; test_msg_simple!(lightning::ln::msgs::ClosingComplete, data); diff --git a/fuzz/src/msg_targets/msg_closing_sig.rs b/fuzz/src/msg_targets/msg_closing_sig.rs index d1854a784bf..7eca16b908f 100644 --- a/fuzz/src/msg_targets/msg_closing_sig.rs +++ b/fuzz/src/msg_targets/msg_closing_sig.rs @@ -20,7 +20,7 @@ pub fn msg_closing_sig_test(data: &[u8], _out: Out) { test_msg_simple!(lightning::ln::msgs::ClosingSig, data); } -#[no_mangle] +#[unsafe(no_mangle)] pub extern "C" fn msg_closing_sig_run(data: *const u8, datalen: usize) { let data = unsafe { std::slice::from_raw_parts(data, datalen) }; test_msg_simple!(lightning::ln::msgs::ClosingSig, data); diff --git a/fuzz/src/msg_targets/msg_closing_signed.rs b/fuzz/src/msg_targets/msg_closing_signed.rs index 74e04d6675a..682599141d1 100644 --- a/fuzz/src/msg_targets/msg_closing_signed.rs +++ b/fuzz/src/msg_targets/msg_closing_signed.rs @@ -20,7 +20,7 @@ pub fn msg_closing_signed_test(data: &[u8], _out: Out) test_msg_simple!(lightning::ln::msgs::ClosingSigned, data); } -#[no_mangle] +#[unsafe(no_mangle)] pub extern "C" fn msg_closing_signed_run(data: *const u8, datalen: usize) { let data = unsafe { std::slice::from_raw_parts(data, datalen) }; test_msg_simple!(lightning::ln::msgs::ClosingSigned, data); diff --git a/fuzz/src/msg_targets/msg_commitment_signed.rs b/fuzz/src/msg_targets/msg_commitment_signed.rs index 7ece314353d..076353be2f5 100644 --- a/fuzz/src/msg_targets/msg_commitment_signed.rs +++ b/fuzz/src/msg_targets/msg_commitment_signed.rs @@ -20,7 +20,7 @@ pub fn msg_commitment_signed_test(data: &[u8], _out: O test_msg_simple!(lightning::ln::msgs::CommitmentSigned, data); } -#[no_mangle] +#[unsafe(no_mangle)] pub extern "C" fn msg_commitment_signed_run(data: *const u8, datalen: usize) { let data = unsafe { std::slice::from_raw_parts(data, datalen) }; test_msg_simple!(lightning::ln::msgs::CommitmentSigned, data); diff --git a/fuzz/src/msg_targets/msg_decoded_onion_error_packet.rs b/fuzz/src/msg_targets/msg_decoded_onion_error_packet.rs index 9d245e2f2d2..068b3d12d00 100644 --- a/fuzz/src/msg_targets/msg_decoded_onion_error_packet.rs +++ b/fuzz/src/msg_targets/msg_decoded_onion_error_packet.rs @@ -20,7 +20,7 @@ pub fn msg_decoded_onion_error_packet_test(data: &[u8] test_msg!(lightning::ln::msgs::DecodedOnionErrorPacket, data); } -#[no_mangle] +#[unsafe(no_mangle)] pub extern "C" fn msg_decoded_onion_error_packet_run(data: *const u8, datalen: usize) { let data = unsafe { std::slice::from_raw_parts(data, datalen) }; test_msg!(lightning::ln::msgs::DecodedOnionErrorPacket, data); diff --git a/fuzz/src/msg_targets/msg_error_message.rs b/fuzz/src/msg_targets/msg_error_message.rs index ae16e1686dc..209fd930673 100644 --- a/fuzz/src/msg_targets/msg_error_message.rs +++ b/fuzz/src/msg_targets/msg_error_message.rs @@ -20,7 +20,7 @@ pub fn msg_error_message_test(data: &[u8], _out: Out) test_msg_hole!(lightning::ln::msgs::ErrorMessage, data, 32, 2); } -#[no_mangle] +#[unsafe(no_mangle)] pub extern "C" fn msg_error_message_run(data: *const u8, datalen: usize) { let data = unsafe { std::slice::from_raw_parts(data, datalen) }; test_msg_hole!(lightning::ln::msgs::ErrorMessage, data, 32, 2); diff --git a/fuzz/src/msg_targets/msg_funding_created.rs b/fuzz/src/msg_targets/msg_funding_created.rs index a6c5ba148c2..f3a87da32d3 100644 --- a/fuzz/src/msg_targets/msg_funding_created.rs +++ b/fuzz/src/msg_targets/msg_funding_created.rs @@ -20,7 +20,7 @@ pub fn msg_funding_created_test(data: &[u8], _out: Out test_msg_simple!(lightning::ln::msgs::FundingCreated, data); } -#[no_mangle] +#[unsafe(no_mangle)] pub extern "C" fn msg_funding_created_run(data: *const u8, datalen: usize) { let data = unsafe { std::slice::from_raw_parts(data, datalen) }; test_msg_simple!(lightning::ln::msgs::FundingCreated, data); diff --git a/fuzz/src/msg_targets/msg_funding_signed.rs b/fuzz/src/msg_targets/msg_funding_signed.rs index 34f0fddaad3..b6b7e280d5f 100644 --- a/fuzz/src/msg_targets/msg_funding_signed.rs +++ b/fuzz/src/msg_targets/msg_funding_signed.rs @@ -20,7 +20,7 @@ pub fn msg_funding_signed_test(data: &[u8], _out: Out) test_msg_simple!(lightning::ln::msgs::FundingSigned, data); } -#[no_mangle] +#[unsafe(no_mangle)] pub extern "C" fn msg_funding_signed_run(data: *const u8, datalen: usize) { let data = unsafe { std::slice::from_raw_parts(data, datalen) }; test_msg_simple!(lightning::ln::msgs::FundingSigned, data); diff --git a/fuzz/src/msg_targets/msg_gossip_timestamp_filter.rs b/fuzz/src/msg_targets/msg_gossip_timestamp_filter.rs index 8e0fb7c5380..c3ab44cbf79 100644 --- a/fuzz/src/msg_targets/msg_gossip_timestamp_filter.rs +++ b/fuzz/src/msg_targets/msg_gossip_timestamp_filter.rs @@ -20,7 +20,7 @@ pub fn msg_gossip_timestamp_filter_test(data: &[u8], _ test_msg_simple!(lightning::ln::msgs::GossipTimestampFilter, data); } -#[no_mangle] +#[unsafe(no_mangle)] pub extern "C" fn msg_gossip_timestamp_filter_run(data: *const u8, datalen: usize) { let data = unsafe { std::slice::from_raw_parts(data, datalen) }; test_msg_simple!(lightning::ln::msgs::GossipTimestampFilter, data); diff --git a/fuzz/src/msg_targets/msg_init.rs b/fuzz/src/msg_targets/msg_init.rs index 5f11441ddf5..c7bf13b436f 100644 --- a/fuzz/src/msg_targets/msg_init.rs +++ b/fuzz/src/msg_targets/msg_init.rs @@ -20,7 +20,7 @@ pub fn msg_init_test(data: &[u8], _out: Out) { test_msg_simple!(lightning::ln::msgs::Init, data); } -#[no_mangle] +#[unsafe(no_mangle)] pub extern "C" fn msg_init_run(data: *const u8, datalen: usize) { let data = unsafe { std::slice::from_raw_parts(data, datalen) }; test_msg_simple!(lightning::ln::msgs::Init, data); diff --git a/fuzz/src/msg_targets/msg_node_announcement.rs b/fuzz/src/msg_targets/msg_node_announcement.rs index ce9bb30d3dd..1d88562ad52 100644 --- a/fuzz/src/msg_targets/msg_node_announcement.rs +++ b/fuzz/src/msg_targets/msg_node_announcement.rs @@ -20,7 +20,7 @@ pub fn msg_node_announcement_test(data: &[u8], _out: O test_msg_exact!(lightning::ln::msgs::NodeAnnouncement, data); } -#[no_mangle] +#[unsafe(no_mangle)] pub extern "C" fn msg_node_announcement_run(data: *const u8, datalen: usize) { let data = unsafe { std::slice::from_raw_parts(data, datalen) }; test_msg_exact!(lightning::ln::msgs::NodeAnnouncement, data); diff --git a/fuzz/src/msg_targets/msg_open_channel.rs b/fuzz/src/msg_targets/msg_open_channel.rs index 9c924e501db..ea33adcd9e1 100644 --- a/fuzz/src/msg_targets/msg_open_channel.rs +++ b/fuzz/src/msg_targets/msg_open_channel.rs @@ -20,7 +20,7 @@ pub fn msg_open_channel_test(data: &[u8], _out: Out) { test_msg_simple!(lightning::ln::msgs::OpenChannel, data); } -#[no_mangle] +#[unsafe(no_mangle)] pub extern "C" fn msg_open_channel_run(data: *const u8, datalen: usize) { let data = unsafe { std::slice::from_raw_parts(data, datalen) }; test_msg_simple!(lightning::ln::msgs::OpenChannel, data); diff --git a/fuzz/src/msg_targets/msg_open_channel_v2.rs b/fuzz/src/msg_targets/msg_open_channel_v2.rs index a43d58ee9e6..75f1e235244 100644 --- a/fuzz/src/msg_targets/msg_open_channel_v2.rs +++ b/fuzz/src/msg_targets/msg_open_channel_v2.rs @@ -20,7 +20,7 @@ pub fn msg_open_channel_v2_test(data: &[u8], _out: Out test_msg_simple!(lightning::ln::msgs::OpenChannelV2, data); } -#[no_mangle] +#[unsafe(no_mangle)] pub extern "C" fn msg_open_channel_v2_run(data: *const u8, datalen: usize) { let data = unsafe { std::slice::from_raw_parts(data, datalen) }; test_msg_simple!(lightning::ln::msgs::OpenChannelV2, data); diff --git a/fuzz/src/msg_targets/msg_ping.rs b/fuzz/src/msg_targets/msg_ping.rs index 2ff54816474..7d94107239f 100644 --- a/fuzz/src/msg_targets/msg_ping.rs +++ b/fuzz/src/msg_targets/msg_ping.rs @@ -20,7 +20,7 @@ pub fn msg_ping_test(data: &[u8], _out: Out) { test_msg_simple!(lightning::ln::msgs::Ping, data); } -#[no_mangle] +#[unsafe(no_mangle)] pub extern "C" fn msg_ping_run(data: *const u8, datalen: usize) { let data = unsafe { std::slice::from_raw_parts(data, datalen) }; test_msg_simple!(lightning::ln::msgs::Ping, data); diff --git a/fuzz/src/msg_targets/msg_pong.rs b/fuzz/src/msg_targets/msg_pong.rs index 52b9ee08486..d8af6312b05 100644 --- a/fuzz/src/msg_targets/msg_pong.rs +++ b/fuzz/src/msg_targets/msg_pong.rs @@ -20,7 +20,7 @@ pub fn msg_pong_test(data: &[u8], _out: Out) { test_msg_simple!(lightning::ln::msgs::Pong, data); } -#[no_mangle] +#[unsafe(no_mangle)] pub extern "C" fn msg_pong_run(data: *const u8, datalen: usize) { let data = unsafe { std::slice::from_raw_parts(data, datalen) }; test_msg_simple!(lightning::ln::msgs::Pong, data); diff --git a/fuzz/src/msg_targets/msg_query_channel_range.rs b/fuzz/src/msg_targets/msg_query_channel_range.rs index 6b59636780b..198743eca2b 100644 --- a/fuzz/src/msg_targets/msg_query_channel_range.rs +++ b/fuzz/src/msg_targets/msg_query_channel_range.rs @@ -20,7 +20,7 @@ pub fn msg_query_channel_range_test(data: &[u8], _out: test_msg_simple!(lightning::ln::msgs::QueryChannelRange, data); } -#[no_mangle] +#[unsafe(no_mangle)] pub extern "C" fn msg_query_channel_range_run(data: *const u8, datalen: usize) { let data = unsafe { std::slice::from_raw_parts(data, datalen) }; test_msg_simple!(lightning::ln::msgs::QueryChannelRange, data); diff --git a/fuzz/src/msg_targets/msg_query_short_channel_ids.rs b/fuzz/src/msg_targets/msg_query_short_channel_ids.rs index c15915fd1a8..b6da2aad38e 100644 --- a/fuzz/src/msg_targets/msg_query_short_channel_ids.rs +++ b/fuzz/src/msg_targets/msg_query_short_channel_ids.rs @@ -20,7 +20,7 @@ pub fn msg_query_short_channel_ids_test(data: &[u8], _ test_msg!(lightning::ln::msgs::QueryShortChannelIds, data); } -#[no_mangle] +#[unsafe(no_mangle)] pub extern "C" fn msg_query_short_channel_ids_run(data: *const u8, datalen: usize) { let data = unsafe { std::slice::from_raw_parts(data, datalen) }; test_msg!(lightning::ln::msgs::QueryShortChannelIds, data); diff --git a/fuzz/src/msg_targets/msg_reply_channel_range.rs b/fuzz/src/msg_targets/msg_reply_channel_range.rs index 3cb94af6c23..d145ec6cbf5 100644 --- a/fuzz/src/msg_targets/msg_reply_channel_range.rs +++ b/fuzz/src/msg_targets/msg_reply_channel_range.rs @@ -20,7 +20,7 @@ pub fn msg_reply_channel_range_test(data: &[u8], _out: test_msg!(lightning::ln::msgs::ReplyChannelRange, data); } -#[no_mangle] +#[unsafe(no_mangle)] pub extern "C" fn msg_reply_channel_range_run(data: *const u8, datalen: usize) { let data = unsafe { std::slice::from_raw_parts(data, datalen) }; test_msg!(lightning::ln::msgs::ReplyChannelRange, data); diff --git a/fuzz/src/msg_targets/msg_reply_short_channel_ids_end.rs b/fuzz/src/msg_targets/msg_reply_short_channel_ids_end.rs index a53459997f9..9af58c8b571 100644 --- a/fuzz/src/msg_targets/msg_reply_short_channel_ids_end.rs +++ b/fuzz/src/msg_targets/msg_reply_short_channel_ids_end.rs @@ -20,7 +20,7 @@ pub fn msg_reply_short_channel_ids_end_test(data: &[u8 test_msg_simple!(lightning::ln::msgs::ReplyShortChannelIdsEnd, data); } -#[no_mangle] +#[unsafe(no_mangle)] pub extern "C" fn msg_reply_short_channel_ids_end_run(data: *const u8, datalen: usize) { let data = unsafe { std::slice::from_raw_parts(data, datalen) }; test_msg_simple!(lightning::ln::msgs::ReplyShortChannelIdsEnd, data); diff --git a/fuzz/src/msg_targets/msg_revoke_and_ack.rs b/fuzz/src/msg_targets/msg_revoke_and_ack.rs index 26f2d7524cd..ad90409cfee 100644 --- a/fuzz/src/msg_targets/msg_revoke_and_ack.rs +++ b/fuzz/src/msg_targets/msg_revoke_and_ack.rs @@ -20,7 +20,7 @@ pub fn msg_revoke_and_ack_test(data: &[u8], _out: Out) test_msg_simple!(lightning::ln::msgs::RevokeAndACK, data); } -#[no_mangle] +#[unsafe(no_mangle)] pub extern "C" fn msg_revoke_and_ack_run(data: *const u8, datalen: usize) { let data = unsafe { std::slice::from_raw_parts(data, datalen) }; test_msg_simple!(lightning::ln::msgs::RevokeAndACK, data); diff --git a/fuzz/src/msg_targets/msg_shutdown.rs b/fuzz/src/msg_targets/msg_shutdown.rs index 77c4cfdaae3..68ad2972956 100644 --- a/fuzz/src/msg_targets/msg_shutdown.rs +++ b/fuzz/src/msg_targets/msg_shutdown.rs @@ -20,7 +20,7 @@ pub fn msg_shutdown_test(data: &[u8], _out: Out) { test_msg_simple!(lightning::ln::msgs::Shutdown, data); } -#[no_mangle] +#[unsafe(no_mangle)] pub extern "C" fn msg_shutdown_run(data: *const u8, datalen: usize) { let data = unsafe { std::slice::from_raw_parts(data, datalen) }; test_msg_simple!(lightning::ln::msgs::Shutdown, data); diff --git a/fuzz/src/msg_targets/msg_splice_ack.rs b/fuzz/src/msg_targets/msg_splice_ack.rs index 65949d273da..578b097d125 100644 --- a/fuzz/src/msg_targets/msg_splice_ack.rs +++ b/fuzz/src/msg_targets/msg_splice_ack.rs @@ -20,7 +20,7 @@ pub fn msg_splice_ack_test(data: &[u8], _out: Out) { test_msg_simple!(lightning::ln::msgs::SpliceAck, data); } -#[no_mangle] +#[unsafe(no_mangle)] pub extern "C" fn msg_splice_ack_run(data: *const u8, datalen: usize) { let data = unsafe { std::slice::from_raw_parts(data, datalen) }; test_msg_simple!(lightning::ln::msgs::SpliceAck, data); diff --git a/fuzz/src/msg_targets/msg_splice_init.rs b/fuzz/src/msg_targets/msg_splice_init.rs index d2e3829171e..4a1958187f5 100644 --- a/fuzz/src/msg_targets/msg_splice_init.rs +++ b/fuzz/src/msg_targets/msg_splice_init.rs @@ -20,7 +20,7 @@ pub fn msg_splice_init_test(data: &[u8], _out: Out) { test_msg_simple!(lightning::ln::msgs::SpliceInit, data); } -#[no_mangle] +#[unsafe(no_mangle)] pub extern "C" fn msg_splice_init_run(data: *const u8, datalen: usize) { let data = unsafe { std::slice::from_raw_parts(data, datalen) }; test_msg_simple!(lightning::ln::msgs::SpliceInit, data); diff --git a/fuzz/src/msg_targets/msg_splice_locked.rs b/fuzz/src/msg_targets/msg_splice_locked.rs index 02e762ade70..1dc3d1c2c10 100644 --- a/fuzz/src/msg_targets/msg_splice_locked.rs +++ b/fuzz/src/msg_targets/msg_splice_locked.rs @@ -20,7 +20,7 @@ pub fn msg_splice_locked_test(data: &[u8], _out: Out) test_msg_simple!(lightning::ln::msgs::SpliceLocked, data); } -#[no_mangle] +#[unsafe(no_mangle)] pub extern "C" fn msg_splice_locked_run(data: *const u8, datalen: usize) { let data = unsafe { std::slice::from_raw_parts(data, datalen) }; test_msg_simple!(lightning::ln::msgs::SpliceLocked, data); diff --git a/fuzz/src/msg_targets/msg_stfu.rs b/fuzz/src/msg_targets/msg_stfu.rs index 87845cf28aa..d1ef0a2b4de 100644 --- a/fuzz/src/msg_targets/msg_stfu.rs +++ b/fuzz/src/msg_targets/msg_stfu.rs @@ -20,7 +20,7 @@ pub fn msg_stfu_test(data: &[u8], _out: Out) { test_msg_simple!(lightning::ln::msgs::Stfu, data); } -#[no_mangle] +#[unsafe(no_mangle)] pub extern "C" fn msg_stfu_run(data: *const u8, datalen: usize) { let data = unsafe { std::slice::from_raw_parts(data, datalen) }; test_msg_simple!(lightning::ln::msgs::Stfu, data); diff --git a/fuzz/src/msg_targets/msg_target_template.txt b/fuzz/src/msg_targets/msg_target_template.txt index f5ed99b64d0..d0b49dc97cb 100644 --- a/fuzz/src/msg_targets/msg_target_template.txt +++ b/fuzz/src/msg_targets/msg_target_template.txt @@ -20,7 +20,7 @@ pub fn TARGET_NAME_test(data: &[u8], _out: Out) { TEST_MSG!(MSG_TARGET, dataEXTRA_ARGS); } -#[no_mangle] +#[unsafe(no_mangle)] pub extern "C" fn TARGET_NAME_run(data: *const u8, datalen: usize) { let data = unsafe { std::slice::from_raw_parts(data, datalen) }; TEST_MSG!(MSG_TARGET, dataEXTRA_ARGS); diff --git a/fuzz/src/msg_targets/msg_tx_abort.rs b/fuzz/src/msg_targets/msg_tx_abort.rs index c80df485040..1644bfd241b 100644 --- a/fuzz/src/msg_targets/msg_tx_abort.rs +++ b/fuzz/src/msg_targets/msg_tx_abort.rs @@ -20,7 +20,7 @@ pub fn msg_tx_abort_test(data: &[u8], _out: Out) { test_msg_simple!(lightning::ln::msgs::TxAbort, data); } -#[no_mangle] +#[unsafe(no_mangle)] pub extern "C" fn msg_tx_abort_run(data: *const u8, datalen: usize) { let data = unsafe { std::slice::from_raw_parts(data, datalen) }; test_msg_simple!(lightning::ln::msgs::TxAbort, data); diff --git a/fuzz/src/msg_targets/msg_tx_ack_rbf.rs b/fuzz/src/msg_targets/msg_tx_ack_rbf.rs index 41fd1ed9c27..ada7ae50c6a 100644 --- a/fuzz/src/msg_targets/msg_tx_ack_rbf.rs +++ b/fuzz/src/msg_targets/msg_tx_ack_rbf.rs @@ -20,7 +20,7 @@ pub fn msg_tx_ack_rbf_test(data: &[u8], _out: Out) { test_msg_simple!(lightning::ln::msgs::TxAckRbf, data); } -#[no_mangle] +#[unsafe(no_mangle)] pub extern "C" fn msg_tx_ack_rbf_run(data: *const u8, datalen: usize) { let data = unsafe { std::slice::from_raw_parts(data, datalen) }; test_msg_simple!(lightning::ln::msgs::TxAckRbf, data); diff --git a/fuzz/src/msg_targets/msg_tx_add_input.rs b/fuzz/src/msg_targets/msg_tx_add_input.rs index 8ae0c61034a..ef7863ec101 100644 --- a/fuzz/src/msg_targets/msg_tx_add_input.rs +++ b/fuzz/src/msg_targets/msg_tx_add_input.rs @@ -20,7 +20,7 @@ pub fn msg_tx_add_input_test(data: &[u8], _out: Out) { test_msg_simple!(lightning::ln::msgs::TxAddInput, data); } -#[no_mangle] +#[unsafe(no_mangle)] pub extern "C" fn msg_tx_add_input_run(data: *const u8, datalen: usize) { let data = unsafe { std::slice::from_raw_parts(data, datalen) }; test_msg_simple!(lightning::ln::msgs::TxAddInput, data); diff --git a/fuzz/src/msg_targets/msg_tx_add_output.rs b/fuzz/src/msg_targets/msg_tx_add_output.rs index 04511ed599f..94d5f3708e3 100644 --- a/fuzz/src/msg_targets/msg_tx_add_output.rs +++ b/fuzz/src/msg_targets/msg_tx_add_output.rs @@ -20,7 +20,7 @@ pub fn msg_tx_add_output_test(data: &[u8], _out: Out) test_msg_simple!(lightning::ln::msgs::TxAddOutput, data); } -#[no_mangle] +#[unsafe(no_mangle)] pub extern "C" fn msg_tx_add_output_run(data: *const u8, datalen: usize) { let data = unsafe { std::slice::from_raw_parts(data, datalen) }; test_msg_simple!(lightning::ln::msgs::TxAddOutput, data); diff --git a/fuzz/src/msg_targets/msg_tx_complete.rs b/fuzz/src/msg_targets/msg_tx_complete.rs index 4cd1a271284..91fbb92d26d 100644 --- a/fuzz/src/msg_targets/msg_tx_complete.rs +++ b/fuzz/src/msg_targets/msg_tx_complete.rs @@ -20,7 +20,7 @@ pub fn msg_tx_complete_test(data: &[u8], _out: Out) { test_msg_simple!(lightning::ln::msgs::TxComplete, data); } -#[no_mangle] +#[unsafe(no_mangle)] pub extern "C" fn msg_tx_complete_run(data: *const u8, datalen: usize) { let data = unsafe { std::slice::from_raw_parts(data, datalen) }; test_msg_simple!(lightning::ln::msgs::TxComplete, data); diff --git a/fuzz/src/msg_targets/msg_tx_init_rbf.rs b/fuzz/src/msg_targets/msg_tx_init_rbf.rs index eab0a747ea8..902c9deac26 100644 --- a/fuzz/src/msg_targets/msg_tx_init_rbf.rs +++ b/fuzz/src/msg_targets/msg_tx_init_rbf.rs @@ -20,7 +20,7 @@ pub fn msg_tx_init_rbf_test(data: &[u8], _out: Out) { test_msg_simple!(lightning::ln::msgs::TxInitRbf, data); } -#[no_mangle] +#[unsafe(no_mangle)] pub extern "C" fn msg_tx_init_rbf_run(data: *const u8, datalen: usize) { let data = unsafe { std::slice::from_raw_parts(data, datalen) }; test_msg_simple!(lightning::ln::msgs::TxInitRbf, data); diff --git a/fuzz/src/msg_targets/msg_tx_remove_input.rs b/fuzz/src/msg_targets/msg_tx_remove_input.rs index 1f934eac274..85e26a83bbe 100644 --- a/fuzz/src/msg_targets/msg_tx_remove_input.rs +++ b/fuzz/src/msg_targets/msg_tx_remove_input.rs @@ -20,7 +20,7 @@ pub fn msg_tx_remove_input_test(data: &[u8], _out: Out test_msg_simple!(lightning::ln::msgs::TxRemoveInput, data); } -#[no_mangle] +#[unsafe(no_mangle)] pub extern "C" fn msg_tx_remove_input_run(data: *const u8, datalen: usize) { let data = unsafe { std::slice::from_raw_parts(data, datalen) }; test_msg_simple!(lightning::ln::msgs::TxRemoveInput, data); diff --git a/fuzz/src/msg_targets/msg_tx_remove_output.rs b/fuzz/src/msg_targets/msg_tx_remove_output.rs index a9e0e8b2ef1..6a54bafc460 100644 --- a/fuzz/src/msg_targets/msg_tx_remove_output.rs +++ b/fuzz/src/msg_targets/msg_tx_remove_output.rs @@ -20,7 +20,7 @@ pub fn msg_tx_remove_output_test(data: &[u8], _out: Ou test_msg_simple!(lightning::ln::msgs::TxRemoveOutput, data); } -#[no_mangle] +#[unsafe(no_mangle)] pub extern "C" fn msg_tx_remove_output_run(data: *const u8, datalen: usize) { let data = unsafe { std::slice::from_raw_parts(data, datalen) }; test_msg_simple!(lightning::ln::msgs::TxRemoveOutput, data); diff --git a/fuzz/src/msg_targets/msg_tx_signatures.rs b/fuzz/src/msg_targets/msg_tx_signatures.rs index 17dc063adc2..eee6a107dcd 100644 --- a/fuzz/src/msg_targets/msg_tx_signatures.rs +++ b/fuzz/src/msg_targets/msg_tx_signatures.rs @@ -20,7 +20,7 @@ pub fn msg_tx_signatures_test(data: &[u8], _out: Out) test_msg_simple!(lightning::ln::msgs::TxSignatures, data); } -#[no_mangle] +#[unsafe(no_mangle)] pub extern "C" fn msg_tx_signatures_run(data: *const u8, datalen: usize) { let data = unsafe { std::slice::from_raw_parts(data, datalen) }; test_msg_simple!(lightning::ln::msgs::TxSignatures, data); diff --git a/fuzz/src/msg_targets/msg_update_add_htlc.rs b/fuzz/src/msg_targets/msg_update_add_htlc.rs index 45a2616243a..0a7b51e41fe 100644 --- a/fuzz/src/msg_targets/msg_update_add_htlc.rs +++ b/fuzz/src/msg_targets/msg_update_add_htlc.rs @@ -20,7 +20,7 @@ pub fn msg_update_add_htlc_test(data: &[u8], _out: Out test_msg_simple!(lightning::ln::msgs::UpdateAddHTLC, data); } -#[no_mangle] +#[unsafe(no_mangle)] pub extern "C" fn msg_update_add_htlc_run(data: *const u8, datalen: usize) { let data = unsafe { std::slice::from_raw_parts(data, datalen) }; test_msg_simple!(lightning::ln::msgs::UpdateAddHTLC, data); diff --git a/fuzz/src/msg_targets/msg_update_fail_htlc.rs b/fuzz/src/msg_targets/msg_update_fail_htlc.rs index e338beeee2f..0b170d16281 100644 --- a/fuzz/src/msg_targets/msg_update_fail_htlc.rs +++ b/fuzz/src/msg_targets/msg_update_fail_htlc.rs @@ -20,7 +20,7 @@ pub fn msg_update_fail_htlc_test(data: &[u8], _out: Ou test_msg_simple!(lightning::ln::msgs::UpdateFailHTLC, data); } -#[no_mangle] +#[unsafe(no_mangle)] pub extern "C" fn msg_update_fail_htlc_run(data: *const u8, datalen: usize) { let data = unsafe { std::slice::from_raw_parts(data, datalen) }; test_msg_simple!(lightning::ln::msgs::UpdateFailHTLC, data); diff --git a/fuzz/src/msg_targets/msg_update_fail_malformed_htlc.rs b/fuzz/src/msg_targets/msg_update_fail_malformed_htlc.rs index 6c1914f03ca..58c91285c5e 100644 --- a/fuzz/src/msg_targets/msg_update_fail_malformed_htlc.rs +++ b/fuzz/src/msg_targets/msg_update_fail_malformed_htlc.rs @@ -20,7 +20,7 @@ pub fn msg_update_fail_malformed_htlc_test(data: &[u8] test_msg_simple!(lightning::ln::msgs::UpdateFailMalformedHTLC, data); } -#[no_mangle] +#[unsafe(no_mangle)] pub extern "C" fn msg_update_fail_malformed_htlc_run(data: *const u8, datalen: usize) { let data = unsafe { std::slice::from_raw_parts(data, datalen) }; test_msg_simple!(lightning::ln::msgs::UpdateFailMalformedHTLC, data); diff --git a/fuzz/src/msg_targets/msg_update_fee.rs b/fuzz/src/msg_targets/msg_update_fee.rs index 991dde925f8..fa19a8acb30 100644 --- a/fuzz/src/msg_targets/msg_update_fee.rs +++ b/fuzz/src/msg_targets/msg_update_fee.rs @@ -20,7 +20,7 @@ pub fn msg_update_fee_test(data: &[u8], _out: Out) { test_msg_simple!(lightning::ln::msgs::UpdateFee, data); } -#[no_mangle] +#[unsafe(no_mangle)] pub extern "C" fn msg_update_fee_run(data: *const u8, datalen: usize) { let data = unsafe { std::slice::from_raw_parts(data, datalen) }; test_msg_simple!(lightning::ln::msgs::UpdateFee, data); diff --git a/fuzz/src/msg_targets/msg_update_fulfill_htlc.rs b/fuzz/src/msg_targets/msg_update_fulfill_htlc.rs index 61e3f30b95c..11a8b1bfa85 100644 --- a/fuzz/src/msg_targets/msg_update_fulfill_htlc.rs +++ b/fuzz/src/msg_targets/msg_update_fulfill_htlc.rs @@ -20,7 +20,7 @@ pub fn msg_update_fulfill_htlc_test(data: &[u8], _out: test_msg_simple!(lightning::ln::msgs::UpdateFulfillHTLC, data); } -#[no_mangle] +#[unsafe(no_mangle)] pub extern "C" fn msg_update_fulfill_htlc_run(data: *const u8, datalen: usize) { let data = unsafe { std::slice::from_raw_parts(data, datalen) }; test_msg_simple!(lightning::ln::msgs::UpdateFulfillHTLC, data); diff --git a/fuzz/src/msg_targets/msg_warning_message.rs b/fuzz/src/msg_targets/msg_warning_message.rs index 0e1a4566677..d2835dce76d 100644 --- a/fuzz/src/msg_targets/msg_warning_message.rs +++ b/fuzz/src/msg_targets/msg_warning_message.rs @@ -20,7 +20,7 @@ pub fn msg_warning_message_test(data: &[u8], _out: Out test_msg_hole!(lightning::ln::msgs::WarningMessage, data, 32, 2); } -#[no_mangle] +#[unsafe(no_mangle)] pub extern "C" fn msg_warning_message_run(data: *const u8, datalen: usize) { let data = unsafe { std::slice::from_raw_parts(data, datalen) }; test_msg_hole!(lightning::ln::msgs::WarningMessage, data, 32, 2); diff --git a/fuzz/src/offer_deser.rs b/fuzz/src/offer_deser.rs index 68902ab3150..671322c6a39 100644 --- a/fuzz/src/offer_deser.rs +++ b/fuzz/src/offer_deser.rs @@ -70,7 +70,7 @@ pub fn offer_deser_test(data: &[u8], out: Out) { do_test(data, out); } -#[no_mangle] +#[unsafe(no_mangle)] pub extern "C" fn offer_deser_run(data: *const u8, datalen: usize) { do_test(unsafe { std::slice::from_raw_parts(data, datalen) }, test_logger::DevNull {}); } diff --git a/fuzz/src/onion_hop_data.rs b/fuzz/src/onion_hop_data.rs index bf3b7b4b44d..b4aad546a44 100644 --- a/fuzz/src/onion_hop_data.rs +++ b/fuzz/src/onion_hop_data.rs @@ -25,7 +25,7 @@ pub fn onion_hop_data_test(data: &[u8], _out: Out) { )>>::read(&mut r, (None, &&node_signer)); } -#[no_mangle] +#[unsafe(no_mangle)] pub extern "C" fn onion_hop_data_run(data: *const u8, datalen: usize) { use bitcoin::secp256k1::PublicKey; use lightning::util::ser::ReadableArgs; diff --git a/fuzz/src/onion_message.rs b/fuzz/src/onion_message.rs index 4859f7379fb..8f559f138db 100644 --- a/fuzz/src/onion_message.rs +++ b/fuzz/src/onion_message.rs @@ -5,10 +5,10 @@ use bitcoin::secp256k1::ecdsa::RecoverableSignature; use bitcoin::secp256k1::schnorr; use bitcoin::secp256k1::{self, PublicKey, Scalar, Secp256k1, SecretKey}; +use lightning::blinded_path::EmptyNodeIdLookUp; use lightning::blinded_path::message::{ AsyncPaymentsContext, BlindedMessagePath, MessageContext, MessageForwardNode, OffersContext, }; -use lightning::blinded_path::EmptyNodeIdLookUp; use lightning::ln::inbound_payment::ExpandedKey; use lightning::ln::msgs::{self, BaseMessageHandler, DecodeError, OnionMessageHandler}; use lightning::ln::peer_handler::IgnoringMessageHandler; @@ -90,7 +90,7 @@ pub fn onion_message_test(data: &[u8], out: Out) { } /// Method that needs to be added manually, {name}_run -#[no_mangle] +#[unsafe(no_mangle)] pub extern "C" fn onion_message_run(data: *const u8, datalen: usize) { let logger = test_logger::TestLogger::new("".to_owned(), test_logger::DevNull {}); do_test(unsafe { std::slice::from_raw_parts(data, datalen) }, &logger); diff --git a/fuzz/src/peer_crypt.rs b/fuzz/src/peer_crypt.rs index b01aa02400b..f6c65d4824a 100644 --- a/fuzz/src/peer_crypt.rs +++ b/fuzz/src/peer_crypt.rs @@ -100,7 +100,7 @@ pub fn peer_crypt_test(data: &[u8], _out: Out) { do_test(data); } -#[no_mangle] +#[unsafe(no_mangle)] pub extern "C" fn peer_crypt_run(data: *const u8, datalen: usize) { do_test(unsafe { std::slice::from_raw_parts(data, datalen) }); } diff --git a/fuzz/src/process_network_graph.rs b/fuzz/src/process_network_graph.rs index 980c147e96a..cc9b3e4f939 100644 --- a/fuzz/src/process_network_graph.rs +++ b/fuzz/src/process_network_graph.rs @@ -18,7 +18,7 @@ pub fn process_network_graph_test(data: &[u8], out: Ou } /// Method that needs to be added manually, {name}_run -#[no_mangle] +#[unsafe(no_mangle)] pub extern "C" fn process_network_graph_run(data: *const u8, datalen: usize) { do_test(unsafe { std::slice::from_raw_parts(data, datalen) }, test_logger::DevNull {}); } diff --git a/fuzz/src/process_onion_failure.rs b/fuzz/src/process_onion_failure.rs index ac70562c006..c87ec5e7be6 100644 --- a/fuzz/src/process_onion_failure.rs +++ b/fuzz/src/process_onion_failure.rs @@ -155,7 +155,7 @@ pub fn process_onion_failure_test(data: &[u8], out: Ou } /// Method that needs to be added manually, {name}_run -#[no_mangle] +#[unsafe(no_mangle)] pub extern "C" fn process_onion_failure_run(data: *const u8, datalen: usize) { do_test(unsafe { std::slice::from_raw_parts(data, datalen) }, test_logger::DevNull {}); } diff --git a/fuzz/src/refund_deser.rs b/fuzz/src/refund_deser.rs index 446ac704455..75c78d6dc8a 100644 --- a/fuzz/src/refund_deser.rs +++ b/fuzz/src/refund_deser.rs @@ -116,7 +116,7 @@ pub fn refund_deser_test(data: &[u8], out: Out) { do_test(data, out); } -#[no_mangle] +#[unsafe(no_mangle)] pub extern "C" fn refund_deser_run(data: *const u8, datalen: usize) { do_test(unsafe { std::slice::from_raw_parts(data, datalen) }, test_logger::DevNull {}); } diff --git a/fuzz/src/router.rs b/fuzz/src/router.rs index 2295ae3d7ff..9703c3bbb5f 100644 --- a/fuzz/src/router.rs +++ b/fuzz/src/router.rs @@ -12,8 +12,8 @@ use bitcoin::constants::ChainHash; use bitcoin::script::Builder; use bitcoin::transaction::TxOut; -use lightning::blinded_path::payment::{BlindedPayInfo, BlindedPaymentPath}; use lightning::blinded_path::BlindedHop; +use lightning::blinded_path::payment::{BlindedPayInfo, BlindedPaymentPath}; use lightning::chain::transaction::OutPoint; use lightning::ln::channel_state::{ChannelCounterparty, ChannelDetails, ChannelShutdownState}; use lightning::ln::channelmanager; @@ -21,7 +21,7 @@ use lightning::ln::msgs; use lightning::ln::types::ChannelId; use lightning::routing::gossip::{NetworkGraph, RoutingFees}; use lightning::routing::router::{ - find_route, PaymentParameters, RouteHint, RouteHintHop, RouteParameters, + PaymentParameters, RouteHint, RouteHintHop, RouteParameters, find_route, }; use lightning::routing::scoring::{ ProbabilisticScorer, ProbabilisticScoringDecayParameters, ProbabilisticScoringFeeParameters, @@ -40,8 +40,8 @@ use bitcoin::secp256k1::PublicKey; use crate::utils::test_logger; use std::convert::TryInto; -use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::Arc; +use std::sync::atomic::{AtomicUsize, Ordering}; #[inline] pub fn slice_to_be16(v: &[u8]) -> u16 { @@ -429,7 +429,7 @@ pub fn router_test(data: &[u8], out: Out) { do_test(data, out); } -#[no_mangle] +#[unsafe(no_mangle)] pub extern "C" fn router_run(data: *const u8, datalen: usize) { do_test(unsafe { std::slice::from_raw_parts(data, datalen) }, test_logger::DevNull {}); } diff --git a/fuzz/src/static_invoice_deser.rs b/fuzz/src/static_invoice_deser.rs index 4256ad26760..f626f721fe2 100644 --- a/fuzz/src/static_invoice_deser.rs +++ b/fuzz/src/static_invoice_deser.rs @@ -25,7 +25,7 @@ pub fn static_invoice_deser_test(data: &[u8], out: Out do_test(data, out); } -#[no_mangle] +#[unsafe(no_mangle)] pub extern "C" fn static_invoice_deser_run(data: *const u8, datalen: usize) { do_test(unsafe { std::slice::from_raw_parts(data, datalen) }, test_logger::DevNull {}); } diff --git a/fuzz/src/zbase32.rs b/fuzz/src/zbase32.rs index 04979204e98..aec058b71e1 100644 --- a/fuzz/src/zbase32.rs +++ b/fuzz/src/zbase32.rs @@ -28,7 +28,7 @@ pub fn zbase32_test(data: &[u8], _out: Out) { do_test(data); } -#[no_mangle] +#[unsafe(no_mangle)] pub extern "C" fn zbase32_run(data: *const u8, datalen: usize) { do_test(unsafe { std::slice::from_raw_parts(data, datalen) }); } diff --git a/fuzz/write-seeds/Cargo.toml b/fuzz/write-seeds/Cargo.toml index 1c5acb7919f..1b4b3fed31e 100644 --- a/fuzz/write-seeds/Cargo.toml +++ b/fuzz/write-seeds/Cargo.toml @@ -3,7 +3,7 @@ name = "lightning-fuzz-write-seeds" version = "0.0.1" authors = ["Automatically generated"] publish = false -edition = "2021" +edition = "2024" [features] diff --git a/lightning-background-processor/Cargo.toml b/lightning-background-processor/Cargo.toml index e958919f4d8..bda53c3ebd3 100644 --- a/lightning-background-processor/Cargo.toml +++ b/lightning-background-processor/Cargo.toml @@ -8,8 +8,8 @@ readme = "../README.md" description = """ Utilities to perform required background tasks for Rust Lightning. """ -edition = "2021" -rust-version = "1.75" +edition = "2024" +rust-version = "1.85" [package.metadata.docs.rs] all-features = true diff --git a/lightning-background-processor/src/lib.rs b/lightning-background-processor/src/lib.rs index 8ab20d5a1f3..f61293155ed 100644 --- a/lightning-background-processor/src/lib.rs +++ b/lightning-background-processor/src/lib.rs @@ -59,8 +59,8 @@ use lightning::util::logger::Logger; #[cfg(not(c_bindings))] use lightning::util::native_async::MaybeSend; use lightning::util::persist::{ - KVStore, KVStoreSync, KVStoreSyncWrapper, CHANNEL_MANAGER_PERSISTENCE_KEY, - CHANNEL_MANAGER_PERSISTENCE_PRIMARY_NAMESPACE, CHANNEL_MANAGER_PERSISTENCE_SECONDARY_NAMESPACE, + CHANNEL_MANAGER_PERSISTENCE_KEY, CHANNEL_MANAGER_PERSISTENCE_PRIMARY_NAMESPACE, + CHANNEL_MANAGER_PERSISTENCE_SECONDARY_NAMESPACE, KVStore, KVStoreSync, KVStoreSyncWrapper, NETWORK_GRAPH_PERSISTENCE_KEY, NETWORK_GRAPH_PERSISTENCE_PRIMARY_NAMESPACE, NETWORK_GRAPH_PERSISTENCE_SECONDARY_NAMESPACE, SCORER_PERSISTENCE_KEY, SCORER_PERSISTENCE_PRIMARY_NAMESPACE, SCORER_PERSISTENCE_SECONDARY_NAMESPACE, @@ -187,11 +187,7 @@ const ARCHIVE_STALE_MONITORS_TIMER: Duration = Duration::from_secs(1); /// core::cmp::min is not currently const, so we define a trivial (and equivalent) replacement const fn min_duration(a: Duration, b: Duration) -> Duration { - if a.as_nanos() < b.as_nanos() { - a - } else { - b - } + if a.as_nanos() < b.as_nanos() { a } else { b } } const FASTEST_TIMER: Duration = min_duration( min_duration(FRESHNESS_TIMER, PING_TIMER), @@ -215,12 +211,12 @@ pub enum GossipSync< } impl< - P: Deref>, - R: Deref>, - G: Deref>, - U: UtxoLookup, - L: Logger, - > GossipSync + P: Deref>, + R: Deref>, + G: Deref>, + U: UtxoLookup, + L: Logger, +> GossipSync { fn network_graph(&self) -> Option<&G> { match self { @@ -255,11 +251,11 @@ impl< /// This is not exported to bindings users as the bindings concretize everything and have constructors for us impl< - P: Deref>, - G: Deref>, - U: UtxoLookup, - L: Logger, - > GossipSync, G, U, L> + P: Deref>, + G: Deref>, + U: UtxoLookup, + L: Logger, +> GossipSync, G, U, L> { /// Initializes a new [`GossipSync::P2P`] variant. pub fn p2p(gossip_sync: P) -> Self { @@ -268,12 +264,7 @@ impl< } /// This is not exported to bindings users as the bindings concretize everything and have constructors for us -impl< - 'a, - R: Deref>, - G: Deref>, - L: Logger, - > +impl<'a, R: Deref>, G: Deref>, L: Logger> GossipSync< &P2PGossipSync, R, @@ -306,7 +297,7 @@ impl<'a, L: Logger> fn handle_network_graph_update(network_graph: &NetworkGraph, event: &Event) { if let Event::PaymentPathFailed { - failure: PathFailure::OnPath { network_update: Some(ref upd) }, + failure: PathFailure::OnPath { network_update: Some(upd) }, .. } = event { @@ -320,11 +311,11 @@ fn update_scorer<'a, S: Deref, SC: 'a + WriteableScore<'a>>( scorer: &'a S, event: &Event, duration_since_epoch: Duration, ) -> bool { match event { - Event::PaymentPathFailed { ref path, short_channel_id: Some(scid), .. } => { + Event::PaymentPathFailed { path, short_channel_id: Some(scid), .. } => { let mut score = scorer.write_lock(); score.payment_path_failed(path, *scid, duration_since_epoch); }, - Event::PaymentPathFailed { ref path, payment_failed_permanently: true, .. } => { + Event::PaymentPathFailed { path, payment_failed_permanently: true, .. } => { // Reached if the destination explicitly failed it back. We treat this as a successful probe // because the payment made it all the way to the destination with sufficient liquidity. let mut score = scorer.write_lock(); @@ -494,7 +485,7 @@ pub(crate) mod futures_util { use core::future::Future; use core::marker::Unpin; use core::pin::Pin; - use core::task::{Poll, RawWaker, RawWakerVTable, Waker}; + use core::task::Poll; pub(crate) struct Selector< A: Future + Unpin, B: Future + Unpin, @@ -521,13 +512,13 @@ pub(crate) mod futures_util { } impl< - A: Future + Unpin, - B: Future + Unpin, - C: Future + Unpin, - D: Future + Unpin, - E: Future + Unpin, - F: Future + Unpin, - > Future for Selector + A: Future + Unpin, + B: Future + Unpin, + C: Future + Unpin, + D: Future + Unpin, + E: Future + Unpin, + F: Future + Unpin, + > Future for Selector { type Output = SelectorOutput; fn poll( @@ -603,24 +594,6 @@ pub(crate) mod futures_util { } } - // If we want to poll a future without an async context to figure out if it has completed or - // not without awaiting, we need a Waker, which needs a vtable...we fill it with dummy values - // but sadly there's a good bit of boilerplate here. - fn dummy_waker_clone(_: *const ()) -> RawWaker { - RawWaker::new(core::ptr::null(), &DUMMY_WAKER_VTABLE) - } - fn dummy_waker_action(_: *const ()) {} - - const DUMMY_WAKER_VTABLE: RawWakerVTable = RawWakerVTable::new( - dummy_waker_clone, - dummy_waker_action, - dummy_waker_action, - dummy_waker_action, - ); - pub(crate) fn dummy_waker() -> Waker { - unsafe { Waker::from_raw(RawWaker::new(core::ptr::null(), &DUMMY_WAKER_VTABLE)) } - } - enum JoinerResult> + Unpin> { Pending(Option), Ready(Result<(), ERR>), @@ -642,13 +615,13 @@ pub(crate) mod futures_util { } impl< - ERR, - A: Future> + Unpin, - B: Future> + Unpin, - C: Future> + Unpin, - D: Future> + Unpin, - E: Future> + Unpin, - > Joiner + ERR, + A: Future> + Unpin, + B: Future> + Unpin, + C: Future> + Unpin, + D: Future> + Unpin, + E: Future> + Unpin, + > Joiner { pub(crate) fn new() -> Self { Self { @@ -681,13 +654,13 @@ pub(crate) mod futures_util { } impl< - ERR, - A: Future> + Unpin, - B: Future> + Unpin, - C: Future> + Unpin, - D: Future> + Unpin, - E: Future> + Unpin, - > Future for Joiner + ERR, + A: Future> + Unpin, + B: Future> + Unpin, + C: Future> + Unpin, + D: Future> + Unpin, + E: Future> + Unpin, + > Future for Joiner where Joiner: Unpin, { @@ -700,7 +673,7 @@ pub(crate) mod futures_util { JoinerResult::Pending(None) => { self.$val = JoinerResult::Ready(Ok(())); }, - JoinerResult::::Pending(Some(ref mut val)) => { + JoinerResult::::Pending(Some(val)) => { match Pin::new(val).poll(ctx) { Poll::Ready(res) => { self.$val = JoinerResult::Ready(res); @@ -722,19 +695,19 @@ pub(crate) mod futures_util { if all_complete { let mut res = [Ok(()), Ok(()), Ok(()), Ok(()), Ok(())]; - if let JoinerResult::Ready(ref mut val) = &mut self.a { + if let JoinerResult::Ready(val) = &mut self.a { core::mem::swap(&mut res[0], val); } - if let JoinerResult::Ready(ref mut val) = &mut self.b { + if let JoinerResult::Ready(val) = &mut self.b { core::mem::swap(&mut res[1], val); } - if let JoinerResult::Ready(ref mut val) = &mut self.c { + if let JoinerResult::Ready(val) = &mut self.c { core::mem::swap(&mut res[2], val); } - if let JoinerResult::Ready(ref mut val) = &mut self.d { + if let JoinerResult::Ready(val) = &mut self.d { core::mem::swap(&mut res[3], val); } - if let JoinerResult::Ready(ref mut val) = &mut self.e { + if let JoinerResult::Ready(val) = &mut self.e { core::mem::swap(&mut res[4], val); } Poll::Ready(res) @@ -745,7 +718,7 @@ pub(crate) mod futures_util { } } use core::task; -use futures_util::{dummy_waker, Joiner, OptionalSelector, Selector, SelectorOutput}; +use futures_util::{Joiner, OptionalSelector, Selector, SelectorOutput}; /// Processes background events in a future. /// @@ -972,42 +945,43 @@ where LM::Target: ALiquidityManager, D::Target: ChangeDestinationSource, { - let async_event_handler = |event| { + let async_event_handler = async |event| { let network_graph = gossip_sync.network_graph(); let event_handler = &event_handler; let scorer = &scorer; let logger = &logger; let kv_store = &kv_store; let fetch_time = &fetch_time; - // We should be able to drop the Box once our MSRV is 1.68 - Box::pin(async move { - if let Some(network_graph) = network_graph { - handle_network_graph_update(network_graph, &event) - } - if let Some(ref scorer) = scorer { - if let Some(duration_since_epoch) = fetch_time() { - if update_scorer(scorer, &event, duration_since_epoch) { - log_trace!(logger, "Persisting scorer after update"); - if let Err(e) = kv_store - .write( - SCORER_PERSISTENCE_PRIMARY_NAMESPACE, - SCORER_PERSISTENCE_SECONDARY_NAMESPACE, - SCORER_PERSISTENCE_KEY, - scorer.encode(), - ) - .await - { - log_error!(logger, "Error: Failed to persist scorer, check your disk and permissions {}", e); - // We opt not to abort early on persistence failure here as persisting - // the scorer is non-critical and we still hope that it will have - // resolved itself when it is potentially critical in event handling - // below. - } + if let Some(network_graph) = network_graph { + handle_network_graph_update(network_graph, &event) + } + if let Some(scorer) = scorer { + if let Some(duration_since_epoch) = fetch_time() { + if update_scorer(scorer, &event, duration_since_epoch) { + log_trace!(logger, "Persisting scorer after update"); + if let Err(e) = kv_store + .write( + SCORER_PERSISTENCE_PRIMARY_NAMESPACE, + SCORER_PERSISTENCE_SECONDARY_NAMESPACE, + SCORER_PERSISTENCE_KEY, + scorer.encode(), + ) + .await + { + log_error!( + logger, + "Error: Failed to persist scorer, check your disk and permissions {}", + e + ); + // We opt not to abort early on persistence failure here as persisting + // the scorer is non-critical and we still hope that it will have + // resolved itself when it is potentially critical in event handling + // below. } } } - event_handler(event).await - }) + } + event_handler(event).await }; let mut batch_delay = BatchDelay::new(); @@ -1125,16 +1099,14 @@ where // before the persistence flag is set. Capturing outside would let us // observe pending ops while the flag is still unset, causing us to // flush monitor writes without persisting the ChannelManager. - // Declared before futures so it outlives the Joiner (drop order). + // Declared before the ChannelManager persistence future so it outlives it (drop order). let pending_monitor_writes; - - let mut futures = Joiner::new(); - - if channel_manager.get_cm().get_and_clear_needs_persistence() { + let channel_manager_persist = if channel_manager.get_cm().get_and_clear_needs_persistence() + { pending_monitor_writes = chain_monitor.get_cm().pending_operation_count(); log_trace!(logger, "Persisting ChannelManager..."); - let fut = async { + Some(async { kv_store .write( CHANNEL_MANAGER_PERSISTENCE_PRIMARY_NAMESPACE, @@ -1148,21 +1120,25 @@ where // that arrived after are left for the next iteration. chain_monitor.get_cm().flush(pending_monitor_writes, &logger); Ok(()) - }; - // TODO: Once our MSRV is 1.68 we should be able to drop the Box - let mut fut = Box::pin(fut); + }) + } else { + None + }; + let mut channel_manager_persist = core::pin::pin!(channel_manager_persist); + let mut channel_manager_persist_res = None; + let mut channel_manager_persist_pending = false; + if let Some(mut fut) = channel_manager_persist.as_mut().as_pin_mut() { // Because persisting the ChannelManager is important to avoid accidental // force-closures, go ahead and poll the future once before we do slightly more // CPU-intensive tasks in the form of NetworkGraph pruning or scorer time-stepping // below. This will get it moving but won't block us for too long if the underlying // future is actually async. use core::future::Future; - let mut waker = dummy_waker(); - let mut ctx = task::Context::from_waker(&mut waker); - match core::pin::Pin::new(&mut fut).poll(&mut ctx) { - task::Poll::Ready(res) => futures.set_a_res(res), - task::Poll::Pending => futures.set_a(fut), + let mut ctx = task::Context::from_waker(core::task::Waker::noop()); + match fut.as_mut().poll(&mut ctx) { + task::Poll::Ready(res) => channel_manager_persist_res = Some(res), + task::Poll::Pending => channel_manager_persist_pending = true, } log_trace!(logger, "Done persisting ChannelManager."); @@ -1210,6 +1186,7 @@ where GossipSync::Rapid(_) => !have_pruned || prune_timer_elapsed, _ => prune_timer_elapsed, }; + let mut network_graph_persist = None; if should_prune { // The network graph must not be pruned while rapid sync completion is pending if let Some(network_graph) = gossip_sync.prunable_network_graph() { @@ -1219,10 +1196,13 @@ where duration_since_epoch.as_secs(), ); } else { - log_warn!(logger, "Not pruning network graph, consider implementing the fetch_time argument or calling remove_stale_channels_and_tracking_with_time manually."); + log_warn!( + logger, + "Not pruning network graph, consider implementing the fetch_time argument or calling remove_stale_channels_and_tracking_with_time manually." + ); log_trace!(logger, "Persisting network graph."); } - let fut = async { + network_graph_persist = Some(async { if let Err(e) = kv_store .write( NETWORK_GRAPH_PERSISTENCE_PRIMARY_NAMESPACE, @@ -1232,18 +1212,21 @@ where ) .await { - log_error!(logger, "Error: Failed to persist network graph, check your disk and permissions {}",e); + log_error!( + logger, + "Error: Failed to persist network graph, check your disk and permissions {}", + e + ); } Ok(()) - }; - - // TODO: Once our MSRV is 1.68 we should be able to drop the Box - futures.set_b(Box::pin(fut)); + }); have_pruned = true; } } + let mut network_graph_persist = core::pin::pin!(network_graph_persist); + if !have_decayed_scorer { if let Some(ref scorer) = scorer { if let Some(duration_since_epoch) = fetch_time() { @@ -1253,6 +1236,7 @@ where } have_decayed_scorer = true; } + let mut scorer_persist = None; match check_and_reset_sleeper(&mut last_scorer_persist_call, || { sleeper(SCORER_PERSIST_TIMER) }) { @@ -1264,7 +1248,7 @@ where } else { log_trace!(logger, "Persisting scorer"); } - let fut = async { + scorer_persist = Some(async { if let Err(e) = kv_store .write( SCORER_PERSISTENCE_PRIMARY_NAMESPACE, @@ -1275,42 +1259,41 @@ where .await { log_error!( - logger, - "Error: Failed to persist scorer, check your disk and permissions {}", - e - ); + logger, + "Error: Failed to persist scorer, check your disk and permissions {}", + e + ); } Ok(()) - }; - - // TODO: Once our MSRV is 1.68 we should be able to drop the Box - futures.set_c(Box::pin(fut)); + }); } }, Some(true) => break, None => {}, } + let mut scorer_persist = core::pin::pin!(scorer_persist); + + let mut sweeper_persist = None; match check_and_reset_sleeper(&mut last_sweeper_call, || sleeper(SWEEPER_TIMER)) { Some(false) => { log_trace!(logger, "Regenerating sweeper spends if necessary"); if let Some(ref sweeper) = sweeper { - let fut = async { + sweeper_persist = Some(async { let _ = sweeper.regenerate_and_broadcast_spend_if_necessary().await; Ok(()) - }; - - // TODO: Once our MSRV is 1.68 we should be able to drop the Box - futures.set_d(Box::pin(fut)); + }); } }, Some(true) => break, None => {}, } + let mut sweeper_persist = core::pin::pin!(sweeper_persist); + let mut liquidity_persist = None; if let Some(liquidity_manager) = liquidity_manager.as_ref() { - let fut = async { + liquidity_persist = Some(async { liquidity_manager .get_lm() .persist() @@ -1324,8 +1307,27 @@ where log_error!(logger, "Persisting LiquidityManager failed: {}", e); e }) - }; - futures.set_e(Box::pin(fut)); + }); + } + let mut liquidity_persist = core::pin::pin!(liquidity_persist); + + let mut futures = Joiner::new(); + if let Some(res) = channel_manager_persist_res { + futures.set_a_res(res); + } else if channel_manager_persist_pending { + futures.set_a(channel_manager_persist.as_mut().as_pin_mut().unwrap()); + } + if let Some(fut) = network_graph_persist.as_mut().as_pin_mut() { + futures.set_b(fut); + } + if let Some(fut) = scorer_persist.as_mut().as_pin_mut() { + futures.set_c(fut); + } + if let Some(fut) = sweeper_persist.as_mut().as_pin_mut() { + futures.set_d(fut); + } + if let Some(fut) = liquidity_persist.as_mut().as_pin_mut() { + futures.set_e(fut); } // Run persistence tasks in parallel and exit if any of them returns an error. @@ -1430,8 +1432,7 @@ fn check_and_reset_sleeper< >( fut: &mut SleepFuture, mut new_sleeper: impl FnMut() -> SleepFuture, ) -> Option { - let mut waker = dummy_waker(); - let mut ctx = task::Context::from_waker(&mut waker); + let mut ctx = task::Context::from_waker(core::task::Waker::noop()); match core::pin::Pin::new(&mut *fut).poll(&mut ctx) { task::Poll::Ready(exit) => { *fut = new_sleeper(); @@ -1621,7 +1622,11 @@ impl BackgroundProcessor { SCORER_PERSISTENCE_KEY, scorer.encode(), ) { - log_error!(logger, "Error: Failed to persist scorer, check your disk and permissions {}", e) + log_error!( + logger, + "Error: Failed to persist scorer, check your disk and permissions {}", + e + ) } } } @@ -1779,7 +1784,11 @@ impl BackgroundProcessor { NETWORK_GRAPH_PERSISTENCE_KEY, network_graph.encode(), ) { - log_error!(logger, "Error: Failed to persist network graph, check your disk and permissions {}", e); + log_error!( + logger, + "Error: Failed to persist network graph, check your disk and permissions {}", + e + ); } have_pruned = true; } @@ -1808,7 +1817,11 @@ impl BackgroundProcessor { SCORER_PERSISTENCE_KEY, scorer.encode(), ) { - log_error!(logger, "Error: Failed to persist scorer, check your disk and permissions {}", e); + log_error!( + logger, + "Error: Failed to persist scorer, check your disk and permissions {}", + e + ); } } last_scorer_persist_call = Instant::now(); @@ -1924,8 +1937,8 @@ impl Drop for BackgroundProcessor { #[cfg(all(feature = "std", test))] mod tests { - use super::{BackgroundProcessor, GossipSync, FRESHNESS_TIMER}; - use bitcoin::constants::{genesis_block, ChainHash}; + use super::{BackgroundProcessor, FRESHNESS_TIMER, GossipSync}; + use bitcoin::constants::{ChainHash, genesis_block}; use bitcoin::hashes::Hash; use bitcoin::locktime::absolute::LockTime; use bitcoin::network::Network; @@ -1941,7 +1954,7 @@ mod tests { use lightning::events::{Event, PathFailure, ReplayEvent}; use lightning::ln::channelmanager; use lightning::ln::channelmanager::{ - ChainParameters, PaymentId, BREAKDOWN_TIMEOUT, MIN_CLTV_EXPIRY_DELTA, + BREAKDOWN_TIMEOUT, ChainParameters, MIN_CLTV_EXPIRY_DELTA, PaymentId, }; use lightning::ln::functional_test_utils::*; use lightning::ln::msgs::{BaseMessageHandler, ChannelMessageHandler, Init, MessageSendEvent}; @@ -1958,12 +1971,11 @@ mod tests { use lightning::types::payment::PaymentHash; use lightning::util::config::UserConfig; use lightning::util::persist::{ - KVStoreSync, KVStoreSyncWrapper, CHANNEL_MANAGER_PERSISTENCE_KEY, - CHANNEL_MANAGER_PERSISTENCE_PRIMARY_NAMESPACE, - CHANNEL_MANAGER_PERSISTENCE_SECONDARY_NAMESPACE, NETWORK_GRAPH_PERSISTENCE_KEY, - NETWORK_GRAPH_PERSISTENCE_PRIMARY_NAMESPACE, NETWORK_GRAPH_PERSISTENCE_SECONDARY_NAMESPACE, - SCORER_PERSISTENCE_KEY, SCORER_PERSISTENCE_PRIMARY_NAMESPACE, - SCORER_PERSISTENCE_SECONDARY_NAMESPACE, + CHANNEL_MANAGER_PERSISTENCE_KEY, CHANNEL_MANAGER_PERSISTENCE_PRIMARY_NAMESPACE, + CHANNEL_MANAGER_PERSISTENCE_SECONDARY_NAMESPACE, KVStoreSync, KVStoreSyncWrapper, + NETWORK_GRAPH_PERSISTENCE_KEY, NETWORK_GRAPH_PERSISTENCE_PRIMARY_NAMESPACE, + NETWORK_GRAPH_PERSISTENCE_SECONDARY_NAMESPACE, SCORER_PERSISTENCE_KEY, + SCORER_PERSISTENCE_PRIMARY_NAMESPACE, SCORER_PERSISTENCE_SECONDARY_NAMESPACE, }; use lightning::util::ser::Writeable; use lightning::util::sweep::{ @@ -1977,8 +1989,8 @@ mod tests { use lightning_rapid_gossip_sync::RapidGossipSync; use std::collections::VecDeque; use std::path::PathBuf; - use std::sync::mpsc::SyncSender; use std::sync::Arc; + use std::sync::mpsc::SyncSender; use std::time::Duration; use std::{env, fs}; @@ -1996,11 +2008,7 @@ mod tests { let path_str = entry.path().to_str().unwrap().to_lowercase(); // Skip any .tmp files that may exist during persistence. // On Windows, ReplaceFileW creates backup files with .TMP (uppercase). - if path_str.ends_with(".tmp") { - None - } else { - Some(entry) - } + if path_str.ends_with(".tmp") { None } else { Some(entry) } }) .collect() } diff --git a/lightning-block-sync/Cargo.toml b/lightning-block-sync/Cargo.toml index d8d71da3fae..48567157ee8 100644 --- a/lightning-block-sync/Cargo.toml +++ b/lightning-block-sync/Cargo.toml @@ -8,8 +8,8 @@ readme = "../README.md" description = """ Utilities to fetch the chain data from a block source and feed them into Rust Lightning. """ -edition = "2021" -rust-version = "1.75" +edition = "2024" +rust-version = "1.85" [package.metadata.docs.rs] all-features = true diff --git a/lightning-block-sync/src/convert.rs b/lightning-block-sync/src/convert.rs index 48a80c8cbf1..9c890544763 100644 --- a/lightning-block-sync/src/convert.rs +++ b/lightning-block-sync/src/convert.rs @@ -4,11 +4,11 @@ use crate::rpc::RpcClientError; use crate::utils::hex_to_work; use crate::{BlockHeaderData, BlockSourceError}; +use bitcoin::Transaction; use bitcoin::block::{Block, Header}; use bitcoin::consensus::encode; use bitcoin::hash_types::{BlockHash, TxMerkleNode, Txid}; use bitcoin::hex::FromHex; -use bitcoin::Transaction; use serde_json; @@ -336,8 +336,8 @@ pub(crate) mod tests { use bitcoin::hashes::Hash; use bitcoin::hex::DisplayHex; use bitcoin::network::Network; - use serde_json::value::Number; use serde_json::Value; + use serde_json::value::Number; /// Converts from `BlockHeaderData` into a `GetHeaderResponse` JSON value. impl From for serde_json::Value { diff --git a/lightning-block-sync/src/gossip.rs b/lightning-block-sync/src/gossip.rs index 477e2785782..89a2d306367 100644 --- a/lightning-block-sync/src/gossip.rs +++ b/lightning-block-sync/src/gossip.rs @@ -16,7 +16,7 @@ use lightning::util::wakers::Notifier; use std::collections::VecDeque; use std::future::Future; use std::ops::Deref; -use std::pin::{pin, Pin}; +use std::pin::{Pin, pin}; use std::sync::{Arc, Mutex}; use std::task::Poll; @@ -70,10 +70,10 @@ pub(crate) struct Joiner< } impl< - 'a, - A: Future), BlockSourceError>>, - B: Future>, - > Joiner<'a, A, B> + 'a, + A: Future), BlockSourceError>>, + B: Future>, +> Joiner<'a, A, B> { fn new(a: Pin<&'a mut A>, b: Pin<&'a mut B>) -> Self { Self { a, b, a_res: None, b_res: None } @@ -81,10 +81,10 @@ impl< } impl< - 'a, - A: Future), BlockSourceError>>, - B: Future>, - > Future for Joiner<'a, A, B> + 'a, + A: Future), BlockSourceError>>, + B: Future>, +> Future for Joiner<'a, A, B> { type Output = Result<((BlockHash, Option), BlockHash), BlockSourceError>; fn poll(mut self: Pin<&mut Self>, ctx: &mut core::task::Context<'_>) -> Poll { @@ -231,11 +231,7 @@ where } let outpoint_unspent = source.is_output_unspent(outpoint).await.map_err(|_| UtxoLookupError::UnknownTx)?; - if outpoint_unspent { - Ok(output) - } else { - Err(UtxoLookupError::UnknownTx) - } + if outpoint_unspent { Ok(output) } else { Err(UtxoLookupError::UnknownTx) } } } diff --git a/lightning-block-sync/src/init.rs b/lightning-block-sync/src/init.rs index b41489e0a28..2e8484d523f 100644 --- a/lightning-block-sync/src/init.rs +++ b/lightning-block-sync/src/init.rs @@ -198,14 +198,9 @@ where *result = Some((header.height, block)); } debug_assert!(fetched_blocks.iter().take(most_connected_blocks.len()).all(|r| r.is_some())); - // TODO: When our MSRV is 1.82, use is_sorted_by_key - debug_assert!(fetched_blocks.windows(2).all(|blocks| { - if let (Some(a), Some(b)) = (&blocks[0], &blocks[1]) { - a.0 < b.0 - } else { - // Any non-None blocks have to come before any None entries - blocks[1].is_none() - } + debug_assert!(fetched_blocks.iter().is_sorted_by_key(|block| match block { + Some((height, _)) => (false, *height), + None => (true, 0), })); for (listener_height, listener) in chain_listeners_at_height.iter() { diff --git a/lightning-block-sync/src/rest.rs b/lightning-block-sync/src/rest.rs index cdcf8424d2a..7a8c9b0879a 100644 --- a/lightning-block-sync/src/rest.rs +++ b/lightning-block-sync/src/rest.rs @@ -6,8 +6,8 @@ use crate::gossip::UtxoSource; use crate::http::{BinaryResponse, HttpClient, HttpClientError, JsonResponse, ToParseErrorMessage}; use crate::{BlockData, BlockHeaderData, BlockSource, BlockSourceResult}; -use bitcoin::hash_types::BlockHash; use bitcoin::OutPoint; +use bitcoin::hash_types::BlockHash; use std::convert::TryFrom; use std::convert::TryInto; diff --git a/lightning-block-sync/src/rpc.rs b/lightning-block-sync/src/rpc.rs index bfa1b31c84a..0924fc0662d 100644 --- a/lightning-block-sync/src/rpc.rs +++ b/lightning-block-sync/src/rpc.rs @@ -5,8 +5,8 @@ use crate::gossip::UtxoSource; use crate::http::{HttpClient, HttpClientError, JsonResponse, ToParseErrorMessage}; use crate::{BlockData, BlockHeaderData, BlockSource, BlockSourceResult}; -use bitcoin::hash_types::BlockHash; use bitcoin::OutPoint; +use bitcoin::hash_types::BlockHash; use serde_json; diff --git a/lightning-block-sync/src/test_utils.rs b/lightning-block-sync/src/test_utils.rs index 20ed6f0545e..3f0d75c8996 100644 --- a/lightning-block-sync/src/test_utils.rs +++ b/lightning-block-sync/src/test_utils.rs @@ -3,13 +3,13 @@ use crate::{ BlockData, BlockHeaderData, BlockSource, BlockSourceError, BlockSourceResult, HeaderCache, }; +use bitcoin::Transaction; use bitcoin::block::{Block, Header, Version}; use bitcoin::constants::genesis_block; use bitcoin::hash_types::{BlockHash, TxMerkleNode}; use bitcoin::locktime::absolute::LockTime; use bitcoin::network::Network; use bitcoin::transaction; -use bitcoin::Transaction; use lightning::chain; use lightning::chain::BlockLocator; diff --git a/lightning-custom-message/Cargo.toml b/lightning-custom-message/Cargo.toml index 854127f9175..a94f9b92105 100644 --- a/lightning-custom-message/Cargo.toml +++ b/lightning-custom-message/Cargo.toml @@ -8,8 +8,8 @@ readme = "../README.md" description = """ Utilities for supporting custom peer-to-peer messages in LDK. """ -edition = "2021" -rust-version = "1.75" +edition = "2024" +rust-version = "1.85" [package.metadata.docs.rs] all-features = true diff --git a/lightning-dns-resolver/Cargo.toml b/lightning-dns-resolver/Cargo.toml index 5299b2f4676..ebdb6815b1e 100644 --- a/lightning-dns-resolver/Cargo.toml +++ b/lightning-dns-resolver/Cargo.toml @@ -6,8 +6,8 @@ license = "MIT OR Apache-2.0" repository = "https://github.com/lightningdevkit/rust-lightning/" readme = "../README.md" description = "A crate which implements DNSSEC resolution for lightning clients over bLIP 32 using `tokio` and the `dnssec-prover` crate." -edition = "2021" -rust-version = "1.75" +edition = "2024" +rust-version = "1.85" [dependencies] lightning = { version = "0.3.0", path = "../lightning", default-features = false } diff --git a/lightning-dns-resolver/src/lib.rs b/lightning-dns-resolver/src/lib.rs index 90f1ac01f02..5d7fb517a2e 100644 --- a/lightning-dns-resolver/src/lib.rs +++ b/lightning-dns-resolver/src/lib.rs @@ -148,10 +148,10 @@ mod test { use bitcoin::secp256k1::{self, PublicKey, Secp256k1}; + use lightning::blinded_path::NodeIdLookUp; use lightning::blinded_path::message::{ BlindedMessagePath, MessageContext, MessageForwardNode, }; - use lightning::blinded_path::NodeIdLookUp; use lightning::ln::channelmanager::PaymentId; use lightning::ln::msgs::{BaseMessageHandler, Init, OnionMessageHandler}; use lightning::onion_message::dns_resolution::{HumanReadableName, OMNameResolver}; diff --git a/lightning-invoice/Cargo.toml b/lightning-invoice/Cargo.toml index 2b5d570f43f..20780249307 100644 --- a/lightning-invoice/Cargo.toml +++ b/lightning-invoice/Cargo.toml @@ -8,8 +8,8 @@ license = "MIT OR Apache-2.0" keywords = [ "lightning", "bitcoin", "invoice", "BOLT11" ] readme = "README.md" repository = "https://github.com/lightningdevkit/rust-lightning/" -edition = "2021" -rust-version = "1.75" +edition = "2024" +rust-version = "1.85" [package.metadata.docs.rs] all-features = true diff --git a/lightning-invoice/src/de.rs b/lightning-invoice/src/de.rs index f1bbe29440a..ca3c21899d7 100644 --- a/lightning-invoice/src/de.rs +++ b/lightning-invoice/src/de.rs @@ -11,22 +11,23 @@ use std::error; use bech32::primitives::decode::{CheckedHrpstring, CheckedHrpstringError}; use bech32::{Fe32, Fe32IterExt}; -use crate::prelude::*; use crate::Bolt11Bech32; -use bitcoin::hashes::sha256; +use crate::prelude::*; use bitcoin::hashes::Hash; +use bitcoin::hashes::sha256; use bitcoin::{PubkeyHash, ScriptHash, WitnessVersion}; use lightning_types::payment::{PaymentHash, PaymentSecret}; use lightning_types::routing::{RouteHint, RouteHintHop, RoutingFees}; -use bitcoin::secp256k1::ecdsa::{RecoverableSignature, RecoveryId}; use bitcoin::secp256k1::PublicKey; +use bitcoin::secp256k1::ecdsa::{RecoverableSignature, RecoveryId}; use super::{ - constants, Bolt11Invoice, Bolt11InvoiceFeatures, Bolt11InvoiceSignature, Bolt11ParseError, + Bolt11Invoice, Bolt11InvoiceFeatures, Bolt11InvoiceSignature, Bolt11ParseError, Bolt11SemanticError, Currency, Description, ExpiryTime, Fallback, MinFinalCltvExpiryDelta, ParseOrSemanticError, PayeePubKey, PositiveTimestamp, PrivateRoute, RawBolt11Invoice, RawDataPart, RawHrp, RawTaggedField, Sha256, SiPrefix, SignedRawBolt11Invoice, TaggedField, + constants, }; use self::hrp_sm::parse_hrp; @@ -1099,20 +1100,22 @@ mod test { }, data: RawDataPart { timestamp: PositiveTimestamp::from_unix_timestamp(1496314658).unwrap(), - tagged_fields: vec ! [ - crate::TaggedField::PaymentHash(crate::PaymentHash( - <[u8; 32]>::try_from( - Vec::from_hex( - "0001020304050607080900010203040506070809000102030405060708090102", - ) - .unwrap(), - ) - .unwrap(), - )) - .into(), - Description(crate::Description::new("coffee beans".to_owned()).unwrap()).into(), - PaymentSecret(crate::PaymentSecret([17; 32])).into(), - Features(expected_features).into()], + tagged_fields: vec![ + crate::TaggedField::PaymentHash(crate::PaymentHash( + <[u8; 32]>::try_from( + Vec::from_hex( + "0001020304050607080900010203040506070809000102030405060708090102", + ) + .unwrap(), + ) + .unwrap(), + )) + .into(), + Description(crate::Description::new("coffee beans".to_owned()).unwrap()) + .into(), + PaymentSecret(crate::PaymentSecret([17; 32])).into(), + Features(expected_features).into(), + ], }, }, hash: [ @@ -1236,7 +1239,7 @@ mod test { qqqqqqqqp9a5vs0t4z56p64xyma8s84yvdx7uhqj0gvrr424fea2wpztq2fwqqqqqqqqqqqqqqqqqqqqqqqqqq\ qqqqmy9qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq\ qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqpcnsxc32du9n7amlypuhclzqrt6lkegq\ - 0v3r7nczjv9tv30z7phq80r3dm7pvgykl7gwuenmem93h5xwdwac6ngsmzqc34khrg3qjgsq6qk6lc" + 0v3r7nczjv9tv30z7phq80r3dm7pvgykl7gwuenmem93h5xwdwac6ngsmzqc34khrg3qjgsq6qk6lc", ); // 1517 B mainnet invoice from Lexe proptest parse_ok( @@ -1257,7 +1260,7 @@ mod test { ccadacjtn52lpe6s85rjfqlxzp6frq33xshaz2nr9xjkhd3jj8qg39nmfzvpgmayakqmy9rseakwgcudug7hs4\ 5wh430ywh7qhj3khczh8gle4cn93ymgfwa7rrvcw9lywyyz58k4p40a3nu9svthaf0qeg8f2ay4tw9p48p70qm\ ayu3ejl2q8pj9e2l22h7775tl44hs6ke4sdfgcr6aj8wra4r2v9sj6xa5chd5ctpfg8chtrer3kkp0e6af88lk\ - rfxcklf2hyslv2hr0xl5lwrm5y5uttxn4ndfz8789znf78nspa3xy68" + rfxcklf2hyslv2hr0xl5lwrm5y5uttxn4ndfz8789znf78nspa3xy68", ); // 1804 B regtest invoice from Lexe proptest parse_ok( @@ -1281,7 +1284,7 @@ mod test { zen7e2qmsdauk665g3llg5qtl79t3xulrhjnducehdn72gpmkjvtth7kh6ejpl9dv0qcsxv2jvzzvg0hzdmk3y\ jsmydqksdk3h78kc63qnr265h8vyeslqexszppfm7y287t3gxvhw0ulg2wp0rsw3tevz03z50kpy77zdz9snxm\ kkwxd76xvj4qvj2f89rrnuvdvzw947ay0kydc077pkec2jet9qwp2tud98s24u65uz07eaxk5jk3e4nggn2caa\ - ek2p5pkrc6mm6mxjm2ezpdu8p5jstg6tgvnttgac3ygt5ys04t4udujzlshpl7e4f3ff03xe6v24cp6aq4wa" + ek2p5pkrc6mm6mxjm2ezpdu8p5jstg6tgvnttgac3ygt5ys04t4udujzlshpl7e4f3ff03xe6v24cp6aq4wa", ); // 1870 B testnet invoice from Lexe proptest parse_ok( @@ -1306,7 +1309,7 @@ mod test { z38cnwl9ma6m5f4nhzqaj0tjxpfrk4nr5arv9d20lvxvddvffhzygmyuvwd959uhdcgcgjejchqt2qncuwpqqk\ 5vws7dflw8x6esrfwhz7h3jwmhevf445k76nme926sr8drsdveqg7l7t7lnjvhaludqnwk4l2pmevkjf9pla92\ 4p77v76r7x8jzyy7h59hmk0lgzfsk6c8dpj37hssj7jt4q7jzvy8hq25l3pag37axxanjqnq56c47gpgy6frsy\ - c0str9w2aahz4h6t7axaka4cwvhwg49r6qgj8kwz2mt6vcje25l9ekvmgq5spqtn" + c0str9w2aahz4h6t7axaka4cwvhwg49r6qgj8kwz2mt6vcje25l9ekvmgq5spqtn", ); } @@ -1320,8 +1323,8 @@ mod test { SignedRawBolt11Invoice, }; use bitcoin::hex::FromHex; - use bitcoin::secp256k1::ecdsa::{RecoverableSignature, RecoveryId}; use bitcoin::secp256k1::PublicKey; + use bitcoin::secp256k1::ecdsa::{RecoverableSignature, RecoveryId}; use lightning_types::routing::{RouteHint, RouteHintHop, RoutingFees}; // Generate an `UnknownSemantics` field with a given length. @@ -1425,7 +1428,7 @@ mod test { // Test that invoices above the maximum length fail to parse with the expected error. #[test] fn test_deser_too_long_fails() { - use crate::{Bolt11Invoice, ParseOrSemanticError, MAX_LENGTH}; + use crate::{Bolt11Invoice, MAX_LENGTH, ParseOrSemanticError}; use bech32::primitives::decode::{CheckedHrpstringError, ChecksumError}; fn parse_is_code_length_err(s: &str) -> bool { diff --git a/lightning-invoice/src/lib.rs b/lightning-invoice/src/lib.rs index 4ee9acb5f27..89e621b5b88 100644 --- a/lightning-invoice/src/lib.rs +++ b/lightning-invoice/src/lib.rs @@ -32,12 +32,12 @@ use std::time::SystemTime; use bech32::primitives::decode::CheckedHrpstringError; use bech32::{Checksum, Fe32}; -use bitcoin::hashes::{sha256, Hash}; +use bitcoin::hashes::{Hash, sha256}; use bitcoin::{Address, Network, PubkeyHash, ScriptHash, WitnessProgram, WitnessVersion}; use lightning_types::features::Bolt11InvoiceFeatures; -use bitcoin::secp256k1::ecdsa::RecoverableSignature; use bitcoin::secp256k1::PublicKey; +use bitcoin::secp256k1::ecdsa::RecoverableSignature; use bitcoin::secp256k1::{Message, Secp256k1}; use alloc::string; @@ -51,7 +51,7 @@ use core::str::FromStr; use core::time::Duration; #[cfg(feature = "serde")] -use serde::{de::Error, Deserialize, Deserializer, Serialize, Serializer}; +use serde::{Deserialize, Deserializer, Serialize, Serializer, de::Error}; #[doc(no_inline)] pub use lightning_types::payment::{PaymentHash, PaymentSecret}; @@ -496,10 +496,8 @@ impl PartialOrd for RawTaggedField { impl Ord for RawTaggedField { fn cmp(&self, other: &Self) -> core::cmp::Ordering { match (self, other) { - (RawTaggedField::KnownSemantics(ref a), RawTaggedField::KnownSemantics(ref b)) => { - a.cmp(b) - }, - (RawTaggedField::UnknownSemantics(ref a), RawTaggedField::UnknownSemantics(ref b)) => { + (RawTaggedField::KnownSemantics(a), RawTaggedField::KnownSemantics(b)) => a.cmp(b), + (RawTaggedField::UnknownSemantics(a), RawTaggedField::UnknownSemantics(b)) => { a.iter().map(|a| a.to_u8()).cmp(b.iter().map(|b| b.to_u8())) }, (RawTaggedField::KnownSemantics(..), RawTaggedField::UnknownSemantics(..)) => { @@ -773,7 +771,7 @@ impl self, description: Bolt11InvoiceDescription, ) -> InvoiceBuilder { match description { - Bolt11InvoiceDescription::Direct(desc) => self.description(desc.0 .0), + Bolt11InvoiceDescription::Direct(desc) => self.description(desc.0.0), Bolt11InvoiceDescription::Hash(hash) => self.description_hash(hash.0), } } @@ -783,7 +781,7 @@ impl self, description_ref: Bolt11InvoiceDescriptionRef<'_>, ) -> InvoiceBuilder { match description_ref { - Bolt11InvoiceDescriptionRef::Direct(desc) => self.description(desc.clone().0 .0), + Bolt11InvoiceDescriptionRef::Direct(desc) => self.description(desc.clone().0.0), Bolt11InvoiceDescriptionRef::Hash(hash) => self.description_hash(hash.0), } } @@ -1743,11 +1741,7 @@ impl ExpiryTime { impl PrivateRoute { /// Creates a new (partial) route from a list of hops pub fn new(hops: RouteHint) -> Result { - if hops.0.len() <= 12 { - Ok(PrivateRoute(hops)) - } else { - Err(CreationError::RouteTooLong) - } + if hops.0.len() <= 12 { Ok(PrivateRoute(hops)) } else { Err(CreationError::RouteTooLong) } } /// Returns the underlying list of hops @@ -1813,13 +1807,24 @@ pub enum CreationError { impl Display for CreationError { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { match self { - CreationError::DescriptionTooLong => f.write_str("The supplied description string was longer than 639 bytes"), - CreationError::RouteTooLong => f.write_str("The specified route has too many hops and can't be encoded"), - CreationError::TimestampOutOfBounds => f.write_str("The Unix timestamp of the supplied date is less than zero or greater than 35-bits"), - CreationError::InvalidAmount => f.write_str("The supplied millisatoshi amount was greater than the total bitcoin supply"), - CreationError::MissingRouteHints => f.write_str("The invoice required route hints and they weren't provided"), + CreationError::DescriptionTooLong => { + f.write_str("The supplied description string was longer than 639 bytes") + }, + CreationError::RouteTooLong => { + f.write_str("The specified route has too many hops and can't be encoded") + }, + CreationError::TimestampOutOfBounds => f.write_str( + "The Unix timestamp of the supplied date is less than zero or greater than 35-bits", + ), + CreationError::InvalidAmount => f.write_str( + "The supplied millisatoshi amount was greater than the total bitcoin supply", + ), + CreationError::MissingRouteHints => { + f.write_str("The invoice required route hints and they weren't provided") + }, CreationError::MinFinalCltvExpiryDeltaTooShort => f.write_str( - "The supplied final CLTV expiry delta was less than LDK's `MIN_FINAL_CLTV_EXPIRY_DELTA`"), + "The supplied final CLTV expiry delta was less than LDK's `MIN_FINAL_CLTV_EXPIRY_DELTA`", + ), } } } @@ -1863,15 +1868,33 @@ pub enum Bolt11SemanticError { impl Display for Bolt11SemanticError { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { match self { - Bolt11SemanticError::NoPaymentHash => f.write_str("The invoice is missing the mandatory payment hash"), - Bolt11SemanticError::MultiplePaymentHashes => f.write_str("The invoice has multiple payment hashes which isn't allowed"), - Bolt11SemanticError::NoDescription => f.write_str("No description or description hash are part of the invoice"), - Bolt11SemanticError::MultipleDescriptions => f.write_str("The invoice contains multiple descriptions and/or description hashes which isn't allowed"), - Bolt11SemanticError::NoPaymentSecret => f.write_str("The invoice is missing the mandatory payment secret"), - Bolt11SemanticError::MultiplePaymentSecrets => f.write_str("The invoice contains multiple payment secrets"), - Bolt11SemanticError::InvalidFeatures => f.write_str("The invoice's features are invalid"), - Bolt11SemanticError::InvalidSignature => f.write_str("The invoice's signature is invalid"), - Bolt11SemanticError::ImpreciseAmount => f.write_str("The invoice's amount was not a whole number of millisatoshis"), + Bolt11SemanticError::NoPaymentHash => { + f.write_str("The invoice is missing the mandatory payment hash") + }, + Bolt11SemanticError::MultiplePaymentHashes => { + f.write_str("The invoice has multiple payment hashes which isn't allowed") + }, + Bolt11SemanticError::NoDescription => { + f.write_str("No description or description hash are part of the invoice") + }, + Bolt11SemanticError::MultipleDescriptions => f.write_str( + "The invoice contains multiple descriptions and/or description hashes which isn't allowed", + ), + Bolt11SemanticError::NoPaymentSecret => { + f.write_str("The invoice is missing the mandatory payment secret") + }, + Bolt11SemanticError::MultiplePaymentSecrets => { + f.write_str("The invoice contains multiple payment secrets") + }, + Bolt11SemanticError::InvalidFeatures => { + f.write_str("The invoice's features are invalid") + }, + Bolt11SemanticError::InvalidSignature => { + f.write_str("The invoice's signature is invalid") + }, + Bolt11SemanticError::ImpreciseAmount => { + f.write_str("The invoice's amount was not a whole number of millisatoshis") + }, } } } @@ -1984,8 +2007,8 @@ mod test { RawDataPart, RawHrp, SignedRawBolt11Invoice, }; use bitcoin::hex::FromHex; - use bitcoin::secp256k1::ecdsa::{RecoverableSignature, RecoveryId}; use bitcoin::secp256k1::Secp256k1; + use bitcoin::secp256k1::ecdsa::{RecoverableSignature, RecoveryId}; use bitcoin::secp256k1::{PublicKey, SecretKey}; let invoice = SignedRawBolt11Invoice { @@ -1993,7 +2016,7 @@ mod test { hrp: RawHrp { currency: Currency::Bitcoin, raw_amount: None, si_prefix: None }, data: RawDataPart { timestamp: PositiveTimestamp::from_unix_timestamp(1496314658).unwrap(), - tagged_fields: vec ! [ + tagged_fields: vec![ crate::TaggedField::PaymentHash(PaymentHash( <[u8; 32]>::try_from( Vec::from_hex( @@ -2006,9 +2029,11 @@ mod test { .into(), Description( crate::Description::new( - "Please consider supporting this project".to_owned() - ).unwrap() - ).into(), + "Please consider supporting this project".to_owned(), + ) + .unwrap(), + ) + .into(), ], }, }, diff --git a/lightning-invoice/src/ser.rs b/lightning-invoice/src/ser.rs index 35d5dc024ea..9fd48a06d32 100644 --- a/lightning-invoice/src/ser.rs +++ b/lightning-invoice/src/ser.rs @@ -6,10 +6,10 @@ use crate::prelude::*; use bech32::{ByteIterExt, Fe32, Fe32IterExt}; use super::{ - constants, Bolt11Invoice, Bolt11InvoiceFeatures, Bolt11InvoiceSignature, Currency, Description, + Bolt11Invoice, Bolt11InvoiceFeatures, Bolt11InvoiceSignature, Currency, Description, ExpiryTime, Fallback, MinFinalCltvExpiryDelta, PayeePubKey, PaymentHash, PaymentSecret, PositiveTimestamp, PrivateRoute, RawDataPart, RawHrp, RawTaggedField, RouteHintHop, Sha256, - SiPrefix, SignedRawBolt11Invoice, TaggedField, + SiPrefix, SignedRawBolt11Invoice, TaggedField, constants, }; macro_rules! define_iterator_enum { @@ -306,13 +306,13 @@ impl Base32Len for Sha256 { impl Base32Iterable for Description { fn fe_iter<'s>(&'s self) -> impl Iterator + 's { - self.0 .0.as_bytes().fe_iter() + self.0.0.as_bytes().fe_iter() } } impl Base32Len for Description { fn base32_len(&self) -> usize { - self.0 .0.as_bytes().base32_len() + self.0.0.as_bytes().base32_len() } } @@ -405,7 +405,7 @@ impl Base32Iterable for PrivateRoute { i1.chain(i2).chain(i3).chain(i4).chain(i5) } - self.0 .0.iter().map(serialize_to_iter).flatten().bytes_to_fes() + self.0.0.iter().map(serialize_to_iter).flatten().bytes_to_fes() } } diff --git a/lightning-invoice/src/test_ser_de.rs b/lightning-invoice/src/test_ser_de.rs index efeed83980e..6146fe3cb06 100644 --- a/lightning-invoice/src/test_ser_de.rs +++ b/lightning-invoice/src/test_ser_de.rs @@ -1,8 +1,8 @@ use crate::de::FromBase32; use crate::ser::{Base32Iterable, Base32Len}; use crate::{ - sha256, PayeePubKey, PaymentHash, PaymentSecret, PositiveTimestamp, RawDataPart, - RawTaggedField, Sha256, TaggedField, + PayeePubKey, PaymentHash, PaymentSecret, PositiveTimestamp, RawDataPart, RawTaggedField, + Sha256, TaggedField, sha256, }; use bech32::Fe32; use bitcoin::hex::FromHex; diff --git a/lightning-invoice/tests/ser_de.rs b/lightning-invoice/tests/ser_de.rs index 353878a9c52..11e459581be 100644 --- a/lightning-invoice/tests/ser_de.rs +++ b/lightning-invoice/tests/ser_de.rs @@ -1,10 +1,10 @@ extern crate bech32; extern crate lightning_invoice; -use bitcoin::hashes::{sha256, Hash}; +use bitcoin::hashes::{Hash, sha256}; use bitcoin::hex::FromHex; -use bitcoin::secp256k1::ecdsa::{RecoverableSignature, RecoveryId}; use bitcoin::secp256k1::PublicKey; +use bitcoin::secp256k1::ecdsa::{RecoverableSignature, RecoveryId}; use bitcoin::{PubkeyHash, ScriptHash, WitnessVersion}; use lightning_invoice::*; use std::collections::HashSet; @@ -527,13 +527,8 @@ fn invoice_deserialize() { }); } if ignore_unknown_fields { - parsed_hunks.retain(|h| { - if let RawTaggedField::UnknownSemantics(_) = h { - false - } else { - true - } - }); + parsed_hunks + .retain(|h| if let RawTaggedField::UnknownSemantics(_) = h { false } else { true }); } assert_eq!(deserialized_hunks, parsed_hunks); @@ -548,28 +543,60 @@ fn test_bolt_invalid_invoices() { }; // Tests the BOLT 11 invalid invoice test vectors - assert_eq!(Bolt11Invoice::from_str( - "lnbc25m1pvjluezpp5qqqsyqcyq5rqwzqfqqqsyqcyq5rqwzqfqqqsyqcyq5rqwzqfqypqdq5vdhkven9v5sxyetpdeessp5zyg3zyg3zyg3zyg3zyg3zyg3zyg3zyg3zyg3zyg3zyg3zyg3zygs9q4psqqqqqqqqqqqqqqqqsgqtqyx5vggfcsll4wu246hz02kp85x4katwsk9639we5n5yngc3yhqkm35jnjw4len8vrnqnf5ejh0mzj9n3vz2px97evektfm2l6wqccp3y7372" - ), Err(ParseOrSemanticError::SemanticError(Bolt11SemanticError::InvalidFeatures))); - assert_eq!(Bolt11Invoice::from_str( - "lnbc2500u1pvjluezpp5qqqsyqcyq5rqwzqfqqqsyqcyq5rqwzqfqqqsyqcyq5rqwzqfqypqdpquwpc4curk03c9wlrswe78q4eyqc7d8d0xqzpuyk0sg5g70me25alkluzd2x62aysf2pyy8edtjeevuv4p2d5p76r4zkmneet7uvyakky2zr4cusd45tftc9c5fh0nnqpnl2jfll544esqchsrnt" - ), Err(ParseOrSemanticError::ParseError(Bolt11ParseError::Bech32Error(CheckedHrpstringError::Checksum(ChecksumError::InvalidResidue))))); - assert_eq!(Bolt11Invoice::from_str( - "pvjluezpp5qqqsyqcyq5rqwzqfqqqsyqcyq5rqwzqfqqqsyqcyq5rqwzqfqypqdpquwpc4curk03c9wlrswe78q4eyqc7d8d0xqzpuyk0sg5g70me25alkluzd2x62aysf2pyy8edtjeevuv4p2d5p76r4zkmneet7uvyakky2zr4cusd45tftc9c5fh0nnqpnl2jfll544esqchsrny" - ), Err(ParseOrSemanticError::ParseError(Bolt11ParseError::Bech32Error(CheckedHrpstringError::Parse(UncheckedHrpstringError::Char(CharError::MissingSeparator)))))); - assert_eq!(Bolt11Invoice::from_str( - "LNBC2500u1pvjluezpp5qqqsyqcyq5rqwzqfqqqsyqcyq5rqwzqfqqqsyqcyq5rqwzqfqypqdpquwpc4curk03c9wlrswe78q4eyqc7d8d0xqzpuyk0sg5g70me25alkluzd2x62aysf2pyy8edtjeevuv4p2d5p76r4zkmneet7uvyakky2zr4cusd45tftc9c5fh0nnqpnl2jfll544esqchsrny" - ), Err(ParseOrSemanticError::ParseError(Bolt11ParseError::Bech32Error(CheckedHrpstringError::Parse(UncheckedHrpstringError::Char(CharError::MixedCase)))))); - assert_eq!(Bolt11Invoice::from_str( - "lnbc2500u1pvjluezpp5qqqsyqcyq5rqwzqfqqqsyqcyq5rqwzqfqqqsyqcyq5rqwzqfqypqdq5xysxxatsyp3k7enxv4jsxqzpusp5zyg3zyg3zyg3zyg3zyg3zyg3zyg3zyg3zyg3zyg3zyg3zyg3zygs9qrsgqwgt7mcn5yqw3yx0w94pswkpq6j9uh6xfqqqtsk4tnarugeektd4hg5975x9am52rz4qskukxdmjemg92vvqz8nvmsye63r5ykel43pgz7zq0g2" - ), Err(ParseOrSemanticError::SemanticError(Bolt11SemanticError::InvalidSignature))); - assert_eq!(Bolt11Invoice::from_str( - "lnbc1pvjluezpp5qqqsyqcyq5rqwzqfqqqsyqcyq5rqwzqfqqqsyqcyq5rqwzqfqypqdpl2pkx2ctnv5sxxmmwwd5kgetjypeh2ursdae8g6na6hlh" - ), Err(ParseOrSemanticError::ParseError(Bolt11ParseError::TooShortDataPart))); - assert_eq!(Bolt11Invoice::from_str( - "lnbc2500x1pvjluezpp5qqqsyqcyq5rqwzqfqqqsyqcyq5rqwzqfqqqsyqcyq5rqwzqfqypqdq5xysxxatsyp3k7enxv4jsxqzpusp5zyg3zyg3zyg3zyg3zyg3zyg3zyg3zyg3zyg3zyg3zyg3zyg3zygs9qrsgqrrzc4cvfue4zp3hggxp47ag7xnrlr8vgcmkjxk3j5jqethnumgkpqp23z9jclu3v0a7e0aruz366e9wqdykw6dxhdzcjjhldxq0w6wgqcnu43j" - ), Err(ParseOrSemanticError::ParseError(Bolt11ParseError::UnknownSiPrefix))); - assert_eq!(Bolt11Invoice::from_str( - "lnbc2500000001p1pvjluezpp5qqqsyqcyq5rqwzqfqqqsyqcyq5rqwzqfqqqsyqcyq5rqwzqfqypqdq5xysxxatsyp3k7enxv4jsxqzpusp5zyg3zyg3zyg3zyg3zyg3zyg3zyg3zyg3zyg3zyg3zyg3zyg3zygs9qrsgq0lzc236j96a95uv0m3umg28gclm5lqxtqqwk32uuk4k6673k6n5kfvx3d2h8s295fad45fdhmusm8sjudfhlf6dcsxmfvkeywmjdkxcp99202x" - ), Err(ParseOrSemanticError::SemanticError(Bolt11SemanticError::ImpreciseAmount))); + assert_eq!( + Bolt11Invoice::from_str( + "lnbc25m1pvjluezpp5qqqsyqcyq5rqwzqfqqqsyqcyq5rqwzqfqqqsyqcyq5rqwzqfqypqdq5vdhkven9v5sxyetpdeessp5zyg3zyg3zyg3zyg3zyg3zyg3zyg3zyg3zyg3zyg3zyg3zyg3zygs9q4psqqqqqqqqqqqqqqqqsgqtqyx5vggfcsll4wu246hz02kp85x4katwsk9639we5n5yngc3yhqkm35jnjw4len8vrnqnf5ejh0mzj9n3vz2px97evektfm2l6wqccp3y7372" + ), + Err(ParseOrSemanticError::SemanticError(Bolt11SemanticError::InvalidFeatures)) + ); + assert_eq!( + Bolt11Invoice::from_str( + "lnbc2500u1pvjluezpp5qqqsyqcyq5rqwzqfqqqsyqcyq5rqwzqfqqqsyqcyq5rqwzqfqypqdpquwpc4curk03c9wlrswe78q4eyqc7d8d0xqzpuyk0sg5g70me25alkluzd2x62aysf2pyy8edtjeevuv4p2d5p76r4zkmneet7uvyakky2zr4cusd45tftc9c5fh0nnqpnl2jfll544esqchsrnt" + ), + Err(ParseOrSemanticError::ParseError(Bolt11ParseError::Bech32Error( + CheckedHrpstringError::Checksum(ChecksumError::InvalidResidue) + ))) + ); + assert_eq!( + Bolt11Invoice::from_str( + "pvjluezpp5qqqsyqcyq5rqwzqfqqqsyqcyq5rqwzqfqqqsyqcyq5rqwzqfqypqdpquwpc4curk03c9wlrswe78q4eyqc7d8d0xqzpuyk0sg5g70me25alkluzd2x62aysf2pyy8edtjeevuv4p2d5p76r4zkmneet7uvyakky2zr4cusd45tftc9c5fh0nnqpnl2jfll544esqchsrny" + ), + Err(ParseOrSemanticError::ParseError(Bolt11ParseError::Bech32Error( + CheckedHrpstringError::Parse(UncheckedHrpstringError::Char( + CharError::MissingSeparator + )) + ))) + ); + assert_eq!( + Bolt11Invoice::from_str( + "LNBC2500u1pvjluezpp5qqqsyqcyq5rqwzqfqqqsyqcyq5rqwzqfqqqsyqcyq5rqwzqfqypqdpquwpc4curk03c9wlrswe78q4eyqc7d8d0xqzpuyk0sg5g70me25alkluzd2x62aysf2pyy8edtjeevuv4p2d5p76r4zkmneet7uvyakky2zr4cusd45tftc9c5fh0nnqpnl2jfll544esqchsrny" + ), + Err(ParseOrSemanticError::ParseError(Bolt11ParseError::Bech32Error( + CheckedHrpstringError::Parse(UncheckedHrpstringError::Char(CharError::MixedCase)) + ))) + ); + assert_eq!( + Bolt11Invoice::from_str( + "lnbc2500u1pvjluezpp5qqqsyqcyq5rqwzqfqqqsyqcyq5rqwzqfqqqsyqcyq5rqwzqfqypqdq5xysxxatsyp3k7enxv4jsxqzpusp5zyg3zyg3zyg3zyg3zyg3zyg3zyg3zyg3zyg3zyg3zyg3zyg3zygs9qrsgqwgt7mcn5yqw3yx0w94pswkpq6j9uh6xfqqqtsk4tnarugeektd4hg5975x9am52rz4qskukxdmjemg92vvqz8nvmsye63r5ykel43pgz7zq0g2" + ), + Err(ParseOrSemanticError::SemanticError(Bolt11SemanticError::InvalidSignature)) + ); + assert_eq!( + Bolt11Invoice::from_str( + "lnbc1pvjluezpp5qqqsyqcyq5rqwzqfqqqsyqcyq5rqwzqfqqqsyqcyq5rqwzqfqypqdpl2pkx2ctnv5sxxmmwwd5kgetjypeh2ursdae8g6na6hlh" + ), + Err(ParseOrSemanticError::ParseError(Bolt11ParseError::TooShortDataPart)) + ); + assert_eq!( + Bolt11Invoice::from_str( + "lnbc2500x1pvjluezpp5qqqsyqcyq5rqwzqfqqqsyqcyq5rqwzqfqqqsyqcyq5rqwzqfqypqdq5xysxxatsyp3k7enxv4jsxqzpusp5zyg3zyg3zyg3zyg3zyg3zyg3zyg3zyg3zyg3zyg3zyg3zyg3zygs9qrsgqrrzc4cvfue4zp3hggxp47ag7xnrlr8vgcmkjxk3j5jqethnumgkpqp23z9jclu3v0a7e0aruz366e9wqdykw6dxhdzcjjhldxq0w6wgqcnu43j" + ), + Err(ParseOrSemanticError::ParseError(Bolt11ParseError::UnknownSiPrefix)) + ); + assert_eq!( + Bolt11Invoice::from_str( + "lnbc2500000001p1pvjluezpp5qqqsyqcyq5rqwzqfqqqsyqcyq5rqwzqfqqqsyqcyq5rqwzqfqypqdq5xysxxatsyp3k7enxv4jsxqzpusp5zyg3zyg3zyg3zyg3zyg3zyg3zyg3zyg3zyg3zyg3zyg3zyg3zygs9qrsgq0lzc236j96a95uv0m3umg28gclm5lqxtqqwk32uuk4k6673k6n5kfvx3d2h8s295fad45fdhmusm8sjudfhlf6dcsxmfvkeywmjdkxcp99202x" + ), + Err(ParseOrSemanticError::SemanticError(Bolt11SemanticError::ImpreciseAmount)) + ); } diff --git a/lightning-liquidity/Cargo.toml b/lightning-liquidity/Cargo.toml index 9b8114e47aa..1449c1198b2 100644 --- a/lightning-liquidity/Cargo.toml +++ b/lightning-liquidity/Cargo.toml @@ -4,8 +4,8 @@ version = "0.3.0+git" authors = ["John Cantrell ", "Elias Rohrer "] homepage = "https://lightningdevkit.org/" license = "MIT OR Apache-2.0" -edition = "2021" -rust-version = "1.75" +edition = "2024" +rust-version = "1.85" description = "Types and primitives to integrate a spec-compliant LSP with an LDK-based node." repository = "https://github.com/lightningdevkit/lightning-liquidity/" readme = "README.md" diff --git a/lightning-liquidity/src/lsps0/client.rs b/lightning-liquidity/src/lsps0/client.rs index 298cb304b51..e5b1c265b8f 100644 --- a/lightning-liquidity/src/lsps0/client.rs +++ b/lightning-liquidity/src/lsps0/client.rs @@ -97,7 +97,13 @@ impl LSPSProtocolMessageHandler false, "Client handler received LSPS0 request message. This should never happen." ); - Err(LightningError { err: format!("Client handler received LSPS0 request message from node {}. This should never happen.", counterparty_node_id), action: ErrorAction::IgnoreAndLog(Level::Info)}) + Err(LightningError { + err: format!( + "Client handler received LSPS0 request message from node {}. This should never happen.", + counterparty_node_id + ), + action: ErrorAction::IgnoreAndLog(Level::Info), + }) }, } } diff --git a/lightning-liquidity/src/lsps0/ser.rs b/lightning-liquidity/src/lsps0/ser.rs index 70649fe0f50..7d0470fd703 100644 --- a/lightning-liquidity/src/lsps0/ser.rs +++ b/lightning-liquidity/src/lsps0/ser.rs @@ -10,20 +10,20 @@ use core::fmt::{self, Display}; use core::str::FromStr; use crate::lsps0::msgs::{ - LSPS0ListProtocolsRequest, LSPS0Message, LSPS0Request, LSPS0Response, - LSPS0_LISTPROTOCOLS_METHOD_NAME, + LSPS0_LISTPROTOCOLS_METHOD_NAME, LSPS0ListProtocolsRequest, LSPS0Message, LSPS0Request, + LSPS0Response, }; use crate::lsps1::msgs::{ - LSPS1Message, LSPS1Request, LSPS1Response, LSPS1_CREATE_ORDER_METHOD_NAME, - LSPS1_GET_INFO_METHOD_NAME, LSPS1_GET_ORDER_METHOD_NAME, + LSPS1_CREATE_ORDER_METHOD_NAME, LSPS1_GET_INFO_METHOD_NAME, LSPS1_GET_ORDER_METHOD_NAME, + LSPS1Message, LSPS1Request, LSPS1Response, }; use crate::lsps2::msgs::{ - LSPS2Message, LSPS2Request, LSPS2Response, LSPS2_BUY_METHOD_NAME, LSPS2_GET_INFO_METHOD_NAME, + LSPS2_BUY_METHOD_NAME, LSPS2_GET_INFO_METHOD_NAME, LSPS2Message, LSPS2Request, LSPS2Response, }; use crate::lsps5::msgs::{ - LSPS5Message, LSPS5Request, LSPS5Response, LSPS5_LIST_WEBHOOKS_METHOD_NAME, - LSPS5_REMOVE_WEBHOOK_METHOD_NAME, LSPS5_SET_WEBHOOK_METHOD_NAME, + LSPS5_LIST_WEBHOOKS_METHOD_NAME, LSPS5_REMOVE_WEBHOOK_METHOD_NAME, + LSPS5_SET_WEBHOOK_METHOD_NAME, LSPS5Message, LSPS5Request, LSPS5Response, }; use crate::prelude::HashMap; @@ -664,7 +664,9 @@ impl<'de, 'a> Visitor<'de> for LSPSMessageVisitor<'a> { LSPS0Response::ListProtocols(list_protocols_response), ))) } else { - Err(de::Error::custom("Received invalid JSON-RPC object: one of method, result, or error required")) + Err(de::Error::custom( + "Received invalid JSON-RPC object: one of method, result, or error required", + )) } }, LSPSMethod::LSPS1GetInfo => { @@ -681,7 +683,9 @@ impl<'de, 'a> Visitor<'de> for LSPSMessageVisitor<'a> { LSPS1Response::GetInfo(response), ))) } else { - Err(de::Error::custom("Received invalid JSON-RPC object: one of method, result, or error required")) + Err(de::Error::custom( + "Received invalid JSON-RPC object: one of method, result, or error required", + )) } }, LSPSMethod::LSPS1CreateOrder => { @@ -698,7 +702,9 @@ impl<'de, 'a> Visitor<'de> for LSPSMessageVisitor<'a> { LSPS1Response::CreateOrder(response), ))) } else { - Err(de::Error::custom("Received invalid JSON-RPC object: one of method, result, or error required")) + Err(de::Error::custom( + "Received invalid JSON-RPC object: one of method, result, or error required", + )) } }, LSPSMethod::LSPS1GetOrder => { @@ -715,7 +721,9 @@ impl<'de, 'a> Visitor<'de> for LSPSMessageVisitor<'a> { LSPS1Response::GetOrder(response), ))) } else { - Err(de::Error::custom("Received invalid JSON-RPC object: one of method, result, or error required")) + Err(de::Error::custom( + "Received invalid JSON-RPC object: one of method, result, or error required", + )) } }, LSPSMethod::LSPS2GetInfo => { @@ -732,7 +740,9 @@ impl<'de, 'a> Visitor<'de> for LSPSMessageVisitor<'a> { LSPS2Response::GetInfo(response), ))) } else { - Err(de::Error::custom("Received invalid JSON-RPC object: one of method, result, or error required")) + Err(de::Error::custom( + "Received invalid JSON-RPC object: one of method, result, or error required", + )) } }, LSPSMethod::LSPS2Buy => { @@ -749,7 +759,9 @@ impl<'de, 'a> Visitor<'de> for LSPSMessageVisitor<'a> { LSPS2Response::Buy(response), ))) } else { - Err(de::Error::custom("Received invalid JSON-RPC object: one of method, result, or error required")) + Err(de::Error::custom( + "Received invalid JSON-RPC object: one of method, result, or error required", + )) } }, LSPSMethod::LSPS5SetWebhook => { @@ -766,7 +778,9 @@ impl<'de, 'a> Visitor<'de> for LSPSMessageVisitor<'a> { LSPS5Response::SetWebhook(response), ))) } else { - Err(de::Error::custom("Received invalid JSON-RPC object: one of method, result, or error required")) + Err(de::Error::custom( + "Received invalid JSON-RPC object: one of method, result, or error required", + )) } }, LSPSMethod::LSPS5ListWebhooks => { @@ -778,7 +792,9 @@ impl<'de, 'a> Visitor<'de> for LSPSMessageVisitor<'a> { LSPS5Response::ListWebhooks(response), ))) } else { - Err(de::Error::custom("Received invalid JSON-RPC object: one of method, result, or error required")) + Err(de::Error::custom( + "Received invalid JSON-RPC object: one of method, result, or error required", + )) } }, LSPSMethod::LSPS5RemoveWebhook => { @@ -795,7 +811,9 @@ impl<'de, 'a> Visitor<'de> for LSPSMessageVisitor<'a> { LSPS5Response::RemoveWebhook(response), ))) } else { - Err(de::Error::custom("Received invalid JSON-RPC object: one of method, result, or error required")) + Err(de::Error::custom( + "Received invalid JSON-RPC object: one of method, result, or error required", + )) } }, }, diff --git a/lightning-liquidity/src/lsps0/service.rs b/lightning-liquidity/src/lsps0/service.rs index f34107603c2..e50850b82f6 100644 --- a/lightning-liquidity/src/lsps0/service.rs +++ b/lightning-liquidity/src/lsps0/service.rs @@ -73,7 +73,13 @@ impl LSPSProtocolMessageHandler for LSPS0ServiceHandler { false, "Service handler received LSPS0 response message. This should never happen." ); - Err(LightningError { err: format!("Service handler received LSPS0 response message from node {}. This should never happen.", counterparty_node_id), action: ErrorAction::IgnoreAndLog(Level::Info)}) + Err(LightningError { + err: format!( + "Service handler received LSPS0 response message from node {}. This should never happen.", + counterparty_node_id + ), + action: ErrorAction::IgnoreAndLog(Level::Info), + }) }, } } diff --git a/lightning-liquidity/src/lsps1/client.rs b/lightning-liquidity/src/lsps1/client.rs index 2cbfb04c86a..dd55648de12 100644 --- a/lightning-liquidity/src/lsps1/client.rs +++ b/lightning-liquidity/src/lsps1/client.rs @@ -19,7 +19,7 @@ use crate::message_queue::MessageQueue; use crate::events::EventQueue; use crate::lsps0::ser::{LSPSProtocolMessageHandler, LSPSRequestId, LSPSResponseError}; -use crate::prelude::{new_hash_map, HashMap, HashSet}; +use crate::prelude::{HashMap, HashSet, new_hash_map}; use crate::sync::{Arc, Mutex, RwLock}; use lightning::ln::msgs::{ErrorAction, LightningError}; @@ -27,8 +27,8 @@ use lightning::sign::EntropySource; use lightning::util::logger::Level; use lightning::util::persist::KVStore; -use bitcoin::secp256k1::PublicKey; use bitcoin::Address; +use bitcoin::secp256k1::PublicKey; /// Client-side configuration options for bLIP-51 / LSPS1 channel requests. #[derive(Clone, Debug)] @@ -249,7 +249,7 @@ impl LSPS1ClientHandler { counterparty_node_id ), action: ErrorAction::IgnoreAndLog(Level::Debug), - }) + }); }, } @@ -367,7 +367,7 @@ impl LSPS1ClientHandler { counterparty_node_id ), action: ErrorAction::IgnoreAndLog(Level::Debug), - }) + }); }, } diff --git a/lightning-liquidity/src/lsps1/event.rs b/lightning-liquidity/src/lsps1/event.rs index 8868790da31..5fe40931a99 100644 --- a/lightning-liquidity/src/lsps1/event.rs +++ b/lightning-liquidity/src/lsps1/event.rs @@ -14,8 +14,8 @@ use super::msgs::{LSPS1ChannelInfo, LSPS1Options, LSPS1OrderParams, LSPS1Payment use crate::lsps0::ser::{LSPSRequestId, LSPSResponseError}; -use bitcoin::secp256k1::PublicKey; use bitcoin::Address; +use bitcoin::secp256k1::PublicKey; /// An event which an bLIP-51 / LSPS1 client should take some action in response to. #[derive(Clone, Debug, PartialEq, Eq)] diff --git a/lightning-liquidity/src/lsps1/msgs.rs b/lightning-liquidity/src/lsps1/msgs.rs index b754f0438aa..a3000487705 100644 --- a/lightning-liquidity/src/lsps1/msgs.rs +++ b/lightning-liquidity/src/lsps1/msgs.rs @@ -14,8 +14,8 @@ use alloc::string::String; use core::convert::TryFrom; use crate::lsps0::ser::{ - string_amount, string_offer, u32_fee_rate, unchecked_address, unchecked_address_option, - LSPSDateTime, LSPSMessage, LSPSRequestId, LSPSResponseError, + LSPSDateTime, LSPSMessage, LSPSRequestId, LSPSResponseError, string_amount, string_offer, + u32_fee_rate, unchecked_address, unchecked_address_option, }; use bitcoin::{Address, FeeRate, OutPoint}; diff --git a/lightning-liquidity/src/lsps1/service.rs b/lightning-liquidity/src/lsps1/service.rs index 0e139907589..7ffe968899b 100644 --- a/lightning-liquidity/src/lsps1/service.rs +++ b/lightning-liquidity/src/lsps1/service.rs @@ -20,12 +20,12 @@ use core::task; use super::event::LSPS1ServiceEvent; use super::msgs::{ - LSPS1ChannelInfo, LSPS1CreateOrderRequest, LSPS1CreateOrderResponse, LSPS1GetInfoResponse, - LSPS1GetOrderRequest, LSPS1Message, LSPS1Options, LSPS1OrderId, LSPS1OrderParams, - LSPS1PaymentInfo, LSPS1PaymentState, LSPS1Request, LSPS1Response, LSPS1_CREATE_ORDER_REQUEST_OPTION_MISMATCH_ERROR_CODE, LSPS1_CREATE_ORDER_REQUEST_UNRECOGNIZED_OR_STALE_TOKEN_ERROR_CODE, - LSPS1_GET_ORDER_REQUEST_ORDER_NOT_FOUND_ERROR_CODE, + LSPS1_GET_ORDER_REQUEST_ORDER_NOT_FOUND_ERROR_CODE, LSPS1ChannelInfo, LSPS1CreateOrderRequest, + LSPS1CreateOrderResponse, LSPS1GetInfoResponse, LSPS1GetOrderRequest, LSPS1Message, + LSPS1Options, LSPS1OrderId, LSPS1OrderParams, LSPS1PaymentInfo, LSPS1PaymentState, + LSPS1Request, LSPS1Response, }; pub use super::peer_state::PaymentMethod; use super::peer_state::PeerState; @@ -33,17 +33,16 @@ use crate::message_queue::MessageQueue; use crate::events::EventQueue; use crate::lsps0::ser::{ - LSPSDateTime, LSPSProtocolMessageHandler, LSPSRequestId, LSPSResponseError, - LSPS0_CLIENT_REJECTED_ERROR_CODE, + LSPS0_CLIENT_REJECTED_ERROR_CODE, LSPSDateTime, LSPSProtocolMessageHandler, LSPSRequestId, + LSPSResponseError, }; use crate::persist::{ LIQUIDITY_MANAGER_PERSISTENCE_PRIMARY_NAMESPACE, LSPS1_SERVICE_PERSISTENCE_SECONDARY_NAMESPACE, }; -use crate::prelude::hash_map::Entry; use crate::prelude::HashMap; +use crate::prelude::hash_map::Entry; use crate::sync::{Arc, Mutex, RwLock}; use crate::utils; -use crate::utils::async_poll::dummy_waker; use crate::utils::time::TimeProvider; use lightning::ln::channelmanager::AChannelManager; @@ -790,7 +789,13 @@ where false, "Service handler received LSPS1 response message. This should never happen." ); - Err(LightningError { err: format!("Service handler received LSPS1 response message from node {:?}. This should never happen.", counterparty_node_id), action: ErrorAction::IgnoreAndLog(Level::Info)}) + Err(LightningError { + err: format!( + "Service handler received LSPS1 response message from node {:?}. This should never happen.", + counterparty_node_id + ), + action: ErrorAction::IgnoreAndLog(Level::Info), + }) }, } } @@ -841,8 +846,7 @@ where payment_details )); - let mut waker = dummy_waker(); - let mut ctx = task::Context::from_waker(&mut waker); + let mut ctx = task::Context::from_waker(core::task::Waker::noop()); match fut.as_mut().poll(&mut ctx) { task::Poll::Ready(result) => result, task::Poll::Pending => { @@ -880,8 +884,7 @@ where let mut fut = pin!(self.inner.order_payment_received(counterparty_node_id, order_id, method)); - let mut waker = dummy_waker(); - let mut ctx = task::Context::from_waker(&mut waker); + let mut ctx = task::Context::from_waker(core::task::Waker::noop()); match fut.as_mut().poll(&mut ctx) { task::Poll::Ready(result) => result, task::Poll::Pending => { @@ -901,8 +904,7 @@ where let mut fut = pin!(self.inner.order_channel_opened(counterparty_node_id, order_id, channel_info)); - let mut waker = dummy_waker(); - let mut ctx = task::Context::from_waker(&mut waker); + let mut ctx = task::Context::from_waker(core::task::Waker::noop()); match fut.as_mut().poll(&mut ctx) { task::Poll::Ready(result) => result, task::Poll::Pending => { @@ -920,8 +922,7 @@ where ) -> Result<(), APIError> { let mut fut = pin!(self.inner.order_failed_and_refunded(counterparty_node_id, order_id)); - let mut waker = dummy_waker(); - let mut ctx = task::Context::from_waker(&mut waker); + let mut ctx = task::Context::from_waker(core::task::Waker::noop()); match fut.as_mut().poll(&mut ctx) { task::Poll::Ready(result) => result, task::Poll::Pending => { diff --git a/lightning-liquidity/src/lsps2/client.rs b/lightning-liquidity/src/lsps2/client.rs index 21b57162010..f0485034c84 100644 --- a/lightning-liquidity/src/lsps2/client.rs +++ b/lightning-liquidity/src/lsps2/client.rs @@ -18,7 +18,7 @@ use crate::events::EventQueue; use crate::lsps0::ser::{LSPSProtocolMessageHandler, LSPSRequestId, LSPSResponseError}; use crate::lsps2::event::LSPS2ClientEvent; use crate::message_queue::MessageQueue; -use crate::prelude::{new_hash_map, new_hash_set, HashMap, HashSet}; +use crate::prelude::{HashMap, HashSet, new_hash_map, new_hash_set}; use crate::sync::{Arc, Mutex, RwLock}; use lightning::ln::msgs::{ErrorAction, LightningError}; @@ -222,7 +222,7 @@ impl LSPS2ClientHandler { counterparty_node_id ), action: ErrorAction::IgnoreAndLog(Level::Debug), - }) + }); }, } @@ -266,7 +266,13 @@ impl LSPS2ClientHandler { Err(lightning_error) }, None => { - return Err(LightningError { err: format!("Received error response for a get_info request from an unknown counterparty {}",counterparty_node_id), action: ErrorAction::IgnoreAndLog(Level::Debug)}); + return Err(LightningError { + err: format!( + "Received error response for a get_info request from an unknown counterparty {}", + counterparty_node_id + ), + action: ErrorAction::IgnoreAndLog(Level::Debug), + }); }, } } @@ -395,7 +401,13 @@ impl LSPSProtocolMessageHandler false, "Client handler received LSPS2 request message. This should never happen." ); - Err(LightningError { err: format!("Client handler received LSPS2 request message from node {}. This should never happen.", counterparty_node_id), action: ErrorAction::IgnoreAndLog(Level::Info)}) + Err(LightningError { + err: format!( + "Client handler received LSPS2 request message from node {}. This should never happen.", + counterparty_node_id + ), + action: ErrorAction::IgnoreAndLog(Level::Info), + }) }, } } diff --git a/lightning-liquidity/src/lsps2/msgs.rs b/lightning-liquidity/src/lsps2/msgs.rs index ba4d0fea4cd..515866a8a4f 100644 --- a/lightning-liquidity/src/lsps2/msgs.rs +++ b/lightning-liquidity/src/lsps2/msgs.rs @@ -25,8 +25,8 @@ use lightning::impl_writeable_tlv_based; use lightning::util::scid_utils; use crate::lsps0::ser::{ - string_amount, string_amount_option, LSPSDateTime, LSPSMessage, LSPSRequestId, - LSPSResponseError, + LSPSDateTime, LSPSMessage, LSPSRequestId, LSPSResponseError, string_amount, + string_amount_option, }; use crate::utils; diff --git a/lightning-liquidity/src/lsps2/payment_queue.rs b/lightning-liquidity/src/lsps2/payment_queue.rs index 003939d699d..90225279de7 100644 --- a/lightning-liquidity/src/lsps2/payment_queue.rs +++ b/lightning-liquidity/src/lsps2/payment_queue.rs @@ -33,10 +33,9 @@ impl PaymentQueue { // HTLCs within a payment should have the same payment hash. debug_assert!(entry.htlcs.iter().all(|htlc| htlc.payment_hash == entry.payment_hash)); // The given HTLC should not already be present. - debug_assert!(entry - .htlcs - .iter() - .all(|htlc| htlc.intercept_id != new_htlc.intercept_id)); + debug_assert!( + entry.htlcs.iter().all(|htlc| htlc.intercept_id != new_htlc.intercept_id) + ); entry.htlcs.push(new_htlc); let total_expected_outbound_amount_msat = entry.htlcs.iter().map(|htlc| htlc.expected_outbound_amount_msat).sum(); diff --git a/lightning-liquidity/src/lsps2/service.rs b/lightning-liquidity/src/lsps2/service.rs index b7f6f2fc64d..d1dd054c82e 100644 --- a/lightning-liquidity/src/lsps2/service.rs +++ b/lightning-liquidity/src/lsps2/service.rs @@ -22,9 +22,9 @@ use core::task; use crate::events::EventQueue; use crate::lsps0::ser::{ - LSPSMessage, LSPSProtocolMessageHandler, LSPSRequestId, LSPSResponseError, JSONRPC_INTERNAL_ERROR_ERROR_CODE, JSONRPC_INTERNAL_ERROR_ERROR_MESSAGE, - LSPS0_CLIENT_REJECTED_ERROR_CODE, + LSPS0_CLIENT_REJECTED_ERROR_CODE, LSPSMessage, LSPSProtocolMessageHandler, LSPSRequestId, + LSPSResponseError, }; use crate::lsps2::event::LSPS2ServiceEvent; use crate::lsps2::payment_queue::{InterceptedHTLC, PaymentQueue}; @@ -36,9 +36,8 @@ use crate::persist::{ LIQUIDITY_MANAGER_PERSISTENCE_PRIMARY_NAMESPACE, LSPS2_SERVICE_PERSISTENCE_SECONDARY_NAMESPACE, }; use crate::prelude::hash_map::Entry; -use crate::prelude::{new_hash_map, HashMap}; +use crate::prelude::{HashMap, new_hash_map}; use crate::sync::{Arc, Mutex, MutexGuard, RwLock}; -use crate::utils::async_poll::dummy_waker; use lightning::chain::chaininterface::{BroadcasterInterface, TransactionType}; use lightning::events::HTLCHandlingFailureType; @@ -52,16 +51,16 @@ use lightning::{impl_writeable_tlv_based, impl_writeable_tlv_based_enum}; use lightning_types::payment::PaymentHash; -use bitcoin::secp256k1::PublicKey; use bitcoin::Transaction; +use bitcoin::secp256k1::PublicKey; use crate::lsps2::msgs::{ - LSPS2BuyRequest, LSPS2BuyResponse, LSPS2GetInfoRequest, LSPS2GetInfoResponse, LSPS2Message, - LSPS2OpeningFeeParams, LSPS2RawOpeningFeeParams, LSPS2Request, LSPS2Response, LSPS2_BUY_REQUEST_INVALID_OPENING_FEE_PARAMS_ERROR_CODE, LSPS2_BUY_REQUEST_PAYMENT_SIZE_TOO_LARGE_ERROR_CODE, LSPS2_BUY_REQUEST_PAYMENT_SIZE_TOO_SMALL_ERROR_CODE, - LSPS2_GET_INFO_REQUEST_UNRECOGNIZED_OR_STALE_TOKEN_ERROR_CODE, + LSPS2_GET_INFO_REQUEST_UNRECOGNIZED_OR_STALE_TOKEN_ERROR_CODE, LSPS2BuyRequest, + LSPS2BuyResponse, LSPS2GetInfoRequest, LSPS2GetInfoResponse, LSPS2Message, + LSPS2OpeningFeeParams, LSPS2RawOpeningFeeParams, LSPS2Request, LSPS2Response, }; const MAX_PENDING_REQUESTS_PER_PEER: usize = 10; @@ -246,12 +245,12 @@ impl OutboundJITChannelState { if expected_payment_size_msat < opening_fee_params.min_payment_size_msat || expected_payment_size_msat > opening_fee_params.max_payment_size_msat { - return Err(ChannelStateError( - format!("Payment size violates our limits: expected_payment_size_msat = {}, min_payment_size_msat = {}, max_payment_size_msat = {}", - expected_payment_size_msat, - opening_fee_params.min_payment_size_msat, - opening_fee_params.max_payment_size_msat - ))); + return Err(ChannelStateError(format!( + "Payment size violates our limits: expected_payment_size_msat = {}, min_payment_size_msat = {}, max_payment_size_msat = {}", + expected_payment_size_msat, + opening_fee_params.min_payment_size_msat, + opening_fee_params.max_payment_size_msat + ))); } let opening_fee_msat = compute_opening_fee( @@ -677,7 +676,8 @@ macro_rules! get_or_insert_peer_state_entry { if is_limited_by_max_total_peers { let error_response = LSPSResponseError { code: JSONRPC_INTERNAL_ERROR_ERROR_CODE, - message: JSONRPC_INTERNAL_ERROR_ERROR_MESSAGE.to_string(), data: None, + message: JSONRPC_INTERNAL_ERROR_ERROR_MESSAGE.to_string(), + data: None, }; let msg = LSPSMessage::Invalid(error_response); @@ -688,17 +688,17 @@ macro_rules! get_or_insert_peer_state_entry { $counterparty_node_id, MAX_TOTAL_PEERS ); - return Err(LightningError { err, action: ErrorAction::IgnoreAndLog(Level::Error) }); + return Err(LightningError { + err, + action: ErrorAction::IgnoreAndLog(Level::Error), + }); } else { e.insert(Mutex::new(PeerState::new())) } - } - Entry::Occupied(e) => { - e.into_mut() - } + }, + Entry::Occupied(e) => e.into_mut(), } - - }} + }}; } /// The main object allowing to send and receive bLIP-52 / LSPS2 messages. @@ -749,8 +749,8 @@ where debug_assert!(res.is_none(), "Channel IDs should never collide"); if res.is_some() { return Err(lightning::io::Error::new( - lightning::io::ErrorKind::InvalidData, - "Failed to read LSPS2 peer state due to data inconsistencies: Channel IDs should never collide", + lightning::io::ErrorKind::InvalidData, + "Failed to read LSPS2 peer state due to data inconsistencies: Channel IDs should never collide", )); } } @@ -946,14 +946,14 @@ where _ => { return Err(APIError::APIMisuseError { err: format!("No pending buy request for request_id: {:?}", request_id), - }) + }); }, } }, None => { return Err(APIError::APIMisuseError { err: format!("No state for the counterparty exists: {}", counterparty_node_id), - }) + }); }, }; @@ -1217,7 +1217,7 @@ where "Forwarded payment was not applicable for JIT channel: {}", e.err ), - }) + }); }, } @@ -1451,7 +1451,7 @@ where "Failed to transition to channel ready: {}", e.err ), - }) + }); }, } } else { @@ -2080,7 +2080,13 @@ where false, "Service handler received LSPS2 response message. This should never happen." ); - Err(LightningError { err: format!("Service handler received LSPS2 response message from node {}. This should never happen.", counterparty_node_id), action: ErrorAction::IgnoreAndLog(Level::Info)}) + Err(LightningError { + err: format!( + "Service handler received LSPS2 response message from node {}. This should never happen.", + counterparty_node_id + ), + action: ErrorAction::IgnoreAndLog(Level::Info), + }) }, } } @@ -2190,8 +2196,7 @@ where user_channel_id, )); - let mut waker = dummy_waker(); - let mut ctx = task::Context::from_waker(&mut waker); + let mut ctx = task::Context::from_waker(core::task::Waker::noop()); match fut.as_mut().poll(&mut ctx) { task::Poll::Ready(result) => result, task::Poll::Pending => { @@ -2217,8 +2222,7 @@ where payment_hash, )); - let mut waker = dummy_waker(); - let mut ctx = task::Context::from_waker(&mut waker); + let mut ctx = task::Context::from_waker(core::task::Waker::noop()); match fut.as_mut().poll(&mut ctx) { task::Poll::Ready(result) => result, task::Poll::Pending => { @@ -2238,8 +2242,7 @@ where ) -> Result<(), APIError> { let mut fut = pin!(self.inner.htlc_handling_failed(failure_type)); - let mut waker = dummy_waker(); - let mut ctx = task::Context::from_waker(&mut waker); + let mut ctx = task::Context::from_waker(core::task::Waker::noop()); match fut.as_mut().poll(&mut ctx) { task::Poll::Ready(result) => result, task::Poll::Pending => { @@ -2259,8 +2262,7 @@ where ) -> Result<(), APIError> { let mut fut = pin!(self.inner.payment_forwarded(next_channel_id, skimmed_fee_msat)); - let mut waker = dummy_waker(); - let mut ctx = task::Context::from_waker(&mut waker); + let mut ctx = task::Context::from_waker(core::task::Waker::noop()); match fut.as_mut().poll(&mut ctx) { task::Poll::Ready(result) => result, task::Poll::Pending => { @@ -2300,8 +2302,7 @@ where let mut fut = pin!(self.inner.channel_open_abandoned(counterparty_node_id, user_channel_id)); - let mut waker = dummy_waker(); - let mut ctx = task::Context::from_waker(&mut waker); + let mut ctx = task::Context::from_waker(core::task::Waker::noop()); match fut.as_mut().poll(&mut ctx) { task::Poll::Ready(result) => result, task::Poll::Pending => { @@ -2319,8 +2320,7 @@ where ) -> Result<(), APIError> { let mut fut = pin!(self.inner.channel_open_failed(counterparty_node_id, user_channel_id)); - let mut waker = dummy_waker(); - let mut ctx = task::Context::from_waker(&mut waker); + let mut ctx = task::Context::from_waker(core::task::Waker::noop()); match fut.as_mut().poll(&mut ctx) { task::Poll::Ready(result) => result, task::Poll::Pending => { @@ -2341,8 +2341,7 @@ where let mut fut = pin!(self.inner.channel_ready(user_channel_id, channel_id, counterparty_node_id)); - let mut waker = dummy_waker(); - let mut ctx = task::Context::from_waker(&mut waker); + let mut ctx = task::Context::from_waker(core::task::Waker::noop()); match fut.as_mut().poll(&mut ctx) { task::Poll::Ready(result) => result, task::Poll::Pending => { diff --git a/lightning-liquidity/src/lsps5/client.rs b/lightning-liquidity/src/lsps5/client.rs index 26c0b180421..0b83318e484 100644 --- a/lightning-liquidity/src/lsps5/client.rs +++ b/lightning-liquidity/src/lsps5/client.rs @@ -19,7 +19,7 @@ use crate::lsps5::msgs::{ }; use crate::message_queue::MessageQueue; -use crate::prelude::{new_hash_map, HashMap}; +use crate::prelude::{HashMap, new_hash_map}; use crate::sync::{Arc, Mutex, RwLock}; use crate::utils::generate_request_id; @@ -498,16 +498,14 @@ mod tests { let outer_state_lock = client.per_peer_state.read().unwrap(); let peer_1_state = outer_state_lock.get(&peer_1).unwrap().lock().unwrap(); - assert!(peer_1_state - .pending_set_webhook_requests - .iter() - .any(|(id, _)| id == &req_id_1)); + assert!( + peer_1_state.pending_set_webhook_requests.iter().any(|(id, _)| id == &req_id_1) + ); let peer_2_state = outer_state_lock.get(&peer_2).unwrap().lock().unwrap(); - assert!(peer_2_state - .pending_set_webhook_requests - .iter() - .any(|(id, _)| id == &req_id_2)); + assert!( + peer_2_state.pending_set_webhook_requests.iter().any(|(id, _)| id == &req_id_2) + ); } } @@ -596,19 +594,20 @@ mod tests { let peer_state = outer_state_lock.get(&peer).unwrap().lock().unwrap(); assert_eq!(peer_state.pending_set_webhook_requests.len(), MAX_PENDING_REQUESTS); - assert!(!peer_state - .pending_set_webhook_requests - .iter() - .any(|(id, _)| id == &request_ids[0])); + assert!( + !peer_state + .pending_set_webhook_requests + .iter() + .any(|(id, _)| id == &request_ids[0]) + ); for req_id in &request_ids[1..] { assert!(peer_state.pending_set_webhook_requests.iter().any(|(id, _)| id == req_id)); } - assert!(peer_state - .pending_set_webhook_requests - .iter() - .any(|(id, _)| id == &new_req_id)); + assert!( + peer_state.pending_set_webhook_requests.iter().any(|(id, _)| id == &new_req_id) + ); } } @@ -626,10 +625,12 @@ mod tests { let state = client.per_peer_state.read().unwrap(); assert!(state.contains_key(&peer)); let peer_state = state.get(&peer).unwrap().lock().unwrap(); - assert!(peer_state - .pending_set_webhook_requests - .iter() - .any(|(id, _)| id == &set_webhook_req_id)); + assert!( + peer_state + .pending_set_webhook_requests + .iter() + .any(|(id, _)| id == &set_webhook_req_id) + ); assert!(peer_state.pending_list_webhooks_requests.contains(&list_webhooks_req_id)); } @@ -647,10 +648,12 @@ mod tests { let state = client.per_peer_state.read().unwrap(); assert!(state.contains_key(&peer)); let peer_state = state.get(&peer).unwrap().lock().unwrap(); - assert!(!peer_state - .pending_set_webhook_requests - .iter() - .any(|(id, _)| id == &set_webhook_req_id)); + assert!( + !peer_state + .pending_set_webhook_requests + .iter() + .any(|(id, _)| id == &set_webhook_req_id) + ); assert!(peer_state.pending_list_webhooks_requests.contains(&list_webhooks_req_id)); } @@ -678,10 +681,9 @@ mod tests { let state = client.per_peer_state.read().unwrap(); assert!(state.contains_key(&peer)); let peer_state = state.get(&peer).unwrap().lock().unwrap(); - assert!(peer_state - .pending_set_webhook_requests - .iter() - .any(|(id, _)| id == &new_req_id)); + assert!( + peer_state.pending_set_webhook_requests.iter().any(|(id, _)| id == &new_req_id) + ); } } } diff --git a/lightning-liquidity/src/lsps5/msgs.rs b/lightning-liquidity/src/lsps5/msgs.rs index 41e05d687c5..254ef5fe58c 100644 --- a/lightning-liquidity/src/lsps5/msgs.rs +++ b/lightning-liquidity/src/lsps5/msgs.rs @@ -21,10 +21,10 @@ use lightning::util::ser::{Readable, Writeable}; use lightning::{impl_writeable_tlv_based, impl_writeable_tlv_based_enum}; use lightning_types::string::UntrustedString; +use serde::Serializer; use serde::de::{self, Deserializer, MapAccess, Visitor}; use serde::ser::SerializeMap; use serde::ser::SerializeStruct; -use serde::Serializer; use serde::{Deserialize, Serialize}; use alloc::string::String; @@ -329,7 +329,7 @@ impl Deref for LSPS5AppName { type Target = str; fn deref(&self) -> &Self::Target { - &self.0 .0 + &self.0.0 } } diff --git a/lightning-liquidity/src/manager.rs b/lightning-liquidity/src/manager.rs index f1b098dbfaa..6f1cf165b9f 100644 --- a/lightning-liquidity/src/manager.rs +++ b/lightning-liquidity/src/manager.rs @@ -14,9 +14,9 @@ use crate::events::{EventQueue, LiquidityEvent}; use crate::lsps0::client::LSPS0ClientHandler; use crate::lsps0::msgs::LSPS0Message; use crate::lsps0::ser::{ - LSPSMessage, LSPSMethod, LSPSProtocolMessageHandler, LSPSRequestId, LSPSResponseError, - RawLSPSMessage, JSONRPC_INVALID_MESSAGE_ERROR_CODE, JSONRPC_INVALID_MESSAGE_ERROR_MESSAGE, - LSPS_MESSAGE_TYPE_ID, + JSONRPC_INVALID_MESSAGE_ERROR_CODE, JSONRPC_INVALID_MESSAGE_ERROR_MESSAGE, + LSPS_MESSAGE_TYPE_ID, LSPSMessage, LSPSMethod, LSPSProtocolMessageHandler, LSPSRequestId, + LSPSResponseError, RawLSPSMessage, }; use crate::lsps0::service::LSPS0ServiceHandler; use crate::lsps5::client::{LSPS5ClientConfig, LSPS5ClientHandler}; @@ -35,9 +35,8 @@ use crate::lsps1::service::{LSPS1ServiceConfig, LSPS1ServiceHandler, LSPS1Servic use crate::lsps2::client::{LSPS2ClientConfig, LSPS2ClientHandler}; use crate::lsps2::msgs::LSPS2Message; use crate::lsps2::service::{LSPS2ServiceConfig, LSPS2ServiceHandler, LSPS2ServiceHandlerSync}; -use crate::prelude::{new_hash_map, new_hash_set, HashMap, HashSet}; +use crate::prelude::{HashMap, HashSet, new_hash_map, new_hash_set}; use crate::sync::{Arc, Mutex, RwLock}; -use crate::utils::async_poll::dummy_waker; #[cfg(feature = "time")] use crate::utils::time::DefaultTimeProvider; use crate::utils::time::TimeProvider; @@ -131,13 +130,13 @@ pub trait ALiquidityManager { } impl< - ES: EntropySource + Clone, - NS: NodeSigner + Clone, - CM: Deref + Clone, - K: KVStore + Clone, - TP: Deref + Clone, - T: BroadcasterInterface + Clone, - > ALiquidityManager for LiquidityManager + ES: EntropySource + Clone, + NS: NodeSigner + Clone, + CM: Deref + Clone, + K: KVStore + Clone, + TP: Deref + Clone, + T: BroadcasterInterface + Clone, +> ALiquidityManager for LiquidityManager where CM::Target: AChannelManager, TP::Target: TimeProvider, @@ -204,13 +203,13 @@ pub trait ALiquidityManagerSync { } impl< - ES: EntropySource + Clone, - NS: NodeSigner + Clone, - CM: Deref + Clone, - KS: Deref + Clone, - TP: Deref + Clone, - T: BroadcasterInterface + Clone, - > ALiquidityManagerSync for LiquidityManagerSync + ES: EntropySource + Clone, + NS: NodeSigner + Clone, + CM: Deref + Clone, + KS: Deref + Clone, + TP: Deref + Clone, + T: BroadcasterInterface + Clone, +> ALiquidityManagerSync for LiquidityManagerSync where CM::Target: AChannelManager, KS::Target: KVStoreSync, @@ -294,12 +293,12 @@ pub struct LiquidityManager< #[cfg(feature = "time")] impl< - ES: EntropySource + Clone, - NS: NodeSigner + Clone, - CM: Deref + Clone, - K: KVStore + Clone, - T: BroadcasterInterface + Clone, - > LiquidityManager + ES: EntropySource + Clone, + NS: NodeSigner + Clone, + CM: Deref + Clone, + K: KVStore + Clone, + T: BroadcasterInterface + Clone, +> LiquidityManager where CM::Target: AChannelManager, { @@ -326,13 +325,13 @@ where } impl< - ES: EntropySource + Clone, - NS: NodeSigner + Clone, - CM: Deref + Clone, - K: KVStore + Clone, - TP: Deref + Clone, - T: BroadcasterInterface + Clone, - > LiquidityManager + ES: EntropySource + Clone, + NS: NodeSigner + Clone, + CM: Deref + Clone, + K: KVStore + Clone, + TP: Deref + Clone, + T: BroadcasterInterface + Clone, +> LiquidityManager where CM::Target: AChannelManager, TP::Target: TimeProvider, @@ -647,7 +646,13 @@ where ) -> Result<(), lightning::ln::msgs::LightningError> { match msg { LSPSMessage::Invalid(_error) => { - return Err(LightningError { err: format!("{} did not understand a message we previously sent, maybe they don't support a protocol we are trying to use?", sender_node_id), action: ErrorAction::IgnoreAndLog(Level::Error)}); + return Err(LightningError { + err: format!( + "{} did not understand a message we previously sent, maybe they don't support a protocol we are trying to use?", + sender_node_id + ), + action: ErrorAction::IgnoreAndLog(Level::Error), + }); }, LSPSMessage::LSPS0(msg @ LSPS0Message::Response(..)) => { self.lsps0_client_handler.handle_message(msg, sender_node_id)?; @@ -658,7 +663,13 @@ where lsps0_service_handler.handle_message(msg, sender_node_id)?; }, None => { - return Err(LightningError { err: format!("Received LSPS0 request message without LSPS0 service handler configured. From node {}", sender_node_id), action: ErrorAction::IgnoreAndLog(Level::Debug)}); + return Err(LightningError { + err: format!( + "Received LSPS0 request message without LSPS0 service handler configured. From node {}", + sender_node_id + ), + action: ErrorAction::IgnoreAndLog(Level::Debug), + }); }, } }, @@ -668,7 +679,13 @@ where lsps1_client_handler.handle_message(msg, sender_node_id)?; }, None => { - return Err(LightningError { err: format!("Received LSPS1 response message without LSPS1 client handler configured. From node {}", sender_node_id), action: ErrorAction::IgnoreAndLog(Level::Debug)}); + return Err(LightningError { + err: format!( + "Received LSPS1 response message without LSPS1 client handler configured. From node {}", + sender_node_id + ), + action: ErrorAction::IgnoreAndLog(Level::Debug), + }); }, } }, @@ -678,7 +695,13 @@ where lsps1_service_handler.handle_message(msg, sender_node_id)?; }, None => { - return Err(LightningError { err: format!("Received LSPS1 request message without LSPS1 service handler configured. From node {}", sender_node_id), action: ErrorAction::IgnoreAndLog(Level::Debug)}); + return Err(LightningError { + err: format!( + "Received LSPS1 request message without LSPS1 service handler configured. From node {}", + sender_node_id + ), + action: ErrorAction::IgnoreAndLog(Level::Debug), + }); }, } }, @@ -688,7 +711,13 @@ where lsps2_client_handler.handle_message(msg, sender_node_id)?; }, None => { - return Err(LightningError { err: format!("Received LSPS2 response message without LSPS2 client handler configured. From node {}", sender_node_id), action: ErrorAction::IgnoreAndLog(Level::Debug)}); + return Err(LightningError { + err: format!( + "Received LSPS2 response message without LSPS2 client handler configured. From node {}", + sender_node_id + ), + action: ErrorAction::IgnoreAndLog(Level::Debug), + }); }, } }, @@ -698,7 +727,13 @@ where lsps2_service_handler.handle_message(msg, sender_node_id)?; }, None => { - return Err(LightningError { err: format!("Received LSPS2 request message without LSPS2 service handler configured. From node {}", sender_node_id), action: ErrorAction::IgnoreAndLog(Level::Debug)}); + return Err(LightningError { + err: format!( + "Received LSPS2 request message without LSPS2 service handler configured. From node {}", + sender_node_id + ), + action: ErrorAction::IgnoreAndLog(Level::Debug), + }); }, } }, @@ -708,7 +743,13 @@ where lsps5_client_handler.handle_message(msg, sender_node_id)?; }, None => { - return Err(LightningError { err: format!("Received LSPS5 response message without LSPS5 client handler configured. From node {}", sender_node_id), action: ErrorAction::IgnoreAndLog(Level::Debug)}); + return Err(LightningError { + err: format!( + "Received LSPS5 response message without LSPS5 client handler configured. From node {}", + sender_node_id + ), + action: ErrorAction::IgnoreAndLog(Level::Debug), + }); }, } }, @@ -737,7 +778,13 @@ where lsps5_service_handler.handle_message(msg, sender_node_id)?; }, None => { - return Err(LightningError { err: format!("Received LSPS5 request message without LSPS5 service handler configured. From node {}", sender_node_id), action: ErrorAction::IgnoreAndLog(Level::Debug)}); + return Err(LightningError { + err: format!( + "Received LSPS5 request message without LSPS5 service handler configured. From node {}", + sender_node_id + ), + action: ErrorAction::IgnoreAndLog(Level::Debug), + }); }, } }, @@ -747,13 +794,13 @@ where } impl< - ES: EntropySource + Clone, - NS: NodeSigner + Clone, - CM: Deref + Clone, - K: KVStore + Clone, - TP: Deref + Clone, - T: BroadcasterInterface + Clone, - > CustomMessageReader for LiquidityManager + ES: EntropySource + Clone, + NS: NodeSigner + Clone, + CM: Deref + Clone, + K: KVStore + Clone, + TP: Deref + Clone, + T: BroadcasterInterface + Clone, +> CustomMessageReader for LiquidityManager where CM::Target: AChannelManager, TP::Target: TimeProvider, @@ -773,13 +820,13 @@ where } impl< - ES: EntropySource + Clone, - NS: NodeSigner + Clone, - CM: Deref + Clone, - K: KVStore + Clone, - TP: Deref + Clone, - T: BroadcasterInterface + Clone, - > CustomMessageHandler for LiquidityManager + ES: EntropySource + Clone, + NS: NodeSigner + Clone, + CM: Deref + Clone, + K: KVStore + Clone, + TP: Deref + Clone, + T: BroadcasterInterface + Clone, +> CustomMessageHandler for LiquidityManager where CM::Target: AChannelManager, TP::Target: TimeProvider, @@ -923,12 +970,12 @@ pub struct LiquidityManagerSync< #[cfg(feature = "time")] impl< - ES: EntropySource + Clone, - NS: NodeSigner + Clone, - CM: Deref + Clone, - KS: Deref + Clone, - T: BroadcasterInterface + Clone, - > LiquidityManagerSync + ES: EntropySource + Clone, + NS: NodeSigner + Clone, + CM: Deref + Clone, + KS: Deref + Clone, + T: BroadcasterInterface + Clone, +> LiquidityManagerSync where CM::Target: AChannelManager, KS::Target: KVStoreSync, @@ -953,8 +1000,7 @@ where client_config, )); - let mut waker = dummy_waker(); - let mut ctx = task::Context::from_waker(&mut waker); + let mut ctx = task::Context::from_waker(core::task::Waker::noop()); let inner = match fut.as_mut().poll(&mut ctx) { task::Poll::Ready(result) => result, task::Poll::Pending => { @@ -967,13 +1013,13 @@ where } impl< - ES: EntropySource + Clone, - NS: NodeSigner + Clone, - CM: Deref + Clone, - KS: Deref + Clone, - TP: Deref + Clone, - T: BroadcasterInterface + Clone, - > LiquidityManagerSync + ES: EntropySource + Clone, + NS: NodeSigner + Clone, + CM: Deref + Clone, + KS: Deref + Clone, + TP: Deref + Clone, + T: BroadcasterInterface + Clone, +> LiquidityManagerSync where CM::Target: AChannelManager, KS::Target: KVStoreSync, @@ -999,8 +1045,7 @@ where time_provider, )); - let mut waker = dummy_waker(); - let mut ctx = task::Context::from_waker(&mut waker); + let mut ctx = task::Context::from_waker(core::task::Waker::noop()); let inner = match fut.as_mut().poll(&mut ctx) { task::Poll::Ready(result) => result, task::Poll::Pending => { @@ -1115,8 +1160,7 @@ where /// /// Wraps [`LiquidityManager::persist`]. pub fn persist(&self) -> Result { - let mut waker = dummy_waker(); - let mut ctx = task::Context::from_waker(&mut waker); + let mut ctx = task::Context::from_waker(core::task::Waker::noop()); match pin!(self.inner.persist()).as_mut().poll(&mut ctx) { task::Poll::Ready(result) => result, task::Poll::Pending => { @@ -1128,13 +1172,13 @@ where } impl< - ES: EntropySource + Clone, - NS: NodeSigner + Clone, - CM: Deref + Clone, - KS: Deref + Clone, - TP: Deref + Clone, - T: BroadcasterInterface + Clone, - > CustomMessageReader for LiquidityManagerSync + ES: EntropySource + Clone, + NS: NodeSigner + Clone, + CM: Deref + Clone, + KS: Deref + Clone, + TP: Deref + Clone, + T: BroadcasterInterface + Clone, +> CustomMessageReader for LiquidityManagerSync where CM::Target: AChannelManager, KS::Target: KVStoreSync, @@ -1150,13 +1194,13 @@ where } impl< - ES: EntropySource + Clone, - NS: NodeSigner + Clone, - CM: Deref + Clone, - KS: Deref + Clone, - TP: Deref + Clone, - T: BroadcasterInterface + Clone, - > CustomMessageHandler for LiquidityManagerSync + ES: EntropySource + Clone, + NS: NodeSigner + Clone, + CM: Deref + Clone, + KS: Deref + Clone, + TP: Deref + Clone, + T: BroadcasterInterface + Clone, +> CustomMessageHandler for LiquidityManagerSync where CM::Target: AChannelManager, KS::Target: KVStoreSync, diff --git a/lightning-liquidity/src/persist.rs b/lightning-liquidity/src/persist.rs index 30d78249796..3d260aa9713 100644 --- a/lightning-liquidity/src/persist.rs +++ b/lightning-liquidity/src/persist.rs @@ -13,7 +13,7 @@ use crate::events::{EventQueueDeserWrapper, LiquidityEvent}; use crate::lsps1::peer_state::PeerState as LSPS1ServicePeerState; use crate::lsps2::service::PeerState as LSPS2ServicePeerState; use crate::lsps5::service::PeerState as LSPS5ServicePeerState; -use crate::prelude::{new_hash_map, HashMap}; +use crate::prelude::{HashMap, new_hash_map}; use crate::sync::Mutex; use lightning::io::Cursor; diff --git a/lightning-liquidity/tests/lsps0_integration_tests.rs b/lightning-liquidity/tests/lsps0_integration_tests.rs index c2e94e30661..c7c139c618d 100644 --- a/lightning-liquidity/tests/lsps0_integration_tests.rs +++ b/lightning-liquidity/tests/lsps0_integration_tests.rs @@ -2,7 +2,7 @@ mod common; -use common::{create_service_and_client_nodes, get_lsps_message, LSPSNodes}; +use common::{LSPSNodes, create_service_and_client_nodes, get_lsps_message}; use lightning_liquidity::events::LiquidityEvent; use lightning_liquidity::lsps0::event::LSPS0ClientEvent; diff --git a/lightning-liquidity/tests/lsps1_integration_tests.rs b/lightning-liquidity/tests/lsps1_integration_tests.rs index a177b338ad7..d978f529857 100644 --- a/lightning-liquidity/tests/lsps1_integration_tests.rs +++ b/lightning-liquidity/tests/lsps1_integration_tests.rs @@ -3,7 +3,7 @@ mod common; use common::create_service_and_client_nodes_with_kv_stores; -use common::{get_lsps_message, LSPSNodes}; +use common::{LSPSNodes, get_lsps_message}; use lightning::ln::peer_handler::CustomMessageHandler; use lightning_liquidity::events::LiquidityEvent; @@ -30,7 +30,7 @@ use bitcoin::{Address, Network, OutPoint}; use std::str::FromStr; use std::sync::Arc; -use lightning::ln::functional_test_utils::{create_network, Node}; +use lightning::ln::functional_test_utils::{Node, create_network}; use lightning_liquidity::lsps1::msgs::LSPS1OrderId; use lightning_liquidity::utils::time::TimeProvider; diff --git a/lightning-liquidity/tests/lsps2_integration_tests.rs b/lightning-liquidity/tests/lsps2_integration_tests.rs index fbff2eae4cd..3d1479bdb9c 100644 --- a/lightning-liquidity/tests/lsps2_integration_tests.rs +++ b/lightning-liquidity/tests/lsps2_integration_tests.rs @@ -3,8 +3,8 @@ mod common; use common::{ - create_service_and_client_nodes_with_kv_stores, create_service_client_and_payer_nodes, - get_lsps_message, LSPSNodes, LSPSNodesWithPayer, LiquidityNode, + LSPSNodes, LSPSNodesWithPayer, LiquidityNode, create_service_and_client_nodes_with_kv_stores, + create_service_client_and_payer_nodes, get_lsps_message, }; use lightning::events::{ClosureReason, Event}; @@ -30,10 +30,10 @@ use lightning_liquidity::utils::time::{DefaultTimeProvider, TimeProvider}; use lightning_liquidity::{LiquidityClientConfig, LiquidityManagerSync, LiquidityServiceConfig}; use lightning::ln::channelmanager::{InterceptId, MIN_FINAL_CLTV_EXPIRY_DELTA}; +use lightning::ln::functional_test_utils::{Node, create_network}; use lightning::ln::functional_test_utils::{ create_chanmon_cfgs, create_node_cfgs, create_node_chanmgrs, }; -use lightning::ln::functional_test_utils::{create_network, Node}; use lightning::ln::peer_handler::CustomMessageHandler; use lightning::log_error; use lightning::routing::router::{RouteHint, RouteHintHop}; @@ -47,8 +47,8 @@ use lightning_invoice::{Bolt11Invoice, InvoiceBuilder, RoutingFees}; use lightning_types::payment::PaymentHash; -use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey}; use bitcoin::Network; +use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey}; use lightning_types::payment::PaymentPreimage; use std::str::FromStr; @@ -1483,17 +1483,19 @@ fn create_channel_with_manual_broadcast( client_node: &LiquidityNode, user_channel_id: u128, expected_outbound_amount_msat: &u64, mark_broadcast_safe: bool, ) -> (ChannelId, bitcoin::Transaction) { - assert!(service_node - .node - .create_channel( - *client_node_id, - *expected_outbound_amount_msat, - 0, - user_channel_id, - None, - None - ) - .is_ok()); + assert!( + service_node + .node + .create_channel( + *client_node_id, + *expected_outbound_amount_msat, + 0, + user_channel_id, + None, + None + ) + .is_ok() + ); let open_channel = get_event_msg!(service_node, MessageSendEvent::SendOpenChannel, *client_node_id); @@ -1976,9 +1978,9 @@ fn htlc_timeout_before_client_claim_results_in_handling_failed() { // Payer->service channel should remain open { let chans = service_node.inner.node.list_channels(); - assert!(chans - .iter() - .any(|cd| cd.counterparty.node_id == payer_node_id && cd.is_channel_ready)); + assert!( + chans.iter().any(|cd| cd.counterparty.node_id == payer_node_id && cd.is_channel_ready) + ); } service_node.inner.node.get_and_clear_pending_msg_events(); @@ -2247,9 +2249,9 @@ fn client_trusts_lsp_partial_fee_does_not_trigger_broadcast() { other => panic!("Unexpected event: {:?}", other), }; - assert!(service_handler - .channel_needs_manual_broadcast(user_channel_id, &client_node_id) - .unwrap()); + assert!( + service_handler.channel_needs_manual_broadcast(user_channel_id, &client_node_id).unwrap() + ); let (channel_id, _) = create_channel_with_manual_broadcast( &service_node_id, diff --git a/lightning-liquidity/tests/lsps5_integration_tests.rs b/lightning-liquidity/tests/lsps5_integration_tests.rs index 2b32b4dcbc6..28e79ad515d 100644 --- a/lightning-liquidity/tests/lsps5_integration_tests.rs +++ b/lightning-liquidity/tests/lsps5_integration_tests.rs @@ -3,20 +3,21 @@ mod common; use common::{ - create_service_and_client_nodes, create_service_and_client_nodes_with_kv_stores, - get_lsps_message, LSPSNodes, LiquidityNode, + LSPSNodes, LiquidityNode, create_service_and_client_nodes, + create_service_and_client_nodes_with_kv_stores, get_lsps_message, }; use lightning::events::ClosureReason; use lightning::ln::channelmanager::InterceptId; use lightning::ln::functional_test_utils::{ - check_closed_event, close_channel, create_chan_between_nodes, create_chanmon_cfgs, - create_network, create_node_cfgs, create_node_chanmgrs, Node, + Node, check_closed_event, close_channel, create_chan_between_nodes, create_chanmon_cfgs, + create_network, create_node_cfgs, create_node_chanmgrs, }; use lightning::ln::msgs::Init; use lightning::ln::peer_handler::CustomMessageHandler; use lightning::util::hash_tables::HashSet; use lightning::util::test_utils::TestStore; +use lightning_liquidity::LiquidityManagerSync; use lightning_liquidity::events::LiquidityEvent; use lightning_liquidity::lsps0::ser::LSPSDateTime; use lightning_liquidity::lsps2::client::LSPS2ClientConfig; @@ -30,14 +31,13 @@ use lightning_liquidity::lsps5::msgs::{ WebhookNotificationMethod, }; use lightning_liquidity::lsps5::service::{ - LSPS5ServiceConfig, DEFAULT_MAX_WEBHOOKS_PER_CLIENT, NOTIFICATION_COOLDOWN_TIME, + DEFAULT_MAX_WEBHOOKS_PER_CLIENT, LSPS5ServiceConfig, NOTIFICATION_COOLDOWN_TIME, }; use lightning_liquidity::lsps5::service::{ MIN_WEBHOOK_RETENTION_DAYS, PRUNE_STALE_WEBHOOKS_INTERVAL_DAYS, }; use lightning_liquidity::lsps5::validator::{LSPS5Validator, MAX_RECENT_SIGNATURES}; use lightning_liquidity::utils::time::{DefaultTimeProvider, TimeProvider}; -use lightning_liquidity::LiquidityManagerSync; use lightning_liquidity::{LiquidityClientConfig, LiquidityServiceConfig}; use lightning_types::payment::PaymentHash; diff --git a/lightning-macros/Cargo.toml b/lightning-macros/Cargo.toml index 822b50816df..2eb157f6002 100644 --- a/lightning-macros/Cargo.toml +++ b/lightning-macros/Cargo.toml @@ -7,8 +7,8 @@ repository = "https://github.com/lightningdevkit/rust-lightning/" description = """ Proc macros used by LDK """ -edition = "2021" -rust-version = "1.75" +edition = "2024" +rust-version = "1.85" [package.metadata.docs.rs] rustdoc-args = ["--cfg", "docsrs"] diff --git a/lightning-macros/src/lib.rs b/lightning-macros/src/lib.rs index 778da45ee8f..169bdaf20e1 100644 --- a/lightning-macros/src/lib.rs +++ b/lightning-macros/src/lib.rs @@ -21,12 +21,12 @@ extern crate alloc; use alloc::string::ToString; -use proc_macro::{Delimiter, Group, TokenStream, TokenTree}; +use proc_macro::{Delimiter, Group, Punct, Spacing, TokenStream, TokenTree}; use proc_macro2::TokenStream as TokenStream2; use quote::quote; use syn::spanned::Spanned; -use syn::{parse, ImplItemFn, Token}; -use syn::{parse_macro_input, Item}; +use syn::{ImplItemFn, Token, parse}; +use syn::{Item, parse_macro_input}; fn add_async_method(mut parsed: ImplItemFn) -> TokenStream { let output = quote! { @@ -162,6 +162,8 @@ fn process_fields(group: Group) -> proc_macro::TokenStream { /// /// Wraps a `match self {..}` statement and scans the fields in the match patterns (in the form /// `ref $field_name: $field_ty`) for types marked `legacy` or `custom`, skipping those fields. +/// The expanded match dereferences `self` so these explicit `ref` patterns continue to compile +/// under Rust 2024's match ergonomics. /// /// Specifically, it expects input like the following, simply dropping `field3` and the /// `: $field_ty` after each field name. @@ -187,6 +189,7 @@ pub fn skip_legacy_fields(expr: TokenStream) -> TokenStream { let self_ident = stream.next().unwrap(); expect_ident(&self_ident, Some("self")); + res.extend(proc_macro::TokenStream::from(TokenTree::Punct(Punct::new('*', Spacing::Alone)))); res.extend(proc_macro::TokenStream::from(self_ident)); let arms = stream.next().unwrap(); diff --git a/lightning-net-tokio/Cargo.toml b/lightning-net-tokio/Cargo.toml index 79b227f44dc..b4bae918b77 100644 --- a/lightning-net-tokio/Cargo.toml +++ b/lightning-net-tokio/Cargo.toml @@ -9,8 +9,8 @@ description = """ Implementation of the rust-lightning network stack using Tokio. For Rust-Lightning clients which wish to make direct connections to Lightning P2P nodes, this is a simple alternative to implementing the required network stack, especially for those already using Tokio. """ -edition = "2021" -rust-version = "1.75" +edition = "2024" +rust-version = "1.85" [package.metadata.docs.rs] all-features = true diff --git a/lightning-net-tokio/src/lib.rs b/lightning-net-tokio/src/lib.rs index 2e8e568f97e..5e47aca2b28 100644 --- a/lightning-net-tokio/src/lib.rs +++ b/lightning-net-tokio/src/lib.rs @@ -44,7 +44,7 @@ use std::hash::Hash; use std::net::SocketAddr; use std::net::TcpStream as StdTcpStream; use std::ops::Deref; -use std::pin::{pin, Pin}; +use std::pin::{Pin, pin}; use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::{Arc, Mutex}; use std::task::{self, Poll}; @@ -105,10 +105,10 @@ pub(crate) struct ThreeSelector< } impl< - A: Future> + Unpin, - B: Future> + Unpin, - C: Future> + Unpin, - > Future for ThreeSelector + A: Future> + Unpin, + B: Future> + Unpin, + C: Future> + Unpin, +> Future for ThreeSelector { type Output = SelectorOutput; fn poll(mut self: Pin<&mut Self>, ctx: &mut task::Context<'_>) -> Poll { @@ -783,9 +783,9 @@ impl Hash for SocketDescriptor { #[cfg(test)] mod tests { + use bitcoin::Network; use bitcoin::constants::ChainHash; use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey}; - use bitcoin::Network; use lightning::ln::msgs::*; use lightning::ln::peer_handler::{IgnoringMessageHandler, MessageHandler, PeerManager}; use lightning::ln::types::ChannelId; diff --git a/lightning-persister/Cargo.toml b/lightning-persister/Cargo.toml index 19c5ac2545e..6e0534cecd8 100644 --- a/lightning-persister/Cargo.toml +++ b/lightning-persister/Cargo.toml @@ -8,8 +8,8 @@ readme = "../README.md" description = """ Utilities for LDK data persistence and retrieval. """ -edition = "2021" -rust-version = "1.75" +edition = "2024" +rust-version = "1.85" [package.metadata.docs.rs] all-features = true @@ -27,7 +27,7 @@ tokio = { version = "1.35", optional = true, default-features = false, features windows-sys = { version = "0.48.0", default-features = false, features = ["Win32_Storage_FileSystem", "Win32_Foundation"] } [target.'cfg(ldk_bench)'.dependencies] -criterion = { version = "0.4", optional = true, default-features = false } +criterion = { version = "0.5", optional = true, default-features = false } [dev-dependencies] lightning = { version = "0.3.0", path = "../lightning", features = ["_test_utils"] } diff --git a/lightning-persister/src/fs_store/common.rs b/lightning-persister/src/fs_store/common.rs index 77321f6f06f..4f440deb847 100644 --- a/lightning-persister/src/fs_store/common.rs +++ b/lightning-persister/src/fs_store/common.rs @@ -25,11 +25,7 @@ use std::os::windows::ffi::OsStrExt; #[cfg(target_os = "windows")] macro_rules! call { ($e: expr) => { - if $e != 0 { - Ok(()) - } else { - Err(std::io::Error::last_os_error()) - } + if $e != 0 { Ok(()) } else { Err(std::io::Error::last_os_error()) } }; } diff --git a/lightning-persister/src/fs_store/v1.rs b/lightning-persister/src/fs_store/v1.rs index 776aba630c4..93e9cfaea61 100644 --- a/lightning-persister/src/fs_store/v1.rs +++ b/lightning-persister/src/fs_store/v1.rs @@ -101,8 +101,8 @@ mod tests { do_read_write_remove_list_persist, do_test_data_migration, do_test_store, }; - use lightning::chain::chainmonitor::Persist; use lightning::chain::ChannelMonitorUpdateStatus; + use lightning::chain::chainmonitor::Persist; use lightning::events::ClosureReason; use lightning::ln::functional_test_utils::*; use lightning::ln::msgs::BaseMessageHandler; diff --git a/lightning-persister/src/fs_store/v2.rs b/lightning-persister/src/fs_store/v2.rs index 2f79cae0da3..f684aa09f77 100644 --- a/lightning-persister/src/fs_store/v2.rs +++ b/lightning-persister/src/fs_store/v2.rs @@ -1,6 +1,6 @@ //! Objects related to [`FilesystemStoreV2`] live here. use crate::fs_store::common::{ - dir_entry_is_key, get_key_from_dir_entry_path, FilesystemStoreState, + FilesystemStoreState, dir_entry_is_key, get_key_from_dir_entry_path, }; use lightning::util::persist::{ @@ -488,11 +488,9 @@ mod tests { assert_eq!(KVStoreSync::read(&fs_store, "primary", "secondary", "key3").unwrap(), data); // Verify files are named just by key (no timestamp prefix) - assert!(temp_path - .join(EMPTY_NAMESPACE_DIR) - .join(EMPTY_NAMESPACE_DIR) - .join("key1") - .exists()); + assert!( + temp_path.join(EMPTY_NAMESPACE_DIR).join(EMPTY_NAMESPACE_DIR).join("key1").exists() + ); assert!(temp_path.join("primary").join(EMPTY_NAMESPACE_DIR).join("key2").exists()); assert!(temp_path.join("primary").join("secondary").join("key3").exists()); } diff --git a/lightning-persister/src/test_utils.rs b/lightning-persister/src/test_utils.rs index b8f3eb0bd99..a2ca5468047 100644 --- a/lightning-persister/src/test_utils.rs +++ b/lightning-persister/src/test_utils.rs @@ -1,8 +1,8 @@ use lightning::events::ClosureReason; use lightning::ln::functional_test_utils::*; use lightning::util::persist::{ - migrate_kv_store_data, read_channel_monitors, KVStoreSync, MigratableKVStore, - KVSTORE_NAMESPACE_KEY_ALPHABET, KVSTORE_NAMESPACE_KEY_MAX_LEN, + KVSTORE_NAMESPACE_KEY_ALPHABET, KVSTORE_NAMESPACE_KEY_MAX_LEN, KVStoreSync, MigratableKVStore, + migrate_kv_store_data, read_channel_monitors, }; use lightning::util::test_utils; diff --git a/lightning-persister/src/utils.rs b/lightning-persister/src/utils.rs index e8e7be5ce5d..757d28fb844 100644 --- a/lightning-persister/src/utils.rs +++ b/lightning-persister/src/utils.rs @@ -30,13 +30,21 @@ pub(crate) fn check_namespace_key_validity( } if primary_namespace.is_empty() && !secondary_namespace.is_empty() { - debug_assert!(false, + debug_assert!( + false, "Failed to {} {}/{}/{}: primary namespace may not be empty if a non-empty secondary namespace is given.", operation, - PrintableString(primary_namespace), PrintableString(secondary_namespace), PrintableString(key)); + PrintableString(primary_namespace), + PrintableString(secondary_namespace), + PrintableString(key) + ); let msg = format!( - "Failed to {} {}/{}/{}: primary namespace may not be empty if a non-empty secondary namespace is given.", operation, - PrintableString(primary_namespace), PrintableString(secondary_namespace), PrintableString(key)); + "Failed to {} {}/{}/{}: primary namespace may not be empty if a non-empty secondary namespace is given.", + operation, + PrintableString(primary_namespace), + PrintableString(secondary_namespace), + PrintableString(key) + ); return Err(std::io::Error::other(msg)); } @@ -44,22 +52,38 @@ pub(crate) fn check_namespace_key_validity( || !is_valid_kvstore_str(secondary_namespace) || !is_valid_kvstore_str(key) { - debug_assert!(false, "Failed to {} {}/{}/{}: primary namespace, secondary namespace, and key must be valid.", + debug_assert!( + false, + "Failed to {} {}/{}/{}: primary namespace, secondary namespace, and key must be valid.", operation, - PrintableString(primary_namespace), PrintableString(secondary_namespace), PrintableString(key)); - let msg = format!("Failed to {} {}/{}/{}: primary namespace, secondary namespace, and key must be valid.", + PrintableString(primary_namespace), + PrintableString(secondary_namespace), + PrintableString(key) + ); + let msg = format!( + "Failed to {} {}/{}/{}: primary namespace, secondary namespace, and key must be valid.", operation, - PrintableString(primary_namespace), PrintableString(secondary_namespace), PrintableString(key)); + PrintableString(primary_namespace), + PrintableString(secondary_namespace), + PrintableString(key) + ); return Err(std::io::Error::other(msg)); } } else { if primary_namespace.is_empty() && !secondary_namespace.is_empty() { - debug_assert!(false, + debug_assert!( + false, "Failed to {} {}/{}: primary namespace may not be empty if a non-empty secondary namespace is given.", - operation, PrintableString(primary_namespace), PrintableString(secondary_namespace)); + operation, + PrintableString(primary_namespace), + PrintableString(secondary_namespace) + ); let msg = format!( "Failed to {} {}/{}: primary namespace may not be empty if a non-empty secondary namespace is given.", - operation, PrintableString(primary_namespace), PrintableString(secondary_namespace)); + operation, + PrintableString(primary_namespace), + PrintableString(secondary_namespace) + ); return Err(std::io::Error::other(msg)); } if !is_valid_kvstore_str(primary_namespace) || !is_valid_kvstore_str(secondary_namespace) { diff --git a/lightning-rapid-gossip-sync/Cargo.toml b/lightning-rapid-gossip-sync/Cargo.toml index b623a5aed13..c8160f586db 100644 --- a/lightning-rapid-gossip-sync/Cargo.toml +++ b/lightning-rapid-gossip-sync/Cargo.toml @@ -4,8 +4,8 @@ version = "0.3.0+git" authors = ["Arik Sosman "] license = "MIT OR Apache-2.0" repository = "https://github.com/lightningdevkit/rust-lightning" -edition = "2021" -rust-version = "1.75" +edition = "2024" +rust-version = "1.85" description = """ Utility to process gossip routing data from Rapid Gossip Sync Server. """ @@ -21,7 +21,7 @@ bitcoin_hashes = { version = "0.14.0", default-features = false } bitcoin-io = { version = "0.1.2", default-features = false } [target.'cfg(ldk_bench)'.dependencies] -criterion = { version = "0.4", optional = true, default-features = false } +criterion = { version = "0.5", optional = true, default-features = false } [dev-dependencies] lightning = { version = "0.3.0", path = "../lightning", features = ["_test_utils"] } diff --git a/lightning-rapid-gossip-sync/src/lib.rs b/lightning-rapid-gossip-sync/src/lib.rs index a9653754655..cd40963139d 100644 --- a/lightning-rapid-gossip-sync/src/lib.rs +++ b/lightning-rapid-gossip-sync/src/lib.rs @@ -307,7 +307,10 @@ mod tests { let start = std::time::Instant::now(); let sync_result = rapid_sync.sync_network_graph_with_file_path("./res/full_graph.lngossip"); if let Err(GraphSyncError::DecodeError(DecodeError::Io(io_error))) = &sync_result { - let error_string = format!("Input file lightning-rapid-gossip-sync/res/full_graph.lngossip is missing! Download it from https://bitcoin.ninja/ldk-compressed_graph-285cb27df79-2022-07-21.bin\n\n{:?}", io_error); + let error_string = format!( + "Input file lightning-rapid-gossip-sync/res/full_graph.lngossip is missing! Download it from https://bitcoin.ninja/ldk-compressed_graph-285cb27df79-2022-07-21.bin\n\n{:?}", + io_error + ); #[cfg(not(require_route_graph_test))] { println!("{}", error_string); diff --git a/lightning-rapid-gossip-sync/src/processing.rs b/lightning-rapid-gossip-sync/src/processing.rs index 9d3287969f2..60c7f439912 100644 --- a/lightning-rapid-gossip-sync/src/processing.rs +++ b/lightning-rapid-gossip-sync/src/processing.rs @@ -326,8 +326,14 @@ impl>, L: Logger> RapidGossipSync { previous_scid = 0; let update_count: u32 = Readable::read(read_cursor)?; - log_debug!(self.logger, "Processing RGS update from {} with {} nodes, {} channel announcements and {} channel updates.", - latest_seen_timestamp, node_id_count, announcement_count, update_count); + log_debug!( + self.logger, + "Processing RGS update from {} with {} nodes, {} channel announcements and {} channel updates.", + latest_seen_timestamp, + node_id_count, + announcement_count, + update_count + ); if update_count == 0 { return Ok(latest_seen_timestamp); } @@ -400,9 +406,12 @@ impl>, L: Logger> RapidGossipSync { synthetic_update.fee_proportional_millionths = directional_info.fees.proportional_millionths; } else { - log_trace!(self.logger, + log_trace!( + self.logger, "Skipping application of channel update for chan {} with flags {} as original data is missing.", - short_channel_id, channel_flags); + short_channel_id, + channel_flags + ); skip_update_for_unknown_channel = true; } }; @@ -785,14 +794,22 @@ mod tests { assert_eq!(network_graph.read_only().channels().len(), 2); let initialized = network_graph.to_string(); - assert!(initialized - .contains("021607cfce19a4c5e7e6e738663dfafbbbac262e4ff76c2c9b30dbeefc35c00643")); - assert!(initialized - .contains("02247d9db0dfafea745ef8c9e161eb322f73ac3f8858d8730b6fd97254747ce76b")); - assert!(initialized - .contains("029e01f279986acc83ba235d46d80aede0b7595f410353b93a8ab540bb677f4432")); - assert!(initialized - .contains("02c913118a8895b9e29c89af6e20ed00d95a1f64e4952edbafa84d048f26804c61")); + assert!( + initialized + .contains("021607cfce19a4c5e7e6e738663dfafbbbac262e4ff76c2c9b30dbeefc35c00643") + ); + assert!( + initialized + .contains("02247d9db0dfafea745ef8c9e161eb322f73ac3f8858d8730b6fd97254747ce76b") + ); + assert!( + initialized + .contains("029e01f279986acc83ba235d46d80aede0b7595f410353b93a8ab540bb677f4432") + ); + assert!( + initialized + .contains("02c913118a8895b9e29c89af6e20ed00d95a1f64e4952edbafa84d048f26804c61") + ); assert!(initialized.contains("619737530008010752")); assert!(initialized.contains("783241506229452801")); diff --git a/lightning-tests/Cargo.toml b/lightning-tests/Cargo.toml index 05a5bd55ce5..8587fd0fad2 100644 --- a/lightning-tests/Cargo.toml +++ b/lightning-tests/Cargo.toml @@ -5,8 +5,8 @@ authors = ["Matt Corallo"] license = "MIT OR Apache-2.0" repository = "https://github.com/lightningdevkit/rust-lightning/" description = "Tests for LDK crates" -edition = "2021" -rust-version = "1.75" +edition = "2024" +rust-version = "1.85" [features] diff --git a/lightning-tests/src/upgrade_downgrade_tests.rs b/lightning-tests/src/upgrade_downgrade_tests.rs index 7f607bba848..4e40a59bec7 100644 --- a/lightning-tests/src/upgrade_downgrade_tests.rs +++ b/lightning-tests/src/upgrade_downgrade_tests.rs @@ -60,7 +60,7 @@ use lightning_types::payment::{PaymentHash, PaymentPreimage, PaymentSecret}; use bitcoin::script::Builder; use bitcoin::secp256k1::Secp256k1; -use bitcoin::{opcodes, Amount, TxOut}; +use bitcoin::{Amount, TxOut, opcodes}; use std::sync::Arc; @@ -78,7 +78,7 @@ fn simple_upgrade() { let payment_preimage = lightning_0_1_utils::route_payment(&nodes[0], &[&nodes[1]], 1_000_000); - preimage = PaymentPreimage(payment_preimage.0 .0); + preimage = PaymentPreimage(payment_preimage.0.0); node_a_ser = nodes[0].node.encode(); node_b_ser = nodes[1].node.encode(); diff --git a/lightning-transaction-sync/Cargo.toml b/lightning-transaction-sync/Cargo.toml index 4bc37d7ff48..d905e7be566 100644 --- a/lightning-transaction-sync/Cargo.toml +++ b/lightning-transaction-sync/Cargo.toml @@ -8,8 +8,8 @@ readme = "../README.md" description = """ Utilities for syncing LDK via the transaction-based `Confirm` interface. """ -edition = "2021" -rust-version = "1.75" +edition = "2024" +rust-version = "1.85" [package.metadata.docs.rs] all-features = true diff --git a/lightning-transaction-sync/src/electrum.rs b/lightning-transaction-sync/src/electrum.rs index 9d643f48511..e6478ab31db 100644 --- a/lightning-transaction-sync/src/electrum.rs +++ b/lightning-transaction-sync/src/electrum.rs @@ -8,9 +8,9 @@ use crate::common::{ConfirmedTx, FilterQueue, SyncState}; use crate::error::{InternalError, TxSyncError}; -use electrum_client::utils::validate_merkle_proof; use electrum_client::Client as ElectrumClient; use electrum_client::ElectrumApi; +use electrum_client::utils::validate_merkle_proof; use lightning::chain::WatchedOutput; use lightning::chain::{Confirm, Filter}; @@ -122,14 +122,17 @@ impl ElectrumSyncClient { ); }, Ok(true) => { - log_debug!(self.logger, - "Encountered inconsistency during transaction sync, restarting."); + log_debug!( + self.logger, + "Encountered inconsistency during transaction sync, restarting." + ); sync_state.pending_sync = true; continue; }, Err(err) => { // (Semi-)permanent failure, retry later. - log_error!(self.logger, + log_error!( + self.logger, "Failed during transaction sync, aborting. Synced so far: {} confirmed, {} unconfirmed.", num_confirmed, num_unconfirmed @@ -141,7 +144,8 @@ impl ElectrumSyncClient { }, Err(err) => { // (Semi-)permanent failure, retry later. - log_error!(self.logger, + log_error!( + self.logger, "Failed during transaction sync, aborting. Synced so far: {} confirmed, {} unconfirmed.", num_confirmed, num_unconfirmed @@ -171,14 +175,17 @@ impl ElectrumSyncClient { .sync_confirmed_transactions(&confirmables, confirmed_txs); }, Ok(true) => { - log_debug!(self.logger, - "Encountered inconsistency during transaction sync, restarting."); + log_debug!( + self.logger, + "Encountered inconsistency during transaction sync, restarting." + ); sync_state.pending_sync = true; continue; }, Err(err) => { // (Semi-)permanent failure, retry later. - log_error!(self.logger, + log_error!( + self.logger, "Failed during transaction sync, aborting. Synced so far: {} confirmed, {} unconfirmed.", num_confirmed, num_unconfirmed @@ -199,7 +206,8 @@ impl ElectrumSyncClient { }, Err(err) => { // (Semi-)permanent failure, retry later. - log_error!(self.logger, + log_error!( + self.logger, "Failed during transaction sync, aborting. Synced so far: {} confirmed, {} unconfirmed.", num_confirmed, num_unconfirmed @@ -279,7 +287,11 @@ impl ElectrumSyncClient { // To protect against this (highly unlikely) attack vector, we check that the // transaction is at least 65 bytes in length. if tx.total_size() == 64 { - log_error!(self.logger, "Skipping transaction {} due to retrieving potentially invalid tx data.", txid); + log_error!( + self.logger, + "Skipping transaction {} due to retrieving potentially invalid tx data.", + txid + ); continue; } @@ -434,9 +446,13 @@ impl ElectrumSyncClient { unconfirmed_txs.push(txid); } else { - log_error!(self.logger, - "Untracked confirmation of funding transaction. Please ensure none of your channels had been created with LDK prior to version 0.0.113!"); - panic!("Untracked confirmation of funding transaction. Please ensure none of your channels had been created with LDK prior to version 0.0.113!"); + log_error!( + self.logger, + "Untracked confirmation of funding transaction. Please ensure none of your channels had been created with LDK prior to version 0.0.113!" + ); + panic!( + "Untracked confirmation of funding transaction. Please ensure none of your channels had been created with LDK prior to version 0.0.113!" + ); } } Ok(unconfirmed_txs) diff --git a/lightning-transaction-sync/src/esplora.rs b/lightning-transaction-sync/src/esplora.rs index 7d3550d65b1..371d2b5657d 100644 --- a/lightning-transaction-sync/src/esplora.rs +++ b/lightning-transaction-sync/src/esplora.rs @@ -17,11 +17,11 @@ use lightning_macros::{maybe_async, maybe_await}; use bitcoin::{BlockHash, Script, Txid}; -#[cfg(not(feature = "async-interface"))] -use esplora_client::blocking::BlockingClient; +use esplora_client::Builder; #[cfg(feature = "async-interface")] use esplora_client::r#async::AsyncClient; -use esplora_client::Builder; +#[cfg(not(feature = "async-interface"))] +use esplora_client::blocking::BlockingClient; use core::ops::Deref; use std::collections::HashSet; @@ -122,7 +122,10 @@ impl EsploraSyncClient { if check_tip_hash != tip_hash { tip_hash = check_tip_hash; - log_debug!(self.logger, "Encountered inconsistency during transaction sync, restarting."); + log_debug!( + self.logger, + "Encountered inconsistency during transaction sync, restarting." + ); sync_state.pending_sync = true; continue; } @@ -134,11 +137,12 @@ impl EsploraSyncClient { }, Err(err) => { // (Semi-)permanent failure, retry later. - log_error!(self.logger, + log_error!( + self.logger, "Failed during transaction sync, aborting. Synced so far: {} confirmed, {} unconfirmed.", num_confirmed, num_unconfirmed - ); + ); sync_state.pending_sync = true; return Err(TxSyncError::from(err)); }, @@ -146,7 +150,8 @@ impl EsploraSyncClient { }, Err(err) => { // (Semi-)permanent failure, retry later. - log_error!(self.logger, + log_error!( + self.logger, "Failed during transaction sync, aborting. Synced so far: {} confirmed, {} unconfirmed.", num_confirmed, num_unconfirmed @@ -173,7 +178,8 @@ impl EsploraSyncClient { }, Err(err) => { // (Semi-)permanent failure, retry later. - log_error!(self.logger, + log_error!( + self.logger, "Failed during transaction sync, aborting. Synced so far: {} confirmed, {} unconfirmed.", num_confirmed, num_unconfirmed @@ -193,8 +199,10 @@ impl EsploraSyncClient { if check_tip_hash != tip_hash { tip_hash = check_tip_hash; - log_debug!(self.logger, - "Encountered inconsistency during transaction sync, restarting."); + log_debug!( + self.logger, + "Encountered inconsistency during transaction sync, restarting." + ); sync_state.pending_sync = true; continue; } @@ -204,7 +212,8 @@ impl EsploraSyncClient { }, Err(err) => { // (Semi-)permanent failure, retry later. - log_error!(self.logger, + log_error!( + self.logger, "Failed during transaction sync, aborting. Synced so far: {} confirmed, {} unconfirmed.", num_confirmed, num_unconfirmed @@ -225,7 +234,8 @@ impl EsploraSyncClient { }, Err(err) => { // (Semi-)permanent failure, retry later. - log_error!(self.logger, + log_error!( + self.logger, "Failed during transaction sync, aborting. Synced so far: {} confirmed, {} unconfirmed.", num_confirmed, num_unconfirmed @@ -302,10 +312,9 @@ impl EsploraSyncClient { } for (_, output) in &sync_state.watched_outputs { - if let Some(output_status) = maybe_await!(self - .client - .get_output_status(&output.outpoint.txid, output.outpoint.index as u64))? - { + if let Some(output_status) = maybe_await!( + self.client.get_output_status(&output.outpoint.txid, output.outpoint.index as u64) + )? { if let Some(spending_txid) = output_status.txid { if let Some(spending_tx_status) = output_status.status { if confirmed_txs.iter().any(|ctx| ctx.txid == spending_txid) { @@ -313,7 +322,11 @@ impl EsploraSyncClient { // Skip inserting duplicate ConfirmedTx entry continue; } else { - log_trace!(self.logger, "Inconsistency: Detected previously-confirmed Tx {} as unconfirmed", spending_txid); + log_trace!( + self.logger, + "Inconsistency: Detected previously-confirmed Tx {} as unconfirmed", + spending_txid + ); return Err(InternalError::Inconsistency); } } @@ -368,7 +381,11 @@ impl EsploraSyncClient { || matches.len() != 1 || matches[0] != txid { - log_error!(self.logger, "Retrieved Merkle block for txid {} doesn't match expectations. This should not happen. Please verify server integrity.", txid); + log_error!( + self.logger, + "Retrieved Merkle block for txid {} doesn't match expectations. This should not happen. Please verify server integrity.", + txid + ); return Err(InternalError::Failed); } @@ -376,7 +393,11 @@ impl EsploraSyncClient { let pos = *indexes.first().unwrap() as usize; if let Some(tx) = maybe_await!(self.client.get_tx(&txid))? { if tx.compute_txid() != txid { - log_error!(self.logger, "Retrieved transaction for txid {} doesn't match expectations. This should not happen. Please verify server integrity.", txid); + log_error!( + self.logger, + "Retrieved transaction for txid {} doesn't match expectations. This should not happen. Please verify server integrity.", + txid + ); return Err(InternalError::Failed); } @@ -445,8 +466,13 @@ impl EsploraSyncClient { unconfirmed_txs.push(txid); } else { - log_error!(self.logger, "Untracked confirmation of funding transaction. Please ensure none of your channels had been created with LDK prior to version 0.0.113!"); - panic!("Untracked confirmation of funding transaction. Please ensure none of your channels had been created with LDK prior to version 0.0.113!"); + log_error!( + self.logger, + "Untracked confirmation of funding transaction. Please ensure none of your channels had been created with LDK prior to version 0.0.113!" + ); + panic!( + "Untracked confirmation of funding transaction. Please ensure none of your channels had been created with LDK prior to version 0.0.113!" + ); } } Ok(unconfirmed_txs) diff --git a/lightning-transaction-sync/tests/integration_tests.rs b/lightning-transaction-sync/tests/integration_tests.rs index 07b190ad30b..10ff3a33104 100644 --- a/lightning-transaction-sync/tests/integration_tests.rs +++ b/lightning-transaction-sync/tests/integration_tests.rs @@ -19,7 +19,7 @@ use bitcoin::network::Network; use bitcoin::{Amount, BlockHash, Txid}; use electrsd::corepc_node::Node as BitcoinD; -use electrsd::{corepc_node, ElectrsD}; +use electrsd::{ElectrsD, corepc_node}; use std::collections::{HashMap, HashSet}; use std::env; diff --git a/lightning-types/Cargo.toml b/lightning-types/Cargo.toml index eddd3d27fb0..7c99d518439 100644 --- a/lightning-types/Cargo.toml +++ b/lightning-types/Cargo.toml @@ -8,8 +8,8 @@ readme = "../README.md" description = """ Basic types which are used in the lightning network """ -edition = "2021" -rust-version = "1.75" +edition = "2024" +rust-version = "1.85" [package.metadata.docs.rs] rustdoc-args = ["--cfg", "docsrs"] diff --git a/lightning-types/src/features.rs b/lightning-types/src/features.rs index 21d59b2b917..b81197492ac 100644 --- a/lightning-types/src/features.rs +++ b/lightning-types/src/features.rs @@ -627,7 +627,8 @@ mod sealed { supports_channel_type, requires_channel_type ); - define_feature!(47, + define_feature!( + 47, SCIDPrivacy, [InitContext, NodeContext, ChannelTypeContext], "Feature flags for only forwarding with SCID aliasing. Called `option_scid_alias` in the BOLTs", diff --git a/lightning-types/src/payment.rs b/lightning-types/src/payment.rs index 0f0fcf7b516..076447be9ab 100644 --- a/lightning-types/src/payment.rs +++ b/lightning-types/src/payment.rs @@ -11,7 +11,7 @@ use core::borrow::Borrow; -use bitcoin::hashes::{sha256::Hash as Sha256, Hash as _}; +use bitcoin::hashes::{Hash as _, sha256::Hash as Sha256}; use bitcoin::hex::display::impl_fmt_traits; /// The payment hash is the hash of the [`PaymentPreimage`] which is the value used to lock funds diff --git a/lightning/Cargo.toml b/lightning/Cargo.toml index 661f8854f89..abe31687134 100644 --- a/lightning/Cargo.toml +++ b/lightning/Cargo.toml @@ -9,8 +9,8 @@ description = """ A Complete Bitcoin Lightning Library in Rust. Handles the core functionality of the Lightning Network, allowing clients to implement custom wallet, chain interactions, storage and network logic without enforcing a specific runtime. """ -edition = "2021" -rust-version = "1.75" +edition = "2024" +rust-version = "1.85" [package.metadata.docs.rs] features = ["std", "dnssec"] @@ -64,7 +64,7 @@ default-features = false features = ["bitcoinconsensus", "secp-recovery"] [target.'cfg(ldk_bench)'.dependencies] -criterion = { version = "0.4", optional = true, default-features = false } +criterion = { version = "0.5", optional = true, default-features = false } [lints] workspace = true diff --git a/lightning/src/blinded_path/payment.rs b/lightning/src/blinded_path/payment.rs index f06c91bf6e0..8dc946331d7 100644 --- a/lightning/src/blinded_path/payment.rs +++ b/lightning/src/blinded_path/payment.rs @@ -1241,14 +1241,16 @@ mod tests { payment_context: PaymentContext::Bolt12Refund(Bolt12RefundContext {}), }; let htlc_minimum_msat = 3798; - assert!(super::compute_payinfo( - &intermediate_nodes[..], - &[], - &recv_tlvs, - htlc_minimum_msat - 1, - TEST_FINAL_CLTV as u16 - ) - .is_err()); + assert!( + super::compute_payinfo( + &intermediate_nodes[..], + &[], + &recv_tlvs, + htlc_minimum_msat - 1, + TEST_FINAL_CLTV as u16 + ) + .is_err() + ); let htlc_maximum_msat = htlc_minimum_msat + 1; let blinded_payinfo = super::compute_payinfo( diff --git a/lightning/src/blinded_path/utils.rs b/lightning/src/blinded_path/utils.rs index 339b4337eb3..12dec9694b2 100644 --- a/lightning/src/blinded_path/utils.rs +++ b/lightning/src/blinded_path/utils.rs @@ -17,7 +17,7 @@ use bitcoin::secp256k1::{self, PublicKey, Scalar, Secp256k1, SecretKey}; use super::message::BlindedMessagePath; use super::{BlindedHop, BlindedPath}; -use crate::crypto::streams::{chachapoly_encrypt_with_swapped_aad, ChaChaPolyWriteAdapter}; +use crate::crypto::streams::{ChaChaPolyWriteAdapter, chachapoly_encrypt_with_swapped_aad}; use crate::io; use crate::ln::onion_utils; use crate::onion_message::messenger::Destination; diff --git a/lightning/src/chain/chaininterface.rs b/lightning/src/chain/chaininterface.rs index bb5f6de95ab..98c11fe154a 100644 --- a/lightning/src/chain/chaininterface.rs +++ b/lightning/src/chain/chaininterface.rs @@ -381,7 +381,7 @@ impl LowerBoundedFeeEstimator { #[cfg(test)] mod tests { use super::{ - ConfirmationTarget, FeeEstimator, LowerBoundedFeeEstimator, FEERATE_FLOOR_SATS_PER_KW, + ConfirmationTarget, FEERATE_FLOOR_SATS_PER_KW, FeeEstimator, LowerBoundedFeeEstimator, }; struct TestFeeEstimator { diff --git a/lightning/src/chain/chainmonitor.rs b/lightning/src/chain/chainmonitor.rs index b3b69096997..7e603568558 100644 --- a/lightning/src/chain/chainmonitor.rs +++ b/lightning/src/chain/chainmonitor.rs @@ -279,14 +279,14 @@ pub struct AsyncPersister< } impl< - K: KVStore + MaybeSend + MaybeSync + 'static, - S: FutureSpawner, - L: Logger + MaybeSend + MaybeSync + 'static, - ES: EntropySource + MaybeSend + MaybeSync + 'static, - SP: SignerProvider + MaybeSend + MaybeSync + 'static, - BI: BroadcasterInterface + MaybeSend + MaybeSync + 'static, - FE: FeeEstimator + MaybeSend + MaybeSync + 'static, - > Deref for AsyncPersister + K: KVStore + MaybeSend + MaybeSync + 'static, + S: FutureSpawner, + L: Logger + MaybeSend + MaybeSync + 'static, + ES: EntropySource + MaybeSend + MaybeSync + 'static, + SP: SignerProvider + MaybeSend + MaybeSync + 'static, + BI: BroadcasterInterface + MaybeSend + MaybeSync + 'static, + FE: FeeEstimator + MaybeSend + MaybeSync + 'static, +> Deref for AsyncPersister { type Target = Self; fn deref(&self) -> &Self { @@ -295,14 +295,14 @@ impl< } impl< - K: KVStore + MaybeSend + MaybeSync + 'static, - S: FutureSpawner, - L: Logger + MaybeSend + MaybeSync + 'static, - ES: EntropySource + MaybeSend + MaybeSync + 'static, - SP: SignerProvider + MaybeSend + MaybeSync + 'static, - BI: BroadcasterInterface + MaybeSend + MaybeSync + 'static, - FE: FeeEstimator + MaybeSend + MaybeSync + 'static, - > Persist for AsyncPersister + K: KVStore + MaybeSend + MaybeSync + 'static, + S: FutureSpawner, + L: Logger + MaybeSend + MaybeSync + 'static, + ES: EntropySource + MaybeSend + MaybeSync + 'static, + SP: SignerProvider + MaybeSend + MaybeSync + 'static, + BI: BroadcasterInterface + MaybeSend + MaybeSync + 'static, + FE: FeeEstimator + MaybeSend + MaybeSync + 'static, +> Persist for AsyncPersister where SP::EcdsaSigner: MaybeSend + 'static, { @@ -391,15 +391,15 @@ pub struct ChainMonitor< } impl< - K: KVStore + MaybeSend + MaybeSync + 'static, - S: FutureSpawner, - SP: SignerProvider + MaybeSend + MaybeSync + 'static, - C: chain::Filter, - T: BroadcasterInterface + MaybeSend + MaybeSync + 'static, - F: FeeEstimator + MaybeSend + MaybeSync + 'static, - L: Logger + MaybeSend + MaybeSync + 'static, - ES: EntropySource + MaybeSend + MaybeSync + 'static, - > ChainMonitor, ES> + K: KVStore + MaybeSend + MaybeSync + 'static, + S: FutureSpawner, + SP: SignerProvider + MaybeSend + MaybeSync + 'static, + C: chain::Filter, + T: BroadcasterInterface + MaybeSend + MaybeSync + 'static, + F: FeeEstimator + MaybeSend + MaybeSync + 'static, + L: Logger + MaybeSend + MaybeSync + 'static, + ES: EntropySource + MaybeSend + MaybeSync + 'static, +> ChainMonitor, ES> where SP::EcdsaSigner: MaybeSend + 'static, { @@ -451,14 +451,14 @@ where } impl< - ChannelSigner: EcdsaChannelSigner, - C: chain::Filter, - T: BroadcasterInterface, - F: FeeEstimator, - L: Logger, - P: Deref, - ES: EntropySource, - > ChainMonitor + ChannelSigner: EcdsaChannelSigner, + C: chain::Filter, + T: BroadcasterInterface, + F: FeeEstimator, + L: Logger, + P: Deref, + ES: EntropySource, +> ChainMonitor where P::Target: Persist, { @@ -1092,7 +1092,10 @@ where let mut monitors = self.monitors.write().unwrap(); let entry = match monitors.entry(channel_id) { hash_map::Entry::Occupied(_) => { - log_error!(logger, "Failed to add new channel data: channel monitor for given channel ID is already present"); + log_error!( + logger, + "Failed to add new channel data: channel monitor for given channel ID is already present" + ); return Err(()); }, hash_map::Entry::Vacant(e) => e, @@ -1113,7 +1116,10 @@ where let mut monitors = self.monitors.write().unwrap(); let entry = match monitors.entry(channel_id) { hash_map::Entry::Occupied(_) => { - log_error!(logger, "Failed to add new channel data: channel monitor for given channel ID is already present"); + log_error!( + logger, + "Failed to add new channel data: channel monitor for given channel ID is already present" + ); return Err(()); }, hash_map::Entry::Vacant(e) => e, @@ -1163,7 +1169,9 @@ where // user could use this object with some proxying in between which makes this // possible, but in tests and fuzzing, this should be a panic. #[cfg(debug_assertions)] - panic!("ChannelManager generated a channel update for a channel that was not yet registered!"); + panic!( + "ChannelManager generated a channel update for a channel that was not yet registered!" + ); #[cfg(not(debug_assertions))] ChannelMonitorUpdateStatus::InProgress }, @@ -1191,7 +1199,10 @@ where // We don't want to persist a `monitor_update` which results in a failure to apply later // while reading `channel_monitor` with updates from storage. Instead, we should persist // the entire `channel_monitor` here. - log_warn!(logger, "Failed to update ChannelMonitor. Going ahead and persisting the entire ChannelMonitor"); + log_warn!( + logger, + "Failed to update ChannelMonitor. Going ahead and persisting the entire ChannelMonitor" + ); self.persister.update_persisted_channel( monitor.persistence_key(), None, @@ -1386,14 +1397,14 @@ where } impl< - ChannelSigner: EcdsaChannelSigner, - C: chain::Filter, - T: BroadcasterInterface, - F: FeeEstimator, - L: Logger, - P: Deref, - ES: EntropySource, - > BaseMessageHandler for ChainMonitor + ChannelSigner: EcdsaChannelSigner, + C: chain::Filter, + T: BroadcasterInterface, + F: FeeEstimator, + L: Logger, + P: Deref, + ES: EntropySource, +> BaseMessageHandler for ChainMonitor where P::Target: Persist, { @@ -1420,28 +1431,28 @@ where } impl< - ChannelSigner: EcdsaChannelSigner, - C: chain::Filter, - T: BroadcasterInterface, - F: FeeEstimator, - L: Logger, - P: Deref, - ES: EntropySource, - > SendOnlyMessageHandler for ChainMonitor + ChannelSigner: EcdsaChannelSigner, + C: chain::Filter, + T: BroadcasterInterface, + F: FeeEstimator, + L: Logger, + P: Deref, + ES: EntropySource, +> SendOnlyMessageHandler for ChainMonitor where P::Target: Persist, { } impl< - ChannelSigner: EcdsaChannelSigner, - C: chain::Filter, - T: BroadcasterInterface, - F: FeeEstimator, - L: Logger, - P: Deref, - ES: EntropySource, - > chain::Listen for ChainMonitor + ChannelSigner: EcdsaChannelSigner, + C: chain::Filter, + T: BroadcasterInterface, + F: FeeEstimator, + L: Logger, + P: Deref, + ES: EntropySource, +> chain::Listen for ChainMonitor where P::Target: Persist, { @@ -1493,14 +1504,14 @@ where } impl< - ChannelSigner: EcdsaChannelSigner, - C: chain::Filter, - T: BroadcasterInterface, - F: FeeEstimator, - L: Logger, - P: Deref, - ES: EntropySource, - > chain::Confirm for ChainMonitor + ChannelSigner: EcdsaChannelSigner, + C: chain::Filter, + T: BroadcasterInterface, + F: FeeEstimator, + L: Logger, + P: Deref, + ES: EntropySource, +> chain::Confirm for ChainMonitor where P::Target: Persist, { @@ -1583,14 +1594,14 @@ where } impl< - ChannelSigner: EcdsaChannelSigner, - C: chain::Filter, - T: BroadcasterInterface, - F: FeeEstimator, - L: Logger, - P: Deref, - ES: EntropySource, - > chain::Watch for ChainMonitor + ChannelSigner: EcdsaChannelSigner, + C: chain::Filter, + T: BroadcasterInterface, + F: FeeEstimator, + L: Logger, + P: Deref, + ES: EntropySource, +> chain::Watch for ChainMonitor where P::Target: Persist, { @@ -1674,14 +1685,14 @@ where } impl< - ChannelSigner: EcdsaChannelSigner, - C: chain::Filter, - T: BroadcasterInterface, - F: FeeEstimator, - L: Logger, - P: Deref, - ES: EntropySource, - > events::EventsProvider for ChainMonitor + ChannelSigner: EcdsaChannelSigner, + C: chain::Filter, + T: BroadcasterInterface, + F: FeeEstimator, + L: Logger, + P: Deref, + ES: EntropySource, +> events::EventsProvider for ChainMonitor where P::Target: Persist, { @@ -1749,14 +1760,14 @@ pub trait AChainMonitor { } impl< - ChannelSigner: EcdsaChannelSigner, - C: chain::Filter, - T: BroadcasterInterface, - F: FeeEstimator, - L: Logger, - P: Deref, - ES: EntropySource, - > AChainMonitor for ChainMonitor + ChannelSigner: EcdsaChannelSigner, + C: chain::Filter, + T: BroadcasterInterface, + F: FeeEstimator, + L: Logger, + P: Deref, + ES: EntropySource, +> AChainMonitor for ChainMonitor where P::Target: Persist, { @@ -1776,7 +1787,7 @@ where #[cfg(test)] mod tests { use super::ChainMonitor; - use crate::chain::channelmonitor::{ChannelMonitorUpdate, ANTI_REORG_DELAY}; + use crate::chain::channelmonitor::{ANTI_REORG_DELAY, ChannelMonitorUpdate}; use crate::chain::{ChannelMonitorUpdateStatus, Watch}; use crate::events::{ClosureReason, Event}; use crate::ln::functional_test_utils::*; @@ -2035,18 +2046,22 @@ mod tests { chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::UnrecoverableError); - assert!(std::panic::catch_unwind(|| { - // Returning an UnrecoverableError should always panic immediately - // Connecting [`DEFAULT_CHAINSYNC_PARTITION_FACTOR`] blocks so that we trigger some persistence - // after accounting for block-height based partitioning/distribution. - connect_blocks(&nodes[0], CHAINSYNC_MONITOR_PARTITION_FACTOR); - }) - .is_err()); - assert!(std::panic::catch_unwind(|| { - // ...and also poison our locks causing later use to panic as well - core::mem::drop(nodes); - }) - .is_err()); + assert!( + std::panic::catch_unwind(|| { + // Returning an UnrecoverableError should always panic immediately + // Connecting [`DEFAULT_CHAINSYNC_PARTITION_FACTOR`] blocks so that we trigger some persistence + // after accounting for block-height based partitioning/distribution. + connect_blocks(&nodes[0], CHAINSYNC_MONITOR_PARTITION_FACTOR); + }) + .is_err() + ); + assert!( + std::panic::catch_unwind(|| { + // ...and also poison our locks causing later use to panic as well + core::mem::drop(nodes); + }) + .is_err() + ); } /// Concrete `ChainMonitor` type wired to the standard test utilities in deferred mode. @@ -2152,13 +2167,15 @@ mod tests { // update_persisted_channel was called for update_id 1, and because it returned // InProgress, update_id 1 remains pending. let monitor_name = deferred.get_monitor(chan).unwrap().persistence_key(); - assert!(persister - .offchain_monitor_updates - .lock() - .unwrap() - .get(&monitor_name) - .unwrap() - .contains(&1)); + assert!( + persister + .offchain_monitor_updates + .lock() + .unwrap() + .get(&monitor_name) + .unwrap() + .contains(&1) + ); assert!(pending_for_chan.contains(&1)); // Flush remaining: update_persisted_channel returns Completed (default), triggers @@ -2167,13 +2184,15 @@ mod tests { assert_eq!(deferred.pending_operation_count(), 0); // update_persisted_channel was called for update_id 2. - assert!(persister - .offchain_monitor_updates - .lock() - .unwrap() - .get(&monitor_name) - .unwrap() - .contains(&2)); + assert!( + persister + .offchain_monitor_updates + .lock() + .unwrap() + .get(&monitor_name) + .unwrap() + .contains(&2) + ); // update_id 1 is still pending from the InProgress earlier, but update_id 2 was // completed in this flush so it is no longer pending. diff --git a/lightning/src/chain/channelmonitor.rs b/lightning/src/chain/channelmonitor.rs index c3e20ef5e6f..7d811ab697a 100644 --- a/lightning/src/chain/channelmonitor.rs +++ b/lightning/src/chain/channelmonitor.rs @@ -26,11 +26,11 @@ use bitcoin::script::{Script, ScriptBuf}; use bitcoin::transaction::{OutPoint as BitcoinOutPoint, Transaction, TxOut}; use bitcoin::hash_types::{BlockHash, Txid}; -use bitcoin::hashes::sha256::Hash as Sha256; use bitcoin::hashes::Hash; +use bitcoin::hashes::sha256::Hash as Sha256; use bitcoin::ecdsa::Signature as BitcoinSignature; -use bitcoin::secp256k1::{self, ecdsa::Signature, PublicKey, Secp256k1, SecretKey}; +use bitcoin::secp256k1::{self, PublicKey, Secp256k1, SecretKey, ecdsa::Signature}; use crate::chain; use crate::chain::chaininterface::{ @@ -58,9 +58,9 @@ use crate::ln::channelmanager::{HTLCSource, PaymentClaimDetails, SentHTLCId}; use crate::ln::msgs::DecodeError; use crate::ln::types::ChannelId; use crate::sign::{ - ecdsa::EcdsaChannelSigner, ChannelDerivationParameters, DelayedPaymentOutputDescriptor, - EntropySource, HTLCDescriptor, SignerProvider, SpendableOutputDescriptor, - StaticPaymentOutputDescriptor, + ChannelDerivationParameters, DelayedPaymentOutputDescriptor, EntropySource, HTLCDescriptor, + SignerProvider, SpendableOutputDescriptor, StaticPaymentOutputDescriptor, + ecdsa::EcdsaChannelSigner, }; use crate::types::features::ChannelTypeFeatures; use crate::types::payment::{PaymentHash, PaymentPreimage}; @@ -68,8 +68,8 @@ use crate::util::byte_utils; use crate::util::logger::{Logger, WithContext}; use crate::util::persist::MonitorName; use crate::util::ser::{ - MaybeReadable, Readable, ReadableArgs, RequiredWrapper, UpgradableRequired, Writeable, Writer, - U48, + MaybeReadable, Readable, ReadableArgs, RequiredWrapper, U48, UpgradableRequired, Writeable, + Writer, }; #[allow(unused_imports)] @@ -3227,11 +3227,7 @@ impl ChannelMonitor { { let htlcs = funding.counterparty_claimable_outpoints.get(&confirmed_txid).unwrap(); walk_htlcs!(htlcs.iter().filter_map(|(a, b)| { - if let &Some(ref source) = b { - Some((a, Some(&**source))) - } else { - None - } + if let &Some(ref source) = b { Some((a, Some(&**source))) } else { None } })); } else if confirmed_txid == funding.current_holder_commitment_tx.trust().txid() { walk_htlcs!(holder_commitment_htlcs!(us, CURRENT_WITH_SOURCES)); @@ -3416,7 +3412,7 @@ impl ChannelMonitorImpl { // We only need to remove fulfilled HTLCs once for the first `FundingScope` we // come across since all `FundingScope`s share the same set of HTLC sources. if !removed_fulfilled_htlcs { - for (_, ref source_opt) in funding.counterparty_claimable_outpoints.get(&txid).unwrap() { + for (_, source_opt) in funding.counterparty_claimable_outpoints.get(&txid).unwrap() { if let Some(source) = source_opt { if !cur_claimables.iter() .any(|(_, cur_source_opt)| cur_source_opt == source_opt) @@ -4537,7 +4533,9 @@ impl ChannelMonitorImpl { // of outputs to watch for spends of, otherwise we're likely to lose user funds. Because // its trivial to do, double-check that here. for txid in self.counterparty_commitment_txn_on_chain.keys() { - self.outputs_to_watch.get(txid).expect("Counterparty commitment txn which have been broadcast should have outputs registered"); + self.outputs_to_watch.get(txid).expect( + "Counterparty commitment txn which have been broadcast should have outputs registered", + ); } &self.outputs_to_watch } @@ -4906,11 +4904,7 @@ impl ChannelMonitorImpl { // If counterparty commitment tx is the state previous to the latest valid state, use // their previous per-commitment point (non-atomicity of revocation means it's valid for // them to temporarily have two valid commitment txns from our viewpoint) - if per_commitment_points.0 == commitment_number + 1 { - Some(*point) - } else { - None - } + if per_commitment_points.0 == commitment_number + 1 { Some(*point) } else { None } } else { None } @@ -5224,7 +5218,10 @@ impl ChannelMonitorImpl { assert_eq!(funding_spent.funding_txid(), funding_txid_spent); let current_msg = if current { "latest holder" } else { "previous holder" }; - log_info!(logger, "Got broadcast of {current_msg} commitment tx {commitment_txid}, searching for available HTLCs to claim"); + log_info!( + logger, + "Got broadcast of {current_msg} commitment tx {commitment_txid}, searching for available HTLCs to claim" + ); let (claim_requests, broadcasted_holder_revokable_script) = self.get_broadcasted_holder_claims(funding_spent, holder_commitment_tx, height); @@ -5943,20 +5940,20 @@ impl ChannelMonitorImpl { //- maturing spendable output has transaction paying us has been disconnected self.onchain_events_awaiting_threshold_conf.retain(|ref entry| entry.height <= new_height); - // TODO: Replace with `take_if` once our MSRV is >= 1.80. let mut should_broadcast_commitment = false; - if let Some((_, conf_height)) = self.alternative_funding_confirmed.as_ref() { - if *conf_height > new_height { - self.alternative_funding_confirmed.take(); - if self.holder_tx_signed || self.funding_spend_seen { - // Cancel any previous claims that are no longer valid as they stemmed from a - // different funding transaction. - let new_holder_commitment_txid = - self.funding.current_holder_commitment_tx.trust().txid(); - self.cancel_prev_commitment_claims(&logger, &new_holder_commitment_txid); + if self + .alternative_funding_confirmed + .take_if(|(_, conf_height)| *conf_height > new_height) + .is_some() + { + if self.holder_tx_signed || self.funding_spend_seen { + // Cancel any previous claims that are no longer valid as they stemmed from a + // different funding transaction. + let new_holder_commitment_txid = + self.funding.current_holder_commitment_tx.trust().txid(); + self.cancel_prev_commitment_claims(&logger, &new_holder_commitment_txid); - should_broadcast_commitment = true; - } + should_broadcast_commitment = true; } } @@ -6001,20 +5998,20 @@ impl ChannelMonitorImpl { debug_assert!(!self.onchain_events_awaiting_threshold_conf.iter().any(|ref entry| entry.txid == *txid)); - // TODO: Replace with `take_if` once our MSRV is >= 1.80. let mut should_broadcast_commitment = false; - if let Some((alternative_funding_txid, _)) = self.alternative_funding_confirmed.as_ref() { - if alternative_funding_txid == txid { - self.alternative_funding_confirmed.take(); - if self.holder_tx_signed || self.funding_spend_seen { - // Cancel any previous claims that are no longer valid as they stemmed from a - // different funding transaction. - let new_holder_commitment_txid = - self.funding.current_holder_commitment_tx.trust().txid(); - self.cancel_prev_commitment_claims(&logger, &new_holder_commitment_txid); + if self + .alternative_funding_confirmed + .take_if(|(alternative_funding_txid, _)| alternative_funding_txid == txid) + .is_some() + { + if self.holder_tx_signed || self.funding_spend_seen { + // Cancel any previous claims that are no longer valid as they stemmed from a + // different funding transaction. + let new_holder_commitment_txid = + self.funding.current_holder_commitment_tx.trust().txid(); + self.cancel_prev_commitment_claims(&logger, &new_holder_commitment_txid); - should_broadcast_commitment = true; - } + should_broadcast_commitment = true; } } @@ -6989,8 +6986,8 @@ pub(super) fn dummy_monitor( mod tests { use bitcoin::amount::Amount; use bitcoin::hash_types::Txid; - use bitcoin::hashes::sha256::Hash as Sha256; use bitcoin::hashes::Hash; + use bitcoin::hashes::sha256::Hash as Sha256; use bitcoin::hex::FromHex; use bitcoin::locktime::absolute::LockTime; use bitcoin::network::Network; @@ -7010,8 +7007,8 @@ mod tests { use super::ChannelMonitorUpdateStep; use crate::chain::channelmonitor::{ChannelMonitor, WithChannelMonitor}; use crate::chain::package::{ - weight_offered_htlc, weight_received_htlc, weight_revoked_offered_htlc, - weight_revoked_received_htlc, WEIGHT_REVOKED_OUTPUT, + WEIGHT_REVOKED_OUTPUT, weight_offered_htlc, weight_received_htlc, + weight_revoked_offered_htlc, weight_revoked_received_htlc, }; use crate::chain::transaction::OutPoint; use crate::chain::{BlockLocator, Confirm}; diff --git a/lightning/src/chain/mod.rs b/lightning/src/chain/mod.rs index d72d58b3149..278a58f4018 100644 --- a/lightning/src/chain/mod.rs +++ b/lightning/src/chain/mod.rs @@ -19,12 +19,12 @@ use bitcoin::script::{Script, ScriptBuf}; use bitcoin::secp256k1::PublicKey; use crate::chain::channelmonitor::{ - ChannelMonitor, ChannelMonitorUpdate, MonitorEvent, ANTI_REORG_DELAY, + ANTI_REORG_DELAY, ChannelMonitor, ChannelMonitorUpdate, MonitorEvent, }; use crate::chain::transaction::{OutPoint, TransactionData}; use crate::ln::types::ChannelId; -use crate::sign::ecdsa::EcdsaChannelSigner; use crate::sign::HTLCDescriptor; +use crate::sign::ecdsa::EcdsaChannelSigner; use core::ops::Deref; diff --git a/lightning/src/chain/onchaintx.rs b/lightning/src/chain/onchaintx.rs index 3eb6d64f3a2..80d92231970 100644 --- a/lightning/src/chain/onchaintx.rs +++ b/lightning/src/chain/onchaintx.rs @@ -18,10 +18,11 @@ use bitcoin::hashes::Hash; use bitcoin::locktime::absolute::LockTime; use bitcoin::script::{Script, ScriptBuf}; use bitcoin::secp256k1; -use bitcoin::secp256k1::{ecdsa::Signature, PublicKey, Secp256k1}; +use bitcoin::secp256k1::{PublicKey, Secp256k1, ecdsa::Signature}; use bitcoin::transaction::OutPoint as BitcoinOutPoint; use bitcoin::transaction::Transaction; +use crate::chain::ClaimId; use crate::chain::chaininterface::ConfirmationTarget; use crate::chain::chaininterface::{ BroadcasterInterface, FeeEstimator, LowerBoundedFeeEstimator, TransactionType, @@ -29,14 +30,13 @@ use crate::chain::chaininterface::{ use crate::chain::channelmonitor::ANTI_REORG_DELAY; use crate::chain::package::{PackageSolvingData, PackageTemplate}; use crate::chain::transaction::MaybeSignedTransaction; -use crate::chain::ClaimId; use crate::ln::chan_utils::{ - get_keyed_anchor_redeemscript, shared_anchor_script_pubkey, ChannelTransactionParameters, - HTLCOutputInCommitment, HolderCommitmentTransaction, + ChannelTransactionParameters, HTLCOutputInCommitment, HolderCommitmentTransaction, + get_keyed_anchor_redeemscript, shared_anchor_script_pubkey, }; use crate::ln::msgs::DecodeError; use crate::ln::types::ChannelId; -use crate::sign::{ecdsa::EcdsaChannelSigner, EntropySource, HTLCDescriptor, SignerProvider}; +use crate::sign::{EntropySource, HTLCDescriptor, SignerProvider, ecdsa::EcdsaChannelSigner}; use crate::util::logger::Logger; use crate::util::ser::{ MaybeReadable, Readable, ReadableArgs, UpgradableRequired, Writeable, Writer, @@ -1282,11 +1282,11 @@ impl OnchainTxHandler { #[cfg(test)] mod tests { + use bitcoin::Network; use bitcoin::hash_types::Txid; - use bitcoin::hashes::sha256::Hash as Sha256; use bitcoin::hashes::Hash; - use bitcoin::Network; - use bitcoin::{key::Secp256k1, secp256k1::PublicKey, secp256k1::SecretKey, ScriptBuf}; + use bitcoin::hashes::sha256::Hash as Sha256; + use bitcoin::{ScriptBuf, key::Secp256k1, secp256k1::PublicKey, secp256k1::SecretKey}; use types::features::ChannelTypeFeatures; use crate::chain::chaininterface::{ConfirmationTarget, LowerBoundedFeeEstimator}; diff --git a/lightning/src/chain/package.rs b/lightning/src/chain/package.rs index 0ef8855242b..c40b7367e1a 100644 --- a/lightning/src/chain/package.rs +++ b/lightning/src/chain/package.rs @@ -24,8 +24,8 @@ use bitcoin::transaction::{Transaction, TxIn, TxOut}; use bitcoin::{Sequence, Witness}; use crate::chain::chaininterface::{ - compute_feerate_sat_per_1000_weight, ConfirmationTarget, FeeEstimator, - FEERATE_FLOOR_SATS_PER_KW, INCREMENTAL_RELAY_FEE_SAT_PER_1000_WEIGHT, + ConfirmationTarget, FEERATE_FLOOR_SATS_PER_KW, FeeEstimator, + INCREMENTAL_RELAY_FEE_SAT_PER_1000_WEIGHT, compute_feerate_sat_per_1000_weight, }; use crate::chain::channelmonitor::COUNTERPARTY_CLAIMABLE_WITHIN_BLOCKS_PINNABLE; use crate::chain::onchaintx::{FeerateStrategy, OnchainTxHandler}; @@ -742,18 +742,18 @@ impl PackageSolvingData { #[rustfmt::skip] fn amount(&self) -> u64 { let amt = match self { - PackageSolvingData::RevokedOutput(ref outp) => outp.amount.to_sat(), - PackageSolvingData::RevokedHTLCOutput(ref outp) => outp.amount, - PackageSolvingData::CounterpartyOfferedHTLCOutput(ref outp) => outp.htlc.amount_msat / 1000, - PackageSolvingData::CounterpartyReceivedHTLCOutput(ref outp) => outp.htlc.amount_msat / 1000, - PackageSolvingData::HolderHTLCOutput(ref outp) => { + PackageSolvingData::RevokedOutput(outp) => outp.amount.to_sat(), + PackageSolvingData::RevokedHTLCOutput(outp) => outp.amount, + PackageSolvingData::CounterpartyOfferedHTLCOutput(outp) => outp.htlc.amount_msat / 1000, + PackageSolvingData::CounterpartyReceivedHTLCOutput(outp) => outp.htlc.amount_msat / 1000, + PackageSolvingData::HolderHTLCOutput(outp) => { let free_htlcs = outp.channel_type_features.supports_anchors_zero_fee_htlc_tx(); let free_commitments = outp.channel_type_features.supports_anchor_zero_fee_commitments(); debug_assert!(free_htlcs || free_commitments); outp.amount_msat / 1000 }, - PackageSolvingData::HolderFundingOutput(ref outp) => { + PackageSolvingData::HolderFundingOutput(outp) => { let free_htlcs = outp.channel_type_features.supports_anchors_zero_fee_htlc_tx(); let free_commitments = outp.channel_type_features.supports_anchor_zero_fee_commitments(); @@ -766,11 +766,11 @@ impl PackageSolvingData { #[rustfmt::skip] fn weight(&self) -> usize { match self { - PackageSolvingData::RevokedOutput(ref outp) => outp.weight as usize, - PackageSolvingData::RevokedHTLCOutput(ref outp) => outp.weight as usize, - PackageSolvingData::CounterpartyOfferedHTLCOutput(ref outp) => weight_offered_htlc(&outp.channel_type_features) as usize, - PackageSolvingData::CounterpartyReceivedHTLCOutput(ref outp) => weight_received_htlc(&outp.channel_type_features) as usize, - PackageSolvingData::HolderHTLCOutput(ref outp) => { + PackageSolvingData::RevokedOutput(outp) => outp.weight as usize, + PackageSolvingData::RevokedHTLCOutput(outp) => outp.weight as usize, + PackageSolvingData::CounterpartyOfferedHTLCOutput(outp) => weight_offered_htlc(&outp.channel_type_features) as usize, + PackageSolvingData::CounterpartyReceivedHTLCOutput(outp) => weight_received_htlc(&outp.channel_type_features) as usize, + PackageSolvingData::HolderHTLCOutput(outp) => { let free_htlcs = outp.channel_type_features.supports_anchors_zero_fee_htlc_tx(); let free_commitments = outp.channel_type_features.supports_anchor_zero_fee_commitments(); @@ -878,7 +878,7 @@ impl PackageSolvingData { fn finalize_input(&self, bumped_tx: &mut Transaction, i: usize, onchain_handler: &mut OnchainTxHandler) -> bool { let channel_parameters = onchain_handler.channel_parameters(); match self { - PackageSolvingData::RevokedOutput(ref outp) => { + PackageSolvingData::RevokedOutput(outp) => { let channel_parameters = outp.channel_parameters.as_ref().unwrap_or(channel_parameters); let directed_parameters = channel_parameters.as_counterparty_broadcastable(); debug_assert_eq!( @@ -903,7 +903,7 @@ impl PackageSolvingData { bumped_tx.input[i].witness.push(witness_script.clone().into_bytes()); } else { return false; } }, - PackageSolvingData::RevokedHTLCOutput(ref outp) => { + PackageSolvingData::RevokedHTLCOutput(outp) => { let channel_parameters = outp.channel_parameters.as_ref().unwrap_or(channel_parameters); let directed_parameters = channel_parameters.as_counterparty_broadcastable(); debug_assert_eq!( @@ -930,7 +930,7 @@ impl PackageSolvingData { bumped_tx.input[i].witness.push(witness_script.clone().into_bytes()); } else { return false; } }, - PackageSolvingData::CounterpartyOfferedHTLCOutput(ref outp) => { + PackageSolvingData::CounterpartyOfferedHTLCOutput(outp) => { let channel_parameters = outp.channel_parameters.as_ref().unwrap_or(channel_parameters); let directed_parameters = channel_parameters.as_counterparty_broadcastable(); debug_assert_eq!( @@ -957,7 +957,7 @@ impl PackageSolvingData { bumped_tx.input[i].witness.push(witness_script.clone().into_bytes()); } }, - PackageSolvingData::CounterpartyReceivedHTLCOutput(ref outp) => { + PackageSolvingData::CounterpartyReceivedHTLCOutput(outp) => { let channel_parameters = outp.channel_parameters.as_ref().unwrap_or(channel_parameters); let directed_parameters = channel_parameters.as_counterparty_broadcastable(); debug_assert_eq!( @@ -992,12 +992,12 @@ impl PackageSolvingData { #[rustfmt::skip] fn get_maybe_finalized_tx(&self, outpoint: &BitcoinOutPoint, onchain_handler: &mut OnchainTxHandler) -> Option { match self { - PackageSolvingData::HolderHTLCOutput(ref outp) => { + PackageSolvingData::HolderHTLCOutput(outp) => { debug_assert!(!outp.channel_type_features.supports_anchors_zero_fee_htlc_tx()); debug_assert!(!outp.channel_type_features.supports_anchor_zero_fee_commitments()); outp.get_maybe_signed_htlc_tx(onchain_handler, outpoint) } - PackageSolvingData::HolderFundingOutput(ref outp) => { + PackageSolvingData::HolderFundingOutput(outp) => { Some(outp.get_maybe_signed_commitment_tx(onchain_handler)) } _ => { panic!("API Error!"); } @@ -1008,7 +1008,7 @@ impl PackageSolvingData { #[rustfmt::skip] fn minimum_locktime(&self) -> Option { match self { - PackageSolvingData::CounterpartyReceivedHTLCOutput(ref outp) => Some(outp.htlc.cltv_expiry), + PackageSolvingData::CounterpartyReceivedHTLCOutput(outp) => Some(outp.htlc.cltv_expiry), _ => None, } } @@ -1016,7 +1016,7 @@ impl PackageSolvingData { /// exact locktime. This returns that locktime for such outputs. fn signed_locktime(&self) -> Option { match self { - PackageSolvingData::HolderHTLCOutput(ref outp) => { + PackageSolvingData::HolderHTLCOutput(outp) => { if outp.preimage.is_some() { debug_assert_eq!(outp.cltv_expiry, 0); } @@ -1047,7 +1047,7 @@ impl PackageSolvingData { PackageMalleability::Malleable(AggregationCluster::Unpinnable), PackageSolvingData::CounterpartyReceivedHTLCOutput(..) => PackageMalleability::Malleable(AggregationCluster::Pinnable), - PackageSolvingData::HolderHTLCOutput(ref outp) => { + PackageSolvingData::HolderHTLCOutput(outp) => { let free_htlcs = outp.channel_type_features.supports_anchors_zero_fee_htlc_tx(); let free_commits = outp.channel_type_features.supports_anchor_zero_fee_commitments(); @@ -1376,7 +1376,7 @@ impl PackageTemplate { let mut htlcs: Option> = None; for (previous_output, input) in &self.inputs { match input { - PackageSolvingData::HolderHTLCOutput(ref outp) => { + PackageSolvingData::HolderHTLCOutput(outp) => { let free_htlcs = outp.channel_type_features.supports_anchors_zero_fee_htlc_tx(); let free_commitments = outp.channel_type_features.supports_anchor_zero_fee_commitments(); @@ -1604,7 +1604,7 @@ impl PackageTemplate { impl Writeable for PackageTemplate { fn write(&self, writer: &mut W) -> Result<(), io::Error> { writer.write_all(&(self.inputs.len() as u64).to_be_bytes())?; - for (ref outpoint, ref rev_outp) in self.inputs.iter() { + for (outpoint, rev_outp) in self.inputs.iter() { outpoint.write(writer)?; rev_outp.write(writer)?; } @@ -1765,12 +1765,12 @@ fn feerate_bump( #[cfg(test)] mod tests { + use crate::chain::Txid; use crate::chain::package::{ - feerate_bump, weight_offered_htlc, weight_received_htlc, CounterpartyOfferedHTLCOutput, - CounterpartyReceivedHTLCOutput, HolderFundingOutput, HolderHTLCOutput, PackageSolvingData, - PackageTemplate, RevokedHTLCOutput, RevokedOutput, WEIGHT_REVOKED_OUTPUT, + CounterpartyOfferedHTLCOutput, CounterpartyReceivedHTLCOutput, HolderFundingOutput, + HolderHTLCOutput, PackageSolvingData, PackageTemplate, RevokedHTLCOutput, RevokedOutput, + WEIGHT_REVOKED_OUTPUT, feerate_bump, weight_offered_htlc, weight_received_htlc, }; - use crate::chain::Txid; use crate::ln::chan_utils::{ ChannelTransactionParameters, HTLCOutputInCommitment, HolderCommitmentTransaction, }; @@ -1788,7 +1788,7 @@ mod tests { use bitcoin::hex::FromHex; use crate::chain::chaininterface::{ - ConfirmationTarget, FeeEstimator, LowerBoundedFeeEstimator, FEERATE_FLOOR_SATS_PER_KW, + ConfirmationTarget, FEERATE_FLOOR_SATS_PER_KW, FeeEstimator, LowerBoundedFeeEstimator, }; use crate::chain::onchaintx::FeerateStrategy; use crate::types::features::ChannelTypeFeatures; diff --git a/lightning/src/crypto/utils.rs b/lightning/src/crypto/utils.rs index 88911b0baf8..9f4a29d1d65 100644 --- a/lightning/src/crypto/utils.rs +++ b/lightning/src/crypto/utils.rs @@ -1,7 +1,7 @@ use bitcoin::hashes::hmac::{Hmac, HmacEngine}; use bitcoin::hashes::sha256::Hash as Sha256; use bitcoin::hashes::{Hash, HashEngine}; -use bitcoin::secp256k1::{ecdsa::Signature, Message, Secp256k1, SecretKey, Signing}; +use bitcoin::secp256k1::{Message, Secp256k1, SecretKey, Signing, ecdsa::Signature}; use crate::sign::EntropySource; diff --git a/lightning/src/events/bump_transaction/mod.rs b/lightning/src/events/bump_transaction/mod.rs index 6a5e9948653..8ca65fb3030 100644 --- a/lightning/src/events/bump_transaction/mod.rs +++ b/lightning/src/events/bump_transaction/mod.rs @@ -15,16 +15,16 @@ pub mod sync; use alloc::collections::BTreeMap; +use crate::chain::ClaimId; use crate::chain::chaininterface::{ - compute_feerate_sat_per_1000_weight, fee_for_weight, BroadcasterInterface, TransactionType, + BroadcasterInterface, TransactionType, compute_feerate_sat_per_1000_weight, fee_for_weight, }; -use crate::chain::ClaimId; use crate::ln::chan_utils; use crate::ln::chan_utils::{ - shared_anchor_script_pubkey, HTLCOutputInCommitment, ANCHOR_INPUT_WITNESS_WEIGHT, - EMPTY_SCRIPT_SIG_WEIGHT, EMPTY_WITNESS_WEIGHT, HTLC_SUCCESS_INPUT_KEYED_ANCHOR_WITNESS_WEIGHT, - HTLC_SUCCESS_INPUT_P2A_ANCHOR_WITNESS_WEIGHT, HTLC_TIMEOUT_INPUT_KEYED_ANCHOR_WITNESS_WEIGHT, - HTLC_TIMEOUT_INPUT_P2A_ANCHOR_WITNESS_WEIGHT, TRUC_CHILD_MAX_WEIGHT, TRUC_MAX_WEIGHT, + ANCHOR_INPUT_WITNESS_WEIGHT, EMPTY_SCRIPT_SIG_WEIGHT, EMPTY_WITNESS_WEIGHT, + HTLC_SUCCESS_INPUT_KEYED_ANCHOR_WITNESS_WEIGHT, HTLC_SUCCESS_INPUT_P2A_ANCHOR_WITNESS_WEIGHT, + HTLC_TIMEOUT_INPUT_KEYED_ANCHOR_WITNESS_WEIGHT, HTLC_TIMEOUT_INPUT_P2A_ANCHOR_WITNESS_WEIGHT, + HTLCOutputInCommitment, TRUC_CHILD_MAX_WEIGHT, TRUC_MAX_WEIGHT, shared_anchor_script_pubkey, }; use crate::ln::types::ChannelId; use crate::prelude::*; @@ -297,7 +297,10 @@ impl= package_target_feerate_sat_per_1000_weight { - log_debug!(self.logger, "Pre-signed commitment {} already has feerate {} sat/kW above required {} sat/kW, broadcasting.", - commitment_tx.compute_txid(), commitment_tx_feerate_sat_per_1000_weight, - package_target_feerate_sat_per_1000_weight); + log_debug!( + self.logger, + "Pre-signed commitment {} already has feerate {} sat/kW above required {} sat/kW, broadcasting.", + commitment_tx.compute_txid(), + commitment_tx_feerate_sat_per_1000_weight, + package_target_feerate_sat_per_1000_weight + ); self.broadcaster.broadcast_transactions(&[( &commitment_tx, TransactionType::UnilateralClose { counterparty_node_id, channel_id }, @@ -371,8 +381,11 @@ impl(); - log_debug!(self.logger, "Performing coin selection for commitment package (commitment and anchor transaction) targeting {} sat/kW", - package_target_feerate_sat_per_1000_weight); + log_debug!( + self.logger, + "Performing coin selection for commitment package (commitment and anchor transaction) targeting {} sat/kW", + package_target_feerate_sat_per_1000_weight + ); let coin_selection: CoinSelection = self .utxo_source .select_confirmed_utxos( diff --git a/lightning/src/events/bump_transaction/sync.rs b/lightning/src/events/bump_transaction/sync.rs index f2e1be1590c..3ed1cd91f6d 100644 --- a/lightning/src/events/bump_transaction/sync.rs +++ b/lightning/src/events/bump_transaction/sync.rs @@ -16,7 +16,6 @@ use core::task; use crate::chain::chaininterface::BroadcasterInterface; use crate::sign::SignerProvider; -use crate::util::async_poll::dummy_waker; use crate::util::logger::Logger; use crate::util::wallet_utils::{CoinSelectionSourceSync, CoinSelectionSourceSyncWrapper}; @@ -61,13 +60,14 @@ where /// Handles all variants of [`BumpTransactionEvent`]. pub fn handle_event(&self, event: &BumpTransactionEvent) { let mut fut = pin!(self.bump_transaction_event_handler.handle_event(event)); - let mut waker = dummy_waker(); - let mut ctx = task::Context::from_waker(&mut waker); + let mut ctx = task::Context::from_waker(core::task::Waker::noop()); match fut.as_mut().poll(&mut ctx) { task::Poll::Ready(result) => result, task::Poll::Pending => { // In a sync context, we can't wait for the future to complete. - unreachable!("BumpTransactionEventHandlerSync::handle_event should not be pending in a sync context"); + unreachable!( + "BumpTransactionEventHandlerSync::handle_event should not be pending in a sync context" + ); }, } } diff --git a/lightning/src/events/mod.rs b/lightning/src/events/mod.rs index 73c4a39c76f..4cd2cc4ef12 100644 --- a/lightning/src/events/mod.rs +++ b/lightning/src/events/mod.rs @@ -47,8 +47,8 @@ use crate::util::ser::{ use crate::io; use crate::sync::Arc; -use bitcoin::hashes::sha256::Hash as Sha256; use bitcoin::hashes::Hash; +use bitcoin::hashes::sha256::Hash as Sha256; use bitcoin::script::ScriptBuf; use bitcoin::secp256k1::PublicKey; use bitcoin::{OutPoint, Transaction, TxOut}; diff --git a/lightning/src/ln/async_payments_tests.rs b/lightning/src/ln/async_payments_tests.rs index bd07d13c13d..56957d8e8d1 100644 --- a/lightning/src/ln/async_payments_tests.rs +++ b/lightning/src/ln/async_payments_tests.rs @@ -18,7 +18,7 @@ use crate::events::{ PaymentFailureReason, PaymentPurpose, }; use crate::ln::blinded_payment_tests::{fail_blinded_htlc_backwards, get_blinded_route_parameters}; -use crate::ln::channelmanager::{OptionalOfferPaymentParams, PaymentId, MIN_CLTV_EXPIRY_DELTA}; +use crate::ln::channelmanager::{MIN_CLTV_EXPIRY_DELTA, OptionalOfferPaymentParams, PaymentId}; use crate::ln::functional_test_utils::*; use crate::ln::inbound_payment; use crate::ln::msgs; @@ -43,8 +43,8 @@ use crate::offers::invoice_request::InvoiceRequest; use crate::offers::nonce::Nonce; use crate::offers::offer::{Amount, Offer}; use crate::offers::static_invoice::{ - StaticInvoice, StaticInvoiceBuilder, - DEFAULT_RELATIVE_EXPIRY as STATIC_INVOICE_DEFAULT_RELATIVE_EXPIRY, + DEFAULT_RELATIVE_EXPIRY as STATIC_INVOICE_DEFAULT_RELATIVE_EXPIRY, StaticInvoice, + StaticInvoiceBuilder, }; use crate::onion_message::async_payments::{AsyncPaymentsMessage, AsyncPaymentsMessageHandler}; use crate::onion_message::messenger::{ @@ -53,7 +53,7 @@ use crate::onion_message::messenger::{ use crate::onion_message::offers::OffersMessage; use crate::onion_message::packet::ParsedOnionMessageContents; use crate::prelude::*; -use crate::routing::router::{Payee, PaymentParameters, DEFAULT_PAYMENT_DUMMY_HOPS}; +use crate::routing::router::{DEFAULT_PAYMENT_DUMMY_HOPS, Payee, PaymentParameters}; use crate::sign::NodeSigner; use crate::sync::Mutex; use crate::types::features::Bolt12InvoiceFeatures; @@ -106,7 +106,7 @@ fn invoice_flow_up_to_send_serve_static_invoice( // Check that the right number of requests were queued and that they were only queued for the // server node. let mut pending_oms = recipient.onion_messenger.release_pending_msgs(); - let mut offer_paths_req_msgs = pending_oms.remove(&server.node.get_our_node_id()).unwrap(); + let offer_paths_req_msgs = pending_oms.remove(&server.node.get_our_node_id()).unwrap(); assert!(offer_paths_req_msgs.len() <= TEST_OFFERS_MESSAGE_REQUEST_LIMIT); for (_, msgs) in pending_oms { assert!(msgs.is_empty()); @@ -120,7 +120,7 @@ fn invoice_flow_up_to_send_serve_static_invoice( recipient.onion_messenger.handle_onion_message(server.node.get_our_node_id(), &offer_paths); // Only one OfferPaths response should be queued. - let mut pending_oms = server.onion_messenger.release_pending_msgs(); + let pending_oms = server.onion_messenger.release_pending_msgs(); for (_, msgs) in pending_oms { assert!(msgs.is_empty()); } @@ -334,9 +334,7 @@ fn create_static_invoice( fn extract_payment_hash(event: &MessageSendEvent) -> PaymentHash { match event { - MessageSendEvent::UpdateHTLCs { ref updates, .. } => { - updates.update_add_htlcs[0].payment_hash - }, + MessageSendEvent::UpdateHTLCs { updates, .. } => updates.update_add_htlcs[0].payment_hash, _ => panic!(), } } @@ -388,7 +386,7 @@ fn extract_static_invoice_om<'a>( invoice_server: &'a Node, next_hop_nodes: &[&'a Node], ) -> (PublicKey, msgs::OnionMessage, StaticInvoice) { let mut static_invoice = None; - let mut expected_msg_type = |peeled_onion: &_| { + let expected_msg_type = |peeled_onion: &_| { if let PeeledOnion::Offers(OffersMessage::StaticInvoice(inv), _, _) = peeled_onion { static_invoice = Some(inv.clone()); true @@ -596,7 +594,7 @@ fn invalid_keysend_payment_secret() { let chanmon_cfgs = create_chanmon_cfgs(3); let node_cfgs = create_node_cfgs(3, &chanmon_cfgs); let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]); - let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs); + let nodes = create_network(3, &node_cfgs, &node_chanmgrs); create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0); let chan_upd_1_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1_000_000, 0).0.contents; @@ -842,9 +840,11 @@ fn ignore_unexpected_static_invoice() { .handle_onion_message(nodes[1].node.get_our_node_id(), &static_invoice_om); let async_pmts_msgs = AsyncPaymentsMessageHandler::release_pending_messages(nodes[0].node); assert!(!async_pmts_msgs.is_empty()); - assert!(async_pmts_msgs - .into_iter() - .all(|(msg, _)| matches!(msg, AsyncPaymentsMessage::HeldHtlcAvailable(_)))); + assert!( + async_pmts_msgs + .into_iter() + .all(|(msg, _)| matches!(msg, AsyncPaymentsMessage::HeldHtlcAvailable(_))) + ); // Receiving a duplicate invoice will have no effect. nodes[1] @@ -1499,7 +1499,7 @@ fn amount_doesnt_match_invreq() { // Check that we've queued the HTLCs of the async keysend payment. let mut events = nodes[0].node.get_and_clear_pending_msg_events(); assert_eq!(events.len(), 1); - let mut ev = remove_first_msg_event_to_node(&nodes[1].node.get_our_node_id(), &mut events); + let ev = remove_first_msg_event_to_node(&nodes[1].node.get_our_node_id(), &mut events); assert!(matches!( ev, MessageSendEvent::UpdateHTLCs { ref updates, .. } if updates.update_add_htlcs.len() == 1)); let payment_hash = extract_payment_hash(&ev); @@ -1527,7 +1527,7 @@ fn amount_doesnt_match_invreq() { nodes[0].node.process_pending_htlc_forwards(); let mut events = nodes[0].node.get_and_clear_pending_msg_events(); assert_eq!(events.len(), 1); - let mut ev = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut events); + let ev = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut events); assert!(matches!( ev, MessageSendEvent::UpdateHTLCs { ref updates, .. } if updates.update_add_htlcs.len() == 1)); check_added_monitors(&nodes[0], 1); @@ -1543,7 +1543,7 @@ fn amount_doesnt_match_invreq() { fn reject_missing_invreq() { // Ensure we'll fail an async payment backwards if the HTLC onion doesn't contain the sender's // original invoice request. - let mut valid_invreq: Mutex> = Mutex::new(None); + let valid_invreq: Mutex> = Mutex::new(None); invalid_async_receive_with_retry( |sender, _, payment_id| { @@ -1575,7 +1575,7 @@ fn reject_missing_invreq() { fn reject_bad_payment_secret() { // Ensure we'll fail an async payment backwards if the payment secret in the onion is invalid. - let mut valid_payment_params: Mutex> = Mutex::new(None); + let valid_payment_params: Mutex> = Mutex::new(None); invalid_async_receive_with_retry( |sender, recipient, payment_id| { // Store invalid payment paths in the sender's outbound Retryable payment to induce the failure @@ -1600,10 +1600,10 @@ fn reject_bad_payment_secret() { // Modify the outbound payment parameters to use payment paths with an invalid payment secret. sender.node.test_modify_pending_payment(&payment_id, |pmt| { - if let PendingOutboundPayment::Retryable { ref mut payment_params, .. } = pmt { + if let PendingOutboundPayment::Retryable { payment_params, .. } = pmt { assert!(payment_params.is_some()); let valid_params = payment_params.clone(); - if let Payee::Blinded { ref mut route_hints, .. } = + if let Payee::Blinded { route_hints, .. } = &mut payment_params.as_mut().unwrap().payee { core::mem::swap(route_hints, &mut invalid_blinded_payment_paths); @@ -1718,7 +1718,7 @@ fn invalid_async_receive_with_retry( // Check that we've queued the HTLCs of the async keysend payment. let mut events = nodes[0].node.get_and_clear_pending_msg_events(); assert_eq!(events.len(), 1); - let mut ev = remove_first_msg_event_to_node(&nodes[1].node.get_our_node_id(), &mut events); + let ev = remove_first_msg_event_to_node(&nodes[1].node.get_our_node_id(), &mut events); assert!(matches!( ev, MessageSendEvent::UpdateHTLCs { ref updates, .. } if updates.update_add_htlcs.len() == 1)); let payment_hash = extract_payment_hash(&ev); @@ -1745,7 +1745,7 @@ fn invalid_async_receive_with_retry( nodes[0].node.process_pending_htlc_forwards(); let mut events = nodes[0].node.get_and_clear_pending_msg_events(); assert_eq!(events.len(), 1); - let mut ev = remove_first_msg_event_to_node(&nodes[1].node.get_our_node_id(), &mut events); + let ev = remove_first_msg_event_to_node(&nodes[1].node.get_our_node_id(), &mut events); assert!(matches!( ev, MessageSendEvent::UpdateHTLCs { ref updates, .. } if updates.update_add_htlcs.len() == 1)); check_added_monitors(&nodes[0], 1); @@ -1762,7 +1762,7 @@ fn invalid_async_receive_with_retry( nodes[0].node.process_pending_htlc_forwards(); let mut events = nodes[0].node.get_and_clear_pending_msg_events(); assert_eq!(events.len(), 1); - let mut ev = remove_first_msg_event_to_node(&nodes[1].node.get_our_node_id(), &mut events); + let ev = remove_first_msg_event_to_node(&nodes[1].node.get_our_node_id(), &mut events); check_added_monitors(&nodes[0], 1); let route: &[&[&Node]] = &[&[&nodes[1], &nodes[2]]]; let args = PassAlongPathArgs::new(&nodes[0], route[0], amt_msat, payment_hash, ev) @@ -1824,10 +1824,12 @@ fn expired_static_invoice_message_path() { .onion_messenger .handle_onion_message(nodes[1].node.get_our_node_id(), &held_htlc_available_om); for i in 0..2 { - assert!(nodes[2] - .onion_messenger - .next_onion_message_for_peer(nodes[i].node.get_our_node_id()) - .is_none()); + assert!( + nodes[2] + .onion_messenger + .next_onion_message_for_peer(nodes[i].node.get_our_node_id()) + .is_none() + ); } } @@ -2001,10 +2003,12 @@ fn ignore_expired_offer_paths_request() { // After the config path expiry the offer paths request will be ignored: advance_time_by(OFFER_PATHS_REQ_RELATIVE_EXPIRY + Duration::from_secs(1), server); server.onion_messenger.handle_onion_message(recipient.node.get_our_node_id(), &offer_paths_req); - assert!(server - .onion_messenger - .next_onion_message_for_peer(recipient.node.get_our_node_id()) - .is_none()); + assert!( + server + .onion_messenger + .next_onion_message_for_peer(recipient.node.get_our_node_id()) + .is_none() + ); } #[cfg_attr(feature = "std", ignore)] @@ -2057,10 +2061,12 @@ fn ignore_expired_offer_paths_message() { // sent over an expired reply path, and not respond with serve_static_invoice. advance_time_by(TEST_TEMP_REPLY_PATH_RELATIVE_EXPIRY + Duration::from_secs(1), recipient); recipient.onion_messenger.handle_onion_message(server.node.get_our_node_id(), &offer_paths); - assert!(recipient - .onion_messenger - .next_onion_message_for_peer(server.node.get_our_node_id()) - .is_none()); + assert!( + recipient + .onion_messenger + .next_onion_message_for_peer(server.node.get_our_node_id()) + .is_none() + ); } #[test] @@ -2099,10 +2105,12 @@ fn limit_offer_paths_requests() { // After the recipient runs out of attempts to request offer paths, they will give up until the // next timer tick. recipient.node.test_check_refresh_async_receive_offers(); - assert!(recipient - .onion_messenger - .next_onion_message_for_peer(server.node.get_our_node_id()) - .is_none()); + assert!( + recipient + .onion_messenger + .next_onion_message_for_peer(server.node.get_our_node_id()) + .is_none() + ); // On the next timer tick, more offer paths requests should be allowed to go through. recipient.node.timer_tick_occurred(); @@ -2156,10 +2164,12 @@ fn limit_serve_static_invoice_requests() { // Force allowing more offer paths request attempts so we can check that the recipient will not // attempt to build any further offers. recipient.node.timer_tick_occurred(); - assert!(recipient - .onion_messenger - .next_onion_message_for_peer(server.node.get_our_node_id()) - .is_none()); + assert!( + recipient + .onion_messenger + .next_onion_message_for_peer(server.node.get_our_node_id()) + .is_none() + ); // If the recipient now receives new offer_paths, they should not attempt to build new offers as // they already have enough. @@ -2171,10 +2181,12 @@ fn limit_serve_static_invoice_requests() { .next_onion_message_for_peer(recipient.node.get_our_node_id()) .unwrap(); recipient.onion_messenger.handle_onion_message(server.node.get_our_node_id(), &offer_paths); - assert!(recipient - .onion_messenger - .next_onion_message_for_peer(server.node.get_our_node_id()) - .is_none()); + assert!( + recipient + .onion_messenger + .next_onion_message_for_peer(server.node.get_our_node_id()) + .is_none() + ); } #[test] @@ -2401,7 +2413,7 @@ fn ignore_expired_static_invoice() { let chanmon_cfgs = create_chanmon_cfgs(2); let node_cfgs = create_node_cfgs(2, &chanmon_cfgs); let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]); - let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs); + let nodes = create_network(2, &node_cfgs, &node_chanmgrs); create_unannounced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0); let server = &nodes[0]; let recipient = &nodes[1]; @@ -2421,7 +2433,7 @@ fn ignore_expired_static_invoice() { server .onion_messenger .handle_onion_message(recipient.node.get_our_node_id(), &serve_static_invoice_om); - let mut events = server.node.get_and_clear_pending_events(); + let events = server.node.get_and_clear_pending_events(); assert!(events.is_empty()); } @@ -2431,7 +2443,7 @@ fn ignore_offer_paths_expiry_too_soon() { let chanmon_cfgs = create_chanmon_cfgs(2); let node_cfgs = create_node_cfgs(2, &chanmon_cfgs); let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]); - let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs); + let nodes = create_network(2, &node_cfgs, &node_chanmgrs); create_unannounced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0); let server = &nodes[0]; let recipient = &nodes[1]; @@ -2503,10 +2515,12 @@ fn ignore_offer_paths_expiry_too_soon() { recipient .onion_messenger .handle_onion_message(server.node.get_our_node_id(), &offer_paths_expiry_too_soon); - assert!(recipient - .onion_messenger - .next_onion_message_for_peer(server.node.get_our_node_id()) - .is_none()); + assert!( + recipient + .onion_messenger + .next_onion_message_for_peer(server.node.get_our_node_id()) + .is_none() + ); } #[test] @@ -2594,12 +2608,14 @@ fn refresh_unused_offers() { // Before the threshold, the recipient will not attempt to update any offers. advance_time_by(TEST_OFFER_REFRESH_THRESHOLD - Duration::from_secs(2), recipient); - assert!(recipient - .onion_messenger - .release_pending_msgs() - .get(&server.node.get_our_node_id()) - .unwrap() - .is_empty()); + assert!( + recipient + .onion_messenger + .release_pending_msgs() + .get(&server.node.get_our_node_id()) + .unwrap() + .is_empty() + ); // After the threshold time passes, the recipient will attempt to replace all of their offers // (which are all unused) except the last. @@ -2612,12 +2628,14 @@ fn refresh_unused_offers() { assert_eq!(flow_res.invoice_slot, expected_invoice_slot as u16); } recipient.node.timer_tick_occurred(); - assert!(recipient - .onion_messenger - .release_pending_msgs() - .get(&server.node.get_our_node_id()) - .unwrap() - .is_empty()); + assert!( + recipient + .onion_messenger + .release_pending_msgs() + .get(&server.node.get_our_node_id()) + .unwrap() + .is_empty() + ); // The recipient will update the last offer after the threshold time has passed. advance_time_by(Duration::from_secs(1), recipient); @@ -2637,7 +2655,7 @@ fn refresh_unused_offers() { // The used offer should only get an invoice update. recipient.node.timer_tick_occurred(); - let mut pending_oms = recipient + let pending_oms = recipient .onion_messenger .release_pending_msgs() .remove(&server.node.get_our_node_id()) @@ -2903,7 +2921,7 @@ fn async_payment_e2e() { .handle_onion_message(sender_lsp.node.get_our_node_id(), &held_htlc_om_to_inv_server); // Get the held_htlc OM from the interception event. - let mut events_rc = core::cell::RefCell::new(Vec::new()); + let events_rc = core::cell::RefCell::new(Vec::new()); invoice_server.onion_messenger.process_pending_events(&|e| Ok(events_rc.borrow_mut().push(e))); let events = events_rc.into_inner(); let held_htlc_om = events @@ -3555,7 +3573,7 @@ fn async_payment_e2e_release_before_hold_registered() { .onion_messenger .handle_onion_message(sender_lsp.node.get_our_node_id(), &held_htlc_om_to_inv_server); - let mut events_rc = core::cell::RefCell::new(Vec::new()); + let events_rc = core::cell::RefCell::new(Vec::new()); invoice_server.onion_messenger.process_pending_events(&|e| Ok(events_rc.borrow_mut().push(e))); let events = events_rc.into_inner(); let held_htlc_om = events diff --git a/lightning/src/ln/async_signer_tests.rs b/lightning/src/ln/async_signer_tests.rs index f238c1db060..b2370e37210 100644 --- a/lightning/src/ln/async_signer_tests.rs +++ b/lightning/src/ln/async_signer_tests.rs @@ -16,8 +16,8 @@ use crate::util::ser::Writeable; use bitcoin::secp256k1::Secp256k1; use bitcoin::{Amount, TxOut}; -use crate::chain::channelmonitor::LATENCY_GRACE_PERIOD_BLOCKS; use crate::chain::ChannelMonitorUpdateStatus; +use crate::chain::channelmonitor::LATENCY_GRACE_PERIOD_BLOCKS; use crate::events::{ClosureReason, Event}; use crate::ln::chan_utils::ClosingTransaction; use crate::ln::channel::DISCONNECT_PEER_AWAITING_RESPONSE_TICKS; @@ -26,8 +26,8 @@ use crate::ln::channelmanager::{PaymentId, RAACommitmentOrder, TrustedChannelFea use crate::ln::msgs::{BaseMessageHandler, ChannelMessageHandler, ErrorAction, MessageSendEvent}; use crate::ln::outbound_payment::RecipientOnionFields; use crate::ln::{functional_test_utils::*, msgs}; -use crate::sign::ecdsa::EcdsaChannelSigner; use crate::sign::SignerProvider; +use crate::sign::ecdsa::EcdsaChannelSigner; use crate::util::logger::Logger; use crate::util::test_channel_signer::SignerOp; use crate::util::wallet_utils::WalletSourceSync; @@ -65,7 +65,7 @@ fn do_test_open_channel(zero_conf: bool) { nodes[0].node.signer_unblocked(None); // nodes[0] --- open_channel --> nodes[1] - let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, node_b_id); + let open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, node_b_id); // Handle an inbound channel simulating an async signer. nodes[1].disable_next_channel_signer_op(SignerOp::GetPerCommitmentPoint); @@ -130,7 +130,7 @@ fn do_test_funding_created(signer_ops: Vec) { nodes[0].node.create_channel(node_b_id, 100000, 10001, 42, None, None).unwrap(); // nodes[0] --- open_channel --> nodes[1] - let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, node_b_id); + let open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, node_b_id); handle_and_accept_open_channel(&nodes[1], node_a_id, &open_chan_msg); // nodes[0] <-- accept_channel --- nodes[1] @@ -169,7 +169,7 @@ fn do_test_funding_created(signer_ops: Vec) { nodes[0].node.signer_unblocked(Some((node_b_id, chan_id))); } - let mut funding_created_msg = + let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, node_b_id); nodes[1].node.handle_funding_created(node_a_id, &funding_created_msg); check_added_monitors(&nodes[1], 1); @@ -207,7 +207,7 @@ fn do_test_funding_signed(signer_ops: Vec) { nodes[0].node.create_channel(node_b_id, 100000, 10001, 42, None, None).unwrap(); // nodes[0] --- open_channel --> nodes[1] - let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, node_b_id); + let open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, node_b_id); handle_and_accept_open_channel(&nodes[1], node_a_id, &open_chan_msg); // nodes[0] <-- accept_channel --- nodes[1] @@ -225,7 +225,7 @@ fn do_test_funding_signed(signer_ops: Vec) { .unwrap(); check_added_monitors(&nodes[0], 0); - let mut funding_created_msg = + let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, node_b_id); // Now let's make node[1]'s signer be unavailable while handling the `funding_created`. It should @@ -411,7 +411,7 @@ fn do_test_funding_signed_0conf(signer_ops: Vec) { .unwrap(); check_added_monitors(&nodes[0], 0); - let mut funding_created_msg = + let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, node_b_id); // Now let's make node[1]'s signer be unavailable while handling the `funding_created`. It should @@ -794,7 +794,7 @@ fn do_test_async_commitment_signature_ordering(monitor_update_failure: bool) { let chanmon_cfgs = create_chanmon_cfgs(2); let node_cfgs = create_node_cfgs(2, &chanmon_cfgs); let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]); - let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs); + let nodes = create_network(2, &node_cfgs, &node_chanmgrs); let node_a_id = nodes[0].node.get_our_node_id(); let node_b_id = nodes[1].node.get_our_node_id(); let (_, _, chan_id, _) = create_announced_chan_between_nodes(&nodes, 0, 1); @@ -1508,7 +1508,7 @@ fn test_async_force_close_on_invalid_secret_for_stale_state() { let chanmon_cfgs = create_chanmon_cfgs(2); let node_cfgs = create_node_cfgs(2, &chanmon_cfgs); let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]); - let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs); + let nodes = create_network(2, &node_cfgs, &node_chanmgrs); let node_id_0 = nodes[0].node.get_our_node_id(); let node_id_1 = nodes[1].node.get_our_node_id(); @@ -1553,7 +1553,7 @@ fn test_async_splice_initial_commit_sig() { let chanmon_cfgs = create_chanmon_cfgs(2); let node_cfgs = create_node_cfgs(2, &chanmon_cfgs); let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]); - let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs); + let nodes = create_network(2, &node_cfgs, &node_chanmgrs); let channel_id = create_announced_chan_between_nodes(&nodes, 0, 1).2; send_payment(&nodes[0], &[&nodes[1]], 1_000); diff --git a/lightning/src/ln/blinded_payment_tests.rs b/lightning/src/ln/blinded_payment_tests.rs index 621c5103353..ac6ead918ee 100644 --- a/lightning/src/ln/blinded_payment_tests.rs +++ b/lightning/src/ln/blinded_payment_tests.rs @@ -8,8 +8,8 @@ // licenses. use crate::blinded_path::payment::{ - BlindedPaymentPath, Bolt12RefundContext, DummyTlvs, ForwardTlvs, PaymentConstraints, - PaymentContext, PaymentForwardNode, PaymentRelay, ReceiveTlvs, PAYMENT_PADDING_ROUND_OFF, + BlindedPaymentPath, Bolt12RefundContext, DummyTlvs, ForwardTlvs, PAYMENT_PADDING_ROUND_OFF, + PaymentConstraints, PaymentContext, PaymentForwardNode, PaymentRelay, ReceiveTlvs, }; use crate::blinded_path::utils::is_padded; use crate::blinded_path::{self, BlindedHop}; @@ -23,7 +23,7 @@ use crate::ln::msgs::{ use crate::ln::onion_payment; use crate::ln::onion_utils::{self, LocalHTLCFailureReason}; use crate::ln::outbound_payment::{ - RecipientCustomTlvs, RecipientOnionFields, Retry, IDEMPOTENCY_TIMEOUT_TICKS, + IDEMPOTENCY_TIMEOUT_TICKS, RecipientCustomTlvs, RecipientOnionFields, Retry, }; use crate::ln::types::ChannelId; use crate::offers::invoice::UnsignedBolt12Invoice; @@ -40,7 +40,7 @@ use crate::util::test_utils::{self, bytes_from_hex, pubkey_from_hex, secret_from use bitcoin::hex::DisplayHex; use bitcoin::secp256k1::ecdh::SharedSecret; use bitcoin::secp256k1::ecdsa::{RecoverableSignature, Signature}; -use bitcoin::secp256k1::{schnorr, All, PublicKey, Scalar, Secp256k1, SecretKey}; +use bitcoin::secp256k1::{All, PublicKey, Scalar, Secp256k1, SecretKey, schnorr}; use lightning_invoice::RawBolt11Invoice; use types::features::Features; @@ -88,7 +88,7 @@ pub fn blinded_payment_path( let receive_auth_key = keys_manager.get_receive_auth_key(); - let mut secp_ctx = Secp256k1::new(); + let secp_ctx = Secp256k1::new(); BlindedPaymentPath::new( &intermediate_nodes[..], *node_ids.last().unwrap(), receive_auth_key, payee_tlvs, intro_node_max_htlc_opt.unwrap_or_else(|| channel_upds.last().unwrap().htlc_maximum_msat), @@ -176,7 +176,7 @@ fn do_one_hop_blinded_path(success: bool) { }; let receive_auth_key = chanmon_cfgs[1].keys_manager.get_receive_auth_key(); - let mut secp_ctx = Secp256k1::new(); + let secp_ctx = Secp256k1::new(); let blinded_path = BlindedPaymentPath::new( &[], nodes[1].node.get_our_node_id(), receive_auth_key, payee_tlvs, u64::MAX, TEST_FINAL_CLTV as u16, @@ -221,7 +221,7 @@ fn one_hop_blinded_path_with_dummy_hops() { let receive_auth_key = chanmon_cfgs[1].keys_manager.get_receive_auth_key(); let dummy_tlvs = [DummyTlvs::default(); 2]; - let mut secp_ctx = Secp256k1::new(); + let secp_ctx = Secp256k1::new(); let blinded_path = BlindedPaymentPath::new_with_dummy_hops( &[], nodes[1].node.get_our_node_id(), @@ -275,7 +275,7 @@ fn mpp_to_one_hop_blinded_path() { let configs: [Option; 4] = core::array::from_fn(|_| Some(config.clone())); let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &configs); let nodes = create_network(4, &node_cfgs, &node_chanmgrs); - let mut secp_ctx = Secp256k1::new(); + let secp_ctx = Secp256k1::new(); create_announced_chan_between_nodes(&nodes, 0, 1); create_announced_chan_between_nodes(&nodes, 0, 2); @@ -454,7 +454,7 @@ fn do_forward_checks_failure(check: ForwardCheckFail, intro_fails: bool) { let chanmon_cfgs = create_chanmon_cfgs(4); let node_cfgs = create_node_cfgs(4, &chanmon_cfgs); let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]); - let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs); + let nodes = create_network(4, &node_cfgs, &node_chanmgrs); // We need the session priv to construct a bogus onion packet later. *nodes[0].keys_manager.override_random_bytes.lock().unwrap() = Some([3; 32]); create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0); @@ -521,7 +521,7 @@ fn do_forward_checks_failure(check: ForwardCheckFail, intro_fails: bool) { check_added_monitors(&nodes[1], 1); if intro_fails { - let mut updates = get_htlc_update_msgs(&nodes[1], &nodes[0].node.get_our_node_id()); + let updates = get_htlc_update_msgs(&nodes[1], &nodes[0].node.get_our_node_id()); nodes[0].node.handle_update_fail_htlc(nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]); do_commitment_signed_dance(&nodes[0], &nodes[1], &updates.commitment_signed, false, false); let failed_destination = match check { @@ -547,7 +547,7 @@ fn do_forward_checks_failure(check: ForwardCheckFail, intro_fails: bool) { } let mut updates_1_2 = get_htlc_update_msgs(&nodes[1], &nodes[2].node.get_our_node_id()); - let mut update_add = &mut updates_1_2.update_add_htlcs[0]; + let update_add = &mut updates_1_2.update_add_htlcs[0]; cause_error!(2, 3, update_add); @@ -577,7 +577,7 @@ fn do_forward_checks_failure(check: ForwardCheckFail, intro_fails: bool) { nodes[1].node.handle_update_fail_malformed_htlc(nodes[2].node.get_our_node_id(), update_malformed); do_commitment_signed_dance(&nodes[1], &nodes[2], &updates.commitment_signed, true, false); - let mut updates = get_htlc_update_msgs(&nodes[1], &nodes[0].node.get_our_node_id()); + let updates = get_htlc_update_msgs(&nodes[1], &nodes[0].node.get_our_node_id()); nodes[0].node.handle_update_fail_htlc(nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]); do_commitment_signed_dance(&nodes[0], &nodes[1], &updates.commitment_signed, false, false); expect_payment_failed_conditions(&nodes[0], payment_hash, false, @@ -592,7 +592,7 @@ fn failed_backwards_to_intro_node() { let chanmon_cfgs = create_chanmon_cfgs(3); let node_cfgs = create_node_cfgs(3, &chanmon_cfgs); let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]); - let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs); + let nodes = create_network(3, &node_cfgs, &node_chanmgrs); create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0); let chan_upd_1_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1_000_000, 0).0.contents; @@ -608,7 +608,7 @@ fn failed_backwards_to_intro_node() { let mut events = nodes[0].node.get_and_clear_pending_msg_events(); assert_eq!(events.len(), 1); let ev = remove_first_msg_event_to_node(&nodes[1].node.get_our_node_id(), &mut events); - let mut payment_event = SendEvent::from_event(ev); + let payment_event = SendEvent::from_event(ev); nodes[1].node.handle_update_add_htlc(nodes[0].node.get_our_node_id(), &payment_event.msgs[0]); check_added_monitors(&nodes[1], 0); @@ -632,7 +632,7 @@ fn failed_backwards_to_intro_node() { check_added_monitors(&nodes[2], 1); let mut updates = get_htlc_update_msgs(&nodes[2], &nodes[1].node.get_our_node_id()); - let mut update_malformed = &mut updates.update_fail_malformed_htlcs[0]; + let update_malformed = &mut updates.update_fail_malformed_htlcs[0]; // Check that the final node encodes its failure correctly. assert_eq!(update_malformed.failure_code, LocalHTLCFailureReason::InvalidOnionBlinding.failure_code()); assert_eq!(update_malformed.sha256_of_onion, [0; 32]); @@ -643,7 +643,7 @@ fn failed_backwards_to_intro_node() { nodes[1].node.handle_update_fail_malformed_htlc(nodes[2].node.get_our_node_id(), update_malformed); do_commitment_signed_dance(&nodes[1], &nodes[2], &updates.commitment_signed, true, false); - let mut updates = get_htlc_update_msgs(&nodes[1], &nodes[0].node.get_our_node_id()); + let updates = get_htlc_update_msgs(&nodes[1], &nodes[0].node.get_our_node_id()); nodes[0].node.handle_update_fail_htlc(nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]); do_commitment_signed_dance(&nodes[0], &nodes[1], &updates.commitment_signed, false, false); expect_payment_failed_conditions(&nodes[0], payment_hash, false, @@ -670,7 +670,7 @@ fn do_forward_fail_in_process_pending_htlc_fwds(check: ProcessPendingHTLCsCheck, let chanmon_cfgs = create_chanmon_cfgs(4); let node_cfgs = create_node_cfgs(4, &chanmon_cfgs); let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]); - let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs); + let nodes = create_network(4, &node_cfgs, &node_chanmgrs); create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0); let (chan_upd_1_2, chan_id_1_2) = { let chan = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1_000_000, 0); @@ -694,7 +694,7 @@ fn do_forward_fail_in_process_pending_htlc_fwds(check: ProcessPendingHTLCsCheck, let mut events = nodes[0].node.get_and_clear_pending_msg_events(); assert_eq!(events.len(), 1); let ev = remove_first_msg_event_to_node(&nodes[1].node.get_our_node_id(), &mut events); - let mut payment_event = SendEvent::from_event(ev); + let payment_event = SendEvent::from_event(ev); nodes[1].node.handle_update_add_htlc(nodes[0].node.get_our_node_id(), &payment_event.msgs[0]); check_added_monitors(&nodes[1], 0); @@ -742,7 +742,7 @@ fn do_forward_fail_in_process_pending_htlc_fwds(check: ProcessPendingHTLCsCheck, check_added_monitors(&nodes[1], 1); let mut updates_1_2 = get_htlc_update_msgs(&nodes[1], &nodes[2].node.get_our_node_id()); - let mut update_add = &mut updates_1_2.update_add_htlcs[0]; + let update_add = &mut updates_1_2.update_add_htlcs[0]; nodes[2].node.handle_update_add_htlc(nodes[1].node.get_our_node_id(), &update_add); check_added_monitors(&nodes[2], 0); do_commitment_signed_dance(&nodes[2], &nodes[1], &updates_1_2.commitment_signed, true, true); @@ -761,7 +761,7 @@ fn do_forward_fail_in_process_pending_htlc_fwds(check: ProcessPendingHTLCsCheck, nodes[1].node.handle_update_fail_malformed_htlc(nodes[2].node.get_our_node_id(), update_malformed); do_commitment_signed_dance(&nodes[1], &nodes[2], &updates.commitment_signed, true, false); - let mut updates = get_htlc_update_msgs(&nodes[1], &nodes[0].node.get_our_node_id()); + let updates = get_htlc_update_msgs(&nodes[1], &nodes[0].node.get_our_node_id()); nodes[0].node.handle_update_fail_htlc(nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]); do_commitment_signed_dance(&nodes[0], &nodes[1], &updates.commitment_signed, false, false); expect_payment_failed_conditions(&nodes[0], payment_hash, false, @@ -863,7 +863,7 @@ fn two_hop_blinded_path_success() { let chanmon_cfgs = create_chanmon_cfgs(3); let node_cfgs = create_node_cfgs(3, &chanmon_cfgs); let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]); - let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs); + let nodes = create_network(3, &node_cfgs, &node_chanmgrs); create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0); let chan_upd_1_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1_000_000, 0).0.contents; @@ -885,7 +885,7 @@ fn three_hop_blinded_path_success() { let chanmon_cfgs = create_chanmon_cfgs(5); let node_cfgs = create_node_cfgs(5, &chanmon_cfgs); let node_chanmgrs = create_node_chanmgrs(5, &node_cfgs, &[None, None, None, None, None]); - let mut nodes = create_network(5, &node_cfgs, &node_chanmgrs); + let nodes = create_network(5, &node_cfgs, &node_chanmgrs); create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0); create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1_000_000, 0); let chan_upd_2_3 = create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 1_000_000, 0).0.contents; @@ -917,7 +917,7 @@ fn three_hop_blinded_path_fail() { let chanmon_cfgs = create_chanmon_cfgs(4); let node_cfgs = create_node_cfgs(4, &chanmon_cfgs); let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]); - let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs); + let nodes = create_network(4, &node_cfgs, &node_chanmgrs); create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0); let chan_upd_1_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1_000_000, 0).0.contents; let chan_upd_2_3 = create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 1_000_000, 0).0.contents; @@ -976,7 +976,7 @@ fn do_multi_hop_receiver_fail(check: ReceiveCheckFail) { let chanmon_cfgs = create_chanmon_cfgs(3); let node_cfgs = create_node_cfgs(3, &chanmon_cfgs); let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]); - let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs); + let nodes = create_network(3, &node_cfgs, &node_chanmgrs); // We need the session priv to construct an invalid onion packet later. let session_priv = [3; 32]; *nodes[0].keys_manager.override_random_bytes.lock().unwrap() = Some(session_priv); @@ -1028,7 +1028,7 @@ fn do_multi_hop_receiver_fail(check: ReceiveCheckFail) { nodes[0].node.send_payment(payment_hash, RecipientOnionFields::spontaneous_empty(amt_msat), PaymentId(payment_hash.0), route_params, Retry::Attempts(0)).unwrap(); check_added_monitors(&nodes[0], 1); - let mut payment_event_0_1 = { + let payment_event_0_1 = { let mut events = nodes[0].node.get_and_clear_pending_msg_events(); assert_eq!(events.len(), 1); let ev = remove_first_msg_event_to_node(&nodes[1].node.get_our_node_id(), &mut events); @@ -1074,7 +1074,7 @@ fn do_multi_hop_receiver_fail(check: ReceiveCheckFail) { let update_add = &mut payment_event_1_2.msgs[0]; onion_payloads.last_mut().map(|p| { - if let msgs::OutboundOnionPayload::BlindedReceive { ref mut intro_node_blinding_point, .. } = p { + if let msgs::OutboundOnionPayload::BlindedReceive { intro_node_blinding_point, .. } = p { // The receiver should error if both the update_add blinding_point and the // intro_node_blinding_point are set. assert!(intro_node_blinding_point.is_none() && update_add.blinding_point.is_some()); @@ -1174,7 +1174,7 @@ fn blinded_path_retries() { higher_fee_chan_cfg.channel_config.forwarding_fee_base_msat += 1; let node_cfgs = create_node_cfgs(4, &chanmon_cfgs); let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, Some(higher_fee_chan_cfg), None]); - let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs); + let nodes = create_network(4, &node_cfgs, &node_chanmgrs); // Create this network topology so nodes[0] has a blinded route hint to retry over. // n1 @@ -1239,7 +1239,7 @@ fn blinded_path_retries() { nodes[0].node.handle_update_fail_htlc($intro_node.node.get_our_node_id(), &updates.update_fail_htlcs[0]); do_commitment_signed_dance(&nodes[0], &$intro_node, &updates.commitment_signed, false, false); - let mut events = nodes[0].node.get_and_clear_pending_events(); + let events = nodes[0].node.get_and_clear_pending_events(); assert_eq!(events.len(), 1); match events[0] { Event::PaymentPathFailed { payment_hash: ev_payment_hash, payment_failed_permanently, .. } => { @@ -1328,7 +1328,7 @@ fn min_htlc() { nodes[0].node.send_payment(payment_hash, RecipientOnionFields::spontaneous_empty(route_params.final_value_msat), PaymentId(payment_hash.0), route_params, Retry::Attempts(0)).unwrap(); check_added_monitors(&nodes[0], 1); - let mut payment_event_0_1 = { + let payment_event_0_1 = { let mut events = nodes[0].node.get_and_clear_pending_msg_events(); assert_eq!(events.len(), 1); let ev = remove_first_msg_event_to_node(&nodes[1].node.get_our_node_id(), &mut events); @@ -1343,7 +1343,7 @@ fn min_htlc() { &[HTLCHandlingFailureType::Forward { node_id: Some(nodes[2].node.get_our_node_id()), channel_id: chan_1_2.2 }] ); check_added_monitors(&nodes[1], 1); - let mut updates = get_htlc_update_msgs(&nodes[1], &nodes[0].node.get_our_node_id()); + let updates = get_htlc_update_msgs(&nodes[1], &nodes[0].node.get_our_node_id()); nodes[0].node.handle_update_fail_htlc(nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]); do_commitment_signed_dance(&nodes[0], &nodes[1], &updates.commitment_signed, false, false); expect_payment_failed_conditions(&nodes[0], payment_hash, false, @@ -1396,7 +1396,7 @@ fn conditionally_round_fwd_amt() { nodes[4].node.claim_funds(payment_preimage); let expected_path = &[&nodes[1], &nodes[2], &nodes[3], &nodes[4]]; let expected_route = &[&expected_path[..]]; - let mut args = ClaimAlongRouteArgs::new(&nodes[0], &expected_route[..], payment_preimage) + let args = ClaimAlongRouteArgs::new(&nodes[0], &expected_route[..], payment_preimage) .allow_1_msat_fee_overpay(); let expected_fee = pass_claimed_payment_along_route(args); expect_payment_sent(&nodes[0], payment_preimage, Some(Some(expected_fee)), true, true); @@ -1423,7 +1423,7 @@ fn custom_tlvs_to_blinded_path() { }; let receive_auth_key = chanmon_cfgs[1].keys_manager.get_receive_auth_key(); - let mut secp_ctx = Secp256k1::new(); + let secp_ctx = Secp256k1::new(); let blinded_path = BlindedPaymentPath::new( &[], nodes[1].node.get_our_node_id(), receive_auth_key, payee_tlvs, u64::MAX, TEST_FINAL_CLTV as u16, @@ -1477,7 +1477,7 @@ fn fails_receive_tlvs_authentication() { }; let receive_auth_key = chanmon_cfgs[1].keys_manager.get_receive_auth_key(); - let mut secp_ctx = Secp256k1::new(); + let secp_ctx = Secp256k1::new(); let blinded_path = BlindedPaymentPath::new( &[], nodes[1].node.get_our_node_id(), receive_auth_key, payee_tlvs, u64::MAX, TEST_FINAL_CLTV as u16, @@ -1508,7 +1508,7 @@ fn fails_receive_tlvs_authentication() { // Use a mismatched ReceiveAuthKey to force auth failure: let mismatched_receive_auth_key = ReceiveAuthKey([0u8; 32]); - let mut secp_ctx = Secp256k1::new(); + let secp_ctx = Secp256k1::new(); let blinded_path = BlindedPaymentPath::new( &[], nodes[1].node.get_our_node_id(), mismatched_receive_auth_key, payee_tlvs, u64::MAX, TEST_FINAL_CLTV as u16, @@ -1526,7 +1526,7 @@ fn fails_receive_tlvs_authentication() { let mut events = nodes[0].node.get_and_clear_pending_msg_events(); assert_eq!(events.len(), 1); let ev = remove_first_msg_event_to_node(&nodes[1].node.get_our_node_id(), &mut events); - let mut payment_event = SendEvent::from_event(ev); + let payment_event = SendEvent::from_event(ev); nodes[1].node.handle_update_add_htlc(nodes[0].node.get_our_node_id(), &payment_event.msgs[0]); do_commitment_signed_dance(&nodes[1], &nodes[0], &payment_event.commitment_msg, true, true); @@ -1535,7 +1535,7 @@ fn fails_receive_tlvs_authentication() { check_added_monitors(&nodes[1], 1); expect_htlc_handling_failed_destinations!(nodes[1].node.get_and_clear_pending_events(), &[HTLCHandlingFailureType::InvalidOnion]); - let mut update_fail = get_htlc_update_msgs(&nodes[1], &nodes[0].node.get_our_node_id()); + let update_fail = get_htlc_update_msgs(&nodes[1], &nodes[0].node.get_our_node_id()); assert!(update_fail.update_fail_htlcs.len() == 1); let fail_msg = &update_fail.update_fail_htlcs[0]; nodes[0].node.handle_update_fail_htlc(nodes[1].node.get_our_node_id(), fail_msg); @@ -1553,7 +1553,7 @@ fn blinded_payment_path_padding() { let chanmon_cfgs = create_chanmon_cfgs(5); let node_cfgs = create_node_cfgs(5, &chanmon_cfgs); let node_chanmgrs = create_node_chanmgrs(5, &node_cfgs, &[None, None, None, None, None]); - let mut nodes = create_network(5, &node_cfgs, &node_chanmgrs); + let nodes = create_network(5, &node_cfgs, &node_chanmgrs); create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0); create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1_000_000, 0); let chan_upd_2_3 = create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 1_000_000, 0).0.contents; @@ -1604,7 +1604,7 @@ fn update_add_msg( #[test] #[rustfmt::skip] fn route_blinding_spec_test_vector() { - let mut secp_ctx = Secp256k1::new(); + let secp_ctx = Secp256k1::new(); let bob_secret = secret_from_hex("4242424242424242424242424242424242424242424242424242424242424242"); let bob_node_id = PublicKey::from_secret_key(&secp_ctx, &bob_secret); let bob_unblinded_tlvs = bytes_from_hex("011a0000000000000000000000000000000000000000000000000000020800000000000006c10a0800240000009627100c06000b69e505dc0e00fd023103123456"); @@ -1663,7 +1663,7 @@ fn route_blinding_spec_test_vector() { blinded_hops.iter().map(|bh| bh.encrypted_payload.clone()).collect::>>() ); - let mut amt_msat = 100_000; + let amt_msat = 100_000; let session_priv = secret_from_hex("0303030303030303030303030303030303030303030303030303030303030303"); let path = Path { hops: vec![RouteHop { @@ -1837,7 +1837,7 @@ fn route_blinding_spec_test_vector() { fn test_combined_trampoline_onion_creation_vectors() { // As per https://github.com/lightning/bolts/blob/fa0594ac2af3531d734f1d707a146d6e13679451/bolt04/trampoline-to-blinded-path-payment-onion-test.json#L251 - let mut secp_ctx = Secp256k1::new(); + let secp_ctx = Secp256k1::new(); let session_priv = secret_from_hex("a64feb81abd58e473df290e9e1c07dc3e56114495cadf33191f44ba5448ebe99"); let path = Path { @@ -2074,7 +2074,7 @@ fn test_trampoline_forward_payload_encoded_as_receive() { let chanmon_cfgs = create_chanmon_cfgs(TOTAL_NODE_COUNT); let node_cfgs = create_node_cfgs(TOTAL_NODE_COUNT, &chanmon_cfgs); let node_chanmgrs = create_node_chanmgrs(TOTAL_NODE_COUNT, &node_cfgs, &vec![None; TOTAL_NODE_COUNT]); - let mut nodes = create_network(TOTAL_NODE_COUNT, &node_cfgs, &node_chanmgrs); + let nodes = create_network(TOTAL_NODE_COUNT, &node_cfgs, &node_chanmgrs); let (_, _, chan_id_alice_bob, _) = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0); let (_, _, chan_id_bob_carol, _) = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1_000_000, 0); @@ -2214,7 +2214,7 @@ fn test_trampoline_forward_payload_encoded_as_receive() { let mut events = nodes[0].node.get_and_clear_pending_msg_events(); assert_eq!(events.len(), 1); let mut first_message_event = remove_first_msg_event_to_node(&nodes[1].node.get_our_node_id(), &mut events); - let mut update_message = match first_message_event { + let update_message = match first_message_event { MessageSendEvent::UpdateHTLCs { ref mut updates, .. } => { assert_eq!(updates.update_add_htlcs.len(), 1); updates.update_add_htlcs.get_mut(0) @@ -2261,7 +2261,7 @@ fn do_test_trampoline_single_hop_receive(success: bool) { let chanmon_cfgs = create_chanmon_cfgs(TOTAL_NODE_COUNT); let node_cfgs = create_node_cfgs(TOTAL_NODE_COUNT, &chanmon_cfgs); let node_chanmgrs = create_node_chanmgrs(TOTAL_NODE_COUNT, &node_cfgs, &vec![None; TOTAL_NODE_COUNT]); - let mut nodes = create_network(TOTAL_NODE_COUNT, &node_cfgs, &node_chanmgrs); + let nodes = create_network(TOTAL_NODE_COUNT, &node_cfgs, &node_chanmgrs); let (_, _, chan_id_alice_bob, _) = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0); let (_, _, chan_id_bob_carol, _) = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1_000_000, 0); @@ -2539,7 +2539,7 @@ fn do_test_trampoline_relay(blinded: bool, test_case: TrampolineTestCase) { let node_cfgs = create_node_cfgs(TOTAL_NODE_COUNT, &chanmon_cfgs); let user_cfgs = &vec![None; TOTAL_NODE_COUNT]; let node_chanmgrs = create_node_chanmgrs(TOTAL_NODE_COUNT, &node_cfgs, &user_cfgs); - let mut nodes = create_network(TOTAL_NODE_COUNT, &node_cfgs, &node_chanmgrs); + let nodes = create_network(TOTAL_NODE_COUNT, &node_cfgs, &node_chanmgrs); let alice_bob_chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0); let bob_carol_chan = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1_000_000, 0); @@ -2632,7 +2632,7 @@ fn do_test_trampoline_relay(blinded: bool, test_case: TrampolineTestCase) { let mut events = nodes[0].node.get_and_clear_pending_msg_events(); assert_eq!(events.len(), 1); let mut first_message_event = remove_first_msg_event_to_node(&bob_node_id, &mut events); - let mut update_message = match first_message_event { + let update_message = match first_message_event { MessageSendEvent::UpdateHTLCs { ref mut updates, .. } => { assert_eq!(updates.update_add_htlcs.len(), 1); updates.update_add_htlcs.get_mut(0) @@ -2732,7 +2732,7 @@ fn test_trampoline_forward_rejection() { let chanmon_cfgs = create_chanmon_cfgs(TOTAL_NODE_COUNT); let node_cfgs = create_node_cfgs(TOTAL_NODE_COUNT, &chanmon_cfgs); let node_chanmgrs = create_node_chanmgrs(TOTAL_NODE_COUNT, &node_cfgs, &vec![None; TOTAL_NODE_COUNT]); - let mut nodes = create_network(TOTAL_NODE_COUNT, &node_cfgs, &node_chanmgrs); + let nodes = create_network(TOTAL_NODE_COUNT, &node_cfgs, &node_chanmgrs); let (_, _, chan_id_alice_bob, _) = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0); let (_, _, chan_id_bob_carol, _) = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1_000_000, 0); diff --git a/lightning/src/ln/chan_utils.rs b/lightning/src/ln/chan_utils.rs index 4bb8ffac9ef..cb420028dc8 100644 --- a/lightning/src/ln/chan_utils.rs +++ b/lightning/src/ln/chan_utils.rs @@ -27,7 +27,7 @@ use bitcoin::hashes::sha256::Hash as Sha256; use bitcoin::hashes::{Hash, HashEngine}; use crate::chain::chaininterface::{ - fee_for_weight, ConfirmationTarget, FeeEstimator, LowerBoundedFeeEstimator, + ConfirmationTarget, FeeEstimator, LowerBoundedFeeEstimator, fee_for_weight, }; use crate::chain::package::WEIGHT_REVOKED_OUTPUT; use crate::ln::msgs::DecodeError; @@ -38,9 +38,9 @@ use crate::util::transaction_utils; use bitcoin::ecdsa::Signature as BitcoinSignature; use bitcoin::locktime::absolute::LockTime; -use bitcoin::secp256k1::{ecdsa::Signature, Message, Secp256k1}; +use bitcoin::secp256k1::{Message, Secp256k1, ecdsa::Signature}; use bitcoin::secp256k1::{PublicKey, Scalar, SecretKey}; -use bitcoin::{secp256k1, Sequence, Witness}; +use bitcoin::{Sequence, Witness, secp256k1}; use super::channel_keys::{ DelayedPaymentBasepoint, DelayedPaymentKey, HtlcBasepoint, HtlcKey, RevocationBasepoint, @@ -985,11 +985,7 @@ pub(crate) fn legacy_deserialization_prevention_marker_for_channel_type_features debug_assert!(!legacy_version_bit_set.supports_any_optional_bits()); debug_assert!(!features.supports_any_optional_bits()); - if features.requires_unknown_bits_from(&legacy_version_bit_set) { - Some(()) - } else { - None - } + if features.requires_unknown_bits_from(&legacy_version_bit_set) { Some(()) } else { None } } /// Gets the witnessScript for the to_remote output when anchors are enabled. @@ -2254,20 +2250,19 @@ mod tests { use super::{ChannelPublicKeys, CounterpartyCommitmentSecrets}; use crate::chain; use crate::ln::chan_utils::{ - get_htlc_redeemscript, get_keyed_anchor_redeemscript, - get_to_countersigner_keyed_anchor_redeemscript, shared_anchor_script_pubkey, BuiltCommitmentTransaction, ChannelTransactionParameters, CommitmentTransaction, CounterpartyChannelTransactionParameters, HTLCOutputInCommitment, - TrustedCommitmentTransaction, + TrustedCommitmentTransaction, get_htlc_redeemscript, get_keyed_anchor_redeemscript, + get_to_countersigner_keyed_anchor_redeemscript, shared_anchor_script_pubkey, }; use crate::sign::{ChannelSigner, SignerProvider}; use crate::types::features::ChannelTypeFeatures; use crate::types::payment::PaymentHash; use crate::util::test_utils; + use bitcoin::PublicKey as BitcoinPublicKey; use bitcoin::hashes::Hash; use bitcoin::hex::FromHex; use bitcoin::secp256k1::{self, PublicKey, Secp256k1, SecretKey}; - use bitcoin::PublicKey as BitcoinPublicKey; use bitcoin::{CompressedPublicKey, Network, ScriptBuf, Txid}; #[allow(unused_imports)] @@ -2583,9 +2578,9 @@ mod tests { let hex = "c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964"; secrets.push([0; 32]); secrets.last_mut().unwrap()[0..32].clone_from_slice(&>::from_hex(hex).unwrap()); - assert!(monitor - .provide_secret(281474976710654, secrets.last().unwrap().clone()) - .is_err()); + assert!( + monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).is_err() + ); } { @@ -2614,9 +2609,9 @@ mod tests { let hex = "27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116"; secrets.push([0; 32]); secrets.last_mut().unwrap()[0..32].clone_from_slice(&>::from_hex(hex).unwrap()); - assert!(monitor - .provide_secret(281474976710652, secrets.last().unwrap().clone()) - .is_err()); + assert!( + monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).is_err() + ); } { @@ -2645,9 +2640,9 @@ mod tests { let hex = "27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116"; secrets.push([0; 32]); secrets.last_mut().unwrap()[0..32].clone_from_slice(&>::from_hex(hex).unwrap()); - assert!(monitor - .provide_secret(281474976710652, secrets.last().unwrap().clone()) - .is_err()); + assert!( + monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).is_err() + ); } { @@ -2700,9 +2695,9 @@ mod tests { let hex = "05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17"; secrets.push([0; 32]); secrets.last_mut().unwrap()[0..32].clone_from_slice(&>::from_hex(hex).unwrap()); - assert!(monitor - .provide_secret(281474976710648, secrets.last().unwrap().clone()) - .is_err()); + assert!( + monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()).is_err() + ); } { @@ -2743,9 +2738,9 @@ mod tests { let hex = "969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2"; secrets.push([0; 32]); secrets.last_mut().unwrap()[0..32].clone_from_slice(&>::from_hex(hex).unwrap()); - assert!(monitor - .provide_secret(281474976710650, secrets.last().unwrap().clone()) - .is_err()); + assert!( + monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).is_err() + ); } { @@ -2798,9 +2793,9 @@ mod tests { let hex = "05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17"; secrets.push([0; 32]); secrets.last_mut().unwrap()[0..32].clone_from_slice(&>::from_hex(hex).unwrap()); - assert!(monitor - .provide_secret(281474976710648, secrets.last().unwrap().clone()) - .is_err()); + assert!( + monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()).is_err() + ); } { @@ -2853,9 +2848,9 @@ mod tests { let hex = "05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17"; secrets.push([0; 32]); secrets.last_mut().unwrap()[0..32].clone_from_slice(&>::from_hex(hex).unwrap()); - assert!(monitor - .provide_secret(281474976710648, secrets.last().unwrap().clone()) - .is_err()); + assert!( + monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()).is_err() + ); } { @@ -2908,9 +2903,9 @@ mod tests { let hex = "a7efbc61aac46d34f77778bac22c8a20c6a46ca460addc49009bda875ec88fa4"; secrets.push([0; 32]); secrets.last_mut().unwrap()[0..32].clone_from_slice(&>::from_hex(hex).unwrap()); - assert!(monitor - .provide_secret(281474976710648, secrets.last().unwrap().clone()) - .is_err()); + assert!( + monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()).is_err() + ); } } diff --git a/lightning/src/ln/chanmon_update_fail_tests.rs b/lightning/src/ln/chanmon_update_fail_tests.rs index 9633800db08..39c5347d808 100644 --- a/lightning/src/ln/chanmon_update_fail_tests.rs +++ b/lightning/src/ln/chanmon_update_fail_tests.rs @@ -14,7 +14,7 @@ use crate::chain::chaininterface::LowerBoundedFeeEstimator; use crate::chain::chainmonitor::ChainMonitor; -use crate::chain::channelmonitor::{ChannelMonitor, MonitorEvent, ANTI_REORG_DELAY}; +use crate::chain::channelmonitor::{ANTI_REORG_DELAY, ChannelMonitor, MonitorEvent}; use crate::chain::transaction::OutPoint; use crate::chain::{BlockLocator, ChannelMonitorUpdateStatus, Confirm, Listen, Watch}; use crate::events::{ClosureReason, Event, HTLCHandlingFailureType, PaymentPurpose}; @@ -30,9 +30,9 @@ use crate::routing::router::{PaymentParameters, RouteParameters}; use crate::sign::NodeSigner; use crate::util::native_async::FutureQueue; use crate::util::persist::{ - MonitorName, MonitorUpdatingPersisterAsync, CHANNEL_MONITOR_PERSISTENCE_PRIMARY_NAMESPACE, - CHANNEL_MONITOR_PERSISTENCE_SECONDARY_NAMESPACE, - CHANNEL_MONITOR_UPDATE_PERSISTENCE_PRIMARY_NAMESPACE, + CHANNEL_MONITOR_PERSISTENCE_PRIMARY_NAMESPACE, CHANNEL_MONITOR_PERSISTENCE_SECONDARY_NAMESPACE, + CHANNEL_MONITOR_UPDATE_PERSISTENCE_PRIMARY_NAMESPACE, MonitorName, + MonitorUpdatingPersisterAsync, }; use crate::util::ser::{ReadableArgs, Writeable}; use crate::util::test_channel_signer::TestChannelSigner; @@ -58,7 +58,7 @@ fn test_monitor_and_persister_update_fail() { let chanmon_cfgs = create_chanmon_cfgs(2); let node_cfgs = create_node_cfgs(2, &chanmon_cfgs); let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]); - let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs); + let nodes = create_network(2, &node_cfgs, &node_chanmgrs); let node_a_id = nodes[0].node.get_our_node_id(); let node_b_id = nodes[1].node.get_our_node_id(); @@ -126,7 +126,7 @@ fn test_monitor_and_persister_update_fail() { nodes[0].node.handle_update_fulfill_htlc(node_b_id, updates.update_fulfill_htlcs.remove(0)); { - let mut per_peer_lock; + let per_peer_lock; let mut peer_state_lock; let chan_opt = get_channel_ref!(nodes[0], nodes[1], per_peer_lock, peer_state_lock, chan.2); if let Some(channel) = chan_opt.as_funded_mut() { @@ -175,7 +175,7 @@ fn do_test_simple_monitor_temporary_update_fail(disconnect: bool) { let chanmon_cfgs = create_chanmon_cfgs(2); let node_cfgs = create_node_cfgs(2, &chanmon_cfgs); let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]); - let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs); + let nodes = create_network(2, &node_cfgs, &node_chanmgrs); nodes[0].disable_monitor_completeness_assertion(); let node_a_id = nodes[0].node.get_our_node_id(); @@ -317,7 +317,7 @@ fn do_test_monitor_temporary_update_fail(disconnect_count: usize) { let chanmon_cfgs = create_chanmon_cfgs(2); let node_cfgs = create_node_cfgs(2, &chanmon_cfgs); let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]); - let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs); + let nodes = create_network(2, &node_cfgs, &node_chanmgrs); nodes[0].disable_monitor_completeness_assertion(); let node_a_id = nodes[0].node.get_our_node_id(); @@ -728,7 +728,7 @@ fn test_monitor_update_fail_cs() { let chanmon_cfgs = create_chanmon_cfgs(2); let node_cfgs = create_node_cfgs(2, &chanmon_cfgs); let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]); - let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs); + let nodes = create_network(2, &node_cfgs, &node_chanmgrs); let node_a_id = nodes[0].node.get_our_node_id(); let node_b_id = nodes[1].node.get_our_node_id(); @@ -838,7 +838,7 @@ fn test_monitor_update_fail_no_rebroadcast() { let chanmon_cfgs = create_chanmon_cfgs(2); let node_cfgs = create_node_cfgs(2, &chanmon_cfgs); let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]); - let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs); + let nodes = create_network(2, &node_cfgs, &node_chanmgrs); let node_a_id = nodes[0].node.get_our_node_id(); @@ -890,7 +890,7 @@ fn test_monitor_update_raa_while_paused() { let chanmon_cfgs = create_chanmon_cfgs(2); let node_cfgs = create_node_cfgs(2, &chanmon_cfgs); let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]); - let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs); + let nodes = create_network(2, &node_cfgs, &node_chanmgrs); let node_a_id = nodes[0].node.get_our_node_id(); let node_b_id = nodes[1].node.get_our_node_id(); @@ -971,7 +971,7 @@ fn do_test_monitor_update_fail_raa(test_ignore_second_cs: bool) { let chanmon_cfgs = create_chanmon_cfgs(3); let node_cfgs = create_node_cfgs(3, &chanmon_cfgs); let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]); - let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs); + let nodes = create_network(3, &node_cfgs, &node_chanmgrs); nodes[1].disable_monitor_completeness_assertion(); let node_a_id = nodes[0].node.get_our_node_id(); @@ -1275,7 +1275,7 @@ fn test_monitor_update_fail_reestablish() { let chanmon_cfgs = create_chanmon_cfgs(3); let node_cfgs = create_node_cfgs(3, &chanmon_cfgs); let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]); - let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs); + let nodes = create_network(3, &node_cfgs, &node_chanmgrs); let node_a_id = nodes[0].node.get_our_node_id(); let node_b_id = nodes[1].node.get_our_node_id(); @@ -1376,7 +1376,7 @@ fn raa_no_response_awaiting_raa_state() { let chanmon_cfgs = create_chanmon_cfgs(2); let node_cfgs = create_node_cfgs(2, &chanmon_cfgs); let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]); - let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs); + let nodes = create_network(2, &node_cfgs, &node_chanmgrs); let node_a_id = nodes[0].node.get_our_node_id(); let node_b_id = nodes[1].node.get_our_node_id(); @@ -1503,7 +1503,7 @@ fn claim_while_disconnected_monitor_update_fail() { let chanmon_cfgs = create_chanmon_cfgs(2); let node_cfgs = create_node_cfgs(2, &chanmon_cfgs); let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]); - let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs); + let nodes = create_network(2, &node_cfgs, &node_chanmgrs); nodes[1].disable_monitor_completeness_assertion(); let node_a_id = nodes[0].node.get_our_node_id(); @@ -1633,21 +1633,21 @@ fn monitor_failed_no_reestablish_response() { let chanmon_cfgs = create_chanmon_cfgs(2); let node_cfgs = create_node_cfgs(2, &chanmon_cfgs); let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]); - let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs); + let nodes = create_network(2, &node_cfgs, &node_chanmgrs); let node_a_id = nodes[0].node.get_our_node_id(); let node_b_id = nodes[1].node.get_our_node_id(); let channel_id = create_announced_chan_between_nodes(&nodes, 0, 1).2; { - let mut per_peer_lock; + let per_peer_lock; let mut peer_state_lock; get_channel_ref!(nodes[0], nodes[1], per_peer_lock, peer_state_lock, channel_id) .context_mut() .announcement_sigs_state = AnnouncementSigsState::PeerReceived; } { - let mut per_peer_lock; + let per_peer_lock; let mut peer_state_lock; get_channel_ref!(nodes[1], nodes[0], per_peer_lock, peer_state_lock, channel_id) .context_mut() @@ -1731,7 +1731,7 @@ fn first_message_on_recv_ordering() { let chanmon_cfgs = create_chanmon_cfgs(2); let node_cfgs = create_node_cfgs(2, &chanmon_cfgs); let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]); - let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs); + let nodes = create_network(2, &node_cfgs, &node_chanmgrs); nodes[1].disable_monitor_completeness_assertion(); let node_a_id = nodes[0].node.get_our_node_id(); @@ -1830,7 +1830,7 @@ fn test_monitor_update_fail_claim() { let chanmon_cfgs = create_chanmon_cfgs(3); let node_cfgs = create_node_cfgs(3, &chanmon_cfgs); let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]); - let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs); + let nodes = create_network(3, &node_cfgs, &node_chanmgrs); let node_a_id = nodes[0].node.get_our_node_id(); let node_b_id = nodes[1].node.get_our_node_id(); @@ -1977,7 +1977,7 @@ fn test_monitor_update_on_pending_forwards() { let chanmon_cfgs = create_chanmon_cfgs(3); let node_cfgs = create_node_cfgs(3, &chanmon_cfgs); let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]); - let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs); + let nodes = create_network(3, &node_cfgs, &node_chanmgrs); let node_a_id = nodes[0].node.get_our_node_id(); let node_b_id = nodes[1].node.get_our_node_id(); @@ -2061,7 +2061,7 @@ fn monitor_update_claim_fail_no_response() { let chanmon_cfgs = create_chanmon_cfgs(2); let node_cfgs = create_node_cfgs(2, &chanmon_cfgs); let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]); - let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs); + let nodes = create_network(2, &node_cfgs, &node_chanmgrs); let node_a_id = nodes[0].node.get_our_node_id(); let node_b_id = nodes[1].node.get_our_node_id(); @@ -2123,7 +2123,7 @@ fn do_during_funding_monitor_fail( let chanmon_cfgs = create_chanmon_cfgs(2); let node_cfgs = create_node_cfgs(2, &chanmon_cfgs); let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]); - let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs); + let nodes = create_network(2, &node_cfgs, &node_chanmgrs); let node_a_id = nodes[0].node.get_our_node_id(); let node_b_id = nodes[1].node.get_our_node_id(); @@ -2256,10 +2256,11 @@ fn do_during_funding_monitor_fail( }; for (i, node) in nodes.iter().enumerate() { let counterparty_node_id = nodes[(i + 1) % 2].node.get_our_node_id(); - assert!(node - .gossip_sync - .handle_channel_announcement(Some(counterparty_node_id), &announcement) - .unwrap()); + assert!( + node.gossip_sync + .handle_channel_announcement(Some(counterparty_node_id), &announcement) + .unwrap() + ); node.gossip_sync.handle_channel_update(Some(counterparty_node_id), &as_update).unwrap(); node.gossip_sync.handle_channel_update(Some(counterparty_node_id), &bs_update).unwrap(); } @@ -2293,7 +2294,7 @@ fn test_path_paused_mpp() { let chanmon_cfgs = create_chanmon_cfgs(4); let node_cfgs = create_node_cfgs(4, &chanmon_cfgs); let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]); - let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs); + let nodes = create_network(4, &node_cfgs, &node_chanmgrs); let node_b_id = nodes[1].node.get_our_node_id(); let node_c_id = nodes[2].node.get_our_node_id(); @@ -2369,7 +2370,7 @@ fn test_pending_update_fee_ack_on_reconnect() { let chanmon_cfgs = create_chanmon_cfgs(2); let node_cfgs = create_node_cfgs(2, &chanmon_cfgs); let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]); - let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs); + let nodes = create_network(2, &node_cfgs, &node_chanmgrs); let node_a_id = nodes[0].node.get_our_node_id(); let node_b_id = nodes[1].node.get_our_node_id(); @@ -2488,7 +2489,7 @@ fn test_fail_htlc_on_broadcast_after_claim() { let chanmon_cfgs = create_chanmon_cfgs(3); let node_cfgs = create_node_cfgs(3, &chanmon_cfgs); let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]); - let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs); + let nodes = create_network(3, &node_cfgs, &node_chanmgrs); let node_a_id = nodes[0].node.get_our_node_id(); let node_b_id = nodes[1].node.get_our_node_id(); @@ -2537,7 +2538,7 @@ fn do_update_fee_resend_test(deliver_update: bool, parallel_updates: bool) { let chanmon_cfgs = create_chanmon_cfgs(2); let node_cfgs = create_node_cfgs(2, &chanmon_cfgs); let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]); - let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs); + let nodes = create_network(2, &node_cfgs, &node_chanmgrs); let node_a_id = nodes[0].node.get_our_node_id(); let node_b_id = nodes[1].node.get_our_node_id(); @@ -2860,7 +2861,7 @@ fn do_test_reconnect_dup_htlc_claims(htlc_status: HTLCStatusAtDupClaim, second_f let chanmon_cfgs = create_chanmon_cfgs(3); let node_cfgs = create_node_cfgs(3, &chanmon_cfgs); let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]); - let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs); + let nodes = create_network(3, &node_cfgs, &node_chanmgrs); let node_a_id = nodes[0].node.get_our_node_id(); let node_b_id = nodes[1].node.get_our_node_id(); @@ -3010,7 +3011,7 @@ fn test_temporary_error_during_shutdown() { let chanmon_cfgs = create_chanmon_cfgs(2); let node_cfgs = create_node_cfgs(2, &chanmon_cfgs); let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(config.clone()), Some(config)]); - let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs); + let nodes = create_network(2, &node_cfgs, &node_chanmgrs); let node_a_id = nodes[0].node.get_our_node_id(); let node_b_id = nodes[1].node.get_our_node_id(); @@ -3078,7 +3079,7 @@ fn double_temp_error() { let chanmon_cfgs = create_chanmon_cfgs(2); let node_cfgs = create_node_cfgs(2, &chanmon_cfgs); let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]); - let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs); + let nodes = create_network(2, &node_cfgs, &node_chanmgrs); let node_a_id = nodes[0].node.get_our_node_id(); let node_b_id = nodes[1].node.get_our_node_id(); @@ -3901,15 +3902,7 @@ fn do_test_durable_preimages_on_closed_channel( // After a timer tick a payment preimage ChannelMonitorUpdate is applied to the A<->B // ChannelMonitor (possible twice), even though the channel has since been closed. check_added_monitors(&nodes[1], 0); - let mons_added = if close_chans_before_reload { - if !close_only_a { - 4 - } else { - 3 - } - } else { - 2 - }; + let mons_added = if close_chans_before_reload { if !close_only_a { 4 } else { 3 } } else { 2 }; if hold_post_reload_mon_update { for _ in 0..mons_added { persister.set_update_ret(ChannelMonitorUpdateStatus::InProgress); @@ -4154,7 +4147,7 @@ fn do_test_glacial_peer_cant_hang(hold_chan_a: bool) { let node_cfgs = create_node_cfgs(3, &chanmon_cfgs); let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]); - let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs); + let nodes = create_network(3, &node_cfgs, &node_chanmgrs); let node_a_id = nodes[0].node.get_our_node_id(); let node_b_id = nodes[1].node.get_our_node_id(); @@ -4182,7 +4175,7 @@ fn do_test_glacial_peer_cant_hang(hold_chan_a: bool) { if !hold_chan_a { let mut bs_updates = get_htlc_update_msgs(&nodes[1], &node_a_id); - let mut update_fulfill = bs_updates.update_fulfill_htlcs.remove(0); + let update_fulfill = bs_updates.update_fulfill_htlcs.remove(0); nodes[0].node.handle_update_fulfill_htlc(node_b_id, update_fulfill); let commitment = &bs_updates.commitment_signed; do_commitment_signed_dance(&nodes[0], &nodes[1], commitment, false, false); @@ -4219,11 +4212,13 @@ fn do_test_glacial_peer_cant_hang(hold_chan_a: bool) { // ...but once we complete the A<->B channel preimage persistence, the B<->C channel // unlocks and we send both peers commitment updates. let (ab_update_id, _) = nodes[1].chain_monitor.get_latest_mon_update_id(chan_id_ab); - assert!(nodes[1] - .chain_monitor - .chain_monitor - .channel_monitor_updated(chan_id_ab, ab_update_id) - .is_ok()); + assert!( + nodes[1] + .chain_monitor + .chain_monitor + .channel_monitor_updated(chan_id_ab, ab_update_id) + .is_ok() + ); let mut msg_events = nodes[1].node.get_and_clear_pending_msg_events(); assert_eq!(msg_events.len(), 2); @@ -4238,11 +4233,7 @@ fn do_test_glacial_peer_cant_hang(hold_chan_a: bool) { .collect::>(); let a_filtermap = |ev| { if let MessageSendEvent::UpdateHTLCs { node_id, channel_id: _, updates } = ev { - if node_id == node_a_id { - Some(updates) - } else { - None - } + if node_id == node_a_id { Some(updates) } else { None } } else { None } @@ -4576,10 +4567,12 @@ fn test_claim_to_closed_channel_blocks_forwarded_preimage_removal() { // At this point nodes[1] has the preimage and is waiting for the `ChannelMonitorUpdate` for // channel A to hit disk. Until it does so, it shouldn't ever let the preimage dissapear from // channel B's `ChannelMonitor` - assert!(get_monitor!(nodes[1], chan_b.2) - .get_all_current_outbound_htlcs() - .iter() - .any(|(_, (_, preimage))| *preimage == Some(payment_preimage))); + assert!( + get_monitor!(nodes[1], chan_b.2) + .get_all_current_outbound_htlcs() + .iter() + .any(|(_, (_, preimage))| *preimage == Some(payment_preimage)) + ); // Once we complete the `ChannelMonitorUpdate` on channel A, and the `ChannelManager` processes // background events (via `get_and_clear_pending_msg_events`), the final `ChannelMonitorUpdate` @@ -4592,10 +4585,12 @@ fn test_claim_to_closed_channel_blocks_forwarded_preimage_removal() { nodes[1].chain_monitor.complete_sole_pending_chan_update(&chan_a.2); assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty()); check_added_monitors(&nodes[1], 1); - assert!(!get_monitor!(nodes[1], chan_b.2) - .get_all_current_outbound_htlcs() - .iter() - .any(|(_, (_, preimage))| *preimage == Some(payment_preimage))); + assert!( + !get_monitor!(nodes[1], chan_b.2) + .get_all_current_outbound_htlcs() + .iter() + .any(|(_, (_, preimage))| *preimage == Some(payment_preimage)) + ); expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], None, true, false); } @@ -4674,7 +4669,7 @@ fn test_single_channel_multiple_mpp() { 10; let configs: [Option; 9] = core::array::from_fn(|_| Some(config.clone())); let node_chanmgrs = create_node_chanmgrs(9, &node_cfgs, &configs); - let mut nodes = create_network(9, &node_cfgs, &node_chanmgrs); + let nodes = create_network(9, &node_cfgs, &node_chanmgrs); let node_b_id = nodes[1].node.get_our_node_id(); let node_c_id = nodes[2].node.get_our_node_id(); @@ -4728,7 +4723,7 @@ fn test_single_channel_multiple_mpp() { create_announced_chan_between_nodes_with_value(&nodes, 6, 7, 100_000, 0); create_announced_chan_between_nodes_with_value(&nodes, 7, 8, 1_000_000, 0); - let (mut route, payment_hash, payment_preimage, payment_secret) = + let (route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[8], 50_000_000); send_along_route_with_secret( @@ -4772,7 +4767,7 @@ fn test_single_channel_multiple_mpp() { let thrd_event = std::thread::spawn(move || { let mut have_event = false; while !have_event { - let mut events = event_node.get_and_clear_pending_events(); + let events = event_node.get_and_clear_pending_events(); assert!(events.len() == 1 || events.len() == 0); if events.len() == 1 { if let Event::PaymentClaimed { .. } = events[0] { @@ -5170,7 +5165,7 @@ fn test_mpp_claim_to_holding_cell() { nodes[2].node.send_payment(paymnt_hash_2, onion, id, route_params, Retry::Attempts(0)).unwrap(); check_added_monitors(&nodes[2], 1); - let mut payment_event = SendEvent::from_node(&nodes[2]); + let payment_event = SendEvent::from_node(&nodes[2]); nodes[3].node.handle_update_add_htlc(node_c_id, &payment_event.msgs[0]); nodes[3].node.handle_commitment_signed_batch_test(node_c_id, &payment_event.commitment_msg); check_added_monitors(&nodes[3], 1); @@ -5217,7 +5212,7 @@ fn test_mpp_claim_to_holding_cell() { // Finally, clear all the pending payments. let path = [&[&nodes[1], &nodes[3]][..], &[&nodes[2], &nodes[3]][..]]; - let mut args = ClaimAlongRouteArgs::new(&nodes[0], &path[..], preimage_1); + let args = ClaimAlongRouteArgs::new(&nodes[0], &path[..], preimage_1); let b_claim_msgs = (b_claim.update_fulfill_htlcs.pop().unwrap(), b_claim.commitment_signed); let c_claim_msgs = (c_claim.update_fulfill_htlcs.pop().unwrap(), c_claim.commitment_signed); let claims = vec![(b_claim_msgs, node_b_id), (c_claim_msgs, node_c_id)]; diff --git a/lightning/src/ln/channel.rs b/lightning/src/ln/channel.rs index 8c74fa6753a..2cf1cd7507b 100644 --- a/lightning/src/ln/channel.rs +++ b/lightning/src/ln/channel.rs @@ -7,6 +7,7 @@ // You may not use this file except in accordance with one or both of these // licenses. +use bitcoin::Witness; use bitcoin::absolute::LockTime; use bitcoin::amount::{Amount, SignedAmount}; use bitcoin::consensus::encode; @@ -14,19 +15,19 @@ use bitcoin::constants::ChainHash; use bitcoin::script::{Builder, Script, ScriptBuf}; use bitcoin::sighash::EcdsaSighashType; use bitcoin::transaction::{Transaction, TxOut}; -use bitcoin::Witness; use bitcoin::hash_types::{BlockHash, Txid}; +use bitcoin::hashes::Hash; use bitcoin::hashes::sha256::Hash as Sha256; use bitcoin::hashes::sha256d::Hash as Sha256d; -use bitcoin::hashes::Hash; use bitcoin::secp256k1::constants::PUBLIC_KEY_SIZE; -use bitcoin::secp256k1::{ecdsa::Signature, Secp256k1}; use bitcoin::secp256k1::{PublicKey, SecretKey}; -use bitcoin::{secp256k1, sighash, FeeRate, Sequence, TxIn}; +use bitcoin::secp256k1::{Secp256k1, ecdsa::Signature}; +use bitcoin::{FeeRate, Sequence, TxIn, secp256k1, sighash}; use crate::blinded_path::message::BlindedMessagePath; +use crate::chain::BlockLocator; use crate::chain::chaininterface::{ ChannelFunding, ConfirmationTarget, FeeEstimator, FundingCandidate, FundingPurpose, LowerBoundedFeeEstimator, TransactionType, @@ -36,25 +37,24 @@ use crate::chain::channelmonitor::{ LATENCY_GRACE_PERIOD_BLOCKS, }; use crate::chain::transaction::{OutPoint, TransactionData}; -use crate::chain::BlockLocator; use crate::events::{ClosureReason, FundingInfo}; use crate::ln::chan_utils; use crate::ln::chan_utils::{ - get_commitment_transaction_number_obscure_factor, max_htlcs, second_stage_tx_fees_sat, - selected_commitment_sat_per_1000_weight, ChannelPublicKeys, ChannelTransactionParameters, - ClosingTransaction, CommitmentTransaction, CounterpartyChannelTransactionParameters, - CounterpartyCommitmentSecrets, HTLCOutputInCommitment, HolderCommitmentTransaction, - EMPTY_SCRIPT_SIG_WEIGHT, FUNDING_TRANSACTION_WITNESS_WEIGHT, + ChannelPublicKeys, ChannelTransactionParameters, ClosingTransaction, CommitmentTransaction, + CounterpartyChannelTransactionParameters, CounterpartyCommitmentSecrets, + EMPTY_SCRIPT_SIG_WEIGHT, FUNDING_TRANSACTION_WITNESS_WEIGHT, HTLCOutputInCommitment, + HolderCommitmentTransaction, get_commitment_transaction_number_obscure_factor, max_htlcs, + second_stage_tx_fees_sat, selected_commitment_sat_per_1000_weight, }; use crate::ln::channel_state::{ ChannelShutdownState, CounterpartyForwardingInfo, InboundHTLCDetails, InboundHTLCStateDetails, OutboundHTLCDetails, OutboundHTLCStateDetails, }; use crate::ln::channelmanager::{ - self, BlindedFailure, ChannelReadyOrder, FundingConfirmedMessage, HTLCFailureMsg, - HTLCPreviousHopData, HTLCSource, OpenChannelMessage, PaymentClaimDetails, PendingHTLCInfo, - PendingHTLCStatus, RAACommitmentOrder, SentHTLCId, TrustedChannelFeatures, BREAKDOWN_TIMEOUT, - MAX_LOCAL_BREAKDOWN_TIMEOUT, MIN_CLTV_EXPIRY_DELTA, + self, BREAKDOWN_TIMEOUT, BlindedFailure, ChannelReadyOrder, FundingConfirmedMessage, + HTLCFailureMsg, HTLCPreviousHopData, HTLCSource, MAX_LOCAL_BREAKDOWN_TIMEOUT, + MIN_CLTV_EXPIRY_DELTA, OpenChannelMessage, PaymentClaimDetails, PendingHTLCInfo, + PendingHTLCStatus, RAACommitmentOrder, SentHTLCId, TrustedChannelFeatures, }; use crate::ln::funding::{ FeeRateAdjustmentError, FundingContribution, FundingTemplate, FundingTxInput, PriorContribution, @@ -66,7 +66,7 @@ use crate::ln::interactivetxs::{ use crate::ln::msgs; use crate::ln::msgs::{ClosingSigned, ClosingSignedFeeRange, DecodeError, OnionErrorPacket}; use crate::ln::onion_utils::{ - AttributionData, HTLCFailReason, LocalHTLCFailureReason, HOLD_TIME_UNIT_MILLIS, + AttributionData, HOLD_TIME_UNIT_MILLIS, HTLCFailReason, LocalHTLCFailureReason, }; use crate::ln::script::{self, ShutdownScript}; use crate::ln::types::ChannelId; @@ -90,7 +90,7 @@ use crate::util::ser::{Readable, ReadableArgs, RequiredWrapper, Writeable, Write use crate::util::wallet_utils::Input; use crate::{impl_readable_for_vec, impl_writeable_for_vec}; -use alloc::collections::{btree_map, BTreeMap}; +use alloc::collections::{BTreeMap, btree_map}; use crate::io; use crate::prelude::*; @@ -516,7 +516,7 @@ impl<'a> Into> for &'a OutboundHTLCOutcome { fn into(self) -> Option<&'a HTLCFailReason> { match self { OutboundHTLCOutcome::Success { .. } => None, - OutboundHTLCOutcome::Failure(ref r) => Some(r), + OutboundHTLCOutcome::Failure(r) => Some(r), } } } @@ -700,31 +700,69 @@ mod state_flags { define_state_flags!( "Flags that apply to all [`ChannelState`] variants in which the channel is funded.", - FundedStateFlags, [ - ("Indicates the remote side is considered \"disconnected\" and no updates are allowed \ - until after we've done a `channel_reestablish` dance.", PEER_DISCONNECTED, state_flags::PEER_DISCONNECTED, - is_peer_disconnected, set_peer_disconnected, clear_peer_disconnected), - ("Indicates the user has told us a `ChannelMonitor` update is pending async persistence \ + FundedStateFlags, + [ + ( + "Indicates the remote side is considered \"disconnected\" and no updates are allowed \ + until after we've done a `channel_reestablish` dance.", + PEER_DISCONNECTED, + state_flags::PEER_DISCONNECTED, + is_peer_disconnected, + set_peer_disconnected, + clear_peer_disconnected + ), + ( + "Indicates the user has told us a `ChannelMonitor` update is pending async persistence \ somewhere and we should pause sending any outbound messages until they've managed to \ - complete it.", MONITOR_UPDATE_IN_PROGRESS, state_flags::MONITOR_UPDATE_IN_PROGRESS, - is_monitor_update_in_progress, set_monitor_update_in_progress, clear_monitor_update_in_progress), - ("Indicates we received a `shutdown` message from the remote end. If set, they may not add \ + complete it.", + MONITOR_UPDATE_IN_PROGRESS, + state_flags::MONITOR_UPDATE_IN_PROGRESS, + is_monitor_update_in_progress, + set_monitor_update_in_progress, + clear_monitor_update_in_progress + ), + ( + "Indicates we received a `shutdown` message from the remote end. If set, they may not add \ any new HTLCs to the channel, and we are expected to respond with our own `shutdown` \ - message when possible.", REMOTE_SHUTDOWN_SENT, state_flags::REMOTE_SHUTDOWN_SENT, - is_remote_shutdown_sent, set_remote_shutdown_sent, clear_remote_shutdown_sent), - ("Indicates we sent a `shutdown` message. At this point, we may not add any new HTLCs to \ - the channel.", LOCAL_SHUTDOWN_SENT, state_flags::LOCAL_SHUTDOWN_SENT, - is_local_shutdown_sent, set_local_shutdown_sent, clear_local_shutdown_sent) + message when possible.", + REMOTE_SHUTDOWN_SENT, + state_flags::REMOTE_SHUTDOWN_SENT, + is_remote_shutdown_sent, + set_remote_shutdown_sent, + clear_remote_shutdown_sent + ), + ( + "Indicates we sent a `shutdown` message. At this point, we may not add any new HTLCs to \ + the channel.", + LOCAL_SHUTDOWN_SENT, + state_flags::LOCAL_SHUTDOWN_SENT, + is_local_shutdown_sent, + set_local_shutdown_sent, + clear_local_shutdown_sent + ) ] ); define_state_flags!( "Flags that only apply to [`ChannelState::NegotiatingFunding`].", - NegotiatingFundingFlags, [ - ("Indicates we have (or are prepared to) send our `open_channel`/`accept_channel` message.", - OUR_INIT_SENT, state_flags::OUR_INIT_SENT, is_our_init_sent, set_our_init_sent, clear_our_init_sent), - ("Indicates we have received their `open_channel`/`accept_channel` message.", - THEIR_INIT_SENT, state_flags::THEIR_INIT_SENT, is_their_init_sent, set_their_init_sent, clear_their_init_sent) + NegotiatingFundingFlags, + [ + ( + "Indicates we have (or are prepared to) send our `open_channel`/`accept_channel` message.", + OUR_INIT_SENT, + state_flags::OUR_INIT_SENT, + is_our_init_sent, + set_our_init_sent, + clear_our_init_sent + ), + ( + "Indicates we have received their `open_channel`/`accept_channel` message.", + THEIR_INIT_SENT, + state_flags::THEIR_INIT_SENT, + is_their_init_sent, + set_their_init_sent, + clear_their_init_sent + ) ] ); @@ -737,45 +775,85 @@ define_state_flags!( define_state_flags!( "Flags that only apply to [`ChannelState::AwaitingChannelReady`].", - FUNDED_STATE, AwaitingChannelReadyFlags, [ - ("Indicates they sent us a `channel_ready` message. Once both `THEIR_CHANNEL_READY` and \ + FUNDED_STATE, + AwaitingChannelReadyFlags, + [ + ( + "Indicates they sent us a `channel_ready` message. Once both `THEIR_CHANNEL_READY` and \ `OUR_CHANNEL_READY` are set, our state moves on to `ChannelReady`.", - THEIR_CHANNEL_READY, state_flags::THEIR_CHANNEL_READY, - is_their_channel_ready, set_their_channel_ready, clear_their_channel_ready), - ("Indicates we sent them a `channel_ready` message. Once both `THEIR_CHANNEL_READY` and \ + THEIR_CHANNEL_READY, + state_flags::THEIR_CHANNEL_READY, + is_their_channel_ready, + set_their_channel_ready, + clear_their_channel_ready + ), + ( + "Indicates we sent them a `channel_ready` message. Once both `THEIR_CHANNEL_READY` and \ `OUR_CHANNEL_READY` are set, our state moves on to `ChannelReady`.", - OUR_CHANNEL_READY, state_flags::OUR_CHANNEL_READY, - is_our_channel_ready, set_our_channel_ready, clear_our_channel_ready), - ("Indicates the channel was funded in a batch and the broadcast of the funding transaction \ + OUR_CHANNEL_READY, + state_flags::OUR_CHANNEL_READY, + is_our_channel_ready, + set_our_channel_ready, + clear_our_channel_ready + ), + ( + "Indicates the channel was funded in a batch and the broadcast of the funding transaction \ is being held until all channels in the batch have received `funding_signed` and have \ - their monitors persisted.", WAITING_FOR_BATCH, state_flags::WAITING_FOR_BATCH, - is_waiting_for_batch, set_waiting_for_batch, clear_waiting_for_batch) + their monitors persisted.", + WAITING_FOR_BATCH, + state_flags::WAITING_FOR_BATCH, + is_waiting_for_batch, + set_waiting_for_batch, + clear_waiting_for_batch + ) ] ); define_state_flags!( "Flags that only apply to [`ChannelState::ChannelReady`].", - FUNDED_STATE, ChannelReadyFlags, [ - ("Indicates that we have sent a `commitment_signed` but are awaiting the responding \ + FUNDED_STATE, + ChannelReadyFlags, + [ + ( + "Indicates that we have sent a `commitment_signed` but are awaiting the responding \ `revoke_and_ack` message. During this period, we can't generate new `commitment_signed` \ messages as we'd be unable to determine which HTLCs they included in their `revoke_and_ack` \ implicit ACK, so instead we have to hold them away temporarily to be sent later.", - AWAITING_REMOTE_REVOKE, state_flags::AWAITING_REMOTE_REVOKE, - is_awaiting_remote_revoke, set_awaiting_remote_revoke, clear_awaiting_remote_revoke), - ("Indicates we have sent a `stfu` message to the counterparty. This message can only be sent \ + AWAITING_REMOTE_REVOKE, + state_flags::AWAITING_REMOTE_REVOKE, + is_awaiting_remote_revoke, + set_awaiting_remote_revoke, + clear_awaiting_remote_revoke + ), + ( + "Indicates we have sent a `stfu` message to the counterparty. This message can only be sent \ if `REMOTE_STFU_SENT` is set, or a `QuiescentAction` is pending. Shutdown requests are \ rejected if this flag is set.", - LOCAL_STFU_SENT, state_flags::LOCAL_STFU_SENT, - is_local_stfu_sent, set_local_stfu_sent, clear_local_stfu_sent), - ("Indicates we have received a `stfu` message from the counterparty. Shutdown requests are \ + LOCAL_STFU_SENT, + state_flags::LOCAL_STFU_SENT, + is_local_stfu_sent, + set_local_stfu_sent, + clear_local_stfu_sent + ), + ( + "Indicates we have received a `stfu` message from the counterparty. Shutdown requests are \ rejected if this flag is set.", - REMOTE_STFU_SENT, state_flags::REMOTE_STFU_SENT, - is_remote_stfu_sent, set_remote_stfu_sent, clear_remote_stfu_sent), - ("Indicates the quiescence handshake has completed and the channel is now quiescent. \ + REMOTE_STFU_SENT, + state_flags::REMOTE_STFU_SENT, + is_remote_stfu_sent, + set_remote_stfu_sent, + clear_remote_stfu_sent + ), + ( + "Indicates the quiescence handshake has completed and the channel is now quiescent. \ Updates are not allowed while this flag is set, and any outbound updates will go \ directly into the holding cell.", - QUIESCENT, state_flags::QUIESCENT, - is_quiescent, set_quiescent, clear_quiescent) + QUIESCENT, + state_flags::QUIESCENT, + is_quiescent, + set_quiescent, + clear_quiescent + ) ] ); @@ -1581,19 +1659,11 @@ where } pub fn as_funded(&self) -> Option<&FundedChannel> { - if let ChannelPhase::Funded(channel) = &self.phase { - Some(channel) - } else { - None - } + if let ChannelPhase::Funded(channel) = &self.phase { Some(channel) } else { None } } pub fn as_funded_mut(&mut self) -> Option<&mut FundedChannel> { - if let ChannelPhase::Funded(channel) = &mut self.phase { - Some(channel) - } else { - None - } + if let ChannelPhase::Funded(channel) = &mut self.phase { Some(channel) } else { None } } pub fn as_unfunded_outbound_v1_mut(&mut self) -> Option<&mut OutboundV1Channel> { @@ -1645,11 +1715,7 @@ where } pub fn as_unfunded_v2(&self) -> Option<&PendingV2Channel> { - if let ChannelPhase::UnfundedV2(channel) = &self.phase { - Some(channel) - } else { - None - } + if let ChannelPhase::UnfundedV2(channel) = &self.phase { Some(channel) } else { None } } #[rustfmt::skip] @@ -1844,7 +1910,10 @@ where if funded_channel.should_reset_pending_splice_state(false) { funded_channel.reset_pending_splice_state() } else { - debug_assert!(false, "We should never fail an interactive funding negotiation once we're exchanging tx_signatures"); + debug_assert!( + false, + "We should never fail an interactive funding negotiation once we're exchanging tx_signatures" + ); None } }, @@ -2178,14 +2247,16 @@ where context.interactive_tx_signing_session.as_mut() { if let Some(pending_splice) = pending_splice.as_ref() { - debug_assert!(pending_splice - .funding_negotiation - .as_ref() - .map(|funding_negotiation| matches!( - funding_negotiation, - FundingNegotiation::AwaitingSignatures { .. } - )) - .unwrap_or(false)); + debug_assert!( + pending_splice + .funding_negotiation + .as_ref() + .map(|funding_negotiation| matches!( + funding_negotiation, + FundingNegotiation::AwaitingSignatures { .. } + )) + .unwrap_or(false) + ); } if signing_session.has_holder_tx_signatures() { @@ -2284,7 +2355,7 @@ where .and_then(|pending_splice| pending_splice.funding_negotiation.as_mut()) .and_then(|funding_negotiation| { if let FundingNegotiation::AwaitingSignatures { - ref mut initial_commitment_signed_from_counterparty, + initial_commitment_signed_from_counterparty, .. } = funding_negotiation { @@ -2354,11 +2425,9 @@ where }; let res = funded_channel.initial_commitment_signed_v2(msg, best_block, signer_provider, logger) .map(|monitor| (Some(monitor), None)) - // TODO: Change to `inspect_err` when MSRV is high enough. - .map_err(|err| { + .inspect_err(|err| { // We always expect a `ChannelError` close. debug_assert!(matches!(err, ChannelError::Close(_))); - err }); self.phase = ChannelPhase::Funded(funded_channel); res @@ -2402,7 +2471,7 @@ where .expect("We have a pending splice negotiated"); log_debug!(logger, "Stashing counterparty initial commitment_signed to process after funding_transaction_signed"); if let FundingNegotiation::AwaitingSignatures { - ref mut initial_commitment_signed_from_counterparty, .. + initial_commitment_signed_from_counterparty, .. } = funding_negotiation { *initial_commitment_signed_from_counterparty = Some(msg.clone()); } @@ -2721,11 +2790,7 @@ impl FundingScope { /// Returns the height in which our funding transaction was confirmed. pub fn get_funding_tx_confirmation_height(&self) -> Option { let conf_height = self.funding_tx_confirmation_height; - if conf_height > 0 { - Some(conf_height) - } else { - None - } + if conf_height > 0 { Some(conf_height) } else { None } } /// Returns the current number of confirmations on the funding transaction. @@ -3901,7 +3966,7 @@ impl ChannelContext { if config.channel_handshake_limits.force_announced_channel_preference { if config.channel_handshake_config.announce_for_forwarding != announce_for_forwarding { return Err(ChannelError::close(String::from( - "Peer tried to open channel but their announcement preference is different from ours" + "Peer tried to open channel but their announcement preference is different from ours", ))); } } @@ -3925,7 +3990,8 @@ impl ChannelContext { log_debug!( logger, "channel_reserve_satoshis ({msg_channel_reserve_satoshis}) is smaller than our dust limit ({MIN_CHAN_DUST_LIMIT_SATOSHIS}). We can broadcast \ - stale states without any risk, implying this channel is very insecure for our counterparty."); + stale states without any risk, implying this channel is very insecure for our counterparty." + ); } if holder_selected_channel_reserve_satoshis < open_channel_fields.dust_limit_satoshis && holder_selected_channel_reserve_satoshis != 0 @@ -3940,32 +4006,33 @@ impl ChannelContext { debug_assert!(our_funding_satoshis == 0 || msg_push_msat == 0); let value_to_self_msat = our_funding_satoshis * 1000 + msg_push_msat; - let counterparty_shutdown_scriptpubkey = - if their_features.supports_upfront_shutdown_script() { - match &open_channel_fields.shutdown_scriptpubkey { - &Some(ref script) => { - // Peer is signaling upfront_shutdown and has opt-out with a 0-length script. We don't enforce anything - if script.len() == 0 { - None - } else { - if !script::is_bolt2_compliant(&script, their_features) { - return Err(ChannelError::close(format!( + let counterparty_shutdown_scriptpubkey = if their_features + .supports_upfront_shutdown_script() + { + match &open_channel_fields.shutdown_scriptpubkey { + &Some(ref script) => { + // Peer is signaling upfront_shutdown and has opt-out with a 0-length script. We don't enforce anything + if script.len() == 0 { + None + } else { + if !script::is_bolt2_compliant(&script, their_features) { + return Err(ChannelError::close(format!( "Peer is signaling upfront_shutdown but has provided an unacceptable scriptpubkey format: {script}" ))); - } - Some(script.clone()) } - }, - // Peer is signaling upfront shutdown but don't opt-out with correct mechanism (a.k.a 0-length script). Peer looks buggy, we fail the channel - &None => { - return Err(ChannelError::close(String::from( - "Peer is signaling upfront_shutdown but we don't get any script. Use 0-length script to opt-out" + Some(script.clone()) + } + }, + // Peer is signaling upfront shutdown but don't opt-out with correct mechanism (a.k.a 0-length script). Peer looks buggy, we fail the channel + &None => { + return Err(ChannelError::close(String::from( + "Peer is signaling upfront_shutdown but we don't get any script. Use 0-length script to opt-out", ))); - }, - } - } else { - None - }; + }, + } + } else { + None + }; let shutdown_scriptpubkey = if config.channel_handshake_config.commit_upfront_shutdown_pubkey { @@ -3974,7 +4041,7 @@ impl ChannelContext { Err(_) => { return Err(ChannelError::close( "Failed to get upfront shutdown scriptpubkey".to_owned(), - )) + )); }, } } else { @@ -3992,7 +4059,7 @@ impl ChannelContext { let destination_script = match signer_provider.get_destination_script(channel_keys_id) { Ok(script) => script, Err(_) => { - return Err(ChannelError::close("Failed to get destination script".to_owned())) + return Err(ChannelError::close("Failed to get destination script".to_owned())); }, }; @@ -4262,15 +4329,18 @@ impl ChannelContext { if holder_selected_contest_delay < BREAKDOWN_TIMEOUT { return Err(APIError::APIMisuseError { err: format!( - "Configured with an unreasonable our_to_self_delay ({holder_selected_contest_delay}) putting user funds at risks" - ), + "Configured with an unreasonable our_to_self_delay ({holder_selected_contest_delay}) putting user funds at risks" + ), }); } let channel_type = get_initial_channel_type(&config, their_features); debug_assert!(!channel_type.supports_any_optional_bits()); - debug_assert!(!channel_type - .requires_unknown_bits_from(&channelmanager::provided_channel_type_features(&config))); + debug_assert!( + !channel_type.requires_unknown_bits_from( + &channelmanager::provided_channel_type_features(&config) + ) + ); let commitment_feerate = selected_commitment_sat_per_1000_weight(&fee_estimator, &channel_type); @@ -4287,7 +4357,7 @@ impl ChannelContext { Err(_) => { return Err(APIError::ChannelUnavailable { err: "Failed to get shutdown scriptpubkey".to_owned(), - }) + }); }, } } else { @@ -4307,7 +4377,7 @@ impl ChannelContext { Err(_) => { return Err(APIError::ChannelUnavailable { err: "Failed to get destination script".to_owned(), - }) + }); }, }; @@ -4876,32 +4946,33 @@ impl ChannelContext { ))); } - let counterparty_shutdown_scriptpubkey = - if their_features.supports_upfront_shutdown_script() { - match &common_fields.shutdown_scriptpubkey { - &Some(ref script) => { - // Peer is signaling upfront_shutdown and has opt-out with a 0-length script. We don't enforce anything - if script.len() == 0 { - None - } else { - if !script::is_bolt2_compliant(&script, their_features) { - return Err(ChannelError::close(format!( + let counterparty_shutdown_scriptpubkey = if their_features + .supports_upfront_shutdown_script() + { + match &common_fields.shutdown_scriptpubkey { + &Some(ref script) => { + // Peer is signaling upfront_shutdown and has opt-out with a 0-length script. We don't enforce anything + if script.len() == 0 { + None + } else { + if !script::is_bolt2_compliant(&script, their_features) { + return Err(ChannelError::close(format!( "Peer is signaling upfront_shutdown but has provided an unacceptable scriptpubkey format: {script}" ))); - } - Some(script.clone()) } - }, - // Peer is signaling upfront shutdown but don't opt-out with correct mechanism (a.k.a 0-length script). Peer looks buggy, we fail the channel - &None => { - return Err(ChannelError::close(String::from( - "Peer is signaling upfront_shutdown but we don't get any script. Use 0-length script to opt-out" + Some(script.clone()) + } + }, + // Peer is signaling upfront shutdown but don't opt-out with correct mechanism (a.k.a 0-length script). Peer looks buggy, we fail the channel + &None => { + return Err(ChannelError::close(String::from( + "Peer is signaling upfront_shutdown but we don't get any script. Use 0-length script to opt-out", ))); - }, - } - } else { - None - }; + }, + } + } else { + None + }; self.counterparty_dust_limit_satoshis = common_fields.dust_limit_satoshis; self.counterparty_max_htlc_value_in_flight_msat = cmp::min( @@ -5554,22 +5625,16 @@ impl ChannelContext { let max_dust_htlc_exposure_msat = self.get_max_dust_htlc_exposure_msat(dust_exposure_limiting_feerate); if local_stats.commitment_stats.dust_exposure_msat > max_dust_htlc_exposure_msat { - return Err(ChannelError::close( - format!( - "Peer sent update_fee with a feerate ({}) which may over-expose us to dust-in-flight on our own transactions (totaling {} msat)", - new_feerate_per_kw, - local_stats.commitment_stats.dust_exposure_msat, - ) - )); + return Err(ChannelError::close(format!( + "Peer sent update_fee with a feerate ({}) which may over-expose us to dust-in-flight on our own transactions (totaling {} msat)", + new_feerate_per_kw, local_stats.commitment_stats.dust_exposure_msat, + ))); } if remote_stats.commitment_stats.dust_exposure_msat > max_dust_htlc_exposure_msat { - return Err(ChannelError::close( - format!( - "Peer sent update_fee with a feerate ({}) which may over-expose us to dust-in-flight on our counterparty's transactions (totaling {} msat)", - new_feerate_per_kw, - remote_stats.commitment_stats.dust_exposure_msat, - ) - )); + return Err(ChannelError::close(format!( + "Peer sent update_fee with a feerate ({}) which may over-expose us to dust-in-flight on our counterparty's transactions (totaling {} msat)", + new_feerate_per_kw, remote_stats.commitment_stats.dust_exposure_msat, + ))); } Ok(()) @@ -5603,11 +5668,14 @@ impl ChannelContext { let sighash = bitcoin_tx.get_sighash_all(&funding_script, funding.get_value_satoshis()); - log_trace!(logger, "Checking commitment tx signature {} by key {} against tx {} (sighash {}) with redeemscript {} in channel {}", + log_trace!( + logger, + "Checking commitment tx signature {} by key {} against tx {} (sighash {}) with redeemscript {} in channel {}", log_bytes!(msg.signature.serialize_compact()[..]), log_bytes!(funding.counterparty_funding_pubkey().serialize()), encode::serialize_hex(&bitcoin_tx.transaction), - log_bytes!(sighash[..]), encode::serialize_hex(&funding_script), + log_bytes!(sighash[..]), + encode::serialize_hex(&funding_script), &self.channel_id(), ); if let Err(_) = self.secp_ctx.verify_ecdsa( @@ -5673,7 +5741,9 @@ impl ChannelContext { ) .unwrap()[..] ); - log_trace!(logger, "Checking HTLC tx signature {} by key {} against tx {} (sighash {}) with redeemscript {} in channel {}.", + log_trace!( + logger, + "Checking HTLC tx signature {} by key {} against tx {} (sighash {}) with redeemscript {} in channel {}.", log_bytes!(counterparty_sig.serialize_compact()[..]), log_bytes!(holder_keys.countersignatory_htlc_key.to_public_key().serialize()), encode::serialize_hex(&htlc_tx), @@ -5845,7 +5915,7 @@ impl ChannelContext { log_info!( logger, "Cannot accept value that would put our total dust exposure at {} over the limit {} on counterparty commitment tx", - remote_stats.commitment_stats.dust_exposure_msat, + remote_stats.commitment_stats.dust_exposure_msat, max_dust_htlc_exposure_msat, ); return Err(LocalHTLCFailureReason::DustLimitCounterparty); @@ -5893,7 +5963,6 @@ impl ChannelContext { log_info!( logger, "Attempting to fail HTLC due to fee spike buffer violation. Rebalancing is required.", - ); return Err(LocalHTLCFailureReason::FeeSpikeBuffer); } @@ -6409,8 +6478,7 @@ impl ChannelContext { let unbroadcasted_batch_funding_txid = self.unbroadcasted_batch_funding_txid(funding); let unbroadcasted_funding_tx = self.unbroadcasted_funding(funding); - if let ClosureReason::HolderForceClosed { ref mut broadcasted_latest_txn, .. } = - &mut closure_reason + if let ClosureReason::HolderForceClosed { broadcasted_latest_txn, .. } = &mut closure_reason { *broadcasted_latest_txn = Some(broadcast); } @@ -7548,7 +7616,12 @@ where InboundHTLCState::LocalRemoved(ref reason) => { if let &InboundHTLCRemovalReason::Fulfill { .. } = reason { } else { - log_warn!(logger, "Have preimage and want to fulfill HTLC with payment hash {} we already failed against channel {}", &htlc.payment_hash, &self.context.channel_id()); + log_warn!( + logger, + "Have preimage and want to fulfill HTLC with payment hash {} we already failed against channel {}", + &htlc.payment_hash, + &self.context.channel_id() + ); debug_assert!( false, "Tried to fulfill an HTLC that was already failed" @@ -7557,7 +7630,10 @@ where return UpdateFulfillFetch::DuplicateClaim {}; }, _ => { - debug_assert!(false, "Have an inbound HTLC we tried to claim before it was fully committed to"); + debug_assert!( + false, + "Have an inbound HTLC we tried to claim before it was fully committed to" + ); // Don't return in release mode here so that we can update channel_monitor }, } @@ -7601,7 +7677,11 @@ where &HTLCUpdateAwaitingACK::FailHTLC { htlc_id, .. } | &HTLCUpdateAwaitingACK::FailMalformedHTLC { htlc_id, .. } => { if htlc_id_arg == htlc_id { - log_warn!(logger, "Have preimage and want to fulfill HTLC with pending failure against channel {}", &self.context.channel_id()); + log_warn!( + logger, + "Have preimage and want to fulfill HTLC with pending failure against channel {}", + &self.context.channel_id() + ); // TODO: We may actually be able to switch to a fulfill here, though its // rare enough it may not be worth the complexity burden. debug_assert!( @@ -7702,7 +7782,10 @@ where held_update.update.update_id += 1; } if !update_blocked { - debug_assert!(false, "If there is a pending blocked monitor we should have MonitorUpdateInProgress set"); + debug_assert!( + false, + "If there is a pending blocked monitor we should have MonitorUpdateInProgress set" + ); let update = self.build_commitment_no_status_check(logger); self.context .blocked_monitor_updates @@ -8190,13 +8273,23 @@ where } } match htlc.state { - OutboundHTLCState::LocalAnnounced(_) => - return Err(ChannelError::close(format!("Remote tried to fulfill/fail HTLC ({}) before it had been committed", htlc_id))), + OutboundHTLCState::LocalAnnounced(_) => { + return Err(ChannelError::close(format!( + "Remote tried to fulfill/fail HTLC ({}) before it had been committed", + htlc_id + ))); + }, OutboundHTLCState::Committed => { htlc.state = OutboundHTLCState::RemoteRemoved(outcome); }, - OutboundHTLCState::AwaitingRemoteRevokeToRemove(_) | OutboundHTLCState::AwaitingRemovedRemoteRevoke(_) | OutboundHTLCState::RemoteRemoved(_) => - return Err(ChannelError::close(format!("Remote tried to fulfill/fail HTLC ({}) that they'd already fulfilled/failed", htlc_id))), + OutboundHTLCState::AwaitingRemoteRevokeToRemove(_) + | OutboundHTLCState::AwaitingRemovedRemoteRevoke(_) + | OutboundHTLCState::RemoteRemoved(_) => { + return Err(ChannelError::close(format!( + "Remote tried to fulfill/fail HTLC ({}) that they'd already fulfilled/failed", + htlc_id + ))); + }, } return Ok(htlc); } @@ -8337,12 +8430,13 @@ where &mut self, msg: &msgs::CommitmentSigned, fee_estimator: &LowerBoundedFeeEstimator, logger: &L, ) -> Result, ChannelError> { - debug_assert!(self - .context - .interactive_tx_signing_session - .as_ref() - .map(|signing_session| !signing_session.has_received_tx_signatures()) - .unwrap_or(false)); + debug_assert!( + self.context + .interactive_tx_signing_session + .as_ref() + .map(|signing_session| !signing_session.has_received_tx_signatures()) + .unwrap_or(false) + ); let pending_splice_funding = self .pending_splice @@ -8605,7 +8699,10 @@ where // the advance to the next point. This should be unreachable since // a new commitment_signed should fail at our signature checks in // validate_commitment_signed. - debug_assert!(false, "We should be ready to advance our commitment point by the time we receive commitment_signed"); + debug_assert!( + false, + "We should be ready to advance our commitment point by the time we receive commitment_signed" + ); return Err(ChannelError::close("Failed to advance our commitment point".to_owned())); } @@ -8620,8 +8717,12 @@ where for htlc in self.context.pending_inbound_htlcs.iter_mut() { if let &InboundHTLCState::RemoteAnnounced(ref htlc_resolution) = &htlc.state { - log_trace!(logger, "Updating HTLC {} to AwaitingRemoteRevokeToAnnounce due to commitment_signed in channel {}.", - &htlc.payment_hash, &self.context.channel_id); + log_trace!( + logger, + "Updating HTLC {} to AwaitingRemoteRevokeToAnnounce due to commitment_signed in channel {}.", + &htlc.payment_hash, + &self.context.channel_id + ); htlc.state = InboundHTLCState::AwaitingRemoteRevokeToAnnounce(htlc_resolution.clone()); need_commitment = true; @@ -8630,8 +8731,12 @@ where let mut claimed_htlcs = Vec::new(); for htlc in self.context.pending_outbound_htlcs.iter_mut() { if let &mut OutboundHTLCState::RemoteRemoved(ref mut outcome) = &mut htlc.state { - log_trace!(logger, "Updating HTLC {} to AwaitingRemoteRevokeToRemove due to commitment_signed in channel {}.", - &htlc.payment_hash, &self.context.channel_id); + log_trace!( + logger, + "Updating HTLC {} to AwaitingRemoteRevokeToRemove due to commitment_signed in channel {}.", + &htlc.payment_hash, + &self.context.channel_id + ); // Swap against a dummy variant to avoid a potentially expensive clone of `OutboundHTLCOutcome::Failure(HTLCFailReason)` let mut reason = OutboundHTLCOutcome::Success { preimage: PaymentPreimage([0u8; 32]), @@ -8654,14 +8759,14 @@ where match &mut update { ChannelMonitorUpdateStep::LatestHolderCommitment { - claimed_htlcs: ref mut update_claimed_htlcs, + claimed_htlcs: update_claimed_htlcs, .. } => { debug_assert!(update_claimed_htlcs.is_empty()); *update_claimed_htlcs = claimed_htlcs.clone(); }, ChannelMonitorUpdateStep::LatestHolderCommitmentTXInfo { - claimed_htlcs: ref mut update_claimed_htlcs, + claimed_htlcs: update_claimed_htlcs, .. } => { debug_assert!(update_claimed_htlcs.is_empty()); @@ -8697,8 +8802,10 @@ where self.context.latest_monitor_update_id = monitor_update.update_id; monitor_update.updates.append(&mut additional_update.updates); } - log_debug!(logger, "Received valid commitment_signed from peer, updated HTLC state but awaiting a monitor update resolution to reply.", - ); + log_debug!( + logger, + "Received valid commitment_signed from peer, updated HTLC state but awaiting a monitor update resolution to reply.", + ); return Ok(self.push_ret_blockable_mon_update(monitor_update)); } @@ -8717,8 +8824,12 @@ where false }; - log_debug!(logger, "Received valid commitment_signed from peer in channel {}, updating HTLC state and responding with{} a revoke_and_ack.", - &self.context.channel_id(), if need_commitment_signed { " our own commitment_signed and" } else { "" }); + log_debug!( + logger, + "Received valid commitment_signed from peer in channel {}, updating HTLC state and responding with{} a revoke_and_ack.", + &self.context.channel_id(), + if need_commitment_signed { " our own commitment_signed and" } else { "" } + ); self.monitor_updating_paused( true, need_commitment_signed, @@ -8921,9 +9032,14 @@ where self.context.latest_monitor_update_id = monitor_update.update_id; monitor_update.updates.append(&mut additional_update.updates); - log_debug!(logger, "Freeing holding cell resulted in {}{} HTLCs added, {} HTLCs fulfilled, and {} HTLCs failed.", + log_debug!( + logger, + "Freeing holding cell resulted in {}{} HTLCs added, {} HTLCs fulfilled, and {} HTLCs failed.", if update_fee.is_some() { "a fee update, " } else { "" }, - update_add_count, update_fulfill_count, update_fail_count); + update_add_count, + update_fulfill_count, + update_fail_count + ); self.monitor_updating_paused( false, @@ -9132,7 +9248,11 @@ where mem::swap(&mut state, &mut htlc.state); if let InboundHTLCState::AwaitingRemoteRevokeToAnnounce(resolution) = state { - log_trace!(logger, " ...promoting inbound AwaitingRemoteRevokeToAnnounce {} to AwaitingAnnouncedRemoteRevoke", &htlc.payment_hash); + log_trace!( + logger, + " ...promoting inbound AwaitingRemoteRevokeToAnnounce {} to AwaitingAnnouncedRemoteRevoke", + &htlc.payment_hash + ); htlc.state = InboundHTLCState::AwaitingAnnouncedRemoteRevoke(resolution); require_commitment = true; } else if let InboundHTLCState::AwaitingAnnouncedRemoteRevoke(resolution) = @@ -9142,7 +9262,11 @@ where InboundHTLCResolution::Resolved { pending_htlc_status } => { match pending_htlc_status { PendingHTLCStatus::Fail(fail_msg) => { - log_trace!(logger, " ...promoting inbound AwaitingAnnouncedRemoteRevoke {} to LocalRemoved due to PendingHTLCStatus indicating failure", &htlc.payment_hash); + log_trace!( + logger, + " ...promoting inbound AwaitingAnnouncedRemoteRevoke {} to LocalRemoved due to PendingHTLCStatus indicating failure", + &htlc.payment_hash + ); require_commitment = true; match fail_msg { HTLCFailureMsg::Relay(msg) => { @@ -9165,7 +9289,11 @@ where } }, PendingHTLCStatus::Forward(forward_info) => { - log_trace!(logger, " ...promoting inbound AwaitingAnnouncedRemoteRevoke {} to Committed, attempting to forward", &htlc.payment_hash); + log_trace!( + logger, + " ...promoting inbound AwaitingAnnouncedRemoteRevoke {} to Committed, attempting to forward", + &htlc.payment_hash + ); to_forward_infos.push((forward_info, htlc.htlc_id)); htlc.state = InboundHTLCState::Committed { // HTLCs will only be in state `InboundHTLCResolution::Resolved` if they were @@ -9176,7 +9304,11 @@ where } }, InboundHTLCResolution::Pending { update_add_htlc } => { - log_trace!(logger, " ...promoting inbound AwaitingAnnouncedRemoteRevoke {} to Committed", &htlc.payment_hash); + log_trace!( + logger, + " ...promoting inbound AwaitingAnnouncedRemoteRevoke {} to Committed", + &htlc.payment_hash + ); pending_update_adds.push(update_add_htlc.clone()); htlc.state = InboundHTLCState::Committed { update_add_htlc: InboundUpdateAdd::WithOnion { @@ -9201,7 +9333,11 @@ where // online. Otherwise, our counterparty could include paths for all of our HTLCs and // use the responses sent to their paths to determine which of our HTLCs are async // payments. - log_trace!(logger, "Counterparty included release_htlc_message_path for non-async payment HTLC {}", htlc_id); + log_trace!( + logger, + "Counterparty included release_htlc_message_path for non-async payment HTLC {}", + htlc_id + ); continue; }, }; @@ -9219,7 +9355,11 @@ where if let &mut OutboundHTLCState::AwaitingRemoteRevokeToRemove(ref mut outcome) = &mut htlc.state { - log_trace!(logger, " ...promoting outbound AwaitingRemoteRevokeToRemove {} to AwaitingRemovedRemoteRevoke", &htlc.payment_hash); + log_trace!( + logger, + " ...promoting outbound AwaitingRemoteRevokeToRemove {} to AwaitingRemovedRemoteRevoke", + &htlc.payment_hash + ); // Swap against a dummy variant to avoid a potentially expensive clone of `OutboundHTLCOutcome::Failure(HTLCFailReason)` let mut reason = OutboundHTLCOutcome::Success { preimage: PaymentPreimage([0u8; 32]), @@ -9255,7 +9395,11 @@ where }, FeeUpdateState::AwaitingRemoteRevokeToAnnounce => { debug_assert!(!self.funding.is_outbound()); - log_trace!(logger, " ...promoting inbound AwaitingRemoteRevokeToAnnounce fee update {} to Committed", feerate); + log_trace!( + logger, + " ...promoting inbound AwaitingRemoteRevokeToAnnounce fee update {} to Committed", + feerate + ); require_commitment = true; self.context.feerate_per_kw = feerate; self.context.pending_update_fee = None; @@ -9293,8 +9437,11 @@ where self.context.latest_monitor_update_id = monitor_update.update_id; monitor_update.updates.append(&mut additional_update.updates); - log_debug!(logger, "Received a valid revoke_and_ack with holding cell HTLCs freed. {} monitor update.", - release_state_str); + log_debug!( + logger, + "Received a valid revoke_and_ack with holding cell HTLCs freed. {} monitor update.", + release_state_str + ); self.monitor_updating_paused( false, @@ -9327,9 +9474,12 @@ where release_state_str ); if self.context.channel_state.can_generate_new_commitment() { - log_debug!(logger, "Responding with a commitment update with {} HTLCs failed for channel {}", + log_debug!( + logger, + "Responding with a commitment update with {} HTLCs failed for channel {}", update_fail_htlcs.len() + update_fail_malformed_htlcs.len(), - &self.context.channel_id); + &self.context.channel_id + ); } else { let reason = if self.context.channel_state.is_local_stfu_sent() { "exits quiescence" @@ -9352,8 +9502,12 @@ where ); return_with_htlcs_to_fail!(htlcs_to_fail); } else { - log_debug!(logger, "Received a valid revoke_and_ack with no reply necessary. {} monitor update {}.", - release_state_str, monitor_update.update_id); + log_debug!( + logger, + "Received a valid revoke_and_ack with no reply necessary. {} monitor update {}.", + release_state_str, + monitor_update.update_id + ); self.monitor_updating_paused( false, @@ -9479,14 +9633,16 @@ where } if let Some(pending_splice) = self.pending_splice.as_ref() { - debug_assert!(pending_splice - .funding_negotiation - .as_ref() - .map(|funding_negotiation| matches!( - funding_negotiation, - FundingNegotiation::AwaitingSignatures { .. } - )) - .unwrap_or(false)); + debug_assert!( + pending_splice + .funding_negotiation + .as_ref() + .map(|funding_negotiation| matches!( + funding_negotiation, + FundingNegotiation::AwaitingSignatures { .. } + )) + .unwrap_or(false) + ); } signing_session @@ -9899,9 +10055,11 @@ where } if self.context.feerate_per_kw < min_feerate { - log_info!(logger, + log_info!( + logger, "Closing channel as feerate of {} is below required {} (the minimum required rate over the past day)", - self.context.feerate_per_kw, min_feerate + self.context.feerate_per_kw, + min_feerate ); Err(ClosureReason::PeerFeerateTooLow { peer_feerate_sat_per_kw: self.context.feerate_per_kw, @@ -10129,13 +10287,19 @@ where } } if !self.holder_commitment_point.can_advance() { - log_trace!(logger, "Last revoke-and-ack pending for sequence {} because the next per-commitment point is not available", - self.holder_commitment_point.next_transaction_number()); + log_trace!( + logger, + "Last revoke-and-ack pending for sequence {} because the next per-commitment point is not available", + self.holder_commitment_point.next_transaction_number() + ); } if per_commitment_secret.is_none() { - log_trace!(logger, "Last revoke-and-ack pending for sequence {} because the next per-commitment secret for {} is not available", + log_trace!( + logger, + "Last revoke-and-ack pending for sequence {} because the next per-commitment secret for {} is not available", self.holder_commitment_point.next_transaction_number(), - self.holder_commitment_point.next_transaction_number() + 2); + self.holder_commitment_point.next_transaction_number() + 2 + ); } // Technically if HolderCommitmentPoint::can_advance is false, // we have a commitment point ready to send in an RAA, however we @@ -10143,8 +10307,11 @@ where // CS before we have any commitment point available. Blocking our // RAA here is a convenient way to make sure that post-funding // we're only ever waiting on one commitment point at a time. - log_trace!(logger, "Last revoke-and-ack pending for sequence {} because the next per-commitment point is not available", - self.holder_commitment_point.next_transaction_number()); + log_trace!( + logger, + "Last revoke-and-ack pending for sequence {} because the next per-commitment point is not available", + self.holder_commitment_point.next_transaction_number() + ); self.context.signer_pending_revoke_and_ack = true; None } @@ -10219,9 +10386,15 @@ where None }; - log_trace!(logger, "Regenerating latest commitment update with{} {} update_adds, {} update_fulfills, {} update_fails, and {} update_fail_malformeds", - if update_fee.is_some() { " update_fee," } else { "" }, - update_add_htlcs.len(), update_fulfill_htlcs.len(), update_fail_htlcs.len(), update_fail_malformed_htlcs.len()); + log_trace!( + logger, + "Regenerating latest commitment update with{} {} update_adds, {} update_fulfills, {} update_fails, and {} update_fail_malformeds", + if update_fee.is_some() { " update_fee," } else { "" }, + update_add_htlcs.len(), + update_fulfill_htlcs.len(), + update_fail_htlcs.len(), + update_fail_malformed_htlcs.len() + ); let commitment_signed = if let Ok(update) = self.send_commitment_no_state_update(logger) { if self.context.signer_pending_commitment_update { log_trace!( @@ -10271,13 +10444,15 @@ where panic!($err_msg); }; } - log_and_panic!("We have fallen behind - we have received proof that if we broadcast our counterparty is going to claim all our funds.\n\ + log_and_panic!( + "We have fallen behind - we have received proof that if we broadcast our counterparty is going to claim all our funds.\n\ This implies you have restarted with lost ChannelMonitor and ChannelManager state, the first of which is a violation of the LDK chain::Watch requirements.\n\ More specifically, this means you have a bug in your implementation that can cause loss of funds, or you are running with an old backup, which is unsafe.\n\ If you have restored from an old backup and wish to claim any available funds, you should restart with\n\ an empty ChannelManager and no ChannelMonitors, reconnect to peer(s), ensure they've force-closed all of your\n\ previous channels and that the closure transaction(s) have confirmed on-chain,\n\ - then restart with an empty ChannelManager and the latest ChannelMonitors that you do have."); + then restart with an empty ChannelManager and the latest ChannelMonitors that you do have." + ); } /// May panic if some calls other than message-handling calls (which will all Err immediately) @@ -10799,8 +10974,13 @@ where assert!(self.context.shutdown_scriptpubkey.is_some()); let (closing_tx, total_fee_satoshis) = self.build_closing_transaction(our_min_fee, false)?; - log_trace!(logger, "Proposing initial closing_signed for our counterparty with a fee range of {}-{} sat (with initial proposal {} sats)", - our_min_fee, our_max_fee, total_fee_satoshis); + log_trace!( + logger, + "Proposing initial closing_signed for our counterparty with a fee range of {}-{} sat (with initial proposal {} sats)", + our_min_fee, + our_max_fee, + total_fee_satoshis + ); let closing_signed = self.get_closing_signed_msg( &closing_tx, @@ -10914,7 +11094,10 @@ where if self.context.counterparty_shutdown_scriptpubkey.is_some() { if Some(&msg.scriptpubkey) != self.context.counterparty_shutdown_scriptpubkey.as_ref() { - return Err(ChannelError::Warn(format!("Got shutdown request with a scriptpubkey ({}) which did not match their previous scriptpubkey.", msg.scriptpubkey.to_hex_string()))); + return Err(ChannelError::Warn(format!( + "Got shutdown request with a scriptpubkey ({}) which did not match their previous scriptpubkey.", + msg.scriptpubkey.to_hex_string() + ))); } } else { self.context.counterparty_shutdown_scriptpubkey = Some(msg.scriptpubkey.clone()); @@ -10934,7 +11117,7 @@ where Err(_) => { return Err(ChannelError::close( "Failed to get shutdown scriptpubkey".to_owned(), - )) + )); }, }; if !shutdown_scriptpubkey.is_compatible(their_features) { @@ -11092,7 +11275,9 @@ where ) -> Result<(Option, Option<(Transaction, ShutdownResult)>), ChannelError> { if self.is_shutdown_pending_signature() { - return Err(ChannelError::Warn(String::from("Remote end sent us a closing_signed while fully shutdown and just waiting on the final closing signature"))); + return Err(ChannelError::Warn(String::from( + "Remote end sent us a closing_signed while fully shutdown and just waiting on the final closing signature", + ))); } if !self.context.channel_state.is_both_sides_shutdown() { return Err(ChannelError::close( @@ -11134,7 +11319,10 @@ where let (mut closing_tx, used_total_fee) = self.build_closing_transaction(msg.fee_satoshis, skip_remote_output)?; if used_total_fee != msg.fee_satoshis { - return Err(ChannelError::close(format!("Remote sent us a closing_signed with a fee other than the value they can claim. Fee in message: {}. Actual closing tx fee: {}", msg.fee_satoshis, used_total_fee))); + return Err(ChannelError::close(format!( + "Remote sent us a closing_signed with a fee other than the value they can claim. Fee in message: {}. Actual closing tx fee: {}", + msg.fee_satoshis, used_total_fee + ))); } let sighash = closing_tx .trust() @@ -11229,13 +11417,22 @@ where msg.fee_range { if msg.fee_satoshis < min_fee_satoshis || msg.fee_satoshis > max_fee_satoshis { - return Err(ChannelError::close(format!("Peer sent a bogus closing_signed - suggested fee of {} sat was not in their desired range of {} sat - {} sat", msg.fee_satoshis, min_fee_satoshis, max_fee_satoshis))); + return Err(ChannelError::close(format!( + "Peer sent a bogus closing_signed - suggested fee of {} sat was not in their desired range of {} sat - {} sat", + msg.fee_satoshis, min_fee_satoshis, max_fee_satoshis + ))); } if max_fee_satoshis < our_min_fee { - return Err(ChannelError::Warn(format!("Unable to come to consensus about closing feerate, remote's max fee ({} sat) was smaller than our min fee ({} sat)", max_fee_satoshis, our_min_fee))); + return Err(ChannelError::Warn(format!( + "Unable to come to consensus about closing feerate, remote's max fee ({} sat) was smaller than our min fee ({} sat)", + max_fee_satoshis, our_min_fee + ))); } if min_fee_satoshis > our_max_fee { - return Err(ChannelError::Warn(format!("Unable to come to consensus about closing feerate, remote's min fee ({} sat) was greater than our max fee ({} sat)", min_fee_satoshis, our_max_fee))); + return Err(ChannelError::Warn(format!( + "Unable to come to consensus about closing feerate, remote's min fee ({} sat) was greater than our max fee ({} sat)", + min_fee_satoshis, our_max_fee + ))); } if !self.funding.is_outbound() { @@ -11249,8 +11446,10 @@ where propose_fee!(cmp::min(max_fee_satoshis, our_max_fee)); } else { if msg.fee_satoshis < our_min_fee || msg.fee_satoshis > our_max_fee { - return Err(ChannelError::close(format!("Peer sent a bogus closing_signed - suggested fee of {} sat was not in our desired range of {} sat - {} sat after we informed them of our range.", - msg.fee_satoshis, our_min_fee, our_max_fee))); + return Err(ChannelError::close(format!( + "Peer sent a bogus closing_signed - suggested fee of {} sat was not in our desired range of {} sat - {} sat after we informed them of our range.", + msg.fee_satoshis, our_min_fee, our_max_fee + ))); } // The proposed fee is in our acceptable range, accept it and broadcast! propose_fee!(msg.fee_satoshis); @@ -11265,7 +11464,10 @@ where } else if last_fee < our_max_fee { propose_fee!(our_max_fee); } else { - return Err(ChannelError::close(format!("Unable to come to consensus about closing feerate, remote wants something ({} sat) higher than our max fee ({} sat)", msg.fee_satoshis, our_max_fee))); + return Err(ChannelError::close(format!( + "Unable to come to consensus about closing feerate, remote wants something ({} sat) higher than our max fee ({} sat)", + msg.fee_satoshis, our_max_fee + ))); } } else { if msg.fee_satoshis > our_min_fee { @@ -11273,7 +11475,10 @@ where } else if last_fee > our_min_fee { propose_fee!(our_min_fee); } else { - return Err(ChannelError::close(format!("Unable to come to consensus about closing feerate, remote wants something ({} sat) lower than our min fee ({} sat)", msg.fee_satoshis, our_min_fee))); + return Err(ChannelError::close(format!( + "Unable to come to consensus about closing feerate, remote wants something ({} sat) lower than our min fee ({} sat)", + msg.fee_satoshis, our_min_fee + ))); } } } else { @@ -12644,13 +12849,13 @@ where let our_funding_contribution = contribution.net_value(); let unsigned_contribution = our_funding_contribution.unsigned_abs(); - if let Err(e) = self.get_next_splice_out_maximum(&self.funding) - .and_then(|splice_max| splice_max - .to_sat() - .checked_add_signed(our_funding_contribution.to_sat()) - .ok_or(format!("Our splice-out value of {unsigned_contribution} is greater than the maximum {splice_max}")) + if let Err(e) = self.get_next_splice_out_maximum(&self.funding).and_then(|splice_max| { + splice_max.to_sat().checked_add_signed(our_funding_contribution.to_sat()).ok_or( + format!( + "Our splice-out value of {unsigned_contribution} is greater than the maximum {splice_max}" + ), ) - { + }) { log_error!(logger, "Channel {} cannot be funded: {}", self.context.channel_id(), e); return Err(QuiescentError::FailSplice(self.splice_funding_failed_for(contribution))); } @@ -13754,7 +13959,11 @@ where None }; if let Some(state) = new_state { - log_trace!(logger, " ...promoting inbound AwaitingRemoteRevokeToAnnounce {} to AwaitingAnnouncedRemoteRevoke", &htlc.payment_hash); + log_trace!( + logger, + " ...promoting inbound AwaitingRemoteRevokeToAnnounce {} to AwaitingAnnouncedRemoteRevoke", + &htlc.payment_hash + ); htlc.state = state; } } @@ -13762,7 +13971,11 @@ where if let &mut OutboundHTLCState::AwaitingRemoteRevokeToRemove(ref mut outcome) = &mut htlc.state { - log_trace!(logger, " ...promoting outbound AwaitingRemoteRevokeToRemove {} to AwaitingRemovedRemoteRevoke", &htlc.payment_hash); + log_trace!( + logger, + " ...promoting outbound AwaitingRemoteRevokeToRemove {} to AwaitingRemovedRemoteRevoke", + &htlc.payment_hash + ); // Swap against a dummy variant to avoid a potentially expensive clone of `OutboundHTLCOutcome::Failure(HTLCFailReason)` let mut reason = OutboundHTLCOutcome::Success { preimage: PaymentPreimage([0u8; 32]), @@ -13775,7 +13988,11 @@ where if let Some((feerate, update_state)) = self.context.pending_update_fee { if update_state == FeeUpdateState::AwaitingRemoteRevokeToAnnounce { debug_assert!(!self.funding.is_outbound()); - log_trace!(logger, " ...promoting inbound AwaitingRemoteRevokeToAnnounce fee update {} to Committed", feerate); + log_trace!( + logger, + " ...promoting inbound AwaitingRemoteRevokeToAnnounce fee update {} to Committed", + feerate + ); self.context.feerate_per_kw = feerate; self.context.pending_update_fee = None; } @@ -14063,7 +14280,7 @@ where Err(_) => { return Err(APIError::ChannelUnavailable { err: "Failed to get shutdown scriptpubkey".to_owned(), - }) + }); }, } }, @@ -15392,12 +15609,26 @@ impl PendingV2Channel { /// [`msgs::AcceptChannelV2`]: crate::ln::msgs::AcceptChannelV2 #[allow(dead_code)] // TODO(dual_funding): Remove once V2 channels is enabled. fn generate_accept_channel_v2_message(&self) -> msgs::AcceptChannelV2 { - let first_per_commitment_point = self.context.holder_signer.get_per_commitment_point( - self.unfunded_context.transaction_number(), &self.context.secp_ctx) - .expect("TODO: async signing is not yet supported for commitment points in v2 channel establishment"); - let second_per_commitment_point = self.context.holder_signer.get_per_commitment_point( - self.unfunded_context.transaction_number() - 1, &self.context.secp_ctx) - .expect("TODO: async signing is not yet supported for commitment points in v2 channel establishment"); + let first_per_commitment_point = self + .context + .holder_signer + .get_per_commitment_point( + self.unfunded_context.transaction_number(), + &self.context.secp_ctx, + ) + .expect( + "TODO: async signing is not yet supported for commitment points in v2 channel establishment", + ); + let second_per_commitment_point = self + .context + .holder_signer + .get_per_commitment_point( + self.unfunded_context.transaction_number() - 1, + &self.context.secp_ctx, + ) + .expect( + "TODO: async signing is not yet supported for commitment points in v2 channel establishment", + ); let keys = self.funding.get_holder_pubkeys(); msgs::AcceptChannelV2 { @@ -16460,12 +16691,12 @@ impl<'a, 'b, 'c, ES: EntropySource, SP: SignerProvider> for htlc in pending_outbound_htlcs.iter_mut() { match &mut htlc.state { OutboundHTLCState::AwaitingRemoteRevokeToRemove(OutboundHTLCOutcome::Success { - ref mut preimage, - ref mut attribution_data, + preimage, + attribution_data, }) | OutboundHTLCState::AwaitingRemovedRemoteRevoke(OutboundHTLCOutcome::Success { - ref mut preimage, - ref mut attribution_data, + preimage, + attribution_data, }) => { // This variant was initialized like this further above debug_assert_eq!(preimage, &PaymentPreimage([0u8; 32])); @@ -16521,7 +16752,7 @@ impl<'a, 'b, 'c, ES: EntropySource, SP: SignerProvider> if let Some(skimmed_fees) = holding_cell_skimmed_fees_opt { let mut iter = skimmed_fees.into_iter(); for htlc in holding_cell_htlc_updates.iter_mut() { - if let HTLCUpdateAwaitingACK::AddHTLC { ref mut skimmed_fee_msat, .. } = htlc { + if let HTLCUpdateAwaitingACK::AddHTLC { skimmed_fee_msat, .. } = htlc { *skimmed_fee_msat = iter.next().ok_or(DecodeError::InvalidValue)?; } } @@ -16543,7 +16774,7 @@ impl<'a, 'b, 'c, ES: EntropySource, SP: SignerProvider> if let Some(blinding_pts) = holding_cell_blinding_points_opt { let mut iter = blinding_pts.into_iter(); for htlc in holding_cell_htlc_updates.iter_mut() { - if let HTLCUpdateAwaitingACK::AddHTLC { ref mut blinding_point, .. } = htlc { + if let HTLCUpdateAwaitingACK::AddHTLC { blinding_point, .. } = htlc { *blinding_point = iter.next().ok_or(DecodeError::InvalidValue)?; } } @@ -16565,7 +16796,7 @@ impl<'a, 'b, 'c, ES: EntropySource, SP: SignerProvider> if let Some(held_htlcs) = holding_cell_held_htlc_flags_opt { let mut iter = held_htlcs.into_iter(); for htlc in holding_cell_htlc_updates.iter_mut() { - if let HTLCUpdateAwaitingACK::AddHTLC { ref mut hold_htlc, .. } = htlc { + if let HTLCUpdateAwaitingACK::AddHTLC { hold_htlc, .. } = htlc { *hold_htlc = iter.next().ok_or(DecodeError::InvalidValue)?; } } @@ -16589,7 +16820,7 @@ impl<'a, 'b, 'c, ES: EntropySource, SP: SignerProvider> if let Some(accountable_htlcs) = holding_cell_accountable { let mut iter = accountable_htlcs.into_iter(); for htlc in holding_cell_htlc_updates.iter_mut() { - if let HTLCUpdateAwaitingACK::AddHTLC { ref mut accountable, .. } = htlc { + if let HTLCUpdateAwaitingACK::AddHTLC { accountable, .. } = htlc { *accountable = iter.next().ok_or(DecodeError::InvalidValue)?; } } @@ -16612,10 +16843,10 @@ impl<'a, 'b, 'c, ES: EntropySource, SP: SignerProvider> let mut removed_htlcs = pending_inbound_htlcs.iter_mut().filter_map(|status| { if let InboundHTLCState::LocalRemoved(reason) = &mut status.state { match reason { - InboundHTLCRemovalReason::FailRelay(ref mut packet) => { + InboundHTLCRemovalReason::FailRelay(packet) => { Some(&mut packet.attribution_data) }, - InboundHTLCRemovalReason::Fulfill { ref mut attribution_data, .. } => { + InboundHTLCRemovalReason::Fulfill { attribution_data, .. } => { Some(attribution_data) }, _ => None, @@ -16637,7 +16868,7 @@ impl<'a, 'b, 'c, ES: EntropySource, SP: SignerProvider> let mut holding_cell_htlcs = holding_cell_htlc_updates.iter_mut().filter_map(|upd| match upd { HTLCUpdateAwaitingACK::FailHTLC { - err_packet: OnionErrorPacket { ref mut attribution_data, .. }, + err_packet: OnionErrorPacket { attribution_data, .. }, .. } => Some(attribution_data), HTLCUpdateAwaitingACK::ClaimHTLC { attribution_data, .. } => { @@ -16704,24 +16935,32 @@ impl<'a, 'b, 'c, ES: EntropySource, SP: SignerProvider> if holder_commitment_next_transaction_number > INITIAL_COMMITMENT_NUMBER - 3 { None } else { - Some(holder_signer - .get_per_commitment_point( - holder_commitment_next_transaction_number + 3, - &secp_ctx, + Some( + holder_signer + .get_per_commitment_point( + holder_commitment_next_transaction_number + 3, + &secp_ctx, + ) + .expect( + "Must be able to derive the previous revoked commitment point upon channel restoration", + ), ) - .expect("Must be able to derive the previous revoked commitment point upon channel restoration")) } }); let last_revoked_point = holder_commitment_point_last_revoked_opt.or_else(|| { if holder_commitment_next_transaction_number > INITIAL_COMMITMENT_NUMBER - 2 { None } else { - Some(holder_signer - .get_per_commitment_point( - holder_commitment_next_transaction_number + 2, - &secp_ctx, - ) - .expect("Must be able to derive the last revoked commitment point upon channel restoration")) + Some( + holder_signer + .get_per_commitment_point( + holder_commitment_next_transaction_number + 2, + &secp_ctx, + ) + .expect( + "Must be able to derive the last revoked commitment point upon channel restoration", + ), + ) } }); @@ -16736,7 +16975,10 @@ impl<'a, 'b, 'c, ES: EntropySource, SP: SignerProvider> }, (_, _) => { let next_point = holder_signer - .get_per_commitment_point(holder_commitment_next_transaction_number, &secp_ctx) + .get_per_commitment_point( + holder_commitment_next_transaction_number, + &secp_ctx, + ) .expect( "Must be able to derive the next commitment point upon channel restoration", ); @@ -16940,20 +17182,20 @@ pub(crate) fn hold_time_since(send_timestamp: Option) -> Option { #[cfg(test)] mod tests { + use crate::chain::BlockLocator; use crate::chain::chaininterface::LowerBoundedFeeEstimator; use crate::chain::transaction::OutPoint; - use crate::chain::BlockLocator; use crate::ln::chan_utils::{self, commit_tx_fee_sat}; use crate::ln::channel::{ AwaitingChannelReadyFlags, ChannelState, FundedChannel, HTLCUpdateAwaitingACK, InboundHTLCOutput, InboundHTLCState, InboundUpdateAdd, InboundV1Channel, - OutboundHTLCOutput, OutboundHTLCState, OutboundV1Channel, WithChannelContext, - MIN_THEIR_CHAN_RESERVE_SATOSHIS, + MIN_THEIR_CHAN_RESERVE_SATOSHIS, OutboundHTLCOutput, OutboundHTLCState, OutboundV1Channel, + WithChannelContext, }; use crate::ln::channel_keys::{RevocationBasepoint, RevocationKey}; use crate::ln::channelmanager::{self, HTLCSource, PaymentId, TrustedChannelFeatures}; use crate::ln::msgs; - use crate::ln::msgs::{ChannelUpdate, UnsignedChannelUpdate, MAX_VALUE_MSAT}; + use crate::ln::msgs::{ChannelUpdate, MAX_VALUE_MSAT, UnsignedChannelUpdate}; use crate::ln::onion_utils::{AttributionData, LocalHTLCFailureReason}; use crate::ln::script::ShutdownScript; use crate::prelude::*; @@ -16975,15 +17217,15 @@ mod tests { }; use bitcoin::amount::Amount; use bitcoin::constants::ChainHash; - use bitcoin::hashes::sha256::Hash as Sha256; use bitcoin::hashes::Hash; + use bitcoin::hashes::sha256::Hash as Sha256; use bitcoin::hex::FromHex; use bitcoin::locktime::absolute::LockTime; use bitcoin::network::Network; use bitcoin::script::Builder; use bitcoin::secp256k1::ffi::Signature as FFISignature; - use bitcoin::secp256k1::{ecdsa::Signature, Secp256k1}; use bitcoin::secp256k1::{PublicKey, SecretKey}; + use bitcoin::secp256k1::{Secp256k1, ecdsa::Signature}; use bitcoin::transaction::{Transaction, TxOut, Version}; use bitcoin::{WitnessProgram, WitnessVersion}; use std::cmp; @@ -17766,9 +18008,7 @@ mod tests { 3 => { let mut dummy_add = dummy_holding_cell_add_htlc.clone(); if let HTLCUpdateAwaitingACK::AddHTLC { - ref mut blinding_point, - ref mut skimmed_fee_msat, - .. + blinding_point, skimmed_fee_msat, .. } = &mut dummy_add { *blinding_point = Some(test_utils::pubkey(42 + i)); @@ -17916,7 +18156,7 @@ mod tests { }; use crate::ln::channel::{HTLCOutputInCommitment, PredictedNextFee}; use crate::ln::channel_keys::{DelayedPaymentBasepoint, HtlcBasepoint}; - use crate::sign::{ecdsa::EcdsaChannelSigner, ChannelDerivationParameters, HTLCDescriptor}; + use crate::sign::{ChannelDerivationParameters, HTLCDescriptor, ecdsa::EcdsaChannelSigner}; use crate::sync::Arc; use crate::types::payment::PaymentPreimage; use crate::util::logger::Logger; @@ -18060,21 +18300,30 @@ mod tests { } // anchors: simple commitment tx with no HTLCs and single anchor - test_commitment_with_anchors!("30440220655bf909fb6fa81d086f1336ac72c97906dce29d1b166e305c99152d810e26e1022051f577faa46412c46707aaac46b65d50053550a66334e00a44af2706f27a8658", - "3044022007cf6b405e9c9b4f527b0ecad9d8bb661fabb8b12abf7d1c0b3ad1855db3ed490220616d5c1eeadccc63bd775a131149455d62d95a42c2a1b01cc7821fc42dce7778", - "02000000000101bef67e4e2fb9ddeeb3461973cd4c62abb35050b1add772995b820b584a488489000000000038b02b80024a010000000000002200202b1b5854183c12d3316565972c4668929d314d81c5dcdbb21cb45fe8a9a8114f10529800000000002200204adb4e2f00643db396dd120d4e7dc17625f5f2c11a40d857accc862d6b7dd80e0400473044022007cf6b405e9c9b4f527b0ecad9d8bb661fabb8b12abf7d1c0b3ad1855db3ed490220616d5c1eeadccc63bd775a131149455d62d95a42c2a1b01cc7821fc42dce7778014730440220655bf909fb6fa81d086f1336ac72c97906dce29d1b166e305c99152d810e26e1022051f577faa46412c46707aaac46b65d50053550a66334e00a44af2706f27a865801475221023da092f6980e58d2c037173180e9a465476026ee50f96695963e8efe436f54eb21030e9f7b623d2ccc7c9bd44d66d5ce21ce504c0acf6385a132cec6d3c39fa711c152ae3e195220", {}); + test_commitment_with_anchors!( + "30440220655bf909fb6fa81d086f1336ac72c97906dce29d1b166e305c99152d810e26e1022051f577faa46412c46707aaac46b65d50053550a66334e00a44af2706f27a8658", + "3044022007cf6b405e9c9b4f527b0ecad9d8bb661fabb8b12abf7d1c0b3ad1855db3ed490220616d5c1eeadccc63bd775a131149455d62d95a42c2a1b01cc7821fc42dce7778", + "02000000000101bef67e4e2fb9ddeeb3461973cd4c62abb35050b1add772995b820b584a488489000000000038b02b80024a010000000000002200202b1b5854183c12d3316565972c4668929d314d81c5dcdbb21cb45fe8a9a8114f10529800000000002200204adb4e2f00643db396dd120d4e7dc17625f5f2c11a40d857accc862d6b7dd80e0400473044022007cf6b405e9c9b4f527b0ecad9d8bb661fabb8b12abf7d1c0b3ad1855db3ed490220616d5c1eeadccc63bd775a131149455d62d95a42c2a1b01cc7821fc42dce7778014730440220655bf909fb6fa81d086f1336ac72c97906dce29d1b166e305c99152d810e26e1022051f577faa46412c46707aaac46b65d50053550a66334e00a44af2706f27a865801475221023da092f6980e58d2c037173180e9a465476026ee50f96695963e8efe436f54eb21030e9f7b623d2ccc7c9bd44d66d5ce21ce504c0acf6385a132cec6d3c39fa711c152ae3e195220", + {} + ); // simple commitment tx with no HTLCs chan.funding.value_to_self_msat = 7000000000; - test_commitment!("3045022100c3127b33dcc741dd6b05b1e63cbd1a9a7d816f37af9b6756fa2376b056f032370220408b96279808fe57eb7e463710804cdf4f108388bc5cf722d8c848d2c7f9f3b0", - "30440220616210b2cc4d3afb601013c373bbd8aac54febd9f15400379a8cb65ce7deca60022034236c010991beb7ff770510561ae8dc885b8d38d1947248c38f2ae055647142", - "02000000000101bef67e4e2fb9ddeeb3461973cd4c62abb35050b1add772995b820b584a488489000000000038b02b8002c0c62d0000000000160014cc1b07838e387deacd0e5232e1e8b49f4c29e48454a56a00000000002200204adb4e2f00643db396dd120d4e7dc17625f5f2c11a40d857accc862d6b7dd80e04004730440220616210b2cc4d3afb601013c373bbd8aac54febd9f15400379a8cb65ce7deca60022034236c010991beb7ff770510561ae8dc885b8d38d1947248c38f2ae05564714201483045022100c3127b33dcc741dd6b05b1e63cbd1a9a7d816f37af9b6756fa2376b056f032370220408b96279808fe57eb7e463710804cdf4f108388bc5cf722d8c848d2c7f9f3b001475221023da092f6980e58d2c037173180e9a465476026ee50f96695963e8efe436f54eb21030e9f7b623d2ccc7c9bd44d66d5ce21ce504c0acf6385a132cec6d3c39fa711c152ae3e195220", {}); + test_commitment!( + "3045022100c3127b33dcc741dd6b05b1e63cbd1a9a7d816f37af9b6756fa2376b056f032370220408b96279808fe57eb7e463710804cdf4f108388bc5cf722d8c848d2c7f9f3b0", + "30440220616210b2cc4d3afb601013c373bbd8aac54febd9f15400379a8cb65ce7deca60022034236c010991beb7ff770510561ae8dc885b8d38d1947248c38f2ae055647142", + "02000000000101bef67e4e2fb9ddeeb3461973cd4c62abb35050b1add772995b820b584a488489000000000038b02b8002c0c62d0000000000160014cc1b07838e387deacd0e5232e1e8b49f4c29e48454a56a00000000002200204adb4e2f00643db396dd120d4e7dc17625f5f2c11a40d857accc862d6b7dd80e04004730440220616210b2cc4d3afb601013c373bbd8aac54febd9f15400379a8cb65ce7deca60022034236c010991beb7ff770510561ae8dc885b8d38d1947248c38f2ae05564714201483045022100c3127b33dcc741dd6b05b1e63cbd1a9a7d816f37af9b6756fa2376b056f032370220408b96279808fe57eb7e463710804cdf4f108388bc5cf722d8c848d2c7f9f3b001475221023da092f6980e58d2c037173180e9a465476026ee50f96695963e8efe436f54eb21030e9f7b623d2ccc7c9bd44d66d5ce21ce504c0acf6385a132cec6d3c39fa711c152ae3e195220", + {} + ); // anchors: simple commitment tx with no HTLCs - test_commitment_with_anchors!("3045022100f89034eba16b2be0e5581f750a0a6309192b75cce0f202f0ee2b4ec0cc394850022076c65dc507fe42276152b7a3d90e961e678adbe966e916ecfe85e64d430e75f3", - "30450221008266ac6db5ea71aac3c95d97b0e172ff596844851a3216eb88382a8dddfd33d2022050e240974cfd5d708708b4365574517c18e7ae535ef732a3484d43d0d82be9f7", - "02000000000101bef67e4e2fb9ddeeb3461973cd4c62abb35050b1add772995b820b584a488489000000000038b02b80044a010000000000002200202b1b5854183c12d3316565972c4668929d314d81c5dcdbb21cb45fe8a9a8114f4a01000000000000220020e9e86e4823faa62e222ebc858a226636856158f07e69898da3b0d1af0ddb3994c0c62d0000000000220020f3394e1e619b0eca1f91be2fb5ab4dfc59ba5b84ebe014ad1d43a564d012994a508b6a00000000002200204adb4e2f00643db396dd120d4e7dc17625f5f2c11a40d857accc862d6b7dd80e04004830450221008266ac6db5ea71aac3c95d97b0e172ff596844851a3216eb88382a8dddfd33d2022050e240974cfd5d708708b4365574517c18e7ae535ef732a3484d43d0d82be9f701483045022100f89034eba16b2be0e5581f750a0a6309192b75cce0f202f0ee2b4ec0cc394850022076c65dc507fe42276152b7a3d90e961e678adbe966e916ecfe85e64d430e75f301475221023da092f6980e58d2c037173180e9a465476026ee50f96695963e8efe436f54eb21030e9f7b623d2ccc7c9bd44d66d5ce21ce504c0acf6385a132cec6d3c39fa711c152ae3e195220", {}); + test_commitment_with_anchors!( + "3045022100f89034eba16b2be0e5581f750a0a6309192b75cce0f202f0ee2b4ec0cc394850022076c65dc507fe42276152b7a3d90e961e678adbe966e916ecfe85e64d430e75f3", + "30450221008266ac6db5ea71aac3c95d97b0e172ff596844851a3216eb88382a8dddfd33d2022050e240974cfd5d708708b4365574517c18e7ae535ef732a3484d43d0d82be9f7", + "02000000000101bef67e4e2fb9ddeeb3461973cd4c62abb35050b1add772995b820b584a488489000000000038b02b80044a010000000000002200202b1b5854183c12d3316565972c4668929d314d81c5dcdbb21cb45fe8a9a8114f4a01000000000000220020e9e86e4823faa62e222ebc858a226636856158f07e69898da3b0d1af0ddb3994c0c62d0000000000220020f3394e1e619b0eca1f91be2fb5ab4dfc59ba5b84ebe014ad1d43a564d012994a508b6a00000000002200204adb4e2f00643db396dd120d4e7dc17625f5f2c11a40d857accc862d6b7dd80e04004830450221008266ac6db5ea71aac3c95d97b0e172ff596844851a3216eb88382a8dddfd33d2022050e240974cfd5d708708b4365574517c18e7ae535ef732a3484d43d0d82be9f701483045022100f89034eba16b2be0e5581f750a0a6309192b75cce0f202f0ee2b4ec0cc394850022076c65dc507fe42276152b7a3d90e961e678adbe966e916ecfe85e64d430e75f301475221023da092f6980e58d2c037173180e9a465476026ee50f96695963e8efe436f54eb21030e9f7b623d2ccc7c9bd44d66d5ce21ce504c0acf6385a132cec6d3c39fa711c152ae3e195220", + {} + ); let payment_preimage_0 = preimage_from_hex("0000000000000000000000000000000000000000000000000000000000000000"); @@ -18460,9 +18709,12 @@ mod tests { chan.context.feerate_per_kw = 4915; chan.context.holder_dust_limit_satoshis = 546; - test_commitment!("304402203a286936e74870ca1459c700c71202af0381910a6bfab687ef494ef1bc3e02c902202506c362d0e3bee15e802aa729bf378e051644648253513f1c085b264cc2a720", - "30450221008a953551f4d67cb4df3037207fc082ddaf6be84d417b0bd14c80aab66f1b01a402207508796dc75034b2dee876fe01dc05a08b019f3e5d689ac8842ade2f1befccf5", - "02000000000101bef67e4e2fb9ddeeb3461973cd4c62abb35050b1add772995b820b584a488489000000000038b02b8002c0c62d0000000000160014cc1b07838e387deacd0e5232e1e8b49f4c29e484fa926a00000000002200204adb4e2f00643db396dd120d4e7dc17625f5f2c11a40d857accc862d6b7dd80e04004830450221008a953551f4d67cb4df3037207fc082ddaf6be84d417b0bd14c80aab66f1b01a402207508796dc75034b2dee876fe01dc05a08b019f3e5d689ac8842ade2f1befccf50147304402203a286936e74870ca1459c700c71202af0381910a6bfab687ef494ef1bc3e02c902202506c362d0e3bee15e802aa729bf378e051644648253513f1c085b264cc2a72001475221023da092f6980e58d2c037173180e9a465476026ee50f96695963e8efe436f54eb21030e9f7b623d2ccc7c9bd44d66d5ce21ce504c0acf6385a132cec6d3c39fa711c152ae3e195220", {}); + test_commitment!( + "304402203a286936e74870ca1459c700c71202af0381910a6bfab687ef494ef1bc3e02c902202506c362d0e3bee15e802aa729bf378e051644648253513f1c085b264cc2a720", + "30450221008a953551f4d67cb4df3037207fc082ddaf6be84d417b0bd14c80aab66f1b01a402207508796dc75034b2dee876fe01dc05a08b019f3e5d689ac8842ade2f1befccf5", + "02000000000101bef67e4e2fb9ddeeb3461973cd4c62abb35050b1add772995b820b584a488489000000000038b02b8002c0c62d0000000000160014cc1b07838e387deacd0e5232e1e8b49f4c29e484fa926a00000000002200204adb4e2f00643db396dd120d4e7dc17625f5f2c11a40d857accc862d6b7dd80e04004830450221008a953551f4d67cb4df3037207fc082ddaf6be84d417b0bd14c80aab66f1b01a402207508796dc75034b2dee876fe01dc05a08b019f3e5d689ac8842ade2f1befccf50147304402203a286936e74870ca1459c700c71202af0381910a6bfab687ef494ef1bc3e02c902202506c362d0e3bee15e802aa729bf378e051644648253513f1c085b264cc2a72001475221023da092f6980e58d2c037173180e9a465476026ee50f96695963e8efe436f54eb21030e9f7b623d2ccc7c9bd44d66d5ce21ce504c0acf6385a132cec6d3c39fa711c152ae3e195220", + {} + ); // anchors: commitment tx with two outputs untrimmed (minimum dust limit) chan.funding.value_to_self_msat = 6993000000; // 7000000000 - 7000000 @@ -18471,9 +18723,12 @@ mod tests { chan.funding.channel_transaction_parameters.channel_type_features = ChannelTypeFeatures::anchors_zero_htlc_fee_and_dependencies(); - test_commitment_with_anchors!("3045022100e784a66b1588575801e237d35e510fd92a81ae3a4a2a1b90c031ad803d07b3f3022021bc5f16501f167607d63b681442da193eb0a76b4b7fd25c2ed4f8b28fd35b95", - "30450221009f16ac85d232e4eddb3fcd750a68ebf0b58e3356eaada45d3513ede7e817bf4c02207c2b043b4e5f971261975406cb955219fa56bffe5d834a833694b5abc1ce4cfd", - "02000000000101bef67e4e2fb9ddeeb3461973cd4c62abb35050b1add772995b820b584a488489000000000038b02b80044a010000000000002200202b1b5854183c12d3316565972c4668929d314d81c5dcdbb21cb45fe8a9a8114f4a01000000000000220020e9e86e4823faa62e222ebc858a226636856158f07e69898da3b0d1af0ddb3994c0c62d0000000000220020f3394e1e619b0eca1f91be2fb5ab4dfc59ba5b84ebe014ad1d43a564d012994ad0886a00000000002200204adb4e2f00643db396dd120d4e7dc17625f5f2c11a40d857accc862d6b7dd80e04004830450221009f16ac85d232e4eddb3fcd750a68ebf0b58e3356eaada45d3513ede7e817bf4c02207c2b043b4e5f971261975406cb955219fa56bffe5d834a833694b5abc1ce4cfd01483045022100e784a66b1588575801e237d35e510fd92a81ae3a4a2a1b90c031ad803d07b3f3022021bc5f16501f167607d63b681442da193eb0a76b4b7fd25c2ed4f8b28fd35b9501475221023da092f6980e58d2c037173180e9a465476026ee50f96695963e8efe436f54eb21030e9f7b623d2ccc7c9bd44d66d5ce21ce504c0acf6385a132cec6d3c39fa711c152ae3e195220", {}); + test_commitment_with_anchors!( + "3045022100e784a66b1588575801e237d35e510fd92a81ae3a4a2a1b90c031ad803d07b3f3022021bc5f16501f167607d63b681442da193eb0a76b4b7fd25c2ed4f8b28fd35b95", + "30450221009f16ac85d232e4eddb3fcd750a68ebf0b58e3356eaada45d3513ede7e817bf4c02207c2b043b4e5f971261975406cb955219fa56bffe5d834a833694b5abc1ce4cfd", + "02000000000101bef67e4e2fb9ddeeb3461973cd4c62abb35050b1add772995b820b584a488489000000000038b02b80044a010000000000002200202b1b5854183c12d3316565972c4668929d314d81c5dcdbb21cb45fe8a9a8114f4a01000000000000220020e9e86e4823faa62e222ebc858a226636856158f07e69898da3b0d1af0ddb3994c0c62d0000000000220020f3394e1e619b0eca1f91be2fb5ab4dfc59ba5b84ebe014ad1d43a564d012994ad0886a00000000002200204adb4e2f00643db396dd120d4e7dc17625f5f2c11a40d857accc862d6b7dd80e04004830450221009f16ac85d232e4eddb3fcd750a68ebf0b58e3356eaada45d3513ede7e817bf4c02207c2b043b4e5f971261975406cb955219fa56bffe5d834a833694b5abc1ce4cfd01483045022100e784a66b1588575801e237d35e510fd92a81ae3a4a2a1b90c031ad803d07b3f3022021bc5f16501f167607d63b681442da193eb0a76b4b7fd25c2ed4f8b28fd35b9501475221023da092f6980e58d2c037173180e9a465476026ee50f96695963e8efe436f54eb21030e9f7b623d2ccc7c9bd44d66d5ce21ce504c0acf6385a132cec6d3c39fa711c152ae3e195220", + {} + ); // commitment tx with two outputs untrimmed (maximum feerate) chan.funding.value_to_self_msat = 6993000000; // 7000000000 - 7000000 @@ -18482,17 +18737,23 @@ mod tests { chan.funding.channel_transaction_parameters.channel_type_features = cached_channel_type.clone(); - test_commitment!("304402200a8544eba1d216f5c5e530597665fa9bec56943c0f66d98fc3d028df52d84f7002201e45fa5c6bc3a506cc2553e7d1c0043a9811313fc39c954692c0d47cfce2bbd3", - "3045022100e11b638c05c650c2f63a421d36ef8756c5ce82f2184278643520311cdf50aa200220259565fb9c8e4a87ccaf17f27a3b9ca4f20625754a0920d9c6c239d8156a11de", - "02000000000101bef67e4e2fb9ddeeb3461973cd4c62abb35050b1add772995b820b584a488489000000000038b02b800222020000000000002200204adb4e2f00643db396dd120d4e7dc17625f5f2c11a40d857accc862d6b7dd80ec0c62d0000000000160014cc1b07838e387deacd0e5232e1e8b49f4c29e4840400483045022100e11b638c05c650c2f63a421d36ef8756c5ce82f2184278643520311cdf50aa200220259565fb9c8e4a87ccaf17f27a3b9ca4f20625754a0920d9c6c239d8156a11de0147304402200a8544eba1d216f5c5e530597665fa9bec56943c0f66d98fc3d028df52d84f7002201e45fa5c6bc3a506cc2553e7d1c0043a9811313fc39c954692c0d47cfce2bbd301475221023da092f6980e58d2c037173180e9a465476026ee50f96695963e8efe436f54eb21030e9f7b623d2ccc7c9bd44d66d5ce21ce504c0acf6385a132cec6d3c39fa711c152ae3e195220", {}); + test_commitment!( + "304402200a8544eba1d216f5c5e530597665fa9bec56943c0f66d98fc3d028df52d84f7002201e45fa5c6bc3a506cc2553e7d1c0043a9811313fc39c954692c0d47cfce2bbd3", + "3045022100e11b638c05c650c2f63a421d36ef8756c5ce82f2184278643520311cdf50aa200220259565fb9c8e4a87ccaf17f27a3b9ca4f20625754a0920d9c6c239d8156a11de", + "02000000000101bef67e4e2fb9ddeeb3461973cd4c62abb35050b1add772995b820b584a488489000000000038b02b800222020000000000002200204adb4e2f00643db396dd120d4e7dc17625f5f2c11a40d857accc862d6b7dd80ec0c62d0000000000160014cc1b07838e387deacd0e5232e1e8b49f4c29e4840400483045022100e11b638c05c650c2f63a421d36ef8756c5ce82f2184278643520311cdf50aa200220259565fb9c8e4a87ccaf17f27a3b9ca4f20625754a0920d9c6c239d8156a11de0147304402200a8544eba1d216f5c5e530597665fa9bec56943c0f66d98fc3d028df52d84f7002201e45fa5c6bc3a506cc2553e7d1c0043a9811313fc39c954692c0d47cfce2bbd301475221023da092f6980e58d2c037173180e9a465476026ee50f96695963e8efe436f54eb21030e9f7b623d2ccc7c9bd44d66d5ce21ce504c0acf6385a132cec6d3c39fa711c152ae3e195220", + {} + ); // commitment tx with one output untrimmed (minimum feerate) chan.funding.value_to_self_msat = 6993000000; // 7000000000 - 7000000 chan.context.feerate_per_kw = 9651181; - test_commitment!("304402202ade0142008309eb376736575ad58d03e5b115499709c6db0b46e36ff394b492022037b63d78d66404d6504d4c4ac13be346f3d1802928a6d3ad95a6a944227161a2", - "304402207e8d51e0c570a5868a78414f4e0cbfaed1106b171b9581542c30718ee4eb95ba02203af84194c97adf98898c9afe2f2ed4a7f8dba05a2dfab28ac9d9c604aa49a379", - "02000000000101bef67e4e2fb9ddeeb3461973cd4c62abb35050b1add772995b820b584a488489000000000038b02b8001c0c62d0000000000160014cc1b07838e387deacd0e5232e1e8b49f4c29e484040047304402207e8d51e0c570a5868a78414f4e0cbfaed1106b171b9581542c30718ee4eb95ba02203af84194c97adf98898c9afe2f2ed4a7f8dba05a2dfab28ac9d9c604aa49a3790147304402202ade0142008309eb376736575ad58d03e5b115499709c6db0b46e36ff394b492022037b63d78d66404d6504d4c4ac13be346f3d1802928a6d3ad95a6a944227161a201475221023da092f6980e58d2c037173180e9a465476026ee50f96695963e8efe436f54eb21030e9f7b623d2ccc7c9bd44d66d5ce21ce504c0acf6385a132cec6d3c39fa711c152ae3e195220", {}); + test_commitment!( + "304402202ade0142008309eb376736575ad58d03e5b115499709c6db0b46e36ff394b492022037b63d78d66404d6504d4c4ac13be346f3d1802928a6d3ad95a6a944227161a2", + "304402207e8d51e0c570a5868a78414f4e0cbfaed1106b171b9581542c30718ee4eb95ba02203af84194c97adf98898c9afe2f2ed4a7f8dba05a2dfab28ac9d9c604aa49a379", + "02000000000101bef67e4e2fb9ddeeb3461973cd4c62abb35050b1add772995b820b584a488489000000000038b02b8001c0c62d0000000000160014cc1b07838e387deacd0e5232e1e8b49f4c29e484040047304402207e8d51e0c570a5868a78414f4e0cbfaed1106b171b9581542c30718ee4eb95ba02203af84194c97adf98898c9afe2f2ed4a7f8dba05a2dfab28ac9d9c604aa49a3790147304402202ade0142008309eb376736575ad58d03e5b115499709c6db0b46e36ff394b492022037b63d78d66404d6504d4c4ac13be346f3d1802928a6d3ad95a6a944227161a201475221023da092f6980e58d2c037173180e9a465476026ee50f96695963e8efe436f54eb21030e9f7b623d2ccc7c9bd44d66d5ce21ce504c0acf6385a132cec6d3c39fa711c152ae3e195220", + {} + ); // anchors: commitment tx with one output untrimmed (minimum dust limit) chan.funding.value_to_self_msat = 6993000000; // 7000000000 - 7000000 @@ -18501,9 +18762,12 @@ mod tests { chan.funding.channel_transaction_parameters.channel_type_features = ChannelTypeFeatures::anchors_zero_htlc_fee_and_dependencies(); - test_commitment_with_anchors!("30450221008fd5dbff02e4b59020d4cd23a3c30d3e287065fda75a0a09b402980adf68ccda022001e0b8b620cd915ddff11f1de32addf23d81d51b90e6841b2cb8dcaf3faa5ecf", - "30450221009ad80792e3038fe6968d12ff23e6888a565c3ddd065037f357445f01675d63f3022018384915e5f1f4ae157e15debf4f49b61c8d9d2b073c7d6f97c4a68caa3ed4c1", - "02000000000101bef67e4e2fb9ddeeb3461973cd4c62abb35050b1add772995b820b584a488489000000000038b02b80024a01000000000000220020e9e86e4823faa62e222ebc858a226636856158f07e69898da3b0d1af0ddb3994c0c62d0000000000220020f3394e1e619b0eca1f91be2fb5ab4dfc59ba5b84ebe014ad1d43a564d012994a04004830450221009ad80792e3038fe6968d12ff23e6888a565c3ddd065037f357445f01675d63f3022018384915e5f1f4ae157e15debf4f49b61c8d9d2b073c7d6f97c4a68caa3ed4c1014830450221008fd5dbff02e4b59020d4cd23a3c30d3e287065fda75a0a09b402980adf68ccda022001e0b8b620cd915ddff11f1de32addf23d81d51b90e6841b2cb8dcaf3faa5ecf01475221023da092f6980e58d2c037173180e9a465476026ee50f96695963e8efe436f54eb21030e9f7b623d2ccc7c9bd44d66d5ce21ce504c0acf6385a132cec6d3c39fa711c152ae3e195220", {}); + test_commitment_with_anchors!( + "30450221008fd5dbff02e4b59020d4cd23a3c30d3e287065fda75a0a09b402980adf68ccda022001e0b8b620cd915ddff11f1de32addf23d81d51b90e6841b2cb8dcaf3faa5ecf", + "30450221009ad80792e3038fe6968d12ff23e6888a565c3ddd065037f357445f01675d63f3022018384915e5f1f4ae157e15debf4f49b61c8d9d2b073c7d6f97c4a68caa3ed4c1", + "02000000000101bef67e4e2fb9ddeeb3461973cd4c62abb35050b1add772995b820b584a488489000000000038b02b80024a01000000000000220020e9e86e4823faa62e222ebc858a226636856158f07e69898da3b0d1af0ddb3994c0c62d0000000000220020f3394e1e619b0eca1f91be2fb5ab4dfc59ba5b84ebe014ad1d43a564d012994a04004830450221009ad80792e3038fe6968d12ff23e6888a565c3ddd065037f357445f01675d63f3022018384915e5f1f4ae157e15debf4f49b61c8d9d2b073c7d6f97c4a68caa3ed4c1014830450221008fd5dbff02e4b59020d4cd23a3c30d3e287065fda75a0a09b402980adf68ccda022001e0b8b620cd915ddff11f1de32addf23d81d51b90e6841b2cb8dcaf3faa5ecf01475221023da092f6980e58d2c037173180e9a465476026ee50f96695963e8efe436f54eb21030e9f7b623d2ccc7c9bd44d66d5ce21ce504c0acf6385a132cec6d3c39fa711c152ae3e195220", + {} + ); // commitment tx with fee greater than funder amount chan.funding.value_to_self_msat = 6993000000; // 7000000000 - 7000000 @@ -18511,9 +18775,12 @@ mod tests { chan.context.holder_dust_limit_satoshis = 546; chan.funding.channel_transaction_parameters.channel_type_features = cached_channel_type; - test_commitment!("304402202ade0142008309eb376736575ad58d03e5b115499709c6db0b46e36ff394b492022037b63d78d66404d6504d4c4ac13be346f3d1802928a6d3ad95a6a944227161a2", - "304402207e8d51e0c570a5868a78414f4e0cbfaed1106b171b9581542c30718ee4eb95ba02203af84194c97adf98898c9afe2f2ed4a7f8dba05a2dfab28ac9d9c604aa49a379", - "02000000000101bef67e4e2fb9ddeeb3461973cd4c62abb35050b1add772995b820b584a488489000000000038b02b8001c0c62d0000000000160014cc1b07838e387deacd0e5232e1e8b49f4c29e484040047304402207e8d51e0c570a5868a78414f4e0cbfaed1106b171b9581542c30718ee4eb95ba02203af84194c97adf98898c9afe2f2ed4a7f8dba05a2dfab28ac9d9c604aa49a3790147304402202ade0142008309eb376736575ad58d03e5b115499709c6db0b46e36ff394b492022037b63d78d66404d6504d4c4ac13be346f3d1802928a6d3ad95a6a944227161a201475221023da092f6980e58d2c037173180e9a465476026ee50f96695963e8efe436f54eb21030e9f7b623d2ccc7c9bd44d66d5ce21ce504c0acf6385a132cec6d3c39fa711c152ae3e195220", {}); + test_commitment!( + "304402202ade0142008309eb376736575ad58d03e5b115499709c6db0b46e36ff394b492022037b63d78d66404d6504d4c4ac13be346f3d1802928a6d3ad95a6a944227161a2", + "304402207e8d51e0c570a5868a78414f4e0cbfaed1106b171b9581542c30718ee4eb95ba02203af84194c97adf98898c9afe2f2ed4a7f8dba05a2dfab28ac9d9c604aa49a379", + "02000000000101bef67e4e2fb9ddeeb3461973cd4c62abb35050b1add772995b820b584a488489000000000038b02b8001c0c62d0000000000160014cc1b07838e387deacd0e5232e1e8b49f4c29e484040047304402207e8d51e0c570a5868a78414f4e0cbfaed1106b171b9581542c30718ee4eb95ba02203af84194c97adf98898c9afe2f2ed4a7f8dba05a2dfab28ac9d9c604aa49a3790147304402202ade0142008309eb376736575ad58d03e5b115499709c6db0b46e36ff394b492022037b63d78d66404d6504d4c4ac13be346f3d1802928a6d3ad95a6a944227161a201475221023da092f6980e58d2c037173180e9a465476026ee50f96695963e8efe436f54eb21030e9f7b623d2ccc7c9bd44d66d5ce21ce504c0acf6385a132cec6d3c39fa711c152ae3e195220", + {} + ); // commitment tx with 3 htlc outputs, 2 offered having the same amount and preimage chan.funding.value_to_self_msat = 7_000_000_000 - 2_000_000; @@ -18606,7 +18873,7 @@ mod tests { CounterpartyChannelTransactionParameters, HolderCommitmentTransaction, }; use crate::ln::channel::HTLCOutputInCommitment; - use crate::sign::{ecdsa::EcdsaChannelSigner, ChannelDerivationParameters, HTLCDescriptor}; + use crate::sign::{ChannelDerivationParameters, HTLCDescriptor, ecdsa::EcdsaChannelSigner}; use crate::sync::Arc; use crate::types::features::ChannelTypeFeatures; use crate::types::payment::PaymentPreimage; @@ -18742,7 +19009,9 @@ mod tests { test_commitment_with_zero_fee!( "3045022100a05afcdfaf045a0a7b6adb194dcda430bb8e47db8c6d1536b2a94bd98fed77ed02206d580dcd5cba42aebed39515fbd00fdd90480825ae23cce87eef1f1711e2125e", "304502210094afa18972599f7a78b06467bd11d742875baf74aa9e516a775720564671fd8e02206b9ed5f48fb92a1c19543d67f29ee3bd43afee1ec1af6f7f9b4e3371beb82162", - "03000000000101ae1e3c841378cf9e4c383bfdd033d4b3c6945e0587ff16635a00b347eea2704b0100000000340fef800300000000000000000451024e7380841e0000000000160014f2123f1a4b67887f2e5f02eda73e6327010152ea00127a0000000000220020f2d298ffcfd6d899a3abada37bfc6f42ce0b7b66f3e39e903e8419ac97dca75a0400483045022100a05afcdfaf045a0a7b6adb194dcda430bb8e47db8c6d1536b2a94bd98fed77ed02206d580dcd5cba42aebed39515fbd00fdd90480825ae23cce87eef1f1711e2125e0148304502210094afa18972599f7a78b06467bd11d742875baf74aa9e516a775720564671fd8e02206b9ed5f48fb92a1c19543d67f29ee3bd43afee1ec1af6f7f9b4e3371beb8216201475221027eb9596a68740445fb151ff37d5422e7f65f2c497c90fda63e738eb606c15bd62103bbc16dc8851bece603322f06b3c8da329401b7be7e9fdd3f3090ad19aed0807052aec50fbb20", {}); + "03000000000101ae1e3c841378cf9e4c383bfdd033d4b3c6945e0587ff16635a00b347eea2704b0100000000340fef800300000000000000000451024e7380841e0000000000160014f2123f1a4b67887f2e5f02eda73e6327010152ea00127a0000000000220020f2d298ffcfd6d899a3abada37bfc6f42ce0b7b66f3e39e903e8419ac97dca75a0400483045022100a05afcdfaf045a0a7b6adb194dcda430bb8e47db8c6d1536b2a94bd98fed77ed02206d580dcd5cba42aebed39515fbd00fdd90480825ae23cce87eef1f1711e2125e0148304502210094afa18972599f7a78b06467bd11d742875baf74aa9e516a775720564671fd8e02206b9ed5f48fb92a1c19543d67f29ee3bd43afee1ec1af6f7f9b4e3371beb8216201475221027eb9596a68740445fb151ff37d5422e7f65f2c497c90fda63e738eb606c15bd62103bbc16dc8851bece603322f06b3c8da329401b7be7e9fdd3f3090ad19aed0807052aec50fbb20", + {} + ); // Commitment transaction without HTLCs, one output trimmed below maximum anchor amount chan.context.holder_dust_limit_satoshis = 330; @@ -18750,15 +19019,19 @@ mod tests { test_commitment_with_zero_fee!( "3045022100a13c79500a9b30eba7af13418816b54aea1da0bdf41c0aa10f53a29017080d5602201a11bcc10f99c4334f778ea94e83db63d2409ff10e9e95b4260ac0dba27a490f", "30440220706abbc90e9ab70a7e1f0f28b24baf2f105e49b7a41bf3b5e694f060806fc54402206020a5e51e437c027610a59f0252ac075dfb2b8e5b45f49149e9532935ba5e7a", - "03000000000101ae1e3c841378cf9e4c383bfdd033d4b3c6945e0587ff16635a00b347eea2704b0100000000340fef8002c8000000000000000451024e73b895980000000000220020f2d298ffcfd6d899a3abada37bfc6f42ce0b7b66f3e39e903e8419ac97dca75a0400483045022100a13c79500a9b30eba7af13418816b54aea1da0bdf41c0aa10f53a29017080d5602201a11bcc10f99c4334f778ea94e83db63d2409ff10e9e95b4260ac0dba27a490f014730440220706abbc90e9ab70a7e1f0f28b24baf2f105e49b7a41bf3b5e694f060806fc54402206020a5e51e437c027610a59f0252ac075dfb2b8e5b45f49149e9532935ba5e7a01475221027eb9596a68740445fb151ff37d5422e7f65f2c497c90fda63e738eb606c15bd62103bbc16dc8851bece603322f06b3c8da329401b7be7e9fdd3f3090ad19aed0807052aec50fbb20", {}); + "03000000000101ae1e3c841378cf9e4c383bfdd033d4b3c6945e0587ff16635a00b347eea2704b0100000000340fef8002c8000000000000000451024e73b895980000000000220020f2d298ffcfd6d899a3abada37bfc6f42ce0b7b66f3e39e903e8419ac97dca75a0400483045022100a13c79500a9b30eba7af13418816b54aea1da0bdf41c0aa10f53a29017080d5602201a11bcc10f99c4334f778ea94e83db63d2409ff10e9e95b4260ac0dba27a490f014730440220706abbc90e9ab70a7e1f0f28b24baf2f105e49b7a41bf3b5e694f060806fc54402206020a5e51e437c027610a59f0252ac075dfb2b8e5b45f49149e9532935ba5e7a01475221027eb9596a68740445fb151ff37d5422e7f65f2c497c90fda63e738eb606c15bd62103bbc16dc8851bece603322f06b3c8da329401b7be7e9fdd3f3090ad19aed0807052aec50fbb20", + {} + ); // Commitment transaction without HTLCs, one output trimmed above maximum anchor amount chan.context.holder_dust_limit_satoshis = 15000; chan.funding.value_to_self_msat = 9990000000; test_commitment_with_zero_fee!( - "304402204042ce57689bb7e52af7fb9ec28d6610674ce00e5e438bb1119acfb91aad6386022065de45c4fe52d86249d80397f2c85e143550cb14b3de0cd1e6a54d0622a2bbd4", - "30450221009fb4e444e9fe2d7db0f867704745c8ea2e4e1018b5986fd8cb9d9facdc1bb1be02202d6589a20ea8a8e3594eac3c99bad523139a36e313a66c6302e619786cb42396", - "03000000000101ae1e3c841378cf9e4c383bfdd033d4b3c6945e0587ff16635a00b347eea2704b0100000000340fef8002f0000000000000000451024e73706f980000000000220020f2d298ffcfd6d899a3abada37bfc6f42ce0b7b66f3e39e903e8419ac97dca75a040047304402204042ce57689bb7e52af7fb9ec28d6610674ce00e5e438bb1119acfb91aad6386022065de45c4fe52d86249d80397f2c85e143550cb14b3de0cd1e6a54d0622a2bbd4014830450221009fb4e444e9fe2d7db0f867704745c8ea2e4e1018b5986fd8cb9d9facdc1bb1be02202d6589a20ea8a8e3594eac3c99bad523139a36e313a66c6302e619786cb4239601475221027eb9596a68740445fb151ff37d5422e7f65f2c497c90fda63e738eb606c15bd62103bbc16dc8851bece603322f06b3c8da329401b7be7e9fdd3f3090ad19aed0807052aec50fbb20", {}); + "304402204042ce57689bb7e52af7fb9ec28d6610674ce00e5e438bb1119acfb91aad6386022065de45c4fe52d86249d80397f2c85e143550cb14b3de0cd1e6a54d0622a2bbd4", + "30450221009fb4e444e9fe2d7db0f867704745c8ea2e4e1018b5986fd8cb9d9facdc1bb1be02202d6589a20ea8a8e3594eac3c99bad523139a36e313a66c6302e619786cb42396", + "03000000000101ae1e3c841378cf9e4c383bfdd033d4b3c6945e0587ff16635a00b347eea2704b0100000000340fef8002f0000000000000000451024e73706f980000000000220020f2d298ffcfd6d899a3abada37bfc6f42ce0b7b66f3e39e903e8419ac97dca75a040047304402204042ce57689bb7e52af7fb9ec28d6610674ce00e5e438bb1119acfb91aad6386022065de45c4fe52d86249d80397f2c85e143550cb14b3de0cd1e6a54d0622a2bbd4014830450221009fb4e444e9fe2d7db0f867704745c8ea2e4e1018b5986fd8cb9d9facdc1bb1be02202d6589a20ea8a8e3594eac3c99bad523139a36e313a66c6302e619786cb4239601475221027eb9596a68740445fb151ff37d5422e7f65f2c497c90fda63e738eb606c15bd62103bbc16dc8851bece603322f06b3c8da329401b7be7e9fdd3f3090ad19aed0807052aec50fbb20", + {} + ); // Commitment transaction with all HTLCs above dust limit chan.context.holder_dust_limit_satoshis = 5000; @@ -19008,7 +19281,9 @@ mod tests { test_commitment_with_zero_fee!( "3044022034f22696dd7501d65fc117af3edcfed535eb301317fe35eef08658b571fca4d0022030ff6276cff9e22968f8b08f92a1d4f2c37fe4da29de095df4841d32bdaa501b", "30450221009c820c376715329110045b3cf90f59838fd2f86b16774cb5ccccbd6a62830d9602205f2d970bef2589a5e37035937ab7db0461223e429b943b38ecf577e32b7b4572", - "03000000000101ae1e3c841378cf9e4c383bfdd033d4b3c6945e0587ff16635a00b347eea2704b0100000000340fef8003b4000000000000000451024e7344841e0000000000160014f2123f1a4b67887f2e5f02eda73e6327010152ea88117a0000000000220020f2d298ffcfd6d899a3abada37bfc6f42ce0b7b66f3e39e903e8419ac97dca75a0400473044022034f22696dd7501d65fc117af3edcfed535eb301317fe35eef08658b571fca4d0022030ff6276cff9e22968f8b08f92a1d4f2c37fe4da29de095df4841d32bdaa501b014830450221009c820c376715329110045b3cf90f59838fd2f86b16774cb5ccccbd6a62830d9602205f2d970bef2589a5e37035937ab7db0461223e429b943b38ecf577e32b7b457201475221027eb9596a68740445fb151ff37d5422e7f65f2c497c90fda63e738eb606c15bd62103bbc16dc8851bece603322f06b3c8da329401b7be7e9fdd3f3090ad19aed0807052aec50fbb20", {}); + "03000000000101ae1e3c841378cf9e4c383bfdd033d4b3c6945e0587ff16635a00b347eea2704b0100000000340fef8003b4000000000000000451024e7344841e0000000000160014f2123f1a4b67887f2e5f02eda73e6327010152ea88117a0000000000220020f2d298ffcfd6d899a3abada37bfc6f42ce0b7b66f3e39e903e8419ac97dca75a0400473044022034f22696dd7501d65fc117af3edcfed535eb301317fe35eef08658b571fca4d0022030ff6276cff9e22968f8b08f92a1d4f2c37fe4da29de095df4841d32bdaa501b014830450221009c820c376715329110045b3cf90f59838fd2f86b16774cb5ccccbd6a62830d9602205f2d970bef2589a5e37035937ab7db0461223e429b943b38ecf577e32b7b457201475221027eb9596a68740445fb151ff37d5422e7f65f2c497c90fda63e738eb606c15bd62103bbc16dc8851bece603322f06b3c8da329401b7be7e9fdd3f3090ad19aed0807052aec50fbb20", + {} + ); // Commitment transaction with millisatoshi dust HTLCs adding to less than 1 satoshi" chan.context.holder_dust_limit_satoshis = 330; @@ -19046,7 +19321,9 @@ mod tests { test_commitment_with_zero_fee!( "304402201368dc415e11647edbfc1faaaccbe4717e5fdb88c4220a0bb19969781c9f757f02203fad3a7578fcfdc428b527b97f918b639ff07941b3b42c44f58b1364fdc57177", "30440220338a338e0d477b63d2a7a00baca06c45b74bdd63d02e7d198cd8435180e9317e022014d0b95c9fde3409678417ee1a71d1d4d755f28db66a83eb10bea56de83d628d", - "03000000000101ae1e3c841378cf9e4c383bfdd033d4b3c6945e0587ff16635a00b347eea2704b0100000000340fef800334000000000000000451024e7362841e0000000000160014f2123f1a4b67887f2e5f02eda73e6327010152eaea117a0000000000220020f2d298ffcfd6d899a3abada37bfc6f42ce0b7b66f3e39e903e8419ac97dca75a040047304402201368dc415e11647edbfc1faaaccbe4717e5fdb88c4220a0bb19969781c9f757f02203fad3a7578fcfdc428b527b97f918b639ff07941b3b42c44f58b1364fdc57177014730440220338a338e0d477b63d2a7a00baca06c45b74bdd63d02e7d198cd8435180e9317e022014d0b95c9fde3409678417ee1a71d1d4d755f28db66a83eb10bea56de83d628d01475221027eb9596a68740445fb151ff37d5422e7f65f2c497c90fda63e738eb606c15bd62103bbc16dc8851bece603322f06b3c8da329401b7be7e9fdd3f3090ad19aed0807052aec50fbb20", {}); + "03000000000101ae1e3c841378cf9e4c383bfdd033d4b3c6945e0587ff16635a00b347eea2704b0100000000340fef800334000000000000000451024e7362841e0000000000160014f2123f1a4b67887f2e5f02eda73e6327010152eaea117a0000000000220020f2d298ffcfd6d899a3abada37bfc6f42ce0b7b66f3e39e903e8419ac97dca75a040047304402201368dc415e11647edbfc1faaaccbe4717e5fdb88c4220a0bb19969781c9f757f02203fad3a7578fcfdc428b527b97f918b639ff07941b3b42c44f58b1364fdc57177014730440220338a338e0d477b63d2a7a00baca06c45b74bdd63d02e7d198cd8435180e9317e022014d0b95c9fde3409678417ee1a71d1d4d755f28db66a83eb10bea56de83d628d01475221027eb9596a68740445fb151ff37d5422e7f65f2c497c90fda63e738eb606c15bd62103bbc16dc8851bece603322f06b3c8da329401b7be7e9fdd3f3090ad19aed0807052aec50fbb20", + {} + ); // Commitment transaction with millisatoshi dust HTLCs adding to 1 satoshi" chan.context.holder_dust_limit_satoshis = 330; @@ -19084,7 +19361,9 @@ mod tests { test_commitment_with_zero_fee!( "304402201368dc415e11647edbfc1faaaccbe4717e5fdb88c4220a0bb19969781c9f757f02203fad3a7578fcfdc428b527b97f918b639ff07941b3b42c44f58b1364fdc57177", "30440220338a338e0d477b63d2a7a00baca06c45b74bdd63d02e7d198cd8435180e9317e022014d0b95c9fde3409678417ee1a71d1d4d755f28db66a83eb10bea56de83d628d", - "03000000000101ae1e3c841378cf9e4c383bfdd033d4b3c6945e0587ff16635a00b347eea2704b0100000000340fef800334000000000000000451024e7362841e0000000000160014f2123f1a4b67887f2e5f02eda73e6327010152eaea117a0000000000220020f2d298ffcfd6d899a3abada37bfc6f42ce0b7b66f3e39e903e8419ac97dca75a040047304402201368dc415e11647edbfc1faaaccbe4717e5fdb88c4220a0bb19969781c9f757f02203fad3a7578fcfdc428b527b97f918b639ff07941b3b42c44f58b1364fdc57177014730440220338a338e0d477b63d2a7a00baca06c45b74bdd63d02e7d198cd8435180e9317e022014d0b95c9fde3409678417ee1a71d1d4d755f28db66a83eb10bea56de83d628d01475221027eb9596a68740445fb151ff37d5422e7f65f2c497c90fda63e738eb606c15bd62103bbc16dc8851bece603322f06b3c8da329401b7be7e9fdd3f3090ad19aed0807052aec50fbb20", {}); + "03000000000101ae1e3c841378cf9e4c383bfdd033d4b3c6945e0587ff16635a00b347eea2704b0100000000340fef800334000000000000000451024e7362841e0000000000160014f2123f1a4b67887f2e5f02eda73e6327010152eaea117a0000000000220020f2d298ffcfd6d899a3abada37bfc6f42ce0b7b66f3e39e903e8419ac97dca75a040047304402201368dc415e11647edbfc1faaaccbe4717e5fdb88c4220a0bb19969781c9f757f02203fad3a7578fcfdc428b527b97f918b639ff07941b3b42c44f58b1364fdc57177014730440220338a338e0d477b63d2a7a00baca06c45b74bdd63d02e7d198cd8435180e9317e022014d0b95c9fde3409678417ee1a71d1d4d755f28db66a83eb10bea56de83d628d01475221027eb9596a68740445fb151ff37d5422e7f65f2c497c90fda63e738eb606c15bd62103bbc16dc8851bece603322f06b3c8da329401b7be7e9fdd3f3090ad19aed0807052aec50fbb20", + {} + ); // Commitment transaction with millisatoshi dust HTLCs adding to more than 1 satoshi" chan.context.holder_dust_limit_satoshis = 330; @@ -19122,7 +19401,9 @@ mod tests { test_commitment_with_zero_fee!( "304402201368dc415e11647edbfc1faaaccbe4717e5fdb88c4220a0bb19969781c9f757f02203fad3a7578fcfdc428b527b97f918b639ff07941b3b42c44f58b1364fdc57177", "30440220338a338e0d477b63d2a7a00baca06c45b74bdd63d02e7d198cd8435180e9317e022014d0b95c9fde3409678417ee1a71d1d4d755f28db66a83eb10bea56de83d628d", - "03000000000101ae1e3c841378cf9e4c383bfdd033d4b3c6945e0587ff16635a00b347eea2704b0100000000340fef800334000000000000000451024e7362841e0000000000160014f2123f1a4b67887f2e5f02eda73e6327010152eaea117a0000000000220020f2d298ffcfd6d899a3abada37bfc6f42ce0b7b66f3e39e903e8419ac97dca75a040047304402201368dc415e11647edbfc1faaaccbe4717e5fdb88c4220a0bb19969781c9f757f02203fad3a7578fcfdc428b527b97f918b639ff07941b3b42c44f58b1364fdc57177014730440220338a338e0d477b63d2a7a00baca06c45b74bdd63d02e7d198cd8435180e9317e022014d0b95c9fde3409678417ee1a71d1d4d755f28db66a83eb10bea56de83d628d01475221027eb9596a68740445fb151ff37d5422e7f65f2c497c90fda63e738eb606c15bd62103bbc16dc8851bece603322f06b3c8da329401b7be7e9fdd3f3090ad19aed0807052aec50fbb20", {}); + "03000000000101ae1e3c841378cf9e4c383bfdd033d4b3c6945e0587ff16635a00b347eea2704b0100000000340fef800334000000000000000451024e7362841e0000000000160014f2123f1a4b67887f2e5f02eda73e6327010152eaea117a0000000000220020f2d298ffcfd6d899a3abada37bfc6f42ce0b7b66f3e39e903e8419ac97dca75a040047304402201368dc415e11647edbfc1faaaccbe4717e5fdb88c4220a0bb19969781c9f757f02203fad3a7578fcfdc428b527b97f918b639ff07941b3b42c44f58b1364fdc57177014730440220338a338e0d477b63d2a7a00baca06c45b74bdd63d02e7d198cd8435180e9317e022014d0b95c9fde3409678417ee1a71d1d4d755f28db66a83eb10bea56de83d628d01475221027eb9596a68740445fb151ff37d5422e7f65f2c497c90fda63e738eb606c15bd62103bbc16dc8851bece603322f06b3c8da329401b7be7e9fdd3f3090ad19aed0807052aec50fbb20", + {} + ); // Commitment transaction with dust HTLCs above maximum anchor amount chan.context.holder_dust_limit_satoshis = 2500; diff --git a/lightning/src/ln/channel_keys.rs b/lightning/src/ln/channel_keys.rs index d6a98e24e3a..0d7cdb5d889 100644 --- a/lightning/src/ln/channel_keys.rs +++ b/lightning/src/ln/channel_keys.rs @@ -15,9 +15,9 @@ use crate::ln::msgs::DecodeError; use crate::util::ser::Readable; use crate::util::ser::Writeable; use crate::util::ser::Writer; -use bitcoin::hashes::sha256::Hash as Sha256; use bitcoin::hashes::Hash; use bitcoin::hashes::HashEngine; +use bitcoin::hashes::sha256::Hash as Sha256; use bitcoin::secp256k1; use bitcoin::secp256k1::PublicKey; use bitcoin::secp256k1::Scalar; @@ -237,10 +237,17 @@ impl RevocationKey { Sha256::from_engine(sha).to_byte_array() }; - let countersignatory_contrib = countersignatory_basepoint.to_public_key().mul_tweak(&secp_ctx, &Scalar::from_be_bytes(rev_append_commit_hash_key).unwrap()) - .expect("Multiplying a valid public key by a hash is expected to never fail per secp256k1 docs"); - let broadcaster_contrib = (&per_commitment_point).mul_tweak(&secp_ctx, &Scalar::from_be_bytes(commit_append_rev_hash_key).unwrap()) - .expect("Multiplying a valid public key by a hash is expected to never fail per secp256k1 docs"); + let countersignatory_contrib = countersignatory_basepoint + .to_public_key() + .mul_tweak(&secp_ctx, &Scalar::from_be_bytes(rev_append_commit_hash_key).unwrap()) + .expect( + "Multiplying a valid public key by a hash is expected to never fail per secp256k1 docs", + ); + let broadcaster_contrib = (&per_commitment_point) + .mul_tweak(&secp_ctx, &Scalar::from_be_bytes(commit_append_rev_hash_key).unwrap()) + .expect( + "Multiplying a valid public key by a hash is expected to never fail per secp256k1 docs", + ); let pk = countersignatory_contrib.combine(&broadcaster_contrib) .expect("Addition only fails if the tweak is the inverse of the key. This is not possible when the tweak commits to the key."); Self(pk) diff --git a/lightning/src/ln/channel_open_tests.rs b/lightning/src/ln/channel_open_tests.rs index ac4a1b67994..36b82640888 100644 --- a/lightning/src/ln/channel_open_tests.rs +++ b/lightning/src/ln/channel_open_tests.rs @@ -15,12 +15,12 @@ use crate::chain::transaction::OutPoint; use crate::chain::{self, ChannelMonitorUpdateStatus}; use crate::events::{ClosureReason, Event, FundingInfo}; use crate::ln::channel::{ - get_holder_selected_channel_reserve_satoshis, ChannelError, InboundV1Channel, - OutboundV1Channel, COINBASE_MATURITY, UNFUNDED_CHANNEL_AGE_LIMIT_TICKS, + COINBASE_MATURITY, ChannelError, InboundV1Channel, OutboundV1Channel, + UNFUNDED_CHANNEL_AGE_LIMIT_TICKS, get_holder_selected_channel_reserve_satoshis, }; use crate::ln::channelmanager::{ - self, TrustedChannelFeatures, BREAKDOWN_TIMEOUT, MAX_UNFUNDED_CHANNEL_PEERS, - MAX_UNFUNDED_CHANS_PER_PEER, + self, BREAKDOWN_TIMEOUT, MAX_UNFUNDED_CHANNEL_PEERS, MAX_UNFUNDED_CHANS_PER_PEER, + TrustedChannelFeatures, }; use crate::ln::msgs::{ AcceptChannel, BaseMessageHandler, ChannelMessageHandler, ErrorAction, MessageSendEvent, @@ -34,6 +34,7 @@ use crate::util::config::{ use crate::util::errors::APIError; use crate::util::test_utils::{self, TestLogger}; +use bitcoin::OutPoint as BitcoinOutPoint; use bitcoin::constants::ChainHash; use bitcoin::hashes::Hash; use bitcoin::locktime::absolute::LockTime; @@ -41,7 +42,6 @@ use bitcoin::network::Network; use bitcoin::script::ScriptBuf; use bitcoin::secp256k1::{PublicKey, SecretKey}; use bitcoin::transaction::Version; -use bitcoin::OutPoint as BitcoinOutPoint; use bitcoin::{Amount, Sequence, Transaction, TxIn, TxOut, Witness}; use lightning_macros::xtest; @@ -193,7 +193,7 @@ fn test_inbound_anchors_config_overridden() { update_overrides: None, }; - let mut anchors_cfg = test_default_channel_config(); + let anchors_cfg = test_default_channel_config(); let accept_message = do_test_manual_inbound_accept_with_override(anchors_cfg, Some(overrides)); assert_eq!(accept_message.common_fields.max_htlc_value_in_flight_msat, 5_000_000); assert_eq!(accept_message.common_fields.htlc_minimum_msat, 1_000); @@ -370,7 +370,7 @@ fn test_no_channel_downgrade() { // Tests that the local node will not retry when a `option_static_remote` channel is // rejected by a peer that advertises support for the feature. let initiator_cfg = test_legacy_channel_config(); - let mut receiver_cfg = test_default_channel_config(); + let receiver_cfg = test_default_channel_config(); let chanmon_cfgs = create_chanmon_cfgs(2); let node_cfgs = create_node_cfgs(2, &chanmon_cfgs); @@ -650,7 +650,7 @@ pub fn test_funding_exceeds_no_wumbo_limit() { // them. use crate::ln::channel::MAX_FUNDING_SATOSHIS_NO_WUMBO; let chanmon_cfgs = create_chanmon_cfgs(2); - let mut node_cfgs = create_node_cfgs(2, &chanmon_cfgs); + let node_cfgs = create_node_cfgs(2, &chanmon_cfgs); let mut features = channelmanager::provided_init_features(&test_default_channel_config()); features.clear_wumbo(); *node_cfgs[1].override_init_features.borrow_mut() = Some(features); @@ -830,10 +830,12 @@ pub fn bolt2_open_channel_sending_node_checks_part1() { // Create a second channel with the same random values. This used to panic due to a colliding // channel_id, but now panics due to a colliding outbound SCID alias. - assert!(nodes[0] - .node - .create_channel(node_b_id, channel_value_satoshis, push_msat, 42, None, None) - .is_err()); + assert!( + nodes[0] + .node + .create_channel(node_b_id, channel_value_satoshis, push_msat, 42, None, None) + .is_err() + ); } #[xtest(feature = "_externalize_tests")] @@ -849,10 +851,12 @@ pub fn bolt2_open_channel_sending_node_checks_part2() { let channel_value_satoshis = 10000; // Test when push_msat is equal to 1000 * funding_satoshis. let push_msat = 1000 * channel_value_satoshis + 1; - assert!(nodes[0] - .node - .create_channel(node_b_id, channel_value_satoshis, push_msat, 42, None, None) - .is_err()); + assert!( + nodes[0] + .node + .create_channel(node_b_id, channel_value_satoshis, push_msat, 42, None, None) + .is_err() + ); nodes[0].node.create_channel(node_b_id, 100_000, 0, 42, None, None).unwrap(); @@ -944,11 +948,13 @@ pub fn test_user_configurable_csv_delay() { ) { match error { APIError::APIMisuseError { err } => { - assert!(regex::Regex::new( - r"Configured with an unreasonable our_to_self_delay \(\d+\) putting user funds at risks" - ) - .unwrap() - .is_match(err.as_str())); + assert!( + regex::Regex::new( + r"Configured with an unreasonable our_to_self_delay \(\d+\) putting user funds at risks" + ) + .unwrap() + .is_match(err.as_str()) + ); }, _ => panic!("Unexpected event"), } @@ -1291,7 +1297,7 @@ pub fn test_duplicate_temporary_channel_id_from_different_peers() { // Create an first channel channel nodes[1].node.create_channel(node_a_id, 100000, 10001, 42, None, None).unwrap(); - let mut open_chan_msg_chan_1_0 = + let open_chan_msg_chan_1_0 = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, node_a_id); // Create an second channel @@ -1443,7 +1449,7 @@ pub fn test_duplicate_chan_id() { nodes[0].node.funding_transaction_generated(temp_channel_id, node_b_id, tx.clone()).unwrap(); check_added_monitors(&nodes[0], 0); - let mut funding_created_msg = + let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, node_b_id); let channel_id = ChannelId::v1_from_funding_txid( funding_created_msg.funding_txid.as_byte_array(), @@ -1513,7 +1519,7 @@ pub fn test_duplicate_chan_id() { let chan_id = open_chan_2_msg.common_fields.temporary_channel_id; let mut channel = a_peer_state.channel_by_id.remove(&chan_id).unwrap(); - if let Some(mut chan) = channel.as_unfunded_outbound_v1_mut() { + if let Some(chan) = channel.as_unfunded_outbound_v1_mut() { let logger = test_utils::TestLogger::new(); chan.get_funding_created(tx.clone(), funding_outpoint, false, &&logger) .map_err(|_| ()) @@ -1614,8 +1620,7 @@ pub fn test_invalid_funding_tx() { // 136 bytes long. This matches our "accepted HTLC preimage spend" matching, previously causing // a panic as we'd try to extract a 32 byte preimage from a witness element without checking // its length. - let mut wit_program: Vec = - channelmonitor::deliberately_bogus_accepted_htlc_witness_program(); + let wit_program: Vec = channelmonitor::deliberately_bogus_accepted_htlc_witness_program(); let wit_program_script: ScriptBuf = wit_program.into(); for output in tx.output.iter_mut() { // Make the confirmed funding transaction have a bogus script_pubkey @@ -1674,7 +1679,7 @@ pub fn test_invalid_funding_tx() { // Now confirm a spend of the (bogus) funding transaction. As long as the witness is 5 elements // long the ChannelMonitor will try to read 32 bytes from the second-to-last element, panicing // as its not 32 bytes long. - let mut spend_tx = Transaction { + let spend_tx = Transaction { version: Version::TWO, lock_time: LockTime::ZERO, input: tx @@ -1793,7 +1798,7 @@ pub fn test_non_final_funding_tx() { witness: Witness::from_slice(&[&[1]]), }; assert_eq!(events.len(), 1); - let mut tx = match events[0] { + let tx = match events[0] { Event::FundingGenerationReady { ref channel_value_satoshis, ref output_script, .. } => { // Timelock the transaction _beyond_ the best client height + 1. Transaction { @@ -1852,7 +1857,7 @@ pub fn test_non_final_funding_tx_within_headroom() { witness: Witness::from_slice(&[[1]]), }; assert_eq!(events.len(), 1); - let mut tx = match events[0] { + let tx = match events[0] { Event::FundingGenerationReady { ref channel_value_satoshis, ref output_script, .. } => { // Timelock the transaction within a +1 headroom from the best block. Transaction { @@ -2083,7 +2088,7 @@ pub fn test_close_in_funding_batch() { // The monitor should become closed. check_added_monitors(&nodes[0], 1); { - let mut monitor_updates = nodes[0].chain_monitor.monitor_updates.lock().unwrap(); + let monitor_updates = nodes[0].chain_monitor.monitor_updates.lock().unwrap(); let monitor_updates_1 = monitor_updates.get(&channel_id_1).unwrap(); assert_eq!(monitor_updates_1.len(), 1); assert_eq!(monitor_updates_1[0].updates.len(), 1); @@ -2179,7 +2184,7 @@ pub fn test_batch_funding_close_after_funding_signed() { nodes[0].node.force_close_broadcasting_latest_txn(&channel_id_1, &node_b_id, err).unwrap(); check_added_monitors(&nodes[0], 2); { - let mut monitor_updates = nodes[0].chain_monitor.monitor_updates.lock().unwrap(); + let monitor_updates = nodes[0].chain_monitor.monitor_updates.lock().unwrap(); let monitor_updates_1 = monitor_updates.get(&channel_id_1).unwrap(); assert_eq!(monitor_updates_1.len(), 1); assert_eq!(monitor_updates_1[0].updates.len(), 1); @@ -2244,7 +2249,7 @@ pub fn test_funding_and_commitment_tx_confirm_same_block() { &node_cfgs, &[Some(min_depth_1_block_cfg.clone()), Some(min_depth_1_block_cfg)], ); - let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs); + let nodes = create_network(2, &node_cfgs, &node_chanmgrs); let node_a_id = nodes[0].node.get_our_node_id(); let node_b_id = nodes[1].node.get_our_node_id(); @@ -2478,7 +2483,10 @@ fn test_fund_pending_channel() { let pending_chan = [(&open_msg.common_fields.temporary_channel_id, &node_b_id)]; let res = nodes[0].node.batch_funding_transaction_generated(&pending_chan, tx); if let Err(APIError::APIMisuseError { err }) = res { - assert_eq!(err, "Channel f7fee84016d554015f5166c0a0df6479942ef55fd70713883b0493493a38e13a with counterparty 0355f8d2238a322d16b602bd0ceaad5b01019fb055971eaadcc9b29226a4da6c23 is not an unfunded, outbound channel ready to fund"); + assert_eq!( + err, + "Channel f7fee84016d554015f5166c0a0df6479942ef55fd70713883b0493493a38e13a with counterparty 0355f8d2238a322d16b602bd0ceaad5b01019fb055971eaadcc9b29226a4da6c23 is not an unfunded, outbound channel ready to fund" + ); } else { panic!("Unexpected result {res:?}"); } diff --git a/lightning/src/ln/channel_type_tests.rs b/lightning/src/ln/channel_type_tests.rs index 77caa8a2bc4..f2c980c8723 100644 --- a/lightning/src/ln/channel_type_tests.rs +++ b/lightning/src/ln/channel_type_tests.rs @@ -1,5 +1,5 @@ use crate::chain::chaininterface::LowerBoundedFeeEstimator; -use crate::ln::channel::{get_initial_channel_type, InboundV1Channel, OutboundV1Channel}; +use crate::ln::channel::{InboundV1Channel, OutboundV1Channel, get_initial_channel_type}; use crate::ln::channelmanager; use crate::prelude::*; use crate::util::config::UserConfig; @@ -77,7 +77,7 @@ fn test_option_zero_fee_commitments_from_zero_htlc_anchors_initial() { let mut start_features = InitFeatures::empty(); start_features.set_anchors_zero_fee_htlc_tx_optional(); - let mut start_type = ChannelTypeFeatures::anchors_zero_htlc_fee_and_dependencies(); + let start_type = ChannelTypeFeatures::anchors_zero_htlc_fee_and_dependencies(); let mut expected_type = ChannelTypeFeatures::empty(); expected_type.set_anchor_zero_fee_commitments_required(); @@ -98,7 +98,7 @@ fn test_option_zero_fee_commitments_from_zero_htlc_anchors_initial() { fn do_test_get_initial_channel_type( start_cfg: UserConfig, start_features: InitFeatures, start_type: ChannelTypeFeatures, - mut local_cfg_mod: F1, mut remote_features_mod: F2, channel_type: ChannelTypeFeatures, + local_cfg_mod: F1, remote_features_mod: F2, channel_type: ChannelTypeFeatures, ) where F1: FnOnce(&mut UserConfig), F2: FnOnce(&mut InitFeatures), diff --git a/lightning/src/ln/channelmanager.rs b/lightning/src/ln/channelmanager.rs index 64486598005..7f1bf2ebde6 100644 --- a/lightning/src/ln/channelmanager.rs +++ b/lightning/src/ln/channelmanager.rs @@ -30,22 +30,22 @@ use bitcoin::hashes::{Hash, HashEngine, HmacEngine}; use bitcoin::secp256k1::Secp256k1; use bitcoin::secp256k1::{PublicKey, SecretKey}; -use bitcoin::{secp256k1, Sequence, SignedAmount}; +use bitcoin::{Sequence, SignedAmount, secp256k1}; +use crate::blinded_path::NodeIdLookUp; use crate::blinded_path::message::{ AsyncPaymentsContext, BlindedMessagePath, MessageForwardNode, OffersContext, }; use crate::blinded_path::payment::{AsyncBolt12OfferContext, Bolt12OfferContext, PaymentContext}; -use crate::blinded_path::NodeIdLookUp; use crate::chain; use crate::chain::chaininterface::{ BroadcasterInterface, ConfirmationTarget, FeeEstimator, LowerBoundedFeeEstimator, TransactionType, }; use crate::chain::channelmonitor::{ - ChannelMonitor, ChannelMonitorUpdate, ChannelMonitorUpdateStep, MonitorEvent, - WithChannelMonitor, ANTI_REORG_DELAY, CLTV_CLAIM_BUFFER, HTLC_FAIL_BACK_BUFFER, - LATENCY_GRACE_PERIOD_BLOCKS, MAX_BLOCKS_FOR_CONF, + ANTI_REORG_DELAY, CLTV_CLAIM_BUFFER, ChannelMonitor, ChannelMonitorUpdate, + ChannelMonitorUpdateStep, HTLC_FAIL_BACK_BUFFER, LATENCY_GRACE_PERIOD_BLOCKS, + MAX_BLOCKS_FOR_CONF, MonitorEvent, WithChannelMonitor, }; use crate::chain::transaction::{OutPoint, TransactionData}; use crate::chain::{BlockLocator, ChannelMonitorUpdateStatus, Confirm, Watch}; @@ -59,10 +59,10 @@ use crate::ln::chan_utils::selected_commitment_sat_per_1000_weight; use crate::ln::channel::QuiescentAction; use crate::ln::channel::QuiescentError; use crate::ln::channel::{ - self, hold_time_since, Channel, ChannelError, ChannelUpdateStatus, DisconnectResult, - FundedChannel, FundingTxSigned, InboundV1Channel, InteractiveTxMsgError, OutboundHop, - OutboundV1Channel, PendingV2Channel, ReconnectionMsg, ShutdownResult, SpliceFundingFailed, - StfuResponse, UpdateFulfillCommitFetch, WithChannelContext, + self, Channel, ChannelError, ChannelUpdateStatus, DisconnectResult, FundedChannel, + FundingTxSigned, InboundV1Channel, InteractiveTxMsgError, OutboundHop, OutboundV1Channel, + PendingV2Channel, ReconnectionMsg, ShutdownResult, SpliceFundingFailed, StfuResponse, + UpdateFulfillCommitFetch, WithChannelContext, hold_time_since, }; use crate::ln::channel_state::ChannelDetails; use crate::ln::funding::{FundingContribution, FundingTemplate}; @@ -74,15 +74,15 @@ use crate::ln::msgs::{ MessageSendEvent, }; use crate::ln::onion_payment::{ - check_incoming_htlc_cltv, create_fwd_pending_htlc_info, create_recv_pending_htlc_info, - decode_incoming_update_add_htlc_onion, invalid_payment_err_data, HopConnector, InboundHTLCErr, - NextPacketDetails, + HopConnector, InboundHTLCErr, NextPacketDetails, check_incoming_htlc_cltv, + create_fwd_pending_htlc_info, create_recv_pending_htlc_info, + decode_incoming_update_add_htlc_onion, invalid_payment_err_data, }; use crate::ln::onion_utils::{self}; +use crate::ln::onion_utils::{AttributionData, process_fulfill_attribution_data}; use crate::ln::onion_utils::{ - decode_fulfill_attribution_data, HTLCFailReason, LocalHTLCFailureReason, + HTLCFailReason, LocalHTLCFailureReason, decode_fulfill_attribution_data, }; -use crate::ln::onion_utils::{process_fulfill_attribution_data, AttributionData}; use crate::ln::our_peer_storage::{EncryptedOurPeerStorage, PeerStorageMonitorHolder}; #[cfg(test)] use crate::ln::outbound_payment; @@ -159,11 +159,11 @@ use { }; use lightning_invoice::{ - Bolt11Invoice, Bolt11InvoiceDescription, CreationError, Currency, Description, - InvoiceBuilder as Bolt11InvoiceBuilder, SignOrCreationError, DEFAULT_EXPIRY_TIME, + Bolt11Invoice, Bolt11InvoiceDescription, CreationError, Currency, DEFAULT_EXPIRY_TIME, + Description, InvoiceBuilder as Bolt11InvoiceBuilder, SignOrCreationError, }; -use alloc::collections::{btree_map, BTreeMap}; +use alloc::collections::{BTreeMap, btree_map}; use crate::io; use crate::io::Read; @@ -211,7 +211,7 @@ pub enum PendingHTLCRouting { /// This could be a real on-chain SCID, an SCID alias, or some other SCID which has meaning /// to the receiving node, such as one returned from /// [`ChannelManager::get_intercept_scid`] or [`ChannelManager::get_phantom_scid`]. - short_channel_id: u64, // This should be NonZero eventually when we bump MSRV + short_channel_id: u64, /// Set if this HTLC is being forwarded within a blinded path. blinded: Option, /// The absolute CLTV of the inbound HTLC @@ -805,14 +805,13 @@ impl SentHTLCId { prev_outbound_scid_alias: hop_data.prev_outbound_scid_alias, htlc_id: hop_data.htlc_id, }, - HTLCSource::TrampolineForward { - ref outbound_payment, - .. - } => Self::TrampolineForward { + HTLCSource::TrampolineForward { outbound_payment, .. } => Self::TrampolineForward { session_priv: outbound_payment .as_ref() .map(|o| o.session_priv.secret_bytes()) - .expect("trying to identify a trampoline payment that we have no outbound_payment tracked for"), + .expect( + "trying to identify a trampoline payment that we have no outbound_payment tracked for", + ), }, HTLCSource::OutboundRoute { session_priv, .. } => { Self::OutboundRoute { session_priv: session_priv.secret_bytes() } @@ -2034,16 +2033,16 @@ pub trait AChannelManager { } impl< - M: chain::Watch, - T: BroadcasterInterface, - ES: EntropySource, - NS: NodeSigner, - SP: SignerProvider, - F: FeeEstimator, - R: Router, - MR: MessageRouter, - L: Logger, - > AChannelManager for ChannelManager + M: chain::Watch, + T: BroadcasterInterface, + ES: EntropySource, + NS: NodeSigner, + SP: SignerProvider, + F: FeeEstimator, + R: Router, + MR: MessageRouter, + L: Logger, +> AChannelManager for ChannelManager { type Watch = M; type Broadcaster = T; @@ -3634,16 +3633,16 @@ impl TrustedChannelFeatures { } impl< - M: chain::Watch, - T: BroadcasterInterface, - ES: EntropySource, - NS: NodeSigner, - SP: SignerProvider, - F: FeeEstimator, - R: Router, - MR: MessageRouter, - L: Logger, - > ChannelManager + M: chain::Watch, + T: BroadcasterInterface, + ES: EntropySource, + NS: NodeSigner, + SP: SignerProvider, + F: FeeEstimator, + R: Router, + MR: MessageRouter, + L: Logger, +> ChannelManager { /// Constructs a new `ChannelManager` to hold several channels and route between them. /// @@ -3758,8 +3757,12 @@ impl< channel.context.outbound_scid_alias(), (counterparty_node_id, channel.context.channel_id()), ); - assert!(outbound_alias_insert.is_none() || outbound_alias_insert.unwrap() == (counterparty_node_id, channel.context.channel_id()), - "SCIDs should never collide - ensure you weren't behind the chain tip by a full month when creating channels"); + assert!( + outbound_alias_insert.is_none() + || outbound_alias_insert.unwrap() + == (counterparty_node_id, channel.context.channel_id()), + "SCIDs should never collide - ensure you weren't behind the chain tip by a full month when creating channels" + ); insert_short_channel_id!(short_to_chan_info, channel); } @@ -3803,7 +3806,9 @@ impl< } i += 1; if i > 1_000_000 { - panic!("Your RNG is busted or we ran out of possible outbound SCID aliases (which should never happen before we run out of memory to store channels"); + panic!( + "Your RNG is busted or we ran out of possible outbound SCID aliases (which should never happen before we run out of memory to store channels" + ); } } outbound_scid_alias @@ -4493,8 +4498,9 @@ impl< if let Some(transaction) = shutdown_res.unbroadcasted_funding_tx { let funding_info = if shutdown_res.is_manual_broadcast { FundingInfo::OutPoint { - outpoint: shutdown_res.channel_funding_txo - .expect("We had an unbroadcasted funding tx, so should also have had a funding outpoint"), + outpoint: shutdown_res.channel_funding_txo.expect( + "We had an unbroadcasted funding tx, so should also have had a funding outpoint", + ), } } else { FundingInfo::Tx { transaction } @@ -5568,7 +5574,7 @@ impl< None => { return Err(APIError::ChannelUnavailable { err: "Channel to first hop is unfunded".to_owned(), - }) + }); }, }; } else { @@ -5975,11 +5981,7 @@ impl< init_features.supports_htlc_hold() && channel.context().is_live() }); - if hold_htlc_channels.is_empty() { - Err(()) - } else { - Ok(hold_htlc_channels) - } + if hold_htlc_channels.is_empty() { Err(()) } else { Ok(hold_htlc_channels) } } fn send_payment_for_static_invoice( @@ -6239,7 +6241,11 @@ impl< if first_hop.next_outbound_htlc_limit_msat < (*used_liquidity + path_value) * liquidity_limit_multiplier { - log_debug!(self.logger, "Skipped sending payment probe to avoid putting channel {} under the liquidity limit.", first_path_hop.short_channel_id); + log_debug!( + self.logger, + "Skipped sending payment probe to avoid putting channel {} under the liquidity limit.", + first_path_hop.short_channel_id + ); continue; } else { *used_liquidity += path_value; @@ -6578,13 +6584,17 @@ impl< && outp.value.to_sat() == chan.funding.get_value_satoshis() { if output_index.is_some() { - return Err("Multiple outputs matched the expected script and value"); + return Err( + "Multiple outputs matched the expected script and value", + ); } output_index = Some(idx as u16); } } if output_index.is_none() { - return Err("No output matched the script_pubkey and value in the FundingGenerationReady event"); + return Err( + "No output matched the script_pubkey and value in the FundingGenerationReady event", + ); } OutPoint { txid, index: output_index.unwrap() } }, @@ -6619,7 +6629,7 @@ impl< .map(|(chan_id, node_id, _state)| (chan_id, node_id)), ); channels_to_remove - .extend(temporary_channels.iter().map(|(&chan_id, &node_id)| (chan_id, node_id))); + .extend(temporary_channels.iter().map(|&(&chan_id, &node_id)| (chan_id, node_id))); let mut shutdown_results: Vec<(Result, _)> = Vec::new(); { let per_peer_state = self.per_peer_state.read().unwrap(); @@ -7274,10 +7284,10 @@ impl< funded_chan.context.outbound_scid_alias() } else { return Err(APIError::ChannelUnavailable { - err: format!( - "Channel with id {next_hop_channel_id} for the passed counterparty node_id {next_node_id} is still opening." - ) - }); + err: format!( + "Channel with id {next_hop_channel_id} for the passed counterparty node_id {next_node_id} is still opening." + ), + }); } }, None => { @@ -7316,7 +7326,10 @@ impl< hold_htlc, .. } => { - debug_assert!(hold_htlc.is_none(), "Held intercept HTLCs should not be surfaced in an event until the recipient comes online"); + debug_assert!( + hold_htlc.is_none(), + "Held intercept HTLCs should not be surfaced in an event until the recipient comes online" + ); PendingHTLCRouting::Forward { onion_packet, blinded, @@ -7607,7 +7620,10 @@ impl< entry.insert(pending_add); }, hash_map::Entry::Occupied(_) => { - debug_assert!(false, "Should never have two HTLCs with the same channel id and htlc id"); + debug_assert!( + false, + "Should never have two HTLCs with the same channel id and htlc id" + ); log_error!(logger, "Duplicate intercept id for HTLC"); fail_htlc_continue_to_next!( LocalHTLCFailureReason::TemporaryNodeFailure @@ -7652,7 +7668,10 @@ impl< logger, "Failed to forward incoming HTLC: detected duplicate intercepted payment", ); - debug_assert!(false, "Should never have two HTLCs with the same channel id and htlc id"); + debug_assert!( + false, + "Should never have two HTLCs with the same channel id and htlc id" + ); fail_htlc_continue_to_next!( LocalHTLCFailureReason::TemporaryNodeFailure ); @@ -7896,7 +7915,7 @@ impl< )); }; - if let PendingHTLCRouting::Forward { ref onion_packet, .. } = routing { + if let PendingHTLCRouting::Forward { onion_packet, .. } = routing { let phantom_pubkey_res = self.node_signer.get_node_id(Recipient::PhantomNode); if phantom_pubkey_res.is_ok() @@ -8081,11 +8100,13 @@ impl< .. } = payment; let (onion_packet, blinded) = match routing { - PendingHTLCRouting::Forward { ref onion_packet, blinded, .. } => { + PendingHTLCRouting::Forward { onion_packet, blinded, .. } => { (onion_packet, blinded) }, _ => { - panic!("short_channel_id != 0 should imply any pending_forward entries are of type Forward"); + panic!( + "short_channel_id != 0 should imply any pending_forward entries are of type Forward" + ); }, }; let next_blinding_point = blinded.and_then(|b| { @@ -8229,7 +8250,12 @@ impl< .and_then(Channel::as_funded_mut) { let logger = WithChannelContext::from(&self.logger, &chan.context, None); - log_trace!(logger, "Failing HTLC back to channel with short id {} (backward HTLC ID {}) after delay", short_chan_id, htlc_id); + log_trace!( + logger, + "Failing HTLC back to channel with short id {} (backward HTLC ID {}) after delay", + short_chan_id, + htlc_id + ); Some((chan.queue_fail_htlc(htlc_id, err_packet.clone(), &&logger), htlc_id)) } else { self.forwarding_channel_not_found( @@ -8249,7 +8275,12 @@ impl< .and_then(Channel::as_funded_mut) { let logger = WithChannelContext::from(&self.logger, &chan.context, None); - log_trace!(logger, "Failing malformed HTLC back to channel with short id {} (backward HTLC ID {}) after delay", short_chan_id, htlc_id); + log_trace!( + logger, + "Failing malformed HTLC back to channel with short id {} (backward HTLC ID {}) after delay", + short_chan_id, + htlc_id + ); let res = chan.queue_fail_malformed_htlc( htlc_id, failure_code, @@ -8288,7 +8319,9 @@ impl< ); } } else { - panic!("Stated return value requirements in queue_fail_{{malformed_}}htlc() were not met"); + panic!( + "Stated return value requirements in queue_fail_{{malformed_}}htlc() were not met" + ); } // fail-backs are best-effort, we probably already have one // pending, and if not that's OK, if not, the channel is on @@ -8375,7 +8408,13 @@ impl< let is_keysend = purpose.is_keysend(); if purpose != claimable_payment.purpose { let log_keysend = |keysend| if keysend { "keysend" } else { "non-keysend" }; - log_trace!(self.logger, "Failing new {} HTLC with payment_hash {} as we already had an existing {} HTLC with the same payment hash", log_keysend(is_keysend), &payment_hash, log_keysend(!is_keysend)); + log_trace!( + self.logger, + "Failing new {} HTLC with payment_hash {} as we already had an existing {} HTLC with the same payment hash", + log_keysend(is_keysend), + &payment_hash, + log_keysend(!is_keysend) + ); debug_assert!(!first_claimable_htlc); return Err(()); } @@ -8539,7 +8578,9 @@ impl< ) }, _ => { - panic!("short_channel_id == 0 should imply any pending_forward entries are of type Receive"); + panic!( + "short_channel_id == 0 should imply any pending_forward entries are of type Receive" + ); }, }; // We differentiate the received value from the sender intended value @@ -8618,7 +8659,11 @@ impl< let (payment_preimage, min_final_cltv_expiry_delta) = match verify_res { Ok(result) => result, Err(()) => { - log_trace!(self.logger, "Failing new HTLC with payment_hash {} as payment verification failed", &payment_hash); + log_trace!( + self.logger, + "Failing new HTLC with payment_hash {} as payment verification failed", + &payment_hash + ); fail_htlc!(payment_hash); }, }; @@ -8627,8 +8672,13 @@ impl< + min_final_cltv_expiry_delta as u32) as u64; if (cltv_expiry as u64) < expected_min_expiry_height { - log_trace!(self.logger, "Failing new HTLC with payment_hash {} as its CLTV expiry was too soon (had {}, earliest expected {})", - &payment_hash, cltv_expiry, expected_min_expiry_height); + log_trace!( + self.logger, + "Failing new HTLC with payment_hash {} as its CLTV expiry was too soon (had {}, earliest expected {})", + &payment_hash, + cltv_expiry, + expected_min_expiry_height + ); fail_htlc!(payment_hash); } } @@ -8722,7 +8772,12 @@ impl< }, } } else if payment_context.is_some() { - log_trace!(self.logger, "Failing new HTLC with payment_hash {}: received a keysend payment to a non-async payments context {:#?}", payment_hash, payment_context); + log_trace!( + self.logger, + "Failing new HTLC with payment_hash {}: received a keysend payment to a non-async payments context {:#?}", + payment_hash, + payment_context + ); fail_htlc!(payment_hash); } else { events::PaymentPurpose::SpontaneousPayment(keysend_preimage) @@ -8988,7 +9043,11 @@ impl< Some(*chan_id), None, ); - log_error!(logger, "Force-closing unaccepted inbound channel {} for not accepting in a timely manner", &chan_id); + log_error!( + logger, + "Force-closing unaccepted inbound channel {} for not accepting in a timely manner", + &chan_id + ); if peer_state.is_connected { peer_state.pending_msg_events.push(MessageSendEvent::HandleError { node_id: counterparty_node_id, @@ -9287,7 +9346,7 @@ impl< // from block_connected which may run during initialization prior to the chain_monitor // being fully configured. See the docs for `ChannelManagerReadArgs` for more. match source { - HTLCSource::OutboundRoute { ref path, ref session_priv, ref payment_id, .. } => { + HTLCSource::OutboundRoute { path, session_priv, payment_id, .. } => { let logger = WithContext::for_payment( &self.logger, path.hops.first().map(|hop| hop.pubkey), @@ -9328,14 +9387,14 @@ impl< } }, HTLCSource::PreviousHopData(HTLCPreviousHopData { - ref prev_outbound_scid_alias, - ref htlc_id, - ref incoming_packet_shared_secret, - ref phantom_shared_secret, - ref trampoline_shared_secret, + prev_outbound_scid_alias, + htlc_id, + incoming_packet_shared_secret, + phantom_shared_secret, + trampoline_shared_secret, outpoint: _, - ref blinded_failure, - ref channel_id, + blinded_failure, + channel_id, .. }) => { log_trace!( @@ -9399,9 +9458,16 @@ impl< .. } = current_hop_data; log_trace!( - WithContext::from(&self.logger, None, Some(*channel_id), Some(*payment_hash)), + WithContext::from( + &self.logger, + None, + Some(*channel_id), + Some(*payment_hash) + ), "Failing {}HTLC with payment_hash {} backwards from us following Trampoline forwarding failure: {:?}", - if blinded_failure.is_some() { "blinded " } else { "" }, &payment_hash, onion_error + if blinded_failure.is_some() { "blinded " } else { "" }, + &payment_hash, + onion_error ); let onion_error = HTLCFailReason::reason( LocalHTLCFailureReason::TemporaryTrampolineFailure, @@ -9530,7 +9596,10 @@ impl< if expected_amt_msat.is_some() && expected_amt_msat != htlc.mpp_part.total_value_received { - log_error!(self.logger, "Somehow ended up with an MPP payment with different received total amounts - this should not be reachable!"); + log_error!( + self.logger, + "Somehow ended up with an MPP payment with different received total amounts - this should not be reachable!" + ); debug_assert!(false); valid_mpp = false; break; @@ -9549,8 +9618,12 @@ impl< } if claimable_amt_msat != expected_amt_msat.unwrap() { self.claimable_payments.lock().unwrap().pending_claiming_payments.remove(&payment_hash); - log_info!(self.logger, "Attempted to claim an incomplete payment, expected {} msat, had {} available to claim.", - expected_amt_msat.unwrap(), claimable_amt_msat); + log_info!( + self.logger, + "Attempted to claim an incomplete payment, expected {} msat, had {} available to claim.", + expected_amt_msat.unwrap(), + claimable_amt_msat + ); return; } if valid_mpp { @@ -9789,7 +9862,8 @@ impl< ComplFunc: FnOnce( Option, bool, - ) -> (Option, Option), + ) + -> (Option, Option), >( &self, prev_hop: &HTLCPreviousHopData, payment_preimage: PaymentPreimage, payment_info: Option, attribution_data: Option, @@ -9827,7 +9901,8 @@ impl< ComplFunc: FnOnce( Option, bool, - ) -> (Option, Option), + ) + -> (Option, Option), >( &self, prev_hop: HTLCClaimSource, payment_preimage: PaymentPreimage, payment_info: Option, attribution_data: Option, @@ -9848,8 +9923,7 @@ impl< let per_peer_state = self.per_peer_state.read().unwrap(); let chan_id = prev_hop.channel_id; - const MISSING_MON_ERROR: &'static str = - "If we're going to claim an HTLC against a channel, we should always have *some* state for the channel, even if just the latest ChannelMonitor update_id. This failure indicates we need to claim an HTLC from a channel for which we did not have a ChannelMonitor at startup and didn't create one while running."; + const MISSING_MON_ERROR: &'static str = "If we're going to claim an HTLC against a channel, we should always have *some* state for the channel, even if just the latest ChannelMonitor update_id. This failure indicates we need to claim an HTLC from a channel for which we did not have a ChannelMonitor at startup and didn't create one while running."; let mut peer_state_lock = per_peer_state .get(&prev_hop.counterparty_node_id) @@ -9955,8 +10029,11 @@ impl< mem::drop(peer_state_lock); - log_trace!(logger, "Completing monitor update completion action as claim was redundant: {:?}", - action); + log_trace!( + logger, + "Completing monitor update completion action as claim was redundant: {:?}", + action + ); if let MonitorUpdateCompletionAction::FreeDuplicateClaimImmediately { downstream_counterparty_node_id: node_id, blocking_action: blocker, @@ -9992,13 +10069,17 @@ impl< action, MonitorUpdateCompletionAction::PaymentClaimed { .. } ) { - debug_assert!(during_init, - "Duplicate claims should always either be for forwarded payments(freeing another channel immediately) or during init (for claim replay)"); + debug_assert!( + during_init, + "Duplicate claims should always either be for forwarded payments(freeing another channel immediately) or during init (for claim replay)" + ); mem::drop(per_peer_state); self.handle_monitor_update_completion_actions([action]); } else { - debug_assert!(false, - "Duplicate claims should always either be for forwarded payments(freeing another channel immediately) or during init (for claim replay)"); + debug_assert!( + false, + "Duplicate claims should always either be for forwarded payments(freeing another channel immediately) or during init (for claim replay)" + ); return; }; }, @@ -10132,8 +10213,10 @@ This indicates a bug inside LDK. Please report this error at https://github.com/ HTLCSource::OutboundRoute { session_priv, payment_id, path, bolt12_invoice, .. } => { - debug_assert!(!startup_replay, - "We don't support claim_htlc claims during startup - monitors may not be available yet"); + debug_assert!( + !startup_replay, + "We don't support claim_htlc claims during startup - monitors may not be available yet" + ); debug_assert_eq!(next_channel_counterparty_node_id, path.hops[0].pubkey); let mut ev_completion_action = if from_onchain { @@ -10569,7 +10652,9 @@ This indicates a bug inside LDK. Please report this error at https://github.com/ #[cfg(not(test))] let skip_check = false; if !skip_check && !is_replay && update_completed && !in_flight_updates.is_empty() { - panic!("Watch::update_channel returned Completed while prior updates are still InProgress"); + panic!( + "Watch::update_channel returned Completed while prior updates are still InProgress" + ); } (update_completed, update_completed && in_flight_updates.is_empty()) } else { @@ -10778,7 +10863,10 @@ This indicates a bug inside LDK. Please report this error at https://github.com/ let update_actions = monitor_update_blocked_actions.remove(&chan_id).unwrap_or(Vec::new()); if chan.blocked_monitor_updates_pending() != 0 { - log_debug!(logger, "Channel has blocked monitor updates, completing update actions but leaving channel blocked"); + log_debug!( + logger, + "Channel has blocked monitor updates, completing update actions but leaving channel blocked" + ); PostMonitorUpdateChanResume::Blocked { update_actions } } else { log_debug!(logger, "Channel is open and awaiting update, resuming it"); @@ -11726,7 +11814,10 @@ This indicates a bug inside LDK. Please report this error at https://github.com/ } }, Some(Err(mut chan)) => { - let err_msg = format!("Got an unexpected funding_created message from peer with counterparty_node_id {}", counterparty_node_id); + let err_msg = format!( + "Got an unexpected funding_created message from peer with counterparty_node_id {}", + counterparty_node_id + ); let err = ChannelError::close(err_msg); return Err(self .locked_handle_force_close( @@ -11741,7 +11832,7 @@ This indicates a bug inside LDK. Please report this error at https://github.com/ return Err(MsgHandleErrInternal::no_such_channel_for_peer( counterparty_node_id, msg.temporary_channel_id, - )) + )); }, }; @@ -11797,7 +11888,10 @@ This indicates a bug inside LDK. Please report this error at https://github.com/ Ok(()) } else { let logger = WithChannelContext::from(&self.logger, &chan.context, None); - log_error!(logger, "Persisting initial ChannelMonitor failed, implying the channel ID was duplicated"); + log_error!( + logger, + "Persisting initial ChannelMonitor failed, implying the channel ID was duplicated" + ); fail_chan!("Duplicate channel ID"); } }, @@ -12514,7 +12608,10 @@ This indicates a bug inside LDK. Please report this error at https://github.com/ chan_entry.get().context(), None, ); - log_error!(logger, "Immediately closing unfunded channel as peer asked to cooperatively shut it down (which is unnecessary)"); + log_error!( + logger, + "Immediately closing unfunded channel as peer asked to cooperatively shut it down (which is unnecessary)" + ); let reason = ClosureReason::CounterpartyCoopClosedUnfundedChannel; let err = ChannelError::Close((reason.to_string(), reason)); let mut chan = chan_entry.remove(); @@ -12599,7 +12696,7 @@ This indicates a bug inside LDK. Please report this error at https://github.com/ return Err(MsgHandleErrInternal::no_such_channel_for_peer( counterparty_node_id, msg.channel_id, - )) + )); }, } }; @@ -12689,7 +12786,8 @@ This indicates a bug inside LDK. Please report this error at https://github.com/ ); let logger = WithChannelContext::from(&self.logger, &chan.context, None); for prev_hop in res.0.previous_hop_data() { - log_trace!(logger, + log_trace!( + logger, "Holding the next revoke_and_ack until the preimage is durably persisted in the inbound edge's ChannelMonitor", ); peer_state @@ -12727,7 +12825,7 @@ This indicates a bug inside LDK. Please report this error at https://github.com/ return Err(MsgHandleErrInternal::no_such_channel_for_peer( counterparty_node_id, msg.channel_id, - )) + )); }, } }; @@ -12845,7 +12943,10 @@ This indicates a bug inside LDK. Please report this error at https://github.com/ } else { let logger = WithChannelContext::from(&self.logger, &chan.context, None); - log_error!(logger, "Persisting initial ChannelMonitor failed, implying the channel ID was duplicated"); + log_error!( + logger, + "Persisting initial ChannelMonitor failed, implying the channel ID was duplicated" + ); let msg = "Channel ID was a duplicate"; let reason = ClosureReason::ProcessingError { err: msg.to_owned() }; let err = ChannelError::Close((msg.to_owned(), reason)); @@ -13372,7 +13473,7 @@ This indicates a bug inside LDK. Please report this error at https://github.com/ return Err(MsgHandleErrInternal::no_such_channel_for_peer( counterparty_node_id, msg.channel_id, - )) + )); }, hash_map::Entry::Occupied(mut chan_entry) => { if self.config.read().unwrap().reject_inbound_splices { @@ -13435,7 +13536,7 @@ This indicates a bug inside LDK. Please report this error at https://github.com/ return Err(MsgHandleErrInternal::no_such_channel_for_peer( counterparty_node_id, msg.channel_id, - )) + )); }, hash_map::Entry::Occupied(mut chan_entry) => { if let Some(ref mut funded_channel) = chan_entry.get_mut().as_funded_mut() { @@ -14648,16 +14749,16 @@ macro_rules! create_refund_builder { ($self: ident, $builder: ty) => { } } impl< - M: Watch, - T: BroadcasterInterface, - ES: EntropySource, - NS: NodeSigner, - SP: SignerProvider, - F: FeeEstimator, - R: Router, - MR: MessageRouter, - L: Logger, - > ChannelManager + M: Watch, + T: BroadcasterInterface, + ES: EntropySource, + NS: NodeSigner, + SP: SignerProvider, + F: FeeEstimator, + R: Router, + MR: MessageRouter, + L: Logger, +> ChannelManager { #[cfg(not(c_bindings))] create_offer_builder!(self, OfferBuilder<'_, DerivedMetadata, secp256k1::All>); @@ -15103,17 +15204,9 @@ impl< ) -> Vec { channel_list.sort_unstable_by_key(|chan| chan.counterparty.node_id); let mut res = Vec::new(); - // TODO: When MSRV reaches 1.77 use chunk_by - let mut start = 0; - while start < channel_list.len() { - let counterparty_node_id = channel_list[start].counterparty.node_id; - let end = channel_list[start..] - .iter() - .position(|chan| chan.counterparty.node_id != counterparty_node_id) - .map(|pos| start + pos) - .unwrap_or(channel_list.len()); - - let peer_chans = &channel_list[start..end]; + for peer_chans in + channel_list.chunk_by(|a, b| a.counterparty.node_id == b.counterparty.node_id) + { if peer_chans.iter().any(|chan| chan.is_usable) && peer_chans.iter().any(|c| c.counterparty.features.supports_onion_messages()) { @@ -15128,7 +15221,6 @@ impl< .and_then(|chan| chan.get_inbound_payment_scid()), }) } - start = end; } res } @@ -15498,16 +15590,16 @@ impl< } impl< - M: chain::Watch, - T: BroadcasterInterface, - ES: EntropySource, - NS: NodeSigner, - SP: SignerProvider, - F: FeeEstimator, - R: Router, - MR: MessageRouter, - L: Logger, - > BaseMessageHandler for ChannelManager + M: chain::Watch, + T: BroadcasterInterface, + ES: EntropySource, + NS: NodeSigner, + SP: SignerProvider, + F: FeeEstimator, + R: Router, + MR: MessageRouter, + L: Logger, +> BaseMessageHandler for ChannelManager { fn provided_node_features(&self) -> NodeFeatures { provided_node_features(&self.config.read().unwrap()) @@ -15617,11 +15709,17 @@ impl< // [`ChannelManager::pending_broadcast_messages`] holds broadcast events, // not per-peer queues. &MessageSendEvent::BroadcastChannelAnnouncement { .. } => { - debug_assert!(false, "BroadcastChannelAnnouncement should be in pending_broadcast_messages"); + debug_assert!( + false, + "BroadcastChannelAnnouncement should be in pending_broadcast_messages" + ); false }, &MessageSendEvent::BroadcastChannelUpdate { .. } => { - debug_assert!(false, "BroadcastChannelUpdate should be in pending_broadcast_messages"); + debug_assert!( + false, + "BroadcastChannelUpdate should be in pending_broadcast_messages" + ); false }, &MessageSendEvent::BroadcastNodeAnnouncement { .. } => true, @@ -15884,16 +15982,16 @@ impl< } impl< - M: chain::Watch, - T: BroadcasterInterface, - ES: EntropySource, - NS: NodeSigner, - SP: SignerProvider, - F: FeeEstimator, - R: Router, - MR: MessageRouter, - L: Logger, - > EventsProvider for ChannelManager + M: chain::Watch, + T: BroadcasterInterface, + ES: EntropySource, + NS: NodeSigner, + SP: SignerProvider, + F: FeeEstimator, + R: Router, + MR: MessageRouter, + L: Logger, +> EventsProvider for ChannelManager { /// Processes events that must be periodically handled. /// @@ -15909,24 +16007,29 @@ impl< } impl< - M: chain::Watch, - T: BroadcasterInterface, - ES: EntropySource, - NS: NodeSigner, - SP: SignerProvider, - F: FeeEstimator, - R: Router, - MR: MessageRouter, - L: Logger, - > chain::Listen for ChannelManager + M: chain::Watch, + T: BroadcasterInterface, + ES: EntropySource, + NS: NodeSigner, + SP: SignerProvider, + F: FeeEstimator, + R: Router, + MR: MessageRouter, + L: Logger, +> chain::Listen for ChannelManager { fn filtered_block_connected(&self, header: &Header, txdata: &TransactionData, height: u32) { { let best_block = self.best_block.read().unwrap(); - assert_eq!(best_block.block_hash, header.prev_blockhash, - "Blocks must be connected in chain-order - the connected header must build on the last connected header"); - assert_eq!(best_block.height, height - 1, - "Blocks must be connected in chain-order - the connected block height must be one greater than the previous height"); + assert_eq!( + best_block.block_hash, header.prev_blockhash, + "Blocks must be connected in chain-order - the connected header must build on the last connected header" + ); + assert_eq!( + best_block.height, + height - 1, + "Blocks must be connected in chain-order - the connected block height must be one greater than the previous height" + ); } self.transactions_confirmed(header, txdata, height); @@ -15941,8 +16044,10 @@ impl< ); { let mut best_block = self.best_block.write().unwrap(); - assert!(best_block.height > fork_point.height, - "Blocks disconnected must indicate disconnection from the current best height, i.e. the new chain tip must be lower than the previous best height"); + assert!( + best_block.height > fork_point.height, + "Blocks disconnected must indicate disconnection from the current best height, i.e. the new chain tip must be lower than the previous best height" + ); *best_block = fork_point; } @@ -15960,16 +16065,16 @@ impl< } impl< - M: chain::Watch, - T: BroadcasterInterface, - ES: EntropySource, - NS: NodeSigner, - SP: SignerProvider, - F: FeeEstimator, - R: Router, - MR: MessageRouter, - L: Logger, - > chain::Confirm for ChannelManager + M: chain::Watch, + T: BroadcasterInterface, + ES: EntropySource, + NS: NodeSigner, + SP: SignerProvider, + F: FeeEstimator, + R: Router, + MR: MessageRouter, + L: Logger, +> chain::Confirm for ChannelManager { #[rustfmt::skip] fn transactions_confirmed(&self, header: &Header, txdata: &TransactionData, height: u32) { @@ -16123,16 +16228,16 @@ pub(super) enum FundingConfirmedMessage { } impl< - M: chain::Watch, - T: BroadcasterInterface, - ES: EntropySource, - NS: NodeSigner, - SP: SignerProvider, - F: FeeEstimator, - R: Router, - MR: MessageRouter, - L: Logger, - > ChannelManager + M: chain::Watch, + T: BroadcasterInterface, + ES: EntropySource, + NS: NodeSigner, + SP: SignerProvider, + F: FeeEstimator, + R: Router, + MR: MessageRouter, + L: Logger, +> ChannelManager { /// 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 @@ -16476,16 +16581,16 @@ impl< } impl< - M: chain::Watch, - T: BroadcasterInterface, - ES: EntropySource, - NS: NodeSigner, - SP: SignerProvider, - F: FeeEstimator, - R: Router, - MR: MessageRouter, - L: Logger, - > ChannelMessageHandler for ChannelManager + M: chain::Watch, + T: BroadcasterInterface, + ES: EntropySource, + NS: NodeSigner, + SP: SignerProvider, + F: FeeEstimator, + R: Router, + MR: MessageRouter, + L: Logger, +> ChannelMessageHandler for ChannelManager { fn handle_open_channel(&self, counterparty_node_id: PublicKey, message: &msgs::OpenChannel) { // Note that we never need to persist the updated ChannelManager for an inbound @@ -17036,16 +17141,16 @@ impl< } impl< - M: chain::Watch, - T: BroadcasterInterface, - ES: EntropySource, - NS: NodeSigner, - SP: SignerProvider, - F: FeeEstimator, - R: Router, - MR: MessageRouter, - L: Logger, - > OffersMessageHandler for ChannelManager + M: chain::Watch, + T: BroadcasterInterface, + ES: EntropySource, + NS: NodeSigner, + SP: SignerProvider, + F: FeeEstimator, + R: Router, + MR: MessageRouter, + L: Logger, +> OffersMessageHandler for ChannelManager { #[rustfmt::skip] fn handle_message( @@ -17244,16 +17349,16 @@ impl< } impl< - M: chain::Watch, - T: BroadcasterInterface, - ES: EntropySource, - NS: NodeSigner, - SP: SignerProvider, - F: FeeEstimator, - R: Router, - MR: MessageRouter, - L: Logger, - > AsyncPaymentsMessageHandler for ChannelManager + M: chain::Watch, + T: BroadcasterInterface, + ES: EntropySource, + NS: NodeSigner, + SP: SignerProvider, + F: FeeEstimator, + R: Router, + MR: MessageRouter, + L: Logger, +> AsyncPaymentsMessageHandler for ChannelManager { fn handle_offer_paths_request( &self, message: OfferPathsRequest, context: AsyncPaymentsContext, @@ -17502,16 +17607,16 @@ impl< } impl< - M: chain::Watch, - T: BroadcasterInterface, - ES: EntropySource, - NS: NodeSigner, - SP: SignerProvider, - F: FeeEstimator, - R: Router, - MR: MessageRouter, - L: Logger, - > NodeIdLookUp for ChannelManager + M: chain::Watch, + T: BroadcasterInterface, + ES: EntropySource, + NS: NodeSigner, + SP: SignerProvider, + F: FeeEstimator, + R: Router, + MR: MessageRouter, + L: Logger, +> NodeIdLookUp for ChannelManager { fn next_node_id(&self, short_channel_id: u64) -> Option { self.short_to_chan_info.read().unwrap().get(&short_channel_id).map(|(pubkey, _)| *pubkey) @@ -17891,9 +17996,9 @@ impl Writeable for HTLCSource { fn write(&self, writer: &mut W) -> Result<(), crate::io::Error> { match self { HTLCSource::OutboundRoute { - ref session_priv, - ref first_hop_htlc_msat, - ref path, + session_priv, + first_hop_htlc_msat, + path, payment_id, bolt12_invoice, } => { @@ -17910,14 +18015,14 @@ impl Writeable for HTLCSource { (7, bolt12_invoice, option), }); }, - HTLCSource::PreviousHopData(ref field) => { + HTLCSource::PreviousHopData(field) => { 1u8.write(writer)?; field.write(writer)?; }, HTLCSource::TrampolineForward { - ref previous_hop_data, + previous_hop_data, incoming_trampoline_shared_secret, - ref outbound_payment, + outbound_payment, } => { 2u8.write(writer)?; write_tlv_fields!(writer, { @@ -18029,16 +18134,16 @@ impl_writeable_tlv_based!(PendingInboundPayment, { }); impl< - M: chain::Watch, - T: BroadcasterInterface, - ES: EntropySource, - NS: NodeSigner, - SP: SignerProvider, - F: FeeEstimator, - R: Router, - MR: MessageRouter, - L: Logger, - > Writeable for ChannelManager + M: chain::Watch, + T: BroadcasterInterface, + ES: EntropySource, + NS: NodeSigner, + SP: SignerProvider, + F: FeeEstimator, + R: Router, + MR: MessageRouter, + L: Logger, +> Writeable for ChannelManager { #[rustfmt::skip] fn write(&self, writer: &mut W) -> Result<(), io::Error> { @@ -18843,17 +18948,17 @@ pub struct ChannelManagerReadArgs< } impl< - 'a, - M: chain::Watch, - T: BroadcasterInterface, - ES: EntropySource, - NS: NodeSigner, - SP: SignerProvider, - F: FeeEstimator, - R: Router, - MR: MessageRouter, - L: Logger + Clone, - > ChannelManagerReadArgs<'a, M, T, ES, NS, SP, F, R, MR, L> + 'a, + M: chain::Watch, + T: BroadcasterInterface, + ES: EntropySource, + NS: NodeSigner, + SP: SignerProvider, + F: FeeEstimator, + R: Router, + MR: MessageRouter, + L: Logger + Clone, +> ChannelManagerReadArgs<'a, M, T, ES, NS, SP, F, R, MR, L> { /// Simple utility function to create a ChannelManagerReadArgs which creates the monitor /// HashMap for you. This is primarily useful for C bindings where it is not practical to @@ -18920,17 +19025,17 @@ fn dedup_decode_update_add_htlcs( // Implement ReadableArgs for an Arc'd ChannelManager to make it a bit easier to work with the // SipmleArcChannelManager type: impl< - 'a, - M: chain::Watch, - T: BroadcasterInterface, - ES: EntropySource, - NS: NodeSigner, - SP: SignerProvider, - F: FeeEstimator, - R: Router, - MR: MessageRouter, - L: Logger + Clone, - > ReadableArgs> + 'a, + M: chain::Watch, + T: BroadcasterInterface, + ES: EntropySource, + NS: NodeSigner, + SP: SignerProvider, + F: FeeEstimator, + R: Router, + MR: MessageRouter, + L: Logger + Clone, +> ReadableArgs> for (BlockLocator, Arc>) { fn read( @@ -18943,17 +19048,17 @@ impl< } impl< - 'a, - M: chain::Watch, - T: BroadcasterInterface, - ES: EntropySource, - NS: NodeSigner, - SP: SignerProvider, - F: FeeEstimator, - R: Router, - MR: MessageRouter, - L: Logger + Clone, - > ReadableArgs> + 'a, + M: chain::Watch, + T: BroadcasterInterface, + ES: EntropySource, + NS: NodeSigner, + SP: SignerProvider, + F: FeeEstimator, + R: Router, + MR: MessageRouter, + L: Logger + Clone, +> ReadableArgs> for (BlockLocator, ChannelManager) { fn read( @@ -18976,16 +19081,16 @@ impl< } impl< - M: chain::Watch, - T: BroadcasterInterface, - ES: EntropySource, - NS: NodeSigner, - SP: SignerProvider, - F: FeeEstimator, - R: Router, - MR: MessageRouter, - L: Logger + Clone, - > ChannelManager + M: chain::Watch, + T: BroadcasterInterface, + ES: EntropySource, + NS: NodeSigner, + SP: SignerProvider, + F: FeeEstimator, + R: Router, + MR: MessageRouter, + L: Logger + Clone, +> ChannelManager { /// Constructs a `ChannelManager` from deserialized data and runtime dependencies. /// @@ -19066,30 +19171,49 @@ impl< logger, "A ChannelManager is stale compared to the current ChannelMonitor!" ); - log_error!(logger, " The channel will be force-closed and the latest commitment transaction from the ChannelMonitor broadcast."); + log_error!( + logger, + " The channel will be force-closed and the latest commitment transaction from the ChannelMonitor broadcast." + ); if channel.context.get_latest_monitor_update_id() < monitor.get_latest_update_id() { - log_error!(logger, " The ChannelMonitor is at update_id {} but the ChannelManager is at update_id {}.", - monitor.get_latest_update_id(), channel.context.get_latest_monitor_update_id()); + log_error!( + logger, + " The ChannelMonitor is at update_id {} but the ChannelManager is at update_id {}.", + monitor.get_latest_update_id(), + channel.context.get_latest_monitor_update_id() + ); } if channel.get_cur_holder_commitment_transaction_number() > monitor.get_cur_holder_commitment_number() { - log_error!(logger, " The ChannelMonitor is at holder commitment number {} but the ChannelManager is at holder commitment number {}.", - monitor.get_cur_holder_commitment_number(), channel.get_cur_holder_commitment_transaction_number()); + log_error!( + logger, + " The ChannelMonitor is at holder commitment number {} but the ChannelManager is at holder commitment number {}.", + monitor.get_cur_holder_commitment_number(), + channel.get_cur_holder_commitment_transaction_number() + ); } if channel.get_revoked_counterparty_commitment_transaction_number() > monitor.get_min_seen_secret() { - log_error!(logger, " The ChannelMonitor is at revoked counterparty transaction number {} but the ChannelManager is at revoked counterparty transaction number {}.", - monitor.get_min_seen_secret(), channel.get_revoked_counterparty_commitment_transaction_number()); + log_error!( + logger, + " The ChannelMonitor is at revoked counterparty transaction number {} but the ChannelManager is at revoked counterparty transaction number {}.", + monitor.get_min_seen_secret(), + channel.get_revoked_counterparty_commitment_transaction_number() + ); } if channel.get_cur_counterparty_commitment_transaction_number() > monitor.get_cur_counterparty_commitment_number() { - log_error!(logger, " The ChannelMonitor is at counterparty commitment transaction number {} but the ChannelManager is at counterparty commitment transaction number {}.", - monitor.get_cur_counterparty_commitment_number(), channel.get_cur_counterparty_commitment_transaction_number()); + log_error!( + logger, + " The ChannelMonitor is at counterparty commitment transaction number {} but the ChannelManager is at counterparty commitment transaction number {}.", + monitor.get_cur_counterparty_commitment_number(), + channel.get_cur_counterparty_commitment_transaction_number() + ); } let shutdown_result = channel.force_shutdown(ClosureReason::OutdatedChannelManager); @@ -19160,8 +19284,10 @@ impl< &channel.context, Some(*payment_hash), ); - log_info!(logger, - "Failing HTLC as it is missing in the ChannelMonitor but was present in the (stale) ChannelManager"); + log_info!( + logger, + "Failing HTLC as it is missing in the ChannelMonitor but was present in the (stale) ChannelManager" + ); failed_htlcs.push(( channel_htlc_source.clone(), *payment_hash, @@ -19177,9 +19303,13 @@ impl< &logger, monitor.get_latest_update_id(), ); - log_info!(logger, "Successfully loaded at update_id {} against monitor at update id {} with {} blocked updates", + log_info!( + logger, + "Successfully loaded at update_id {} against monitor at update id {} with {} blocked updates", channel.context.get_latest_monitor_update_id(), - monitor.get_latest_update_id(), channel.blocked_monitor_updates_pending()); + monitor.get_latest_update_id(), + channel.blocked_monitor_updates_pending() + ); if let Some(short_channel_id) = channel.funding.get_short_channel_id() { short_to_chan_info.insert( short_channel_id, @@ -19226,13 +19356,22 @@ impl< "Missing ChannelMonitor for channel {} needed by ChannelManager.", &channel.context.channel_id() ); - log_error!(logger, " The chain::Watch API *requires* that monitors are persisted durably before returning,"); - log_error!(logger, " client applications must ensure that ChannelMonitor data is always available and the latest to avoid funds loss!"); + log_error!( + logger, + " The chain::Watch API *requires* that monitors are persisted durably before returning," + ); + log_error!( + logger, + " client applications must ensure that ChannelMonitor data is always available and the latest to avoid funds loss!" + ); log_error!( logger, " Without the ChannelMonitor we cannot continue without risking funds." ); - log_error!(logger, " Please ensure the chain::Watch API requirements are met and file a bug report at https://github.com/lightningdevkit/rust-lightning"); + log_error!( + logger, + " Please ensure the chain::Watch API requirements are met and file a bug report at https://github.com/lightningdevkit/rust-lightning" + ); return Err(DecodeError::InvalidValue); } } @@ -19344,7 +19483,7 @@ impl< macro_rules! handle_in_flight_updates { ($counterparty_node_id: expr, $chan_in_flight_upds: expr, $monitor: expr, $peer_state: expr, $logger: expr, $channel_info_log: expr - ) => { { + ) => {{ // When all in-flight updates have completed after we were last serialized, we // need to remove them. However, we can't guarantee that the next serialization // will have happened after processing the @@ -19358,7 +19497,8 @@ impl< let num_updates_completed = $chan_in_flight_upds .iter() .filter(|update| { - max_in_flight_update_id = cmp::max(max_in_flight_update_id, update.update_id); + max_in_flight_update_id = + cmp::max(max_in_flight_update_id, update.update_id); update.update_id <= $monitor.get_latest_update_id() }) .count(); @@ -19373,40 +19513,56 @@ impl< let funding_txo = $monitor.get_funding_txo(); if all_updates_completed { - log_debug!($logger, "All monitor updates completed since the ChannelManager was last serialized"); - pending_background_events.push( - BackgroundEvent::MonitorUpdatesComplete { - counterparty_node_id: $counterparty_node_id, - channel_id: $monitor.channel_id(), - highest_update_id_completed: max_in_flight_update_id, - }); + log_debug!( + $logger, + "All monitor updates completed since the ChannelManager was last serialized" + ); + pending_background_events.push(BackgroundEvent::MonitorUpdatesComplete { + counterparty_node_id: $counterparty_node_id, + channel_id: $monitor.channel_id(), + highest_update_id_completed: max_in_flight_update_id, + }); } else { $chan_in_flight_upds.retain(|update| { let replay = update.update_id > $monitor.get_latest_update_id(); if replay { - log_debug!($logger, "Replaying ChannelMonitorUpdate {} for {}channel {}", - update.update_id, $channel_info_log, &$monitor.channel_id()); + log_debug!( + $logger, + "Replaying ChannelMonitorUpdate {} for {}channel {}", + update.update_id, + $channel_info_log, + &$monitor.channel_id() + ); pending_background_events.push( BackgroundEvent::MonitorUpdateRegeneratedOnStartup { counterparty_node_id: $counterparty_node_id, - funding_txo: funding_txo, + funding_txo, channel_id: $monitor.channel_id(), update: update.clone(), - } + }, ); } replay }); - $peer_state.closed_channel_monitor_update_ids.entry($monitor.channel_id()) + $peer_state + .closed_channel_monitor_update_ids + .entry($monitor.channel_id()) .and_modify(|v| *v = cmp::max(max_in_flight_update_id, *v)) .or_insert(max_in_flight_update_id); } - if $peer_state.in_flight_monitor_updates.insert($monitor.channel_id(), (funding_txo, $chan_in_flight_upds)).is_some() { - log_error!($logger, "Duplicate in-flight monitor update set for the same channel!"); + if $peer_state + .in_flight_monitor_updates + .insert($monitor.channel_id(), (funding_txo, $chan_in_flight_upds)) + .is_some() + { + log_error!( + $logger, + "Duplicate in-flight monitor update set for the same channel!" + ); return Err(DecodeError::InvalidValue); } max_in_flight_update_id - } } + }}; } for (counterparty_id, peer_state_mtx) in per_peer_state.iter_mut() { @@ -19442,18 +19598,37 @@ impl< > max_in_flight_update_id { // If the channel is ahead of the monitor, return DangerousValue: - log_error!(logger, "A ChannelMonitor is stale compared to the current ChannelManager! This indicates a potentially-critical violation of the chain::Watch API!"); - log_error!(logger, " The ChannelMonitor is at update_id {} with update_id through {} in-flight", - monitor.get_latest_update_id(), max_in_flight_update_id); + log_error!( + logger, + "A ChannelMonitor is stale compared to the current ChannelManager! This indicates a potentially-critical violation of the chain::Watch API!" + ); + log_error!( + logger, + " The ChannelMonitor is at update_id {} with update_id through {} in-flight", + monitor.get_latest_update_id(), + max_in_flight_update_id + ); log_error!( logger, " but the ChannelManager is at update_id {}.", funded_chan.get_latest_unblocked_monitor_update_id() ); - log_error!(logger, " The chain::Watch API *requires* that monitors are persisted durably before returning,"); - log_error!(logger, " client applications must ensure that ChannelMonitor data is always available and the latest to avoid funds loss!"); - log_error!(logger, " Without the latest ChannelMonitor we cannot continue without risking funds."); - log_error!(logger, " Please ensure the chain::Watch API requirements are met and file a bug report at https://github.com/lightningdevkit/rust-lightning"); + log_error!( + logger, + " The chain::Watch API *requires* that monitors are persisted durably before returning," + ); + log_error!( + logger, + " client applications must ensure that ChannelMonitor data is always available and the latest to avoid funds loss!" + ); + log_error!( + logger, + " Without the latest ChannelMonitor we cannot continue without risking funds." + ); + log_error!( + logger, + " Please ensure the chain::Watch API requirements are met and file a bug report at https://github.com/lightningdevkit/rust-lightning" + ); return Err(DecodeError::DangerousValue); } } else { @@ -19486,15 +19661,27 @@ impl< "closed " ); } else { - log_error!(logger, "A ChannelMonitor is missing even though we have in-flight updates for it! This indicates a potentially-critical violation of the chain::Watch API!"); + log_error!( + logger, + "A ChannelMonitor is missing even though we have in-flight updates for it! This indicates a potentially-critical violation of the chain::Watch API!" + ); log_error!(logger, " The ChannelMonitor for channel {} is missing.", channel_id); - log_error!(logger, " The chain::Watch API *requires* that monitors are persisted durably before returning,"); - log_error!(logger, " client applications must ensure that ChannelMonitor data is always available and the latest to avoid funds loss!"); + log_error!( + logger, + " The chain::Watch API *requires* that monitors are persisted durably before returning," + ); + log_error!( + logger, + " client applications must ensure that ChannelMonitor data is always available and the latest to avoid funds loss!" + ); log_error!( logger, " Without the latest ChannelMonitor we cannot continue without risking funds." ); - log_error!(logger, " Please ensure the chain::Watch API requirements are met and file a bug report at https://github.com/lightningdevkit/rust-lightning"); + log_error!( + logger, + " Please ensure the chain::Watch API requirements are met and file a bug report at https://github.com/lightningdevkit/rust-lightning" + ); log_error!(logger, " Pending in-flight updates are: {:?}", chan_in_flight_updates); return Err(DecodeError::InvalidValue); } @@ -19591,11 +19778,7 @@ impl< Err(_) => { let rand_val = std::collections::hash_map::RandomState::new().build_hasher().finish(); - if rand_val % 2 == 0 { - true - } else { - false - } + if rand_val % 2 == 0 { true } else { false } }, } }); @@ -19809,17 +19992,17 @@ impl< }; if !have_action && compl_action.is_some() { let mut peer_state = per_peer_state - .get(&counterparty_node_id) - .map(|state| state.lock().unwrap()) - .expect( - "Channels originating a preimage must have peer state", - ); + .get(&counterparty_node_id) + .map(|state| state.lock().unwrap()) + .expect( + "Channels originating a preimage must have peer state", + ); let update_id = peer_state - .closed_channel_monitor_update_ids - .get_mut(channel_id) - .expect( - "Channels originating a preimage must have a monitor", - ); + .closed_channel_monitor_update_ids + .get_mut(channel_id) + .expect( + "Channels originating a preimage must have a monitor", + ); // Note that for channels closed pre-0.1, the latest // update_id is `u64::MAX`. *update_id = update_id.saturating_add(1); @@ -19958,7 +20141,8 @@ impl< .get(&htlc.mpp_part.prev_hop.prev_outbound_scid_alias) .is_some() { - log_error!(args.logger, + log_error!( + args.logger, "We do not have the required information to claim a pending payment with payment hash {} reliably.\ As long as the channel for the inbound edge of the forward remains open, this may work okay, but we may panic at runtime!\ All HTLCs that were received by LDK 0.0.123 and prior must be resolved prior to upgrading to LDK 0.1\ @@ -19966,7 +20150,8 @@ impl< payment_hash, ); } else { - log_error!(args.logger, + log_error!( + args.logger, "We do not have the required information to claim a pending payment with payment hash {}.\ All HTLCs that were received by LDK 0.0.123 and prior must be resolved prior to upgrading to LDK 0.1", payment_hash, @@ -20069,9 +20254,11 @@ impl< } = action { if let Some(blocked_peer_state) = per_peer_state.get(blocked_node_id) { - log_trace!(logger, + log_trace!( + logger, "Holding the next revoke_and_ack from {} until the preimage is durably persisted in the inbound edge's ChannelMonitor", - blocked_channel_id); + blocked_channel_id + ); blocked_peer_state .lock() .unwrap() @@ -20091,7 +20278,10 @@ impl< .. } = action { - debug_assert!(false, "Non-event-generating channel freeing should not appear in our queue"); + debug_assert!( + false, + "Non-event-generating channel freeing should not appear in our queue" + ); } } // Note that we may have a post-update action for a channel that has no pending @@ -20448,7 +20638,11 @@ impl< let payment = claimable_payments.claimable_payments.remove(&payment_hash); mem::drop(claimable_payments); if let Some(payment) = payment { - log_info!(channel_manager.logger, "Re-claiming HTLCs with payment hash {} as we've released the preimage to a ChannelMonitor!", &payment_hash); + log_info!( + channel_manager.logger, + "Re-claiming HTLCs with payment hash {} as we've released the preimage to a ChannelMonitor!", + &payment_hash + ); let mut claimable_amt_msat = 0; let mut receiver_node_id = Some(our_network_pubkey); let phantom_shared_secret = @@ -20686,25 +20880,41 @@ fn reconcile_pending_htlcs_with_monitor( forwards.retain(|forward| { if let HTLCForwardInfo::AddHTLC(htlc_info) = forward { if pending_forward_matches_htlc(&htlc_info) { - log_info!(logger, "Removing pending to-forward HTLC with hash {} as it was forwarded to the closed channel {}", - &payment_hash, channel_id); + log_info!( + logger, + "Removing pending to-forward HTLC with hash {} as it was forwarded to the closed channel {}", + &payment_hash, + channel_id + ); false - } else { true } - } else { true } + } else { + true + } + } else { + true + } }); !forwards.is_empty() }); pending_intercepted_htlcs_legacy.retain(|intercepted_id, htlc_info| { if pending_forward_matches_htlc(&htlc_info) { - log_info!(logger, "Removing pending intercepted HTLC with hash {} as it was forwarded to the closed channel {}", - payment_hash, channel_id); + log_info!( + logger, + "Removing pending intercepted HTLC with hash {} as it was forwarded to the closed channel {}", + payment_hash, + channel_id + ); pending_events_read.retain(|(event, _)| { if let Event::HTLCIntercepted { intercept_id: ev_id, .. } = event { intercepted_id != ev_id - } else { true } + } else { + true + } }); false - } else { true } + } else { + true + } }); } @@ -20712,8 +20922,8 @@ fn reconcile_pending_htlcs_with_monitor( mod tests { use crate::events::{ClosureReason, Event, HTLCHandlingFailureType}; use crate::ln::channelmanager::{ - create_recv_pending_htlc_info, inbound_payment, InterceptId, PaymentId, - RecipientOnionFields, + InterceptId, PaymentId, RecipientOnionFields, create_recv_pending_htlc_info, + inbound_payment, }; use crate::ln::functional_test_utils::*; use crate::ln::msgs::{self, BaseMessageHandler, ChannelMessageHandler, MessageSendEvent}; @@ -20721,7 +20931,7 @@ mod tests { use crate::ln::outbound_payment::Retry; use crate::ln::types::ChannelId; use crate::prelude::*; - use crate::routing::router::{find_route, PaymentParameters, RouteParameters}; + use crate::routing::router::{PaymentParameters, RouteParameters, find_route}; use crate::sign::EntropySource; use crate::types::payment::{PaymentHash, PaymentPreimage, PaymentSecret}; use crate::util::config::{ChannelConfig, ChannelConfigUpdate}; @@ -21799,8 +22009,8 @@ mod tests { #[cfg(ldk_bench)] pub mod bench { - use crate::chain::chainmonitor::{ChainMonitor, Persist}; use crate::chain::Listen; + use crate::chain::chainmonitor::{ChainMonitor, Persist}; use crate::events::Event; use crate::ln::channelmanager::{ BlockLocator, ChainParameters, ChannelManager, PaymentHash, PaymentId, PaymentPreimage, @@ -21815,8 +22025,8 @@ pub mod bench { use crate::util::test_utils; use bitcoin::amount::Amount; - use bitcoin::hashes::sha256::Hash as Sha256; use bitcoin::hashes::Hash; + use bitcoin::hashes::sha256::Hash as Sha256; use bitcoin::locktime::absolute::LockTime; use bitcoin::transaction::Version; use bitcoin::{Transaction, TxOut}; diff --git a/lightning/src/ln/functional_test_utils.rs b/lightning/src/ln/functional_test_utils.rs index b48d76d646d..81ad8b67534 100644 --- a/lightning/src/ln/functional_test_utils.rs +++ b/lightning/src/ln/functional_test_utils.rs @@ -16,18 +16,18 @@ use crate::blinded_path::payment::{ use crate::chain::channelmonitor::{ChannelMonitor, HTLC_FAIL_BACK_BUFFER}; use crate::chain::transaction::OutPoint; use crate::chain::{BlockLocator, ChannelMonitorUpdateStatus, Confirm, Listen, Watch}; -use crate::events::bump_transaction::sync::BumpTransactionEventHandlerSync; use crate::events::bump_transaction::BumpTransactionEvent; +use crate::events::bump_transaction::sync::BumpTransactionEventHandlerSync; use crate::events::{ ClaimedHTLC, ClosureReason, Event, FundingInfo, HTLCHandlingFailureType, PaidBolt12Invoice, PathFailure, PaymentFailureReason, PaymentPurpose, }; use crate::ln::chan_utils::{ - commitment_tx_base_weight, COMMITMENT_TX_WEIGHT_PER_HTLC, TRUC_MAX_WEIGHT, + COMMITMENT_TX_WEIGHT_PER_HTLC, TRUC_MAX_WEIGHT, commitment_tx_base_weight, }; use crate::ln::channelmanager::{ - AChannelManager, ChainParameters, ChannelManager, ChannelManagerReadArgs, PaymentId, - RAACommitmentOrder, TrustedChannelFeatures, MIN_CLTV_EXPIRY_DELTA, + AChannelManager, ChainParameters, ChannelManager, ChannelManagerReadArgs, + MIN_CLTV_EXPIRY_DELTA, PaymentId, RAACommitmentOrder, TrustedChannelFeatures, }; use crate::ln::funding::{FundingContribution, FundingTxInput}; use crate::ln::msgs::{self, OpenChannel}; @@ -42,7 +42,7 @@ use crate::ln::types::ChannelId; use crate::onion_message::messenger::OnionMessenger; use crate::routing::gossip::{NetworkGraph, NetworkUpdate, P2PGossipSync}; use crate::routing::router::{self, PaymentParameters, Route, RouteParameters}; -use crate::routing::router::{compute_fees, BlindedTail, TrampolineHop}; +use crate::routing::router::{BlindedTail, TrampolineHop, compute_fees}; use crate::sign::{EntropySource, RandomBytes, ReceiveAuthKey}; use crate::types::features::ChannelTypeFeatures; use crate::types::features::InitFeatures; @@ -57,12 +57,13 @@ use crate::util::test_utils::{self, TestLogger}; use crate::util::test_utils::{TestChainMonitor, TestKeysInterface, TestScorer}; use crate::util::wallet_utils::{WalletSourceSync, WalletSync}; +use bitcoin::WPubkeyHash; use bitcoin::amount::Amount; use bitcoin::block::{Block, Header, Version as BlockVersion}; use bitcoin::hash_types::{BlockHash, TxMerkleNode}; -use bitcoin::hashes::sha256::Hash as Sha256; use bitcoin::hashes::Hash as _; -use bitcoin::locktime::absolute::{LockTime, LOCK_TIME_THRESHOLD}; +use bitcoin::hashes::sha256::Hash as Sha256; +use bitcoin::locktime::absolute::{LOCK_TIME_THRESHOLD, LockTime}; use bitcoin::network::Network; use bitcoin::policy::MAX_STANDARD_TX_WEIGHT; use bitcoin::pow::CompactTarget; @@ -70,7 +71,6 @@ use bitcoin::script::ScriptBuf; use bitcoin::secp256k1::{PublicKey, SecretKey}; use bitcoin::transaction::{self, Version as TxVersion}; use bitcoin::transaction::{Transaction, TxIn, TxOut}; -use bitcoin::WPubkeyHash; use crate::io; use crate::prelude::*; @@ -1180,7 +1180,7 @@ macro_rules! get_channel_ref { #[cfg(any(test, feature = "_externalize_tests"))] macro_rules! get_feerate { ($node: expr, $counterparty_node: expr, $channel_id: expr) => {{ - let mut per_peer_state_lock; + let per_peer_state_lock; let mut peer_state_lock; let chan = get_channel_ref!( $node, @@ -1196,7 +1196,7 @@ macro_rules! get_feerate { #[cfg(any(test, feature = "_externalize_tests"))] macro_rules! get_channel_type_features { ($node: expr, $counterparty_node: expr, $channel_id: expr) => {{ - let mut per_peer_state_lock; + let per_peer_state_lock; let mut peer_state_lock; let chan = get_channel_ref!( $node, @@ -1212,9 +1212,7 @@ macro_rules! get_channel_type_features { /// Returns a channel monitor given a channel id, making some naive assumptions #[macro_export] macro_rules! get_monitor { - ($node: expr, $channel_id: expr) => {{ - $node.chain_monitor.chain_monitor.get_monitor($channel_id).unwrap() - }}; + ($node: expr, $channel_id: expr) => {{ $node.chain_monitor.chain_monitor.get_monitor($channel_id).unwrap() }}; } /// Returns any local commitment transactions for the channel. @@ -1551,10 +1549,12 @@ pub fn sign_funding_transaction<'a, 'b, 'c>( create_funding_transaction(node_a, &node_b_id, channel_value, 42); assert_eq!(temporary_channel_id, expected_temporary_channel_id); - assert!(node_a - .node - .funding_transaction_generated(temporary_channel_id, node_b_id, tx.clone()) - .is_ok()); + assert!( + node_a + .node + .funding_transaction_generated(temporary_channel_id, node_b_id, tx.clone()) + .is_ok() + ); check_added_monitors(&node_a, 0); let funding_created_msg = @@ -1593,10 +1593,12 @@ pub fn sign_funding_transaction<'a, 'b, 'c>( node_a.tx_broadcaster.clear(); // Ensure that funding_transaction_generated is idempotent. - assert!(node_a - .node - .funding_transaction_generated(temporary_channel_id, node_b_id, tx.clone()) - .is_err()); + assert!( + node_a + .node + .funding_transaction_generated(temporary_channel_id, node_b_id, tx.clone()) + .is_err() + ); assert!(node_a.node.get_and_clear_pending_msg_events().is_empty()); check_added_monitors(&node_a, 0); @@ -2906,11 +2908,7 @@ pub fn check_payment_claimable( ) { match event { Event::PaymentClaimable { - ref payment_hash, - ref purpose, - amount_msat, - receiver_node_id, - .. + payment_hash, purpose, amount_msat, receiver_node_id, .. } => { assert_eq!(expected_payment_hash, *payment_hash); assert_eq!(expected_recv_value, *amount_msat); @@ -3442,7 +3440,7 @@ pub fn expect_payment_failed_conditions_event<'a, 'b, 'c, 'd, 'e>( }; if !conditions.expected_mpp_parts_remain && !conditions.retry_expected { match &payment_failed_events[1] { - Event::PaymentFailed { ref payment_hash, ref payment_id, ref reason } => { + Event::PaymentFailed { payment_hash, payment_id, reason } => { assert_eq!( *payment_hash, Some(expected_payment_hash), @@ -3664,11 +3662,11 @@ pub fn do_pass_along_path<'a, 'b, 'c>(args: PassAlongPathArgs) -> Option assert_eq!(events_2.len(), 1); match &events_2[0] { Event::PaymentClaimable { - ref payment_hash, - ref purpose, + payment_hash, + purpose, amount_msat, receiver_node_id, - ref receiving_channel_ids, + receiving_channel_ids, claim_deadline, onion_fields, .. @@ -5066,7 +5064,7 @@ pub fn handle_announce_close_broadcast_events<'a, 'b, 'c>( let events_2 = nodes[b].node.get_and_clear_pending_msg_events(); assert_eq!(events_2.len(), if needs_err_handle { 1 } else { 2 }); let bs_update = match events_2.last().unwrap() { - MessageSendEvent::BroadcastChannelUpdate { ref msg, .. } => msg.clone(), + MessageSendEvent::BroadcastChannelUpdate { msg, .. } => msg.clone(), _ => panic!("Unexpected event"), }; if !needs_err_handle { @@ -5206,10 +5204,9 @@ macro_rules! handle_chan_reestablish_msgs { }, &MessageSendEvent::UpdateHTLCs { ref node_id, ref channel_id, ref updates } => { assert_eq!(*node_id, $dst_node.node.get_our_node_id()); - assert!(updates - .commitment_signed - .iter() - .all(|cs| cs.channel_id == *channel_id)); + assert!( + updates.commitment_signed.iter().all(|cs| cs.channel_id == *channel_id) + ); commitment_update = Some(updates.clone()); idx += 1; RAACommitmentOrder::CommitmentFirst @@ -5231,10 +5228,9 @@ macro_rules! handle_chan_reestablish_msgs { &MessageSendEvent::UpdateHTLCs { ref node_id, ref channel_id, ref updates } => { assert_eq!(*node_id, $dst_node.node.get_our_node_id()); assert!(commitment_update.is_none()); - assert!(updates - .commitment_signed - .iter() - .all(|cs| cs.channel_id == *channel_id)); + assert!( + updates.commitment_signed.iter().all(|cs| cs.channel_id == *channel_id) + ); commitment_update = Some(updates.clone()); idx += 1; }, @@ -5735,13 +5731,15 @@ pub fn create_batch_channel_funding<'a, 'b, 'c>( input: Vec::new(), output: tx_outs, }; - assert!(funding_node - .node - .batch_funding_transaction_generated( - temp_chan_ids.iter().map(|(a, b)| (a, b)).collect::>().as_slice(), - tx.clone(), - ) - .is_ok()); + assert!( + funding_node + .node + .batch_funding_transaction_generated( + temp_chan_ids.iter().map(|(a, b)| (a, b)).collect::>().as_slice(), + tx.clone(), + ) + .is_ok() + ); check_added_monitors(&funding_node, 0); let events = funding_node.node.get_and_clear_pending_msg_events(); assert_eq!(events.len(), params.len()); diff --git a/lightning/src/ln/functional_tests.rs b/lightning/src/ln/functional_tests.rs index c8ecb40fa6d..f532c07900f 100644 --- a/lightning/src/ln/functional_tests.rs +++ b/lightning/src/ln/functional_tests.rs @@ -12,30 +12,30 @@ //! claim outputs on-chain. use crate::chain; +use crate::chain::BlockLocator; use crate::chain::chaininterface::LowerBoundedFeeEstimator; use crate::chain::channelmonitor; use crate::chain::channelmonitor::{ - Balance, ANTI_REORG_DELAY, CLTV_CLAIM_BUFFER, COUNTERPARTY_CLAIMABLE_WITHIN_BLOCKS_PINNABLE, + ANTI_REORG_DELAY, Balance, CLTV_CLAIM_BUFFER, COUNTERPARTY_CLAIMABLE_WITHIN_BLOCKS_PINNABLE, LATENCY_GRACE_PERIOD_BLOCKS, }; use crate::chain::transaction::OutPoint; -use crate::chain::BlockLocator; use crate::chain::{ChannelMonitorUpdateStatus, Confirm, Listen, Watch}; use crate::events::{ ClosureReason, Event, HTLCHandlingFailureType, PathFailure, PaymentFailureReason, PaymentPurpose, }; use crate::ln::chan_utils::{ - commitment_tx_base_weight, second_stage_tx_fees_sat, COMMITMENT_TX_WEIGHT_PER_HTLC, - OFFERED_HTLC_SCRIPT_WEIGHT, + COMMITMENT_TX_WEIGHT_PER_HTLC, OFFERED_HTLC_SCRIPT_WEIGHT, commitment_tx_base_weight, + second_stage_tx_fees_sat, }; use crate::ln::channel::{ - get_holder_selected_channel_reserve_satoshis, Channel, DISCONNECT_PEER_AWAITING_RESPONSE_TICKS, - MIN_CHAN_DUST_LIMIT_SATOSHIS, UNFUNDED_CHANNEL_AGE_LIMIT_TICKS, + Channel, DISCONNECT_PEER_AWAITING_RESPONSE_TICKS, MIN_CHAN_DUST_LIMIT_SATOSHIS, + UNFUNDED_CHANNEL_AGE_LIMIT_TICKS, get_holder_selected_channel_reserve_satoshis, }; use crate::ln::channelmanager::{ - PaymentId, RAACommitmentOrder, BREAKDOWN_TIMEOUT, DISABLE_GOSSIP_TICKS, ENABLE_GOSSIP_TICKS, - MIN_CLTV_EXPIRY_DELTA, + BREAKDOWN_TIMEOUT, DISABLE_GOSSIP_TICKS, ENABLE_GOSSIP_TICKS, MIN_CLTV_EXPIRY_DELTA, PaymentId, + RAACommitmentOrder, }; use crate::ln::msgs; use crate::ln::msgs::{ @@ -47,7 +47,7 @@ use crate::ln::types::ChannelId; use crate::ln::{chan_utils, onion_utils}; use crate::routing::gossip::{NetworkGraph, NetworkUpdate}; use crate::routing::router::{ - get_route, Path, PaymentParameters, Route, RouteHop, RouteParameters, + Path, PaymentParameters, Route, RouteHop, RouteParameters, get_route, }; use crate::sign::ChannelSigner; use crate::sign::{EntropySource, OutputSpender, SignerProvider}; @@ -244,7 +244,7 @@ pub fn duplicate_htlc_test() { let chanmon_cfgs = create_chanmon_cfgs(6); let node_cfgs = create_node_cfgs(6, &chanmon_cfgs); let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs, &[None, None, None, None, None, None]); - let mut nodes = create_network(6, &node_cfgs, &node_chanmgrs); + let nodes = create_network(6, &node_cfgs, &node_chanmgrs); // Create some initial channels to route via 3 to 4/5 from 0/1/2 create_announced_chan_between_nodes(&nodes, 0, 3); @@ -334,7 +334,10 @@ pub fn test_duplicate_htlc_different_direction_onchain() { action: msgs::ErrorAction::SendErrorMessage { ref msg }, } => { assert_eq!(node_id, node_b_id); - assert_eq!(msg.data, "Channel closed because commitment or closing transaction was confirmed on chain."); + assert_eq!( + msg.data, + "Channel closed because commitment or closing transaction was confirmed on chain." + ); }, MessageSendEvent::UpdateHTLCs { ref node_id, @@ -624,7 +627,7 @@ pub fn channel_monitor_network_test() { let reason = ClosureReason::HolderForceClosed { broadcasted_latest_txn: Some(true), message }; check_closed_event(&nodes[1], 1, reason, &[node_a_id], 100000); { - let mut node_txn = test_txn_broadcast(&nodes[1], &chan_1, None, HTLCType::NONE); + let node_txn = test_txn_broadcast(&nodes[1], &chan_1, None, HTLCType::NONE); assert_eq!(node_txn.len(), 1); mine_transaction(&nodes[1], &node_txn[0]); if nodes[1].connect_style.borrow().updates_best_block_first() { @@ -655,7 +658,7 @@ pub fn channel_monitor_network_test() { check_closed_broadcast(&nodes[1], 1, true); check_added_monitors(&nodes[1], 1); { - let mut node_txn = test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::NONE); + let node_txn = test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::NONE); connect_blocks( &nodes[1], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + MIN_CLTV_EXPIRY_DELTA as u32 + 1, @@ -762,11 +765,7 @@ pub fn channel_monitor_network_test() { { let mut node_txn = nodes[3].tx_broadcaster.txn_broadcasted.lock().unwrap(); node_txn.retain(|tx| { - if tx.input[0].previous_output.txid == node2_commitment_txid { - false - } else { - true - } + if tx.input[0].previous_output.txid == node2_commitment_txid { false } else { true } }); } @@ -833,7 +832,7 @@ pub fn test_justice_tx_htlc_timeout() { let node_cfgs = create_node_cfgs(2, &chanmon_cfgs); let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs); - let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs); + let nodes = create_network(2, &node_cfgs, &node_chanmgrs); let node_a_id = nodes[0].node.get_our_node_id(); let node_b_id = nodes[1].node.get_our_node_id(); @@ -858,7 +857,7 @@ pub fn test_justice_tx_htlc_timeout() { revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT ); // HTLC-Timeout - // Revoke the old state + // Revoke the old state claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_3); { @@ -921,7 +920,7 @@ pub fn test_justice_tx_htlc_success() { let node_cfgs = create_node_cfgs(2, &chanmon_cfgs); let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs); - let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs); + let nodes = create_network(2, &node_cfgs, &node_chanmgrs); let node_a_id = nodes[0].node.get_our_node_id(); let node_b_id = nodes[1].node.get_our_node_id(); @@ -1646,7 +1645,7 @@ pub fn test_htlc_on_chain_success() { } // HTLC timeout claims for non-anchor channels are only aggregated when claimed from the // remote commitment transaction. - let mut node_txn = nodes[0].tx_broadcaster.txn_broadcast(); + let node_txn = nodes[0].tx_broadcaster.txn_broadcast(); assert_eq!(node_txn.len(), 2); for tx in node_txn.iter() { check_spends!(tx, node_a_commitment_tx[0]); @@ -1674,7 +1673,7 @@ fn do_test_htlc_on_chain_timeout(connect_style: ConnectStyle) { &node_cfgs, &[Some(legacy_cfg.clone()), Some(legacy_cfg.clone()), Some(legacy_cfg)], ); - let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs); + let nodes = create_network(3, &node_cfgs, &node_chanmgrs); let node_a_id = nodes[0].node.get_our_node_id(); let node_b_id = nodes[1].node.get_our_node_id(); @@ -1930,7 +1929,7 @@ fn do_test_commitment_revoked_fail_backward_exhaustive( &node_cfgs, &[Some(legacy_cfg.clone()), Some(legacy_cfg.clone()), Some(legacy_cfg)], ); - let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs); + let nodes = create_network(3, &node_cfgs, &node_chanmgrs); let node_a_id = nodes[0].node.get_our_node_id(); let node_b_id = nodes[1].node.get_our_node_id(); @@ -2070,11 +2069,11 @@ fn do_test_commitment_revoked_fail_backward_exhaustive( ))); assert!(events.iter().any(|ev| matches!( ev, - Event::PaymentPathFailed { ref payment_hash, .. } if *payment_hash == fourth_payment_hash + Event::PaymentPathFailed { payment_hash, .. } if *payment_hash == fourth_payment_hash ))); assert!(events.iter().any(|ev| matches!( ev, - Event::PaymentFailed { ref payment_hash, .. } if *payment_hash == Some(fourth_payment_hash) + Event::PaymentFailed { payment_hash, .. } if *payment_hash == Some(fourth_payment_hash) ))); nodes[1].node.process_pending_htlc_forwards(); @@ -2241,7 +2240,7 @@ pub fn fail_backward_pending_htlc_upon_channel_failure() { let chanmon_cfgs = create_chanmon_cfgs(2); let node_cfgs = create_node_cfgs(2, &chanmon_cfgs); let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]); - let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs); + let nodes = create_network(2, &node_cfgs, &node_chanmgrs); let node_b_id = nodes[1].node.get_our_node_id(); @@ -2407,7 +2406,7 @@ pub fn test_force_close_fail_back() { &node_cfgs, &[Some(legacy_cfg.clone()), Some(legacy_cfg.clone()), Some(legacy_cfg)], ); - let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs); + let nodes = create_network(3, &node_cfgs, &node_chanmgrs); let node_a_id = nodes[0].node.get_our_node_id(); let node_b_id = nodes[1].node.get_our_node_id(); @@ -2562,10 +2561,12 @@ pub fn test_peer_disconnected_before_funding_broadcasted() { create_funding_transaction(&nodes[0], &node_b_id, 1_000_000, 42); assert_eq!(temporary_channel_id, expected_temporary_channel_id); - assert!(nodes[0] - .node - .funding_transaction_generated(temporary_channel_id, node_b_id, tx.clone()) - .is_ok()); + assert!( + nodes[0] + .node + .funding_transaction_generated(temporary_channel_id, node_b_id, tx.clone()) + .is_ok() + ); let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, node_b_id); @@ -2683,7 +2684,7 @@ fn do_test_drop_messages_peer_disconnect(messages_delivered: u8, simulate_broken let chanmon_cfgs = create_chanmon_cfgs(2); let node_cfgs = create_node_cfgs(2, &chanmon_cfgs); let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]); - let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs); + let nodes = create_network(2, &node_cfgs, &node_chanmgrs); let node_a_id = nodes[0].node.get_our_node_id(); let node_b_id = nodes[1].node.get_our_node_id(); @@ -3007,7 +3008,7 @@ pub fn test_channel_ready_without_best_block_updated() { let chanmon_cfgs = create_chanmon_cfgs(2); let node_cfgs = create_node_cfgs(2, &chanmon_cfgs); let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]); - let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs); + let nodes = create_network(2, &node_cfgs, &node_chanmgrs); let node_a_id = nodes[0].node.get_our_node_id(); let node_b_id = nodes[1].node.get_our_node_id(); @@ -3033,7 +3034,7 @@ pub fn test_channel_monitor_skipping_block_when_channel_manager_is_leading() { let chanmon_cfgs = create_chanmon_cfgs(2); let node_cfgs = create_node_cfgs(2, &chanmon_cfgs); let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]); - let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs); + let nodes = create_network(2, &node_cfgs, &node_chanmgrs); let node_a_id = nodes[0].node.get_our_node_id(); let node_b_id = nodes[1].node.get_our_node_id(); @@ -3042,7 +3043,7 @@ pub fn test_channel_monitor_skipping_block_when_channel_manager_is_leading() { // This is to emulate race-condition where newly added channel_monitor skips processing 1 block, // in case where client calls block_connect on channel_manager first and then on chain_monitor. let height_1 = nodes[0].best_block_info().1 + 1; - let mut block_1 = create_dummy_block(nodes[0].best_block_hash(), height_1, Vec::new()); + let block_1 = create_dummy_block(nodes[0].best_block_hash(), height_1, Vec::new()); nodes[0].blocks.lock().unwrap().push((block_1.clone(), height_1)); nodes[0].node.block_connected(&block_1, height_1); @@ -3068,7 +3069,7 @@ pub fn test_channel_monitor_skipping_block_when_channel_manager_is_lagging() { let chanmon_cfgs = create_chanmon_cfgs(2); let node_cfgs = create_node_cfgs(2, &chanmon_cfgs); let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]); - let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs); + let nodes = create_network(2, &node_cfgs, &node_chanmgrs); let node_a_id = nodes[0].node.get_our_node_id(); let node_b_id = nodes[1].node.get_our_node_id(); @@ -3077,7 +3078,7 @@ pub fn test_channel_monitor_skipping_block_when_channel_manager_is_lagging() { // This is to emulate race-condition where newly added channel_monitor skips processing 1 block, // in case where client calls block_connect on chain_monitor first and then on channel_manager. let height_1 = nodes[0].best_block_info().1 + 1; - let mut block_1 = create_dummy_block(nodes[0].best_block_hash(), height_1, Vec::new()); + let block_1 = create_dummy_block(nodes[0].best_block_hash(), height_1, Vec::new()); nodes[0].blocks.lock().unwrap().push((block_1.clone(), height_1)); nodes[0].chain_monitor.chain_monitor.block_connected(&block_1, height_1); @@ -3108,7 +3109,7 @@ pub fn test_drop_messages_peer_disconnect_dual_htlc() { let chanmon_cfgs = create_chanmon_cfgs(2); let node_cfgs = create_node_cfgs(2, &chanmon_cfgs); let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]); - let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs); + let nodes = create_network(2, &node_cfgs, &node_chanmgrs); let node_a_id = nodes[0].node.get_our_node_id(); let node_b_id = nodes[1].node.get_our_node_id(); @@ -3392,7 +3393,7 @@ fn do_test_holding_cell_htlc_add_timeouts(forwarded_htlc: bool) { let chanmon_cfgs = create_chanmon_cfgs(3); let node_cfgs = create_node_cfgs(3, &chanmon_cfgs); let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]); - let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs); + let nodes = create_network(3, &node_cfgs, &node_chanmgrs); let node_a_id = nodes[0].node.get_our_node_id(); let node_b_id = nodes[1].node.get_our_node_id(); @@ -4132,7 +4133,7 @@ pub fn test_duplicate_payment_hash_one_failure_one_success() { Some(config.clone()), ]; let node_chanmgrs = create_node_chanmgrs(5, &node_cfgs, &configs); - let mut nodes = create_network(5, &node_cfgs, &node_chanmgrs); + let nodes = create_network(5, &node_cfgs, &node_chanmgrs); let node_a_id = nodes[0].node.get_our_node_id(); let node_b_id = nodes[1].node.get_our_node_id(); @@ -5057,7 +5058,7 @@ fn do_htlc_claim_current_remote_commitment_only(use_dust: bool) { let legacy_cfg = test_legacy_channel_config(); let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(legacy_cfg.clone()), Some(legacy_cfg)]); - let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs); + let nodes = create_network(2, &node_cfgs, &node_chanmgrs); let node_b_id = nodes[1].node.get_our_node_id(); @@ -5196,7 +5197,7 @@ pub fn test_fail_holding_cell_htlc_upon_free() { let legacy_cfg = test_legacy_channel_config(); let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(legacy_cfg.clone()), Some(legacy_cfg)]); - let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs); + let nodes = create_network(2, &node_cfgs, &node_chanmgrs); let node_a_id = nodes[0].node.get_our_node_id(); let node_b_id = nodes[1].node.get_our_node_id(); @@ -5297,7 +5298,7 @@ pub fn test_free_and_fail_holding_cell_htlcs() { let legacy_cfg = test_legacy_channel_config(); let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(legacy_cfg.clone()), Some(legacy_cfg)]); - let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs); + let nodes = create_network(2, &node_cfgs, &node_chanmgrs); let node_a_id = nodes[0].node.get_our_node_id(); let node_b_id = nodes[1].node.get_our_node_id(); @@ -5447,7 +5448,7 @@ pub fn test_fail_holding_cell_htlc_upon_free_multihop() { &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())], ); - let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs); + let nodes = create_network(3, &node_cfgs, &node_chanmgrs); let node_a_id = nodes[0].node.get_our_node_id(); let node_b_id = nodes[1].node.get_our_node_id(); @@ -5582,7 +5583,7 @@ pub fn test_update_fulfill_htlc_bolt2_after_malformed_htlc_message_must_forward_ let chanmon_cfgs = create_chanmon_cfgs(3); let node_cfgs = create_node_cfgs(3, &chanmon_cfgs); let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]); - let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs); + let nodes = create_network(3, &node_cfgs, &node_chanmgrs); let node_a_id = nodes[0].node.get_our_node_id(); let node_b_id = nodes[1].node.get_our_node_id(); @@ -5695,7 +5696,7 @@ pub fn test_channel_failed_after_message_with_badonion_node_perm_bits_set() { let chanmon_cfgs = create_chanmon_cfgs(3); let node_cfgs = create_node_cfgs(3, &chanmon_cfgs); let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]); - let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs); + let nodes = create_network(3, &node_cfgs, &node_chanmgrs); let node_a_id = nodes[0].node.get_our_node_id(); let node_b_id = nodes[1].node.get_our_node_id(); @@ -6032,7 +6033,7 @@ pub fn test_check_htlc_underpaying() { let chanmon_cfgs = create_chanmon_cfgs(2); let node_cfgs = create_node_cfgs(2, &chanmon_cfgs); let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]); - let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs); + let nodes = create_network(2, &node_cfgs, &node_chanmgrs); let node_a_id = nodes[0].node.get_our_node_id(); let node_b_id = nodes[1].node.get_our_node_id(); @@ -6070,7 +6071,7 @@ pub fn test_check_htlc_underpaying() { let mut events = nodes[0].node.get_and_clear_pending_msg_events(); assert_eq!(events.len(), 1); - let mut payment_event = SendEvent::from_event(events.pop().unwrap()); + let payment_event = SendEvent::from_event(events.pop().unwrap()); nodes[1].node.handle_update_add_htlc(node_a_id, &payment_event.msgs[0]); do_commitment_signed_dance(&nodes[1], &nodes[0], &payment_event.commitment_msg, false, false); @@ -6155,7 +6156,7 @@ pub fn test_announce_disable_channels() { match e { MessageSendEvent::BroadcastChannelUpdate { ref msg, .. } => { assert_eq!(msg.contents.channel_flags & (1 << 1), 1 << 1); // The "channel disabled" bit should be set - // Check that each channel gets updated exactly once + // Check that each channel gets updated exactly once if chans_disabled .insert(msg.contents.short_channel_id, msg.contents.timestamp) .is_some() @@ -6676,7 +6677,7 @@ pub fn test_counterparty_raa_skip_no_crash() { let next_per_commitment_point; { let per_peer_state = nodes[0].node.per_peer_state.read().unwrap(); - let mut guard = per_peer_state.get(&node_b_id).unwrap().lock().unwrap(); + let guard = per_peer_state.get(&node_b_id).unwrap().lock().unwrap(); let keys = guard.channel_by_id.get(&channel_id).and_then(Channel::as_funded).unwrap().get_signer(); @@ -6970,7 +6971,7 @@ pub fn test_onion_value_mpp_set_calculation() { let chanmon_cfgs = create_chanmon_cfgs(node_count); let node_cfgs = create_node_cfgs(node_count, &chanmon_cfgs); let node_chanmgrs = create_node_chanmgrs(node_count, &node_cfgs, &vec![None; node_count]); - let mut nodes = create_network(node_count, &node_cfgs, &node_chanmgrs); + let nodes = create_network(node_count, &node_cfgs, &node_chanmgrs); let node_b_id = nodes[1].node.get_our_node_id(); let node_c_id = nodes[2].node.get_our_node_id(); @@ -7032,7 +7033,7 @@ pub fn test_onion_value_mpp_set_calculation() { let session_priv = [3; 32]; let height = nodes[0].best_block_info().1; let session_priv = SecretKey::from_slice(&session_priv).unwrap(); - let mut onion_keys = onion_utils::construct_onion_keys( + let onion_keys = onion_utils::construct_onion_keys( &Secp256k1::new(), &route.paths[0], &session_priv, @@ -7237,7 +7238,7 @@ pub fn test_preimage_storage() { check_added_monitors(&nodes[0], 1); let mut events = nodes[0].node.get_and_clear_pending_msg_events(); - let mut payment_event = SendEvent::from_event(events.pop().unwrap()); + let payment_event = SendEvent::from_event(events.pop().unwrap()); nodes[1].node.handle_update_add_htlc(node_a_id, &payment_event.msgs[0]); let commitment = &payment_event.commitment_msg; do_commitment_signed_dance(&nodes[1], &nodes[0], commitment, false, false); @@ -7356,7 +7357,7 @@ pub fn test_update_err_monitor_lockdown() { let chanmon_cfgs = create_chanmon_cfgs(2); let node_cfgs = create_node_cfgs(2, &chanmon_cfgs); let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]); - let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs); + let nodes = create_network(2, &node_cfgs, &node_chanmgrs); let node_a_id = nodes[0].node.get_our_node_id(); let node_b_id = nodes[1].node.get_our_node_id(); @@ -7416,7 +7417,7 @@ pub fn test_update_err_monitor_lockdown() { assert_eq!(updates.update_fulfill_htlcs.len(), 1); nodes[0].node.handle_update_fulfill_htlc(node_b_id, updates.update_fulfill_htlcs.remove(0)); { - let mut per_peer_lock; + let per_peer_lock; let mut peer_state_lock; let chan_ref = get_channel_ref!(nodes[0], nodes[1], per_peer_lock, peer_state_lock, chan_1.2); @@ -7461,7 +7462,7 @@ pub fn test_concurrent_monitor_claim() { let legacy_cfg = test_legacy_channel_config(); let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(legacy_cfg.clone()), Some(legacy_cfg)]); - let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs); + let nodes = create_network(2, &node_cfgs, &node_chanmgrs); let node_a_id = nodes[0].node.get_our_node_id(); let node_b_id = nodes[1].node.get_our_node_id(); @@ -7520,7 +7521,7 @@ pub fn test_concurrent_monitor_claim() { // Watchtower Alice should have broadcast a commitment/HTLC-timeout { - let mut txn = alice_broadcaster.txn_broadcast(); + let txn = alice_broadcaster.txn_broadcast(); assert_eq!(txn.len(), 2); check_spends!(txn[0], chan_1.3); check_spends!(txn[1], txn[0]); @@ -7574,7 +7575,7 @@ pub fn test_concurrent_monitor_claim() { assert_eq!(updates.update_add_htlcs.len(), 1); nodes[0].node.handle_update_add_htlc(node_b_id, &updates.update_add_htlcs[0]); { - let mut per_peer_lock; + let per_peer_lock; let mut peer_state_lock; let chan_ref = get_channel_ref!(nodes[0], nodes[1], per_peer_lock, peer_state_lock, chan_1.2); @@ -7664,7 +7665,7 @@ pub fn test_pre_lockin_no_chan_closed_update() { // Create an initial channel nodes[0].node.create_channel(node_b_id, 100000, 10001, 42, None, None).unwrap(); - let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, node_b_id); + let open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, node_b_id); handle_and_accept_open_channel(&nodes[1], node_a_id, &open_chan_msg); let accept_chan_msg = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, node_a_id); nodes[0].node.handle_accept_channel(node_b_id, &accept_chan_msg); @@ -7926,7 +7927,7 @@ fn do_test_onchain_htlc_settlement_after_close( let reason = ClosureReason::CommitmentTxConfirmed; check_closed_event(&nodes[1], 1, reason, &[node_a_id], 100000); } - let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap(); + let bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap(); if broadcast_alice { assert_eq!(bob_txn.len(), 1); check_spends!(bob_txn[0], txn_to_broadcast[0]); @@ -8056,7 +8057,7 @@ pub fn test_duplicate_conflicting_funding_from_second_peer() { nodes[0].node.funding_transaction_generated(temp_chan_id, node_b_id, tx.clone()).unwrap(); - let mut funding_created_msg = + let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, node_b_id); nodes[1].node.handle_funding_created(node_a_id, &funding_created_msg); let funding_signed_msg = @@ -8194,7 +8195,7 @@ fn do_test_tx_confirmed_skipping_blocks_immediate_broadcast(test_height_before_t &node_cfgs, &[Some(legacy_cfg.clone()), Some(legacy_cfg.clone()), Some(legacy_cfg)], ); - let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs); + let nodes = create_network(3, &node_cfgs, &node_chanmgrs); *nodes[0].connect_style.borrow_mut() = ConnectStyle::BestBlockFirstSkippingBlocks; @@ -8323,7 +8324,7 @@ fn do_test_dup_htlc_second_rejected(test_for_second_fail_panic: bool) { check_added_monitors(&nodes[0], 1); let mut events = nodes[0].node.get_and_clear_pending_msg_events(); assert_eq!(events.len(), 1); - let mut payment_event = SendEvent::from_event(events.pop().unwrap()); + let payment_event = SendEvent::from_event(events.pop().unwrap()); nodes[1].node.handle_update_add_htlc(node_a_id, &payment_event.msgs[0]); let commitment = &payment_event.commitment_msg; do_commitment_signed_dance(&nodes[1], &nodes[0], commitment, false, false); @@ -8339,7 +8340,7 @@ fn do_test_dup_htlc_second_rejected(test_for_second_fail_panic: bool) { check_added_monitors(&nodes[0], 1); let mut events = nodes[0].node.get_and_clear_pending_msg_events(); assert_eq!(events.len(), 1); - let mut payment_event = SendEvent::from_event(events.pop().unwrap()); + let payment_event = SendEvent::from_event(events.pop().unwrap()); nodes[1].node.handle_update_add_htlc(node_a_id, &payment_event.msgs[0]); let commitment = &payment_event.commitment_msg; do_commitment_signed_dance(&nodes[1], &nodes[0], commitment, false, false); @@ -8715,7 +8716,7 @@ fn do_test_max_dust_htlc_exposure( }; let node_cfgs = create_node_cfgs(2, &chanmon_cfgs); let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(config), None]); - let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs); + let nodes = create_network(2, &node_cfgs, &node_chanmgrs); let node_a_id = nodes[0].node.get_our_node_id(); let node_b_id = nodes[1].node.get_our_node_id(); @@ -8728,17 +8729,16 @@ fn do_test_max_dust_htlc_exposure( open_channel.common_fields.dust_limit_satoshis = 546; } handle_and_accept_open_channel(&nodes[1], node_a_id, &open_channel); - let mut accept_channel = - get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, node_a_id); + let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, node_a_id); nodes[0].node.handle_accept_channel(node_b_id, &accept_channel); let (chan_id, tx, _) = create_funding_transaction(&nodes[0], &node_b_id, 1_000_000, 42); if on_holder_tx { - let mut per_peer_lock; + let per_peer_lock; let mut peer_state_lock; let channel = get_channel_ref!(nodes[0], nodes[1], per_peer_lock, peer_state_lock, chan_id); - if let Some(mut chan) = channel.as_unfunded_outbound_v1_mut() { + if let Some(chan) = channel.as_unfunded_outbound_v1_mut() { chan.context.holder_dust_limit_satoshis = 546; } else { panic!("Unexpected Channel phase"); @@ -9299,7 +9299,7 @@ fn do_test_nondust_htlc_fees_dust_exposure_delta(features: ChannelTypeFeatures) let node_cfgs = create_node_cfgs(2, &chanmon_cfgs); let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(default_config), Some(fixed_limit_config)]); - let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs); + let nodes = create_network(2, &node_cfgs, &node_chanmgrs); let node_a_id = nodes[0].node.get_our_node_id(); let node_b_id = nodes[1].node.get_our_node_id(); @@ -9469,7 +9469,7 @@ fn test_nondust_htlc_fees_dust_exposure_delta() { } fn do_payment_with_custom_min_final_cltv_expiry(valid_delta: bool, use_user_hash: bool) { - let mut chanmon_cfgs = create_chanmon_cfgs(2); + let chanmon_cfgs = create_chanmon_cfgs(2); let node_cfgs = create_node_cfgs(2, &chanmon_cfgs); let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]); let nodes = create_network(2, &node_cfgs, &node_chanmgrs); @@ -9503,7 +9503,7 @@ fn do_payment_with_custom_min_final_cltv_expiry(valid_delta: bool, use_user_hash check_added_monitors(&nodes[0], 1); let mut events = nodes[0].node.get_and_clear_pending_msg_events(); assert_eq!(events.len(), 1); - let mut payment_event = SendEvent::from_event(events.pop().unwrap()); + let payment_event = SendEvent::from_event(events.pop().unwrap()); nodes[1].node.handle_update_add_htlc(node_a_id, &payment_event.msgs[0]); do_commitment_signed_dance(&nodes[1], &nodes[0], &payment_event.commitment_msg, false, false); @@ -9542,7 +9542,7 @@ pub fn test_payment_with_custom_min_cltv_expiry_delta() { pub fn test_disconnects_peer_awaiting_response_ticks() { // Tests that nodes which are awaiting on a response critical for channel responsiveness // disconnect their counterparty after `DISCONNECT_PEER_AWAITING_RESPONSE_TICKS`. - let mut chanmon_cfgs = create_chanmon_cfgs(2); + let chanmon_cfgs = create_chanmon_cfgs(2); let node_cfgs = create_node_cfgs(2, &chanmon_cfgs); let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]); let nodes = create_network(2, &node_cfgs, &node_chanmgrs); @@ -9818,7 +9818,7 @@ fn do_test_manual_broadcast_skips_commitment_until_funding( // forced to broadcast using `ChannelMonitor::broadcast_latest_holder_commitment_txn`. let chanmon_cfgs = create_chanmon_cfgs(2); let node_cfgs = create_node_cfgs(2, &chanmon_cfgs); - let mut chan_config = test_legacy_channel_config(); + let chan_config = test_legacy_channel_config(); let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(chan_config)]); let nodes = create_network(2, &node_cfgs, &node_chanmgrs); diff --git a/lightning/src/ln/funding.rs b/lightning/src/ln/funding.rs index 2867a03add7..e66e79d5802 100644 --- a/lightning/src/ln/funding.rs +++ b/lightning/src/ln/funding.rs @@ -13,14 +13,14 @@ use bitcoin::hashes::Hash; use bitcoin::secp256k1::PublicKey; use bitcoin::{Amount, FeeRate, OutPoint, ScriptBuf, SignedAmount, TxOut, WScriptHash, Weight}; +use crate::ln::LN_MAX_MSG_LEN; use crate::ln::chan_utils::{ - make_funding_redeemscript, BASE_INPUT_WEIGHT, EMPTY_SCRIPT_SIG_WEIGHT, - FUNDING_TRANSACTION_WITNESS_WEIGHT, + BASE_INPUT_WEIGHT, EMPTY_SCRIPT_SIG_WEIGHT, FUNDING_TRANSACTION_WITNESS_WEIGHT, + make_funding_redeemscript, }; -use crate::ln::interactivetxs::{get_output_weight, TX_COMMON_FIELDS_WEIGHT}; +use crate::ln::interactivetxs::{TX_COMMON_FIELDS_WEIGHT, get_output_weight}; use crate::ln::msgs; use crate::ln::types::ChannelId; -use crate::ln::LN_MAX_MSG_LEN; use crate::prelude::*; use crate::util::native_async::MaybeSend; use crate::util::wallet_utils::{ @@ -768,11 +768,7 @@ impl FundingContribution { for existing in existing_outputs { outputs.retain(|output| *output != *existing); } - if inputs.is_empty() && outputs.is_empty() { - None - } else { - Some((inputs, outputs)) - } + if inputs.is_empty() && outputs.is_empty() { None } else { Some((inputs, outputs)) } } /// Computes the adjusted fee and change output value at the given target feerate, which may @@ -1550,8 +1546,8 @@ impl SyncFundingBuilder { #[cfg(test)] mod tests { use super::{ - estimate_transaction_fee, FeeRateAdjustmentError, FundingBuilder, FundingContribution, - FundingContributionError, FundingTemplate, FundingTxInput, PriorContribution, + FeeRateAdjustmentError, FundingBuilder, FundingContribution, FundingContributionError, + FundingTemplate, FundingTxInput, PriorContribution, estimate_transaction_fee, }; use crate::chain::ClaimId; use crate::util::wallet_utils::{CoinSelection, CoinSelectionSourceSync, Input}; diff --git a/lightning/src/ln/htlc_reserve_unit_tests.rs b/lightning/src/ln/htlc_reserve_unit_tests.rs index 45d3cf5950f..808897ad490 100644 --- a/lightning/src/ln/htlc_reserve_unit_tests.rs +++ b/lightning/src/ln/htlc_reserve_unit_tests.rs @@ -2,14 +2,14 @@ use crate::events::{ClosureReason, Event, HTLCHandlingFailureType, PaymentPurpose}; use crate::ln::chan_utils::{ - self, commit_tx_fee_sat, commitment_tx_base_weight, second_stage_tx_fees_sat, - shared_anchor_script_pubkey, CommitmentTransaction, COMMITMENT_TX_WEIGHT_PER_HTLC, - TRUC_CHILD_MAX_WEIGHT, + self, COMMITMENT_TX_WEIGHT_PER_HTLC, CommitmentTransaction, TRUC_CHILD_MAX_WEIGHT, + commit_tx_fee_sat, commitment_tx_base_weight, second_stage_tx_fees_sat, + shared_anchor_script_pubkey, }; use crate::ln::channel::{ - get_holder_selected_channel_reserve_satoshis, Channel, ANCHOR_OUTPUT_VALUE_SATOSHI, - FEE_SPIKE_BUFFER_FEE_INCREASE_MULTIPLE, MIN_AFFORDABLE_HTLC_COUNT, - MIN_CHAN_DUST_LIMIT_SATOSHIS, + ANCHOR_OUTPUT_VALUE_SATOSHI, Channel, FEE_SPIKE_BUFFER_FEE_INCREASE_MULTIPLE, + MIN_AFFORDABLE_HTLC_COUNT, MIN_CHAN_DUST_LIMIT_SATOSHIS, + get_holder_selected_channel_reserve_satoshis, }; use crate::ln::channelmanager::{PaymentId, RAACommitmentOrder, TrustedChannelFeatures}; use crate::ln::functional_test_utils::*; @@ -18,9 +18,9 @@ use crate::ln::onion_utils::{self, AttributionData}; use crate::ln::outbound_payment::RecipientOnionFields; use crate::ln::types::ChannelId; use crate::routing::router::PaymentParameters; +use crate::sign::ChannelSigner; use crate::sign::ecdsa::EcdsaChannelSigner; use crate::sign::tx_builder::{SpecTxBuilder, TxBuilder}; -use crate::sign::ChannelSigner; use crate::types::features::ChannelTypeFeatures; use crate::types::payment::{PaymentHash, PaymentPreimage}; use crate::util::config::UserConfig; @@ -80,7 +80,7 @@ fn do_test_counterparty_no_reserve(send_from_initiator: bool) { { let sender_node = if send_from_initiator { &nodes[1] } else { &nodes[0] }; let counterparty_node = if send_from_initiator { &nodes[0] } else { &nodes[1] }; - let mut sender_node_per_peer_lock; + let sender_node_per_peer_lock; let mut sender_node_peer_state_lock; let channel = get_channel_ref!( @@ -134,7 +134,7 @@ pub fn test_channel_reserve_holding_cell_htlcs() { let configs = [Some(config.clone()), Some(config.clone()), Some(config.clone())]; let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &configs); - let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs); + let nodes = create_network(3, &node_cfgs, &node_chanmgrs); let node_a_id = nodes[0].node.get_our_node_id(); let node_b_id = nodes[1].node.get_our_node_id(); @@ -294,7 +294,8 @@ pub fn test_channel_reserve_holding_cell_htlcs() { stat.value_to_self_msat - (stat.pending_outbound_htlcs_amount_msat + recv_value_21 + recv_value_22 - + total_fee_msat + total_fee_msat + + total_fee_msat + + total_fee_msat + commit_tx_fee_3_htlcs), stat.channel_reserve_msat ); @@ -483,7 +484,7 @@ pub fn channel_reserve_in_flight_removes() { let chanmon_cfgs = create_chanmon_cfgs(2); let node_cfgs = create_node_cfgs(2, &chanmon_cfgs); let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]); - let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs); + let nodes = create_network(2, &node_cfgs, &node_chanmgrs); let node_a_id = nodes[0].node.get_our_node_id(); let node_b_id = nodes[1].node.get_our_node_id(); @@ -629,7 +630,7 @@ pub fn holding_cell_htlc_counting() { let chanmon_cfgs = create_chanmon_cfgs(3); let node_cfgs = create_node_cfgs(3, &chanmon_cfgs); let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]); - let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs); + let nodes = create_network(3, &node_cfgs, &node_chanmgrs); let node_a_id = nodes[0].node.get_our_node_id(); let node_b_id = nodes[1].node.get_our_node_id(); @@ -761,7 +762,7 @@ pub fn test_basic_channel_reserve() { let legacy_cfg = test_legacy_channel_config(); let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(legacy_cfg.clone()), Some(legacy_cfg)]); - let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs); + let nodes = create_network(2, &node_cfgs, &node_chanmgrs); let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000); @@ -805,7 +806,7 @@ pub fn do_test_fee_spike_buffer(cfg: Option, htlc_fails: bool) { let chanmon_cfgs = create_chanmon_cfgs(2); let node_cfgs = create_node_cfgs(2, &chanmon_cfgs); let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[cfg.clone(), cfg]); - let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs); + let nodes = create_network(2, &node_cfgs, &node_chanmgrs); let node_a_id = nodes[0].node.get_our_node_id(); let node_b_id = nodes[1].node.get_our_node_id(); @@ -980,7 +981,7 @@ pub fn do_test_fee_spike_buffer(cfg: Option, htlc_fails: bool) { #[xtest(feature = "_externalize_tests")] pub fn test_chan_reserve_violation_outbound_htlc_inbound_chan() { - let mut chanmon_cfgs = create_chanmon_cfgs(2); + let chanmon_cfgs = create_chanmon_cfgs(2); // Set the fee rate for the channel very high, to the point where the fundee // sending any above-dust amount would result in a channel reserve violation. // In this test we check that we would be prevented from sending an HTLC in @@ -990,7 +991,7 @@ pub fn test_chan_reserve_violation_outbound_htlc_inbound_chan() { let legacy_cfg = test_legacy_channel_config(); let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(legacy_cfg.clone()), Some(legacy_cfg)]); - let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs); + let nodes = create_network(2, &node_cfgs, &node_chanmgrs); let default_config = UserConfig::default(); let channel_type_features = ChannelTypeFeatures::only_static_remote_key(); @@ -1027,14 +1028,14 @@ pub fn test_chan_reserve_violation_outbound_htlc_inbound_chan() { pub fn test_chan_reserve_dust_inbound_htlcs_outbound_chan() { // Test that if we receive many dust HTLCs over an outbound channel, they don't count when // calculating our commitment transaction fee (this was previously broken). - let mut chanmon_cfgs = create_chanmon_cfgs(2); + let chanmon_cfgs = create_chanmon_cfgs(2); let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap(); let node_cfgs = create_node_cfgs(2, &chanmon_cfgs); let legacy_cfg = test_legacy_channel_config(); let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(legacy_cfg.clone()), Some(legacy_cfg)]); - let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs); + let nodes = create_network(2, &node_cfgs, &node_chanmgrs); let default_config = UserConfig::default(); let channel_type_features = ChannelTypeFeatures::only_static_remote_key(); @@ -1086,7 +1087,7 @@ pub fn test_chan_reserve_dust_inbound_htlcs_inbound_chan() { let legacy_cfg = test_legacy_channel_config(); let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(legacy_cfg.clone()), Some(legacy_cfg)]); - let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs); + let nodes = create_network(2, &node_cfgs, &node_chanmgrs); create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 98000000); @@ -1116,7 +1117,7 @@ pub fn test_chan_reserve_violation_inbound_htlc_inbound_chan() { let chanmon_cfgs = create_chanmon_cfgs(3); let node_cfgs = create_node_cfgs(3, &chanmon_cfgs); let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]); - let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs); + let nodes = create_network(3, &node_cfgs, &node_chanmgrs); let node_a_id = nodes[0].node.get_our_node_id(); @@ -1223,7 +1224,7 @@ pub fn test_payment_route_reaching_same_channel_twice() { let chanmon_cfgs = create_chanmon_cfgs(2); let node_cfgs = create_node_cfgs(2, &chanmon_cfgs); let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]); - let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs); + let nodes = create_network(2, &node_cfgs, &node_chanmgrs); let node_b_id = nodes[1].node.get_our_node_id(); @@ -1239,10 +1240,18 @@ pub fn test_payment_route_reaching_same_channel_twice() { let cloned_hops = route.paths[0].hops.clone(); route.paths[0].hops.extend_from_slice(&cloned_hops); - unwrap_send_err!(nodes[0], nodes[0].node.send_payment_with_route(route, our_payment_hash, - RecipientOnionFields::secret_only(our_payment_secret, 100000000), PaymentId(our_payment_hash.0) - ), false, APIError::InvalidRoute { ref err }, - assert_eq!(err, &"Path went through the same channel twice")); + unwrap_send_err!( + nodes[0], + nodes[0].node.send_payment_with_route( + route, + our_payment_hash, + RecipientOnionFields::secret_only(our_payment_secret, 100000000), + PaymentId(our_payment_hash.0) + ), + false, + APIError::InvalidRoute { err }, + assert_eq!(err, &"Path went through the same channel twice") + ); assert!(nodes[0].node.list_recent_payments().is_empty()); } @@ -1256,7 +1265,7 @@ pub fn test_update_add_htlc_bolt2_sender_value_below_minimum_msat() { let chanmon_cfgs = create_chanmon_cfgs(2); let node_cfgs = create_node_cfgs(2, &chanmon_cfgs); let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]); - let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs); + let nodes = create_network(2, &node_cfgs, &node_chanmgrs); let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000); @@ -1277,7 +1286,7 @@ pub fn test_update_add_htlc_bolt2_sender_zero_value_msat() { let chanmon_cfgs = create_chanmon_cfgs(2); let node_cfgs = create_node_cfgs(2, &chanmon_cfgs); let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]); - let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs); + let nodes = create_network(2, &node_cfgs, &node_chanmgrs); let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000); @@ -1287,9 +1296,13 @@ pub fn test_update_add_htlc_bolt2_sender_zero_value_msat() { let onion = RecipientOnionFields::secret_only(our_payment_secret, 0); let id = PaymentId(our_payment_hash.0); let res = nodes[0].node.send_payment_with_route(route, our_payment_hash, onion, id); - unwrap_send_err!(nodes[0], res, - true, APIError::ChannelUnavailable { ref err }, - assert_eq!(err, "Cannot send 0-msat HTLC")); + unwrap_send_err!( + nodes[0], + res, + true, + APIError::ChannelUnavailable { err }, + assert_eq!(err, "Cannot send 0-msat HTLC") + ); assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty()); nodes[0].logger.assert_log_contains( @@ -1305,7 +1318,7 @@ pub fn test_update_add_htlc_bolt2_receiver_zero_value_msat() { let chanmon_cfgs = create_chanmon_cfgs(2); let node_cfgs = create_node_cfgs(2, &chanmon_cfgs); let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]); - let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs); + let nodes = create_network(2, &node_cfgs, &node_chanmgrs); let node_a_id = nodes[0].node.get_our_node_id(); let node_b_id = nodes[1].node.get_our_node_id(); @@ -1342,7 +1355,7 @@ pub fn test_update_add_htlc_bolt2_sender_cltv_expiry_too_high() { let chanmon_cfgs = create_chanmon_cfgs(2); let node_cfgs = create_node_cfgs(2, &chanmon_cfgs); let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]); - let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs); + let nodes = create_network(2, &node_cfgs, &node_chanmgrs); let node_b_id = nodes[1].node.get_our_node_id(); @@ -1359,8 +1372,13 @@ pub fn test_update_add_htlc_bolt2_sender_cltv_expiry_too_high() { let onion = RecipientOnionFields::secret_only(our_payment_secret, 100000000); let id = PaymentId(our_payment_hash.0); let res = nodes[0].node.send_payment_with_route(route, our_payment_hash, onion, id); - unwrap_send_err!(nodes[0], res, true, APIError::InvalidRoute { ref err }, - assert_eq!(err, &"Channel CLTV overflowed?")); + unwrap_send_err!( + nodes[0], + res, + true, + APIError::InvalidRoute { err }, + assert_eq!(err, &"Channel CLTV overflowed?") + ); } #[xtest(feature = "_externalize_tests")] @@ -1371,7 +1389,7 @@ pub fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_num_and_htlc_id_increme let chanmon_cfgs = create_chanmon_cfgs(2); let node_cfgs = create_node_cfgs(2, &chanmon_cfgs); let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]); - let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs); + let nodes = create_network(2, &node_cfgs, &node_chanmgrs); let node_a_id = nodes[0].node.get_our_node_id(); @@ -1431,7 +1449,7 @@ pub fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_value_in_flight() { let chanmon_cfgs = create_chanmon_cfgs(2); let node_cfgs = create_node_cfgs(2, &chanmon_cfgs); let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]); - let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs); + let nodes = create_network(2, &node_cfgs, &node_chanmgrs); let channel_value = 100000; let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 0); @@ -1461,7 +1479,7 @@ pub fn test_update_add_htlc_bolt2_receiver_check_amount_received_more_than_min() let chanmon_cfgs = create_chanmon_cfgs(2); let node_cfgs = create_node_cfgs(2, &chanmon_cfgs); let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]); - let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs); + let nodes = create_network(2, &node_cfgs, &node_chanmgrs); let node_a_id = nodes[0].node.get_our_node_id(); let node_b_id = nodes[1].node.get_our_node_id(); @@ -1500,7 +1518,7 @@ pub fn test_update_add_htlc_bolt2_receiver_sender_can_afford_amount_sent() { let legacy_cfg = test_legacy_channel_config(); let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(legacy_cfg.clone()), Some(legacy_cfg)]); - let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs); + let nodes = create_network(2, &node_cfgs, &node_chanmgrs); let node_a_id = nodes[0].node.get_our_node_id(); let node_b_id = nodes[1].node.get_our_node_id(); @@ -1544,7 +1562,7 @@ pub fn test_update_add_htlc_bolt2_receiver_check_max_htlc_limit() { let chanmon_cfgs = create_chanmon_cfgs(2); let node_cfgs = create_node_cfgs(2, &chanmon_cfgs); let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]); - let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs); + let nodes = create_network(2, &node_cfgs, &node_chanmgrs); let node_a_id = nodes[0].node.get_our_node_id(); @@ -1597,9 +1615,11 @@ pub fn test_update_add_htlc_bolt2_receiver_check_max_htlc_limit() { assert!(nodes[1].node.list_channels().is_empty()); let err_msg = check_closed_broadcast(&nodes[1], 1, true).pop().unwrap(); - assert!(regex::Regex::new(r"Remote tried to push more than our max accepted HTLCs \(\d+\)") - .unwrap() - .is_match(err_msg.data.as_str())); + assert!( + regex::Regex::new(r"Remote tried to push more than our max accepted HTLCs \(\d+\)") + .unwrap() + .is_match(err_msg.data.as_str()) + ); check_added_monitors(&nodes[1], 1); let reason = ClosureReason::ProcessingError { err: err_msg.data }; check_closed_event(&nodes[1], 1, reason, &[node_a_id], 100000); @@ -1611,7 +1631,7 @@ pub fn test_update_add_htlc_bolt2_receiver_check_max_in_flight_msat() { let chanmon_cfgs = create_chanmon_cfgs(2); let node_cfgs = create_node_cfgs(2, &chanmon_cfgs); let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]); - let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs); + let nodes = create_network(2, &node_cfgs, &node_chanmgrs); let node_a_id = nodes[0].node.get_our_node_id(); let node_b_id = nodes[1].node.get_our_node_id(); @@ -1632,9 +1652,11 @@ pub fn test_update_add_htlc_bolt2_receiver_check_max_in_flight_msat() { assert!(nodes[1].node.list_channels().is_empty()); let err_msg = check_closed_broadcast(&nodes[1], 1, true).pop().unwrap(); - assert!(regex::Regex::new("Remote HTLC add would put them over our max HTLC value") - .unwrap() - .is_match(err_msg.data.as_str())); + assert!( + regex::Regex::new("Remote HTLC add would put them over our max HTLC value") + .unwrap() + .is_match(err_msg.data.as_str()) + ); check_added_monitors(&nodes[1], 1); let reason = ClosureReason::ProcessingError { err: err_msg.data }; check_closed_event(&nodes[1], 1, reason, &[node_a_id], 1000000); @@ -1646,7 +1668,7 @@ pub fn test_update_add_htlc_bolt2_receiver_check_cltv_expiry() { let chanmon_cfgs = create_chanmon_cfgs(2); let node_cfgs = create_node_cfgs(2, &chanmon_cfgs); let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]); - let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs); + let nodes = create_network(2, &node_cfgs, &node_chanmgrs); let node_a_id = nodes[0].node.get_our_node_id(); let node_b_id = nodes[1].node.get_our_node_id(); @@ -1678,7 +1700,7 @@ pub fn test_update_add_htlc_bolt2_receiver_check_repeated_id_ignore() { let chanmon_cfgs = create_chanmon_cfgs(2); let node_cfgs = create_node_cfgs(2, &chanmon_cfgs); let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]); - let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs); + let nodes = create_network(2, &node_cfgs, &node_chanmgrs); let node_a_id = nodes[0].node.get_our_node_id(); let node_b_id = nodes[1].node.get_our_node_id(); @@ -1728,9 +1750,11 @@ pub fn test_update_add_htlc_bolt2_receiver_check_repeated_id_ignore() { assert!(nodes[1].node.list_channels().is_empty()); let err_msg = check_closed_broadcast(&nodes[1], 1, true).pop().unwrap(); - assert!(regex::Regex::new(r"Remote skipped HTLC ID \(skipped ID: \d+\)") - .unwrap() - .is_match(err_msg.data.as_str())); + assert!( + regex::Regex::new(r"Remote skipped HTLC ID \(skipped ID: \d+\)") + .unwrap() + .is_match(err_msg.data.as_str()) + ); check_added_monitors(&nodes[1], 1); let reason = ClosureReason::ProcessingError { err: err_msg.data }; check_closed_event(&nodes[1], 1, reason, &[node_a_id], 100000); @@ -1743,7 +1767,7 @@ pub fn test_update_fulfill_htlc_bolt2_update_fulfill_htlc_before_commitment() { let chanmon_cfgs = create_chanmon_cfgs(2); let node_cfgs = create_node_cfgs(2, &chanmon_cfgs); let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]); - let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs); + let nodes = create_network(2, &node_cfgs, &node_chanmgrs); let node_a_id = nodes[0].node.get_our_node_id(); let node_b_id = nodes[1].node.get_our_node_id(); @@ -1770,11 +1794,13 @@ pub fn test_update_fulfill_htlc_bolt2_update_fulfill_htlc_before_commitment() { assert!(nodes[0].node.list_channels().is_empty()); let err_msg = check_closed_broadcast(&nodes[0], 1, true).pop().unwrap(); - assert!(regex::Regex::new( - r"Remote tried to fulfill/fail HTLC \(\d+\) before it had been committed" - ) - .unwrap() - .is_match(err_msg.data.as_str())); + assert!( + regex::Regex::new( + r"Remote tried to fulfill/fail HTLC \(\d+\) before it had been committed" + ) + .unwrap() + .is_match(err_msg.data.as_str()) + ); check_added_monitors(&nodes[0], 1); let reason = ClosureReason::ProcessingError { err: err_msg.data }; check_closed_event(&nodes[0], 1, reason, &[node_b_id], 100000); @@ -1787,7 +1813,7 @@ pub fn test_update_fulfill_htlc_bolt2_update_fail_htlc_before_commitment() { let chanmon_cfgs = create_chanmon_cfgs(2); let node_cfgs = create_node_cfgs(2, &chanmon_cfgs); let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]); - let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs); + let nodes = create_network(2, &node_cfgs, &node_chanmgrs); let node_a_id = nodes[0].node.get_our_node_id(); let node_b_id = nodes[1].node.get_our_node_id(); @@ -1814,11 +1840,13 @@ pub fn test_update_fulfill_htlc_bolt2_update_fail_htlc_before_commitment() { assert!(nodes[0].node.list_channels().is_empty()); let err_msg = check_closed_broadcast(&nodes[0], 1, true).pop().unwrap(); - assert!(regex::Regex::new( - r"Remote tried to fulfill/fail HTLC \(\d+\) before it had been committed" - ) - .unwrap() - .is_match(err_msg.data.as_str())); + assert!( + regex::Regex::new( + r"Remote tried to fulfill/fail HTLC \(\d+\) before it had been committed" + ) + .unwrap() + .is_match(err_msg.data.as_str()) + ); check_added_monitors(&nodes[0], 1); let reason = ClosureReason::ProcessingError { err: err_msg.data }; check_closed_event(&nodes[0], 1, reason, &[node_b_id], 100000); @@ -1831,7 +1859,7 @@ pub fn test_update_fulfill_htlc_bolt2_update_fail_malformed_htlc_before_commitme let chanmon_cfgs = create_chanmon_cfgs(2); let node_cfgs = create_node_cfgs(2, &chanmon_cfgs); let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]); - let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs); + let nodes = create_network(2, &node_cfgs, &node_chanmgrs); let node_a_id = nodes[0].node.get_our_node_id(); let node_b_id = nodes[1].node.get_our_node_id(); @@ -1857,11 +1885,13 @@ pub fn test_update_fulfill_htlc_bolt2_update_fail_malformed_htlc_before_commitme assert!(nodes[0].node.list_channels().is_empty()); let err_msg = check_closed_broadcast(&nodes[0], 1, true).pop().unwrap(); - assert!(regex::Regex::new( - r"Remote tried to fulfill/fail HTLC \(\d+\) before it had been committed" - ) - .unwrap() - .is_match(err_msg.data.as_str())); + assert!( + regex::Regex::new( + r"Remote tried to fulfill/fail HTLC \(\d+\) before it had been committed" + ) + .unwrap() + .is_match(err_msg.data.as_str()) + ); check_added_monitors(&nodes[0], 1); let reason = ClosureReason::ProcessingError { err: err_msg.data }; check_closed_event(&nodes[0], 1, reason, &[node_b_id], 100000); @@ -1979,9 +2009,11 @@ pub fn test_update_fulfill_htlc_bolt2_wrong_preimage() { assert!(nodes[0].node.list_channels().is_empty()); let err_msg = check_closed_broadcast(&nodes[0], 1, true).pop().unwrap(); - assert!(regex::Regex::new(r"Remote tried to fulfill HTLC \(\d+\) with an incorrect preimage") - .unwrap() - .is_match(err_msg.data.as_str())); + assert!( + regex::Regex::new(r"Remote tried to fulfill HTLC \(\d+\) with an incorrect preimage") + .unwrap() + .is_match(err_msg.data.as_str()) + ); check_added_monitors(&nodes[0], 1); let reason = ClosureReason::ProcessingError { err: err_msg.data }; check_closed_event(&nodes[0], 1, reason, &[node_b_id], 100000); @@ -1994,7 +2026,7 @@ pub fn test_update_fulfill_htlc_bolt2_missing_badonion_bit_for_malformed_htlc_me let chanmon_cfgs = create_chanmon_cfgs(2); let node_cfgs = create_node_cfgs(2, &chanmon_cfgs); let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]); - let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs); + let nodes = create_network(2, &node_cfgs, &node_chanmgrs); let node_a_id = nodes[0].node.get_our_node_id(); let node_b_id = nodes[1].node.get_our_node_id(); @@ -2077,7 +2109,7 @@ pub fn do_test_dust_limit_fee_accounting(can_afford: bool) { let node_cfgs = create_node_cfgs(2, &chanmon_cfgs); let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]); - let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs); + let nodes = create_network(2, &node_cfgs, &node_chanmgrs); let node_a_id = nodes[0].node.get_our_node_id(); let node_b_id = nodes[1].node.get_our_node_id(); @@ -2101,7 +2133,7 @@ pub fn do_test_dust_limit_fee_accounting(can_afford: bool) { + 2 * crate::ln::channel::ANCHOR_OUTPUT_VALUE_SATOSHI + MIN_AFFORDABLE_HTLC_COUNT as u64 * HTLC_AMT_SAT - if can_afford { 0 } else { 1 }; - let mut node_1_balance_sat = CHANNEL_VALUE_SAT - node_0_balance_sat; + let node_1_balance_sat = CHANNEL_VALUE_SAT - node_0_balance_sat; let chan_id = create_chan_between_nodes_with_value( &nodes[0], @@ -2390,10 +2422,10 @@ fn do_test_create_channel_to_trusted_peer_0reserve(mut config: UserConfig) -> Ch .node .create_channel_to_trusted_peer_0reserve(node_b_id, channel_value_sat, 0, 42, None, None) .unwrap(); - let mut open_channel_message = + let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, node_b_id); handle_and_accept_open_channel(&nodes[1], node_a_id, &open_channel_message); - let mut accept_channel_message = + let accept_channel_message = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, node_a_id); nodes[0].node.handle_accept_channel(node_b_id, &accept_channel_message); let funding_tx = sign_funding_transaction(&nodes[0], &nodes[1], 100_000, temp_channel_id); @@ -2478,7 +2510,7 @@ fn do_test_accept_inbound_channel_from_trusted_peer_0reserve( nodes[0].node.create_channel(node_b_id, channel_value_sat, 0, 42, None, None).unwrap(); - let mut open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, node_b_id); + let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, node_b_id); nodes[1].node.handle_open_channel(node_a_id, &open_channel); let events = nodes[1].node.get_and_clear_pending_events(); assert_eq!(events.len(), 1); @@ -2498,7 +2530,7 @@ fn do_test_accept_inbound_channel_from_trusted_peer_0reserve( _ => panic!("Unexpected event"), }; - let mut accept_channel_msg = + let accept_channel_msg = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, node_a_id); nodes[0].node.handle_accept_channel(node_b_id, &accept_channel_msg); @@ -2648,11 +2680,11 @@ pub(crate) fn setup_0reserve_no_outputs_channels<'a, 'b, 'c, 'd>( update_nodes_with_chan_announce(nodes, 0, 1, &announcement, &as_update, &bs_update); { - let mut per_peer_lock; + let per_peer_lock; let mut peer_state_lock; let channel = get_channel_ref!(nodes[0], nodes[1], per_peer_lock, peer_state_lock, channel_id); - if let Some(mut chan) = channel.as_funded_mut() { + if let Some(chan) = channel.as_funded_mut() { chan.context.holder_dust_limit_satoshis = dust_limit_satoshis; } else { panic!("Unexpected Channel phase"); @@ -2660,11 +2692,11 @@ pub(crate) fn setup_0reserve_no_outputs_channels<'a, 'b, 'c, 'd>( } { - let mut per_peer_lock; + let per_peer_lock; let mut peer_state_lock; let channel = get_channel_ref!(nodes[1], nodes[0], per_peer_lock, peer_state_lock, channel_id); - if let Some(mut chan) = channel.as_funded_mut() { + if let Some(chan) = channel.as_funded_mut() { chan.context.holder_dust_limit_satoshis = dust_limit_satoshis; } else { panic!("Unexpected Channel phase"); @@ -3000,7 +3032,8 @@ fn do_test_0reserve_no_outputs_keyed_anchors(payment_success: bool) { // min opener balance is the fee for 4 HTLCs, the anchors, and the dust limit let min_channel_size = commit_tx_fee_sat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT, &channel_type) - + anchors_sat + dust_limit_satoshis; + + anchors_sat + + dust_limit_satoshis; assert!(min_channel_size > 1002); min_channel_size }; diff --git a/lightning/src/ln/inbound_payment.rs b/lightning/src/ln/inbound_payment.rs index a7597701768..60db7d766f1 100644 --- a/lightning/src/ln/inbound_payment.rs +++ b/lightning/src/ln/inbound_payment.rs @@ -410,7 +410,11 @@ pub(super) fn verify( &iv_bytes, &Hmac::from_engine(hmac).to_byte_array().split_at_mut(IV_LEN).0, ) { - log_trace!(logger, "Failing async payment HTLC with sender-generated payment_hash {}: unexpected payment_secret", &payment_hash); + log_trace!( + logger, + "Failing async payment HTLC with sender-generated payment_hash {}: unexpected payment_secret", + &payment_hash + ); return Err(()); } }, @@ -440,7 +444,13 @@ pub(super) fn verify( let expiry = u64::from_be_bytes(expiry_bytes.try_into().unwrap()); if payment_data.total_msat < min_amt_msat { - log_trace!(logger, "Failing HTLC with payment_hash {} due to total_msat {} being less than the minimum amount of {} msat", &payment_hash, payment_data.total_msat, min_amt_msat); + log_trace!( + logger, + "Failing HTLC with payment_hash {} due to total_msat {} being less than the minimum amount of {} msat", + &payment_hash, + payment_data.total_msat, + min_amt_msat + ); return Err(()); } diff --git a/lightning/src/ln/interactivetxs.rs b/lightning/src/ln/interactivetxs.rs index ca8c4450012..ccf99aed239 100644 --- a/lightning/src/ln/interactivetxs.rs +++ b/lightning/src/ln/interactivetxs.rs @@ -22,8 +22,8 @@ use bitcoin::secp256k1::{Message, PublicKey}; use bitcoin::sighash::SighashCache; use bitcoin::transaction::Version; use bitcoin::{ - sighash, EcdsaSighashType, OutPoint as BitcoinOutPoint, ScriptBuf, Sequence, TapSighashType, - Transaction, TxIn, TxOut, Txid, Weight, Witness, XOnlyPublicKey, + EcdsaSighashType, OutPoint as BitcoinOutPoint, ScriptBuf, Sequence, TapSighashType, + Transaction, TxIn, TxOut, Txid, Weight, Witness, XOnlyPublicKey, sighash, }; use crate::chain::chaininterface::fee_for_weight; @@ -794,19 +794,27 @@ impl InteractiveTxSigningSession { // P2WPKH if script_pubkey.is_p2wpkh() { if witness.len() != 2 { - let err = format!("The witness for input at index {input_idx} does not have the correct number of elements for a P2WPKH spend. Expected 2 got {}", witness.len()); + let err = format!( + "The witness for input at index {input_idx} does not have the correct number of elements for a P2WPKH spend. Expected 2 got {}", + witness.len() + ); return Err(err); } let pubkey = PublicKey::from_slice(&witness[1]).map_err(|_| { - format!("The witness for input at index {input_idx} contains an invalid ECDSA public key") + format!( + "The witness for input at index {input_idx} contains an invalid ECDSA public key" + ) })?; - let sig = - bitcoin::ecdsa::Signature::from_slice(&witness[0]).map_err(|_| { - format!("The witness for input at index {input_idx} contains an invalid signature") - })?; + let sig = bitcoin::ecdsa::Signature::from_slice(&witness[0]).map_err(|_| { + format!( + "The witness for input at index {input_idx} contains an invalid signature" + ) + })?; if !matches!(sig.sighash_type, EcdsaSighashType::All) { - let err = format!("Signature does not use SIGHASH_ALL for input at index {input_idx} for P2WPKH spend"); + let err = format!( + "Signature does not use SIGHASH_ALL for input at index {input_idx} for P2WPKH spend" + ); return Err(err); } @@ -824,7 +832,9 @@ impl InteractiveTxSigningSession { let msg = Message::from_digest_slice(&sighash[..]) .expect("Sighash is a SHA256 which is 32 bytes long"); secp_ctx.verify_ecdsa(&msg, &sig.signature, &pubkey).map_err(|_| { - format!("Failed signature verification for input at index {input_idx} for P2WPKH spend") + format!( + "Failed signature verification for input at index {input_idx} for P2WPKH spend" + ) })?; continue; @@ -848,7 +858,9 @@ impl InteractiveTxSigningSession { format!("The witness for input at index {input_idx} for a P2TR key path spend has an invalid signature") })?; if !matches!(sig.sighash_type, TapSighashType::Default | TapSighashType::All) { - let err = format!("Signature does not use SIGHASH_DEFAULT or SIGHASH_ALL for input at index {input_idx} for P2TR key path spend"); + let err = format!( + "Signature does not use SIGHASH_DEFAULT or SIGHASH_ALL for input at index {input_idx} for P2TR key path spend" + ); return Err(err); } @@ -861,7 +873,9 @@ impl InteractiveTxSigningSession { let msg = Message::from_digest_slice(&sighash[..]) .expect("Sighash is a SHA256 which is 32 bytes long"); secp_ctx.verify_schnorr(&sig.signature, &msg, &pubkey).map_err(|_| { - format!("Failed signature verification for input at index {input_idx} for P2TR key path spend") + format!( + "Failed signature verification for input at index {input_idx} for P2TR key path spend" + ) })?; continue; @@ -877,7 +891,9 @@ impl InteractiveTxSigningSession { .map(|sig| matches!(sig.sighash_type, EcdsaSighashType::All)) .unwrap_or(true) { - let err = format!("An ECDSA signature in the witness for input {input_idx} does not use SIGHASH_ALL"); + let err = format!( + "An ECDSA signature in the witness for input {input_idx} does not use SIGHASH_ALL" + ); return Err(err); } }, @@ -898,7 +914,9 @@ impl InteractiveTxSigningSession { .map(|sig| matches!(sig.sighash_type, TapSighashType::All)) .unwrap_or(true) { - let err = format!("A (likely) Schnorr signature in the witness for input {input_idx} does not use SIGHASH_DEFAULT or SIGHASH_ALL"); + let err = format!( + "A (likely) Schnorr signature in the witness for input {input_idx} does not use SIGHASH_DEFAULT or SIGHASH_ALL" + ); return Err(err); } }, @@ -1456,7 +1474,11 @@ define_state!( ReceivedTxComplete, "We have received a `tx_complete` message and the counterparty is awaiting ours." ); -define_state!(NegotiationComplete, InteractiveTxSigningSession, "We have exchanged consecutive `tx_complete` messages with the counterparty and the transaction negotiation is complete."); +define_state!( + NegotiationComplete, + InteractiveTxSigningSession, + "We have exchanged consecutive `tx_complete` messages with the counterparty and the transaction negotiation is complete." +); define_state!( NegotiationAborted, AbortReason, @@ -1733,7 +1755,7 @@ impl InputOwned { pub fn tx_in_mut(&mut self) -> &mut TxIn { match self { - InputOwned::Single(ref mut single) => &mut single.input, + InputOwned::Single(single) => &mut single.input, InputOwned::Shared(shared) => &mut shared.input, } } @@ -2328,7 +2350,10 @@ impl InteractiveTxConstructor { Ok(HandleTxCompleteValue::SendTxMessage(msg_send)) }, // We either had an input or output to contribute. _ => { - debug_assert!(false, "We cannot transition to any other states after receiving `tx_complete` and responding"); + debug_assert!( + false, + "We cannot transition to any other states after receiving `tx_complete` and responding" + ); Err(AbortReason::InvalidStateTransition) }, } @@ -2357,14 +2382,14 @@ impl InteractiveTxConstructor { #[cfg(test)] mod tests { - use crate::chain::chaininterface::{fee_for_weight, FEERATE_FLOOR_SATS_PER_KW}; + use crate::chain::chaininterface::{FEERATE_FLOOR_SATS_PER_KW, fee_for_weight}; use crate::ln::channel::TOTAL_BITCOIN_SUPPLY_SATOSHIS; use crate::ln::funding::FundingTxInput; use crate::ln::interactivetxs::{ - generate_holder_serial_id, AbortReason, HandleTxCompleteValue, InteractiveTxConstructor, - InteractiveTxConstructorArgs, InteractiveTxMessageSend, SharedOwnedInput, - SharedOwnedOutput, MAX_INPUTS_OUTPUTS_COUNT, MAX_RECEIVED_TX_ADD_INPUT_COUNT, - MAX_RECEIVED_TX_ADD_OUTPUT_COUNT, + AbortReason, HandleTxCompleteValue, InteractiveTxConstructor, InteractiveTxConstructorArgs, + InteractiveTxMessageSend, MAX_INPUTS_OUTPUTS_COUNT, MAX_RECEIVED_TX_ADD_INPUT_COUNT, + MAX_RECEIVED_TX_ADD_OUTPUT_COUNT, SharedOwnedInput, SharedOwnedOutput, + generate_holder_serial_id, }; use crate::ln::types::ChannelId; use crate::sign::EntropySource; @@ -2377,15 +2402,15 @@ mod tests { use bitcoin::script::Builder; use bitcoin::secp256k1::{Keypair, PublicKey, Secp256k1, SecretKey}; use bitcoin::transaction::Version; - use bitcoin::{opcodes, WScriptHash, Weight, XOnlyPublicKey}; use bitcoin::{ OutPoint, PubkeyHash, ScriptBuf, Sequence, Transaction, TxIn, TxOut, WPubkeyHash, }; + use bitcoin::{WScriptHash, Weight, XOnlyPublicKey, opcodes}; use super::{ - get_output_weight, ConstructedTransaction, InteractiveTxSigningSession, TxInMetadata, - P2TR_INPUT_WEIGHT_LOWER_BOUND, P2WPKH_INPUT_WEIGHT_LOWER_BOUND, - P2WSH_INPUT_WEIGHT_LOWER_BOUND, REMOTE_FEE_TOLERANCE_PERCENT, TX_COMMON_FIELDS_WEIGHT, + ConstructedTransaction, InteractiveTxSigningSession, P2TR_INPUT_WEIGHT_LOWER_BOUND, + P2WPKH_INPUT_WEIGHT_LOWER_BOUND, P2WSH_INPUT_WEIGHT_LOWER_BOUND, + REMOTE_FEE_TOLERANCE_PERCENT, TX_COMMON_FIELDS_WEIGHT, TxInMetadata, get_output_weight, }; const TEST_FEERATE_SATS_PER_KW: u32 = FEERATE_FLOOR_SATS_PER_KW * 10; @@ -3370,58 +3395,60 @@ mod tests { fn test_verify_tx_signatures_p2tr_key_path_p2wsh_no_sig() { // Uses transaction https://mempool.space/tx/c28d01b47b8426039306e4209534fc5235da4a31406179639c54c48212be7655 let transaction: Transaction = bitcoin::consensus::encode::deserialize_hex("02000000000105d08ef8a4eac88a9568d660732d6e1bd8f216fecb46b7ebc7fc7b5a85e3ba1da50000000000ffffffff3ae09cc085873112f0602cac61e005827e7f21ce03595c6bf1e5ab41643e2e240000000000ffffffff030d20d2b28c4f27797e90ab2259392e99070307f0ee14a621025f8adc9054720000000000100000007d2e78b06110de8ac2298e71fa6fd96e24a287597f3a3fbfaa60837e40453a990000000000100000007d2e78b06110de8ac2298e71fa6fd96e24a287597f3a3fbfaa60837e40453a990100000000100000000104310d01000000002251207434164bd41e2185651f084b6a79e11ce57abe69093b7f939bb1c8786e5d233b0140e612c3728bcc6ed6c4ef67238e57f0332fa77a4c2e76db183e28b7f3cea5eab6b235b6f0cbab8035fd79b3c1990c5c3f3a56e2c7d5e4609b390ddaad8ac1c1d7024730440220036e88464b21c8bd819d97ae746622da00053ec1374a932f33aa1ab60170c9da022041cabc146ebdd12f6316a2f72f870771e8e6ff51f3cadad4027eab2e443770110121030c7196376bc1df61b6da6ee711868fd30e370dd273332bfb02a2287d11e2e9c50200282102fd481d39bdbc090313b530fddfd1aa004a9e3263da1406cf806670fdeb8ebb91ac736460b2680200282102092f44ee333630b985e490dbbc69865e499853cba15a51426d0f4e5906087e55ac736460b26802002821021dadb5ffb2cb74f5427f039e2913738e5cd8e93cc0d12db4cfa4f555005c326aac736460b26800000000").unwrap(); - let prev_outputs = - vec![ - // Added by holder - TxOut { - value: Amount::from_sat(17414236), - script_pubkey: ScriptBuf::new_p2tr_tweaked( - TweakedPublicKey::dangerous_assume_tweaked(XOnlyPublicKey::from_slice( + let prev_outputs = vec![ + // Added by holder + TxOut { + value: Amount::from_sat(17414236), + script_pubkey: ScriptBuf::new_p2tr_tweaked( + TweakedPublicKey::dangerous_assume_tweaked( + XOnlyPublicKey::from_slice( &<[u8; 32]>::from_hex( "7434164bd41e2185651f084b6a79e11ce57abe69093b7f939bb1c8786e5d233b", ) .unwrap(), - ).unwrap()), - ), - }, - // Added by remote (corresponding input should not be checked) - TxOut { - value: Amount::from_sat(227321), - script_pubkey: ScriptBuf::new_p2wpkh(&WPubkeyHash::from_byte_array( - <[u8; 20]>::from_hex("92b8c3a56fac121ddcdffbc85b02fb9ef681038a").unwrap(), - )), - }, - // Added by holder - TxOut { - value: Amount::from_sat(330), - script_pubkey: ScriptBuf::new_p2wsh(&WScriptHash::from_byte_array( - <[u8; 32]>::from_hex( - "97a4f4b73947411e18486b7182063f160f9b3a238664b91ff70a56eaffca8b9d", - ) - .unwrap(), - )), - }, - // Added by remote (corresponding input should not be checked) - TxOut { - value: Amount::from_sat(330), - script_pubkey: ScriptBuf::new_p2wsh(&WScriptHash::from_byte_array( - <[u8; 32]>::from_hex( - "0d0f49839e6bbf78271ea31d979895758ed66312b4fbab215da8a68a951f36ee", ) .unwrap(), - )), - }, - // Added by holder - TxOut { - value: Amount::from_sat(330), - script_pubkey: ScriptBuf::new_p2wsh(&WScriptHash::from_byte_array( - <[u8; 32]>::from_hex( - "f2c42991382f63a20308c35ce67133cd8564ede8f8615062d814ec69112ddd46", - ) - .unwrap(), - )), - } - ]; + ), + ), + }, + // Added by remote (corresponding input should not be checked) + TxOut { + value: Amount::from_sat(227321), + script_pubkey: ScriptBuf::new_p2wpkh(&WPubkeyHash::from_byte_array( + <[u8; 20]>::from_hex("92b8c3a56fac121ddcdffbc85b02fb9ef681038a").unwrap(), + )), + }, + // Added by holder + TxOut { + value: Amount::from_sat(330), + script_pubkey: ScriptBuf::new_p2wsh(&WScriptHash::from_byte_array( + <[u8; 32]>::from_hex( + "97a4f4b73947411e18486b7182063f160f9b3a238664b91ff70a56eaffca8b9d", + ) + .unwrap(), + )), + }, + // Added by remote (corresponding input should not be checked) + TxOut { + value: Amount::from_sat(330), + script_pubkey: ScriptBuf::new_p2wsh(&WScriptHash::from_byte_array( + <[u8; 32]>::from_hex( + "0d0f49839e6bbf78271ea31d979895758ed66312b4fbab215da8a68a951f36ee", + ) + .unwrap(), + )), + }, + // Added by holder + TxOut { + value: Amount::from_sat(330), + script_pubkey: ScriptBuf::new_p2wsh(&WScriptHash::from_byte_array( + <[u8; 32]>::from_hex( + "f2c42991382f63a20308c35ce67133cd8564ede8f8615062d814ec69112ddd46", + ) + .unwrap(), + )), + }, + ]; assert!(do_verify_tx_signatures(transaction, prev_outputs).is_ok()); } @@ -3486,30 +3513,35 @@ mod tests { // Using on-chain transaction: https://mempool.space/tx/f7636876156f3a8a48a6cddb150e07363c1641495f4b319faab1e8c4527e58db let transaction: Transaction = bitcoin::consensus::encode::deserialize_hex("02000000000102977aba41d493f93acc890e49c292dad6cbe423cb1356c6e6191cb93eed3f60c20200000000ffffffff1d956f8838a87c551c308f49fe80da594bfb888209ae8159bc77c6f471dd3b540000000000ffffffff022202000000000000225120fcb2498c6a6a335951f4c96fc89266c388e1ef4c416a2c6fca438a2f5cbb7ffe26d0030000000000225120cbc74f986822b48c4801ef5a1cadc44b27f7d23e699d8244c391d5defd69802a0141b7b9685f6b790e24392670fa06b9af34331bd3308a58b4d8b2cd86a4bcea19a2a780565b410062b58fbff026ab74513f0bac00711eba9f80e3d6b2a7cf3887a1810140a5ae4d75b89e54cfe470eb152e527a403e30b2fb3fdf5dcad1019f015827a1871431dd7202cb520ddcd3b0205cc2b9aafcb6b52522562d381d05cac4522f258100000000").unwrap(); - let prev_outputs = - vec![ + let prev_outputs = vec![ // Added by holder (SIGHASH_ALL | ACP) TxOut { value: Amount::from_sat(546), script_pubkey: ScriptBuf::new_p2tr_tweaked( - TweakedPublicKey::dangerous_assume_tweaked(XOnlyPublicKey::from_slice( - &<[u8; 32]>::from_hex( - "cbc74f986822b48c4801ef5a1cadc44b27f7d23e699d8244c391d5defd69802a", + TweakedPublicKey::dangerous_assume_tweaked( + XOnlyPublicKey::from_slice( + &<[u8; 32]>::from_hex( + "cbc74f986822b48c4801ef5a1cadc44b27f7d23e699d8244c391d5defd69802a", + ) + .unwrap(), ) .unwrap(), - ).unwrap()), + ), ), }, // Added by remote (corresponding input should not be checked) TxOut { value: Amount::from_sat(250148), script_pubkey: ScriptBuf::new_p2tr_tweaked( - TweakedPublicKey::dangerous_assume_tweaked(XOnlyPublicKey::from_slice( - &<[u8; 32]>::from_hex( - "56cee5ccf725d94a428100de365fdfa134ff4deb1a0dca14470e70b4a64ff32b", + TweakedPublicKey::dangerous_assume_tweaked( + XOnlyPublicKey::from_slice( + &<[u8; 32]>::from_hex( + "56cee5ccf725d94a428100de365fdfa134ff4deb1a0dca14470e70b4a64ff32b", + ) + .unwrap(), ) .unwrap(), - ).unwrap()), + ), ), }, ]; @@ -3576,18 +3608,20 @@ mod tests { // Using on-chain transaction: https://mempool.space/tx/d26108e025ada641e4f1163e372c74087c0e471f3756bd3c736854bee9b5a06a let transaction: Transaction = bitcoin::consensus::encode::deserialize_hex("020000000001025f17ea06dd80e90a7c59bf2710903d938561f45c08cd3187d379e988f282d3c30000000000fdffffff10146764d4bb7e5fe0503df41a042ff39b175070ab1dd05345cbe1a12ac6fbbd0100000000fdffffff01a04f020000000000220020d55050579d2bcdf9ecfdf75df7741b8ac16d572b5cdf326028b4f3538ad34b5e0140e769ec44d5e30fe84ff5d873ed20d1a8ffa8b444e208b0584e24cb94b798286f46f4ba0d4dedfa279870c6b2e43aee45802128e7227e45a043c6193743c1c3240400483045022100cdf0cedd4e35d23af24e0c786bce5bbb47147e867e72fdb49b165a0fa7cac668022035493bb8f280115846c3475f51f7e1b56ec67dfb73744faa74b47d049e20436f01473044022034e60933f7a42effe174dbbb33ec60c1e4b06df1f0356caffbfae053944b552702207b59f352bb8a6100ca14c6dc486eb17145bde714c26766cd8bc2e0a139b06789014752210329a0c88d99fa89cb9497205a237da07b26737e5382dafca6cf40a3fd454b955021032e80b176382ccb76832cd773cf76cbb89883ea74a5b1bb5fa0e30b0bfc87ed8452ae7ed70d00").unwrap(); - let prev_outputs = - vec![ + let prev_outputs = vec![ // Added by holder TxOut { value: Amount::from_sat(25841), script_pubkey: ScriptBuf::new_p2tr_tweaked( - TweakedPublicKey::dangerous_assume_tweaked(XOnlyPublicKey::from_slice( - &<[u8; 32]>::from_hex( - "ce78617dd8b31b96b24e89140639f9d87b6c6cf3b2cc8f3ff2b3afa0e505d7ec", + TweakedPublicKey::dangerous_assume_tweaked( + XOnlyPublicKey::from_slice( + &<[u8; 32]>::from_hex( + "ce78617dd8b31b96b24e89140639f9d87b6c6cf3b2cc8f3ff2b3afa0e505d7ec", + ) + .unwrap(), ) .unwrap(), - ).unwrap()), + ), ), }, // Added by remote (corresponding input should not be checked) @@ -3610,18 +3644,20 @@ mod tests { // Using on-chain transaction: https://mempool.space/tx/905ecdf95a84804b192f4dc221cfed4d77959b81ed66013a7e41a6e61e7ed530 let transaction: Transaction = bitcoin::consensus::encode::deserialize_hex("02000000000101b41b20295ac85fd2ae3e3d02900f1a1e7ddd6139b12e341386189c03d6f5795b0000000000fdffffff0100000000000000003c6a3a546878205361746f7368692120e2889e2f32316d696c20466972737420546170726f6f74206d756c7469736967207370656e64202d426974476f044123b1d4ff27b16af4b0fcb9672df671701a1a7f5a6bb7352b051f461edbc614aa6068b3e5313a174f90f3d95dc4e06f69bebd9cf5a3098fde034b01e69e8e788901400fd4a0d3f36a1f1074cb15838a48f572dc18d412d0f0f0fc1eeda9fa4820c942abb77e4d1a3c2b99ccf4ad29d9189e6e04a017fe611748464449f681bc38cf394420febe583fa77e49089f89b78fa8c116710715d6e40cc5f5a075ef1681550dd3c4ad20d0fa46cb883e940ac3dc5421f05b03859972639f51ed2eccbf3dc5a62e2e1b15ac41c02e44c9e47eaeb4bb313adecd11012dfad435cd72ce71f525329f24d75c5b9432774e148e9209baf3f1656a46986d5f38ddf4e20912c6ac28f48d6bf747469fb100000000").unwrap(); - let prev_outputs = - vec![ + let prev_outputs = vec![ // Added by holder TxOut { value: Amount::from_sat(7500), script_pubkey: ScriptBuf::new_p2tr_tweaked( - TweakedPublicKey::dangerous_assume_tweaked(XOnlyPublicKey::from_slice( - &<[u8; 32]>::from_hex( - "2fcad7470279652cc5f88b8908678d6f4d57af5627183b03fc8404cb4e16d889", + TweakedPublicKey::dangerous_assume_tweaked( + XOnlyPublicKey::from_slice( + &<[u8; 32]>::from_hex( + "2fcad7470279652cc5f88b8908678d6f4d57af5627183b03fc8404cb4e16d889", + ) + .unwrap(), ) .unwrap(), - ).unwrap()), + ), ), }, ]; diff --git a/lightning/src/ln/interception_tests.rs b/lightning/src/ln/interception_tests.rs index 5fece51c027..0c90a614163 100644 --- a/lightning/src/ln/interception_tests.rs +++ b/lightning/src/ln/interception_tests.rs @@ -181,8 +181,10 @@ fn do_test_htlc_interception_flags( assert_eq!(events.len(), 1, "{events:?}"); if let Event::HTLCIntercepted { intercept_id: id, requested_next_hop_scid, .. } = &events[0] { - assert_eq!(*requested_next_hop_scid, target_scid, - "Bitmask {flags_bitmask:#x}: Expected interception for bit {flag:?} to target SCID {target_scid}"); + assert_eq!( + *requested_next_hop_scid, target_scid, + "Bitmask {flags_bitmask:#x}: Expected interception for bit {flag:?} to target SCID {target_scid}" + ); intercept_id = *id; } else { panic!("{events:?}"); diff --git a/lightning/src/ln/invoice_utils.rs b/lightning/src/ln/invoice_utils.rs index 63ad110bba0..ad3f31deb88 100644 --- a/lightning/src/ln/invoice_utils.rs +++ b/lightning/src/ln/invoice_utils.rs @@ -9,7 +9,7 @@ use crate::prelude::*; use crate::ln::channel_state::ChannelDetails; use crate::ln::channelmanager::{ - PhantomRouteHints, MIN_CLTV_EXPIRY_DELTA, MIN_FINAL_CLTV_EXPIRY_DELTA, + MIN_CLTV_EXPIRY_DELTA, MIN_FINAL_CLTV_EXPIRY_DELTA, PhantomRouteHints, }; use crate::ln::inbound_payment::{create, create_from_hash}; use crate::routing::gossip::RoutingFees; @@ -17,7 +17,7 @@ use crate::routing::router::{RouteHint, RouteHintHop}; use crate::sign::{EntropySource, NodeSigner, Recipient}; use crate::types::payment::PaymentHash; use crate::util::logger::{Logger, Record}; -use alloc::collections::{btree_map, BTreeMap}; +use alloc::collections::{BTreeMap, btree_map}; use bitcoin::secp256k1::PublicKey; #[cfg(not(feature = "std"))] use core::iter::Iterator; @@ -355,7 +355,7 @@ fn rotate_through_iterators>(mut vecs: Vec) -> impl /// otherwise sort by highest inbound capacity to give the payment the best chance of succeeding. pub(super) fn sort_and_filter_channels( channels: Vec, min_inbound_capacity_msat: Option, logger: &L, -) -> impl ExactSizeIterator { +) -> impl ExactSizeIterator + use { let mut filtered_channels: BTreeMap = BTreeMap::new(); let min_inbound_capacity = min_inbound_capacity_msat.unwrap_or(0); let mut min_capacity_channel_exists = false; @@ -444,22 +444,30 @@ pub(super) fn sort_and_filter_channels( channel.is_announced == entry.get().is_announced && !prefer_current; if new_now_public || new_channel_preferable { - log_trace!(logger, + log_trace!( + logger, "Preferring counterparty {} channel {} (SCID {:?}, {} msats) over {} (SCID {:?}, {} msats) for invoice route hints", log_pubkey!(channel.counterparty.node_id), - &channel.channel_id, channel.short_channel_id, + &channel.channel_id, + channel.short_channel_id, channel.inbound_capacity_msat, - &entry.get().channel_id, entry.get().short_channel_id, - current_max_capacity); + &entry.get().channel_id, + entry.get().short_channel_id, + current_max_capacity + ); entry.insert(channel); } else { - log_trace!(logger, + log_trace!( + logger, "Preferring counterparty {} channel {} (SCID {:?}, {} msats) over {} (SCID {:?}, {} msats) for invoice route hints", log_pubkey!(channel.counterparty.node_id), - &entry.get().channel_id, entry.get().short_channel_id, + &entry.get().channel_id, + entry.get().short_channel_id, current_max_capacity, - &channel.channel_id, channel.short_channel_id, - channel.inbound_capacity_msat); + &channel.channel_id, + channel.short_channel_id, + channel.inbound_capacity_msat + ); } }, btree_map::Entry::Vacant(entry) => { @@ -587,8 +595,8 @@ mod test { use super::*; use crate::chain::channelmonitor::HTLC_FAIL_BACK_BUFFER; use crate::ln::channelmanager::{ - Bolt11InvoiceParameters, OptionalBolt11PaymentParams, PaymentId, PhantomRouteHints, - MIN_FINAL_CLTV_EXPIRY_DELTA, + Bolt11InvoiceParameters, MIN_FINAL_CLTV_EXPIRY_DELTA, OptionalBolt11PaymentParams, + PaymentId, PhantomRouteHints, }; use crate::ln::functional_test_utils::*; use crate::ln::msgs::{BaseMessageHandler, ChannelMessageHandler, MessageSendEvent}; @@ -600,8 +608,8 @@ mod test { use crate::util::config::UserConfig; use crate::util::dyn_signer::{DynKeysInterface, DynPhantomKeysInterface}; use crate::util::test_utils; - use bitcoin::hashes::sha256::Hash as Sha256; use bitcoin::hashes::Hash; + use bitcoin::hashes::sha256::Hash as Sha256; use bitcoin::network::Network; use core::time::Duration; use lightning_invoice::{ @@ -1297,11 +1305,7 @@ mod test { assert_eq!(events.len(), 1); let fwd_idx = match events[0] { MessageSendEvent::UpdateHTLCs { node_id, .. } => { - if node_id == nodes[1].node.get_our_node_id() { - 1 - } else { - 2 - } + if node_id == nodes[1].node.get_our_node_id() { 1 } else { 2 } }, _ => panic!("Unexpected event"), }; @@ -1527,8 +1531,8 @@ mod test { } #[test] - fn test_multi_node_hints_includes_one_channel_of_each_counterparty_nodes_per_participating_node( - ) { + fn test_multi_node_hints_includes_one_channel_of_each_counterparty_nodes_per_participating_node() + { let mut chanmon_cfgs = create_chanmon_cfgs(4); let seed_1 = [42u8; 32]; let seed_2 = [43u8; 32]; diff --git a/lightning/src/ln/max_payment_path_len_tests.rs b/lightning/src/ln/max_payment_path_len_tests.rs index 0515a5290d7..c2c41fff073 100644 --- a/lightning/src/ln/max_payment_path_len_tests.rs +++ b/lightning/src/ln/max_payment_path_len_tests.rs @@ -10,11 +10,11 @@ //! Tests for calculating the maximum length of a path based on the payment metadata, custom TLVs, //! and/or blinded paths present. +use crate::blinded_path::BlindedHop; use crate::blinded_path::payment::{ BlindedPayInfo, BlindedPaymentPath, Bolt12RefundContext, PaymentConstraints, PaymentContext, ReceiveTlvs, }; -use crate::blinded_path::BlindedHop; use crate::events::Event; use crate::ln::blinded_payment_tests::get_blinded_route_parameters; use crate::ln::channelmanager::{OptionalOfferPaymentParams, PaymentId}; @@ -28,7 +28,7 @@ use crate::ln::outbound_payment::{ }; use crate::prelude::*; use crate::routing::router::{ - PaymentParameters, RouteParameters, DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA, + DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA, PaymentParameters, RouteParameters, }; use crate::sign::NodeSigner; use crate::types::features::BlindedHopFeatures; @@ -78,12 +78,12 @@ fn large_payment_metadata() { - 2 // onion payload varint prefix increased ser size due to metadata - PAYLOAD_HMAC_LEN - final_payload_len_without_metadata; - let mut payment_metadata = vec![42; max_metadata_len]; + let payment_metadata = vec![42; max_metadata_len]; // Check that the maximum-size metadata is sendable. let (mut route_0_1, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(&nodes[0], &nodes[1], amt_msat); - let mut max_sized_onion = RecipientOnionFields { + let max_sized_onion = RecipientOnionFields { payment_secret: Some(payment_secret), payment_metadata: Some(payment_metadata.clone()), custom_tlvs: Vec::new(), @@ -112,7 +112,7 @@ fn large_payment_metadata() { // Check that the payment parameter for max path length will prevent us from routing past our // next-hop peer given the payment_metadata size. - let (mut route_0_2, payment_hash_2, payment_preimage_2, payment_secret_2) = + let (route_0_2, payment_hash_2, payment_preimage_2, payment_secret_2) = get_route_and_payment_hash!(&nodes[0], &nodes[2], amt_msat); let mut route_params_0_2 = route_0_2.route_params.clone().unwrap(); route_params_0_2.payment_params.max_path_length = 1; @@ -128,7 +128,7 @@ fn large_payment_metadata() { // If our payment_metadata contains 1 additional byte, we'll fail prior to pathfinding. let mut too_large_onion = max_sized_onion.clone(); - too_large_onion.payment_metadata.as_mut().map(|mut md| md.push(42)); + too_large_onion.payment_metadata.as_mut().map(|md| md.push(42)); too_large_onion.total_mpp_amount_msat = MIN_FINAL_VALUE_ESTIMATE_WITH_OVERPAY; // First confirm we'll fail to create the onion packet directly. @@ -164,7 +164,7 @@ fn large_payment_metadata() { // If we remove enough payment_metadata bytes to allow for 2 hops, we're now able to send to // nodes[2]. let two_hop_metadata = vec![42; max_metadata_len - INTERMED_PAYLOAD_LEN_ESTIMATE]; - let mut onion_allowing_2_hops = RecipientOnionFields { + let onion_allowing_2_hops = RecipientOnionFields { payment_secret: Some(payment_secret_2), payment_metadata: Some(two_hop_metadata.clone()), custom_tlvs: Vec::new(), @@ -225,7 +225,7 @@ fn one_hop_blinded_path_with_custom_tlv() { payment_context: PaymentContext::Bolt12Refund(Bolt12RefundContext {}), }; let receive_auth_key = chanmon_cfgs[2].keys_manager.get_receive_auth_key(); - let mut secp_ctx = Secp256k1::new(); + let secp_ctx = Secp256k1::new(); let blinded_path = BlindedPaymentPath::new( &[], nodes[2].node.get_our_node_id(), diff --git a/lightning/src/ln/mod.rs b/lightning/src/ln/mod.rs index d6e0b92f1d0..d349b90ca7f 100644 --- a/lightning/src/ln/mod.rs +++ b/lightning/src/ln/mod.rs @@ -48,78 +48,53 @@ pub mod wire; #[allow(dead_code)] // TODO(dual_funding): Remove once contribution to V2 channels is enabled. pub(crate) mod interactivetxs; -// Older rustc (which we support) refuses to let us call the get_payment_preimage_hash!() macro -// without the node parameter being mut. This is incorrect, and thus newer rustcs will complain -// about an unnecessary mut. Thus, we silence the unused_mut warning in two test modules below. - #[cfg(test)] mod accountable_tests; #[cfg(test)] -#[allow(unused_mut)] mod async_payments_tests; #[cfg(test)] -#[allow(unused_mut)] mod async_signer_tests; #[cfg(test)] -#[allow(unused_mut)] mod blinded_payment_tests; #[cfg(test)] -#[allow(unused_mut)] pub mod bolt11_payment_tests; #[cfg(test)] -#[allow(unused_mut)] mod chanmon_update_fail_tests; #[cfg(test)] -#[allow(unused_mut)] mod channel_open_tests; #[cfg(test)] -#[allow(unused_mut)] mod channel_type_tests; #[cfg(test)] -#[allow(unused_mut)] mod dual_funding_tests; #[cfg(any(test, feature = "_externalize_tests"))] -#[allow(unused_mut)] pub mod functional_tests; #[cfg(any(test, feature = "_externalize_tests"))] -#[allow(unused_mut)] pub mod htlc_reserve_unit_tests; #[cfg(any(test, feature = "_externalize_tests"))] -#[allow(unused_mut)] pub mod interception_tests; #[cfg(test)] -#[allow(unused_mut)] mod max_payment_path_len_tests; #[cfg(test)] -#[allow(unused_mut)] mod monitor_tests; #[cfg(test)] -#[allow(unused_mut)] mod offers_tests; #[cfg(test)] -#[allow(unused_mut)] mod onion_route_tests; #[cfg(test)] -#[allow(unused_mut)] mod payment_tests; #[cfg(test)] -#[allow(unused_mut)] mod priv_short_conf_tests; #[cfg(test)] mod quiescence_tests; #[cfg(test)] -#[allow(unused_mut)] mod reload_tests; #[cfg(test)] -#[allow(unused_mut)] mod reorg_tests; #[cfg(test)] -#[allow(unused_mut)] mod shutdown_tests; #[cfg(any(feature = "_test_utils", test))] pub mod splicing_tests; #[cfg(any(test, feature = "_externalize_tests"))] -#[allow(unused_mut)] pub mod update_fee_tests; #[cfg(test)] mod zero_fee_commitment_tests; diff --git a/lightning/src/ln/monitor_tests.rs b/lightning/src/ln/monitor_tests.rs index f52f093917b..3fa79fbb6d2 100644 --- a/lightning/src/ln/monitor_tests.rs +++ b/lightning/src/ln/monitor_tests.rs @@ -61,7 +61,7 @@ fn chanmon_fail_from_stale_commitment() { let chanmon_cfgs = create_chanmon_cfgs(3); let node_cfgs = create_node_cfgs(3, &chanmon_cfgs); let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]); - let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs); + let nodes = create_network(3, &node_cfgs, &node_chanmgrs); create_announced_chan_between_nodes(&nodes, 0, 1); let (update_a, _, chan_id_2, _) = create_announced_chan_between_nodes(&nodes, 1, 2); @@ -175,9 +175,9 @@ fn archive_fully_resolved_monitors() { // Test we archive fully resolved channel monitors at the right time. let chanmon_cfgs = create_chanmon_cfgs(2); let node_cfgs = create_node_cfgs(2, &chanmon_cfgs); - let mut user_config = test_legacy_channel_config(); + let user_config = test_legacy_channel_config(); let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(user_config.clone()), Some(user_config)]); - let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs); + let nodes = create_network(2, &node_cfgs, &node_chanmgrs); let (_, _, chan_id, funding_tx) = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 1_000_000); @@ -650,13 +650,13 @@ fn do_test_claim_value_force_close(keyed_anchors: bool, p2a_anchor: bool, prev_c match events.pop().unwrap() { Event::BumpTransaction(bump_event) => { let mut first_htlc_event = bump_event.clone(); - if let BumpTransactionEvent::HTLCResolution { ref mut htlc_descriptors, .. } = &mut first_htlc_event { + if let BumpTransactionEvent::HTLCResolution { htlc_descriptors, .. } = &mut first_htlc_event { htlc_descriptors.remove(1); } else { panic!("Unexpected event"); } let mut second_htlc_event = bump_event; - if let BumpTransactionEvent::HTLCResolution { ref mut htlc_descriptors, .. } = &mut second_htlc_event { + if let BumpTransactionEvent::HTLCResolution { htlc_descriptors, .. } = &mut second_htlc_event { htlc_descriptors.remove(0); } else { panic!("Unexpected event"); @@ -870,7 +870,7 @@ fn do_test_balances_on_local_commitment_htlcs(keyed_anchors: bool, p2a_anchor: b user_config.channel_handshake_config.negotiate_anchors_zero_fee_htlc_tx = keyed_anchors; user_config.channel_handshake_config.negotiate_anchor_zero_fee_commitments = p2a_anchor; let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(user_config.clone()), Some(user_config)]); - let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs); + let nodes = create_network(2, &node_cfgs, &node_chanmgrs); let coinbase_tx = provide_anchor_reserves(&nodes); @@ -941,7 +941,7 @@ fn do_test_balances_on_local_commitment_htlcs(keyed_anchors: bool, p2a_anchor: b if keyed_anchors || p2a_anchor { handle_bump_close_event(&nodes[0]); } - let mut txn = nodes[0].tx_broadcaster.txn_broadcast(); + let txn = nodes[0].tx_broadcaster.txn_broadcast(); assert_eq!(txn.len(), if keyed_anchors || p2a_anchor { 2 } else { 1 }); assert_eq!(txn[0].compute_txid(), commitment_tx.compute_txid()); if p2a_anchor { @@ -1123,7 +1123,7 @@ fn test_no_preimage_inbound_htlc_balances() { let node_cfgs = create_node_cfgs(2, &chanmon_cfgs); let legacy_cfg = test_legacy_channel_config(); let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(legacy_cfg.clone()), Some(legacy_cfg)]); - let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs); + let nodes = create_network(2, &node_cfgs, &node_chanmgrs); let (_, _, chan_id, funding_tx) = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 500_000_000); @@ -1621,7 +1621,7 @@ fn do_test_revoked_counterparty_commitment_balances(keyed_anchors: bool, p2a_anc test_spendable_output(&nodes[1], &as_revoked_txn[0], false); check_added_monitors(&nodes[1], 0); - let mut payment_failed_events = nodes[1].node.get_and_clear_pending_events(); + let payment_failed_events = nodes[1].node.get_and_clear_pending_events(); check_added_monitors(&nodes[1], 2); expect_payment_failed_conditions_event(payment_failed_events[..2].to_vec(), missing_htlc_payment_hash, false, PaymentFailedConditions::new()); @@ -1632,7 +1632,7 @@ fn do_test_revoked_counterparty_commitment_balances(keyed_anchors: bool, p2a_anc if confirm_htlc_spend_first { test_spendable_output(&nodes[1], &claim_txn[0], false); check_added_monitors(&nodes[1], 0); - let mut payment_failed_events = nodes[1].node.get_and_clear_pending_events(); + let payment_failed_events = nodes[1].node.get_and_clear_pending_events(); check_added_monitors(&nodes[1], 2); expect_payment_failed_conditions_event(payment_failed_events[..2].to_vec(), live_payment_hash, false, PaymentFailedConditions::new()); @@ -1647,7 +1647,7 @@ fn do_test_revoked_counterparty_commitment_balances(keyed_anchors: bool, p2a_anc } else { test_spendable_output(&nodes[1], &claim_txn[0], false); check_added_monitors(&nodes[1], 0); - let mut payment_failed_events = nodes[1].node.get_and_clear_pending_events(); + let payment_failed_events = nodes[1].node.get_and_clear_pending_events(); check_added_monitors(&nodes[1], 2); expect_payment_failed_conditions_event(payment_failed_events[..2].to_vec(), live_payment_hash, false, PaymentFailedConditions::new()); @@ -2046,7 +2046,7 @@ fn do_test_revoked_counterparty_aggregated_claims(keyed_anchors: bool, p2a_ancho check_closed_event(&nodes[1], 1, ClosureReason::CommitmentTxConfirmed, &[nodes[0].node.get_our_node_id()], 1000000); check_added_monitors(&nodes[1], 1); - let mut claim_txn = nodes[1].tx_broadcaster.txn_broadcast(); + let claim_txn = nodes[1].tx_broadcaster.txn_broadcast(); assert_eq!(claim_txn.len(), 2); // One unpinnable revoked to_self output. assert_eq!(claim_txn[0].input.len(), 1); @@ -2099,7 +2099,7 @@ fn do_test_revoked_counterparty_aggregated_claims(keyed_anchors: bool, p2a_ancho mine_transaction(&nodes[1], &htlc_success_claim); expect_payment_sent(&nodes[1], claimed_payment_preimage, None, true, true); - let mut claim_txn_2 = nodes[1].tx_broadcaster.txn_broadcast(); + let claim_txn_2 = nodes[1].tx_broadcaster.txn_broadcast(); // Once B sees the HTLC-Success transaction it splits its claim transaction into two, though in // theory it could re-aggregate the claims as well. assert_eq!(claim_txn_2.len(), 2); @@ -2243,7 +2243,7 @@ fn do_test_claimable_balance_correct_while_payment_pending(outbound_payment: boo // is pending. // // This tests that we get the correct balance in either of the cases above. - let mut chanmon_cfgs = create_chanmon_cfgs(3); + let chanmon_cfgs = create_chanmon_cfgs(3); let node_cfgs = create_node_cfgs(3, &chanmon_cfgs); let mut user_config = test_default_channel_config(); user_config.channel_handshake_config.negotiate_anchors_zero_fee_htlc_tx = keyed_anchors; @@ -2391,7 +2391,7 @@ fn test_restored_packages_retry() { fn do_test_monitor_rebroadcast_pending_claims(keyed_anchors: bool, p2a_anchor: bool) { // Test that we will retry broadcasting pending claims for a force-closed channel on every // `ChainMonitor::rebroadcast_pending_claims` call. - let mut chanmon_cfgs = create_chanmon_cfgs(2); + let chanmon_cfgs = create_chanmon_cfgs(2); let node_cfgs = create_node_cfgs(2, &chanmon_cfgs); let mut config = test_default_channel_config(); config.channel_handshake_config.negotiate_anchors_zero_fee_htlc_tx = keyed_anchors; @@ -2515,7 +2515,7 @@ fn do_test_yield_anchors_events(have_htlcs: bool, p2a_anchor: bool) { // allowing the consumer to provide additional fees to the commitment transaction to be // broadcast. Once the commitment transaction confirms, events for the HTLC resolution should be // emitted by LDK, such that the consumer can attach fees to the zero fee HTLC transactions. - let mut chanmon_cfgs = create_chanmon_cfgs(2); + let chanmon_cfgs = create_chanmon_cfgs(2); let node_cfgs = create_node_cfgs(2, &chanmon_cfgs); let mut anchors_config = test_default_channel_config(); anchors_config.channel_handshake_config.announce_for_forwarding = true; @@ -2641,7 +2641,7 @@ fn do_test_yield_anchors_events(have_htlcs: bool, p2a_anchor: bool) { if nodes[1].connect_style.borrow().updates_best_block_first() { handle_bump_close_event(&nodes[1]); } - let mut txn = nodes[1].tx_broadcaster.unique_txn_broadcast(); + let txn = nodes[1].tx_broadcaster.unique_txn_broadcast(); // Both HTLC claims are pinnable at this point, // and will be broadcast in a single transaction. assert_eq!(txn.len(), if nodes[1].connect_style.borrow().updates_best_block_first() { 3 } else { 1 }); @@ -3121,7 +3121,7 @@ fn do_test_monitor_claims_with_random_signatures(keyed_anchors: bool, p2a_anchor user_config.channel_handshake_config.negotiate_anchors_zero_fee_htlc_tx = keyed_anchors; user_config.channel_handshake_config.negotiate_anchor_zero_fee_commitments = p2a_anchor; let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(user_config.clone()), Some(user_config)]); - let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs); + let nodes = create_network(2, &node_cfgs, &node_chanmgrs); let coinbase_tx = provide_anchor_reserves(&nodes); @@ -3203,7 +3203,7 @@ fn do_test_monitor_claims_with_random_signatures(keyed_anchors: bool, p2a_anchor handle_bump_htlc_event(&nodes[0], 1); } { - let mut txn = nodes[0].tx_broadcaster.txn_broadcast(); + let txn = nodes[0].tx_broadcaster.txn_broadcast(); assert_eq!(txn.len(), 1); assert_eq!(txn[0].compute_txid(), htlc_timeout_tx.compute_txid()); assert_ne!(txn[0].compute_wtxid(), htlc_timeout_tx.compute_wtxid()); @@ -3480,7 +3480,7 @@ fn do_test_lost_preimage_monitor_events(on_counterparty_tx: bool, p2a_anchor: bo }; mine_transaction(&nodes[2], selected_commit_tx); - let mut cs_transactions = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0); + let cs_transactions = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0); let c_replays_commitment = nodes[2].connect_style.borrow().updates_best_block_first(); let cs_htlc_claims = if on_counterparty_tx { assert_eq!(cs_transactions.len(), 0); @@ -3706,7 +3706,7 @@ fn do_test_lost_timeout_monitor_events(confirm_tx: CommitmentType, dust_htlcs: b } connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1); - let mut events = nodes[1].chain_monitor.chain_monitor.get_and_clear_pending_events(); + let events = nodes[1].chain_monitor.chain_monitor.get_and_clear_pending_events(); match confirm_tx { CommitmentType::LocalWithoutLastHTLC|CommitmentType::LocalWithLastHTLC => { assert_eq!(events.len(), 0, "{events:?}"); @@ -3837,7 +3837,7 @@ fn test_ladder_preimage_htlc_claims() { let node_cfgs = create_node_cfgs(2, &chanmon_cfgs); let legacy_cfg = test_legacy_channel_config(); let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(legacy_cfg.clone()), Some(legacy_cfg)]); - let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs); + let nodes = create_network(2, &node_cfgs, &node_chanmgrs); let node_id_0 = nodes[0].node.get_our_node_id(); let node_id_1 = nodes[1].node.get_our_node_id(); diff --git a/lightning/src/ln/msgs.rs b/lightning/src/ln/msgs.rs index 6210d26893a..d3d38bd58db 100644 --- a/lightning/src/ln/msgs.rs +++ b/lightning/src/ln/msgs.rs @@ -27,9 +27,9 @@ use bitcoin::constants::ChainHash; use bitcoin::hash_types::Txid; use bitcoin::script::ScriptBuf; -use bitcoin::secp256k1::ecdsa::Signature; use bitcoin::secp256k1::PublicKey; -use bitcoin::{secp256k1, Transaction, Witness}; +use bitcoin::secp256k1::ecdsa::Signature; +use bitcoin::{Transaction, Witness, secp256k1}; use crate::blinded_path::message::BlindedMessagePath; use crate::blinded_path::payment::{BlindedPaymentTlvs, DummyTlvs, ForwardTlvs, ReceiveTlvs}; @@ -1214,9 +1214,14 @@ pub enum SocketAddressParseError { impl fmt::Display for SocketAddressParseError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { - SocketAddressParseError::SocketAddrParse => write!(f, "Socket address (IPv4/IPv6) parsing error"), - SocketAddressParseError::InvalidInput => write!(f, "Invalid input format. \ - Expected: \":\", \"[]:\", \".onion:\" or \":\""), + SocketAddressParseError::SocketAddrParse => { + write!(f, "Socket address (IPv4/IPv6) parsing error") + }, + SocketAddressParseError::InvalidInput => write!( + f, + "Invalid input format. \ + Expected: \":\", \"[]:\", \".onion:\" or \":\"" + ), SocketAddressParseError::InvalidPort => write!(f, "Invalid port"), SocketAddressParseError::InvalidOnionV3 => write!(f, "Invalid onion v3 address"), } @@ -1266,7 +1271,7 @@ impl std::net::ToSocketAddrs for SocketAddress { let socket_addr = SocketAddr::new(ip_addr.into(), *port); Ok(vec![socket_addr].into_iter()) }, - SocketAddress::Hostname { ref hostname, port } => { + SocketAddress::Hostname { hostname, port } => { (hostname.as_str(), *port).to_socket_addrs() }, SocketAddress::OnionV2(..) => Err(std::io::Error::other( @@ -1311,27 +1316,40 @@ pub fn parse_onion_address( impl Display for SocketAddress { fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { match self { - SocketAddress::TcpIpV4{addr, port} => write!( - f, "{}.{}.{}.{}:{}", addr[0], addr[1], addr[2], addr[3], port)?, - SocketAddress::TcpIpV6{addr, port} => write!( + SocketAddress::TcpIpV4 { addr, port } => { + write!(f, "{}.{}.{}.{}:{}", addr[0], addr[1], addr[2], addr[3], port)? + }, + SocketAddress::TcpIpV6 { addr, port } => write!( f, "[{:02x}{:02x}:{:02x}{:02x}:{:02x}{:02x}:{:02x}{:02x}:{:02x}{:02x}:{:02x}{:02x}:{:02x}{:02x}:{:02x}{:02x}]:{}", - addr[0], addr[1], addr[2], addr[3], addr[4], addr[5], addr[6], addr[7], addr[8], addr[9], addr[10], addr[11], addr[12], addr[13], addr[14], addr[15], port + addr[0], + addr[1], + addr[2], + addr[3], + addr[4], + addr[5], + addr[6], + addr[7], + addr[8], + addr[9], + addr[10], + addr[11], + addr[12], + addr[13], + addr[14], + addr[15], + port )?, SocketAddress::OnionV2(bytes) => write!(f, "OnionV2({:?})", bytes)?, - SocketAddress::OnionV3 { - ed25519_pubkey, - checksum, - version, - port, - } => { + SocketAddress::OnionV3 { ed25519_pubkey, checksum, version, port } => { let mut addr = Vec::with_capacity(35); addr.extend_from_slice(ed25519_pubkey); let [c0, c1] = checksum.to_be_bytes(); addr.push(c0); addr.push(c1); addr.push(*version); - let onion = base32::Alphabet::RFC4648 { padding: false }.encode(&addr).to_lowercase(); + let onion = + base32::Alphabet::RFC4648 { padding: false }.encode(&addr).to_lowercase(); write!(f, "{}.onion:{}", onion, port)? }, SocketAddress::Hostname { hostname, port } => write!(f, "{}:{}", hostname, port)?, @@ -1381,9 +1399,9 @@ pub enum UnsignedGossipMessage<'a> { impl<'a> Writeable for UnsignedGossipMessage<'a> { fn write(&self, writer: &mut W) -> Result<(), io::Error> { match self { - UnsignedGossipMessage::ChannelAnnouncement(ref msg) => msg.write(writer), - UnsignedGossipMessage::ChannelUpdate(ref msg) => msg.write(writer), - UnsignedGossipMessage::NodeAnnouncement(ref msg) => msg.write(writer), + UnsignedGossipMessage::ChannelAnnouncement(msg) => msg.write(writer), + UnsignedGossipMessage::ChannelUpdate(msg) => msg.write(writer), + UnsignedGossipMessage::NodeAnnouncement(msg) => msg.write(writer), } } } @@ -2050,7 +2068,7 @@ pub trait BaseMessageHandler { /// /// [`Self::peer_disconnected`] will not be called if `Err(())` is returned. fn peer_connected(&self, their_node_id: PublicKey, msg: &Init, inbound: bool) - -> Result<(), ()>; + -> Result<(), ()>; } impl> BaseMessageHandler for B { @@ -2753,9 +2771,9 @@ pub struct OnionPacket { } impl onion_utils::Packet for OnionPacket { - type Data = onion_utils::FixedSizeOnionPacket; - fn new(pubkey: PublicKey, hop_data: onion_utils::FixedSizeOnionPacket, hmac: [u8; 32]) -> Self { - Self { version: 0, public_key: Ok(pubkey), hop_data: hop_data.0, hmac } + type Data = [u8; onion_utils::ONION_DATA_LEN]; + fn new(pubkey: PublicKey, hop_data: [u8; onion_utils::ONION_DATA_LEN], hmac: [u8; 32]) -> Self { + Self { version: 0, public_key: Ok(pubkey), hop_data, hmac } } } @@ -3616,8 +3634,8 @@ impl<'a> Writeable for OutboundOnionPayload<'a> { Self::TrampolineEntrypoint { amt_to_forward, outgoing_cltv_value, - ref multipath_trampoline_data, - ref trampoline_packet, + multipath_trampoline_data, + trampoline_packet, } => { _encode_varint_length_prefixed_tlv!(w, { (2, HighZeroBytesDroppedBigSize(*amt_to_forward), required), @@ -3630,8 +3648,8 @@ impl<'a> Writeable for OutboundOnionPayload<'a> { amt_to_forward, outgoing_cltv_value, current_path_key, - ref multipath_trampoline_data, - ref trampoline_packet, + multipath_trampoline_data, + trampoline_packet, } => { _encode_varint_length_prefixed_tlv!(w, { (2, HighZeroBytesDroppedBigSize(*amt_to_forward), required), @@ -3642,12 +3660,12 @@ impl<'a> Writeable for OutboundOnionPayload<'a> { }); }, Self::Receive { - ref payment_data, - ref payment_metadata, - ref keysend_preimage, + payment_data, + payment_metadata, + keysend_preimage, sender_intended_htlc_amt_msat, cltv_expiry_height, - ref custom_tlvs, + custom_tlvs, } => { // We need to update [`ln::outbound_payment::RecipientOnionFields::with_custom_tlvs`] // to reject any reserved types in the experimental range if new ones are ever @@ -3676,8 +3694,8 @@ impl<'a> Writeable for OutboundOnionPayload<'a> { encrypted_tlvs, intro_node_blinding_point, keysend_preimage, - ref invoice_request, - ref custom_tlvs, + invoice_request, + custom_tlvs, } => { // We need to update [`ln::outbound_payments::RecipientCustomTlvs::new`] // to reject any reserved types in the experimental range if new ones are ever @@ -3714,11 +3732,7 @@ impl<'a> Writeable for OutboundTrampolinePayload<'a> { }); }, #[cfg(test)] - Self::Receive { - ref payment_data, - sender_intended_htlc_amt_msat, - cltv_expiry_height, - } => { + Self::Receive { payment_data, sender_intended_htlc_amt_msat, cltv_expiry_height } => { _encode_varint_length_prefixed_tlv!(w, { (2, HighZeroBytesDroppedBigSize(*sender_intended_htlc_amt_msat), required), (4, HighZeroBytesDroppedBigSize(*cltv_expiry_height), required), @@ -3868,7 +3882,8 @@ impl ReadableArgs<(Option, NS)> for InboundOnionPaylo used_aad, } => { if amt.is_some() - || cltv_value.is_some() || total_msat.is_some() + || cltv_value.is_some() + || total_msat.is_some() || keysend_preimage.is_some() || invoice_request.is_some() || used_aad != TriPolyAADUsed::None @@ -3890,7 +3905,8 @@ impl ReadableArgs<(Option, NS)> for InboundOnionPaylo used_aad, } => { if amt.is_some() - || cltv_value.is_some() || total_msat.is_some() + || cltv_value.is_some() + || total_msat.is_some() || keysend_preimage.is_some() || invoice_request.is_some() || used_aad == TriPolyAADUsed::None @@ -4038,7 +4054,8 @@ impl ReadableArgs<(Option, NS)> for InboundTrampoline used_aad, } => { if amt.is_some() - || cltv_value.is_some() || total_msat.is_some() + || cltv_value.is_some() + || total_msat.is_some() || keysend_preimage.is_some() || invoice_request.is_some() || used_aad != TriPolyAADUsed::None @@ -5702,7 +5719,10 @@ mod tests { require_confirmed_inputs: Some(()), }; let encoded_value = splice_init.encode(); - assert_eq!(encoded_value.as_hex().to_string(), "0202020202020202020202020202020202020202020202020202020202020202fffffffffffe1dc0000007d000000000031b84c5567b126440995d3ed5aaba0565d71e1834604819ff9c17f5e9d5dd078f0200"); + assert_eq!( + encoded_value.as_hex().to_string(), + "0202020202020202020202020202020202020202020202020202020202020202fffffffffffe1dc0000007d000000000031b84c5567b126440995d3ed5aaba0565d71e1834604819ff9c17f5e9d5dd078f0200" + ); } #[test] @@ -5736,7 +5756,10 @@ mod tests { require_confirmed_inputs: Some(()), }; let encoded_value = splice_ack.encode(); - assert_eq!(encoded_value.as_hex().to_string(), "0202020202020202020202020202020202020202020202020202020202020202fffffffffffe1dc0031b84c5567b126440995d3ed5aaba0565d71e1834604819ff9c17f5e9d5dd078f0200"); + assert_eq!( + encoded_value.as_hex().to_string(), + "0202020202020202020202020202020202020202020202020202020202020202fffffffffffe1dc0031b84c5567b126440995d3ed5aaba0565d71e1834604819ff9c17f5e9d5dd078f0200" + ); } #[test] @@ -5749,7 +5772,10 @@ mod tests { .unwrap(), }; let encoded_value = splice_locked.encode(); - assert_eq!(encoded_value.as_hex().to_string(), "02020202020202020202020202020202020202020202020202020202020202026e96fe9f8b0ddcd729ba03cfafa5a27b050b39d354dd980814268dfa9a44d4c2"); + assert_eq!( + encoded_value.as_hex().to_string(), + "02020202020202020202020202020202020202020202020202020202020202026e96fe9f8b0ddcd729ba03cfafa5a27b050b39d354dd980814268dfa9a44d4c2" + ); } #[test] @@ -5988,7 +6014,10 @@ mod tests { fn encoding_tx_abort() { let tx_abort = msgs::TxAbort { channel_id: ChannelId::from_bytes([2; 32]), - data: >::from_hex("54686520717569636B2062726F776E20666F78206A756D7073206F76657220746865206C617A7920646F672E").unwrap(), + data: >::from_hex( + "54686520717569636B2062726F776E20666F78206A756D7073206F76657220746865206C617A7920646F672E", + ) + .unwrap(), }; let encoded_value = tx_abort.encode(); let target_value = >::from_hex("0202020202020202020202020202020202020202020202020202020202020202002C54686520717569636B2062726F776E20666F78206A756D7073206F76657220746865206C617A7920646F672E").unwrap(); @@ -6260,11 +6289,18 @@ mod tests { #[test] fn encoding_init() { let mainnet_hash = ChainHash::using_genesis_block(Network::Bitcoin); - assert_eq!(msgs::Init { - features: InitFeatures::from_le_bytes(vec![0xFF, 0xFF, 0xFF]), - networks: Some(vec![mainnet_hash]), - remote_network_address: None, - }.encode(), >::from_hex("00023fff0003ffffff01206fe28c0ab6f1b372c1a6a246ae63f74f931e8365e15a089c68d6190000000000").unwrap()); + assert_eq!( + msgs::Init { + features: InitFeatures::from_le_bytes(vec![0xFF, 0xFF, 0xFF]), + networks: Some(vec![mainnet_hash]), + remote_network_address: None, + } + .encode(), + >::from_hex( + "00023fff0003ffffff01206fe28c0ab6f1b372c1a6a246ae63f74f931e8365e15a089c68d6190000000000" + ) + .unwrap() + ); assert_eq!( msgs::Init { features: InitFeatures::from_le_bytes(vec![0xFF]), @@ -6300,7 +6336,10 @@ mod tests { }), }; let encoded_value = init_msg.encode(); - let target_value = >::from_hex("0000000001206fe28c0ab6f1b372c1a6a246ae63f74f931e8365e15a089c68d61900000000000307017f00000103e8").unwrap(); + let target_value = >::from_hex( + "0000000001206fe28c0ab6f1b372c1a6a246ae63f74f931e8365e15a089c68d61900000000000307017f00000103e8", + ) + .unwrap(); assert_eq!(encoded_value, target_value); assert_eq!( msgs::Init::read_from_fixed_length_buffer(&mut &target_value[..]).unwrap(), @@ -6479,11 +6518,13 @@ mod tests { }; let encoded_value = msg.encode(); let node_signer = test_utils::TestKeysInterface::new(&[42; 32], Network::Testnet); - assert!(msgs::InboundOnionPayload::read( - &mut Cursor::new(&encoded_value[..]), - (None, &node_signer) - ) - .is_err()); + assert!( + msgs::InboundOnionPayload::read( + &mut Cursor::new(&encoded_value[..]), + (None, &node_signer) + ) + .is_err() + ); let good_type_range_tlvs = vec![((1 << 16) - 3, vec![42]), ((1 << 16) - 1, vec![42; 32])]; if let msgs::OutboundOnionPayload::Receive { ref mut custom_tlvs, .. } = msg { *custom_tlvs = &good_type_range_tlvs; @@ -6512,7 +6553,10 @@ mod tests { cltv_expiry_height: 0xffffffff, }; let encoded_value = msg.encode(); - let target_value = >::from_hex("2e02080badf00d010203040404ffffffffff0000000146c6616b021234ff0000000146c6616f084242424242424242").unwrap(); + let target_value = >::from_hex( + "2e02080badf00d010203040404ffffffffff0000000146c6616b021234ff0000000146c6616f084242424242424242", + ) + .unwrap(); assert_eq!(encoded_value, target_value); let node_signer = test_utils::TestKeysInterface::new(&[42; 32], Network::Testnet); let inbound_msg: msgs::InboundOnionPayload = @@ -6648,7 +6692,10 @@ mod tests { invoice_features: Some(trampoline_features), }; let serialized_payload = trampoline_payload.encode().to_lower_hex_string(); - assert_eq!(serialized_payload, "71020408f0d18004030c35001503020000165f032c0b7cf95324a07d05398b240174dc0c2be444d96b159aa6c7f7b1e66868099102eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f28368661900000001f4000003e800240000000000000001000000001dcd65000000"); + assert_eq!( + serialized_payload, + "71020408f0d18004030c35001503020000165f032c0b7cf95324a07d05398b240174dc0c2be444d96b159aa6c7f7b1e66868099102eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f28368661900000001f4000003e800240000000000000001000000001dcd65000000" + ); } #[test] @@ -6663,14 +6710,20 @@ mod tests { custom_tlvs: &vec![], }; let eve_payload = trampoline_payload_eve.encode().to_lower_hex_string(); - assert_eq!(eve_payload, "e4020408f0d18004030c35000ad1bcd747394fbd4d99588da075a623316e15a576df5bc785cccc7cd6ec7b398acce6faf520175f9ec920f2ef261cdb83dc28cc3a0eeb970107b3306489bf771ef5b1213bca811d345285405861d08a655b6c237fa247a8b4491beee20c878a60e9816492026d8feb9dafa84585b253978db6a0aa2945df5ef445c61e801fb82f43d5f00716baf9fc9b3de50bc22950a36bda8fc27bfb1242e5860c7e687438d4133e058770361a19b6c271a2a07788d34dccc27e39b9829b061a4d960eac4a2c2b0f4de506c24f9af3868c0aff6dda27281c120408f0d180"); + assert_eq!( + eve_payload, + "e4020408f0d18004030c35000ad1bcd747394fbd4d99588da075a623316e15a576df5bc785cccc7cd6ec7b398acce6faf520175f9ec920f2ef261cdb83dc28cc3a0eeb970107b3306489bf771ef5b1213bca811d345285405861d08a655b6c237fa247a8b4491beee20c878a60e9816492026d8feb9dafa84585b253978db6a0aa2945df5ef445c61e801fb82f43d5f00716baf9fc9b3de50bc22950a36bda8fc27bfb1242e5860c7e687438d4133e058770361a19b6c271a2a07788d34dccc27e39b9829b061a4d960eac4a2c2b0f4de506c24f9af3868c0aff6dda27281c120408f0d180" + ); let trampoline_payload_dave = OutboundTrampolinePayload::BlindedForward { encrypted_tlvs: &>::from_hex("0ccf3c8a58deaa603f657ee2a5ed9d604eb5c8ca1e5f801989afa8f3ea6d789bbdde2c7e7a1ef9ca8c38d2c54760febad8446d3f273ddb537569ef56613846ccd3aba78a").unwrap(), intro_node_blinding_point: Some(PublicKey::from_slice(&>::from_hex("02988face71e92c345a068f740191fd8e53be14f0bb957ef730d3c5f76087b960e").unwrap()).unwrap()), }; let dave_payload = trampoline_payload_dave.encode().to_lower_hex_string(); - assert_eq!(dave_payload, "690a440ccf3c8a58deaa603f657ee2a5ed9d604eb5c8ca1e5f801989afa8f3ea6d789bbdde2c7e7a1ef9ca8c38d2c54760febad8446d3f273ddb537569ef56613846ccd3aba78a0c2102988face71e92c345a068f740191fd8e53be14f0bb957ef730d3c5f76087b960e") + assert_eq!( + dave_payload, + "690a440ccf3c8a58deaa603f657ee2a5ed9d604eb5c8ca1e5f801989afa8f3ea6d789bbdde2c7e7a1ef9ca8c38d2c54760febad8446d3f273ddb537569ef56613846ccd3aba78a0c2102988face71e92c345a068f740191fd8e53be14f0bb957ef730d3c5f76087b960e" + ) } #[test] @@ -6943,10 +6996,12 @@ mod tests { SocketAddress::from_str("127.0.0.1@1234") ); assert_eq!(Err(SocketAddressParseError::InvalidInput), "".parse::()); - assert!(SocketAddress::from_str( - "pg6mmjiyjmcrsslvykfwnntlaru7p5svn6y2ymmju6nubxndf4pscryd.onion.onion:9735:94" - ) - .is_err()); + assert!( + SocketAddress::from_str( + "pg6mmjiyjmcrsslvykfwnntlaru7p5svn6y2ymmju6nubxndf4pscryd.onion.onion:9735:94" + ) + .is_err() + ); assert!(SocketAddress::from_str("wrong$%#.com:1234").is_err()); assert_eq!( Err(SocketAddressParseError::InvalidPort), @@ -6957,10 +7012,12 @@ mod tests { assert!("invalid-onion-v3-hostname.onion:8080".parse::().is_err()); assert!("b32.example.onion:invalid-port".parse::().is_err()); assert!("invalid-address".parse::().is_err()); - assert!(SocketAddress::from_str( - "pg6mmjiyjmcrsslvykfwnntlaru7p5svn6y2ymmju6nubxndf4pscryd.onion.onion:1234" - ) - .is_err()); + assert!( + SocketAddress::from_str( + "pg6mmjiyjmcrsslvykfwnntlaru7p5svn6y2ymmju6nubxndf4pscryd.onion.onion:1234" + ) + .is_err() + ); } #[test] @@ -6994,17 +7051,19 @@ mod tests { SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::from([0u8; 4]), 0)) ); assert!(SocketAddress::OnionV2([0u8; 12]).to_socket_addrs().is_err()); - assert!(SocketAddress::OnionV3 { - ed25519_pubkey: [ - 37, 24, 75, 5, 25, 73, 117, 194, 139, 102, 182, 107, 4, 105, 247, 246, 85, 111, - 177, 172, 49, 137, 167, 155, 64, 221, 163, 47, 31, 33, 71, 3 - ], - checksum: 48326, - version: 121, - port: 1234 - } - .to_socket_addrs() - .is_err()); + assert!( + SocketAddress::OnionV3 { + ed25519_pubkey: [ + 37, 24, 75, 5, 25, 73, 117, 194, 139, 102, 182, 107, 4, 105, 247, 246, 85, 111, + 177, 172, 49, 137, 167, 155, 64, 221, 163, 47, 31, 33, 71, 3 + ], + checksum: 48326, + version: 121, + port: 1234 + } + .to_socket_addrs() + .is_err() + ); } fn test_update_add_htlc() -> msgs::UpdateAddHTLC { diff --git a/lightning/src/ln/offers_tests.rs b/lightning/src/ln/offers_tests.rs index de08af5d276..087744201c4 100644 --- a/lightning/src/ln/offers_tests.rs +++ b/lightning/src/ln/offers_tests.rs @@ -1700,7 +1700,7 @@ fn fails_authentication_when_handling_invoice_for_offer() { // will be sent over the wrong blinded path. { let mut pending_offers_messages = david.node.flow.pending_offers_messages.lock().unwrap(); - let mut pending_invoice_request = pending_offers_messages.first_mut().unwrap(); + let pending_invoice_request = pending_offers_messages.first_mut().unwrap(); match &mut pending_invoice_request.1 { MessageSendInstructions::WithSpecifiedReplyPath { reply_path, .. } => *reply_path = invalid_reply_path, @@ -2483,7 +2483,7 @@ fn rejects_keysend_to_non_static_invoice_path() { .expect_failure(HTLCHandlingFailureType::Receive { payment_hash }) .with_dummy_tlvs(&[DummyTlvs::default(); DEFAULT_PAYMENT_DUMMY_HOPS]); do_pass_along_path(args); - let mut updates = get_htlc_update_msgs(&nodes[1], &nodes[0].node.get_our_node_id()); + let updates = get_htlc_update_msgs(&nodes[1], &nodes[0].node.get_our_node_id()); nodes[0].node.handle_update_fail_malformed_htlc(nodes[1].node.get_our_node_id(), &updates.update_fail_malformed_htlcs[0]); do_commitment_signed_dance(&nodes[0], &nodes[1], &updates.commitment_signed, false, false); expect_payment_failed_conditions(&nodes[0], payment_hash, false, PaymentFailedConditions::new()); diff --git a/lightning/src/ln/onion_payment.rs b/lightning/src/ln/onion_payment.rs index e8ff9788f3c..6fc3cc8fc88 100644 --- a/lightning/src/ln/onion_payment.rs +++ b/lightning/src/ln/onion_payment.rs @@ -3,8 +3,8 @@ //! Primarily features [`peel_payment_onion`], which allows the decoding of an onion statelessly //! and can be used to predict whether we'd accept a payment. -use bitcoin::hashes::sha256::Hash as Sha256; use bitcoin::hashes::Hash; +use bitcoin::hashes::sha256::Hash as Sha256; use bitcoin::secp256k1::ecdh::SharedSecret; use bitcoin::secp256k1::{self, PublicKey, Secp256k1}; @@ -12,8 +12,8 @@ use crate::blinded_path; use crate::blinded_path::payment::{PaymentConstraints, PaymentRelay}; use crate::chain::channelmonitor::{HTLC_FAIL_BACK_BUFFER, LATENCY_GRACE_PERIOD_BLOCKS}; use crate::ln::channelmanager::{ - BlindedFailure, BlindedForward, HTLCFailureMsg, PendingHTLCInfo, PendingHTLCRouting, - CLTV_FAR_FAR_AWAY, MIN_CLTV_EXPIRY_DELTA, + BlindedFailure, BlindedForward, CLTV_FAR_FAR_AWAY, HTLCFailureMsg, MIN_CLTV_EXPIRY_DELTA, + PendingHTLCInfo, PendingHTLCRouting, }; use crate::ln::msgs; use crate::ln::onion_utils; @@ -760,8 +760,8 @@ mod tests { use crate::types::features::{ChannelFeatures, NodeFeatures}; use crate::types::payment::{PaymentHash, PaymentPreimage, PaymentSecret}; use crate::util::test_utils; - use bitcoin::hashes::sha256::Hash as Sha256; use bitcoin::hashes::Hash; + use bitcoin::hashes::sha256::Hash as Sha256; use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey}; #[test] diff --git a/lightning/src/ln/onion_route_tests.rs b/lightning/src/ln/onion_route_tests.rs index 019d8faf98c..d981a6c7a81 100644 --- a/lightning/src/ln/onion_route_tests.rs +++ b/lightning/src/ln/onion_route_tests.rs @@ -15,8 +15,8 @@ use crate::chain::channelmonitor::{CLTV_CLAIM_BUFFER, LATENCY_GRACE_PERIOD_BLOCK use crate::events::{Event, HTLCHandlingFailureType, PathFailure, PaymentFailureReason}; use crate::ln::channel::EXPIRE_PREV_CONFIG_TICKS; use crate::ln::channelmanager::{ - FailureCode, HTLCForwardInfo, PaymentId, PendingAddHTLCInfo, PendingHTLCInfo, - PendingHTLCRouting, CLTV_FAR_FAR_AWAY, DISABLE_GOSSIP_TICKS, MIN_CLTV_EXPIRY_DELTA, + CLTV_FAR_FAR_AWAY, DISABLE_GOSSIP_TICKS, FailureCode, HTLCForwardInfo, MIN_CLTV_EXPIRY_DELTA, + PaymentId, PendingAddHTLCInfo, PendingHTLCInfo, PendingHTLCRouting, }; use crate::ln::functional_test_utils::test_default_channel_config; use crate::ln::msgs; @@ -25,14 +25,14 @@ use crate::ln::msgs::{ OutboundOnionPayload, OutboundTrampolinePayload, }; use crate::ln::onion_utils::{ - self, construct_onion_keys, test_build_onion_payloads, LocalHTLCFailureReason, + self, LocalHTLCFailureReason, construct_onion_keys, test_build_onion_payloads, }; use crate::ln::outbound_payment::RecipientOnionFields; use crate::ln::wire::Encode; use crate::routing::gossip::{NetworkUpdate, RoutingFees}; use crate::routing::router::{ - get_route, BlindedTail, Path, PaymentParameters, Route, RouteHint, RouteHintHop, RouteHop, - RouteParameters, TrampolineHop, + BlindedTail, Path, PaymentParameters, Route, RouteHint, RouteHintHop, RouteHop, + RouteParameters, TrampolineHop, get_route, }; use crate::sign::{EntropySource, NodeSigner, Recipient}; use crate::types::features::{Bolt11InvoiceFeatures, InitFeatures}; @@ -391,7 +391,7 @@ fn test_fee_failures() { &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config)], ); - let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs); + let nodes = create_network(3, &node_cfgs, &node_chanmgrs); let channels = [ create_announced_chan_between_nodes(&nodes, 0, 1), create_announced_chan_between_nodes(&nodes, 1, 2), @@ -492,7 +492,7 @@ fn test_onion_failure() { &node_cfgs, &[Some(config.clone()), Some(config), Some(node_2_cfg)], ); - let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs); + let nodes = create_network(3, &node_cfgs, &node_chanmgrs); let channels = [ create_announced_chan_between_nodes(&nodes, 0, 1), create_announced_chan_between_nodes(&nodes, 1, 2), @@ -1536,7 +1536,7 @@ fn test_overshoot_final_cltv() { let chanmon_cfgs = create_chanmon_cfgs(3); let node_cfgs = create_node_cfgs(3, &chanmon_cfgs); let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]); - let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs); + let nodes = create_network(3, &node_cfgs, &node_chanmgrs); create_announced_chan_between_nodes(&nodes, 0, 1); create_announced_chan_between_nodes(&nodes, 1, 2); let (route, payment_hash, payment_preimage, payment_secret) = @@ -1551,7 +1551,7 @@ fn test_overshoot_final_cltv() { check_added_monitors(&nodes[0], 1); let update_0 = get_htlc_update_msgs(&nodes[0], &nodes[1].node.get_our_node_id()); - let mut update_add_0 = update_0.update_add_htlcs[0].clone(); + let update_add_0 = update_0.update_add_htlcs[0].clone(); nodes[1].node.handle_update_add_htlc(nodes[0].node.get_our_node_id(), &update_add_0); do_commitment_signed_dance(&nodes[1], &nodes[0], &update_0.commitment_signed, false, true); @@ -1570,7 +1570,7 @@ fn test_overshoot_final_cltv() { check_added_monitors(&nodes[1], 1); let update_1 = get_htlc_update_msgs(&nodes[1], &nodes[2].node.get_our_node_id()); - let mut update_add_1 = update_1.update_add_htlcs[0].clone(); + let update_add_1 = update_1.update_add_htlcs[0].clone(); nodes[2].node.handle_update_add_htlc(nodes[1].node.get_our_node_id(), &update_add_1); do_commitment_signed_dance(&nodes[2], &nodes[1], &update_1.commitment_signed, false, true); @@ -1810,7 +1810,7 @@ fn test_always_create_tlv_format_onion_payloads() { // specifies no support for variable length onions, as the legacy payload format has been // deprecated in BOLT4. let chanmon_cfgs = create_chanmon_cfgs(3); - let mut node_cfgs = create_node_cfgs(3, &chanmon_cfgs); + let node_cfgs = create_node_cfgs(3, &chanmon_cfgs); // Set `node[1]`'s init features to features which return `false` for // `supports_variable_length_onion()` @@ -1819,7 +1819,7 @@ fn test_always_create_tlv_format_onion_payloads() { *node_cfgs[1].override_init_features.borrow_mut() = Some(no_variable_length_onion_features); let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]); - let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs); + let nodes = create_network(3, &node_cfgs, &node_chanmgrs); create_announced_chan_between_nodes(&nodes, 0, 1); create_announced_chan_between_nodes(&nodes, 1, 2); @@ -1887,7 +1887,10 @@ fn test_trampoline_onion_payload_serialization() { |slice: &[u8]| slice.iter().map(|b| format!("{:02x}", b).to_string()).collect::(); let carol_payload_hex = slice_to_hex(&trampoline_payload.encode()); - assert_eq!(carol_payload_hex, "2e020405f5e10004030c35000e2102edabbd16b41c8371b92ef2f04c1185b4f03b6dcd52ba9b78d9d7c89c8f221145"); + assert_eq!( + carol_payload_hex, + "2e020405f5e10004030c35000e2102edabbd16b41c8371b92ef2f04c1185b4f03b6dcd52ba9b78d9d7c89c8f221145" + ); } #[test] @@ -2097,14 +2100,20 @@ fn test_trampoline_onion_payload_construction_vectors() { outgoing_node_id: PublicKey::from_slice(&>::from_hex(DAVE_HEX).unwrap()).unwrap(), }; let carol_payload = trampoline_payload_carol.encode().to_lower_hex_string(); - assert_eq!(carol_payload, "2e020408f31d6404030c35240e21032c0b7cf95324a07d05398b240174dc0c2be444d96b159aa6c7f7b1e668680991"); + assert_eq!( + carol_payload, + "2e020408f31d6404030c35240e21032c0b7cf95324a07d05398b240174dc0c2be444d96b159aa6c7f7b1e668680991" + ); let trampoline_payload_dave = OutboundTrampolinePayload::BlindedForward { encrypted_tlvs: &>::from_hex("0ccf3c8a58deaa603f657ee2a5ed9d604eb5c8ca1e5f801989afa8f3ea6d789bbdde2c7e7a1ef9ca8c38d2c54760febad8446d3f273ddb537569ef56613846ccd3aba78a").unwrap(), intro_node_blinding_point: Some(PublicKey::from_slice(&>::from_hex(BLINDING_POINT_HEX).unwrap()).unwrap()), }; let dave_payload = trampoline_payload_dave.encode().to_lower_hex_string(); - assert_eq!(dave_payload, "690a440ccf3c8a58deaa603f657ee2a5ed9d604eb5c8ca1e5f801989afa8f3ea6d789bbdde2c7e7a1ef9ca8c38d2c54760febad8446d3f273ddb537569ef56613846ccd3aba78a0c2102988face71e92c345a068f740191fd8e53be14f0bb957ef730d3c5f76087b960e"); + assert_eq!( + dave_payload, + "690a440ccf3c8a58deaa603f657ee2a5ed9d604eb5c8ca1e5f801989afa8f3ea6d789bbdde2c7e7a1ef9ca8c38d2c54760febad8446d3f273ddb537569ef56613846ccd3aba78a0c2102988face71e92c345a068f740191fd8e53be14f0bb957ef730d3c5f76087b960e" + ); let trampoline_payload_eve = OutboundTrampolinePayload::BlindedReceive { sender_intended_htlc_amt_msat: 150_000_000, @@ -2116,7 +2125,10 @@ fn test_trampoline_onion_payload_construction_vectors() { custom_tlvs: &vec![], }; let eve_payload = trampoline_payload_eve.encode().to_lower_hex_string(); - assert_eq!(eve_payload, "e4020408f0d18004030c35000ad1bcd747394fbd4d99588da075a623316e15a576df5bc785cccc7cd6ec7b398acce6faf520175f9ec920f2ef261cdb83dc28cc3a0eeb970107b3306489bf771ef5b1213bca811d345285405861d08a655b6c237fa247a8b4491beee20c878a60e9816492026d8feb9dafa84585b253978db6a0aa2945df5ef445c61e801fb82f43d5f00716baf9fc9b3de50bc22950a36bda8fc27bfb1242e5860c7e687438d4133e058770361a19b6c271a2a07788d34dccc27e39b9829b061a4d960eac4a2c2b0f4de506c24f9af3868c0aff6dda27281c120408f0d180"); + assert_eq!( + eve_payload, + "e4020408f0d18004030c35000ad1bcd747394fbd4d99588da075a623316e15a576df5bc785cccc7cd6ec7b398acce6faf520175f9ec920f2ef261cdb83dc28cc3a0eeb970107b3306489bf771ef5b1213bca811d345285405861d08a655b6c237fa247a8b4491beee20c878a60e9816492026d8feb9dafa84585b253978db6a0aa2945df5ef445c61e801fb82f43d5f00716baf9fc9b3de50bc22950a36bda8fc27bfb1242e5860c7e687438d4133e058770361a19b6c271a2a07788d34dccc27e39b9829b061a4d960eac4a2c2b0f4de506c24f9af3868c0aff6dda27281c120408f0d180" + ); let trampoline_payloads = vec![trampoline_payload_carol, trampoline_payload_dave, trampoline_payload_eve]; @@ -2191,7 +2203,10 @@ fn test_trampoline_onion_payload_construction_vectors() { ) .unwrap(); let trampoline_onion_packet_hex = trampoline_onion_packet.encode().to_lower_hex_string(); - assert_eq!(trampoline_onion_packet_hex, "0002bc59a9abc893d75a8d4f56a6572f9a3507323a8de22abe0496ea8d37da166a8b4bba0e560f1a9deb602bfd98fe9167141d0b61d669df90c0149096d505b85d3d02806e6c12caeb308b878b6bc7f1b15839c038a6443cd3bec3a94c2293165375555f6d7720862b525930f41fddcc02260d197abd93fb58e60835fd97d9dc14e7979c12f59df08517b02e3e4d50e1817de4271df66d522c4e9675df71c635c4176a8381bc22b342ff4e9031cede87f74cc039fca74aa0a3786bc1db2e158a9a520ecb99667ef9a6bbfaf5f0e06f81c27ca48134ba2103229145937c5dc7b8ecc5201d6aeb592e78faa3c05d3a035df77628f0be9b1af3ef7d386dd5cc87b20778f47ebd40dbfcf12b9071c5d7112ab84c3e0c5c14867e684d09a18bc93ac47d73b7343e3403ef6e3b70366835988920e7d772c3719d3596e53c29c4017cb6938421a557ce81b4bb26701c25bf622d4c69f1359dc85857a375c5c74987a4d3152f66987001c68a50c4bf9e0b1dab4ad1a64b0535319bbf6c4fbe4f9c50cb65f5ef887bfb91b0a57c0f86ba3d91cbeea1607fb0c12c6c75d03bbb0d3a3019c40597027f5eebca23083e50ec79d41b1152131853525bf3fc13fb0be62c2e3ce733f59671eee5c4064863fb92ae74be9ca68b9c716f9519fd268478ee27d91d466b0de51404de3226b74217d28250ead9d2c95411e0230570f547d4cc7c1d589791623131aa73965dccc5aa17ec12b442215ce5d346df664d799190df5dd04a13"); + assert_eq!( + trampoline_onion_packet_hex, + "0002bc59a9abc893d75a8d4f56a6572f9a3507323a8de22abe0496ea8d37da166a8b4bba0e560f1a9deb602bfd98fe9167141d0b61d669df90c0149096d505b85d3d02806e6c12caeb308b878b6bc7f1b15839c038a6443cd3bec3a94c2293165375555f6d7720862b525930f41fddcc02260d197abd93fb58e60835fd97d9dc14e7979c12f59df08517b02e3e4d50e1817de4271df66d522c4e9675df71c635c4176a8381bc22b342ff4e9031cede87f74cc039fca74aa0a3786bc1db2e158a9a520ecb99667ef9a6bbfaf5f0e06f81c27ca48134ba2103229145937c5dc7b8ecc5201d6aeb592e78faa3c05d3a035df77628f0be9b1af3ef7d386dd5cc87b20778f47ebd40dbfcf12b9071c5d7112ab84c3e0c5c14867e684d09a18bc93ac47d73b7343e3403ef6e3b70366835988920e7d772c3719d3596e53c29c4017cb6938421a557ce81b4bb26701c25bf622d4c69f1359dc85857a375c5c74987a4d3152f66987001c68a50c4bf9e0b1dab4ad1a64b0535319bbf6c4fbe4f9c50cb65f5ef887bfb91b0a57c0f86ba3d91cbeea1607fb0c12c6c75d03bbb0d3a3019c40597027f5eebca23083e50ec79d41b1152131853525bf3fc13fb0be62c2e3ce733f59671eee5c4064863fb92ae74be9ca68b9c716f9519fd268478ee27d91d466b0de51404de3226b74217d28250ead9d2c95411e0230570f547d4cc7c1d589791623131aa73965dccc5aa17ec12b442215ce5d346df664d799190df5dd04a13" + ); let outer_payloads = vec![ // Bob @@ -2246,7 +2261,10 @@ fn test_trampoline_onion_payload_construction_vectors() { assert_eq!(bob_payload, "15020408f3272804030c353c060808bbaa00002a0b05"); let carol_payload = outer_payloads[1].encode().to_lower_hex_string(); - assert_eq!(carol_payload, "fd0255020408f3272804030c353c08247494b65bc092b48a75465e43e29be807eb2cc535ce8aaba31012b8ff1ceac5da08f3272814fd02200002bc59a9abc893d75a8d4f56a6572f9a3507323a8de22abe0496ea8d37da166a8b4bba0e560f1a9deb602bfd98fe9167141d0b61d669df90c0149096d505b85d3d02806e6c12caeb308b878b6bc7f1b15839c038a6443cd3bec3a94c2293165375555f6d7720862b525930f41fddcc02260d197abd93fb58e60835fd97d9dc14e7979c12f59df08517b02e3e4d50e1817de4271df66d522c4e9675df71c635c4176a8381bc22b342ff4e9031cede87f74cc039fca74aa0a3786bc1db2e158a9a520ecb99667ef9a6bbfaf5f0e06f81c27ca48134ba2103229145937c5dc7b8ecc5201d6aeb592e78faa3c05d3a035df77628f0be9b1af3ef7d386dd5cc87b20778f47ebd40dbfcf12b9071c5d7112ab84c3e0c5c14867e684d09a18bc93ac47d73b7343e3403ef6e3b70366835988920e7d772c3719d3596e53c29c4017cb6938421a557ce81b4bb26701c25bf622d4c69f1359dc85857a375c5c74987a4d3152f66987001c68a50c4bf9e0b1dab4ad1a64b0535319bbf6c4fbe4f9c50cb65f5ef887bfb91b0a57c0f86ba3d91cbeea1607fb0c12c6c75d03bbb0d3a3019c40597027f5eebca23083e50ec79d41b1152131853525bf3fc13fb0be62c2e3ce733f59671eee5c4064863fb92ae74be9ca68b9c716f9519fd268478ee27d91d466b0de51404de3226b74217d28250ead9d2c95411e0230570f547d4cc7c1d589791623131aa73965dccc5aa17ec12b442215ce5d346df664d799190df5dd04a13"); + assert_eq!( + carol_payload, + "fd0255020408f3272804030c353c08247494b65bc092b48a75465e43e29be807eb2cc535ce8aaba31012b8ff1ceac5da08f3272814fd02200002bc59a9abc893d75a8d4f56a6572f9a3507323a8de22abe0496ea8d37da166a8b4bba0e560f1a9deb602bfd98fe9167141d0b61d669df90c0149096d505b85d3d02806e6c12caeb308b878b6bc7f1b15839c038a6443cd3bec3a94c2293165375555f6d7720862b525930f41fddcc02260d197abd93fb58e60835fd97d9dc14e7979c12f59df08517b02e3e4d50e1817de4271df66d522c4e9675df71c635c4176a8381bc22b342ff4e9031cede87f74cc039fca74aa0a3786bc1db2e158a9a520ecb99667ef9a6bbfaf5f0e06f81c27ca48134ba2103229145937c5dc7b8ecc5201d6aeb592e78faa3c05d3a035df77628f0be9b1af3ef7d386dd5cc87b20778f47ebd40dbfcf12b9071c5d7112ab84c3e0c5c14867e684d09a18bc93ac47d73b7343e3403ef6e3b70366835988920e7d772c3719d3596e53c29c4017cb6938421a557ce81b4bb26701c25bf622d4c69f1359dc85857a375c5c74987a4d3152f66987001c68a50c4bf9e0b1dab4ad1a64b0535319bbf6c4fbe4f9c50cb65f5ef887bfb91b0a57c0f86ba3d91cbeea1607fb0c12c6c75d03bbb0d3a3019c40597027f5eebca23083e50ec79d41b1152131853525bf3fc13fb0be62c2e3ce733f59671eee5c4064863fb92ae74be9ca68b9c716f9519fd268478ee27d91d466b0de51404de3226b74217d28250ead9d2c95411e0230570f547d4cc7c1d589791623131aa73965dccc5aa17ec12b442215ce5d346df664d799190df5dd04a13" + ); let outer_session_key = SecretKey::from_slice( &>::from_hex("4f777e8dac16e6dfe333066d9efb014f7a51d11762ff76eca4d3a95ada99ba3e") @@ -2264,7 +2282,10 @@ fn test_trampoline_onion_payload_construction_vectors() { ) .unwrap(); let outer_onion_packet_hex = outer_onion_packet.encode().to_lower_hex_string(); - assert_eq!(outer_onion_packet_hex, "00025fd60556c134ae97e4baedba220a644037754ee67c54fd05e93bf40c17cbb73362fb9dee96001ff229945595b6edb59437a6bc143406d3f90f749892a84d8d430c6890437d26d5bfc599d565316ef51347521075bbab87c59c57bcf20af7e63d7192b46cf171e4f73cb11f9f603915389105d91ad630224bea95d735e3988add1e24b5bf28f1d7128db64284d90a839ba340d088c74b1fb1bd21136b1809428ec5399c8649e9bdf92d2dcfc694deae5046fa5b2bdf646847aaad73f5e95275763091c90e71031cae1f9a770fdea559642c9c02f424a2a28163dd0957e3874bd28a97bec67d18c0321b0e68bc804aa8345b17cb626e2348ca06c8312a167c989521056b0f25c55559d446507d6c491d50605cb79fa87929ce64b0a9860926eeaec2c431d926a1cadb9a1186e4061cb01671a122fc1f57602cbef06d6c194ec4b715c2e3dd4120baca3172cd81900b49fef857fb6d6afd24c983b608108b0a5ac0c1c6c52011f23b8778059ffadd1bb7cd06e2525417365f485a7fd1d4a9ba3818ede7cdc9e71afee8532252d08e2531ca52538655b7e8d912f7ec6d37bbcce8d7ec690709dbf9321e92c565b78e7fe2c22edf23e0902153d1ca15a112ad32fb19695ec65ce11ddf670da7915f05ad4b86c154fb908cb567315d1124f303f75fa075ebde8ef7bb12e27737ad9e4924439097338ea6d7a6fc3721b88c9b830a34e8d55f4c582b74a3895cc848fe57f4fe29f115dabeb6b3175be15d94408ed6771109cfaf57067ae658201082eae7605d26b1449af4425ae8e8f58cdda5c6265f1fd7a386fc6cea3074e4f25b909b96175883676f7610a00fdf34df9eb6c7b9a4ae89b839c69fd1f285e38cdceb634d782cc6d81179759bc9fd47d7fd060470d0b048287764c6837963274e708314f017ac7dc26d0554d59bfcfd3136225798f65f0b0fea337c6b256ebbb63a90b994c0ab93fd8b1d6bd4c74aebe535d6110014cd3d525394027dfe8faa98b4e9b2bee7949eb1961f1b026791092f84deea63afab66603dbe9b6365a102a1fef2f6b9744bc1bb091a8da9130d34d4d39f25dbad191649cfb67e10246364b7ce0c6ec072f9690cabb459d9fda0c849e17535de4357e9907270c75953fca3c845bb613926ecf73205219c7057a4b6bb244c184362bb4e2f24279dc4e60b94a5b1ec11c34081a628428ba5646c995b9558821053ba9c84a05afbf00dabd60223723096516d2f5668f3ec7e11612b01eb7a3a0506189a2272b88e89807943adb34291a17f6cb5516ffd6f945a1c42a524b21f096d66f350b1dad4db455741ae3d0e023309fbda5ef55fb0dc74f3297041448b2be76c525141963934c6afc53d263fb7836626df502d7c2ee9e79cbbd87afd84bbb8dfbf45248af3cd61ad5fac827e7683ca4f91dfad507a8eb9c17b2c9ac5ec051fe645a4a6cb37136f6f19b611e0ea8da7960af2d779507e55f57305bc74b7568928c5dd5132990fe54c22117df91c257d8c7b61935a018a28c1c3b17bab8e4294fa699161ec21123c9fc4e71079df31f300c2822e1246561e04765d3aab333eafd026c7431ac7616debb0e022746f4538e1c6348b600c988eeb2d051fc60c468dca260a84c79ab3ab8342dc345a764672848ea234e17332bc124799daf7c5fcb2e2358514a7461357e1c19c802c5ee32deccf1776885dd825bedd5f781d459984370a6b7ae885d4483a76ddb19b30f47ed47cd56aa5a079a89793dbcad461c59f2e002067ac98dd5a534e525c9c46c2af730741bf1f8629357ec0bfc0bc9ecb31af96777e507648ff4260dc3673716e098d9111dfd245f1d7c55a6de340deb8bd7a053e5d62d760f184dc70ca8fa255b9023b9b9aedfb6e419a5b5951ba0f83b603793830ee68d442d7b88ee1bbf6bbd1bcd6f68cc1af"); + assert_eq!( + outer_onion_packet_hex, + "00025fd60556c134ae97e4baedba220a644037754ee67c54fd05e93bf40c17cbb73362fb9dee96001ff229945595b6edb59437a6bc143406d3f90f749892a84d8d430c6890437d26d5bfc599d565316ef51347521075bbab87c59c57bcf20af7e63d7192b46cf171e4f73cb11f9f603915389105d91ad630224bea95d735e3988add1e24b5bf28f1d7128db64284d90a839ba340d088c74b1fb1bd21136b1809428ec5399c8649e9bdf92d2dcfc694deae5046fa5b2bdf646847aaad73f5e95275763091c90e71031cae1f9a770fdea559642c9c02f424a2a28163dd0957e3874bd28a97bec67d18c0321b0e68bc804aa8345b17cb626e2348ca06c8312a167c989521056b0f25c55559d446507d6c491d50605cb79fa87929ce64b0a9860926eeaec2c431d926a1cadb9a1186e4061cb01671a122fc1f57602cbef06d6c194ec4b715c2e3dd4120baca3172cd81900b49fef857fb6d6afd24c983b608108b0a5ac0c1c6c52011f23b8778059ffadd1bb7cd06e2525417365f485a7fd1d4a9ba3818ede7cdc9e71afee8532252d08e2531ca52538655b7e8d912f7ec6d37bbcce8d7ec690709dbf9321e92c565b78e7fe2c22edf23e0902153d1ca15a112ad32fb19695ec65ce11ddf670da7915f05ad4b86c154fb908cb567315d1124f303f75fa075ebde8ef7bb12e27737ad9e4924439097338ea6d7a6fc3721b88c9b830a34e8d55f4c582b74a3895cc848fe57f4fe29f115dabeb6b3175be15d94408ed6771109cfaf57067ae658201082eae7605d26b1449af4425ae8e8f58cdda5c6265f1fd7a386fc6cea3074e4f25b909b96175883676f7610a00fdf34df9eb6c7b9a4ae89b839c69fd1f285e38cdceb634d782cc6d81179759bc9fd47d7fd060470d0b048287764c6837963274e708314f017ac7dc26d0554d59bfcfd3136225798f65f0b0fea337c6b256ebbb63a90b994c0ab93fd8b1d6bd4c74aebe535d6110014cd3d525394027dfe8faa98b4e9b2bee7949eb1961f1b026791092f84deea63afab66603dbe9b6365a102a1fef2f6b9744bc1bb091a8da9130d34d4d39f25dbad191649cfb67e10246364b7ce0c6ec072f9690cabb459d9fda0c849e17535de4357e9907270c75953fca3c845bb613926ecf73205219c7057a4b6bb244c184362bb4e2f24279dc4e60b94a5b1ec11c34081a628428ba5646c995b9558821053ba9c84a05afbf00dabd60223723096516d2f5668f3ec7e11612b01eb7a3a0506189a2272b88e89807943adb34291a17f6cb5516ffd6f945a1c42a524b21f096d66f350b1dad4db455741ae3d0e023309fbda5ef55fb0dc74f3297041448b2be76c525141963934c6afc53d263fb7836626df502d7c2ee9e79cbbd87afd84bbb8dfbf45248af3cd61ad5fac827e7683ca4f91dfad507a8eb9c17b2c9ac5ec051fe645a4a6cb37136f6f19b611e0ea8da7960af2d779507e55f57305bc74b7568928c5dd5132990fe54c22117df91c257d8c7b61935a018a28c1c3b17bab8e4294fa699161ec21123c9fc4e71079df31f300c2822e1246561e04765d3aab333eafd026c7431ac7616debb0e022746f4538e1c6348b600c988eeb2d051fc60c468dca260a84c79ab3ab8342dc345a764672848ea234e17332bc124799daf7c5fcb2e2358514a7461357e1c19c802c5ee32deccf1776885dd825bedd5f781d459984370a6b7ae885d4483a76ddb19b30f47ed47cd56aa5a079a89793dbcad461c59f2e002067ac98dd5a534e525c9c46c2af730741bf1f8629357ec0bfc0bc9ecb31af96777e507648ff4260dc3673716e098d9111dfd245f1d7c55a6de340deb8bd7a053e5d62d760f184dc70ca8fa255b9023b9b9aedfb6e419a5b5951ba0f83b603793830ee68d442d7b88ee1bbf6bbd1bcd6f68cc1af" + ); } fn do_test_fail_htlc_backwards_with_reason(failure_code: FailureCode) { @@ -2286,7 +2307,7 @@ fn do_test_fail_htlc_backwards_with_reason(failure_code: FailureCode) { check_added_monitors(&nodes[0], 1); let mut events = nodes[0].node.get_and_clear_pending_msg_events(); - let mut payment_event = SendEvent::from_event(events.pop().unwrap()); + let payment_event = SendEvent::from_event(events.pop().unwrap()); nodes[1].node.handle_update_add_htlc(nodes[0].node.get_our_node_id(), &payment_event.msgs[0]); do_commitment_signed_dance(&nodes[1], &nodes[0], &payment_event.commitment_msg, false, false); @@ -2435,7 +2456,7 @@ fn test_phantom_onion_hmac_failure() { .unwrap(); check_added_monitors(&nodes[0], 1); let update_0 = get_htlc_update_msgs(&nodes[0], &nodes[1].node.get_our_node_id()); - let mut update_add = update_0.update_add_htlcs[0].clone(); + let update_add = update_0.update_add_htlcs[0].clone(); nodes[1].node.handle_update_add_htlc(nodes[0].node.get_our_node_id(), &update_add); do_commitment_signed_dance(&nodes[1], &nodes[0], &update_0.commitment_signed, false, true); @@ -2445,7 +2466,7 @@ fn test_phantom_onion_hmac_failure() { // Modify the payload so the phantom hop's HMAC is bogus. let sha256_of_onion = { let mut forward_htlcs = nodes[1].node.forward_htlcs.lock().unwrap(); - let mut pending_forward = forward_htlcs.get_mut(&phantom_scid).unwrap(); + let pending_forward = forward_htlcs.get_mut(&phantom_scid).unwrap(); match pending_forward[0] { HTLCForwardInfo::AddHTLC(PendingAddHTLCInfo { forward_info: @@ -2475,7 +2496,7 @@ fn test_phantom_onion_hmac_failure() { do_commitment_signed_dance(&nodes[0], &nodes[1], &update_1.commitment_signed, false, false); // Ensure the payment fails with the expected error. - let mut fail_conditions = PaymentFailedConditions::new() + let fail_conditions = PaymentFailedConditions::new() .blamed_scid(phantom_scid) .blamed_chan_closed(true) .expected_htlc_error_data(LocalHTLCFailureReason::InvalidOnionHMAC, &sha256_of_onion); @@ -2487,7 +2508,7 @@ fn test_phantom_invalid_onion_payload() { let chanmon_cfgs = create_chanmon_cfgs(2); let node_cfgs = create_node_cfgs(2, &chanmon_cfgs); let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]); - let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs); + let nodes = create_network(2, &node_cfgs, &node_chanmgrs); let channel = create_announced_chan_between_nodes(&nodes, 0, 1); @@ -2508,7 +2529,7 @@ fn test_phantom_invalid_onion_payload() { .unwrap(); check_added_monitors(&nodes[0], 1); let update_0 = get_htlc_update_msgs(&nodes[0], &nodes[1].node.get_our_node_id()); - let mut update_add = update_0.update_add_htlcs[0].clone(); + let update_add = update_0.update_add_htlcs[0].clone(); nodes[1].node.handle_update_add_htlc(nodes[0].node.get_our_node_id(), &update_add); do_commitment_signed_dance(&nodes[1], &nodes[0], &update_0.commitment_signed, false, true); @@ -2577,7 +2598,7 @@ fn test_phantom_invalid_onion_payload() { // Ensure the payment fails with the expected error. let error_data = Vec::new(); - let mut fail_conditions = PaymentFailedConditions::new() + let fail_conditions = PaymentFailedConditions::new() .blamed_scid(phantom_scid) .blamed_chan_closed(true) .expected_htlc_error_data(LocalHTLCFailureReason::InvalidOnionPayload, &error_data); @@ -2607,7 +2628,7 @@ fn test_phantom_final_incorrect_cltv_expiry() { .unwrap(); check_added_monitors(&nodes[0], 1); let update_0 = get_htlc_update_msgs(&nodes[0], &nodes[1].node.get_our_node_id()); - let mut update_add = update_0.update_add_htlcs[0].clone(); + let update_add = update_0.update_add_htlcs[0].clone(); nodes[1].node.handle_update_add_htlc(nodes[0].node.get_our_node_id(), &update_add); do_commitment_signed_dance(&nodes[1], &nodes[0], &update_0.commitment_signed, false, true); @@ -2644,7 +2665,7 @@ fn test_phantom_final_incorrect_cltv_expiry() { // Ensure the payment fails with the expected error. let expected_cltv: u32 = 80; let error_data = expected_cltv.to_be_bytes().to_vec(); - let mut fail_conditions = PaymentFailedConditions::new() + let fail_conditions = PaymentFailedConditions::new() .blamed_scid(phantom_scid) .expected_htlc_error_data(LocalHTLCFailureReason::FinalIncorrectCLTVExpiry, &error_data); expect_payment_failed_conditions(&nodes[0], payment_hash, false, fail_conditions); @@ -2676,7 +2697,7 @@ fn test_phantom_failure_too_low_cltv() { .unwrap(); check_added_monitors(&nodes[0], 1); let update_0 = get_htlc_update_msgs(&nodes[0], &nodes[1].node.get_our_node_id()); - let mut update_add = update_0.update_add_htlcs[0].clone(); + let update_add = update_0.update_add_htlcs[0].clone(); nodes[1].node.handle_update_add_htlc(nodes[0].node.get_our_node_id(), &update_add); do_commitment_signed_dance(&nodes[1], &nodes[0], &update_0.commitment_signed, false, true); @@ -2698,7 +2719,7 @@ fn test_phantom_failure_too_low_cltv() { // Ensure the payment fails with the expected error. let mut error_data = recv_value_msat.to_be_bytes().to_vec(); error_data.extend_from_slice(&nodes[0].node.best_block.read().unwrap().height.to_be_bytes()); - let mut fail_conditions = PaymentFailedConditions::new() + let fail_conditions = PaymentFailedConditions::new() .blamed_scid(phantom_scid) .expected_htlc_error_data(LocalHTLCFailureReason::IncorrectPaymentDetails, &error_data); expect_payment_failed_conditions(&nodes[0], payment_hash, true, fail_conditions); @@ -2719,7 +2740,7 @@ fn test_phantom_failure_modified_cltv() { let recv_value_msat = 10_000; let (_, payment_hash, payment_secret) = get_payment_preimage_hash(&nodes[1], Some(recv_value_msat), None); - let (mut route, phantom_scid) = get_phantom_route!(nodes, recv_value_msat, channel); + let (route, phantom_scid) = get_phantom_route!(nodes, recv_value_msat, channel); // Route the HTLC through to the destination. let recipient_onion = RecipientOnionFields::secret_only(payment_secret, recv_value_msat); @@ -2753,7 +2774,7 @@ fn test_phantom_failure_modified_cltv() { let mut err_data = Vec::new(); err_data.extend_from_slice(&update_add.cltv_expiry.to_be_bytes()); err_data.extend_from_slice(&0u16.to_be_bytes()); - let mut fail_conditions = PaymentFailedConditions::new() + let fail_conditions = PaymentFailedConditions::new() .blamed_scid(phantom_scid) .expected_htlc_error_data(LocalHTLCFailureReason::IncorrectCLTVExpiry, &err_data); expect_payment_failed_conditions(&nodes[0], payment_hash, false, fail_conditions); @@ -2774,7 +2795,7 @@ fn test_phantom_failure_expires_too_soon() { let recv_value_msat = 10_000; let (_, payment_hash, payment_secret) = get_payment_preimage_hash(&nodes[1], Some(recv_value_msat), None); - let (mut route, phantom_scid) = get_phantom_route!(nodes, recv_value_msat, channel); + let (route, phantom_scid) = get_phantom_route!(nodes, recv_value_msat, channel); // Route the HTLC through to the destination. let recipient_onion = RecipientOnionFields::secret_only(payment_secret, recv_value_msat); @@ -2784,7 +2805,7 @@ fn test_phantom_failure_expires_too_soon() { .unwrap(); check_added_monitors(&nodes[0], 1); let update_0 = get_htlc_update_msgs(&nodes[0], &nodes[1].node.get_our_node_id()); - let mut update_add = update_0.update_add_htlcs[0].clone(); + let update_add = update_0.update_add_htlcs[0].clone(); connect_blocks(&nodes[1], CLTV_FAR_FAR_AWAY); nodes[1].node.handle_update_add_htlc(nodes[0].node.get_our_node_id(), &update_add); @@ -2804,7 +2825,7 @@ fn test_phantom_failure_expires_too_soon() { // Ensure the payment fails with the expected error. let err_data = 0u16.to_be_bytes(); - let mut fail_conditions = PaymentFailedConditions::new() + let fail_conditions = PaymentFailedConditions::new() .blamed_scid(phantom_scid) .expected_htlc_error_data(LocalHTLCFailureReason::CLTVExpiryTooSoon, &err_data); expect_payment_failed_conditions(&nodes[0], payment_hash, false, fail_conditions); @@ -2824,7 +2845,7 @@ fn test_phantom_failure_too_low_recv_amt() { let bad_recv_amt_msat = recv_amt_msat - 10; let (_, payment_hash, payment_secret) = get_payment_preimage_hash(&nodes[1], Some(recv_amt_msat), None); - let (mut route, phantom_scid) = get_phantom_route!(nodes, bad_recv_amt_msat, channel); + let (route, phantom_scid) = get_phantom_route!(nodes, bad_recv_amt_msat, channel); // Route the HTLC through to the destination. let recipient_onion = @@ -2835,7 +2856,7 @@ fn test_phantom_failure_too_low_recv_amt() { .unwrap(); check_added_monitors(&nodes[0], 1); let update_0 = get_htlc_update_msgs(&nodes[0], &nodes[1].node.get_our_node_id()); - let mut update_add = update_0.update_add_htlcs[0].clone(); + let update_add = update_0.update_add_htlcs[0].clone(); nodes[1].node.handle_update_add_htlc(nodes[0].node.get_our_node_id(), &update_add); do_commitment_signed_dance(&nodes[1], &nodes[0], &update_0.commitment_signed, false, true); @@ -2859,7 +2880,7 @@ fn test_phantom_failure_too_low_recv_amt() { // Ensure the payment fails with the expected error. let mut error_data = bad_recv_amt_msat.to_be_bytes().to_vec(); error_data.extend_from_slice(&nodes[1].node.best_block.read().unwrap().height.to_be_bytes()); - let mut fail_conditions = PaymentFailedConditions::new() + let fail_conditions = PaymentFailedConditions::new() .blamed_scid(phantom_scid) .expected_htlc_error_data(LocalHTLCFailureReason::IncorrectPaymentDetails, &error_data); expect_payment_failed_conditions(&nodes[0], payment_hash, true, fail_conditions); @@ -2894,7 +2915,7 @@ fn do_test_phantom_dust_exposure_failure(multiplier_dust_limit: bool) { // Get the route with an amount exceeding the dust exposure threshold of nodes[1]. let (_, payment_hash, payment_secret) = get_payment_preimage_hash(&nodes[1], Some(max_dust_exposure + 1), None); - let (mut route, phantom_scid) = get_phantom_route!(nodes, max_dust_exposure + 1, channel); + let (route, phantom_scid) = get_phantom_route!(nodes, max_dust_exposure + 1, channel); // Route the HTLC through to the destination. let recipient_onion = RecipientOnionFields::secret_only(payment_secret, max_dust_exposure + 1); @@ -2905,7 +2926,7 @@ fn do_test_phantom_dust_exposure_failure(multiplier_dust_limit: bool) { .unwrap(); check_added_monitors(&nodes[0], 1); let update_0 = get_htlc_update_msgs(&nodes[0], &nodes[1].node.get_our_node_id()); - let mut update_add = update_0.update_add_htlcs[0].clone(); + let update_add = update_0.update_add_htlcs[0].clone(); nodes[1].node.handle_update_add_htlc(nodes[0].node.get_our_node_id(), &update_add); do_commitment_signed_dance(&nodes[1], &nodes[0], &update_0.commitment_signed, false, true); @@ -2924,7 +2945,7 @@ fn do_test_phantom_dust_exposure_failure(multiplier_dust_limit: bool) { // Ensure the payment fails with the expected error. let err_data = 0u16.to_be_bytes(); - let mut fail_conditions = PaymentFailedConditions::new() + let fail_conditions = PaymentFailedConditions::new() .blamed_scid(phantom_scid) .expected_htlc_error_data(LocalHTLCFailureReason::TemporaryChannelFailure, &err_data); expect_payment_failed_conditions(&nodes[0], payment_hash, false, fail_conditions); @@ -2944,7 +2965,7 @@ fn test_phantom_failure_reject_payment() { let recv_amt_msat = 10_000; let (_, payment_hash, payment_secret) = get_payment_preimage_hash(&nodes[1], Some(recv_amt_msat), None); - let (mut route, phantom_scid) = get_phantom_route!(nodes, recv_amt_msat, channel); + let (route, phantom_scid) = get_phantom_route!(nodes, recv_amt_msat, channel); // Route the HTLC through to the destination. let recipient_onion = RecipientOnionFields::secret_only(payment_secret, recv_amt_msat); @@ -2955,7 +2976,7 @@ fn test_phantom_failure_reject_payment() { .unwrap(); check_added_monitors(&nodes[0], 1); let update_0 = get_htlc_update_msgs(&nodes[0], &nodes[1].node.get_our_node_id()); - let mut update_add = update_0.update_add_htlcs[0].clone(); + let update_add = update_0.update_add_htlcs[0].clone(); nodes[1].node.handle_update_add_htlc(nodes[0].node.get_our_node_id(), &update_add); do_commitment_signed_dance(&nodes[1], &nodes[0], &update_0.commitment_signed, false, true); @@ -2989,7 +3010,7 @@ fn test_phantom_failure_reject_payment() { // Ensure the payment fails with the expected error. let mut error_data = recv_amt_msat.to_be_bytes().to_vec(); error_data.extend_from_slice(&nodes[1].node.best_block.read().unwrap().height.to_be_bytes()); - let mut fail_conditions = PaymentFailedConditions::new() + let fail_conditions = PaymentFailedConditions::new() .blamed_scid(phantom_scid) .expected_htlc_error_data(LocalHTLCFailureReason::IncorrectPaymentDetails, &error_data); expect_payment_failed_conditions(&nodes[0], payment_hash, true, fail_conditions); diff --git a/lightning/src/ln/onion_utils.rs b/lightning/src/ln/onion_utils.rs index fe41bc1c6dc..d7dd79033d5 100644 --- a/lightning/src/ln/onion_utils.rs +++ b/lightning/src/ln/onion_utils.rs @@ -731,11 +731,10 @@ pub(super) fn construct_onion_packet( debug_assert_eq!(payloads.len(), onion_keys.len(), "Payloads and keys must have equal lengths"); - let packet = FixedSizeOnionPacket(packet_data); construct_onion_packet_with_init_noise::<_, _>( payloads, onion_keys, - packet, + packet_data, Some(associated_data), ) } @@ -787,11 +786,10 @@ pub(super) fn construct_onion_packet_with_writable_hopdata( let mut chacha = ChaCha20::new(Key::new(prng_seed), Nonce::new([0; 12]), 0); chacha.apply_keystream(&mut packet_data); - let packet = FixedSizeOnionPacket(packet_data); construct_onion_packet_with_init_noise::<_, _>( payloads, onion_keys, - packet, + packet_data, Some(associated_data), ) } @@ -804,16 +802,6 @@ pub(crate) trait Packet { fn new(pubkey: PublicKey, hop_data: Self::Data, hmac: [u8; 32]) -> Self; } -// Needed for rustc versions older than 1.47 to avoid E0277: "arrays only have std trait -// implementations for lengths 0..=32". -pub(crate) struct FixedSizeOnionPacket(pub(crate) [u8; ONION_DATA_LEN]); - -impl AsMut<[u8]> for FixedSizeOnionPacket { - fn as_mut(&mut self) -> &mut [u8] { - &mut self.0 - } -} - pub(crate) fn payloads_serialized_length(payloads: &Vec) -> usize { payloads.iter().map(|p| p.serialized_length() + 32 /* HMAC */).sum() } @@ -1007,7 +995,7 @@ mod fuzzy_onion_utils { encrypted_packet: OnionErrorPacket, ) -> DecodedOnionFailure { let (path, session_priv) = match htlc_source { - HTLCSource::OutboundRoute { ref path, ref session_priv, .. } => (path, session_priv), + HTLCSource::OutboundRoute { path, session_priv, .. } => (path, session_priv), _ => unreachable!(), }; @@ -2176,9 +2164,9 @@ pub(crate) trait NextPacketBytes: AsMut<[u8]> { fn new(len: usize) -> Self; } -impl NextPacketBytes for FixedSizeOnionPacket { +impl NextPacketBytes for [u8; ONION_DATA_LEN] { fn new(_len: usize) -> Self { - Self([0 as u8; ONION_DATA_LEN]) + [0 as u8; ONION_DATA_LEN] } } @@ -2350,44 +2338,33 @@ pub(crate) fn decode_next_payment_hop( (blinding_point, &node_signer), ); match decoded_hop { - Ok((next_hop_data, Some((next_hop_hmac, FixedSizeOnionPacket(new_packet_bytes))))) => { - match next_hop_data { - msgs::InboundOnionPayload::Forward(next_hop_data) => Ok(Hop::Forward { - shared_secret, - next_hop_data, - next_hop_hmac, - new_packet_bytes, - }), - msgs::InboundOnionPayload::BlindedForward(next_hop_data) => { - Ok(Hop::BlindedForward { - shared_secret, - next_hop_data, - next_hop_hmac, - new_packet_bytes, - }) - }, - msgs::InboundOnionPayload::Dummy(dummy_hop_data) => Ok(Hop::Dummy { - dummy_hop_data, - shared_secret, - next_hop_hmac, - new_packet_bytes, - }), - _ => { - if blinding_point.is_some() { - return Err(OnionDecodeErr::Malformed { - err_msg: - "Final Node OnionHopData provided for us as an intermediary node", - reason: LocalHTLCFailureReason::InvalidOnionBlinding, - }); - } - Err(OnionDecodeErr::Relay { + Ok((next_hop_data, Some((next_hop_hmac, new_packet_bytes)))) => match next_hop_data { + msgs::InboundOnionPayload::Forward(next_hop_data) => { + Ok(Hop::Forward { shared_secret, next_hop_data, next_hop_hmac, new_packet_bytes }) + }, + msgs::InboundOnionPayload::BlindedForward(next_hop_data) => Ok(Hop::BlindedForward { + shared_secret, + next_hop_data, + next_hop_hmac, + new_packet_bytes, + }), + msgs::InboundOnionPayload::Dummy(dummy_hop_data) => { + Ok(Hop::Dummy { dummy_hop_data, shared_secret, next_hop_hmac, new_packet_bytes }) + }, + _ => { + if blinding_point.is_some() { + return Err(OnionDecodeErr::Malformed { err_msg: "Final Node OnionHopData provided for us as an intermediary node", - reason: LocalHTLCFailureReason::InvalidOnionPayload, - shared_secret, - trampoline_shared_secret: None, - }) - }, - } + reason: LocalHTLCFailureReason::InvalidOnionBlinding, + }); + } + Err(OnionDecodeErr::Relay { + err_msg: "Final Node OnionHopData provided for us as an intermediary node", + reason: LocalHTLCFailureReason::InvalidOnionPayload, + shared_secret, + trampoline_shared_secret: None, + }) + }, }, Ok((next_hop_data, None)) => match next_hop_data { msgs::InboundOnionPayload::Receive(hop_data) => { @@ -2501,8 +2478,7 @@ pub(crate) fn decode_next_payment_hop( }); } Err(OnionDecodeErr::Malformed { - err_msg: - "Final Trampoline onion data provided to us as intermediate hop", + err_msg: "Final Trampoline onion data provided to us as intermediate hop", reason: LocalHTLCFailureReason::InvalidOnionBlinding, }) }, @@ -2518,8 +2494,7 @@ pub(crate) fn decode_next_payment_hop( }, Ok((msgs::InboundTrampolinePayload::Receive(_), Some(_))) => { Err(OnionDecodeErr::Relay { - err_msg: - "Final Trampoline onion data provided to us as intermediate hop", + err_msg: "Final Trampoline onion data provided to us as intermediate hop", reason: LocalHTLCFailureReason::InvalidTrampolinePayload, shared_secret, trampoline_shared_secret: Some(SharedSecret::from_bytes( @@ -3457,24 +3432,24 @@ mod tests { const EXPECTED_MESSAGES: [ExpectedMessage; 5] = [ ExpectedMessage { message: "146e94a9086dbbed6a0ab6932d00c118a7195dbf69b7d7a12b0e6956fc54b5e0a989f165b5f12fd45edd73a5b0c48630ff5be69500d3d82a29c0803f0a0679a6a073c33a6fb8250090a3152eba3f11a85184fa87b67f1b0354d6f48e3b342e332a17b7710f342f342a87cf32eccdf0afc2160808d58abb5e5840d2c760c538e63a6f841970f97d2e6fe5b8739dc45e2f7f5f532f227bcc2988ab0f9cc6d3f12909cd5842c37bc8c7608475a5ebbe10626d5ecc1f3388ad5f645167b44a4d166f87863fe34918cea25c18059b4c4d9cb414b59f6bc50c1cea749c80c43e2344f5d23159122ed4ab9722503b212016470d9610b46c35dbeebaf2e342e09770b38392a803bc9d2e7c8d6d384ffcbeb74943fe3f64afb2a543a6683c7db3088441c531eeb4647518cb41992f8954f1269fb969630944928c2d2b45593731b5da0c4e70d04a0a57afe4af42e99912fbb4f8883a5ecb9cb29b883cb6bfa0f4db2279ff8c6d2b56a232f55ba28fe7dfa70a9ab0433a085388f25cce8d53de6a2fbd7546377d6ede9027ad173ba1f95767461a3689ef405ab608a21086165c64b02c1782b04a6dba2361a7784603069124e12f2f6dcb1ec7612a4fbf94c0e14631a2bef6190c3d5f35e0c4b32aa85201f449d830fd8f782ec758b0910428e3ec3ca1dba3b6c7d89f69e1ee1b9df3dfbbf6d361e1463886b38d52e8f43b73a3bd48c6f36f5897f514b93364a31d49d1d506340b1315883d425cb36f4ea553430d538fd6f3596d4afc518db2f317dd051abc0d4bfb0a7870c3db70f19fe78d6604bbf088fcb4613f54e67b038277fedcd9680eb97bdffc3be1ab2cbcbafd625b8a7ac34d8c190f98d3064ecd3b95b8895157c6a37f31ef4de094b2cb9dbf8ff1f419ba0ecacb1bb13df0253b826bec2ccca1e745dd3b3e7cc6277ce284d649e7b8285727735ff4ef6cca6c18e2714f4e2a1ac67b25213d3bb49763b3b94e7ebf72507b71fb2fe0329666477ee7cb7ebd6b88ad5add8b217188b1ca0fa13de1ec09cc674346875105be6e0e0d6c8928eb0df23c39a639e04e4aedf535c4e093f08b2c905a14f25c0c0fe47a5a1535ab9eae0d9d67bdd79de13a08d59ee05385c7ea4af1ad3248e61dd22f8990e9e99897d653dd7b1b1433a6d464ea9f74e377f2d8ce99ba7dbc753297644234d25ecb5bd528e2e2082824681299ac30c05354baaa9c3967d86d7c07736f87fc0f63e5036d47235d7ae12178ced3ae36ee5919c093a02579e4fc9edad2c446c656c790704bfc8e2c491a42500aa1d75c8d4921ce29b753f883e17c79b09ea324f1f32ddf1f3284cd70e847b09d90f6718c42e5c94484cc9cbb0df659d255630a3f5a27e7d5dd14fa6b974d1719aa98f01a20fb4b7b1c77b42d57fab3c724339d459ee4a1c6b5d3bd4e08624c786a257872acc9ad3ff62222f2265a658d9f2a007229a5293b67ec91c84c4b4407c228434bad8a815ca9b256c776bd2c9f", - attribution_data: "d77d0711b5f71d1d1be56bd88b3bb7ebc1792bb739ea7ebc1bc3b031b8bc2df3a50e25aeb99f47d7f7ab39e24187d3f4df9c4333463b053832ee9ac07274a5261b8b2a01fc09ce9ea7cd04d7b585dfb8cf5958e3f3f2a4365d1ec0df1d83c6a6221b5b7d1ff30156a2289a1d3ee559e7c7256bda444bb8e046f860e00b3a59a85e1e1a43de215fd5e6bf646a5deab97b1912c934e31b1cfd344764d6ca7e14ea7b3f2a951aba907c964c0f5d19a44e6d1d7279637321fa598adde927b3087d238f8b426ecde500d318617cdb7a56e6ce3520fc95be41a549973764e4dc483853ecc313947709f1b5199cb077d46e701fa633e11d3e13b03e9212c115ca6fa004b2f3dd912814693b705a561a06da54cdf603677a3abecdc22c7358c2de3cef771b366a568150aeecc86ad1990bb0f4e2865933b03ea0df87901bff467908273dc6cea31cbab0e2b8d398d10b001058c259ed221b7b55762f4c7e49c8c11a45a107b7a2c605c26dc5b0b10d719b1c844670102b2b6a36c43fe4753a78a483fc39166ae28420f112d50c10ee64ca69569a2f690712905236b7c2cb7ac8954f02922d2d918c56d42649261593c47b14b324a65038c3c5be8d3c403ce0c8f19299b1664bf077d7cf1636c4fb9685a8e58b7029fd0939fa07925a60bed339b23f973293598f595e75c8f9d455d7cebe4b5e23357c8bd47d66d6628b39427e37e0aecbabf46c11be6771f7136e108a143ae9bafba0fc47a51b6c7deef4cba54bae906398ee3162a41f2191ca386b628bde7e1dd63d1611aa01a95c456df337c763cb8c3a81a6013aa633739d8cd554c688102211725e6adad165adc1bcd429d020c51b4b25d2117e8bb27eb0cc7020f9070d4ad19ac31a76ebdf5f9246646aeadbfb9a3f1d75bd8237961e786302516a1a781780e8b73f58dc06f307e58bd0eb1d8f5c9111f01312974c1dc777a6a2d3834d8a2a40014e9818d0685cb3919f6b3b788ddc640b0ff9b1854d7098c7dd6f35196e902b26709640bc87935a3914869a807e8339281e9cedaaca99474c3e7bdd35050bb998ab4546f9900904e0e39135e861ff7862049269701081ebce32e4cca992c6967ff0fd239e38233eaf614af31e186635e9439ec5884d798f9174da6ff569d68ed5c092b78bd3f880f5e88a7a8ab36789e1b57b035fb6c32a6358f51f83e4e5f46220bcad072943df8bd9541a61b7dae8f30fa3dd5fb39b1fd9a0b8e802552b78d4ec306ecee15bfe6da14b29ba6d19ce5be4dd478bca74a52429cd5309d404655c3dec85c252" + attribution_data: "d77d0711b5f71d1d1be56bd88b3bb7ebc1792bb739ea7ebc1bc3b031b8bc2df3a50e25aeb99f47d7f7ab39e24187d3f4df9c4333463b053832ee9ac07274a5261b8b2a01fc09ce9ea7cd04d7b585dfb8cf5958e3f3f2a4365d1ec0df1d83c6a6221b5b7d1ff30156a2289a1d3ee559e7c7256bda444bb8e046f860e00b3a59a85e1e1a43de215fd5e6bf646a5deab97b1912c934e31b1cfd344764d6ca7e14ea7b3f2a951aba907c964c0f5d19a44e6d1d7279637321fa598adde927b3087d238f8b426ecde500d318617cdb7a56e6ce3520fc95be41a549973764e4dc483853ecc313947709f1b5199cb077d46e701fa633e11d3e13b03e9212c115ca6fa004b2f3dd912814693b705a561a06da54cdf603677a3abecdc22c7358c2de3cef771b366a568150aeecc86ad1990bb0f4e2865933b03ea0df87901bff467908273dc6cea31cbab0e2b8d398d10b001058c259ed221b7b55762f4c7e49c8c11a45a107b7a2c605c26dc5b0b10d719b1c844670102b2b6a36c43fe4753a78a483fc39166ae28420f112d50c10ee64ca69569a2f690712905236b7c2cb7ac8954f02922d2d918c56d42649261593c47b14b324a65038c3c5be8d3c403ce0c8f19299b1664bf077d7cf1636c4fb9685a8e58b7029fd0939fa07925a60bed339b23f973293598f595e75c8f9d455d7cebe4b5e23357c8bd47d66d6628b39427e37e0aecbabf46c11be6771f7136e108a143ae9bafba0fc47a51b6c7deef4cba54bae906398ee3162a41f2191ca386b628bde7e1dd63d1611aa01a95c456df337c763cb8c3a81a6013aa633739d8cd554c688102211725e6adad165adc1bcd429d020c51b4b25d2117e8bb27eb0cc7020f9070d4ad19ac31a76ebdf5f9246646aeadbfb9a3f1d75bd8237961e786302516a1a781780e8b73f58dc06f307e58bd0eb1d8f5c9111f01312974c1dc777a6a2d3834d8a2a40014e9818d0685cb3919f6b3b788ddc640b0ff9b1854d7098c7dd6f35196e902b26709640bc87935a3914869a807e8339281e9cedaaca99474c3e7bdd35050bb998ab4546f9900904e0e39135e861ff7862049269701081ebce32e4cca992c6967ff0fd239e38233eaf614af31e186635e9439ec5884d798f9174da6ff569d68ed5c092b78bd3f880f5e88a7a8ab36789e1b57b035fb6c32a6358f51f83e4e5f46220bcad072943df8bd9541a61b7dae8f30fa3dd5fb39b1fd9a0b8e802552b78d4ec306ecee15bfe6da14b29ba6d19ce5be4dd478bca74a52429cd5309d404655c3dec85c252", }, ExpectedMessage { message: "7512354d6a26781d25e65539772ba049b7ed7c530bf75ab7ef80cf974b978a07a1c3dabc61940011585323f70fa98cfa1d4c868da30b1f751e44a72d9b3f79809c8c51c9f0843daa8fe83587844fedeacb7348362003b31922cbb4d6169b2087b6f8d192d9cfe5363254cd1fde24641bde9e422f170c3eb146f194c48a459ae2889d706dc654235fa9dd20307ea54091d09970bf956c067a3bcc05af03c41e01af949a131533778bf6ee3b546caf2eabe9d53d0fb2e8cc952b7e0f5326a69ed2e58e088729a1d85971c6b2e129a5643f3ac43da031e655b27081f10543262cf9d72d6f64d5d96387ac0d43da3e3a03da0c309af121dcf3e99192efa754eab6960c256ffd4c546208e292e0ab9894e3605db098dc16b40f17c320aa4a0e42fc8b105c22f08c9bc6537182c24e32062c6cd6d7ec7062a0c2c2ecdae1588c82185cdc61d874ee916a7873ac54cddf929354f307e870011704a0e9fbc5c7802d6140134028aca0e78a7e2f3d9e5c7e49e20c3a56b624bfea51196ec9e88e4e56be38ff56031369f45f1e03be826d44a182f270c153ee0d9f8cf9f1f4132f33974e37c7887d5b857365c873cb218cbf20d4be3abdb2a2011b14add0a5672e01e5845421cf6dd6faca1f2f443757aae575c53ab797c2227ecdab03882bbbf4599318cefafa72fa0c9a0f5a51d13c9d0e5d25bfcfb0154ed25895260a9df8743ac188714a3f16960e6e2ff663c08bffda41743d50960ea2f28cda0bc3bd4a180e297b5b41c700b674cb31d99c7f2a1445e121e772984abff2bbe3f42d757ceeda3d03fb1ffe710aecabda21d738b1f4620e757e57b123dbc3c4aa5d9617dfa72f4a12d788ca596af14bea583f502f16fdc13a5e739afb0715424af2767049f6b9aa107f69c5da0e85f6d8c5e46507e14616d5d0b797c3dea8b74a1b12d4e47ba7f57f09d515f6c7314543f78b5e85329d50c5f96ee2f55bbe0df742b4003b24ccbd4598a64413ee4807dc7f2a9c0b92424e4ae1b418a3cdf02ea4da5c3b12139348aa7022cc8272a3a1714ee3e4ae111cffd1bdfd62c503c80bdf27b2feaea0d5ab8fe00f9cec66e570b00fd24b4a2ed9a5f6384f148a4d6325110a41ca5659ebc5b98721d298a52819b6fb150f273383f1c5754d320be428941922da790e17f482989c365c078f7f3ae100965e1b38c052041165295157e1a7c5b7a57671b842d4d85a7d971323ad1f45e17a16c4656d889fc75c12fc3d8033f598306196e29571e414281c5da19c12605f48347ad5b4648e371757cbe1c40adb93052af1d6110cfbf611af5c8fc682b7e2ade3bfca8b5c7717d19fc9f97964ba6025aebbc91a6671e259949dcf40984342118de1f6b514a7786bd4f6598ffbe1604cef476b2a4cb1343db608aca09d1d38fc23e98ee9c65e7f6023a8d1e61fd4f34f753454bd8e858c8ad6be6403edc599c220e03ca917db765980ac781e758179cd93983e9c1e769e4241d47c", - attribution_data: "1571e10db7f8aa9f8e7e99caaf9c892e106c817df1d8e3b7b0e39d1c48f631e473e17e205489dd7b3c634cac3be0825cbf01418cd46e83c24b8d9c207742db9a0f0e5bcd888086498159f08080ba7bf36dee297079eb841391ccd3096da76461e314863b6412efe0ffe228d51c6097db10d3edb2e50ea679820613bfe9db11ba02920ab4c1f2a79890d997f1fc022f3ab78f0029cc6de0c90be74d55f4a99bf77a50e20f8d076fe61776190a61d2f41c408871c0279309cba3b60fcdc7efc4a0e90b47cb4a418fc78f362ecc7f15ebbce9f854c09c7be300ebc1a40a69d4c7cb7a19779b6905e82bec221a709c1dab8cbdcde7b527aca3f54bde651aa9f3f2178829cee3f1c0b9292758a40cc63bd998fcd0d3ed4bdcaf1023267b8f8e44130a63ad15f76145936552381eabb6d684c0a3af6ba8efcf207cebaea5b7acdbb63f8e7221102409d10c23f0514dc9f4d0efb2264161a193a999a23e992632710580a0d320f676d367b9190721194514457761af05207cdab2b6328b1b3767eacb36a7ef4f7bd2e16762d13df188e0898b7410f62459458712a44bf594ae662fd89eb300abb6952ff8ad40164f2bcd7f86db5c7650b654b79046de55d51aa8061ce35f867a3e8f5bf98ad920be827101c64fb871d86e53a4b3c0455bfac5784168218aa72cbee86d9c750a9fa63c363a8b43d7bf4b2762516706a306f0aa3be1ec788b5e13f8b24837e53ac414f211e11c7a093cd9653dfa5fba4e377c79adfa5e841e2ddb6afc054fc715c05ddc6c8fc3e1ee3406e1ffceb2df77dc2f02652614d1bfcfaddebaa53ba919c7051034e2c7b7cfaabdf89f26e7f8e3f956d205dfab747ad0cb505b85b54a68439621b25832cbc2898919d0cd7c0a64cfd235388982dd4dd68240cb668f57e1d2619a656ed326f8c92357ee0d9acead3c20008bc5f04ca8059b55d77861c6d04dfc57cfba57315075acbe1451c96cf28e1e328e142890248d18f53b5d3513ce574dea7156cf596fdb3d909095ec287651f9cf1bcdc791c5938a5dd9b47e84c004d24ab3ae74492c7e8dcc1da15f65324be2672947ec82074cac8ce2b925bc555facbbf1b55d63ea6fbea6a785c97d4caf2e1dad9551b7f66c31caae5ebc7c0047e892f201308fcf452c588be0e63d89152113d87bf0dbd01603b4cdc7f0b724b0714a9851887a01f709408882e18230fe810b9fafa58a666654576d8eba3005f07221f55a6193815a672e5db56204053bc4286fa3db38250396309fd28011b5708a26a2d76c4a333b69b6bfd272fb" + attribution_data: "1571e10db7f8aa9f8e7e99caaf9c892e106c817df1d8e3b7b0e39d1c48f631e473e17e205489dd7b3c634cac3be0825cbf01418cd46e83c24b8d9c207742db9a0f0e5bcd888086498159f08080ba7bf36dee297079eb841391ccd3096da76461e314863b6412efe0ffe228d51c6097db10d3edb2e50ea679820613bfe9db11ba02920ab4c1f2a79890d997f1fc022f3ab78f0029cc6de0c90be74d55f4a99bf77a50e20f8d076fe61776190a61d2f41c408871c0279309cba3b60fcdc7efc4a0e90b47cb4a418fc78f362ecc7f15ebbce9f854c09c7be300ebc1a40a69d4c7cb7a19779b6905e82bec221a709c1dab8cbdcde7b527aca3f54bde651aa9f3f2178829cee3f1c0b9292758a40cc63bd998fcd0d3ed4bdcaf1023267b8f8e44130a63ad15f76145936552381eabb6d684c0a3af6ba8efcf207cebaea5b7acdbb63f8e7221102409d10c23f0514dc9f4d0efb2264161a193a999a23e992632710580a0d320f676d367b9190721194514457761af05207cdab2b6328b1b3767eacb36a7ef4f7bd2e16762d13df188e0898b7410f62459458712a44bf594ae662fd89eb300abb6952ff8ad40164f2bcd7f86db5c7650b654b79046de55d51aa8061ce35f867a3e8f5bf98ad920be827101c64fb871d86e53a4b3c0455bfac5784168218aa72cbee86d9c750a9fa63c363a8b43d7bf4b2762516706a306f0aa3be1ec788b5e13f8b24837e53ac414f211e11c7a093cd9653dfa5fba4e377c79adfa5e841e2ddb6afc054fc715c05ddc6c8fc3e1ee3406e1ffceb2df77dc2f02652614d1bfcfaddebaa53ba919c7051034e2c7b7cfaabdf89f26e7f8e3f956d205dfab747ad0cb505b85b54a68439621b25832cbc2898919d0cd7c0a64cfd235388982dd4dd68240cb668f57e1d2619a656ed326f8c92357ee0d9acead3c20008bc5f04ca8059b55d77861c6d04dfc57cfba57315075acbe1451c96cf28e1e328e142890248d18f53b5d3513ce574dea7156cf596fdb3d909095ec287651f9cf1bcdc791c5938a5dd9b47e84c004d24ab3ae74492c7e8dcc1da15f65324be2672947ec82074cac8ce2b925bc555facbbf1b55d63ea6fbea6a785c97d4caf2e1dad9551b7f66c31caae5ebc7c0047e892f201308fcf452c588be0e63d89152113d87bf0dbd01603b4cdc7f0b724b0714a9851887a01f709408882e18230fe810b9fafa58a666654576d8eba3005f07221f55a6193815a672e5db56204053bc4286fa3db38250396309fd28011b5708a26a2d76c4a333b69b6bfd272fb", }, ExpectedMessage { message: "145bc1c63058f7204abbd2320d422e69fb1b3801a14312f81e5e29e6b5f4774cfed8a25241d3dfb7466e749c1b3261559e49090853612e07bd669dfb5f4c54162fa504138dabd6ebcf0db8017840c35f12a2cfb84f89cc7c8959a6d51815b1d2c5136cedec2e4106bb5f2af9a21bd0a02c40b44ded6e6a90a145850614fb1b0eef2a03389f3f2693bc8a755630fc81fff1d87a147052863a71ad5aebe8770537f333e07d841761ec448257f948540d8f26b1d5b66f86e073746106dfdbb86ac9475acf59d95ece037fba360670d924dce53aaa74262711e62a8fc9eb70cd8618fbedae22853d3053c7f10b1a6f75369d7f73c419baa7dbf9f1fc5895362dcc8b6bd60cca4943ef7143956c91992119bccbe1666a20b7de8a2ff30a46112b53a6bb79b763903ecbd1f1f74952fb1d8eb0950c504df31fe702679c23b463f82a921a2c931500ab08e686cffb2d87258d254fb17843959cccd265a57ba26c740f0f231bb76df932b50c12c10be90174b37d454a3f8b284c849e86578a6182c4a7b2e47dd57d44730a1be9fec4ad07287a397e28dce4fda57e9cdfdb2eb5afdf0d38ef19d982341d18d07a556bb16c1416f480a396f278373b8fd9897023a4ac506e65cf4c306377730f9c8ca63cf47565240b59c4861e52f1dab84d938e96fb31820064d534aca05fd3d2600834fe4caea98f2a748eb8f200af77bd9fbf46141952b9ddda66ef0ebea17ea1e7bb5bce65b6e71554c56dd0d4e14f4cf74c77a150776bf31e7419756c71e7421dc22efe9cf01de9e19fc8808d5b525431b944400db121a77994518d6025711cb25a18774068bba7faaa16d8f65c91bec8768848333156dcb4a08dfbbd9fef392da3e4de13d4d74e83a7d6e46cfe530ee7a6f711e2caf8ad5461ba8177b2ef0a518baf9058ff9156e6aa7b08d938bd8d1485a787809d7b4c8aed97be880708470cd2b2cdf8e2f13428cc4b04ef1f2acbc9562f3693b948d0aa94b0e6113cafa684f8e4a67dc431dfb835726874bef1de36f273f52ee694ec46b0700f77f8538067642a552968e866a72a3f2031ad116663ac17b172b446c5bc705b84777363a9a3fdc6443c07b2f4ef58858122168d4ebbaee920cefc312e1cea870ed6e15eec046ab2073bbf08b0a3366f55cfc6ad4681a12ab0946534e7b6f90ea8992d530ec3daa6b523b3cf03101c60cadd914f30dec932c1ef4341b5a8efac3c921e203574cfe0f1f83433fddb8ccfd273f7c3cab7bc27efe3bb61fdccd5146f1185364b9b621e7fb2b74b51f5ee6be72ab6ff46a6359dc2c855e61469724c1dbeb273df9d2e1c1fb74891239c0019dc12d5c7535f7238f963b761d7102b585372cf021b64c4fc85bfb3161e59d2e298bba44cfd34d6859d9dba9dc6271e5047d525468c814f2ae438474b0a977273036da1a2292f88fcfb89574a6bdca1185b40f8aa54026d5926725f99ef028da1be892e3586361efe15f4a148ff1bc9", - attribution_data: "34e34397b8621ec2f2b54dbe6c14073e267324cd60b152bce76aec8729a6ddefb61bc263be4b57bd592aae604a32bea69afe6ef4a6b573c26b17d69381ec1fc9b5aa769d148f2f1f8b5377a73840bb6dc641f68e356323d766fff0aaca5039fe7fc27038195844951a97d5a5b26698a4ca1e9cd4bca1fcca0aac5fee91b18977d2ad0e399ba159733fc98f6e96898ebc39bf0028c9c81619233bab6fad0328aa183a635fac20437fa6e00e899b2527c3697a8ab7342e42d55a679b176ab76671fcd480a9894cb897fa6af0a45b917a162bed6c491972403185df7235502f7ada65769d1bfb12d29f10e25b0d3cc08bbf6de8481ac5c04df32b4533b4f764c2aefb7333202645a629fb16e4a208e9045dc36830759c852b31dd613d8b2b10bbead1ed4eb60c85e8a4517deba5ab53e39867c83c26802beee2ee545bdd713208751added5fc0eb2bc89a5aa2decb18ee37dac39f22a33b60cc1a369d24de9f3d2d8b63c039e248806de4e36a47c7a0aed30edd30c3d62debdf1ad82bf7aedd7edec413850d91c261e12beec7ad1586a9ad25b2db62c58ca17119d61dcc4f3e5c4520c42a8e384a45d8659b338b3a08f9e123a1d3781f5fc97564ccff2c1d97f06fa0150cfa1e20eacabefb0c339ec109336d207cc63d9170752fc58314c43e6d4a528fd0975afa85f3aa186ff1b6b8cb12c97ed4ace295b0ef5f075f0217665b8bb180246b87982d10f43c9866b22878106f5214e99188781180478b07764a5e12876ddcb709e0a0a8dd42cf004c695c6fc1669a6fd0e4a1ca54b024d0d80eac492a9e5036501f36fb25b72a054189294955830e43c18e55668337c8c6733abb09fc2d4ade18d5a853a2b82f7b4d77151a64985004f1d9218f2945b63c56fdebd1e96a2a7e49fa70acb4c39873947b83c191c10e9a8f40f60f3ad5a2be47145c22ea59ed3f5f4e61cb069e875fb67142d281d784bf925cc286eacc2c43e94d08da4924b83e58dbf2e43fa625bdd620eba6d9ce960ff17d14ed1f2dbee7d08eceb540fdc75ff06dabc767267658fad8ce99e2a3236e46d2deedcb51c3c6f81589357edebac9772a70b3d910d83cd1b9ce6534a011e9fa557b891a23b5d88afcc0d9856c6dabeab25eea55e9a248182229e4927f268fe5431672fcce52f434ca3d27d1a2136bae5770bb36920df12fbc01d0e8165610efa04794f414c1417f1d4059435c5385bfe2de83ce0e238d6fd2dbd3c0487c69843298577bfa480fe2a16ab2a0e4bc712cd8b5a14871cda61c993b6835303d9043d7689a" + attribution_data: "34e34397b8621ec2f2b54dbe6c14073e267324cd60b152bce76aec8729a6ddefb61bc263be4b57bd592aae604a32bea69afe6ef4a6b573c26b17d69381ec1fc9b5aa769d148f2f1f8b5377a73840bb6dc641f68e356323d766fff0aaca5039fe7fc27038195844951a97d5a5b26698a4ca1e9cd4bca1fcca0aac5fee91b18977d2ad0e399ba159733fc98f6e96898ebc39bf0028c9c81619233bab6fad0328aa183a635fac20437fa6e00e899b2527c3697a8ab7342e42d55a679b176ab76671fcd480a9894cb897fa6af0a45b917a162bed6c491972403185df7235502f7ada65769d1bfb12d29f10e25b0d3cc08bbf6de8481ac5c04df32b4533b4f764c2aefb7333202645a629fb16e4a208e9045dc36830759c852b31dd613d8b2b10bbead1ed4eb60c85e8a4517deba5ab53e39867c83c26802beee2ee545bdd713208751added5fc0eb2bc89a5aa2decb18ee37dac39f22a33b60cc1a369d24de9f3d2d8b63c039e248806de4e36a47c7a0aed30edd30c3d62debdf1ad82bf7aedd7edec413850d91c261e12beec7ad1586a9ad25b2db62c58ca17119d61dcc4f3e5c4520c42a8e384a45d8659b338b3a08f9e123a1d3781f5fc97564ccff2c1d97f06fa0150cfa1e20eacabefb0c339ec109336d207cc63d9170752fc58314c43e6d4a528fd0975afa85f3aa186ff1b6b8cb12c97ed4ace295b0ef5f075f0217665b8bb180246b87982d10f43c9866b22878106f5214e99188781180478b07764a5e12876ddcb709e0a0a8dd42cf004c695c6fc1669a6fd0e4a1ca54b024d0d80eac492a9e5036501f36fb25b72a054189294955830e43c18e55668337c8c6733abb09fc2d4ade18d5a853a2b82f7b4d77151a64985004f1d9218f2945b63c56fdebd1e96a2a7e49fa70acb4c39873947b83c191c10e9a8f40f60f3ad5a2be47145c22ea59ed3f5f4e61cb069e875fb67142d281d784bf925cc286eacc2c43e94d08da4924b83e58dbf2e43fa625bdd620eba6d9ce960ff17d14ed1f2dbee7d08eceb540fdc75ff06dabc767267658fad8ce99e2a3236e46d2deedcb51c3c6f81589357edebac9772a70b3d910d83cd1b9ce6534a011e9fa557b891a23b5d88afcc0d9856c6dabeab25eea55e9a248182229e4927f268fe5431672fcce52f434ca3d27d1a2136bae5770bb36920df12fbc01d0e8165610efa04794f414c1417f1d4059435c5385bfe2de83ce0e238d6fd2dbd3c0487c69843298577bfa480fe2a16ab2a0e4bc712cd8b5a14871cda61c993b6835303d9043d7689a", }, ExpectedMessage { message: "1b4b09a935ce7af95b336baae307f2b400e3a7e808d9b4cf421cc4b3955620acb69dcdb656128dae8857adbd4e6b37fbb1be9c1f2f02e61e9e59a630c4c77cf383cb37b07413aa4de2f2fbf5b40ae40a91a8f4c6d74aeacef1bb1be4ecbc26ec2c824d2bc45db4b9098e732a769788f1cff3f5b41b0d25c132d40dc5ad045ef0043b15332ca3c5a09de2cdb17455a0f82a8f20da08346282823dab062cdbd2111e238528141d69de13de6d83994fbc711e3e269df63a12d3a4177c5c149150eb4dc2f589cd8acabcddba14dec3b0dada12d663b36176cd3c257c5460bab93981ad99f58660efa9b31d7e63b39915329695b3fa60e0a3bdb93e7e29a54ca6a8f360d3848866198f9c3da3ba958e7730847fe1e6478ce8597848d3412b4ae48b06e05ba9a104e648f6eaf183226b5f63ed2e68f77f7e38711b393766a6fab7921b03eba82b5d7cb78e34dc961948d6161eadd7cf5d95d9c56df2ff5faa6ccf85eacdc9ff2fc3abafe41c365a5bd14fd486d6b5e2f24199319e7813e02e798877ffe31a70ae2398d9e31b9e3727e6c1a3c0d995c67d37bb6e72e9660aaaa9232670f382add2edd468927e3303b6142672546997fe105583e7c5a3c4c2b599731308b5416e6c9a3f3ba55b181ad0439d3535356108b059f2cb8742eed7a58d4eba9fe79eaa77c34b12aff1abdaea93197aabd0e74cb271269ca464b3b06aef1d6573df5e1224179616036b368677f26479376681b772d3760e871d99efd34cca5cd6beca95190d967da820b21e5bec60082ea46d776b0517488c84f26d12873912d1f68fafd67bcf4c298e43cfa754959780682a2db0f75f95f0598c0d04fd014c50e4beb86a9e37d95f2bba7e5065ae052dc306555bca203d104c44a538b438c9762de299e1c4ad30d5b4a6460a76484661fc907682af202cd69b9a4473813b2fdc1142f1403a49b7e69a650b7cde9ff133997dcc6d43f049ecac5fce097a21e2bce49c810346426585e3a5a18569b4cddd5ff6bdec66d0b69fcbc5ab3b137b34cc8aefb8b850a764df0e685c81c326611d901c392a519866e132bbb73234f6a358ba284fbafb21aa3605cacbaf9d0c901390a98b7a7dac9d4f0b405f7291c88b2ff45874241c90ac6c5fc895a440453c344d3a365cb929f9c91b9e39cb98b142444aae03a6ae8284c77eb04b0a163813d4c21883df3c0f398f47bf127b5525f222107a2d8fe55289f0cfd3f4bbad6c5387b0594ef8a966afc9e804ccaf75fe39f35c6446f7ee076d433f2f8a44dba1515acc78e589fa8c71b0a006fe14feebd51d0e0aa4e51110d16759eee86192eee90b34432130f387e0ccd2ee71023f1f641cddb571c690107e08f592039fe36d81336a421e89378f351e633932a2f5f697d25b620ffb8e84bb6478e9bd229bf3b164b48d754ae97bd23f319e3c56b3bcdaaeb3bd7fc02ec02066b324cb72a09b6b43dec1097f49d69d3c138ce6f1a6402898baf7568c", - attribution_data: "74a4ea61339463642a2182758871b2ea724f31f531aa98d80f1c3043febca41d5ee52e8b1e127e61719a0d078db8909748d57839e58424b91f063c4fbc8a221bef261140e66a9b596ca6d420a973ad54fef30646ae53ccf0855b61f291a81e0ec6dc0f6bf69f0ca0e5889b7e23f577ba67d2a7d6a2aa91264ab9b20630ed52f8ed56cc10a869807cd1a4c2cd802d8433fee5685d6a04edb0bff248a480b93b01904bed3bb31705d1ecb7332004290cc0cd9cc2f7907cf9db28eec02985301668f53fbc28c3e095c8f3a6cd8cab28e5e442fd9ba608b8b12e098731bbfda755393bd403c62289093b40390b2bae337fc87d2606ca028311d73a9ffbdffef56020c735ada30f54e577c6a9ec515ae2739290609503404b118d7494499ecf0457d75015bb60a16288a4959d74cf5ac5d8d6c113de39f748a418d2a7083b90c9c0a09a49149fd1f2d2cde4412e5aa2421eca6fd4f6fe6b2c362ff37d1a0608c931c7ca3b8fefcfd4c44ef9c38357a0767b14f83cb49bd1989fb3f8e2ab202ac98bd8439790764a40bf309ea2205c1632610956495720030a25dc7118e0c868fdfa78c3e9ecce58215579a0581b3bafdb7dbbe53be9e904567fdc0ce1236aab5d22f1ebc18997e3ea83d362d891e04c5785fd5238326f767bce499209f8db211a50e1402160486e98e7235cf397dbb9ae19fd9b79ef589c821c6f99f28be33452405a003b33f4540fe0a41dfcc286f4d7cc10b70552ba7850869abadcd4bb7f256823face853633d6e2a999ac9fcd259c71d08e266db5d744e1909a62c0db673745ad9585949d108ab96640d2bc27fb4acac7fa8b170a30055a5ede90e004df9a44bdc29aeb4a6bec1e85dde1de6aaf01c6a5d12405d0bec22f49026cb23264f8c04b8401d3c2ab6f2e109948b6193b3bec27adfe19fb8afb8a92364d6fc5b219e8737d583e7ff3a4bcb75d53edda3bf3f52896ac36d8a877ad9f296ea6c045603fc62ac4ae41272bde85ef7c3b3fd3538aacfd5b025fefbe277c2906821ecb20e6f75ea479fa3280f9100fb0089203455c56b6bc775e5c2f0f58c63edd63fa3eec0b40da4b276d0d41da2ec0ead865a98d12bc694e23d8eaadd2b4d0ee88e9570c88fb878930f492e036d27998d593e47763927ff7eb80b188864a3846dd2238f7f95f4090ed399ae95deaeb37abca1cf37c397cc12189affb42dca46b4ff6988eb8c060691d155302d448f50ff70a794d97c0408f8cee9385d6a71fa412e36edcb22dbf433db9db4779f27b682ee17fc05e70c8e794b9f7f6d1" + attribution_data: "74a4ea61339463642a2182758871b2ea724f31f531aa98d80f1c3043febca41d5ee52e8b1e127e61719a0d078db8909748d57839e58424b91f063c4fbc8a221bef261140e66a9b596ca6d420a973ad54fef30646ae53ccf0855b61f291a81e0ec6dc0f6bf69f0ca0e5889b7e23f577ba67d2a7d6a2aa91264ab9b20630ed52f8ed56cc10a869807cd1a4c2cd802d8433fee5685d6a04edb0bff248a480b93b01904bed3bb31705d1ecb7332004290cc0cd9cc2f7907cf9db28eec02985301668f53fbc28c3e095c8f3a6cd8cab28e5e442fd9ba608b8b12e098731bbfda755393bd403c62289093b40390b2bae337fc87d2606ca028311d73a9ffbdffef56020c735ada30f54e577c6a9ec515ae2739290609503404b118d7494499ecf0457d75015bb60a16288a4959d74cf5ac5d8d6c113de39f748a418d2a7083b90c9c0a09a49149fd1f2d2cde4412e5aa2421eca6fd4f6fe6b2c362ff37d1a0608c931c7ca3b8fefcfd4c44ef9c38357a0767b14f83cb49bd1989fb3f8e2ab202ac98bd8439790764a40bf309ea2205c1632610956495720030a25dc7118e0c868fdfa78c3e9ecce58215579a0581b3bafdb7dbbe53be9e904567fdc0ce1236aab5d22f1ebc18997e3ea83d362d891e04c5785fd5238326f767bce499209f8db211a50e1402160486e98e7235cf397dbb9ae19fd9b79ef589c821c6f99f28be33452405a003b33f4540fe0a41dfcc286f4d7cc10b70552ba7850869abadcd4bb7f256823face853633d6e2a999ac9fcd259c71d08e266db5d744e1909a62c0db673745ad9585949d108ab96640d2bc27fb4acac7fa8b170a30055a5ede90e004df9a44bdc29aeb4a6bec1e85dde1de6aaf01c6a5d12405d0bec22f49026cb23264f8c04b8401d3c2ab6f2e109948b6193b3bec27adfe19fb8afb8a92364d6fc5b219e8737d583e7ff3a4bcb75d53edda3bf3f52896ac36d8a877ad9f296ea6c045603fc62ac4ae41272bde85ef7c3b3fd3538aacfd5b025fefbe277c2906821ecb20e6f75ea479fa3280f9100fb0089203455c56b6bc775e5c2f0f58c63edd63fa3eec0b40da4b276d0d41da2ec0ead865a98d12bc694e23d8eaadd2b4d0ee88e9570c88fb878930f492e036d27998d593e47763927ff7eb80b188864a3846dd2238f7f95f4090ed399ae95deaeb37abca1cf37c397cc12189affb42dca46b4ff6988eb8c060691d155302d448f50ff70a794d97c0408f8cee9385d6a71fa412e36edcb22dbf433db9db4779f27b682ee17fc05e70c8e794b9f7f6d1", }, ExpectedMessage { message: "2dd2f49c1f5af0fcad371d96e8cddbdcd5096dc309c1d4e110f955926506b3c03b44c192896f45610741c85ed4074212537e0c118d472ff3a559ae244acd9d783c65977765c5d4e00b723d00f12475aafaafff7b31c1be5a589e6e25f8da2959107206dd42bbcb43438129ce6cce2b6b4ae63edc76b876136ca5ea6cd1c6a04ca86eca143d15e53ccdc9e23953e49dc2f87bb11e5238cd6536e57387225b8fff3bf5f3e686fd08458ffe0211b87d64770db9353500af9b122828a006da754cf979738b4374e146ea79dd93656170b89c98c5f2299d6e9c0410c826c721950c780486cd6d5b7130380d7eaff994a8503a8fef3270ce94889fe996da66ed121741987010f785494415ca991b2e8b39ef2df6bde98efd2aec7d251b2772485194c8368451ad49c2354f9d30d95367bde316fec6cbdddc7dc0d25e99d3075e13d3de0822669861dafcd29de74eac48b64411987285491f98d78584d0c2a163b7221ea796f9e8671b2bb91e38ef5e18aaf32c6c02f2fb690358872a1ed28166172631a82c2568d23238017188ebbd48944a147f6cdb3690d5f88e51371cb70adf1fa02afe4ed8b581afc8bcc5104922843a55d52acde09bc9d2b71a663e178788280f3c3eae127d21b0b95777976b3eb17be40a702c244d0e5f833ff49dae6403ff44b131e66df8b88e33ab0a58e379f2c34bf5113c66b9ea8241fc7aa2b1fa53cf4ed3cdd91d407730c66fb039ef3a36d4050dde37d34e80bcfe02a48a6b14ae28227b1627b5ad07608a7763a531f2ffc96dff850e8c583461831b19feffc783bc1beab6301f647e9617d14c92c4b1d63f5147ccda56a35df8ca4806b8884c4aa3c3cc6a174fdc2232404822569c01aba686c1df5eecc059ba97e9688c8b16b70f0d24eacfdba15db1c71f72af1b2af85bd168f0b0800483f115eeccd9b02adf03bdd4a88eab03e43ce342877af2b61f9d3d85497cd1c6b96674f3d4f07f635bb26add1e36835e321d70263b1c04234e222124dad30ffb9f2a138e3ef453442df1af7e566890aedee568093aa922dd62db188aa8361c55503f8e2c2e6ba93de744b55c15260f15ec8e69bb01048ca1fa7bbbd26975bde80930a5b95054688a0ea73af0353cc84b997626a987cc06a517e18f91e02908829d4f4efc011b9867bd9bfe04c5f94e4b9261d30cc39982eb7b250f12aee2a4cce0484ff34eebba89bc6e35bd48d3968e4ca2d77527212017e202141900152f2fd8af0ac3aa456aae13276a13b9b9492a9a636e18244654b3245f07b20eb76b8e1cea8c55e5427f08a63a16b0a633af67c8e48ef8e53519041c9138176eb14b8782c6c2ee76146b8490b97978ee73cd0104e12f483be5a4af414404618e9f6633c55dda6f22252cb793d3d16fae4f0e1431434e7acc8fa2c009d4f6e345ade172313d558a4e61b4377e31b8ed4e28f7cd13a7fe3f72a409bc3bdabfe0ba47a6d861e21f64d2fac706dab18b3e546df4", - attribution_data: "84986c936d26bfd3bb2d34d3ec62cfdb63e0032fdb3d9d75f3e5d456f73dffa7e35aab1db4f1bd3b98ff585caf004f656c51037a3f4e810d275f3f6aea0c8e3a125ebee5f374b6440bcb9bb2955ebf706f42be9999a62ed49c7a81fc73c0b4a16419fd6d334532f40bf179dd19afec21bd8519d5e6ebc3802501ef373bc378eee1f14a6fc5fab5b697c91ce31d5922199d1b0ad5ee12176aacafc7c81d54bc5b8fb7e63f3bfd40a3b6e21f985340cbd1c124c7f85f0369d1aa86ebc66def417107a7861131c8bcd73e8946f4fb54bfac87a2dc15bd7af642f32ae583646141e8875ef81ec9083d7e32d5f135131eab7a43803360434100ff67087762bbe3d6afe2034f5746b8c50e0c3c20dd62a4c174c38b1df7365dccebc7f24f19406649fbf48981448abe5c858bbd4bef6eb983ae7a23e9309fb33b5e7c0522554e88ca04b1d65fc190947dead8c0ccd32932976537d869b5ca53ed4945bccafab2a014ea4cbdc6b0250b25be66ba0afff2ff19c0058c68344fd1b9c472567147525b13b1bc27563e61310110935cf89fda0e34d0575e2389d57bdf2869398ca2965f64a6f04e1d1c2edf2082b97054264a47824dd1a9691c27902b39d57ae4a94dd6481954a9bd1b5cff4ab29ca221fa2bf9b28a362c9661206f896fc7cec563fb80aa5eaccb26c09fa4ef7a981e63028a9c4dac12f82ccb5bea090d56bbb1a4c431e315d9a169299224a8dbd099fb67ea61dfc604edf8a18ee742550b636836bb552dabb28820221bf8546331f32b0c143c1c89310c4fa2e1e0e895ce1a1eb0f43278fdb528131a3e32bfffe0c6de9006418f5309cba773ca38b6ad8507cc59445ccc0257506ebc16a4c01d4cd97e03fcf7a2049fea0db28447858f73b8e9fe98b391b136c9dc510288630a1f0af93b26a8891b857bfe4b818af99a1e011e6dbaa53982d29cf74ae7dffef45545279f19931708ed3eede5e82280eab908e8eb80abff3f1f023ab66869297b40da8496861dc455ac3abe1efa8a6f9e2c4eda48025d43a486a3f26f269743eaa30d6f0e1f48db6287751358a41f5b07aee0f098862e3493731fe2697acce734f004907c6f11eef189424fee52cd30ad708707eaf2e441f52bcf3d0c5440c1742458653c0c8a27b5ade784d9e09c8b47f1671901a29360e7e5e94946b9c75752a1a8d599d2a3e14ac81b84d42115cd688c8383a64fc6e7e1dc5568bb4837358ebe63207a4067af66b2027ad2ce8fb7ae3a452d40723a51fdf9f9c9913e8029a222cf81d12ad41e58860d75deb6de30ad" - } + attribution_data: "84986c936d26bfd3bb2d34d3ec62cfdb63e0032fdb3d9d75f3e5d456f73dffa7e35aab1db4f1bd3b98ff585caf004f656c51037a3f4e810d275f3f6aea0c8e3a125ebee5f374b6440bcb9bb2955ebf706f42be9999a62ed49c7a81fc73c0b4a16419fd6d334532f40bf179dd19afec21bd8519d5e6ebc3802501ef373bc378eee1f14a6fc5fab5b697c91ce31d5922199d1b0ad5ee12176aacafc7c81d54bc5b8fb7e63f3bfd40a3b6e21f985340cbd1c124c7f85f0369d1aa86ebc66def417107a7861131c8bcd73e8946f4fb54bfac87a2dc15bd7af642f32ae583646141e8875ef81ec9083d7e32d5f135131eab7a43803360434100ff67087762bbe3d6afe2034f5746b8c50e0c3c20dd62a4c174c38b1df7365dccebc7f24f19406649fbf48981448abe5c858bbd4bef6eb983ae7a23e9309fb33b5e7c0522554e88ca04b1d65fc190947dead8c0ccd32932976537d869b5ca53ed4945bccafab2a014ea4cbdc6b0250b25be66ba0afff2ff19c0058c68344fd1b9c472567147525b13b1bc27563e61310110935cf89fda0e34d0575e2389d57bdf2869398ca2965f64a6f04e1d1c2edf2082b97054264a47824dd1a9691c27902b39d57ae4a94dd6481954a9bd1b5cff4ab29ca221fa2bf9b28a362c9661206f896fc7cec563fb80aa5eaccb26c09fa4ef7a981e63028a9c4dac12f82ccb5bea090d56bbb1a4c431e315d9a169299224a8dbd099fb67ea61dfc604edf8a18ee742550b636836bb552dabb28820221bf8546331f32b0c143c1c89310c4fa2e1e0e895ce1a1eb0f43278fdb528131a3e32bfffe0c6de9006418f5309cba773ca38b6ad8507cc59445ccc0257506ebc16a4c01d4cd97e03fcf7a2049fea0db28447858f73b8e9fe98b391b136c9dc510288630a1f0af93b26a8891b857bfe4b818af99a1e011e6dbaa53982d29cf74ae7dffef45545279f19931708ed3eede5e82280eab908e8eb80abff3f1f023ab66869297b40da8496861dc455ac3abe1efa8a6f9e2c4eda48025d43a486a3f26f269743eaa30d6f0e1f48db6287751358a41f5b07aee0f098862e3493731fe2697acce734f004907c6f11eef189424fee52cd30ad708707eaf2e441f52bcf3d0c5440c1742458653c0c8a27b5ade784d9e09c8b47f1671901a29360e7e5e94946b9c75752a1a8d599d2a3e14ac81b84d42115cd688c8383a64fc6e7e1dc5568bb4837358ebe63207a4067af66b2027ad2ce8fb7ae3a452d40723a51fdf9f9c9913e8029a222cf81d12ad41e58860d75deb6de30ad", + }, ]; let failure_data = >::from_hex(FAILURE_DATA).unwrap(); @@ -3621,7 +3596,13 @@ mod tests { hops: vec![ // Bob RouteHop { - pubkey: PublicKey::from_slice(&>::from_hex("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()).unwrap(), + pubkey: PublicKey::from_slice( + &>::from_hex( + "0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c", + ) + .unwrap(), + ) + .unwrap(), node_features: NodeFeatures::empty(), short_channel_id: 0, channel_features: ChannelFeatures::empty(), @@ -3629,10 +3610,15 @@ mod tests { cltv_expiry_delta: 24, maybe_announced_channel: false, }, - // Carol RouteHop { - pubkey: PublicKey::from_slice(&>::from_hex("027f31ebc5462c1fdce1b737ecff52d37d75dea43ce11c74d25aa297165faa2007").unwrap()).unwrap(), + pubkey: PublicKey::from_slice( + &>::from_hex( + "027f31ebc5462c1fdce1b737ecff52d37d75dea43ce11c74d25aa297165faa2007", + ) + .unwrap(), + ) + .unwrap(), node_features: NodeFeatures::empty(), short_channel_id: (572330 << 40) + (42 << 16) + 2821, channel_features: ChannelFeatures::empty(), @@ -3645,23 +3631,39 @@ mod tests { trampoline_hops: vec![ // Carol's pubkey TrampolineHop { - pubkey: PublicKey::from_slice(&>::from_hex("027f31ebc5462c1fdce1b737ecff52d37d75dea43ce11c74d25aa297165faa2007").unwrap()).unwrap(), + pubkey: PublicKey::from_slice( + &>::from_hex( + "027f31ebc5462c1fdce1b737ecff52d37d75dea43ce11c74d25aa297165faa2007", + ) + .unwrap(), + ) + .unwrap(), node_features: Features::empty(), fee_msat: 2_500, cltv_expiry_delta: 24, }, - // Dave's pubkey TrampolineHop { - pubkey: PublicKey::from_slice(&>::from_hex("02edabbd16b41c8371b92ef2f04c1185b4f03b6dcd52ba9b78d9d7c89c8f221145").unwrap()).unwrap(), + pubkey: PublicKey::from_slice( + &>::from_hex( + "02edabbd16b41c8371b92ef2f04c1185b4f03b6dcd52ba9b78d9d7c89c8f221145", + ) + .unwrap(), + ) + .unwrap(), node_features: Features::empty(), fee_msat: 2_500, cltv_expiry_delta: 24, }, - // Emily's pubkey TrampolineHop { - pubkey: PublicKey::from_slice(&>::from_hex("032c0b7cf95324a07d05398b240174dc0c2be444d96b159aa6c7f7b1e668680991").unwrap()).unwrap(), + pubkey: PublicKey::from_slice( + &>::from_hex( + "032c0b7cf95324a07d05398b240174dc0c2be444d96b159aa6c7f7b1e668680991", + ) + .unwrap(), + ) + .unwrap(), node_features: Features::empty(), fee_msat: 150_500, cltv_expiry_delta: 36, @@ -3672,11 +3674,23 @@ mod tests { hops: vec![ // Emily's dummy blinded node id BlindedHop { - blinded_node_id: PublicKey::from_slice(&>::from_hex("0295d40514096a8be54859e7dfe947b376eaafea8afe5cb4eb2c13ff857ed0b4be").unwrap()).unwrap(), + blinded_node_id: PublicKey::from_slice( + &>::from_hex( + "0295d40514096a8be54859e7dfe947b376eaafea8afe5cb4eb2c13ff857ed0b4be", + ) + .unwrap(), + ) + .unwrap(), encrypted_payload: vec![], - } + }, ], - blinding_point: PublicKey::from_slice(&>::from_hex("02988face71e92c345a068f740191fd8e53be14f0bb957ef730d3c5f76087b960e").unwrap()).unwrap(), + blinding_point: PublicKey::from_slice( + &>::from_hex( + "02988face71e92c345a068f740191fd8e53be14f0bb957ef730d3c5f76087b960e", + ) + .unwrap(), + ) + .unwrap(), excess_final_cltv_expiry_delta: 0, final_value_msat: 150_000_000, }), diff --git a/lightning/src/ln/our_peer_storage.rs b/lightning/src/ln/our_peer_storage.rs index 937e446bcff..7e74cc65317 100644 --- a/lightning/src/ln/our_peer_storage.rs +++ b/lightning/src/ln/our_peer_storage.rs @@ -179,7 +179,7 @@ impl_writeable_tlv_based!(PeerStorageMonitorHolder, { #[cfg(test)] mod tests { - use crate::ln::our_peer_storage::{derive_nonce, DecryptedOurPeerStorage}; + use crate::ln::our_peer_storage::{DecryptedOurPeerStorage, derive_nonce}; use crate::sign::PeerStorageKey; #[test] diff --git a/lightning/src/ln/outbound_payment.rs b/lightning/src/ln/outbound_payment.rs index 7259f60796f..82b0f046b18 100644 --- a/lightning/src/ln/outbound_payment.rs +++ b/lightning/src/ln/outbound_payment.rs @@ -9,8 +9,8 @@ //! This module contains various types which are used to configure or process outbound payments. -use bitcoin::hashes::sha256::Hash as Sha256; use bitcoin::hashes::Hash; +use bitcoin::hashes::sha256::Hash as Sha256; use bitcoin::secp256k1::{self, Secp256k1, SecretKey}; use lightning_invoice::Bolt11Invoice; @@ -341,8 +341,8 @@ impl PendingOutboundPayment { }; if remove_res { if let PendingOutboundPayment::Retryable { - ref mut pending_amt_msat, ref mut pending_fee_msat, - ref mut remaining_max_total_routing_fee_msat, .. + pending_amt_msat, pending_fee_msat, + remaining_max_total_routing_fee_msat, .. } = self { let path = path.expect("Removing a failed payment should always come with a path"); *pending_amt_msat -= path.final_value_msat(); @@ -375,8 +375,8 @@ impl PendingOutboundPayment { }; if insert_res { if let PendingOutboundPayment::Retryable { - ref mut pending_amt_msat, ref mut pending_fee_msat, - ref mut remaining_max_total_routing_fee_msat, .. + pending_amt_msat, pending_fee_msat, + remaining_max_total_routing_fee_msat, .. } = self { *pending_amt_msat += path.final_value_msat(); let path_fee_msat = path.fee_msat(); @@ -1285,18 +1285,20 @@ impl OutboundPayments { )); } - let amount_msat = match InvoiceBuilder::::amount_msats( - invreq, - ) { - Ok(amt) => amt, - Err(_) => { - // We check this during invoice request parsing, when constructing the invreq's - // contents from its TLV stream. - debug_assert!(false, "LDK requires an msat amount in either the invreq or the invreq's underlying offer"); - abandon_with_entry!(entry, PaymentFailureReason::UnexpectedError); - return Err(Bolt12PaymentError::UnknownRequiredFeatures); - }, - }; + let amount_msat = + match InvoiceBuilder::::amount_msats(invreq) { + Ok(amt) => amt, + Err(_) => { + // We check this during invoice request parsing, when constructing the invreq's + // contents from its TLV stream. + debug_assert!( + false, + "LDK requires an msat amount in either the invreq or the invreq's underlying offer" + ); + abandon_with_entry!(entry, PaymentFailureReason::UnexpectedError); + return Err(Bolt12PaymentError::UnknownRequiredFeatures); + }, + }; let keysend_preimage = PaymentPreimage(entropy_source.get_secure_random_bytes()); let payment_hash = @@ -2699,13 +2701,24 @@ impl OutboundPayments { entry.get_mut().insert(session_priv_bytes, &path) }, }; - log_info!(logger, "{} a pending payment path for {} msat for session priv {} on an existing pending payment with payment hash {}", - if newly_added { "Added" } else { "Had" }, path_amt, log_bytes!(session_priv_bytes), payment_hash); + log_info!( + logger, + "{} a pending payment path for {} msat for session priv {} on an existing pending payment with payment hash {}", + if newly_added { "Added" } else { "Had" }, + path_amt, + log_bytes!(session_priv_bytes), + payment_hash + ); }, hash_map::Entry::Vacant(entry) => { entry.insert(new_retryable!()); - log_info!(logger, "Added a pending payment for {} msat with payment hash {} for path with session priv {}", - path_amt, payment_hash, log_bytes!(session_priv_bytes)); + log_info!( + logger, + "Added a pending payment for {} msat with payment hash {} for path with session priv {}", + path_amt, + payment_hash, + log_bytes!(session_priv_bytes) + ); }, } } diff --git a/lightning/src/ln/payment_tests.rs b/lightning/src/ln/payment_tests.rs index 5b4f5f93d71..195a053b6bf 100644 --- a/lightning/src/ln/payment_tests.rs +++ b/lightning/src/ln/payment_tests.rs @@ -21,19 +21,19 @@ use crate::events::{ }; use crate::ln::chan_utils; use crate::ln::channel::{ - get_holder_selected_channel_reserve_satoshis, ANCHOR_OUTPUT_VALUE_SATOSHI, - EXPIRE_PREV_CONFIG_TICKS, + ANCHOR_OUTPUT_VALUE_SATOSHI, EXPIRE_PREV_CONFIG_TICKS, + get_holder_selected_channel_reserve_satoshis, }; use crate::ln::channelmanager::{ - HTLCForwardInfo, PaymentId, PendingAddHTLCInfo, PendingHTLCRouting, RecentPaymentDetails, - BREAKDOWN_TIMEOUT, MIN_CLTV_EXPIRY_DELTA, MPP_TIMEOUT_TICKS, + BREAKDOWN_TIMEOUT, HTLCForwardInfo, MIN_CLTV_EXPIRY_DELTA, MPP_TIMEOUT_TICKS, PaymentId, + PendingAddHTLCInfo, PendingHTLCRouting, RecentPaymentDetails, }; use crate::ln::msgs; use crate::ln::msgs::{BaseMessageHandler, ChannelMessageHandler, MessageSendEvent}; use crate::ln::onion_utils::{self, LocalHTLCFailureReason}; use crate::ln::outbound_payment::{ - ProbeSendFailure, RecipientCustomTlvs, RecipientOnionFields, Retry, RetryableSendFailure, - IDEMPOTENCY_TIMEOUT_TICKS, + IDEMPOTENCY_TIMEOUT_TICKS, ProbeSendFailure, RecipientCustomTlvs, RecipientOnionFields, Retry, + RetryableSendFailure, }; use crate::ln::types::ChannelId; use crate::routing::gossip::{EffectiveCapacity, RoutingFees}; @@ -48,8 +48,8 @@ use crate::types::string::UntrustedString; use crate::util::config::{HTLCInterceptionFlags, UserConfig}; use crate::util::errors::APIError; use crate::util::ser::Writeable; -use bitcoin::hashes::sha256::Hash as Sha256; use bitcoin::hashes::Hash; +use bitcoin::hashes::sha256::Hash as Sha256; use bitcoin::secp256k1::{Secp256k1, SecretKey}; use crate::prelude::*; @@ -173,7 +173,7 @@ fn mpp_retry() { check_added_monitors(&nodes[2], 1); nodes[0].node.handle_update_fail_htlc(node_c_id, &htlc_updates.update_fail_htlcs[0]); do_commitment_signed_dance(&nodes[0], &nodes[2], &htlc_updates.commitment_signed, false, false); - let mut events = nodes[0].node.get_and_clear_pending_events(); + let events = nodes[0].node.get_and_clear_pending_events(); let conditions = PaymentFailedConditions::new().mpp_parts_remain(); expect_payment_failed_conditions_event(events, hash, false, conditions); @@ -294,7 +294,7 @@ fn mpp_retry_overpay() { check_added_monitors(&nodes[2], 1); nodes[0].node.handle_update_fail_htlc(node_c_id, &htlc_updates.update_fail_htlcs[0]); do_commitment_signed_dance(&nodes[0], &nodes[2], &htlc_updates.commitment_signed, false, false); - let mut events = nodes[0].node.get_and_clear_pending_events(); + let events = nodes[0].node.get_and_clear_pending_events(); let fail_conditions = PaymentFailedConditions::new().mpp_parts_remain(); expect_payment_failed_conditions_event(events, hash, false, fail_conditions); @@ -424,7 +424,7 @@ fn do_mpp_receive_timeout(send_partial_mpp: bool, keysend: bool) { let commitment = &htlc_fail_updates.commitment_signed; do_commitment_signed_dance(&nodes[0], &nodes[1], commitment, false, false); - let mut conditions = PaymentFailedConditions::new() + let conditions = PaymentFailedConditions::new() .mpp_parts_remain() .expected_htlc_error_data(LocalHTLCFailureReason::MPPTimeout, &[][..]); expect_payment_failed_conditions(&nodes[0], hash, false, conditions); @@ -786,7 +786,7 @@ fn no_pending_leak_on_initial_send_failure() { let chanmon_cfgs = create_chanmon_cfgs(2); let node_cfgs = create_node_cfgs(2, &chanmon_cfgs); let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]); - let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs); + let nodes = create_network(2, &node_cfgs, &node_chanmgrs); let node_a_id = nodes[0].node.get_our_node_id(); let node_b_id = nodes[1].node.get_our_node_id(); @@ -802,8 +802,13 @@ fn no_pending_leak_on_initial_send_failure() { let onion = RecipientOnionFields::secret_only(payment_secret, 100_000); let payment_id = PaymentId(payment_hash.0); let res = nodes[0].node.send_payment_with_route(route, payment_hash, onion, payment_id); - unwrap_send_err!(nodes[0], res, true, APIError::ChannelUnavailable { ref err }, - assert_eq!(err, "Peer for first hop currently disconnected")); + unwrap_send_err!( + nodes[0], + res, + true, + APIError::ChannelUnavailable { err }, + assert_eq!(err, "Peer for first hop currently disconnected") + ); assert!(!nodes[0].node.has_pending_payments()); } @@ -1022,7 +1027,7 @@ fn do_retry_with_no_persist(confirm_before_reload: bool) { { let per_peer_state = nodes[1].node.per_peer_state.read().unwrap(); let mut peer_state = per_peer_state.get(&node_c_id).unwrap().lock().unwrap(); - let mut channel = peer_state.channel_by_id.get_mut(&chan_id_2).unwrap(); + let channel = peer_state.channel_by_id.get_mut(&chan_id_2).unwrap(); let mut new_config = channel.context().config(); new_config.forwarding_fee_base_msat += 100_000; channel.context_mut().update_config(&new_config); @@ -1071,7 +1076,7 @@ fn do_test_completed_payment_not_retryable_on_reload(use_dust: bool) { let chanmon_cfgs = create_chanmon_cfgs(3); let node_cfgs = create_node_cfgs(3, &chanmon_cfgs); - let mut legacy_cfg = test_legacy_channel_config(); + let legacy_cfg = test_legacy_channel_config(); let persist_1; let chain_monitor_1; @@ -1539,7 +1544,7 @@ fn get_ldk_payment_preimage() { let chanmon_cfgs = create_chanmon_cfgs(2); let node_cfgs = create_node_cfgs(2, &chanmon_cfgs); let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]); - let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs); + let nodes = create_network(2, &node_cfgs, &node_chanmgrs); let node_b_id = nodes[1].node.get_our_node_id(); @@ -2072,7 +2077,7 @@ fn test_trivial_inflight_htlc_tracking() { let (_, payment_hash, _, payment_id) = send_payment(&nodes[0], &[&nodes[1], &nodes[2]], 500000); let inflight_htlcs = node_chanmgrs[0].compute_inflight_htlcs(); { - let mut per_peer_lock; + let per_peer_lock; let mut peer_state_lock; let channel_1 = get_channel_ref!(&nodes[0], nodes[1], per_peer_lock, peer_state_lock, chan_1_id); @@ -2085,7 +2090,7 @@ fn test_trivial_inflight_htlc_tracking() { assert_eq!(chan_1_used_liquidity, None); } { - let mut per_peer_lock; + let per_peer_lock; let mut peer_state_lock; let channel_2 = get_channel_ref!(&nodes[1], nodes[2], per_peer_lock, peer_state_lock, chan_2_id); @@ -2113,7 +2118,7 @@ fn test_trivial_inflight_htlc_tracking() { route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 500000); let inflight_htlcs = node_chanmgrs[0].compute_inflight_htlcs(); { - let mut per_peer_lock; + let per_peer_lock; let mut peer_state_lock; let channel_1 = get_channel_ref!(&nodes[0], nodes[1], per_peer_lock, peer_state_lock, chan_1_id); @@ -2127,7 +2132,7 @@ fn test_trivial_inflight_htlc_tracking() { assert_eq!(chan_1_used_liquidity, Some(501000)); } { - let mut per_peer_lock; + let per_peer_lock; let mut peer_state_lock; let channel_2 = get_channel_ref!(&nodes[1], nodes[2], per_peer_lock, peer_state_lock, chan_2_id); @@ -2155,7 +2160,7 @@ fn test_trivial_inflight_htlc_tracking() { let inflight_htlcs = node_chanmgrs[0].compute_inflight_htlcs(); { - let mut per_peer_lock; + let per_peer_lock; let mut peer_state_lock; let channel_1 = get_channel_ref!(&nodes[0], nodes[1], per_peer_lock, peer_state_lock, chan_1_id); @@ -2168,7 +2173,7 @@ fn test_trivial_inflight_htlc_tracking() { assert_eq!(chan_1_used_liquidity, None); } { - let mut per_peer_lock; + let per_peer_lock; let mut peer_state_lock; let channel_2 = get_channel_ref!(&nodes[1], nodes[2], per_peer_lock, peer_state_lock, chan_2_id); @@ -2190,7 +2195,7 @@ fn test_holding_cell_inflight_htlcs() { let chanmon_cfgs = create_chanmon_cfgs(2); let node_cfgs = create_node_cfgs(2, &chanmon_cfgs); let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]); - let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs); + let nodes = create_network(2, &node_cfgs, &node_chanmgrs); let node_a_id = nodes[0].node.get_our_node_id(); let node_b_id = nodes[1].node.get_our_node_id(); @@ -2218,7 +2223,7 @@ fn test_holding_cell_inflight_htlcs() { let inflight_htlcs = node_chanmgrs[0].compute_inflight_htlcs(); { - let mut per_peer_lock; + let per_peer_lock; let mut peer_state_lock; let channel = get_channel_ref!(&nodes[0], nodes[1], per_peer_lock, peer_state_lock, channel_id); @@ -2251,7 +2256,7 @@ fn do_test_intercepted_payment(test: InterceptTest) { let chanmon_cfgs = create_chanmon_cfgs(3); let node_cfgs = create_node_cfgs(3, &chanmon_cfgs); - let mut zero_conf_chan_config = test_default_channel_config(); + let zero_conf_chan_config = test_default_channel_config(); let mut intercept_forwards_config = test_default_channel_config(); intercept_forwards_config.htlc_interception_flags = HTLCInterceptionFlags::ToInterceptSCIDs as u8; @@ -2686,7 +2691,7 @@ fn do_automatic_retries(test: AutoRetry) { // Send a payment attempt that fails due to lack of liquidity on the second hop check_added_monitors(&nodes[0], 1); let update_0 = get_htlc_update_msgs(&nodes[0], &node_b_id); - let mut update_add = update_0.update_add_htlcs[0].clone(); + let update_add = update_0.update_add_htlcs[0].clone(); nodes[1].node.handle_update_add_htlc(node_a_id, &update_add); let commitment = &update_0.commitment_signed; do_commitment_signed_dance(&nodes[1], &nodes[0], commitment, false, true); @@ -2709,7 +2714,7 @@ fn do_automatic_retries(test: AutoRetry) { do_commitment_signed_dance(&nodes[0], &nodes[1], commitment, false, false); // Ensure the attempt fails - let mut events = nodes[0].node.get_and_clear_pending_events(); + let events = nodes[0].node.get_and_clear_pending_events(); if $expect_pending_htlcs_forwardable { assert_eq!(events.len(), 1); } else { @@ -2801,7 +2806,7 @@ fn do_automatic_retries(test: AutoRetry) { // Ensure we won't retry a second time. nodes[0].node.process_pending_htlc_forwards(); - let mut msg_events = nodes[0].node.get_and_clear_pending_msg_events(); + let msg_events = nodes[0].node.get_and_clear_pending_msg_events(); assert_eq!(msg_events.len(), 0); } else if test == AutoRetry::FailTimeout { #[cfg(feature = "std")] @@ -2818,10 +2823,10 @@ fn do_automatic_retries(test: AutoRetry) { // Make sure we don't retry again. nodes[0].node.process_pending_htlc_forwards(); - let mut msg_events = nodes[0].node.get_and_clear_pending_msg_events(); + let msg_events = nodes[0].node.get_and_clear_pending_msg_events(); assert_eq!(msg_events.len(), 0); - let mut events = nodes[0].node.get_and_clear_pending_events(); + let events = nodes[0].node.get_and_clear_pending_events(); assert_eq!(events.len(), 1); match events[0] { Event::PaymentFailed { payment_hash, payment_id, reason } => { @@ -2855,10 +2860,10 @@ fn do_automatic_retries(test: AutoRetry) { nodes[0].node.process_pending_htlc_forwards(); // Make sure we don't retry again. - let mut msg_events = nodes[0].node.get_and_clear_pending_msg_events(); + let msg_events = nodes[0].node.get_and_clear_pending_msg_events(); assert_eq!(msg_events.len(), 0); - let mut events = nodes[0].node.get_and_clear_pending_events(); + let events = nodes[0].node.get_and_clear_pending_events(); assert_eq!(events.len(), 1); match events[0] { Event::PaymentFailed { payment_hash, payment_id, reason } => { @@ -2877,10 +2882,10 @@ fn do_automatic_retries(test: AutoRetry) { // We retry payments in `process_pending_htlc_forwards`. Since our channel closed, we should // fail to find a route. nodes[0].node.process_pending_htlc_forwards(); - let mut msg_events = nodes[0].node.get_and_clear_pending_msg_events(); + let msg_events = nodes[0].node.get_and_clear_pending_msg_events(); assert_eq!(msg_events.len(), 0); - let mut events = nodes[0].node.get_and_clear_pending_events(); + let events = nodes[0].node.get_and_clear_pending_events(); assert_eq!(events.len(), 1); match events[0] { Event::PaymentFailed { payment_hash, payment_id, reason } => { @@ -2901,7 +2906,7 @@ fn auto_retry_partial_failure() { let legacy_cfg = test_legacy_channel_config(); let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(legacy_cfg.clone()), Some(legacy_cfg)]); - let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs); + let nodes = create_network(2, &node_cfgs, &node_chanmgrs); let node_a_id = nodes[0].node.get_our_node_id(); let node_b_id = nodes[1].node.get_our_node_id(); @@ -3052,7 +3057,7 @@ fn auto_retry_partial_failure() { // Only one HTLC/channel update actually made it out assert_eq!(msg_events.len(), 1); - let mut payment_event = SendEvent::from_event(msg_events.remove(0)); + let payment_event = SendEvent::from_event(msg_events.remove(0)); nodes[1].node.handle_update_add_htlc(node_a_id, &payment_event.msgs[0]); nodes[1].node.handle_commitment_signed_batch_test(node_a_id, &payment_event.commitment_msg); @@ -3148,7 +3153,7 @@ fn auto_retry_zero_attempts_send_error() { let legacy_cfg = test_legacy_channel_config(); let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(legacy_cfg.clone()), Some(legacy_cfg)]); - let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs); + let nodes = create_network(2, &node_cfgs, &node_chanmgrs); let node_b_id = nodes[1].node.get_our_node_id(); @@ -3216,7 +3221,7 @@ fn fails_paying_after_rejected_by_payee() { let chanmon_cfgs = create_chanmon_cfgs(2); let node_cfgs = create_node_cfgs(2, &chanmon_cfgs); let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]); - let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs); + let nodes = create_network(2, &node_cfgs, &node_chanmgrs); let node_a_id = nodes[0].node.get_our_node_id(); let node_b_id = nodes[1].node.get_our_node_id(); @@ -3247,7 +3252,7 @@ fn fails_paying_after_rejected_by_payee() { check_added_monitors(&nodes[0], 1); let mut events = nodes[0].node.get_and_clear_pending_msg_events(); assert_eq!(events.len(), 1); - let mut payment_event = SendEvent::from_event(events.pop().unwrap()); + let payment_event = SendEvent::from_event(events.pop().unwrap()); nodes[1].node.handle_update_add_htlc(node_a_id, &payment_event.msgs[0]); check_added_monitors(&nodes[1], 0); do_commitment_signed_dance(&nodes[1], &nodes[0], &payment_event.commitment_msg, false, false); @@ -3655,7 +3660,7 @@ fn no_extra_retries_on_back_to_back_fail() { // // Because we now retry payments as a batch, we simply return a single-path route in the // second, batched, request, have that fail, ensure the payment was abandoned. - let mut events = nodes[0].node.get_and_clear_pending_events(); + let events = nodes[0].node.get_and_clear_pending_events(); assert_eq!(events.len(), 2); match events[0] { Event::PaymentPathFailed { @@ -3699,7 +3704,7 @@ fn no_extra_retries_on_back_to_back_fail() { let commitment = &bs_fail_update.commitment_signed; do_commitment_signed_dance(&nodes[0], &nodes[1], commitment, false, true); - let mut events = nodes[0].node.get_and_clear_pending_events(); + let events = nodes[0].node.get_and_clear_pending_events(); assert_eq!(events.len(), 2); match events[0] { Event::PaymentPathFailed { @@ -3873,7 +3878,7 @@ fn test_simple_partial_retry() { { let mut msg_events = nodes[1].node.get_and_clear_pending_msg_events(); assert_eq!(msg_events.len(), 2); - let mut handle_update_htlcs = |event: MessageSendEvent| { + let handle_update_htlcs = |event: MessageSendEvent| { if let MessageSendEvent::UpdateHTLCs { node_id, channel_id: _, updates } = event { let commitment = &updates.commitment_signed; if node_id == node_a_id { @@ -3895,7 +3900,7 @@ fn test_simple_partial_retry() { handle_update_htlcs(msg_events.remove(0)); } - let mut events = nodes[0].node.get_and_clear_pending_events(); + let events = nodes[0].node.get_and_clear_pending_events(); assert_eq!(events.len(), 1); match events[0] { Event::PaymentPathFailed { @@ -4303,7 +4308,7 @@ fn do_claim_from_closed_chan(fail_payment: bool) { .announced_channel_max_inbound_htlc_value_in_flight_percentage = 10; let configs: [Option; 4] = core::array::from_fn(|_| Some(legacy_cfg.clone())); let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &configs); - let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs); + let nodes = create_network(4, &node_cfgs, &node_chanmgrs); let node_a_id = nodes[0].node.get_our_node_id(); let node_b_id = nodes[1].node.get_our_node_id(); @@ -4321,17 +4326,13 @@ fn do_claim_from_closed_chan(fail_payment: bool) { .unwrap(); let amt_msat = 10_000_000; - let mut route_params = RouteParameters::from_payment_params_and_value(payment_params, amt_msat); + let route_params = RouteParameters::from_payment_params_and_value(payment_params, amt_msat); let inflight = nodes[0].node.compute_inflight_htlcs(); let mut route = nodes[0].router.find_route(&node_a_id, &route_params, None, inflight).unwrap(); // Make sure the route is ordered as the B->D path before C->D route.paths.sort_by(|a, _| { - if a.hops[0].pubkey == node_b_id { - Ordering::Less - } else { - Ordering::Greater - } + if a.hops[0].pubkey == node_b_id { Ordering::Less } else { Ordering::Greater } }); // Note that we add an extra 1 in the send pipeline to compensate for any blocks found while @@ -4350,11 +4351,7 @@ fn do_claim_from_closed_chan(fail_payment: bool) { send_msgs.sort_by(|a, _| { let a_node_id = if let MessageSendEvent::UpdateHTLCs { node_id, .. } = a { node_id } else { panic!() }; - if *a_node_id == node_b_id { - Ordering::Less - } else { - Ordering::Greater - } + if *a_node_id == node_b_id { Ordering::Less } else { Ordering::Greater } }); assert_eq!(send_msgs.len(), 2); @@ -4491,7 +4488,7 @@ fn do_test_custom_tlvs(spontaneous: bool, even_tlvs: bool, known_tlvs: bool) { let chanmon_cfgs = create_chanmon_cfgs(2); let node_cfgs = create_node_cfgs(2, &chanmon_cfgs); let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]); - let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs); + let nodes = create_network(2, &node_cfgs, &node_chanmgrs); let node_a_id = nodes[0].node.get_our_node_id(); let node_b_id = nodes[1].node.get_our_node_id(); @@ -4499,7 +4496,7 @@ fn do_test_custom_tlvs(spontaneous: bool, even_tlvs: bool, known_tlvs: bool) { create_announced_chan_between_nodes(&nodes, 0, 1); let amt_msat = 100_000; - let (mut route, hash, preimage, payment_secret) = + let (route, hash, preimage, payment_secret) = get_route_and_payment_hash!(&nodes[0], &nodes[1], amt_msat); let id = PaymentId(hash.0); let custom_tlvs = vec![ @@ -4523,7 +4520,7 @@ fn do_test_custom_tlvs(spontaneous: bool, even_tlvs: bool, known_tlvs: bool) { let mut events = nodes[0].node.get_and_clear_pending_msg_events(); let ev = remove_first_msg_event_to_node(&node_b_id, &mut events); - let mut payment_event = SendEvent::from_event(ev); + let payment_event = SendEvent::from_event(ev); nodes[1].node.handle_update_add_htlc(node_a_id, &payment_event.msgs[0]); check_added_monitors(&nodes[1], 0); @@ -4618,7 +4615,7 @@ fn test_retry_custom_tlvs() { nodes[0].node.handle_update_fail_htlc(node_b_id, &update_fail_htlcs[0]); do_commitment_signed_dance(&nodes[0], &nodes[1], &commitment_signed, false, false); - let mut events = nodes[0].node.get_and_clear_pending_events(); + let events = nodes[0].node.get_and_clear_pending_events(); let conditions = PaymentFailedConditions::new().mpp_parts_remain(); expect_payment_failed_conditions_event(events, hash, false, conditions); @@ -4712,11 +4709,7 @@ fn do_test_custom_tlvs_consistency( assert_eq!(route.paths.len(), 2); route.paths.sort_by(|path_a, _| { // Sort the path so that the path through nodes[1] comes first - if path_a.hops[0].pubkey == node_b_id { - Ordering::Less - } else { - Ordering::Greater - } + if path_a.hops[0].pubkey == node_b_id { Ordering::Less } else { Ordering::Greater } }); let (preimage, hash, payment_secret) = get_payment_preimage_hash(&nodes[3], None, None); @@ -4873,7 +4866,7 @@ fn do_test_payment_metadata_consistency(do_reload: bool, do_modify: bool) { let payment_params = PaymentParameters::from_node_id(node_d_id, TEST_FINAL_CLTV) .with_bolt11_features(nodes[1].node.bolt11_invoice_features()) .unwrap(); - let mut route_params = RouteParameters::from_payment_params_and_value(payment_params, amt_msat); + let route_params = RouteParameters::from_payment_params_and_value(payment_params, amt_msat); // Send the MPP payment, delivering the updated commitment state to nodes[1]. let onion = RecipientOnionFields { @@ -5142,7 +5135,7 @@ fn peel_payment_onion_custom_tlvs() { let payment_params = PaymentParameters::for_keysend(node_b_id, TEST_FINAL_CLTV, false); let route_params = RouteParameters::from_payment_params_and_value(payment_params, amt_msat); let route = functional_test_utils::get_route(&nodes[0], &route_params).unwrap(); - let mut recipient_onion = RecipientOnionFields::spontaneous_empty(amt_msat) + let recipient_onion = RecipientOnionFields::spontaneous_empty(amt_msat) .with_custom_tlvs(RecipientCustomTlvs::new(vec![(414141, vec![42; 1200])]).unwrap()); let prng_seed = chanmon_cfgs[0].keys_manager.get_secure_random_bytes(); let session_priv = SecretKey::from_slice(&prng_seed[..]).expect("RNG is busted"); @@ -5283,7 +5276,7 @@ fn test_non_strict_forwarding() { check_added_monitors(&nodes[0], 1); let mut msg_events = nodes[0].node.get_and_clear_pending_msg_events(); assert_eq!(msg_events.len(), 1); - let mut send_event = SendEvent::from_event(msg_events.remove(0)); + let send_event = SendEvent::from_event(msg_events.remove(0)); nodes[1].node.handle_update_add_htlc(node_a_id, &send_event.msgs[0]); do_commitment_signed_dance(&nodes[1], &nodes[0], &send_event.commitment_msg, false, false); @@ -5575,7 +5568,7 @@ fn do_bolt11_multi_node_mpp(use_bolt11_pay: bool) { check_added_monitors(&nodes[2], 2); // Get the fulfill messages from C to both A and B - let mut events_c = nodes[2].node.get_and_clear_pending_msg_events(); + let events_c = nodes[2].node.get_and_clear_pending_msg_events(); assert_eq!(events_c.len(), 2); // Handle fulfill message from C to A @@ -5840,7 +5833,7 @@ fn bolt11_multi_node_mpp_with_retry() { check_added_monitors(&nodes[3], 2); // Get the fulfill messages from D to both C (for A) and B - let mut events_d = nodes[3].node.get_and_clear_pending_msg_events(); + let events_d = nodes[3].node.get_and_clear_pending_msg_events(); assert_eq!(events_d.len(), 2); // Find which event goes to C and which to B diff --git a/lightning/src/ln/peer_channel_encryptor.rs b/lightning/src/ln/peer_channel_encryptor.rs index d9fc6dd2c6a..b9eccacb68e 100644 --- a/lightning/src/ln/peer_channel_encryptor.rs +++ b/lightning/src/ln/peer_channel_encryptor.rs @@ -22,8 +22,8 @@ use bitcoin::hashes::{Hash, HashEngine}; use bitcoin::hex::DisplayHex; use bitcoin::secp256k1; -use bitcoin::secp256k1::ecdh::SharedSecret; use bitcoin::secp256k1::Secp256k1; +use bitcoin::secp256k1::ecdh::SharedSecret; use bitcoin::secp256k1::{PublicKey, SecretKey}; use chacha20_poly1305::{ChaCha20Poly1305, Key, Nonce}; @@ -263,7 +263,7 @@ impl PeerChannelEncryptor { return Err(LightningError { err: format!("Invalid public key {}", &act[1..34].as_hex()), action: msgs::ErrorAction::DisconnectPeer { msg: None }, - }) + }); }, Ok(key) => key, }; @@ -474,7 +474,7 @@ impl PeerChannelEncryptor { return Err(LightningError { err: format!("Bad node_id from peer, {}", &their_node_id.as_hex()), action: msgs::ErrorAction::DisconnectPeer { msg: None }, - }) + }); }, }); @@ -663,7 +663,7 @@ impl MessageBuf { #[cfg(test)] mod tests { - use super::{MessageBuf, LN_MAX_MSG_LEN}; + use super::{LN_MAX_MSG_LEN, MessageBuf}; use bitcoin::hex::FromHex; use bitcoin::secp256k1::Secp256k1; @@ -830,14 +830,16 @@ mod tests { let hex = "01036360e856310ce5d294e8be33fc807077dc56ac80d95d9cd4ddbd21325eff73f70df6086551151f58b8afe6c195782c6a"; let act_one = >::from_hex(hex).unwrap().to_vec(); - assert!(inbound_peer - .process_act_one_with_keys( - &act_one[..], - &&node_signer, - our_ephemeral.clone(), - &secp_ctx - ) - .is_err()); + assert!( + inbound_peer + .process_act_one_with_keys( + &act_one[..], + &&node_signer, + our_ephemeral.clone(), + &secp_ctx + ) + .is_err() + ); } { // transport-responder act1 bad key serialization test @@ -845,14 +847,16 @@ mod tests { let hex = "00046360e856310ce5d294e8be33fc807077dc56ac80d95d9cd4ddbd21325eff73f70df6086551151f58b8afe6c195782c6a"; let act_one = >::from_hex(hex).unwrap().to_vec(); - assert!(inbound_peer - .process_act_one_with_keys( - &act_one[..], - &&node_signer, - our_ephemeral.clone(), - &secp_ctx - ) - .is_err()); + assert!( + inbound_peer + .process_act_one_with_keys( + &act_one[..], + &&node_signer, + our_ephemeral.clone(), + &secp_ctx + ) + .is_err() + ); } { // transport-responder act1 bad MAC test @@ -860,14 +864,16 @@ mod tests { let hex = "00036360e856310ce5d294e8be33fc807077dc56ac80d95d9cd4ddbd21325eff73f70df6086551151f58b8afe6c195782c6b"; let act_one = >::from_hex(hex).unwrap().to_vec(); - assert!(inbound_peer - .process_act_one_with_keys( - &act_one[..], - &&node_signer, - our_ephemeral.clone(), - &secp_ctx - ) - .is_err()); + assert!( + inbound_peer + .process_act_one_with_keys( + &act_one[..], + &&node_signer, + our_ephemeral.clone(), + &secp_ctx + ) + .is_err() + ); } { // transport-responder act3 bad version test diff --git a/lightning/src/ln/peer_handler.rs b/lightning/src/ln/peer_handler.rs index 69d0815e8f0..ab3227e1d78 100644 --- a/lightning/src/ln/peer_handler.rs +++ b/lightning/src/ln/peer_handler.rs @@ -25,7 +25,7 @@ use crate::ln::msgs::{ OnionMessageHandler, RoutingMessageHandler, SendOnlyMessageHandler, SocketAddress, }; use crate::ln::peer_channel_encryptor::{ - MessageBuf, NextNoiseStep, PeerChannelEncryptor, MSG_BUF_ALLOC_SIZE, + MSG_BUF_ALLOC_SIZE, MessageBuf, NextNoiseStep, PeerChannelEncryptor, }; use crate::ln::types::ChannelId; use crate::ln::wire; @@ -108,7 +108,7 @@ pub trait CustomMessageHandler: wire::CustomMessageReader { /// /// [`Self::peer_disconnected`] will not be called if `Err(())` is returned. fn peer_connected(&self, their_node_id: PublicKey, msg: &Init, inbound: bool) - -> Result<(), ()>; + -> Result<(), ()>; /// Gets the node feature flags which this handler itself supports. All available handlers are /// queried similarly and their feature flags are OR'd together to form the [`NodeFeatures`] @@ -1003,15 +1003,15 @@ pub trait APeerManager { } impl< - Descriptor: SocketDescriptor, - CM: ChannelMessageHandler, - RM: RoutingMessageHandler, - OM: OnionMessageHandler, - L: Logger, - CMH: CustomMessageHandler, - NS: NodeSigner, - SM: SendOnlyMessageHandler, - > APeerManager for PeerManager + Descriptor: SocketDescriptor, + CM: ChannelMessageHandler, + RM: RoutingMessageHandler, + OM: OnionMessageHandler, + L: Logger, + CMH: CustomMessageHandler, + NS: NodeSigner, + SM: SendOnlyMessageHandler, +> APeerManager for PeerManager { type Descriptor = Descriptor; type CM = CM; @@ -1131,13 +1131,13 @@ fn encode_message(message: wire::Message) -> Vec { } impl< - Descriptor: SocketDescriptor, - CM: ChannelMessageHandler, - OM: OnionMessageHandler, - L: Logger, - NS: NodeSigner, - SM: SendOnlyMessageHandler, - > PeerManager + Descriptor: SocketDescriptor, + CM: ChannelMessageHandler, + OM: OnionMessageHandler, + L: Logger, + NS: NodeSigner, + SM: SendOnlyMessageHandler, +> PeerManager { /// Constructs a new `PeerManager` with the given `ChannelMessageHandler` and /// `OnionMessageHandler`. No routing message handler is used and network graph messages are @@ -1226,11 +1226,7 @@ impl(&'a Option<(PublicKey, NodeId)>); impl core::fmt::Display for OptionalFromDebugger<'_> { fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> Result<(), core::fmt::Error> { - if let Some((node_id, _)) = self.0 { - write!(f, " from {}", node_id) - } else { - Ok(()) - } + if let Some((node_id, _)) = self.0 { write!(f, " from {}", node_id) } else { Ok(()) } } } @@ -1268,15 +1264,15 @@ fn filter_addresses(ip_address: Option) -> Option } impl< - Descriptor: SocketDescriptor, - CM: ChannelMessageHandler, - RM: RoutingMessageHandler, - OM: OnionMessageHandler, - L: Logger, - CMH: CustomMessageHandler, - NS: NodeSigner, - SM: SendOnlyMessageHandler, - > PeerManager + Descriptor: SocketDescriptor, + CM: ChannelMessageHandler, + RM: RoutingMessageHandler, + OM: OnionMessageHandler, + L: Logger, + CMH: CustomMessageHandler, + NS: NodeSigner, + SM: SendOnlyMessageHandler, +> PeerManager { /// Constructs a new `PeerManager` with the given message handlers. /// @@ -1944,11 +1940,17 @@ impl< msgs::DecodeError::UnknownRequiredFeature, Some(ty), ) if is_gossip_msg(ty) => { - log_gossip!(logger, "Got a channel/node announcement with an unknown required feature flag, you may want to update!"); + log_gossip!( + logger, + "Got a channel/node announcement with an unknown required feature flag, you may want to update!" + ); continue; }, (msgs::DecodeError::UnsupportedCompression, _) => { - log_gossip!(logger, "We don't support zlib-compressed message fields, sending a warning and ignoring message"); + log_gossip!( + logger, + "We don't support zlib-compressed message fields, sending a warning and ignoring message" + ); let channel_id = ChannelId::new_zero(); let data = "Unsupported message compression: zlib" .to_owned(); @@ -1960,7 +1962,10 @@ impl< continue; }, (_, Some(ty)) if is_gossip_msg(ty) => { - log_gossip!(logger, "Got an invalid value while deserializing a gossip message"); + log_gossip!( + logger, + "Got an invalid value while deserializing a gossip message" + ); let channel_id = ChannelId::new_zero(); let data = format!( "Unreadable/bogus gossip message of type {}", @@ -1974,28 +1979,37 @@ impl< continue; }, (msgs::DecodeError::UnknownRequiredFeature, _) => { - log_debug!(logger, "Received a message with an unknown required feature flag or TLV, you may want to update!"); + log_debug!( + logger, + "Received a message with an unknown required feature flag or TLV, you may want to update!" + ); return Err(PeerHandleError {}); }, (msgs::DecodeError::UnknownVersion, _) => { - return Err(PeerHandleError {}) + return Err(PeerHandleError {}); }, (msgs::DecodeError::InvalidValue, _) => { - log_debug!(logger, "Got an invalid value while deserializing message"); + log_debug!( + logger, + "Got an invalid value while deserializing message" + ); return Err(PeerHandleError {}); }, (msgs::DecodeError::ShortRead, _) => { - log_debug!(logger, "Deserialization failed due to shortness of message"); + log_debug!( + logger, + "Deserialization failed due to shortness of message" + ); return Err(PeerHandleError {}); }, (msgs::DecodeError::BadLengthDescriptor, _) => { - return Err(PeerHandleError {}) + return Err(PeerHandleError {}); }, (msgs::DecodeError::Io(_), _) => { - return Err(PeerHandleError {}) + return Err(PeerHandleError {}); }, (msgs::DecodeError::DangerousValue, _) => { - return Err(PeerHandleError {}) + return Err(PeerHandleError {}); }, } }, @@ -2274,11 +2288,13 @@ impl< if let Message::CommitmentSigned(msg) = message { if let Some(message_batch) = &mut peer_lock.message_batch { - let MessageBatchImpl::CommitmentSigned(ref mut messages) = - &mut message_batch.messages; + let MessageBatchImpl::CommitmentSigned(messages) = &mut message_batch.messages; if msg.channel_id != message_batch.channel_id { - let error = format!("Peer {} sent batched commitment_signed for the wrong channel (expected: {}, actual: {})", their_node_id, message_batch.channel_id, &msg.channel_id); + let error = format!( + "Peer {} sent batched commitment_signed for the wrong channel (expected: {}, actual: {})", + their_node_id, message_batch.channel_id, &msg.channel_id + ); log_debug!(logger, "{}", error); return Err(LightningError { err: error.clone(), @@ -2623,7 +2639,12 @@ impl< ) { match msg { BroadcastGossipMessage::ChannelAnnouncement(msg) => { - log_gossip!(self.logger, "Sending message to all peers except {:?} or the announced channel's counterparties: {:?}", except_node, msg); + log_gossip!( + self.logger, + "Sending message to all peers except {:?} or the announced channel's counterparties: {:?}", + except_node, + msg + ); let our_channel = self.our_node_id == msg.contents.node_id_1 || self.our_node_id == msg.contents.node_id_2; let scid = msg.contents.short_channel_id; @@ -2852,54 +2873,113 @@ impl< self.enqueue_message(&mut *get_peer_for_forwarding!(node_id)?, msg); }, MessageSendEvent::SendAcceptChannel { ref node_id, msg } => { - log_debug!(WithContext::from(&self.logger, Some(*node_id), Some(msg.common_fields.temporary_channel_id), None), "Handling SendAcceptChannel event in peer_handler for node {} for channel {}", - node_id, - &msg.common_fields.temporary_channel_id); + log_debug!( + WithContext::from( + &self.logger, + Some(*node_id), + Some(msg.common_fields.temporary_channel_id), + None + ), + "Handling SendAcceptChannel event in peer_handler for node {} for channel {}", + node_id, + &msg.common_fields.temporary_channel_id + ); let msg = Message::AcceptChannel(msg); self.enqueue_message(&mut *get_peer_for_forwarding!(node_id)?, msg); }, MessageSendEvent::SendAcceptChannelV2 { ref node_id, msg } => { - log_debug!(WithContext::from(&self.logger, Some(*node_id), Some(msg.common_fields.temporary_channel_id), None), "Handling SendAcceptChannelV2 event in peer_handler for node {} for channel {}", - node_id, - &msg.common_fields.temporary_channel_id); + log_debug!( + WithContext::from( + &self.logger, + Some(*node_id), + Some(msg.common_fields.temporary_channel_id), + None + ), + "Handling SendAcceptChannelV2 event in peer_handler for node {} for channel {}", + node_id, + &msg.common_fields.temporary_channel_id + ); let msg = Message::AcceptChannelV2(msg); self.enqueue_message(&mut *get_peer_for_forwarding!(node_id)?, msg); }, MessageSendEvent::SendOpenChannel { ref node_id, msg } => { - log_debug!(WithContext::from(&self.logger, Some(*node_id), Some(msg.common_fields.temporary_channel_id), None), "Handling SendOpenChannel event in peer_handler for node {} for channel {}", - node_id, - &msg.common_fields.temporary_channel_id); + log_debug!( + WithContext::from( + &self.logger, + Some(*node_id), + Some(msg.common_fields.temporary_channel_id), + None + ), + "Handling SendOpenChannel event in peer_handler for node {} for channel {}", + node_id, + &msg.common_fields.temporary_channel_id + ); let msg = Message::OpenChannel(msg); self.enqueue_message(&mut *get_peer_for_forwarding!(node_id)?, msg); }, MessageSendEvent::SendOpenChannelV2 { ref node_id, msg } => { - log_debug!(WithContext::from(&self.logger, Some(*node_id), Some(msg.common_fields.temporary_channel_id), None), "Handling SendOpenChannelV2 event in peer_handler for node {} for channel {}", - node_id, - &msg.common_fields.temporary_channel_id); + log_debug!( + WithContext::from( + &self.logger, + Some(*node_id), + Some(msg.common_fields.temporary_channel_id), + None + ), + "Handling SendOpenChannelV2 event in peer_handler for node {} for channel {}", + node_id, + &msg.common_fields.temporary_channel_id + ); let msg = Message::OpenChannelV2(msg); self.enqueue_message(&mut *get_peer_for_forwarding!(node_id)?, msg); }, MessageSendEvent::SendFundingCreated { ref node_id, msg } => { - log_debug!(WithContext::from(&self.logger, Some(*node_id), Some(msg.temporary_channel_id), None), "Handling SendFundingCreated event in peer_handler for node {} for channel {} (which becomes {})", - node_id, - &msg.temporary_channel_id, - ChannelId::v1_from_funding_txid(msg.funding_txid.as_byte_array(), msg.funding_output_index)); + log_debug!( + WithContext::from( + &self.logger, + Some(*node_id), + Some(msg.temporary_channel_id), + None + ), + "Handling SendFundingCreated event in peer_handler for node {} for channel {} (which becomes {})", + node_id, + &msg.temporary_channel_id, + ChannelId::v1_from_funding_txid( + msg.funding_txid.as_byte_array(), + msg.funding_output_index + ) + ); // TODO: If the peer is gone we should generate a DiscardFunding event // indicating to the wallet that they should just throw away this funding transaction let msg = Message::FundingCreated(msg); self.enqueue_message(&mut *get_peer_for_forwarding!(node_id)?, msg); }, MessageSendEvent::SendFundingSigned { ref node_id, msg } => { - log_debug!(WithContext::from(&self.logger, Some(*node_id), Some(msg.channel_id), None), "Handling SendFundingSigned event in peer_handler for node {} for channel {}", - node_id, - &msg.channel_id); + log_debug!( + WithContext::from( + &self.logger, + Some(*node_id), + Some(msg.channel_id), + None + ), + "Handling SendFundingSigned event in peer_handler for node {} for channel {}", + node_id, + &msg.channel_id + ); let msg = Message::FundingSigned(msg); self.enqueue_message(&mut *get_peer_for_forwarding!(node_id)?, msg); }, MessageSendEvent::SendChannelReady { ref node_id, msg } => { - log_debug!(WithContext::from(&self.logger, Some(*node_id), Some(msg.channel_id), None), "Handling SendChannelReady event in peer_handler for node {} for channel {}", - node_id, - &msg.channel_id); + log_debug!( + WithContext::from( + &self.logger, + Some(*node_id), + Some(msg.channel_id), + None + ), + "Handling SendChannelReady event in peer_handler for node {} for channel {}", + node_id, + &msg.channel_id + ); let msg = Message::ChannelReady(msg); self.enqueue_message(&mut *get_peer_for_forwarding!(node_id)?, msg); }, @@ -2910,9 +2990,12 @@ impl< Some(msg.channel_id), None, ); - log_debug!(logger, "Handling SendStfu event in peer_handler for node {} for channel {}", - node_id, - &msg.channel_id); + log_debug!( + logger, + "Handling SendStfu event in peer_handler for node {} for channel {}", + node_id, + &msg.channel_id + ); let msg = Message::Stfu(msg); self.enqueue_message(&mut *get_peer_for_forwarding!(node_id)?, msg); }, @@ -2923,9 +3006,12 @@ impl< Some(msg.channel_id), None, ); - log_debug!(logger, "Handling SendSpliceInit event in peer_handler for node {} for channel {}", - node_id, - &msg.channel_id); + log_debug!( + logger, + "Handling SendSpliceInit event in peer_handler for node {} for channel {}", + node_id, + &msg.channel_id + ); let msg = Message::SpliceInit(msg); self.enqueue_message(&mut *get_peer_for_forwarding!(node_id)?, msg); }, @@ -2936,9 +3022,12 @@ impl< Some(msg.channel_id), None, ); - log_debug!(logger, "Handling SendSpliceAck event in peer_handler for node {} for channel {}", - node_id, - &msg.channel_id); + log_debug!( + logger, + "Handling SendSpliceAck event in peer_handler for node {} for channel {}", + node_id, + &msg.channel_id + ); let msg = Message::SpliceAck(msg); self.enqueue_message(&mut *get_peer_for_forwarding!(node_id)?, msg); }, @@ -2949,79 +3038,162 @@ impl< Some(msg.channel_id), None, ); - log_debug!(logger, "Handling SendSpliceLocked event in peer_handler for node {} for channel {}", - node_id, - &msg.channel_id); + log_debug!( + logger, + "Handling SendSpliceLocked event in peer_handler for node {} for channel {}", + node_id, + &msg.channel_id + ); let msg = Message::SpliceLocked(msg); self.enqueue_message(&mut *get_peer_for_forwarding!(node_id)?, msg); }, MessageSendEvent::SendTxAddInput { ref node_id, msg } => { - log_debug!(WithContext::from(&self.logger, Some(*node_id), Some(msg.channel_id), None), "Handling SendTxAddInput event in peer_handler for node {} for channel {}", - node_id, - &msg.channel_id); + log_debug!( + WithContext::from( + &self.logger, + Some(*node_id), + Some(msg.channel_id), + None + ), + "Handling SendTxAddInput event in peer_handler for node {} for channel {}", + node_id, + &msg.channel_id + ); let msg = Message::TxAddInput(msg); self.enqueue_message(&mut *get_peer_for_forwarding!(node_id)?, msg); }, MessageSendEvent::SendTxAddOutput { ref node_id, msg } => { - log_debug!(WithContext::from(&self.logger, Some(*node_id), Some(msg.channel_id), None), "Handling SendTxAddOutput event in peer_handler for node {} for channel {}", - node_id, - &msg.channel_id); + log_debug!( + WithContext::from( + &self.logger, + Some(*node_id), + Some(msg.channel_id), + None + ), + "Handling SendTxAddOutput event in peer_handler for node {} for channel {}", + node_id, + &msg.channel_id + ); let msg = Message::TxAddOutput(msg); self.enqueue_message(&mut *get_peer_for_forwarding!(node_id)?, msg); }, MessageSendEvent::SendTxRemoveInput { ref node_id, msg } => { - log_debug!(WithContext::from(&self.logger, Some(*node_id), Some(msg.channel_id), None), "Handling SendTxRemoveInput event in peer_handler for node {} for channel {}", - node_id, - &msg.channel_id); + log_debug!( + WithContext::from( + &self.logger, + Some(*node_id), + Some(msg.channel_id), + None + ), + "Handling SendTxRemoveInput event in peer_handler for node {} for channel {}", + node_id, + &msg.channel_id + ); let msg = Message::TxRemoveInput(msg); self.enqueue_message(&mut *get_peer_for_forwarding!(node_id)?, msg); }, MessageSendEvent::SendTxRemoveOutput { ref node_id, msg } => { - log_debug!(WithContext::from(&self.logger, Some(*node_id), Some(msg.channel_id), None), "Handling SendTxRemoveOutput event in peer_handler for node {} for channel {}", - node_id, - &msg.channel_id); + log_debug!( + WithContext::from( + &self.logger, + Some(*node_id), + Some(msg.channel_id), + None + ), + "Handling SendTxRemoveOutput event in peer_handler for node {} for channel {}", + node_id, + &msg.channel_id + ); let msg = Message::TxRemoveOutput(msg); self.enqueue_message(&mut *get_peer_for_forwarding!(node_id)?, msg); }, MessageSendEvent::SendTxComplete { ref node_id, msg } => { - log_debug!(WithContext::from(&self.logger, Some(*node_id), Some(msg.channel_id), None), "Handling SendTxComplete event in peer_handler for node {} for channel {}", - node_id, - &msg.channel_id); + log_debug!( + WithContext::from( + &self.logger, + Some(*node_id), + Some(msg.channel_id), + None + ), + "Handling SendTxComplete event in peer_handler for node {} for channel {}", + node_id, + &msg.channel_id + ); let msg = Message::TxComplete(msg); self.enqueue_message(&mut *get_peer_for_forwarding!(node_id)?, msg); }, MessageSendEvent::SendTxSignatures { ref node_id, msg } => { - log_debug!(WithContext::from(&self.logger, Some(*node_id), Some(msg.channel_id), None), "Handling SendTxSignatures event in peer_handler for node {} for channel {}", - node_id, - &msg.channel_id); + log_debug!( + WithContext::from( + &self.logger, + Some(*node_id), + Some(msg.channel_id), + None + ), + "Handling SendTxSignatures event in peer_handler for node {} for channel {}", + node_id, + &msg.channel_id + ); let msg = Message::TxSignatures(msg); self.enqueue_message(&mut *get_peer_for_forwarding!(node_id)?, msg); }, MessageSendEvent::SendTxInitRbf { ref node_id, msg } => { - log_debug!(WithContext::from(&self.logger, Some(*node_id), Some(msg.channel_id), None), "Handling SendTxInitRbf event in peer_handler for node {} for channel {}", - node_id, - &msg.channel_id); + log_debug!( + WithContext::from( + &self.logger, + Some(*node_id), + Some(msg.channel_id), + None + ), + "Handling SendTxInitRbf event in peer_handler for node {} for channel {}", + node_id, + &msg.channel_id + ); let msg = Message::TxInitRbf(msg); self.enqueue_message(&mut *get_peer_for_forwarding!(node_id)?, msg); }, MessageSendEvent::SendTxAckRbf { ref node_id, msg } => { - log_debug!(WithContext::from(&self.logger, Some(*node_id), Some(msg.channel_id), None), "Handling SendTxAckRbf event in peer_handler for node {} for channel {}", - node_id, - &msg.channel_id); + log_debug!( + WithContext::from( + &self.logger, + Some(*node_id), + Some(msg.channel_id), + None + ), + "Handling SendTxAckRbf event in peer_handler for node {} for channel {}", + node_id, + &msg.channel_id + ); let msg = Message::TxAckRbf(msg); self.enqueue_message(&mut *get_peer_for_forwarding!(node_id)?, msg); }, MessageSendEvent::SendTxAbort { ref node_id, msg } => { - log_debug!(WithContext::from(&self.logger, Some(*node_id), Some(msg.channel_id), None), "Handling SendTxAbort event in peer_handler for node {} for channel {}", - node_id, - &msg.channel_id); + log_debug!( + WithContext::from( + &self.logger, + Some(*node_id), + Some(msg.channel_id), + None + ), + "Handling SendTxAbort event in peer_handler for node {} for channel {}", + node_id, + &msg.channel_id + ); let msg = Message::TxAbort(msg); self.enqueue_message(&mut *get_peer_for_forwarding!(node_id)?, msg); }, MessageSendEvent::SendAnnouncementSignatures { ref node_id, msg } => { - log_debug!(WithContext::from(&self.logger, Some(*node_id), Some(msg.channel_id), None), "Handling SendAnnouncementSignatures event in peer_handler for node {} for channel {})", - node_id, - &msg.channel_id); + log_debug!( + WithContext::from( + &self.logger, + Some(*node_id), + Some(msg.channel_id), + None + ), + "Handling SendAnnouncementSignatures event in peer_handler for node {} for channel {})", + node_id, + &msg.channel_id + ); let msg = Message::AnnouncementSignatures(msg); self.enqueue_message(&mut *get_peer_for_forwarding!(node_id)?, msg); }, @@ -3038,13 +3210,21 @@ impl< commitment_signed, }, } => { - log_debug!(WithContext::from(&self.logger, Some(*node_id), Some(*channel_id), None), "Handling UpdateHTLCs event in peer_handler for node {} with {} adds, {} fulfills, {} fails, {} commits for channel {}", - node_id, - update_add_htlcs.len(), - update_fulfill_htlcs.len(), - update_fail_htlcs.len(), - commitment_signed.len(), - channel_id); + log_debug!( + WithContext::from( + &self.logger, + Some(*node_id), + Some(*channel_id), + None + ), + "Handling UpdateHTLCs event in peer_handler for node {} with {} adds, {} fulfills, {} fails, {} commits for channel {}", + node_id, + update_add_htlcs.len(), + update_fulfill_htlcs.len(), + update_fail_htlcs.len(), + commitment_signed.len(), + channel_id + ); let mut peer = get_peer_for_forwarding!(node_id)?; for msg in update_fulfill_htlcs { let msg = Message::UpdateFulfillHTLC(msg); @@ -3081,32 +3261,64 @@ impl< } }, MessageSendEvent::SendRevokeAndACK { ref node_id, msg } => { - log_debug!(WithContext::from(&self.logger, Some(*node_id), Some(msg.channel_id), None), "Handling SendRevokeAndACK event in peer_handler for node {} for channel {}", - node_id, - &msg.channel_id); + log_debug!( + WithContext::from( + &self.logger, + Some(*node_id), + Some(msg.channel_id), + None + ), + "Handling SendRevokeAndACK event in peer_handler for node {} for channel {}", + node_id, + &msg.channel_id + ); let msg = Message::RevokeAndACK(msg); self.enqueue_message(&mut *get_peer_for_forwarding!(node_id)?, msg); }, MessageSendEvent::SendClosingSigned { ref node_id, msg } => { - log_debug!(WithContext::from(&self.logger, Some(*node_id), Some(msg.channel_id), None), "Handling SendClosingSigned event in peer_handler for node {} for channel {}", - node_id, - &msg.channel_id); + log_debug!( + WithContext::from( + &self.logger, + Some(*node_id), + Some(msg.channel_id), + None + ), + "Handling SendClosingSigned event in peer_handler for node {} for channel {}", + node_id, + &msg.channel_id + ); let msg = Message::ClosingSigned(msg); self.enqueue_message(&mut *get_peer_for_forwarding!(node_id)?, msg); }, #[cfg(simple_close)] MessageSendEvent::SendClosingComplete { ref node_id, msg } => { - log_debug!(WithContext::from(&self.logger, Some(*node_id), Some(msg.channel_id), None), "Handling SendClosingComplete event in peer_handler for node {} for channel {}", - node_id, - &msg.channel_id); + log_debug!( + WithContext::from( + &self.logger, + Some(*node_id), + Some(msg.channel_id), + None + ), + "Handling SendClosingComplete event in peer_handler for node {} for channel {}", + node_id, + &msg.channel_id + ); let msg = Message::ClosingComplete(msg); self.enqueue_message(&mut *get_peer_for_forwarding!(node_id)?, msg); }, #[cfg(simple_close)] MessageSendEvent::SendClosingSig { ref node_id, msg } => { - log_debug!(WithContext::from(&self.logger, Some(*node_id), Some(msg.channel_id), None), "Handling SendClosingSig event in peer_handler for node {} for channel {}", - node_id, - &msg.channel_id); + log_debug!( + WithContext::from( + &self.logger, + Some(*node_id), + Some(msg.channel_id), + None + ), + "Handling SendClosingSig event in peer_handler for node {} for channel {}", + node_id, + &msg.channel_id + ); let msg = Message::ClosingSig(msg); self.enqueue_message(&mut *get_peer_for_forwarding!(node_id)?, msg); }, @@ -3124,9 +3336,17 @@ impl< self.enqueue_message(&mut *get_peer_for_forwarding!(node_id)?, msg); }, MessageSendEvent::SendChannelReestablish { ref node_id, msg } => { - log_debug!(WithContext::from(&self.logger, Some(*node_id), Some(msg.channel_id), None), "Handling SendChannelReestablish event in peer_handler for node {} for channel {}", - node_id, - &msg.channel_id); + log_debug!( + WithContext::from( + &self.logger, + Some(*node_id), + Some(msg.channel_id), + None + ), + "Handling SendChannelReestablish event in peer_handler for node {} for channel {}", + node_id, + &msg.channel_id + ); let msg = Message::ChannelReestablish(msg); self.enqueue_message(&mut *get_peer_for_forwarding!(node_id)?, msg); }, @@ -3135,9 +3355,12 @@ impl< msg, update_msg, } => { - log_debug!(WithContext::from(&self.logger, Some(*node_id), None, None), "Handling SendChannelAnnouncement event in peer_handler for node {} for short channel id {}", - node_id, - msg.contents.short_channel_id); + log_debug!( + WithContext::from(&self.logger, Some(*node_id), None, None), + "Handling SendChannelAnnouncement event in peer_handler for node {} for short channel id {}", + node_id, + msg.contents.short_channel_id + ); let msg = Message::ChannelAnnouncement(msg); self.enqueue_message(&mut *get_peer_for_forwarding!(node_id)?, msg); let update_msg = Message::ChannelUpdate(update_msg); @@ -3147,7 +3370,11 @@ impl< ); }, MessageSendEvent::BroadcastChannelAnnouncement { msg, update_msg } => { - log_debug!(self.logger, "Handling BroadcastChannelAnnouncement event in peer_handler for short channel id {}", msg.contents.short_channel_id); + log_debug!( + self.logger, + "Handling BroadcastChannelAnnouncement event in peer_handler for short channel id {}", + msg.contents.short_channel_id + ); let node_id_1 = msg.contents.node_id_1; let node_id_2 = msg.contents.node_id_2; match route_handler.handle_channel_announcement(None, &msg) { @@ -3190,7 +3417,11 @@ impl< } }, MessageSendEvent::BroadcastChannelUpdate { msg, node_id_1, node_id_2 } => { - log_debug!(self.logger, "Handling BroadcastChannelUpdate event in peer_handler for contents {:?}", msg.contents); + log_debug!( + self.logger, + "Handling BroadcastChannelUpdate event in peer_handler for contents {:?}", + msg.contents + ); match route_handler.handle_channel_update(None, &msg) { Ok(_) | Err(LightningError { @@ -3213,7 +3444,11 @@ impl< } }, MessageSendEvent::BroadcastNodeAnnouncement { msg } => { - log_debug!(self.logger, "Handling BroadcastNodeAnnouncement event in peer_handler for node {}", msg.contents.node_id); + log_debug!( + self.logger, + "Handling BroadcastNodeAnnouncement event in peer_handler for node {}", + msg.contents.node_id + ); match route_handler.handle_node_announcement(None, &msg) { Ok(_) | Err(LightningError { @@ -3245,11 +3480,16 @@ impl< match action { msgs::ErrorAction::DisconnectPeer { msg } => { if let Some(msg) = msg.as_ref() { - log_trace!(logger, "Handling DisconnectPeer HandleError event in peer_handler with message {}", - msg.data); + log_trace!( + logger, + "Handling DisconnectPeer HandleError event in peer_handler with message {}", + msg.data + ); } else { - log_trace!(logger, "Handling DisconnectPeer HandleError event in peer_handler", - ); + log_trace!( + logger, + "Handling DisconnectPeer HandleError event in peer_handler", + ); } // We do not have the peers write lock, so we just store that we're // about to disconnect the peer and do it after we finish @@ -3259,8 +3499,11 @@ impl< peers_to_disconnect.insert(node_id, msg); }, msgs::ErrorAction::DisconnectPeerWithWarning { msg } => { - log_trace!(logger, "Handling DisconnectPeer HandleError event in peer_handler with message {}", - msg.data); + log_trace!( + logger, + "Handling DisconnectPeer HandleError event in peer_handler with message {}", + msg.data + ); // We do not have the peers write lock, so we just store that we're // about to disconnect the peer and do it after we finish // processing most messages. @@ -3282,9 +3525,11 @@ impl< ); }, msgs::ErrorAction::SendErrorMessage { msg } => { - log_trace!(logger, "Handling SendErrorMessage HandleError event in peer_handler with message {}", - - msg.data); + log_trace!( + logger, + "Handling SendErrorMessage HandleError event in peer_handler with message {}", + msg.data + ); let msg = Message::Error(msg); self.enqueue_message( &mut *get_peer_for_forwarding!(&node_id)?, @@ -3292,9 +3537,12 @@ impl< ); }, msgs::ErrorAction::SendWarningMessage { msg, ref log_level } => { - log_given_level!(logger, *log_level, "Handling SendWarningMessage HandleError event in peer_handler with message {}", - - msg.data); + log_given_level!( + logger, + *log_level, + "Handling SendWarningMessage HandleError event in peer_handler with message {}", + msg.data + ); let msg = Message::Warning(msg); self.enqueue_message( &mut *get_peer_for_forwarding!(&node_id)?, @@ -3304,35 +3552,43 @@ impl< } }, MessageSendEvent::SendChannelRangeQuery { ref node_id, msg } => { - log_gossip!(WithContext::from(&self.logger, Some(*node_id), None, None), "Handling SendChannelRangeQuery event in peer_handler with first_blocknum={}, number_of_blocks={}", - + log_gossip!( + WithContext::from(&self.logger, Some(*node_id), None, None), + "Handling SendChannelRangeQuery event in peer_handler with first_blocknum={}, number_of_blocks={}", msg.first_blocknum, - msg.number_of_blocks); + msg.number_of_blocks + ); let msg = Message::QueryChannelRange(msg); self.enqueue_message(&mut *get_peer_for_forwarding!(node_id)?, msg); }, MessageSendEvent::SendShortIdsQuery { ref node_id, msg } => { - log_gossip!(WithContext::from(&self.logger, Some(*node_id), None, None), "Handling SendShortIdsQuery event in peer_handler with num_scids={}", - - msg.short_channel_ids.len()); + log_gossip!( + WithContext::from(&self.logger, Some(*node_id), None, None), + "Handling SendShortIdsQuery event in peer_handler with num_scids={}", + msg.short_channel_ids.len() + ); let msg = Message::QueryShortChannelIds(msg); self.enqueue_message(&mut *get_peer_for_forwarding!(node_id)?, msg); }, MessageSendEvent::SendReplyChannelRange { ref node_id, msg } => { - log_gossip!(WithContext::from(&self.logger, Some(*node_id), None, None), "Handling SendReplyChannelRange event in peer_handler with num_scids={} first_blocknum={} number_of_blocks={}, sync_complete={}", - + log_gossip!( + WithContext::from(&self.logger, Some(*node_id), None, None), + "Handling SendReplyChannelRange event in peer_handler with num_scids={} first_blocknum={} number_of_blocks={}, sync_complete={}", msg.short_channel_ids.len(), msg.first_blocknum, msg.number_of_blocks, - msg.sync_complete); + msg.sync_complete + ); let msg = Message::ReplyChannelRange(msg); self.enqueue_message(&mut *get_peer_for_forwarding!(node_id)?, msg); }, MessageSendEvent::SendGossipTimestampFilter { ref node_id, msg } => { - log_gossip!(WithContext::from(&self.logger, Some(*node_id), None, None), "Handling SendGossipTimestampFilter event in peer_handler with first_timestamp={}, timestamp_range={}", - + log_gossip!( + WithContext::from(&self.logger, Some(*node_id), None, None), + "Handling SendGossipTimestampFilter event in peer_handler with first_timestamp={}, timestamp_range={}", msg.first_timestamp, - msg.timestamp_range); + msg.timestamp_range + ); let msg = Message::GossipTimestampFilter(msg); self.enqueue_message(&mut *get_peer_for_forwarding!(node_id)?, msg); }, @@ -3731,9 +3987,9 @@ mod tests { use crate::types::features::{InitFeatures, NodeFeatures}; use crate::util::test_utils; + use bitcoin::Network; use bitcoin::constants::ChainHash; use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey}; - use bitcoin::Network; use crate::sync::{Arc, Mutex}; use core::convert::Infallible; diff --git a/lightning/src/ln/priv_short_conf_tests.rs b/lightning/src/ln/priv_short_conf_tests.rs index 979c896e15d..e8c74a7a7a2 100644 --- a/lightning/src/ln/priv_short_conf_tests.rs +++ b/lightning/src/ln/priv_short_conf_tests.rs @@ -14,7 +14,7 @@ use crate::chain::ChannelMonitorUpdateStatus; use crate::events::{ClosureReason, Event, HTLCHandlingFailureType, PaymentFailureReason}; use crate::ln::channel::CHANNEL_ANNOUNCEMENT_PROPAGATION_DELAY; -use crate::ln::channelmanager::{PaymentId, TrustedChannelFeatures, MIN_CLTV_EXPIRY_DELTA}; +use crate::ln::channelmanager::{MIN_CLTV_EXPIRY_DELTA, PaymentId, TrustedChannelFeatures}; use crate::ln::msgs; use crate::ln::msgs::{ BaseMessageHandler, ChannelMessageHandler, ErrorAction, MessageSendEvent, RoutingMessageHandler, @@ -197,7 +197,7 @@ fn do_test_1_conf_open(connect_style: ConnectStyle) { let node_cfgs = create_node_cfgs(2, &chanmon_cfgs); let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(alice_config), Some(bob_config)]); - let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs); + let nodes = create_network(2, &node_cfgs, &node_chanmgrs); let node_a_id = nodes[0].node.get_our_node_id(); let node_b_id = nodes[1].node.get_our_node_id(); *nodes[0].connect_style.borrow_mut() = connect_style; @@ -286,10 +286,11 @@ fn do_test_1_conf_open(connect_style: ConnectStyle) { for (i, node) in nodes.iter().enumerate() { let counterparty_node_id = nodes[(i + 1) % 2].node.get_our_node_id(); - assert!(node - .gossip_sync - .handle_channel_announcement(Some(counterparty_node_id), &announcement) - .unwrap()); + assert!( + node.gossip_sync + .handle_channel_announcement(Some(counterparty_node_id), &announcement) + .unwrap() + ); node.gossip_sync.handle_channel_update(Some(counterparty_node_id), &as_update).unwrap(); node.gossip_sync.handle_channel_update(Some(counterparty_node_id), &bs_update).unwrap(); } @@ -309,7 +310,7 @@ fn test_routed_scid_alias() { let mut no_announce_cfg = test_default_channel_config(); no_announce_cfg.accept_forwards_to_priv_channels = true; let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, Some(no_announce_cfg), None]); - let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs); + let nodes = create_network(3, &node_cfgs, &node_chanmgrs); let node_b_id = nodes[1].node.get_our_node_id(); let node_c_id = nodes[2].node.get_our_node_id(); @@ -384,7 +385,7 @@ fn test_scid_privacy_on_pub_channel() { let chanmon_cfgs = create_chanmon_cfgs(2); let node_cfgs = create_node_cfgs(2, &chanmon_cfgs); let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]); - let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs); + let nodes = create_network(2, &node_cfgs, &node_chanmgrs); let node_a_id = nodes[0].node.get_our_node_id(); let node_b_id = nodes[1].node.get_our_node_id(); @@ -413,7 +414,7 @@ fn test_scid_privacy_negotiation() { let chanmon_cfgs = create_chanmon_cfgs(2); let node_cfgs = create_node_cfgs(2, &chanmon_cfgs); let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]); - let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs); + let nodes = create_network(2, &node_cfgs, &node_chanmgrs); let node_a_id = nodes[0].node.get_our_node_id(); let node_b_id = nodes[1].node.get_our_node_id(); @@ -442,12 +443,9 @@ fn test_scid_privacy_negotiation() { let second_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, node_b_id); - assert!(!second_open_channel - .common_fields - .channel_type - .as_ref() - .unwrap() - .supports_scid_privacy()); + assert!( + !second_open_channel.common_fields.channel_type.as_ref().unwrap().supports_scid_privacy() + ); handle_and_accept_open_channel(&nodes[1], node_a_id, &second_open_channel); nodes[0].node.handle_accept_channel( node_b_id, @@ -461,16 +459,12 @@ fn test_scid_privacy_negotiation() { _ => panic!("Unexpected event"), } - assert!(!nodes[0].node.list_channels()[0] - .channel_type - .as_ref() - .unwrap() - .supports_scid_privacy()); - assert!(!nodes[1].node.list_channels()[0] - .channel_type - .as_ref() - .unwrap() - .supports_scid_privacy()); + assert!( + !nodes[0].node.list_channels()[0].channel_type.as_ref().unwrap().supports_scid_privacy() + ); + assert!( + !nodes[1].node.list_channels()[0].channel_type.as_ref().unwrap().supports_scid_privacy() + ); } #[test] @@ -483,7 +477,7 @@ fn test_inbound_scid_privacy() { accept_forward_cfg.accept_forwards_to_priv_channels = true; let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, Some(accept_forward_cfg), None]); - let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs); + let nodes = create_network(3, &node_cfgs, &node_chanmgrs); let node_a_id = nodes[0].node.get_our_node_id(); let node_b_id = nodes[1].node.get_our_node_id(); let node_c_id = nodes[2].node.get_our_node_id(); @@ -497,7 +491,7 @@ fn test_inbound_scid_privacy() { .node .create_channel(node_c_id, 100_000, 10_000, 42, None, Some(no_announce_cfg)) .unwrap(); - let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, node_c_id); + let open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, node_c_id); assert!(open_channel.common_fields.channel_type.as_ref().unwrap().requires_scid_privacy()); @@ -624,7 +618,7 @@ fn test_inbound_scid_privacy() { 1, ); - let mut updates = get_htlc_update_msgs(&nodes[1], &node_a_id); + let updates = get_htlc_update_msgs(&nodes[1], &node_a_id); nodes[0].node.handle_update_fail_htlc(node_b_id, &updates.update_fail_htlcs[0]); do_commitment_signed_dance(&nodes[0], &nodes[1], &updates.commitment_signed, false, false); @@ -659,7 +653,7 @@ fn test_scid_alias_returned() { let chan = create_unannounced_chan_between_nodes_with_value(&nodes, 1, 2, 10_000, 0); let last_hop = nodes[2].node.list_usable_channels(); - let mut hop_hints = vec![RouteHint(vec![RouteHintHop { + let hop_hints = vec![RouteHint(vec![RouteHintHop { src_node_id: node_b_id, short_channel_id: last_hop[0].inbound_scid_alias.unwrap(), fees: RoutingFees { @@ -780,7 +774,7 @@ fn test_simple_0conf_channel() { let chanmon_cfgs = create_chanmon_cfgs(2); let node_cfgs = create_node_cfgs(2, &chanmon_cfgs); - let mut chan_config = test_default_channel_config(); + let chan_config = test_default_channel_config(); let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(chan_config)]); let nodes = create_network(2, &node_cfgs, &node_chanmgrs); @@ -830,8 +824,7 @@ fn test_0conf_channel_with_async_monitor() { _ => panic!("Unexpected event"), }; - let mut accept_channel = - get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, node_a_id); + let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, node_a_id); assert_eq!(accept_channel.common_fields.minimum_depth, 0); nodes[0].node.handle_accept_channel(node_b_id, &accept_channel); @@ -1115,7 +1108,7 @@ fn test_0conf_channel_reorg() { let original_scid = bs_chan.short_channel_id.unwrap(); assert_eq!(nodes[2].node.list_usable_channels()[0].short_channel_id.unwrap(), original_scid); - let (mut route, payment_hash, payment_preimage, payment_secret) = + let (route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 10_000); assert_eq!(route.paths[0].hops[0].short_channel_id, original_scid); send_along_route_with_secret( @@ -1335,10 +1328,12 @@ fn test_zero_conf_accept_reject() { match events[0] { Event::OpenChannelRequest { temporary_channel_id, .. } => { // Assert we fail to accept via the non-0conf method - assert!(nodes[1] - .node - .accept_inbound_channel(&temporary_channel_id, &node_a_id, 0, None) - .is_err()); + assert!( + nodes[1] + .node + .accept_inbound_channel(&temporary_channel_id, &node_a_id, 0, None) + .is_err() + ); }, _ => panic!(), } @@ -1368,16 +1363,18 @@ fn test_zero_conf_accept_reject() { match events[0] { Event::OpenChannelRequest { temporary_channel_id, .. } => { // Assert we can accept via the 0conf method - assert!(nodes[1] - .node - .accept_inbound_channel_from_trusted_peer( - &temporary_channel_id, - &node_a_id, - 0, - TrustedChannelFeatures::ZeroConf, - None, - ) - .is_ok()); + assert!( + nodes[1] + .node + .accept_inbound_channel_from_trusted_peer( + &temporary_channel_id, + &node_a_id, + 0, + TrustedChannelFeatures::ZeroConf, + None, + ) + .is_ok() + ); }, _ => panic!(), } @@ -1425,8 +1422,7 @@ fn test_connect_before_funding() { _ => panic!("Unexpected event"), }; - let mut accept_channel = - get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, node_a_id); + let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, node_a_id); assert_eq!(accept_channel.common_fields.minimum_depth, 0); nodes[0].node.handle_accept_channel(node_b_id, &accept_channel); @@ -1528,7 +1524,7 @@ fn test_channel_update_dont_forward_flag() { let public_channel_update = events .iter() .find_map(|e| { - if let MessageSendEvent::BroadcastChannelUpdate { ref msg, .. } = e { + if let MessageSendEvent::BroadcastChannelUpdate { msg, .. } = e { Some(msg.clone()) } else { None @@ -1573,10 +1569,10 @@ fn test_channel_update_dont_forward_flag() { #[test] fn test_unknown_channel_update_with_dont_forward_logs_debug() { + use bitcoin::Network; use bitcoin::constants::ChainHash; use bitcoin::secp256k1::ecdsa::Signature; use bitcoin::secp256k1::ffi::Signature as FFISignature; - use bitcoin::Network; let chanmon_cfgs = create_chanmon_cfgs(2); let node_cfgs = create_node_cfgs(2, &chanmon_cfgs); diff --git a/lightning/src/ln/quiescence_tests.rs b/lightning/src/ln/quiescence_tests.rs index 495a1622522..006b6f417aa 100644 --- a/lightning/src/ln/quiescence_tests.rs +++ b/lightning/src/ln/quiescence_tests.rs @@ -236,11 +236,7 @@ fn test_quiescence_waits_for_async_signer_and_monitor_update() { $events .iter() .find_map(|event| { - if let MessageSendEvent::$msg { ref msg, .. } = event { - Some(msg) - } else { - None - } + if let MessageSendEvent::$msg { msg, .. } = event { Some(msg) } else { None } }) .unwrap() }}; diff --git a/lightning/src/ln/reload_tests.rs b/lightning/src/ln/reload_tests.rs index 16ba896685e..f84de0d84fb 100644 --- a/lightning/src/ln/reload_tests.rs +++ b/lightning/src/ln/reload_tests.rs @@ -620,7 +620,7 @@ fn do_test_data_loss_protect(reconnect_panicing: bool, substantially_old: bool, } { - let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap(); + let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap(); // The node B should never force-close the channel. assert!(node_txn.is_empty()); } @@ -905,7 +905,7 @@ fn do_test_partial_claim_before_restart(persist_both_monitors: bool, double_rest let mut cs_updates = match ds_msgs.remove(1) { MessageSendEvent::UpdateHTLCs { mut updates, .. } => { - let mut fulfill = updates.update_fulfill_htlcs.remove(0); + let fulfill = updates.update_fulfill_htlcs.remove(0); nodes[2].node.handle_update_fulfill_htlc(nodes[3].node.get_our_node_id(), fulfill); check_added_monitors(&nodes[2], 1); let cs_updates = get_htlc_update_msgs(&nodes[2], &nodes[0].node.get_our_node_id()); @@ -1316,7 +1316,7 @@ fn test_manager_persisted_post_outbound_edge_forward() { // Lock in the HTLC from node_a <> node_b. let amt_msat = 5000; - let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat); + let (route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat); nodes[0].node.send_payment_with_route(route, payment_hash, RecipientOnionFields::secret_only(payment_secret, amt_msat), PaymentId(payment_hash.0)).unwrap(); check_added_monitors(&nodes[0], 1); let updates = get_htlc_update_msgs(&nodes[0], &nodes[1].node.get_our_node_id()); @@ -1513,7 +1513,7 @@ fn test_reload_partial_funding_batch() { // The monitor should become closed. check_added_monitors(&nodes[0], 1); { - let mut monitor_updates = nodes[0].chain_monitor.monitor_updates.lock().unwrap(); + let monitor_updates = nodes[0].chain_monitor.monitor_updates.lock().unwrap(); let monitor_updates_1 = monitor_updates.get(&channel_id_1).unwrap(); assert_eq!(monitor_updates_1.len(), 1); assert_eq!(monitor_updates_1[0].updates.len(), 1); @@ -2183,7 +2183,7 @@ fn test_reload_with_mpp_claims_on_same_channel() { nodes[0].node.peer_disconnected(node_1_id); nodes[1].node.peer_disconnected(node_0_id); - let mut events = nodes[2].node.get_and_clear_pending_msg_events(); + let events = nodes[2].node.get_and_clear_pending_msg_events(); assert_eq!(events.len(), 2); for ev in events { match ev { diff --git a/lightning/src/ln/reorg_tests.rs b/lightning/src/ln/reorg_tests.rs index 5b5160148d7..78f2cacdd60 100644 --- a/lightning/src/ln/reorg_tests.rs +++ b/lightning/src/ln/reorg_tests.rs @@ -9,10 +9,10 @@ //! Further functional tests which test blockchain reorganizations. +use crate::chain::Confirm; use crate::chain::chaininterface::LowerBoundedFeeEstimator; -use crate::chain::channelmonitor::{Balance, ANTI_REORG_DELAY, LATENCY_GRACE_PERIOD_BLOCKS}; +use crate::chain::channelmonitor::{ANTI_REORG_DELAY, Balance, LATENCY_GRACE_PERIOD_BLOCKS}; use crate::chain::transaction::OutPoint; -use crate::chain::Confirm; use crate::events::{ClosureReason, Event, HTLCHandlingFailureType}; use crate::ln::msgs::{BaseMessageHandler, ChannelMessageHandler, Init, MessageSendEvent}; use crate::ln::types::ChannelId; @@ -341,8 +341,7 @@ fn do_test_unconf_chan( } let expected_err = "Funding transaction was un-confirmed, originally locked at 6 confs."; - let broadcast_close_msg = - "Channel closed because of an exception: Funding transaction was un-confirmed, originally locked at 6 confs."; + let broadcast_close_msg = "Channel closed because of an exception: Funding transaction was un-confirmed, originally locked at 6 confs."; let counterparty_force_closed_reason = || ClosureReason::CounterpartyForceClosed { peer_msg: UntrustedString(format!( "Channel closed because of an exception: {}", @@ -629,7 +628,7 @@ fn do_test_to_remote_after_local_detection(style: ConnectStyle) { let chanmon_cfgs = create_chanmon_cfgs(2); let node_cfgs = create_node_cfgs(2, &chanmon_cfgs); let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]); - let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs); + let nodes = create_network(2, &node_cfgs, &node_chanmgrs); let node_id_0 = nodes[0].node.get_our_node_id(); let node_id_1 = nodes[1].node.get_our_node_id(); @@ -838,8 +837,8 @@ fn test_htlc_preimage_claim_holder_commitment_after_counterparty_commitment_reor } #[test] -fn test_htlc_preimage_claim_prev_counterparty_commitment_after_current_counterparty_commitment_reorg( -) { +fn test_htlc_preimage_claim_prev_counterparty_commitment_after_current_counterparty_commitment_reorg() + { // We detect a counterparty commitment confirm onchain, followed by a reorg and a // confirmation of the previous (still unrevoked) counterparty commitment. Then, if we learn // of the preimage for an HTLC in both commitments, test that we only claim the currently @@ -1052,18 +1051,18 @@ fn do_test_retries_own_commitment_broadcast_after_reorg( // `commitment_b`. if keyed_anchors || p2a_anchor { handle_bump_close_event(&nodes[0]); - let mut txn = nodes[0].tx_broadcaster.txn_broadcast(); + let txn = nodes[0].tx_broadcaster.txn_broadcast(); assert_eq!(txn.len(), 3); check_spends!(txn[0], commitment_b); check_spends!(txn[1], funding_tx); check_spends!(txn[2], txn[1], coinbase_tx); // Anchor output spend transaction. } else { - let mut txn = nodes[0].tx_broadcaster.txn_broadcast(); + let txn = nodes[0].tx_broadcaster.txn_broadcast(); assert_eq!(txn.len(), 2); check_spends!(txn.last().unwrap(), commitment_b); } } else { - let mut txn = nodes[0].tx_broadcaster.txn_broadcast(); + let txn = nodes[0].tx_broadcaster.txn_broadcast(); assert_eq!(txn.len(), 1); check_spends!(txn[0], commitment_b); } @@ -1077,7 +1076,7 @@ fn do_test_retries_own_commitment_broadcast_after_reorg( handle_bump_close_event(&nodes[0]); } { - let mut txn = nodes[0].tx_broadcaster.unique_txn_broadcast(); + let txn = nodes[0].tx_broadcaster.unique_txn_broadcast(); if keyed_anchors || p2a_anchor { assert_eq!(txn.len(), 2); check_spends!(txn[0], funding_tx); @@ -1223,7 +1222,7 @@ fn do_test_split_htlc_expiry_tracking(use_third_htlc: bool, reorg_out: bool, p2a // But confirm B's dual-HTLC-claim transaction instead. A should now have nothing to broadcast // as the third HTLC (if there is one) won't expire for another block. mine_transaction(&nodes[0], &bs_htlc_spend_tx); - let mut txn = nodes[0].tx_broadcaster.txn_broadcast(); + let txn = nodes[0].tx_broadcaster.txn_broadcast(); assert_eq!(txn.len(), 0); check_added_monitors(&nodes[0], 0); @@ -1278,7 +1277,7 @@ fn do_test_split_htlc_expiry_tracking(use_third_htlc: bool, reorg_out: bool, p2a // We connect blocks until one block before `bs_htlc_spend_tx` reaches `ANTI_REORG_DELAY` // confirmations. connect_blocks(&nodes[0], ANTI_REORG_DELAY - 4); - let mut txn = nodes[0].tx_broadcaster.txn_broadcast(); + let txn = nodes[0].tx_broadcaster.txn_broadcast(); assert_eq!(txn.len(), 0); assert!(nodes[0].node.get_and_clear_pending_events().is_empty()); diff --git a/lightning/src/ln/shutdown_tests.rs b/lightning/src/ln/shutdown_tests.rs index d70b240e4e4..99f5d0f88f9 100644 --- a/lightning/src/ln/shutdown_tests.rs +++ b/lightning/src/ln/shutdown_tests.rs @@ -10,8 +10,8 @@ //! Tests of our shutdown and closing_signed negotiation logic as well as some assorted force-close //! handling tests. -use crate::chain::transaction::OutPoint; use crate::chain::ChannelMonitorUpdateStatus; +use crate::chain::transaction::OutPoint; use crate::events::{ClosureReason, Event, HTLCHandlingFailureReason, HTLCHandlingFailureType}; use crate::ln::channel_state::{ChannelDetails, ChannelShutdownState}; use crate::ln::channelmanager::{self, PaymentId}; @@ -22,7 +22,7 @@ use crate::ln::outbound_payment::{RecipientOnionFields, Retry}; use crate::ln::script::ShutdownScript; use crate::ln::types::ChannelId; use crate::prelude::*; -use crate::routing::router::{get_route, PaymentParameters, RouteParameters}; +use crate::routing::router::{PaymentParameters, RouteParameters, get_route}; use crate::sign::{EntropySource, SignerProvider}; use crate::types::string::UntrustedString; use crate::util::config::UserConfig; @@ -141,7 +141,7 @@ fn expect_channel_shutdown_state_with_htlc() { let chanmon_cfgs = create_chanmon_cfgs(3); let node_cfgs = create_node_cfgs(3, &chanmon_cfgs); let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]); - let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs); + let nodes = create_network(3, &node_cfgs, &node_chanmgrs); let node_a_id = nodes[0].node.get_our_node_id(); let node_b_id = nodes[1].node.get_our_node_id(); let node_c_id = nodes[2].node.get_our_node_id(); @@ -237,7 +237,7 @@ fn test_lnd_bug_6039() { let chanmon_cfgs = create_chanmon_cfgs(2); let node_cfgs = create_node_cfgs(2, &chanmon_cfgs); let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]); - let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs); + let nodes = create_network(2, &node_cfgs, &node_chanmgrs); let node_a_id = nodes[0].node.get_our_node_id(); let node_b_id = nodes[1].node.get_our_node_id(); let chan = create_announced_chan_between_nodes(&nodes, 0, 1); @@ -387,7 +387,7 @@ fn updates_shutdown_wait() { let chanmon_cfgs = create_chanmon_cfgs(3); let node_cfgs = create_node_cfgs(3, &chanmon_cfgs); let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]); - let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs); + let nodes = create_network(3, &node_cfgs, &node_chanmgrs); let node_a_id = nodes[0].node.get_our_node_id(); let node_b_id = nodes[1].node.get_our_node_id(); let node_c_id = nodes[2].node.get_our_node_id(); @@ -518,7 +518,7 @@ fn do_htlc_fail_async_shutdown(blinded_recipient: bool) { let chanmon_cfgs = create_chanmon_cfgs(3); let node_cfgs = create_node_cfgs(3, &chanmon_cfgs); let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]); - let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs); + let nodes = create_network(3, &node_cfgs, &node_chanmgrs); let node_a_id = nodes[0].node.get_our_node_id(); let node_b_id = nodes[1].node.get_our_node_id(); let node_c_id = nodes[2].node.get_our_node_id(); @@ -879,7 +879,7 @@ fn test_upfront_shutdown_script() { let chanmon_cfgs = create_chanmon_cfgs(3); let node_cfgs = create_node_cfgs(3, &chanmon_cfgs); let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &user_cfgs); - let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs); + let nodes = create_network(3, &node_cfgs, &node_chanmgrs); let node_a_id = nodes[0].node.get_our_node_id(); let node_b_id = nodes[1].node.get_our_node_id(); let node_c_id = nodes[2].node.get_our_node_id(); @@ -976,7 +976,7 @@ fn test_upfront_shutdown_script() { #[test] fn test_unsupported_anysegwit_upfront_shutdown_script() { let chanmon_cfgs = create_chanmon_cfgs(2); - let mut node_cfgs = create_node_cfgs(2, &chanmon_cfgs); + let node_cfgs = create_node_cfgs(2, &chanmon_cfgs); // Clear shutdown_anysegwit on initiator let mut features = channelmanager::provided_init_features(&test_default_channel_config()); features.clear_shutdown_anysegwit(); @@ -998,10 +998,12 @@ fn test_unsupported_anysegwit_upfront_shutdown_script() { assert_eq!(events.len(), 1); match &events[0] { Event::OpenChannelRequest { temporary_channel_id, counterparty_node_id, .. } => { - assert!(nodes[1] - .node - .accept_inbound_channel(temporary_channel_id, counterparty_node_id, 42, None,) - .is_err()); + assert!( + nodes[1] + .node + .accept_inbound_channel(temporary_channel_id, counterparty_node_id, 42, None,) + .is_err() + ); }, _ => panic!("Unexpected event"), }; @@ -1014,13 +1016,16 @@ fn test_unsupported_anysegwit_upfront_shutdown_script() { node_id, } => { assert_eq!(node_id, node_a_id); - assert_eq!(msg.data, "Peer is signaling upfront_shutdown but has provided an unacceptable scriptpubkey format: OP_PUSHNUM_16 OP_PUSHBYTES_2 0028"); + assert_eq!( + msg.data, + "Peer is signaling upfront_shutdown but has provided an unacceptable scriptpubkey format: OP_PUSHNUM_16 OP_PUSHBYTES_2 0028" + ); }, _ => panic!("Unexpected event"), } let chanmon_cfgs = create_chanmon_cfgs(2); - let mut node_cfgs = create_node_cfgs(2, &chanmon_cfgs); + let node_cfgs = create_node_cfgs(2, &chanmon_cfgs); // Clear shutdown_anysegwit on responder let mut features = channelmanager::provided_init_features(&test_default_channel_config()); features.clear_shutdown_anysegwit(); @@ -1048,7 +1053,10 @@ fn test_unsupported_anysegwit_upfront_shutdown_script() { node_id, } => { assert_eq!(node_id, node_b_id); - assert_eq!(msg.data, "Peer is signaling upfront_shutdown but has provided an unacceptable scriptpubkey format: OP_PUSHNUM_16 OP_PUSHBYTES_2 0028"); + assert_eq!( + msg.data, + "Peer is signaling upfront_shutdown but has provided an unacceptable scriptpubkey format: OP_PUSHNUM_16 OP_PUSHBYTES_2 0028" + ); }, _ => panic!("Unexpected event"), } @@ -1076,10 +1084,12 @@ fn test_invalid_upfront_shutdown_script() { assert_eq!(events.len(), 1); match &events[0] { Event::OpenChannelRequest { temporary_channel_id, counterparty_node_id, .. } => { - assert!(nodes[1] - .node - .accept_inbound_channel(temporary_channel_id, counterparty_node_id, 42, None,) - .is_err()); + assert!( + nodes[1] + .node + .accept_inbound_channel(temporary_channel_id, counterparty_node_id, 42, None,) + .is_err() + ); }, _ => panic!("Unexpected event"), }; @@ -1092,7 +1102,10 @@ fn test_invalid_upfront_shutdown_script() { node_id, } => { assert_eq!(node_id, node_a_id); - assert_eq!(msg.data, "Peer is signaling upfront_shutdown but has provided an unacceptable scriptpubkey format: OP_0 OP_PUSHBYTES_2 0000"); + assert_eq!( + msg.data, + "Peer is signaling upfront_shutdown but has provided an unacceptable scriptpubkey format: OP_0 OP_PUSHBYTES_2 0000" + ); }, _ => panic!("Unexpected event"), } @@ -1184,7 +1197,7 @@ fn test_unsupported_anysegwit_shutdown_script() { config.channel_handshake_config.commit_upfront_shutdown_pubkey = false; let user_cfgs = [None, Some(config.clone()), None]; let chanmon_cfgs = create_chanmon_cfgs(3); - let mut node_cfgs = create_node_cfgs(3, &chanmon_cfgs); + let node_cfgs = create_node_cfgs(3, &chanmon_cfgs); let mut features = channelmanager::provided_init_features(&config); features.clear_shutdown_anysegwit(); *node_cfgs[0].override_init_features.borrow_mut() = Some(features.clone()); @@ -1281,7 +1294,7 @@ fn test_user_shutdown_script() { .unwrap(); check_added_monitors(&nodes[1], 1); - let mut node_0_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, node_a_id); + let node_0_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, node_a_id); assert_eq!(node_0_shutdown.scriptpubkey, script); } @@ -1339,7 +1352,7 @@ fn do_test_closing_signed_reinit_timeout(timeout_step: TimeoutStep) { let node_cfgs = create_node_cfgs(2, &chanmon_cfgs); let legacy_cfg = test_legacy_channel_config(); let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(legacy_cfg), None]); - let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs); + let nodes = create_network(2, &node_cfgs, &node_chanmgrs); let node_a_id = nodes[0].node.get_our_node_id(); let node_b_id = nodes[1].node.get_our_node_id(); let chan_id = create_announced_chan_between_nodes(&nodes, 0, 1).2; @@ -1368,14 +1381,16 @@ fn do_test_closing_signed_reinit_timeout(timeout_step: TimeoutStep) { if timeout_step != TimeoutStep::AfterShutdown { nodes[1].node.handle_closing_signed(node_a_id, &node_0_closing_signed); - assert!(check_warn_msg!(nodes[1], node_a_id, chan_id) - .starts_with("Unable to come to consensus about closing feerate")); + assert!( + check_warn_msg!(nodes[1], node_a_id, chan_id) + .starts_with("Unable to come to consensus about closing feerate") + ); // Now deliver a mutated closing_signed indicating a higher acceptable fee range, which // nodes[1] should happily accept and respond to. node_0_closing_signed.fee_range.as_mut().unwrap().max_fee_satoshis *= 10; { - let mut per_peer_lock; + let per_peer_lock; let mut peer_state_lock; let chan = get_channel_ref!(nodes[0], nodes[1], per_peer_lock, peer_state_lock, chan_id); @@ -1865,7 +1880,7 @@ fn test_pending_htlcs_arent_lost_on_mon_delay() { let node_cfgs = create_node_cfgs(3, &chanmon_cfgs); let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]); - let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs); + let nodes = create_network(3, &node_cfgs, &node_chanmgrs); let node_a_id = nodes[0].node.get_our_node_id(); let node_b_id = nodes[1].node.get_our_node_id(); diff --git a/lightning/src/ln/splicing_tests.rs b/lightning/src/ln/splicing_tests.rs index 9a3813904e1..0ce1d25cc7b 100644 --- a/lightning/src/ln/splicing_tests.rs +++ b/lightning/src/ln/splicing_tests.rs @@ -9,10 +9,10 @@ #![cfg_attr(not(test), allow(unused_imports))] -use crate::chain::chaininterface::{FundingPurpose, TransactionType, FEERATE_FLOOR_SATS_PER_KW}; +use crate::chain::ChannelMonitorUpdateStatus; +use crate::chain::chaininterface::{FEERATE_FLOOR_SATS_PER_KW, FundingPurpose, TransactionType}; use crate::chain::channelmonitor::{ANTI_REORG_DELAY, LATENCY_GRACE_PERIOD_BLOCKS}; use crate::chain::transaction::OutPoint; -use crate::chain::ChannelMonitorUpdateStatus; use crate::events::{ClosureReason, Event, FundingInfo, HTLCHandlingFailureType}; use crate::ln::chan_utils; use crate::ln::channel::{ @@ -20,7 +20,7 @@ use crate::ln::channel::{ DISCONNECT_PEER_AWAITING_RESPONSE_TICKS, FEE_SPIKE_BUFFER_FEE_INCREASE_MULTIPLE, MIN_CHANNEL_VALUE_SATOSHIS, }; -use crate::ln::channelmanager::{provided_init_features, PaymentId, BREAKDOWN_TIMEOUT}; +use crate::ln::channelmanager::{BREAKDOWN_TIMEOUT, PaymentId, provided_init_features}; use crate::ln::functional_test_utils::*; use crate::ln::funding::{FundingContribution, FundingContributionError}; use crate::ln::msgs::{self, BaseMessageHandler, ChannelMessageHandler, MessageSendEvent}; @@ -116,9 +116,9 @@ fn test_v1_splice_in_negative_insufficient_inputs() { nodes[0].node.splice_channel(&channel_id, &nodes[1].node.get_our_node_id()).unwrap(); let wallet = WalletSync::new(Arc::clone(&nodes[0].wallet_source), nodes[0].logger); - assert!(funding_template - .splice_in_sync(splice_in_value, feerate, FeeRate::MAX, &wallet) - .is_err()); + assert!( + funding_template.splice_in_sync(splice_in_value, feerate, FeeRate::MAX, &wallet).is_err() + ); } /// A mock wallet that returns a pre-configured [`CoinSelection`] with a single input and change @@ -537,7 +537,7 @@ pub fn sign_interactive_funding_tx_with_acceptor_contribution<'a, 'b, 'c, 'd>( let msg_events = initiator.node.get_and_clear_pending_msg_events(); assert_eq!(msg_events.len(), 1, "{msg_events:?}"); let initial_commit_sig_for_acceptor = - if let MessageSendEvent::UpdateHTLCs { ref updates, .. } = &msg_events[0] { + if let MessageSendEvent::UpdateHTLCs { updates, .. } = &msg_events[0] { updates.commitment_signed[0].clone() } else { panic!(); @@ -569,13 +569,13 @@ pub fn sign_interactive_funding_tx_with_acceptor_contribution<'a, 'b, 'c, 'd>( let msg_events = acceptor.node.get_and_clear_pending_msg_events(); assert_eq!(msg_events.len(), 2, "{msg_events:?}"); - if let MessageSendEvent::UpdateHTLCs { ref updates, .. } = &msg_events[0] { + if let MessageSendEvent::UpdateHTLCs { updates, .. } = &msg_events[0] { let commitment_signed = &updates.commitment_signed[0]; initiator.node.handle_commitment_signed(node_id_acceptor, commitment_signed); } else { panic!(); } - if let MessageSendEvent::SendTxSignatures { ref msg, .. } = &msg_events[1] { + if let MessageSendEvent::SendTxSignatures { msg, .. } = &msg_events[1] { initiator.node.handle_tx_signatures(node_id_acceptor, msg); } else { panic!(); @@ -583,7 +583,7 @@ pub fn sign_interactive_funding_tx_with_acceptor_contribution<'a, 'b, 'c, 'd>( let mut msg_events = initiator.node.get_and_clear_pending_msg_events(); assert_eq!(msg_events.len(), if is_0conf { 2 } else { 1 }, "{msg_events:?}"); - if let MessageSendEvent::SendTxSignatures { ref msg, .. } = &msg_events[0] { + if let MessageSendEvent::SendTxSignatures { msg, .. } = &msg_events[0] { acceptor.node.handle_tx_signatures(node_id_initiator, msg); } else { panic!(); @@ -2562,7 +2562,7 @@ fn do_test_propose_splice_while_disconnected(use_0conf: bool) { // Node 1's quiescent action was consumed, so it should NOT send stfu. let msg_events = nodes[1].node.get_and_clear_pending_msg_events(); assert_eq!(msg_events.len(), if use_0conf { 1 } else { 2 }, "{msg_events:?}"); - if let MessageSendEvent::SendSpliceLocked { ref msg, .. } = &msg_events[0] { + if let MessageSendEvent::SendSpliceLocked { msg, .. } = &msg_events[0] { nodes[0].node.handle_splice_locked(node_id_1, msg); if use_0conf { // TODO(splicing): Revisit splice transaction rebroadcasts. @@ -2576,7 +2576,7 @@ fn do_test_propose_splice_while_disconnected(use_0conf: bool) { panic!("Unexpected event {:?}", &msg_events[0]); } if !use_0conf { - if let MessageSendEvent::SendAnnouncementSignatures { ref msg, .. } = &msg_events[1] { + if let MessageSendEvent::SendAnnouncementSignatures { msg, .. } = &msg_events[1] { nodes[0].node.handle_announcement_signatures(node_id_1, msg); } else { panic!("Unexpected event {:?}", &msg_events[1]); @@ -2586,7 +2586,7 @@ fn do_test_propose_splice_while_disconnected(use_0conf: bool) { let msg_events = nodes[0].node.get_and_clear_pending_msg_events(); assert_eq!(msg_events.len(), if use_0conf { 0 } else { 2 }, "{msg_events:?}"); if !use_0conf { - if let MessageSendEvent::SendAnnouncementSignatures { ref msg, .. } = &msg_events[0] { + if let MessageSendEvent::SendAnnouncementSignatures { msg, .. } = &msg_events[0] { nodes[1].node.handle_announcement_signatures(node_id_0, msg); } else { panic!("Unexpected event {:?}", &msg_events[1]); @@ -2928,14 +2928,14 @@ fn free_holding_cell_on_tx_signatures_quiescence_exit() { let msg_events = acceptor.node.get_and_clear_pending_msg_events(); assert_eq!(msg_events.len(), 2, "{msg_events:?}"); - if let MessageSendEvent::UpdateHTLCs { ref updates, .. } = &msg_events[0] { + if let MessageSendEvent::UpdateHTLCs { updates, .. } = &msg_events[0] { let commitment_signed = &updates.commitment_signed[0]; initiator.node.handle_commitment_signed(node_id_acceptor, commitment_signed); check_added_monitors(&initiator, 1); } else { panic!("Unexpected event {:?}", &msg_events[0]); } - if let MessageSendEvent::SendTxSignatures { ref msg, .. } = &msg_events[1] { + if let MessageSendEvent::SendTxSignatures { msg, .. } = &msg_events[1] { initiator.node.handle_tx_signatures(node_id_acceptor, msg); } else { panic!("Unexpected event {:?}", &msg_events[1]); @@ -2946,7 +2946,7 @@ fn free_holding_cell_on_tx_signatures_quiescence_exit() { let msg_events = initiator.node.get_and_clear_pending_msg_events(); assert_eq!(msg_events.len(), 2, "{msg_events:?}"); check_added_monitors(initiator, 1); // Outgoing HTLC monitor update - if let MessageSendEvent::SendTxSignatures { ref msg, .. } = &msg_events[0] { + if let MessageSendEvent::SendTxSignatures { msg, .. } = &msg_events[0] { acceptor.node.handle_tx_signatures(node_id_initiator, msg); } else { panic!("Unexpected event {:?}", &msg_events[0]); @@ -3401,12 +3401,12 @@ fn test_splice_buffer_commitment_signed_until_funding_tx_signed() { // 2. The buffered commitment_signed from the acceptor should be processed (monitor update) let msg_events = nodes[0].node.get_and_clear_pending_msg_events(); assert_eq!(msg_events.len(), 1, "{msg_events:?}"); - let initiator_commit_sig = - if let MessageSendEvent::UpdateHTLCs { ref updates, .. } = &msg_events[0] { - updates.commitment_signed[0].clone() - } else { - panic!("Expected UpdateHTLCs message"); - }; + let initiator_commit_sig = if let MessageSendEvent::UpdateHTLCs { updates, .. } = &msg_events[0] + { + updates.commitment_signed[0].clone() + } else { + panic!("Expected UpdateHTLCs message"); + }; // The buffered commitment_signed should have been processed, resulting in a monitor update. check_added_monitors(&nodes[0], 1); @@ -3415,7 +3415,7 @@ fn test_splice_buffer_commitment_signed_until_funding_tx_signed() { nodes[1].node.handle_commitment_signed(node_id_0, &initiator_commit_sig); let msg_events = nodes[1].node.get_and_clear_pending_msg_events(); assert_eq!(msg_events.len(), 1, "{msg_events:?}"); - if let MessageSendEvent::SendTxSignatures { ref msg, .. } = &msg_events[0] { + if let MessageSendEvent::SendTxSignatures { msg, .. } = &msg_events[0] { nodes[0].node.handle_tx_signatures(node_id_1, msg); } else { panic!("Expected SendTxSignatures message"); @@ -3424,7 +3424,7 @@ fn test_splice_buffer_commitment_signed_until_funding_tx_signed() { let msg_events = nodes[0].node.get_and_clear_pending_msg_events(); assert_eq!(msg_events.len(), 1, "{msg_events:?}"); - if let MessageSendEvent::SendTxSignatures { ref msg, .. } = &msg_events[0] { + if let MessageSendEvent::SendTxSignatures { msg, .. } = &msg_events[0] { nodes[1].node.handle_tx_signatures(node_id_0, msg); } else { panic!("Expected SendTxSignatures message"); @@ -3535,14 +3535,14 @@ fn test_splice_buffer_invalid_commitment_signed_closes_channel() { let msg_events = nodes[0].node.get_and_clear_pending_msg_events(); assert_eq!(msg_events.len(), 3, "{msg_events:?}"); match &msg_events[0] { - MessageSendEvent::UpdateHTLCs { ref updates, .. } => { + MessageSendEvent::UpdateHTLCs { updates, .. } => { assert!(!updates.commitment_signed.is_empty()); }, _ => panic!("Expected UpdateHTLCs message, got {:?}", msg_events[0]), } match &msg_events[1] { MessageSendEvent::HandleError { - action: msgs::ErrorAction::SendErrorMessage { ref msg }, + action: msgs::ErrorAction::SendErrorMessage { msg }, .. } => { assert!(msg.data.contains("Invalid commitment tx signature from peer")); @@ -3550,7 +3550,7 @@ fn test_splice_buffer_invalid_commitment_signed_closes_channel() { _ => panic!("Expected HandleError with SendErrorMessage, got {:?}", msg_events[1]), } match &msg_events[2] { - MessageSendEvent::BroadcastChannelUpdate { ref msg, .. } => { + MessageSendEvent::BroadcastChannelUpdate { msg, .. } => { assert_eq!(msg.contents.channel_flags & 2, 2); }, _ => panic!("Expected BroadcastChannelUpdate, got {:?}", msg_events[2]), @@ -3627,13 +3627,13 @@ fn do_splice_waits_for_initial_commitment_monitor_update_before_releasing_tx_sig let msg_events = nodes[1].node.get_and_clear_pending_msg_events(); assert_eq!(msg_events.len(), 2, "{msg_events:?}"); let counterparty_commit_sig = - if let MessageSendEvent::UpdateHTLCs { ref updates, .. } = &msg_events[0] { + if let MessageSendEvent::UpdateHTLCs { updates, .. } = &msg_events[0] { updates.commitment_signed[0].clone() } else { panic!("Expected UpdateHTLCs message"); }; let counterparty_tx_signatures = - if let MessageSendEvent::SendTxSignatures { ref msg, .. } = &msg_events[1] { + if let MessageSendEvent::SendTxSignatures { msg, .. } = &msg_events[1] { msg.clone() } else { panic!("Expected SendTxSignatures message"); @@ -4288,7 +4288,9 @@ fn do_test_splice_pending_htlcs(config: UserConfig) { assert_eq!(error, APIError::APIMisuseError { err: cannot_accept_contribution }); let cannot_be_funded = format!( "Channel {} cannot be funded: Our splice-out value of {} is greater than the maximum {}", - channel_id, splice_out_incl_fees + Amount::ONE_SAT, splice_out_incl_fees, + channel_id, + splice_out_incl_fees + Amount::ONE_SAT, + splice_out_incl_fees, ); initiator.logger.assert_log("lightning::ln::channel", cannot_be_funded, 1); @@ -4317,7 +4319,9 @@ fn do_test_splice_pending_htlcs(config: UserConfig) { assert_eq!(msg.channel_id, channel_id); let cannot_be_spliced_out = format!( "Channel {} cannot be spliced out; their post-splice channel balance {} is smaller than our selected v2 reserve {}", - channel_id, post_splice_reserve - Amount::ONE_SAT, post_splice_reserve + channel_id, + post_splice_reserve - Amount::ONE_SAT, + post_splice_reserve ); assert_eq!(msg.data, cannot_be_spliced_out); @@ -4719,15 +4723,17 @@ fn test_splice_rbf_insufficient_feerate() { assert_eq!(min_rbf_feerate, expected_floor); let wallet = WalletSync::new(Arc::clone(&nodes[0].wallet_source), nodes[0].logger); - assert!(funding_template - .splice_in_sync(added_value, same_feerate, FeeRate::MAX, &wallet) - .is_err()); + assert!( + funding_template.splice_in_sync(added_value, same_feerate, FeeRate::MAX, &wallet).is_err() + ); // Verify that the floor feerate succeeds. let funding_template = nodes[0].node.splice_channel(&channel_id, &node_id_1).unwrap(); - assert!(funding_template - .splice_in_sync(added_value, min_rbf_feerate, FeeRate::MAX, &wallet) - .is_ok()); + assert!( + funding_template + .splice_in_sync(added_value, min_rbf_feerate, FeeRate::MAX, &wallet) + .is_ok() + ); // Acceptor-side: tx_init_rbf with an insufficient feerate is also rejected. // Node 0 initiates a proper RBF but we tamper the feerate to be insufficient. @@ -7727,7 +7733,8 @@ fn do_test_0reserve_splice_holder_validation( Amount::from_sat( initiator_value_to_self_sat - commit_tx_fee_sat - - anchors_sat - estimated_fees_sat + - anchors_sat + - estimated_fees_sat - dust_limit_satoshis, ) } else if counterparty_has_output && !node_0_is_initiator { diff --git a/lightning/src/ln/types.rs b/lightning/src/ln/types.rs index fd8ccbae382..317eb44f6d8 100644 --- a/lightning/src/ln/types.rs +++ b/lightning/src/ln/types.rs @@ -20,7 +20,7 @@ use crate::util::ser::{Readable, Writeable, Writer}; #[allow(unused_imports)] use crate::prelude::*; -use bitcoin::hashes::{sha256::Hash as Sha256, Hash as _, HashEngine as _}; +use bitcoin::hashes::{Hash as _, HashEngine as _, sha256::Hash as Sha256}; use bitcoin::hex::display::impl_fmt_traits; use core::borrow::Borrow; @@ -131,7 +131,7 @@ impl_fmt_traits! { #[cfg(test)] mod tests { - use bitcoin::hashes::{sha256::Hash as Sha256, Hash as _, HashEngine as _}; + use bitcoin::hashes::{Hash as _, HashEngine as _, sha256::Hash as Sha256}; use bitcoin::hex::DisplayHex; use bitcoin::secp256k1::PublicKey; diff --git a/lightning/src/ln/update_fee_tests.rs b/lightning/src/ln/update_fee_tests.rs index b1f8257088e..a9b3a371b4c 100644 --- a/lightning/src/ln/update_fee_tests.rs +++ b/lightning/src/ln/update_fee_tests.rs @@ -2,12 +2,12 @@ use crate::events::{ClosureReason, Event}; use crate::ln::chan_utils::{ - self, commitment_tx_base_weight, CommitmentTransaction, HTLCOutputInCommitment, - COMMITMENT_TX_WEIGHT_PER_HTLC, + self, COMMITMENT_TX_WEIGHT_PER_HTLC, CommitmentTransaction, HTLCOutputInCommitment, + commitment_tx_base_weight, }; use crate::ln::channel::{ - get_holder_selected_channel_reserve_satoshis, ANCHOR_OUTPUT_VALUE_SATOSHI, - CONCURRENT_INBOUND_HTLC_FEE_BUFFER, MIN_AFFORDABLE_HTLC_COUNT, + ANCHOR_OUTPUT_VALUE_SATOSHI, CONCURRENT_INBOUND_HTLC_FEE_BUFFER, MIN_AFFORDABLE_HTLC_COUNT, + get_holder_selected_channel_reserve_satoshis, }; use crate::ln::channelmanager::PaymentId; use crate::ln::functional_test_utils::*; @@ -15,8 +15,8 @@ use crate::ln::msgs::{ self, BaseMessageHandler, ChannelMessageHandler, ErrorAction, MessageSendEvent, }; use crate::ln::outbound_payment::RecipientOnionFields; -use crate::sign::ecdsa::EcdsaChannelSigner; use crate::sign::ChannelSigner; +use crate::sign::ecdsa::EcdsaChannelSigner; use crate::types::features::ChannelTypeFeatures; use crate::util::config::UserConfig; use crate::util::errors::APIError; @@ -30,7 +30,7 @@ pub fn test_async_inbound_update_fee() { let chanmon_cfgs = create_chanmon_cfgs(2); let node_cfgs = create_node_cfgs(2, &chanmon_cfgs); let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]); - let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs); + let nodes = create_network(2, &node_cfgs, &node_chanmgrs); let node_a_id = nodes[0].node.get_our_node_id(); let node_b_id = nodes[1].node.get_our_node_id(); @@ -148,7 +148,7 @@ pub fn test_update_fee_unordered_raa() { let chanmon_cfgs = create_chanmon_cfgs(2); let node_cfgs = create_node_cfgs(2, &chanmon_cfgs); let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]); - let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs); + let nodes = create_network(2, &node_cfgs, &node_chanmgrs); let node_a_id = nodes[0].node.get_our_node_id(); let node_b_id = nodes[1].node.get_our_node_id(); @@ -467,7 +467,7 @@ pub fn do_test_update_fee_that_funder_cannot_afford(channel_type_features: Chann const INITIAL_COMMITMENT_NUMBER: u64 = 281474976710654; let remote_point = { - let mut per_peer_lock; + let per_peer_lock; let mut peer_state_lock; let channel = get_channel_ref!(nodes[1], nodes[0], per_peer_lock, peer_state_lock, chan.2); @@ -477,7 +477,7 @@ pub fn do_test_update_fee_that_funder_cannot_afford(channel_type_features: Chann }; let res = { - let mut per_peer_lock; + let per_peer_lock; let mut peer_state_lock; let local_chan = @@ -540,13 +540,13 @@ pub fn test_update_fee_that_saturates_subs() { // on the commitment transaction that is greater than her balance, we saturate the subtractions, // and force close the channel. - let mut cfg = test_legacy_channel_config(); + let cfg = test_legacy_channel_config(); let secp_ctx = Secp256k1::new(); let chanmon_cfgs = create_chanmon_cfgs(2); let node_cfgs = create_node_cfgs(2, &chanmon_cfgs); let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(cfg.clone()), Some(cfg)]); - let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs); + let nodes = create_network(2, &node_cfgs, &node_chanmgrs); let node_a_id = nodes[0].node.get_our_node_id(); @@ -565,7 +565,7 @@ pub fn test_update_fee_that_saturates_subs() { // in `commitment_signed`. let remote_point = { - let mut per_peer_lock; + let per_peer_lock; let mut peer_state_lock; let channel = get_channel_ref!(nodes[1], nodes[0], per_peer_lock, peer_state_lock, chan_id); @@ -574,7 +574,7 @@ pub fn test_update_fee_that_saturates_subs() { }; let res = { - let mut per_peer_lock; + let per_peer_lock; let mut peer_state_lock; let local_chan = @@ -624,7 +624,7 @@ pub fn test_update_fee_with_fundee_update_add_htlc() { let chanmon_cfgs = create_chanmon_cfgs(2); let node_cfgs = create_node_cfgs(2, &chanmon_cfgs); let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]); - let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs); + let nodes = create_network(2, &node_cfgs, &node_chanmgrs); let node_a_id = nodes[0].node.get_our_node_id(); let node_b_id = nodes[1].node.get_our_node_id(); @@ -854,13 +854,13 @@ pub fn test_update_fee() { pub fn test_chan_init_feerate_unaffordability() { // Test that we will reject channel opens which do not leave enough to pay for any HTLCs due to // channel reserve and feerate requirements. - let mut chanmon_cfgs = create_chanmon_cfgs(2); + let chanmon_cfgs = create_chanmon_cfgs(2); let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap(); let node_cfgs = create_node_cfgs(2, &chanmon_cfgs); let legacy_cfg = test_legacy_channel_config(); let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(legacy_cfg.clone()), Some(legacy_cfg)]); - let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs); + let nodes = create_network(2, &node_cfgs, &node_chanmgrs); let node_a_id = nodes[0].node.get_our_node_id(); let node_b_id = nodes[1].node.get_our_node_id(); @@ -897,10 +897,12 @@ pub fn test_chan_init_feerate_unaffordability() { assert_eq!(events.len(), 1); match &events[0] { Event::OpenChannelRequest { temporary_channel_id, counterparty_node_id, .. } => { - assert!(nodes[1] - .node - .accept_inbound_channel(temporary_channel_id, counterparty_node_id, 42, None,) - .is_err()); + assert!( + nodes[1] + .node + .accept_inbound_channel(temporary_channel_id, counterparty_node_id, 42, None,) + .is_err() + ); }, _ => panic!("Unexpected event"), } @@ -922,7 +924,7 @@ pub fn accept_busted_but_better_fee() { // If a peer sends us a fee update that is too low, but higher than our previous channel // feerate, we should accept it. In the future we may want to consider closing the channel // later, but for now we only accept the update. - let mut chanmon_cfgs = create_chanmon_cfgs(2); + let chanmon_cfgs = create_chanmon_cfgs(2); let node_cfgs = create_node_cfgs(2, &chanmon_cfgs); let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]); let nodes = create_network(2, &node_cfgs, &node_chanmgrs); @@ -1040,7 +1042,7 @@ pub fn do_cannot_afford_on_holding_cell_release( let node_cfgs = create_node_cfgs(2, &chanmon_cfgs); let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(cfg.clone()), Some(cfg)]); - let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs); + let nodes = create_network(2, &node_cfgs, &node_chanmgrs); let node_a_id = nodes[0].node.get_our_node_id(); let node_b_id = nodes[1].node.get_our_node_id(); @@ -1234,7 +1236,7 @@ pub fn do_can_afford_given_trimmed_htlcs(inequality_regions: core::cmp::Ordering let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(legacy_cfg.clone()), Some(legacy_cfg)]); - let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs); + let nodes = create_network(2, &node_cfgs, &node_chanmgrs); let node_a_id = nodes[0].node.get_our_node_id(); let node_b_id = nodes[1].node.get_our_node_id(); @@ -1399,11 +1401,9 @@ pub fn test_zero_fee_commitments_no_update_fee() { for node in nodes.iter() { let channels = node.node.list_channels(); assert_eq!(channels.len(), 1); - assert!(channels[0] - .channel_type - .as_ref() - .unwrap() - .supports_anchor_zero_fee_commitments()); + assert!( + channels[0].channel_type.as_ref().unwrap().supports_anchor_zero_fee_commitments() + ); assert_eq!(channels[0].feerate_sat_per_1000_weight.unwrap(), 0); } }; @@ -1423,11 +1423,12 @@ pub fn test_zero_fee_commitments_no_update_fee() { assert_eq!(events_1.len(), 1); match events_1[0] { MessageSendEvent::HandleError { ref action, .. } => match action { - ErrorAction::DisconnectPeerWithWarning { ref msg, .. } => { + ErrorAction::DisconnectPeerWithWarning { msg, .. } => { assert_eq!(msg.channel_id, channel_id); - assert!(msg - .data - .contains("Update fee message received for zero fee commitment channel")); + assert!( + msg.data + .contains("Update fee message received for zero fee commitment channel") + ); }, _ => panic!("Expected DisconnectPeerWithWarning, got {:?}", action), }, diff --git a/lightning/src/ln/zero_fee_commitment_tests.rs b/lightning/src/ln/zero_fee_commitment_tests.rs index 61c3e1063d0..f537ae2eb1b 100644 --- a/lightning/src/ln/zero_fee_commitment_tests.rs +++ b/lightning/src/ln/zero_fee_commitment_tests.rs @@ -8,8 +8,8 @@ use crate::ln::functional_test_utils::*; use crate::ln::msgs::BaseMessageHandler; use crate::prelude::*; -use bitcoin::constants::WITNESS_SCALE_FACTOR; use bitcoin::Amount; +use bitcoin::constants::WITNESS_SCALE_FACTOR; #[test] fn test_p2a_anchor_values_under_trims_and_rounds() { diff --git a/lightning/src/offers/async_receive_offer_cache.rs b/lightning/src/offers/async_receive_offer_cache.rs index c4442b4dd8f..09dd271e673 100644 --- a/lightning/src/offers/async_receive_offer_cache.rs +++ b/lightning/src/offers/async_receive_offer_cache.rs @@ -414,11 +414,7 @@ impl AsyncReceiveOfferCache { /// Returns an iterator over (offer_idx, offer) fn offers_with_idx(&self) -> impl Iterator { self.offers.iter().enumerate().filter_map(|(idx, offer_opt)| { - if let Some(offer) = offer_opt { - Some((idx, offer)) - } else { - None - } + if let Some(offer) = offer_opt { Some((idx, offer)) } else { None } }) } @@ -487,7 +483,7 @@ impl AsyncReceiveOfferCache { let mut offers = self.offers.iter_mut(); let offer_entry = offers.find(|o| o.as_ref().is_some_and(|o| o.offer.id() == offer_id)); - if let Some(Some(ref mut offer)) = offer_entry { + if let Some(Some(offer)) = offer_entry { match offer.status { OfferStatus::Used { invoice_created_at: ref mut inv_created_at } | OfferStatus::Ready { invoice_created_at: ref mut inv_created_at } => { diff --git a/lightning/src/offers/flow.rs b/lightning/src/offers/flow.rs index 6c1b7a5befe..e1f1bb992ff 100644 --- a/lightning/src/offers/flow.rs +++ b/lightning/src/offers/flow.rs @@ -31,12 +31,12 @@ use crate::prelude::*; use crate::chain::BlockLocator; use crate::ln::channel_state::ChannelDetails; -use crate::ln::channelmanager::{InterceptId, PaymentId, CLTV_FAR_FAR_AWAY}; +use crate::ln::channelmanager::{CLTV_FAR_FAR_AWAY, InterceptId, PaymentId}; use crate::ln::inbound_payment; use crate::offers::async_receive_offer_cache::AsyncReceiveOfferCache; use crate::offers::invoice::{ - Bolt12Invoice, DerivedSigningPubkey, ExplicitSigningPubkey, InvoiceBuilder, - DEFAULT_RELATIVE_EXPIRY, + Bolt12Invoice, DEFAULT_RELATIVE_EXPIRY, DerivedSigningPubkey, ExplicitSigningPubkey, + InvoiceBuilder, }; use crate::offers::invoice_request::{ InvoiceRequest, InvoiceRequestBuilder, InvoiceRequestVerifiedFromOffer, VerifiedInvoiceRequest, @@ -51,7 +51,7 @@ use crate::onion_message::async_payments::{ StaticInvoicePersisted, }; use crate::onion_message::messenger::{ - Destination, MessageRouter, MessageSendInstructions, Responder, DUMMY_HOPS_PATH_LENGTH, + DUMMY_HOPS_PATH_LENGTH, Destination, MessageRouter, MessageSendInstructions, Responder, }; use crate::onion_message::offers::OffersMessage; use crate::onion_message::packet::OnionMessageContents; @@ -294,11 +294,7 @@ impl OffersMessageFlow { per_node_paths.retain(|node_paths| !node_paths.is_empty()); } - if res.is_empty() { - Err(()) - } else { - Ok(res) - } + if res.is_empty() { Err(()) } else { Ok(res) } } /// Creates a collection of blinded paths by delegating to @@ -1233,11 +1229,13 @@ impl OffersMessageFlow { MessageContext::AsyncPayments(AsyncPaymentsContext::OutboundPayment { payment_id, }); - self.create_blinded_paths(peers, context) - .map_err(|_| { - log_trace!(self.logger, "Failed to create blinded paths when enqueueing held_htlc_available message"); - Bolt12SemanticError::MissingPaths - })? + self.create_blinded_paths(peers, context).map_err(|_| { + log_trace!( + self.logger, + "Failed to create blinded paths when enqueueing held_htlc_available message" + ); + Bolt12SemanticError::MissingPaths + })? }, HeldHtlcReplyPath::ToCounterparty { path } => vec![path], }; diff --git a/lightning/src/offers/invoice.rs b/lightning/src/offers/invoice.rs index fd77595ca7d..a5c70578104 100644 --- a/lightning/src/offers/invoice.rs +++ b/lightning/src/offers/invoice.rs @@ -114,9 +114,9 @@ //! //! ``` +use crate::blinded_path::BlindedPath; use crate::blinded_path::message::BlindedMessagePath; use crate::blinded_path::payment::{BlindedPayInfo, BlindedPaymentPath}; -use crate::blinded_path::BlindedPath; use crate::io; use crate::ln::channelmanager::PaymentId; use crate::ln::inbound_payment::{ExpandedKey, IV_LEN}; @@ -125,24 +125,24 @@ use crate::ln::msgs::DecodeError; use crate::offers::invoice_macros::invoice_builder_methods_test_common; use crate::offers::invoice_macros::{invoice_accessors_common, invoice_builder_methods_common}; use crate::offers::invoice_request::{ - ExperimentalInvoiceRequestTlvStream, ExperimentalInvoiceRequestTlvStreamRef, InvoiceRequest, - InvoiceRequestContents, InvoiceRequestTlvStream, InvoiceRequestTlvStreamRef, - EXPERIMENTAL_INVOICE_REQUEST_TYPES, INVOICE_REQUEST_PAYER_ID_TYPE, INVOICE_REQUEST_TYPES, - IV_BYTES as INVOICE_REQUEST_IV_BYTES, + EXPERIMENTAL_INVOICE_REQUEST_TYPES, ExperimentalInvoiceRequestTlvStream, + ExperimentalInvoiceRequestTlvStreamRef, INVOICE_REQUEST_PAYER_ID_TYPE, INVOICE_REQUEST_TYPES, + IV_BYTES as INVOICE_REQUEST_IV_BYTES, InvoiceRequest, InvoiceRequestContents, + InvoiceRequestTlvStream, InvoiceRequestTlvStreamRef, }; use crate::offers::merkle::{ self, SignError, SignFn, SignatureTlvStream, SignatureTlvStreamRef, TaggedHash, TlvStream, }; use crate::offers::nonce::Nonce; use crate::offers::offer::{ - Amount, ExperimentalOfferTlvStream, ExperimentalOfferTlvStreamRef, OfferId, OfferTlvStream, - OfferTlvStreamRef, Quantity, EXPERIMENTAL_OFFER_TYPES, OFFER_TYPES, + Amount, EXPERIMENTAL_OFFER_TYPES, ExperimentalOfferTlvStream, ExperimentalOfferTlvStreamRef, + OFFER_TYPES, OfferId, OfferTlvStream, OfferTlvStreamRef, Quantity, }; use crate::offers::parse::{Bolt12ParseError, Bolt12SemanticError, ParsedMessage}; -use crate::offers::payer::{PayerTlvStream, PayerTlvStreamRef, PAYER_METADATA_TYPE}; +use crate::offers::payer::{PAYER_METADATA_TYPE, PayerTlvStream, PayerTlvStreamRef}; use crate::offers::refund::{ - Refund, RefundContents, IV_BYTES_WITHOUT_METADATA as REFUND_IV_BYTES_WITHOUT_METADATA, IV_BYTES_WITH_METADATA as REFUND_IV_BYTES_WITH_METADATA, + IV_BYTES_WITHOUT_METADATA as REFUND_IV_BYTES_WITHOUT_METADATA, Refund, RefundContents, }; use crate::offers::signer::{self, Metadata}; use crate::types::features::{Bolt12InvoiceFeatures, InvoiceRequestFeatures, OfferFeatures}; @@ -1824,9 +1824,9 @@ pub(super) fn check_invoice_signing_pubkey( #[cfg(test)] mod tests { use super::{ - Bolt12Invoice, ExperimentalInvoiceTlvStreamRef, FallbackAddress, FullInvoiceTlvStreamRef, - InvoiceTlvStreamRef, UnsignedBolt12Invoice, DEFAULT_RELATIVE_EXPIRY, - EXPERIMENTAL_INVOICE_TYPES, INVOICE_TYPES, SIGNATURE_TAG, + Bolt12Invoice, DEFAULT_RELATIVE_EXPIRY, EXPERIMENTAL_INVOICE_TYPES, + ExperimentalInvoiceTlvStreamRef, FallbackAddress, FullInvoiceTlvStreamRef, INVOICE_TYPES, + InvoiceTlvStreamRef, SIGNATURE_TAG, UnsignedBolt12Invoice, }; use bitcoin::address::Address; @@ -1839,8 +1839,8 @@ mod tests { use bitcoin::{CompressedPublicKey, WitnessProgram, WitnessVersion}; use core::time::Duration; - use crate::blinded_path::message::BlindedMessagePath; use crate::blinded_path::BlindedHop; + use crate::blinded_path::message::BlindedMessagePath; use crate::ln::channelmanager::PaymentId; use crate::ln::inbound_payment::ExpandedKey; use crate::ln::msgs::DecodeError; @@ -2285,9 +2285,9 @@ mod tests { } let expanded_key = ExpandedKey::new([41; 32]); - assert!(invoice_request - .verify_using_recipient_data(nonce, &expanded_key, &secp_ctx) - .is_err()); + assert!( + invoice_request.verify_using_recipient_data(nonce, &expanded_key, &secp_ctx).is_err() + ); } #[test] diff --git a/lightning/src/offers/invoice_request.rs b/lightning/src/offers/invoice_request.rs index 7805882ef73..1db78a9b3df 100644 --- a/lightning/src/offers/invoice_request.rs +++ b/lightning/src/offers/invoice_request.rs @@ -77,8 +77,8 @@ use crate::offers::merkle::{ }; use crate::offers::nonce::Nonce; use crate::offers::offer::{ - Amount, ExperimentalOfferTlvStream, ExperimentalOfferTlvStreamRef, Offer, OfferContents, - OfferId, OfferTlvStream, OfferTlvStreamRef, EXPERIMENTAL_OFFER_TYPES, OFFER_TYPES, + Amount, EXPERIMENTAL_OFFER_TYPES, ExperimentalOfferTlvStream, ExperimentalOfferTlvStreamRef, + OFFER_TYPES, Offer, OfferContents, OfferId, OfferTlvStream, OfferTlvStreamRef, }; use crate::offers::parse::{Bolt12ParseError, Bolt12SemanticError, ParsedMessage}; use crate::offers::payer::{PayerContents, PayerTlvStream, PayerTlvStreamRef}; @@ -1407,7 +1407,7 @@ impl TryFrom> for InvoiceRequest { None => { return Err(Bolt12ParseError::InvalidSemantics( Bolt12SemanticError::MissingSignature, - )) + )); }, Some(signature) => signature, }; @@ -1548,9 +1548,9 @@ impl Readable for InvoiceRequestFields { #[cfg(test)] mod tests { use super::{ - ExperimentalInvoiceRequestTlvStreamRef, InvoiceRequest, InvoiceRequestFields, - InvoiceRequestTlvStreamRef, UnsignedInvoiceRequest, EXPERIMENTAL_INVOICE_REQUEST_TYPES, - INVOICE_REQUEST_TYPES, PAYER_NOTE_LIMIT, SIGNATURE_TAG, + EXPERIMENTAL_INVOICE_REQUEST_TYPES, ExperimentalInvoiceRequestTlvStreamRef, + INVOICE_REQUEST_TYPES, InvoiceRequest, InvoiceRequestFields, InvoiceRequestTlvStreamRef, + PAYER_NOTE_LIMIT, SIGNATURE_TAG, UnsignedInvoiceRequest, }; use crate::ln::channelmanager::PaymentId; @@ -1624,12 +1624,14 @@ mod tests { let message = TaggedHash::from_valid_tlv_stream_bytes(SIGNATURE_TAG, &invoice_request.bytes); - assert!(merkle::verify_signature( - &invoice_request.signature, - &message, - invoice_request.payer_signing_pubkey(), - ) - .is_ok()); + assert!( + merkle::verify_signature( + &invoice_request.signature, + &message, + invoice_request.payer_signing_pubkey(), + ) + .is_ok() + ); assert_eq!( invoice_request.as_tlv_stream(), @@ -1736,9 +1738,9 @@ mod tests { .sign(recipient_sign) .unwrap(); assert!(invoice.verify_using_metadata(&expanded_key, &secp_ctx).is_err()); - assert!(invoice - .verify_using_payer_data(payment_id, nonce, &expanded_key, &secp_ctx) - .is_ok()); + assert!( + invoice.verify_using_payer_data(payment_id, nonce, &expanded_key, &secp_ctx).is_ok() + ); // Fails verification with altered fields let ( @@ -1774,9 +1776,9 @@ mod tests { .unwrap(); let invoice = Bolt12Invoice::try_from(encoded_invoice).unwrap(); - assert!(invoice - .verify_using_payer_data(payment_id, nonce, &expanded_key, &secp_ctx) - .is_err()); + assert!( + invoice.verify_using_payer_data(payment_id, nonce, &expanded_key, &secp_ctx).is_err() + ); // Fails verification with altered payer id let ( @@ -1812,9 +1814,9 @@ mod tests { .unwrap(); let invoice = Bolt12Invoice::try_from(encoded_invoice).unwrap(); - assert!(invoice - .verify_using_payer_data(payment_id, nonce, &expanded_key, &secp_ctx) - .is_err()); + assert!( + invoice.verify_using_payer_data(payment_id, nonce, &expanded_key, &secp_ctx).is_err() + ); } #[test] diff --git a/lightning/src/offers/merkle.rs b/lightning/src/offers/merkle.rs index 1a38fe5441f..95932660149 100644 --- a/lightning/src/offers/merkle.rs +++ b/lightning/src/offers/merkle.rs @@ -11,7 +11,7 @@ use crate::io; use crate::util::ser::{BigSize, Readable, Writeable, Writer}; -use bitcoin::hashes::{sha256, Hash, HashEngine}; +use bitcoin::hashes::{Hash, HashEngine, sha256}; use bitcoin::secp256k1::schnorr::Signature; use bitcoin::secp256k1::{self, Message, PublicKey, Secp256k1}; @@ -282,7 +282,7 @@ impl<'a> Writeable for TlvRecord<'a> { #[cfg(test)] mod tests { - use super::{TlvStream, SIGNATURE_TYPES}; + use super::{SIGNATURE_TYPES, TlvStream}; use crate::ln::channelmanager::PaymentId; use crate::ln::inbound_payment::ExpandedKey; @@ -293,7 +293,7 @@ mod tests { use crate::offers::signer::Metadata; use crate::offers::test_utils::recipient_pubkey; use crate::util::ser::Writeable; - use bitcoin::hashes::{sha256, Hash}; + use bitcoin::hashes::{Hash, sha256}; use bitcoin::hex::FromHex; use bitcoin::secp256k1::schnorr::Signature; use bitcoin::secp256k1::{Keypair, Message, Secp256k1, SecretKey}; @@ -319,7 +319,11 @@ mod tests { sha256::Hash::from_slice(&bytes_2).unwrap(), ); - const HEX_3: &'static str = concat!("010203e8","02080000010000020003", "03310266e4598d1d3c415f572a8488830b60f7e744ed9235eb0b1ba93283b315c0351800000000000000010000000000000002"); + const HEX_3: &'static str = concat!( + "010203e8", + "02080000010000020003", + "03310266e4598d1d3c415f572a8488830b60f7e744ed9235eb0b1ba93283b315c0351800000000000000010000000000000002" + ); let bytes_3 = >::from_hex("ab2e79b1283b0b31e0b035258de23782df6b89a38cfa7237bde69aed1a658c5d") .unwrap(); diff --git a/lightning/src/offers/offer.rs b/lightning/src/offers/offer.rs index b2703454169..e5d22dd824e 100644 --- a/lightning/src/offers/offer.rs +++ b/lightning/src/offers/offer.rs @@ -1052,13 +1052,8 @@ impl OfferContents { }, }; - let features = { - if self.features == OfferFeatures::empty() { - None - } else { - Some(&self.features) - } - }; + let features = + { if self.features == OfferFeatures::empty() { None } else { Some(&self.features) } }; let offer = OfferTlvStreamRef { chains: self.chains.as_ref(), @@ -1337,7 +1332,7 @@ impl TryFrom for OfferContents { let (issuer_signing_pubkey, paths) = match (issuer_id, paths) { (None, None) => return Err(Bolt12SemanticError::MissingIssuerSigningPubkey), (None, Some(paths)) if paths.is_empty() => { - return Err(Bolt12SemanticError::MissingPaths) + return Err(Bolt12SemanticError::MissingPaths); }, (issuer_id, paths) => (issuer_id, paths), }; @@ -1386,12 +1381,12 @@ mod tests { #[cfg(c_bindings)] use super::OfferWithExplicitMetadataBuilder as OfferBuilder; use super::{ - Amount, ExperimentalOfferTlvStreamRef, Offer, OfferTlvStreamRef, Quantity, - EXPERIMENTAL_OFFER_TYPES, OFFER_TYPES, + Amount, EXPERIMENTAL_OFFER_TYPES, ExperimentalOfferTlvStreamRef, OFFER_TYPES, Offer, + OfferTlvStreamRef, Quantity, }; - use crate::blinded_path::message::BlindedMessagePath; use crate::blinded_path::BlindedHop; + use crate::blinded_path::message::BlindedMessagePath; use crate::ln::channelmanager::PaymentId; use crate::ln::inbound_payment::ExpandedKey; use crate::ln::msgs::{DecodeError, MAX_VALUE_MSAT}; @@ -1543,9 +1538,9 @@ mod tests { .unwrap() .build_and_sign() .unwrap(); - assert!(invoice_request - .verify_using_recipient_data(nonce, &expanded_key, &secp_ctx) - .is_err()); + assert!( + invoice_request.verify_using_recipient_data(nonce, &expanded_key, &secp_ctx).is_err() + ); // Fails verification with altered offer field let mut tlv_stream = offer.as_tlv_stream(); @@ -1639,9 +1634,9 @@ mod tests { .unwrap() .build_and_sign() .unwrap(); - assert!(invoice_request - .verify_using_recipient_data(nonce, &expanded_key, &secp_ctx) - .is_err()); + assert!( + invoice_request.verify_using_recipient_data(nonce, &expanded_key, &secp_ctx).is_err() + ); // Fails verification with altered signing pubkey let mut tlv_stream = offer.as_tlv_stream(); @@ -1657,9 +1652,9 @@ mod tests { .unwrap() .build_and_sign() .unwrap(); - assert!(invoice_request - .verify_using_recipient_data(nonce, &expanded_key, &secp_ctx) - .is_err()); + assert!( + invoice_request.verify_using_recipient_data(nonce, &expanded_key, &secp_ctx).is_err() + ); } #[test] @@ -2344,58 +2339,40 @@ mod bolt12_tests { "lno1zcss9mk8y3wkklfvevcrszlmu23kfrxh49px20665dqwmn4p72pksese", // with description (but no amount) "lno1pgx9getnwss8vetrw3hhyuckyypwa3eyt44h6txtxquqh7lz5djge4afgfjn7k4rgrkuag0jsd5xvxg", - // for testnet "lno1qgsyxjtl6luzd9t3pr62xr7eemp6awnejusgf6gw45q75vcfqqqqqqq2p32x2um5ypmx2cm5dae8x93pqthvwfzadd7jejes8q9lhc4rvjxd022zv5l44g6qah82ru5rdpnpj", - // for bitcoin (redundant) "lno1qgsxlc5vp2m0rvmjcxn2y34wv0m5lyc7sdj7zksgn35dvxgqqqqqqqq2p32x2um5ypmx2cm5dae8x93pqthvwfzadd7jejes8q9lhc4rvjxd022zv5l44g6qah82ru5rdpnpj", - // for bitcoin or liquidv1 "lno1qfqpge38tqmzyrdjj3x2qkdr5y80dlfw56ztq6yd9sme995g3gsxqqm0u2xq4dh3kdevrf4zg6hx8a60jv0gxe0ptgyfc6xkryqqqqqqqq9qc4r9wd6zqan9vd6x7unnzcss9mk8y3wkklfvevcrszlmu23kfrxh49px20665dqwmn4p72pksese", - // with metadata "lno1qsgqqqqqqqqqqqqqqqqqqqqqqqqqqzsv23jhxapqwejkxar0wfe3vggzamrjghtt05kvkvpcp0a79gmy3nt6jsn98ad2xs8de6sl9qmgvcvs", - // with amount "lno1pqpzwyq2p32x2um5ypmx2cm5dae8x93pqthvwfzadd7jejes8q9lhc4rvjxd022zv5l44g6qah82ru5rdpnpj", - // with currency "lno1qcp4256ypqpzwyq2p32x2um5ypmx2cm5dae8x93pqthvwfzadd7jejes8q9lhc4rvjxd022zv5l44g6qah82ru5rdpnpj", - // with expiry "lno1pgx9getnwss8vetrw3hhyucwq3ay997czcss9mk8y3wkklfvevcrszlmu23kfrxh49px20665dqwmn4p72pksese", - // with issuer "lno1pgx9getnwss8vetrw3hhyucjy358garswvaz7tmzdak8gvfj9ehhyeeqgf85c4p3xgsxjmnyw4ehgunfv4e3vggzamrjghtt05kvkvpcp0a79gmy3nt6jsn98ad2xs8de6sl9qmgvcvs", - // with quantity "lno1pgx9getnwss8vetrw3hhyuc5qyz3vggzamrjghtt05kvkvpcp0a79gmy3nt6jsn98ad2xs8de6sl9qmgvcvs", - // with unlimited (or unknown) quantity "lno1pgx9getnwss8vetrw3hhyuc5qqtzzqhwcuj966ma9n9nqwqtl032xeyv6755yeflt235pmww58egx6rxry", - // with single quantity (weird but valid) "lno1pgx9getnwss8vetrw3hhyuc5qyq3vggzamrjghtt05kvkvpcp0a79gmy3nt6jsn98ad2xs8de6sl9qmgvcvs", - // with feature "lno1pgx9getnwss8vetrw3hhyucvp5yqqqqqqqqqqqqqqqqqqqqkyypwa3eyt44h6txtxquqh7lz5djge4afgfjn7k4rgrkuag0jsd5xvxg", - // with blinded path via Bob (0x424242...), blinding 020202... "lno1pgx9getnwss8vetrw3hhyucs5ypjgef743p5fzqq9nqxh0ah7y87rzv3ud0eleps9kl2d5348hq2k8qzqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgqpqqqqqqqqqqqqqqqqqqqqqqqqqqqzqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqqzq3zyg3zyg3zyg3vggzamrjghtt05kvkvpcp0a79gmy3nt6jsn98ad2xs8de6sl9qmgvcvs", - // ... and with sciddir introduction node "lno1pgx9getnwss8vetrw3hhyucs3yqqqqqqqqqqqqp2qgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqqyqqqqqqqqqqqqqqqqqqqqqqqqqqqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqqgzyg3zyg3zyg3z93pqthvwfzadd7jejes8q9lhc4rvjxd022zv5l44g6qah82ru5rdpnpj", - // with no issuer_id and blinded path via Bob (0x424242...), blinding 020202... "lno1pgx9getnwss8vetrw3hhyucs5ypjgef743p5fzqq9nqxh0ah7y87rzv3ud0eleps9kl2d5348hq2k8qzqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgqpqqqqqqqqqqqqqqqqqqqqqqqqqqqzqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqqzq3zyg3zyg3zygs", - //... and with second blinded path via 1x2x3 (direction 1), blinding 020202... "lno1pgx9getnwss8vetrw3hhyucsl5qj5qeyv5l2cs6y3qqzesrth7mlzrlp3xg7xhulusczm04x6g6nms9trspqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqqsqqqqqqqqqqqqqqqqqqqqqqqqqqpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsqpqg3zyg3zyg3zygpqqqqzqqqqgqqxqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqqgqqqqqqqqqqqqqqqqqqqqqqqqqqqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgqqsg3zyg3zyg3zygtzzqhwcuj966ma9n9nqwqtl032xeyv6755yeflt235pmww58egx6rxry", - // unknown odd field "lno1pgx9getnwss8vetrw3hhyuckyypwa3eyt44h6txtxquqh7lz5djge4afgfjn7k4rgrkuag0jsd5xvxfppf5x2mrvdamk7unvvs", - // unknown odd experimental field "lno1pgx9getnwss8vetrw3hhyuckyypwa3eyt44h6txtxquqh7lz5djge4afgfjn7k4rgrkuag0jsd5xvx078wdv5gg2dpjkcmr0wahhymry", ]; diff --git a/lightning/src/offers/parse.rs b/lightning/src/offers/parse.rs index df71e860d2d..53892ea285f 100644 --- a/lightning/src/offers/parse.rs +++ b/lightning/src/offers/parse.rs @@ -27,7 +27,7 @@ pub use sealed::Bech32Encode; mod sealed { use super::Bolt12ParseError; use bech32::primitives::decode::CheckedHrpstring; - use bech32::{encode_to_fmt, EncodeError, Hrp, NoChecksum}; + use bech32::{EncodeError, Hrp, NoChecksum, encode_to_fmt}; use core::fmt; #[allow(unused_imports)] @@ -285,16 +285,12 @@ mod bolt12_tests { let offers = [ // A complete string is valid "lno1pqps7sjqpgtyzm3qv4uxzmtsd3jjqer9wd3hy6tsw35k7msjzfpy7nz5yqcnygrfdej82um5wf5k2uckyypwa3eyt44h6txtxquqh7lz5djge4afgfjn7k4rgrkuag0jsd5xvxg", - // Uppercase is valid "LNO1PQPS7SJQPGTYZM3QV4UXZMTSD3JJQER9WD3HY6TSW35K7MSJZFPY7NZ5YQCNYGRFDEJ82UM5WF5K2UCKYYPWA3EYT44H6TXTXQUQH7LZ5DJGE4AFGFJN7K4RGRKUAG0JSD5XVXG", - // + can join anywhere "l+no1pqps7sjqpgtyzm3qv4uxzmtsd3jjqer9wd3hy6tsw35k7msjzfpy7nz5yqcnygrfdej82um5wf5k2uckyypwa3eyt44h6txtxquqh7lz5djge4afgfjn7k4rgrkuag0jsd5xvxg", - // Multiple + can join "lno1pqps7sjqpgt+yzm3qv4uxzmtsd3jjqer9wd3hy6tsw3+5k7msjzfpy7nz5yqcn+ygrfdej82um5wf5k2uckyypwa3eyt44h6txtxquqh7lz5djge4afgfjn7k4rgrkuag0jsd+5xvxg", - // + can be followed by whitespace "lno1pqps7sjqpgt+ yzm3qv4uxzmtsd3jjqer9wd3hy6tsw3+ 5k7msjzfpy7nz5yqcn+\nygrfdej82um5wf5k2uckyypwa3eyt44h6txtxquqh7lz5djge4afgfjn7k4rgrkuag0jsd+\r\n 5xvxg", ]; diff --git a/lightning/src/offers/refund.rs b/lightning/src/offers/refund.rs index c0fd9dfdd3e..f782e0a744a 100644 --- a/lightning/src/offers/refund.rs +++ b/lightning/src/offers/refund.rs @@ -1032,14 +1032,14 @@ mod tests { use core::time::Duration; - use crate::blinded_path::message::BlindedMessagePath; use crate::blinded_path::BlindedHop; + use crate::blinded_path::message::BlindedMessagePath; use crate::ln::channelmanager::PaymentId; use crate::ln::inbound_payment::ExpandedKey; use crate::ln::msgs::{DecodeError, MAX_VALUE_MSAT}; use crate::offers::invoice_request::{ - ExperimentalInvoiceRequestTlvStreamRef, InvoiceRequestTlvStreamRef, - EXPERIMENTAL_INVOICE_REQUEST_TYPES, INVOICE_REQUEST_TYPES, + EXPERIMENTAL_INVOICE_REQUEST_TYPES, ExperimentalInvoiceRequestTlvStreamRef, + INVOICE_REQUEST_TYPES, InvoiceRequestTlvStreamRef, }; use crate::offers::nonce::Nonce; use crate::offers::offer::{ExperimentalOfferTlvStreamRef, OfferTlvStreamRef}; @@ -1167,9 +1167,9 @@ mod tests { Ok(payment_id) => assert_eq!(payment_id, PaymentId([1; 32])), Err(()) => panic!("verification failed"), } - assert!(invoice - .verify_using_payer_data(payment_id, nonce, &expanded_key, &secp_ctx) - .is_err()); + assert!( + invoice.verify_using_payer_data(payment_id, nonce, &expanded_key, &secp_ctx).is_err() + ); let mut tlv_stream = refund.as_tlv_stream(); tlv_stream.2.amount = Some(2000); @@ -1249,9 +1249,9 @@ mod tests { .sign(recipient_sign) .unwrap(); assert!(invoice.verify_using_metadata(&expanded_key, &secp_ctx).is_err()); - assert!(invoice - .verify_using_payer_data(payment_id, nonce, &expanded_key, &secp_ctx) - .is_ok()); + assert!( + invoice.verify_using_payer_data(payment_id, nonce, &expanded_key, &secp_ctx).is_ok() + ); // Fails verification with altered fields let mut tlv_stream = refund.as_tlv_stream(); @@ -1268,9 +1268,9 @@ mod tests { .unwrap() .sign(recipient_sign) .unwrap(); - assert!(invoice - .verify_using_payer_data(payment_id, nonce, &expanded_key, &secp_ctx) - .is_err()); + assert!( + invoice.verify_using_payer_data(payment_id, nonce, &expanded_key, &secp_ctx).is_err() + ); // Fails verification with altered payer_id let mut tlv_stream = refund.as_tlv_stream(); @@ -1288,9 +1288,9 @@ mod tests { .unwrap() .sign(recipient_sign) .unwrap(); - assert!(invoice - .verify_using_payer_data(payment_id, nonce, &expanded_key, &secp_ctx) - .is_err()); + assert!( + invoice.verify_using_payer_data(payment_id, nonce, &expanded_key, &secp_ctx).is_err() + ); } #[test] diff --git a/lightning/src/offers/signer.rs b/lightning/src/offers/signer.rs index e51a120b6d7..b39f3cc1cab 100644 --- a/lightning/src/offers/signer.rs +++ b/lightning/src/offers/signer.rs @@ -393,11 +393,7 @@ fn verify_metadata( if metadata[0] & 1 == 0 { ok = true; } - if ok { - Ok(Some(derived_keys)) - } else { - Err(()) - } + if ok { Ok(Some(derived_keys)) } else { Err(()) } } else { #[allow(unused_mut)] let mut ok = metadata.len() == Nonce::LENGTH + Sha256::LEN @@ -406,11 +402,7 @@ fn verify_metadata( if metadata.is_empty() || metadata[0] & 1 == 0 { ok = true; } - if ok { - Ok(None) - } else { - Err(()) - } + if ok { Ok(None) } else { Err(()) } } } diff --git a/lightning/src/offers/static_invoice.rs b/lightning/src/offers/static_invoice.rs index 860835912a1..166ca8942e7 100644 --- a/lightning/src/offers/static_invoice.rs +++ b/lightning/src/offers/static_invoice.rs @@ -15,9 +15,9 @@ use crate::io; use crate::ln::inbound_payment::ExpandedKey; use crate::ln::msgs::DecodeError; use crate::offers::invoice::{ - check_invoice_signing_pubkey, construct_payment_paths, filter_fallbacks, ExperimentalInvoiceTlvStream, ExperimentalInvoiceTlvStreamRef, FallbackAddress, - InvoiceTlvStream, InvoiceTlvStreamRef, + InvoiceTlvStream, InvoiceTlvStreamRef, check_invoice_signing_pubkey, construct_payment_paths, + filter_fallbacks, }; #[cfg(test)] use crate::offers::invoice_macros::invoice_builder_methods_test_common; @@ -28,8 +28,8 @@ use crate::offers::merkle::{ }; use crate::offers::nonce::Nonce; use crate::offers::offer::{ - Amount, ExperimentalOfferTlvStream, ExperimentalOfferTlvStreamRef, Offer, OfferContents, - OfferId, OfferTlvStream, OfferTlvStreamRef, Quantity, EXPERIMENTAL_OFFER_TYPES, OFFER_TYPES, + Amount, EXPERIMENTAL_OFFER_TYPES, ExperimentalOfferTlvStream, ExperimentalOfferTlvStreamRef, + OFFER_TYPES, Offer, OfferContents, OfferId, OfferTlvStream, OfferTlvStreamRef, Quantity, }; use crate::offers::parse::{Bolt12ParseError, Bolt12SemanticError, ParsedMessage}; use crate::types::features::{Bolt12InvoiceFeatures, OfferFeatures}; @@ -652,7 +652,7 @@ impl TryFrom> for StaticInvoice { None => { return Err(Bolt12ParseError::InvalidSemantics( Bolt12SemanticError::MissingSignature, - )) + )); }, Some(signature) => signature, }; @@ -737,13 +737,13 @@ impl TryFrom for InvoiceContents { #[cfg(test)] mod tests { - use crate::blinded_path::message::BlindedMessagePath; use crate::blinded_path::BlindedHop; + use crate::blinded_path::message::BlindedMessagePath; use crate::ln::inbound_payment::ExpandedKey; use crate::ln::msgs::DecodeError; use crate::offers::invoice::{ - ExperimentalInvoiceTlvStreamRef, InvoiceTlvStreamRef, EXPERIMENTAL_INVOICE_TYPES, - INVOICE_TYPES, + EXPERIMENTAL_INVOICE_TYPES, ExperimentalInvoiceTlvStreamRef, INVOICE_TYPES, + InvoiceTlvStreamRef, }; use crate::offers::merkle; use crate::offers::merkle::{SignatureTlvStreamRef, TaggedHash, TlvStream}; @@ -753,15 +753,15 @@ mod tests { }; use crate::offers::parse::{Bolt12ParseError, Bolt12SemanticError}; use crate::offers::static_invoice::{ - StaticInvoice, StaticInvoiceBuilder, UnsignedStaticInvoice, DEFAULT_RELATIVE_EXPIRY, - SIGNATURE_TAG, + DEFAULT_RELATIVE_EXPIRY, SIGNATURE_TAG, StaticInvoice, StaticInvoiceBuilder, + UnsignedStaticInvoice, }; use crate::offers::test_utils::*; use crate::types::features::{Bolt12InvoiceFeatures, OfferFeatures}; use crate::util::ser::{BigSize, Iterable, Writeable}; + use bitcoin::Network; use bitcoin::constants::ChainHash; use bitcoin::secp256k1::{self, Secp256k1}; - use bitcoin::Network; use core::time::Duration; type FullInvoiceTlvStreamRef<'a> = ( diff --git a/lightning/src/offers/test_utils.rs b/lightning/src/offers/test_utils.rs index d0decdf2c38..be2ccd25f93 100644 --- a/lightning/src/offers/test_utils.rs +++ b/lightning/src/offers/test_utils.rs @@ -12,9 +12,9 @@ use bitcoin::secp256k1::schnorr::Signature; use bitcoin::secp256k1::{Keypair, PublicKey, Secp256k1, SecretKey}; +use crate::blinded_path::BlindedHop; use crate::blinded_path::message::BlindedMessagePath; use crate::blinded_path::payment::{BlindedPayInfo, BlindedPaymentPath}; -use crate::blinded_path::BlindedHop; use crate::ln::inbound_payment::ExpandedKey; use crate::offers::merkle::TaggedHash; use crate::sign::EntropySource; diff --git a/lightning/src/onion_message/functional_tests.rs b/lightning/src/onion_message/functional_tests.rs index 75e2aaf3c5f..8a3169f8efd 100644 --- a/lightning/src/onion_message/functional_tests.rs +++ b/lightning/src/onion_message/functional_tests.rs @@ -22,12 +22,12 @@ use super::messenger::{ }; use super::offers::{OffersMessage, OffersMessageHandler}; use super::packet::{OnionMessageContents, Packet}; +use crate::blinded_path::EmptyNodeIdLookUp; use crate::blinded_path::message::{ - AsyncPaymentsContext, BlindedMessagePath, DNSResolverContext, MessageContext, - MessageForwardNode, OffersContext, MESSAGE_PADDING_ROUND_OFF, + AsyncPaymentsContext, BlindedMessagePath, DNSResolverContext, MESSAGE_PADDING_ROUND_OFF, + MessageContext, MessageForwardNode, OffersContext, }; use crate::blinded_path::utils::is_padded; -use crate::blinded_path::EmptyNodeIdLookUp; use crate::events::{Event, EventsProvider}; use crate::ln::msgs::{self, BaseMessageHandler, DecodeError, OnionMessageHandler}; use crate::routing::gossip::{NetworkGraph, P2PGossipSync}; diff --git a/lightning/src/onion_message/messenger.rs b/lightning/src/onion_message/messenger.rs index 7ef4e4a66a8..4a3035e5a3f 100644 --- a/lightning/src/onion_message/messenger.rs +++ b/lightning/src/onion_message/messenger.rs @@ -21,7 +21,7 @@ use super::offers::{OffersMessage, OffersMessageHandler}; use super::packet::OnionMessageContents; use super::packet::ParsedOnionMessageContents; use super::packet::{ - ForwardControlTlvs, Packet, Payload, ReceiveControlTlvs, BIG_PACKET_HOP_DATA_LEN, + BIG_PACKET_HOP_DATA_LEN, ForwardControlTlvs, Packet, Payload, ReceiveControlTlvs, SMALL_PACKET_HOP_DATA_LEN, }; use crate::blinded_path::message::{ @@ -100,16 +100,16 @@ pub trait AOnionMessenger { } impl< - ES: EntropySource, - NS: NodeSigner, - L: Logger, - NL: NodeIdLookUp, - MR: MessageRouter, - OMH: OffersMessageHandler, - APH: AsyncPaymentsMessageHandler, - DRH: DNSResolverMessageHandler, - CMH: CustomOnionMessageHandler, - > AOnionMessenger for OnionMessenger + ES: EntropySource, + NS: NodeSigner, + L: Logger, + NL: NodeIdLookUp, + MR: MessageRouter, + OMH: OffersMessageHandler, + APH: AsyncPaymentsMessageHandler, + DRH: DNSResolverMessageHandler, + CMH: CustomOnionMessageHandler, +> AOnionMessenger for OnionMessenger { type EntropySource = ES; type NodeSigner = NS; @@ -1327,7 +1327,10 @@ pub fn peel_onion_message { - log_trace!(logger, "Received bogus onion message packet, either the sender encoded a final hop as a forwarding hop or vice versa"); + log_trace!( + logger, + "Received bogus onion message packet, either the sender encoded a final hop as a forwarding hop or vice versa" + ); Err(()) }, } @@ -1363,16 +1366,16 @@ macro_rules! drop_handled_events_and_abort { } impl< - ES: EntropySource, - NS: NodeSigner, - L: Logger, - NL: NodeIdLookUp, - MR: MessageRouter, - OMH: OffersMessageHandler, - APH: AsyncPaymentsMessageHandler, - DRH: DNSResolverMessageHandler, - CMH: CustomOnionMessageHandler, - > OnionMessenger + ES: EntropySource, + NS: NodeSigner, + L: Logger, + NL: NodeIdLookUp, + MR: MessageRouter, + OMH: OffersMessageHandler, + APH: AsyncPaymentsMessageHandler, + DRH: DNSResolverMessageHandler, + CMH: CustomOnionMessageHandler, +> OnionMessenger { /// Constructs a new `OnionMessenger` to send, forward, and delegate received onion messages to /// their respective handlers. @@ -1664,7 +1667,12 @@ impl< NextMessageHop::ShortChannelId(scid) => match self.node_id_lookup.next_node_id(scid) { Some(pubkey) => pubkey, None => { - log_trace!(self.logger, "Dropping forwarded onion messager: unable to resolve next hop using SCID {} {}", scid, log_suffix); + log_trace!( + self.logger, + "Dropping forwarded onion messager: unable to resolve next hop using SCID {} {}", + scid, + log_suffix + ); return Err(SendError::GetNodeIdFailed); }, }, @@ -1877,7 +1885,7 @@ impl< /// /// See the trait-level documentation of [`EventsProvider`] for requirements. pub async fn process_pending_events_async< - Future: core::future::Future> + core::marker::Unpin, + Future: core::future::Future>, H: Fn(Event) -> Future, >( &self, handler: H, @@ -1997,16 +2005,16 @@ fn outbound_buffer_full( } impl< - ES: EntropySource, - NS: NodeSigner, - L: Logger, - NL: NodeIdLookUp, - MR: MessageRouter, - OMH: OffersMessageHandler, - APH: AsyncPaymentsMessageHandler, - DRH: DNSResolverMessageHandler, - CMH: CustomOnionMessageHandler, - > EventsProvider for OnionMessenger + ES: EntropySource, + NS: NodeSigner, + L: Logger, + NL: NodeIdLookUp, + MR: MessageRouter, + OMH: OffersMessageHandler, + APH: AsyncPaymentsMessageHandler, + DRH: DNSResolverMessageHandler, + CMH: CustomOnionMessageHandler, +> EventsProvider for OnionMessenger { fn process_pending_events(&self, handler: H) where @@ -2108,16 +2116,16 @@ impl< } impl< - ES: EntropySource, - NS: NodeSigner, - L: Logger, - NL: NodeIdLookUp, - MR: MessageRouter, - OMH: OffersMessageHandler, - APH: AsyncPaymentsMessageHandler, - DRH: DNSResolverMessageHandler, - CMH: CustomOnionMessageHandler, - > BaseMessageHandler for OnionMessenger + ES: EntropySource, + NS: NodeSigner, + L: Logger, + NL: NodeIdLookUp, + MR: MessageRouter, + OMH: OffersMessageHandler, + APH: AsyncPaymentsMessageHandler, + DRH: DNSResolverMessageHandler, + CMH: CustomOnionMessageHandler, +> BaseMessageHandler for OnionMessenger { fn provided_node_features(&self) -> NodeFeatures { let mut features = NodeFeatures::empty(); @@ -2170,16 +2178,16 @@ impl< } impl< - ES: EntropySource, - NS: NodeSigner, - L: Logger, - NL: NodeIdLookUp, - MR: MessageRouter, - OMH: OffersMessageHandler, - APH: AsyncPaymentsMessageHandler, - DRH: DNSResolverMessageHandler, - CMH: CustomOnionMessageHandler, - > OnionMessageHandler for OnionMessenger + ES: EntropySource, + NS: NodeSigner, + L: Logger, + NL: NodeIdLookUp, + MR: MessageRouter, + OMH: OffersMessageHandler, + APH: AsyncPaymentsMessageHandler, + DRH: DNSResolverMessageHandler, + CMH: CustomOnionMessageHandler, +> OnionMessageHandler for OnionMessenger { fn handle_onion_message(&self, peer_node_id: PublicKey, msg: &OnionMessage) { let logger = WithContext::from(&self.logger, Some(peer_node_id), None, None); diff --git a/lightning/src/onion_message/packet.rs b/lightning/src/onion_message/packet.rs index cd9a923b070..c28690911ec 100644 --- a/lightning/src/onion_message/packet.rs +++ b/lightning/src/onion_message/packet.rs @@ -9,8 +9,8 @@ //! Structs and enums useful for constructing and reading an onion message packet. -use bitcoin::secp256k1::ecdh::SharedSecret; use bitcoin::secp256k1::PublicKey; +use bitcoin::secp256k1::ecdh::SharedSecret; use super::async_payments::AsyncPaymentsMessage; use super::dns_resolution::DNSResolverMessage; @@ -168,19 +168,19 @@ impl OnionMessageContents for ParsedOnionMessageContent #[cfg(c_bindings)] fn msg_type(&self) -> String { match self { - ParsedOnionMessageContents::Offers(ref msg) => msg.msg_type(), - ParsedOnionMessageContents::AsyncPayments(ref msg) => msg.msg_type(), - ParsedOnionMessageContents::DNSResolver(ref msg) => msg.msg_type(), - ParsedOnionMessageContents::Custom(ref msg) => msg.msg_type(), + ParsedOnionMessageContents::Offers(msg) => msg.msg_type(), + ParsedOnionMessageContents::AsyncPayments(msg) => msg.msg_type(), + ParsedOnionMessageContents::DNSResolver(msg) => msg.msg_type(), + ParsedOnionMessageContents::Custom(msg) => msg.msg_type(), } } #[cfg(not(c_bindings))] fn msg_type(&self) -> &'static str { match self { - ParsedOnionMessageContents::Offers(ref msg) => msg.msg_type(), - ParsedOnionMessageContents::AsyncPayments(ref msg) => msg.msg_type(), - ParsedOnionMessageContents::DNSResolver(ref msg) => msg.msg_type(), - ParsedOnionMessageContents::Custom(ref msg) => msg.msg_type(), + ParsedOnionMessageContents::Offers(msg) => msg.msg_type(), + ParsedOnionMessageContents::AsyncPayments(msg) => msg.msg_type(), + ParsedOnionMessageContents::DNSResolver(msg) => msg.msg_type(), + ParsedOnionMessageContents::Custom(msg) => msg.msg_type(), } } } diff --git a/lightning/src/routing/gossip.rs b/lightning/src/routing/gossip.rs index adeb67a9e6c..c71aeff4a7e 100644 --- a/lightning/src/routing/gossip.rs +++ b/lightning/src/routing/gossip.rs @@ -13,12 +13,12 @@ use bitcoin::amount::Amount; use bitcoin::constants::ChainHash; use bitcoin::secp256k1; -use bitcoin::secp256k1::constants::PUBLIC_KEY_SIZE; use bitcoin::secp256k1::Secp256k1; +use bitcoin::secp256k1::constants::PUBLIC_KEY_SIZE; use bitcoin::secp256k1::{PublicKey, Verification}; -use bitcoin::hashes::sha256d::Hash as Sha256dHash; use bitcoin::hashes::Hash; +use bitcoin::hashes::sha256d::Hash as Sha256dHash; use bitcoin::network::Network; use crate::ln::msgs; @@ -26,8 +26,8 @@ use crate::ln::msgs::{ BaseMessageHandler, ChannelAnnouncement, ChannelUpdate, GossipTimestampFilter, NodeAnnouncement, }; use crate::ln::msgs::{ - DecodeError, ErrorAction, Init, LightningError, RoutingMessageHandler, SocketAddress, - MAX_VALUE_MSAT, + DecodeError, ErrorAction, Init, LightningError, MAX_VALUE_MSAT, RoutingMessageHandler, + SocketAddress, }; use crate::ln::msgs::{ MessageSendEvent, QueryChannelRange, QueryShortChannelIds, ReplyChannelRange, @@ -41,7 +41,7 @@ use crate::util::indexed_map::{ Entry as IndexedMapEntry, IndexedMap, OccupiedEntry as IndexedMapOccupiedEntry, }; use crate::util::logger::{Level, Logger}; -use crate::util::scid_utils::{block_from_scid, scid_from_parts, MAX_SCID_BLOCK}; +use crate::util::scid_utils::{MAX_SCID_BLOCK, block_from_scid, scid_from_parts}; use crate::util::ser::{MaybeReadable, Readable, ReadableArgs, RequiredWrapper, Writeable, Writer}; use crate::util::wakers::Future; @@ -384,7 +384,7 @@ impl>, U: UtxoLookup, L: Logger> P2PGossipSync pending_events.reserve(msgs.len()); for mut message in msgs { match &mut message { - MessageSendEvent::BroadcastChannelAnnouncement { msg, ref mut update_msg } => { + MessageSendEvent::BroadcastChannelAnnouncement { msg, update_msg } => { if msg.contents.excess_data.len() > MAX_EXCESS_BYTES_FOR_RELAY { continue; } @@ -1098,11 +1098,7 @@ impl ChannelInfo { /// Returns a [`ChannelUpdateInfo`] based on the direction implied by the channel_flag. pub fn get_directional_info(&self, channel_flags: u8) -> Option<&ChannelUpdateInfo> { let direction = channel_flags & 1u8; - if direction == 0 { - self.one_to_two.as_ref() - } else { - self.two_to_one.as_ref() - } + if direction == 0 { self.one_to_two.as_ref() } else { self.two_to_one.as_ref() } } } @@ -1256,11 +1252,7 @@ impl<'a> DirectedChannelInfo<'a> { /// Refers to the `node_id` forwarding the payment to the next hop. #[inline] pub fn source(&self) -> &'a NodeId { - if self.from_node_one { - &self.channel.node_one - } else { - &self.channel.node_two - } + if self.from_node_one { &self.channel.node_one } else { &self.channel.node_two } } /// Returns the `node_id` of the target hop. @@ -1268,11 +1260,7 @@ impl<'a> DirectedChannelInfo<'a> { /// Refers to the `node_id` receiving the payment from the previous hop. #[inline] pub fn target(&self) -> &'a NodeId { - if self.from_node_one { - &self.channel.node_two - } else { - &self.channel.node_one - } + if self.from_node_one { &self.channel.node_two } else { &self.channel.node_one } } /// Returns the source node's counter @@ -2184,9 +2172,13 @@ impl NetworkGraph { || removed_nodes.contains_key(&msg.node_id_1) || removed_nodes.contains_key(&msg.node_id_2) { - return Err(LightningError{ - err: format!("Channel with SCID {} or one of its nodes was removed from our network graph recently", &msg.short_channel_id), - action: ErrorAction::IgnoreAndLog(Level::Gossip)}); + return Err(LightningError { + err: format!( + "Channel with SCID {} or one of its nodes was removed from our network graph recently", + &msg.short_channel_id + ), + action: ErrorAction::IgnoreAndLog(Level::Gossip), + }); } } @@ -2360,15 +2352,25 @@ impl NetworkGraph { if info.one_to_two.is_some() && info.one_to_two.as_ref().unwrap().last_update < min_time_unix { - log_gossip!(self.logger, "Removing directional update one_to_two (0) for channel {} due to its timestamp {} being below {}", - scid, info.one_to_two.as_ref().unwrap().last_update, min_time_unix); + log_gossip!( + self.logger, + "Removing directional update one_to_two (0) for channel {} due to its timestamp {} being below {}", + scid, + info.one_to_two.as_ref().unwrap().last_update, + min_time_unix + ); info.one_to_two = None; } if info.two_to_one.is_some() && info.two_to_one.as_ref().unwrap().last_update < min_time_unix { - log_gossip!(self.logger, "Removing directional update two_to_one (1) for channel {} due to its timestamp {} being below {}", - scid, info.two_to_one.as_ref().unwrap().last_update, min_time_unix); + log_gossip!( + self.logger, + "Removing directional update two_to_one (1) for channel {} due to its timestamp {} being below {}", + scid, + info.two_to_one.as_ref().unwrap().last_update, + min_time_unix + ); info.two_to_one = None; } if info.one_to_two.is_none() || info.two_to_one.is_none() { @@ -2377,8 +2379,13 @@ impl NetworkGraph { // channel_update for. let announcement_received_timestamp = info.announcement_received_time; if announcement_received_timestamp < min_time_unix as u64 { - log_gossip!(self.logger, "Removing channel {} because both directional updates are missing and its announcement timestamp {} being below {}", - scid, announcement_received_timestamp, min_time_unix); + log_gossip!( + self.logger, + "Removing channel {} because both directional updates are missing and its announcement timestamp {} being below {}", + scid, + announcement_received_timestamp, + min_time_unix + ); scids_to_remove.insert(*scid); } } @@ -2735,15 +2742,13 @@ pub(crate) mod tests { use crate::ln::channelmanager; use crate::ln::msgs::{BaseMessageHandler, MessageSendEvent, SocketAddress}; use crate::ln::msgs::{ - ChannelAnnouncement, ChannelUpdate, NodeAnnouncement, QueryChannelRange, + ChannelAnnouncement, ChannelUpdate, MAX_VALUE_MSAT, NodeAnnouncement, QueryChannelRange, QueryShortChannelIds, ReplyChannelRange, RoutingMessageHandler, UnsignedChannelAnnouncement, UnsignedChannelUpdate, UnsignedNodeAnnouncement, - MAX_VALUE_MSAT, }; use crate::routing::gossip::{ - ChannelInfo, ChannelUpdateInfo, NetworkGraph, NetworkUpdate, NodeAlias, - NodeAnnouncementInfo, NodeId, NodeInfo, P2PGossipSync, RoutingFees, - MAX_EXCESS_BYTES_FOR_RELAY, + ChannelInfo, ChannelUpdateInfo, MAX_EXCESS_BYTES_FOR_RELAY, NetworkGraph, NetworkUpdate, + NodeAlias, NodeAnnouncementInfo, NodeId, NodeInfo, P2PGossipSync, RoutingFees, }; use crate::routing::utxo::{UtxoLookupError, UtxoResult}; #[cfg(feature = "std")] @@ -2758,8 +2763,8 @@ pub(crate) mod tests { use bitcoin::amount::Amount; use bitcoin::constants::ChainHash; - use bitcoin::hashes::sha256d::Hash as Sha256dHash; use bitcoin::hashes::Hash; + use bitcoin::hashes::sha256d::Hash as Sha256dHash; use bitcoin::hex::FromHex; use bitcoin::network::Network; use bitcoin::script::ScriptBuf; @@ -3076,9 +3081,13 @@ pub(crate) mod tests { node_2_privkey, &secp_ctx, ); - match gossip_sync.handle_channel_announcement(Some(node_1_pubkey), &valid_announcement) { + match gossip_sync.handle_channel_announcement(Some(node_1_pubkey), &valid_announcement) + { Ok(_) => panic!(), - Err(e) => assert_eq!(e.err, "Channel with SCID 3 or one of its nodes was removed from our network graph recently") + Err(e) => assert_eq!( + e.err, + "Channel with SCID 3 or one of its nodes was removed from our network graph recently" + ), } gossip_sync.network_graph().remove_stale_channels_and_tracking_with_time( @@ -3384,9 +3393,11 @@ pub(crate) mod tests { get_signed_channel_announcement(|_| {}, node_1_privkey, node_2_privkey, &secp_ctx); scid = valid_channel_announcement.contents.short_channel_id; let chain_source: Option<&test_utils::TestChainSource> = None; - assert!(network_graph - .update_channel_from_announcement(&valid_channel_announcement, &chain_source) - .is_ok()); + assert!( + network_graph + .update_channel_from_announcement(&valid_channel_announcement, &chain_source) + .is_ok() + ); assert!(network_graph.read_only().channels().get(&scid).is_some()); let valid_channel_update = get_signed_channel_update(|_| {}, node_1_privkey, &secp_ctx); @@ -3437,9 +3448,11 @@ pub(crate) mod tests { get_signed_channel_announcement(|_| {}, node_1_privkey, node_2_privkey, &secp_ctx); let short_channel_id = valid_channel_announcement.contents.short_channel_id; let chain_source: Option<&test_utils::TestChainSource> = None; - assert!(network_graph - .update_channel_from_announcement(&valid_channel_announcement, &chain_source) - .is_ok()); + assert!( + network_graph + .update_channel_from_announcement(&valid_channel_announcement, &chain_source) + .is_ok() + ); assert!(network_graph.read_only().channels().get(&short_channel_id).is_some()); // Non-permanent node failure does not delete any nodes or channels @@ -3480,16 +3493,18 @@ pub(crate) mod tests { get_signed_channel_announcement(|_| {}, node_1_privkey, node_2_privkey, &secp_ctx); let scid = valid_channel_announcement.contents.short_channel_id; let chain_source: Option<&test_utils::TestChainSource> = None; - assert!(network_graph - .update_channel_from_announcement(&valid_channel_announcement, &chain_source) - .is_ok()); + assert!( + network_graph + .update_channel_from_announcement(&valid_channel_announcement, &chain_source) + .is_ok() + ); assert!(network_graph.read_only().channels().get(&scid).is_some()); // Submit two channel updates for each channel direction (update.flags bit). let valid_channel_update = get_signed_channel_update(|_| {}, node_1_privkey, &secp_ctx); - assert!(gossip_sync - .handle_channel_update(Some(node_1_pubkey), &valid_channel_update) - .is_ok()); + assert!( + gossip_sync.handle_channel_update(Some(node_1_pubkey), &valid_channel_update).is_ok() + ); assert!(network_graph.read_only().channels().get(&scid).unwrap().one_to_two.is_some()); let valid_channel_update_2 = get_signed_channel_update( @@ -3545,9 +3560,11 @@ pub(crate) mod tests { node_1_privkey, &secp_ctx, ); - assert!(gossip_sync - .handle_channel_update(Some(node_1_pubkey), &valid_channel_update) - .is_ok()); + assert!( + gossip_sync + .handle_channel_update(Some(node_1_pubkey), &valid_channel_update) + .is_ok() + ); assert!(network_graph.read_only().channels().get(&scid).unwrap().one_to_two.is_some()); network_graph.remove_stale_channels_and_tracking_with_time( announcement_time + 1 + STALE_CHANNEL_UPDATE_AGE_LIMIT_SECS, @@ -3581,9 +3598,11 @@ pub(crate) mod tests { // Add a channel and nodes from channel announcement. So our network graph will // now only consist of two nodes and one channel between them. - assert!(network_graph - .update_channel_from_announcement(&valid_channel_announcement, &chain_source) - .is_ok()); + assert!( + network_graph + .update_channel_from_announcement(&valid_channel_announcement, &chain_source) + .is_ok() + ); // Mark the channel as permanently failed. This will also remove the two nodes // and all of the entries will be tracked as removed. @@ -3630,9 +3649,11 @@ pub(crate) mod tests { // Add a channel and nodes from channel announcement. So our network graph will // now only consist of two nodes and one channel between them. - assert!(network_graph - .update_channel_from_announcement(&valid_channel_announcement, &chain_source) - .is_ok()); + assert!( + network_graph + .update_channel_from_announcement(&valid_channel_announcement, &chain_source) + .is_ok() + ); // Mark the channel as permanently failed. This will also remove the two nodes // and all of the entries will be tracked as removed. @@ -4304,7 +4325,10 @@ pub(crate) mod tests { ); assert!(read_chan_update_info_res.is_err()); - let legacy_chan_update_info_with_none: Vec = >::from_hex("2c0004000000170201010402002a060800000000000004d20801000a0d0c00040000000902040000000a0c0100").unwrap(); + let legacy_chan_update_info_with_none: Vec = >::from_hex( + "2c0004000000170201010402002a060800000000000004d20801000a0d0c00040000000902040000000a0c0100", + ) + .unwrap(); let read_chan_update_info_res: Result = crate::util::ser::Readable::read(&mut legacy_chan_update_info_with_none.as_slice()); assert!(read_chan_update_info_res.is_err()); @@ -4553,7 +4577,7 @@ pub(crate) mod tests { #[cfg(ldk_bench)] pub mod benches { use super::*; - use criterion::{black_box, Criterion}; + use criterion::{Criterion, black_box}; use std::io::Read; pub fn read_network_graph(bench: &mut Criterion) { diff --git a/lightning/src/routing/router.rs b/lightning/src/routing/router.rs index 4ac89874e2e..6aada8d7633 100644 --- a/lightning/src/routing/router.rs +++ b/lightning/src/routing/router.rs @@ -19,7 +19,7 @@ use crate::blinded_path::payment::{ }; use crate::blinded_path::{BlindedHop, Direction, IntroductionNode}; use crate::ln::channel_state::ChannelDetails; -use crate::ln::channelmanager::{PaymentId, MIN_FINAL_CLTV_EXPIRY_DELTA}; +use crate::ln::channelmanager::{MIN_FINAL_CLTV_EXPIRY_DELTA, PaymentId}; use crate::ln::msgs::{DecodeError, MAX_VALUE_MSAT}; use crate::ln::onion_utils; use crate::ln::outbound_payment::RecipientOnionFields; @@ -77,13 +77,13 @@ pub struct DefaultRouter< pub const DEFAULT_PAYMENT_DUMMY_HOPS: usize = 3; impl< - G: Deref>, - L: Logger, - ES: EntropySource, - S: Deref, - SP: Sized, - Sc: ScoreLookUp, - > DefaultRouter + G: Deref>, + L: Logger, + ES: EntropySource, + S: Deref, + SP: Sized, + Sc: ScoreLookUp, +> DefaultRouter where S::Target: for<'a> LockableScore<'a, ScoreLookUp = Sc>, { @@ -96,13 +96,13 @@ where } impl< - G: Deref>, - L: Logger, - ES: EntropySource, - S: Deref, - SP: Sized, - Sc: ScoreLookUp, - > Router for DefaultRouter + G: Deref>, + L: Logger, + ES: EntropySource, + S: Deref, + SP: Sized, + Sc: ScoreLookUp, +> Router for DefaultRouter where S::Target: for<'a> LockableScore<'a, ScoreLookUp = Sc>, { @@ -712,7 +712,9 @@ impl Route { if let Some(max_total_fee) = route_params.max_total_routing_fee_msat { let total_fee = self.get_total_fees(); if total_fee > max_total_fee { - let err = format!("Router returned an attempt to pay with a higher fee ({total_fee}msat) than we allowed ({max_total_fee}msat). Your router is critically buggy!"); + let err = format!( + "Router returned an attempt to pay with a higher fee ({total_fee}msat) than we allowed ({max_total_fee}msat). Your router is critically buggy!" + ); debug_assert!(false, "{}", err); log_error!(logger, "{}", err); return Err(()); @@ -4077,21 +4079,21 @@ fn build_route_from_hops_internal( #[cfg(test)] mod tests { - use crate::blinded_path::payment::{BlindedPayInfo, BlindedPaymentPath}; use crate::blinded_path::BlindedHop; + use crate::blinded_path::payment::{BlindedPayInfo, BlindedPaymentPath}; use crate::chain::transaction::OutPoint; use crate::ln::chan_utils::make_funding_redeemscript; use crate::ln::channel_state::{ChannelCounterparty, ChannelDetails, ChannelShutdownState}; use crate::ln::channelmanager; - use crate::ln::msgs::{UnsignedChannelUpdate, MAX_VALUE_MSAT}; + use crate::ln::msgs::{MAX_VALUE_MSAT, UnsignedChannelUpdate}; use crate::ln::types::ChannelId; use crate::routing::gossip::{EffectiveCapacity, NetworkGraph, NodeId, P2PGossipSync}; use crate::routing::router::{ - add_random_cltv_offset, build_route_from_hops_internal, default_node_features, get_route, - BlindedPathCandidate, BlindedTail, CandidateRouteHop, InFlightHtlcs, Path, - PaymentParameters, PublicHopCandidate, Route, RouteHint, RouteHintHop, RouteHop, - RouteParameters, RoutingFees, ScorerAccountingForInFlightHtlcs, - DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA, MAX_PATH_LENGTH_ESTIMATE, + BlindedPathCandidate, BlindedTail, CandidateRouteHop, DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA, + InFlightHtlcs, MAX_PATH_LENGTH_ESTIMATE, Path, PaymentParameters, PublicHopCandidate, + Route, RouteHint, RouteHintHop, RouteHop, RouteParameters, RoutingFees, + ScorerAccountingForInFlightHtlcs, add_random_cltv_offset, build_route_from_hops_internal, + default_node_features, get_route, }; use crate::routing::scoring::{ ChannelUsage, FixedPenaltyScorer, ProbabilisticScorer, ProbabilisticScoringDecayParameters, @@ -7480,23 +7482,56 @@ mod tests { #[test] fn total_fees_single_path() { let route = Route { - paths: vec![Path { hops: vec![ - RouteHop { - pubkey: PublicKey::from_slice(&>::from_hex("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(), - channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(), - short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0, maybe_announced_channel: true, - }, - RouteHop { - pubkey: PublicKey::from_slice(&>::from_hex("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(), - channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(), - short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0, maybe_announced_channel: true, - }, - RouteHop { - pubkey: PublicKey::from_slice(&>::from_hex("027f31ebc5462c1fdce1b737ecff52d37d75dea43ce11c74d25aa297165faa2007").unwrap()[..]).unwrap(), - channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(), - short_channel_id: 0, fee_msat: 225, cltv_expiry_delta: 0, maybe_announced_channel: true, - }, - ], blinded_tail: None }], + paths: vec![Path { + hops: vec![ + RouteHop { + pubkey: PublicKey::from_slice( + &>::from_hex( + "02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619", + ) + .unwrap()[..], + ) + .unwrap(), + channel_features: ChannelFeatures::empty(), + node_features: NodeFeatures::empty(), + short_channel_id: 0, + fee_msat: 100, + cltv_expiry_delta: 0, + maybe_announced_channel: true, + }, + RouteHop { + pubkey: PublicKey::from_slice( + &>::from_hex( + "0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c", + ) + .unwrap()[..], + ) + .unwrap(), + channel_features: ChannelFeatures::empty(), + node_features: NodeFeatures::empty(), + short_channel_id: 0, + fee_msat: 150, + cltv_expiry_delta: 0, + maybe_announced_channel: true, + }, + RouteHop { + pubkey: PublicKey::from_slice( + &>::from_hex( + "027f31ebc5462c1fdce1b737ecff52d37d75dea43ce11c74d25aa297165faa2007", + ) + .unwrap()[..], + ) + .unwrap(), + channel_features: ChannelFeatures::empty(), + node_features: NodeFeatures::empty(), + short_channel_id: 0, + fee_msat: 225, + cltv_expiry_delta: 0, + maybe_announced_channel: true, + }, + ], + blinded_tail: None, + }], route_params: None, }; @@ -7507,29 +7542,78 @@ mod tests { #[test] fn total_fees_multi_path() { let route = Route { - paths: vec![Path { hops: vec![ - RouteHop { - pubkey: PublicKey::from_slice(&>::from_hex("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(), - channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(), - short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0, maybe_announced_channel: true, - }, - RouteHop { - pubkey: PublicKey::from_slice(&>::from_hex("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(), - channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(), - short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0, maybe_announced_channel: true, - }, - ], blinded_tail: None }, Path { hops: vec![ - RouteHop { - pubkey: PublicKey::from_slice(&>::from_hex("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(), - channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(), - short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0, maybe_announced_channel: true, + paths: vec![ + Path { + hops: vec![ + RouteHop { + pubkey: PublicKey::from_slice( + &>::from_hex( + "02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619", + ) + .unwrap()[..], + ) + .unwrap(), + channel_features: ChannelFeatures::empty(), + node_features: NodeFeatures::empty(), + short_channel_id: 0, + fee_msat: 100, + cltv_expiry_delta: 0, + maybe_announced_channel: true, + }, + RouteHop { + pubkey: PublicKey::from_slice( + &>::from_hex( + "0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c", + ) + .unwrap()[..], + ) + .unwrap(), + channel_features: ChannelFeatures::empty(), + node_features: NodeFeatures::empty(), + short_channel_id: 0, + fee_msat: 150, + cltv_expiry_delta: 0, + maybe_announced_channel: true, + }, + ], + blinded_tail: None, }, - RouteHop { - pubkey: PublicKey::from_slice(&>::from_hex("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(), - channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(), - short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0, maybe_announced_channel: true, + Path { + hops: vec![ + RouteHop { + pubkey: PublicKey::from_slice( + &>::from_hex( + "02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619", + ) + .unwrap()[..], + ) + .unwrap(), + channel_features: ChannelFeatures::empty(), + node_features: NodeFeatures::empty(), + short_channel_id: 0, + fee_msat: 100, + cltv_expiry_delta: 0, + maybe_announced_channel: true, + }, + RouteHop { + pubkey: PublicKey::from_slice( + &>::from_hex( + "0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c", + ) + .unwrap()[..], + ) + .unwrap(), + channel_features: ChannelFeatures::empty(), + node_features: NodeFeatures::empty(), + short_channel_id: 0, + fee_msat: 150, + cltv_expiry_delta: 0, + maybe_announced_channel: true, + }, + ], + blinded_tail: None, }, - ], blinded_tail: None }], + ], route_params: None, }; diff --git a/lightning/src/routing/scoring.rs b/lightning/src/routing/scoring.rs index 1592bc0ccb2..7bb8a3fd291 100644 --- a/lightning/src/routing/scoring.rs +++ b/lightning/src/routing/scoring.rs @@ -1439,10 +1439,10 @@ fn success_probability( } impl< - L: Deref, - HT: Deref, - T: Deref, - > DirectedChannelLiquidity + L: Deref, + HT: Deref, + T: Deref, +> DirectedChannelLiquidity { /// Returns a liquidity penalty for routing the given HTLC `amount_msat` through the channel in /// this direction. @@ -1580,10 +1580,10 @@ impl< } impl< - L: DerefMut, - HT: DerefMut, - T: DerefMut, - > DirectedChannelLiquidity + L: DerefMut, + HT: DerefMut, + T: DerefMut, +> DirectedChannelLiquidity { /// Adjusts the channel liquidity balance bounds when failing to route `amount_msat`. #[rustfmt::skip] @@ -2631,8 +2631,8 @@ mod tests { use crate::io; use bitcoin::constants::ChainHash; - use bitcoin::hashes::sha256d::Hash as Sha256dHash; use bitcoin::hashes::Hash; + use bitcoin::hashes::sha256d::Hash as Sha256dHash; use bitcoin::network::Network; use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey}; use core::time::Duration; diff --git a/lightning/src/routing/utxo.rs b/lightning/src/routing/utxo.rs index 6b2f2963b76..12748ad5c47 100644 --- a/lightning/src/routing/utxo.rs +++ b/lightning/src/routing/utxo.rs @@ -13,9 +13,9 @@ //! channel matches a UTXO on-chain, requiring at least some marginal on-chain transacting in //! order to announce a channel. This module handles that checking. +use bitcoin::TxOut; use bitcoin::amount::Amount; use bitcoin::constants::ChainHash; -use bitcoin::TxOut; use bitcoin::hex::DisplayHex; @@ -889,20 +889,24 @@ mod tests { assert!(network_graph.read_only().channels().get(&scid).unwrap().one_to_two.is_some()); assert!(network_graph.read_only().channels().get(&scid).unwrap().two_to_one.is_some()); - assert!(network_graph - .read_only() - .nodes() - .get(&valid_announcement.contents.node_id_1) - .unwrap() - .announcement_info - .is_some()); - assert!(network_graph - .read_only() - .nodes() - .get(&valid_announcement.contents.node_id_2) - .unwrap() - .announcement_info - .is_some()); + assert!( + network_graph + .read_only() + .nodes() + .get(&valid_announcement.contents.node_id_1) + .unwrap() + .announcement_info + .is_some() + ); + assert!( + network_graph + .read_only() + .nodes() + .get(&valid_announcement.contents.node_id_2) + .unwrap() + .announcement_info + .is_some() + ); } #[test] diff --git a/lightning/src/sign/mod.rs b/lightning/src/sign/mod.rs index 374ad38b2ce..0a9925236db 100644 --- a/lightning/src/sign/mod.rs +++ b/lightning/src/sign/mod.rs @@ -28,12 +28,12 @@ use bitcoin::hashes::sha256::Hash as Sha256; use bitcoin::hashes::sha256d::Hash as Sha256dHash; use bitcoin::hashes::{Hash, HashEngine}; +use bitcoin::secp256k1::All; use bitcoin::secp256k1::ecdh::SharedSecret; use bitcoin::secp256k1::ecdsa::{RecoverableSignature, Signature}; use bitcoin::secp256k1::schnorr; -use bitcoin::secp256k1::All; use bitcoin::secp256k1::{Keypair, PublicKey, Scalar, Secp256k1, SecretKey, Signing}; -use bitcoin::{secp256k1, Psbt, Sequence, Txid, WPubkeyHash, Witness}; +use bitcoin::{Psbt, Sequence, Txid, WPubkeyHash, Witness, secp256k1}; use chacha20_poly1305::chacha20::{ChaCha20, Key, Nonce}; use lightning_invoice::RawBolt11Invoice; @@ -42,14 +42,14 @@ use crate::chain::transaction::OutPoint; use crate::crypto::utils::{hkdf_extract_expand_twice, sign, sign_with_aux_rand}; use crate::ln::chan_utils; use crate::ln::chan_utils::{ - get_countersigner_payment_script, get_revokeable_redeemscript, make_funding_redeemscript, ChannelPublicKeys, ChannelTransactionParameters, ClosingTransaction, CommitmentTransaction, - HTLCOutputInCommitment, HolderCommitmentTransaction, + HTLCOutputInCommitment, HolderCommitmentTransaction, get_countersigner_payment_script, + get_revokeable_redeemscript, make_funding_redeemscript, }; use crate::ln::channel::ANCHOR_OUTPUT_VALUE_SATOSHI; use crate::ln::channel_keys::{ - add_public_key_tweak, DelayedPaymentBasepoint, DelayedPaymentKey, HtlcBasepoint, HtlcKey, - RevocationBasepoint, RevocationKey, + DelayedPaymentBasepoint, DelayedPaymentKey, HtlcBasepoint, HtlcKey, RevocationBasepoint, + RevocationKey, add_public_key_tweak, }; use crate::ln::inbound_payment::ExpandedKey; use crate::ln::msgs::{UnsignedChannelAnnouncement, UnsignedGossipMessage}; @@ -511,7 +511,7 @@ impl SpendableOutputDescriptor { } input_value += descriptor.output.value; }, - SpendableOutputDescriptor::StaticOutput { ref outpoint, ref output, .. } => { + SpendableOutputDescriptor::StaticOutput { outpoint, output, .. } => { if !output_set.insert(*outpoint) { return Err(()); } @@ -2298,7 +2298,7 @@ impl KeysManager { )?; psbt.inputs[input_idx].final_script_witness = Some(witness); }, - SpendableOutputDescriptor::StaticOutput { ref outpoint, ref output, .. } => { + SpendableOutputDescriptor::StaticOutput { outpoint, output, .. } => { let input_idx = get_input_idx(outpoint)?; let derivation_idx = if output.script_pubkey == self.destination_script { 1 } else { 2 }; @@ -2723,10 +2723,10 @@ pub fn dyn_sign() { #[cfg(ldk_bench)] pub mod benches { use crate::sign::{EntropySource, KeysManager}; - use bitcoin::constants::genesis_block; use bitcoin::Network; + use bitcoin::constants::genesis_block; use std::sync::mpsc::TryRecvError; - use std::sync::{mpsc, Arc}; + use std::sync::{Arc, mpsc}; use std::thread; use std::time::Duration; @@ -2743,14 +2743,16 @@ pub mod benches { for _ in 1..5 { let keys_manager_clone = Arc::clone(&keys_manager); let (stop_sender, stop_receiver) = mpsc::channel(); - let handle = thread::spawn(move || loop { - keys_manager_clone.get_secure_random_bytes(); - match stop_receiver.try_recv() { - Ok(_) | Err(TryRecvError::Disconnected) => { - println!("Terminating."); - break; - }, - Err(TryRecvError::Empty) => {}, + let handle = thread::spawn(move || { + loop { + keys_manager_clone.get_secure_random_bytes(); + match stop_receiver.try_recv() { + Ok(_) | Err(TryRecvError::Disconnected) => { + println!("Terminating."); + break; + }, + Err(TryRecvError::Empty) => {}, + } } }); handles.push(handle); diff --git a/lightning/src/sign/tx_builder.rs b/lightning/src/sign/tx_builder.rs index ffb01c571b7..5442788b2f3 100644 --- a/lightning/src/sign/tx_builder.rs +++ b/lightning/src/sign/tx_builder.rs @@ -5,13 +5,12 @@ use core::cmp; use bitcoin::secp256k1::{self, PublicKey, Secp256k1}; use crate::ln::chan_utils::{ - commit_tx_fee_sat, htlc_success_tx_weight, htlc_timeout_tx_weight, htlc_tx_fees_sat, - second_stage_tx_fees_sat, ChannelTransactionParameters, CommitmentTransaction, - HTLCOutputInCommitment, + ChannelTransactionParameters, CommitmentTransaction, HTLCOutputInCommitment, commit_tx_fee_sat, + htlc_success_tx_weight, htlc_timeout_tx_weight, htlc_tx_fees_sat, second_stage_tx_fees_sat, }; use crate::ln::channel::{ - get_v2_channel_reserve_satoshis, CommitmentStats, ANCHOR_OUTPUT_VALUE_SATOSHI, - MIN_CHANNEL_VALUE_SATOSHIS, + ANCHOR_OUTPUT_VALUE_SATOSHI, CommitmentStats, MIN_CHANNEL_VALUE_SATOSHIS, + get_v2_channel_reserve_satoshis, }; use crate::prelude::*; use crate::types::features::ChannelTypeFeatures; diff --git a/lightning/src/sync/debug_sync.rs b/lightning/src/sync/debug_sync.rs index 84abbc5a9ed..124f5d7323b 100644 --- a/lightning/src/sync/debug_sync.rs +++ b/lightning/src/sync/debug_sync.rs @@ -6,10 +6,10 @@ use core::time::Duration; use std::cell::RefCell; -use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; use std::sync::RwLock as StdRwLock; use std::sync::RwLockReadGuard as StdRwLockReadGuard; use std::sync::RwLockWriteGuard as StdRwLockWriteGuard; +use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; #[cfg(feature = "std")] use parking_lot::Condvar as StdCondvar; @@ -157,9 +157,11 @@ impl LockMetadata { let mut locks = unsafe { LOCKS.as_ref() }.unwrap().lock(); match locks.entry(lock_constr_location) { hash_map::Entry::Occupied(e) => { - assert_eq!(lock_constr_colno, + assert_eq!( + lock_constr_colno, locate_call_symbol(&e.get()._lock_construction_bt).1, - "Because Windows doesn't support column number results in backtraces, we cannot construct two mutexes on the same line or we risk lockorder detection false positives."); + "Because Windows doesn't support column number results in backtraces, we cannot construct two mutexes on the same line or we risk lockorder detection false positives." + ); return Arc::clone(e.get()); }, hash_map::Entry::Vacant(e) => { @@ -262,11 +264,7 @@ pub struct Mutex { impl Mutex { pub(crate) fn into_inner(self) -> LockResult { - if self.poisoned.load(Ordering::Acquire) { - Err(()) - } else { - Ok(self.inner.into_inner()) - } + if self.poisoned.load(Ordering::Acquire) { Err(()) } else { Ok(self.inner.into_inner()) } } } @@ -373,11 +371,7 @@ impl Mutex { } pub fn get_mut<'a>(&'a mut self) -> LockResult<&'a mut T> { - if self.poisoned.load(Ordering::Acquire) { - Err(()) - } else { - Ok(self.inner.get_mut()) - } + if self.poisoned.load(Ordering::Acquire) { Err(()) } else { Ok(self.inner.get_mut()) } } } diff --git a/lightning/src/util/anchor_channel_reserves.rs b/lightning/src/util/anchor_channel_reserves.rs index 000f5432529..91149e8b9d9 100644 --- a/lightning/src/util/anchor_channel_reserves.rs +++ b/lightning/src/util/anchor_channel_reserves.rs @@ -19,23 +19,23 @@ //! appropriately, it can lead to loss of funds of the in-flight HLTCs as mentioned above. Only //! partially satisfying UTXO requirements incurs the risk of not being able to resolve a subset of //! HTLCs. +use crate::chain::Filter; use crate::chain::chaininterface::BroadcasterInterface; use crate::chain::chaininterface::FeeEstimator; use crate::chain::chainmonitor::ChainMonitor; use crate::chain::chainmonitor::Persist; -use crate::chain::Filter; use crate::ln::chan_utils::max_htlcs; use crate::ln::channelmanager::AChannelManager; use crate::prelude::new_hash_set; -use crate::sign::ecdsa::EcdsaChannelSigner; use crate::sign::EntropySource; +use crate::sign::ecdsa::EcdsaChannelSigner; use crate::types::features::ChannelTypeFeatures; use crate::util::logger::Logger; use crate::util::wallet_utils::Utxo; -use bitcoin::constants::WITNESS_SCALE_FACTOR; use bitcoin::Amount; use bitcoin::FeeRate; use bitcoin::Weight; +use bitcoin::constants::WITNESS_SCALE_FACTOR; use core::cmp::min; use core::ops::Deref; diff --git a/lightning/src/util/async_poll.rs b/lightning/src/util/async_poll.rs index 23ca1aad603..b38d9b65142 100644 --- a/lightning/src/util/async_poll.rs +++ b/lightning/src/util/async_poll.rs @@ -13,9 +13,9 @@ use alloc::vec::Vec; use core::future::Future; use core::marker::Unpin; use core::pin::Pin; -use core::task::{Context, Poll, RawWaker, RawWakerVTable, Waker}; +use core::task::{Context, Poll}; -pub(crate) enum ResultFuture + Unpin, O> { +pub(crate) enum ResultFuture, O> { Pending(F), Ready(O), } @@ -89,29 +89,27 @@ impl + Unpin, BF: Future + Unpin> F } } -pub(crate) struct MultiResultFuturePoller + Unpin, O> { +pub(crate) struct MultiResultFuturePoller, O> { futures_state: Vec>, } -impl + Unpin, O> MultiResultFuturePoller { +impl, O> MultiResultFuturePoller { pub fn new(futures_state: Vec>) -> Self { Self { futures_state } } } -impl + Unpin, O> Future for MultiResultFuturePoller { +impl, O> Future for MultiResultFuturePoller { type Output = Vec; fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { let mut have_pending_futures = false; - // SAFETY: While we are pinned, we can't get direct access to `futures_state` because we - // aren't `Unpin`. However, we don't actually need the `Pin` - we only use it below on the - // `Future` in the `ResultFuture::Pending` case, and the `Future` is bound by `Unpin`. - // Thus, the `Pin` is not actually used, and its safe to bypass it and access the inner - // reference directly. + // SAFETY: We never move a pending future after polling it. The vector is not reallocated + // while polling, and a pending future is only replaced once it returns `Ready`, at which + // point dropping the pinned future is allowed. let futures_state = unsafe { &mut self.get_unchecked_mut().futures_state }; for state in futures_state.iter_mut() { match state { - ResultFuture::Pending(ref mut fut) => match Pin::new(fut).poll(cx) { + ResultFuture::Pending(fut) => match unsafe { Pin::new_unchecked(fut) }.poll(cx) { Poll::Ready(res) => { *state = ResultFuture::Ready(res); }, @@ -143,24 +141,3 @@ impl + Unpin, O> Future for MultiResultFuturePoller } } } - -// If we want to poll a future without an async context to figure out if it has completed or -// not without awaiting, we need a Waker, which needs a vtable...we fill it with dummy values -// but sadly there's a good bit of boilerplate here. -// -// Waker::noop() would be preferable, but requires an MSRV of 1.85. -fn dummy_waker_clone(_: *const ()) -> RawWaker { - RawWaker::new(core::ptr::null(), &DUMMY_WAKER_VTABLE) -} -fn dummy_waker_action(_: *const ()) {} - -const DUMMY_WAKER_VTABLE: RawWakerVTable = RawWakerVTable::new( - dummy_waker_clone, - dummy_waker_action, - dummy_waker_action, - dummy_waker_action, -); - -pub(crate) fn dummy_waker() -> Waker { - unsafe { Waker::from_raw(RawWaker::new(core::ptr::null(), &DUMMY_WAKER_VTABLE)) } -} diff --git a/lightning/src/util/dyn_signer.rs b/lightning/src/util/dyn_signer.rs index 436eaabda34..fa8a6badc28 100644 --- a/lightning/src/util/dyn_signer.rs +++ b/lightning/src/util/dyn_signer.rs @@ -11,8 +11,8 @@ use crate::ln::chan_utils::{ use crate::ln::inbound_payment::ExpandedKey; use crate::ln::msgs::{UnsignedChannelAnnouncement, UnsignedGossipMessage}; use crate::ln::script::ShutdownScript; -use crate::sign::ecdsa::EcdsaChannelSigner; use crate::sign::InMemorySigner; +use crate::sign::ecdsa::EcdsaChannelSigner; use crate::sign::{ChannelSigner, ReceiveAuthKey}; use crate::sign::{EntropySource, HTLCDescriptor, OutputSpender, PhantomKeysManager}; use crate::sign::{ @@ -21,10 +21,10 @@ use crate::sign::{ use bitcoin; use bitcoin::absolute::LockTime; use bitcoin::secp256k1::All; -use bitcoin::{secp256k1, ScriptBuf, Transaction, TxOut, Txid}; +use bitcoin::{ScriptBuf, Transaction, TxOut, Txid, secp256k1}; use lightning_invoice::RawBolt11Invoice; use secp256k1::ecdsa::RecoverableSignature; -use secp256k1::{ecdh::SharedSecret, ecdsa::Signature, PublicKey, Scalar, Secp256k1, SecretKey}; +use secp256k1::{PublicKey, Scalar, Secp256k1, SecretKey, ecdh::SharedSecret, ecdsa::Signature}; use types::payment::PaymentPreimage; /// A super-trait for all the traits that a dyn signer backing implements diff --git a/lightning/src/util/message_signing.rs b/lightning/src/util/message_signing.rs index d16fc73df7c..b361df2a4a6 100644 --- a/lightning/src/util/message_signing.rs +++ b/lightning/src/util/message_signing.rs @@ -23,7 +23,7 @@ #[allow(unused)] use crate::prelude::*; use crate::util::base32; -use bitcoin::hashes::{sha256d, Hash}; +use bitcoin::hashes::{Hash, sha256d}; use bitcoin::secp256k1::ecdsa::{RecoverableSignature, RecoveryId}; use bitcoin::secp256k1::{Error, Message, PublicKey, Secp256k1, SecretKey}; @@ -100,7 +100,10 @@ mod test { let one_key = SecretKey::from_slice(&ONE).unwrap(); let zbase32_sig = sign(message.as_bytes(), &one_key); - assert_eq!(zbase32_sig, "d9tibmnic9t5y41hg7hkakdcra94akas9ku3rmmj4ag9mritc8ok4p5qzefs78c9pqfhpuftqqzhydbdwfg7u6w6wdxcqpqn4sj4e73e") + assert_eq!( + zbase32_sig, + "d9tibmnic9t5y41hg7hkakdcra94akas9ku3rmmj4ag9mritc8ok4p5qzefs78c9pqfhpuftqqzhydbdwfg7u6w6wdxcqpqn4sj4e73e" + ) } #[test] @@ -129,18 +132,24 @@ mod test { // Taken from https://github.com/ElementsProject/lightning/blob/1275af6fbb02460c8eb2f00990bb0ef9179ce8f3/tests/test_misc.py#L1925-L1938 let corpus = [ - ["@bitconner", - "is this compatible?", - "rbgfioj114mh48d8egqx8o9qxqw4fmhe8jbeeabdioxnjk8z3t1ma1hu1fiswpakgucwwzwo6ofycffbsqusqdimugbh41n1g698hr9t", - "02b80cabdf82638aac86948e4c06e82064f547768dcef977677b9ea931ea75bab5"], - ["@duck1123", - "hi", - "rnrphcjswusbacjnmmmrynh9pqip7sy5cx695h6mfu64iac6qmcmsd8xnsyczwmpqp9shqkth3h4jmkgyqu5z47jfn1q7gpxtaqpx4xg", - "02de60d194e1ca5947b59fe8e2efd6aadeabfb67f2e89e13ae1a799c1e08e4a43b"], - ["@jochemin", - "hi", - "ry8bbsopmduhxy3dr5d9ekfeabdpimfx95kagdem7914wtca79jwamtbw4rxh69hg7n6x9ty8cqk33knbxaqftgxsfsaeprxkn1k48p3", - "022b8ece90ee891cbcdac0c1cc6af46b73c47212d8defbce80265ac81a6b794931"], + [ + "@bitconner", + "is this compatible?", + "rbgfioj114mh48d8egqx8o9qxqw4fmhe8jbeeabdioxnjk8z3t1ma1hu1fiswpakgucwwzwo6ofycffbsqusqdimugbh41n1g698hr9t", + "02b80cabdf82638aac86948e4c06e82064f547768dcef977677b9ea931ea75bab5", + ], + [ + "@duck1123", + "hi", + "rnrphcjswusbacjnmmmrynh9pqip7sy5cx695h6mfu64iac6qmcmsd8xnsyczwmpqp9shqkth3h4jmkgyqu5z47jfn1q7gpxtaqpx4xg", + "02de60d194e1ca5947b59fe8e2efd6aadeabfb67f2e89e13ae1a799c1e08e4a43b", + ], + [ + "@jochemin", + "hi", + "ry8bbsopmduhxy3dr5d9ekfeabdpimfx95kagdem7914wtca79jwamtbw4rxh69hg7n6x9ty8cqk33knbxaqftgxsfsaeprxkn1k48p3", + "022b8ece90ee891cbcdac0c1cc6af46b73c47212d8defbce80265ac81a6b794931", + ], ]; for c in &corpus { diff --git a/lightning/src/util/native_async.rs b/lightning/src/util/native_async.rs index 31b07c2f3b5..25248edaa30 100644 --- a/lightning/src/util/native_async.rs +++ b/lightning/src/util/native_async.rs @@ -195,8 +195,7 @@ impl FutureQueue { futures = self.0.borrow_mut(); } futures.retain_mut(|fut| { - let waker = crate::util::async_poll::dummy_waker(); - match fut.as_mut().poll(&mut Context::from_waker(&waker)) { + match fut.as_mut().poll(&mut Context::from_waker(core::task::Waker::noop())) { Poll::Ready(()) => false, Poll::Pending => true, } diff --git a/lightning/src/util/persist.rs b/lightning/src/util/persist.rs index 95d6032e130..d10767f5914 100644 --- a/lightning/src/util/persist.rs +++ b/lightning/src/util/persist.rs @@ -13,15 +13,15 @@ use alloc::sync::Arc; -use bitcoin::hashes::hex::FromHex; use bitcoin::Txid; +use bitcoin::hashes::hex::FromHex; use core::convert::Infallible; use core::fmt; use core::future::Future; use core::mem; use core::ops::Deref; -use core::pin::{pin, Pin}; +use core::pin::{Pin, pin}; use core::str::FromStr; use core::task; @@ -29,17 +29,15 @@ use crate::prelude::*; use crate::{io, log_error}; use crate::chain; +use crate::chain::BlockLocator; use crate::chain::chaininterface::{BroadcasterInterface, FeeEstimator}; use crate::chain::chainmonitor::Persist; use crate::chain::channelmonitor::{ChannelMonitor, ChannelMonitorUpdate}; use crate::chain::transaction::OutPoint; -use crate::chain::BlockLocator; use crate::ln::types::ChannelId; -use crate::sign::{ecdsa::EcdsaChannelSigner, EntropySource, SignerProvider}; +use crate::sign::{EntropySource, SignerProvider, ecdsa::EcdsaChannelSigner}; use crate::sync::Mutex; -use crate::util::async_poll::{ - dummy_waker, MultiResultFuturePoller, ResultFuture, TwoFutureJoiner, -}; +use crate::util::async_poll::{MultiResultFuturePoller, ResultFuture, TwoFutureJoiner}; use crate::util::logger::Logger; use crate::util::native_async::{FutureSpawner, MaybeSend, MaybeSync}; use crate::util::ser::{Readable, ReadableArgs, Writeable}; @@ -688,7 +686,7 @@ where return Err(io::Error::new( io::ErrorKind::InvalidData, "Failed to read ChannelMonitor", - )) + )); }, } } @@ -707,8 +705,7 @@ impl FutureSpawner for PanicingSpawner { } fn poll_sync_future(future: F) -> F::Output { - let mut waker = dummy_waker(); - let mut ctx = task::Context::from_waker(&mut waker); + let mut ctx = task::Context::from_waker(core::task::Waker::noop()); match pin!(future).poll(&mut ctx) { task::Poll::Ready(result) => result, task::Poll::Pending => { @@ -805,13 +802,13 @@ where K::Target: KVStoreSync; impl< - K: Deref, - L: Logger, - ES: EntropySource, - SP: SignerProvider, - BI: BroadcasterInterface, - FE: FeeEstimator, - > MonitorUpdatingPersister + K: Deref, + L: Logger, + ES: EntropySource, + SP: SignerProvider, + BI: BroadcasterInterface, + FE: FeeEstimator, +> MonitorUpdatingPersister where K::Target: KVStoreSync, { @@ -894,14 +891,14 @@ where } impl< - ChannelSigner: EcdsaChannelSigner, - K: Deref, - L: Logger, - ES: EntropySource, - SP: SignerProvider, - BI: BroadcasterInterface, - FE: FeeEstimator, - > Persist for MonitorUpdatingPersister + ChannelSigner: EcdsaChannelSigner, + K: Deref, + L: Logger, + ES: EntropySource, + SP: SignerProvider, + BI: BroadcasterInterface, + FE: FeeEstimator, +> Persist for MonitorUpdatingPersister where K::Target: KVStoreSync, { @@ -910,12 +907,12 @@ where fn persist_new_channel( &self, monitor_name: MonitorName, monitor: &ChannelMonitor, ) -> chain::ChannelMonitorUpdateStatus { - let res = poll_sync_future(self.0 .0.persist_new_channel(monitor_name, monitor)); + let res = poll_sync_future(self.0.0.persist_new_channel(monitor_name, monitor)); match res { Ok(_) => chain::ChannelMonitorUpdateStatus::Completed, Err(e) => { log_error!( - self.0 .0.logger, + self.0.0.logger, "Failed to write ChannelMonitor {}/{}/{} reason: {}", CHANNEL_MONITOR_PERSISTENCE_PRIMARY_NAMESPACE, CHANNEL_MONITOR_PERSISTENCE_SECONDARY_NAMESPACE, @@ -940,13 +937,13 @@ where &self, monitor_name: MonitorName, update: Option<&ChannelMonitorUpdate>, monitor: &ChannelMonitor, ) -> chain::ChannelMonitorUpdateStatus { - let inner = Arc::clone(&self.0 .0); + let inner = Arc::clone(&self.0.0); let res = poll_sync_future(inner.update_persisted_channel(monitor_name, update, monitor)); match res { Ok(()) => chain::ChannelMonitorUpdateStatus::Completed, Err(e) => { log_error!( - self.0 .0.logger, + self.0.0.logger, "Failed to write ChannelMonitorUpdate {} id {} reason: {}", monitor_name, update.as_ref().map(|upd| upd.update_id).unwrap_or(0), @@ -958,7 +955,7 @@ where } fn archive_persisted_channel(&self, monitor_name: MonitorName) { - poll_sync_future(self.0 .0.archive_persisted_channel(monitor_name)); + poll_sync_future(self.0.0.archive_persisted_channel(monitor_name)); } } @@ -1005,14 +1002,14 @@ struct MonitorUpdatingPersisterAsyncInner< } impl< - K: KVStore, - S: FutureSpawner, - L: Logger, - ES: EntropySource, - SP: SignerProvider, - BI: BroadcasterInterface, - FE: FeeEstimator, - > MonitorUpdatingPersisterAsync + K: KVStore, + S: FutureSpawner, + L: Logger, + ES: EntropySource, + SP: SignerProvider, + BI: BroadcasterInterface, + FE: FeeEstimator, +> MonitorUpdatingPersisterAsync { /// Constructs a new [`MonitorUpdatingPersisterAsync`]. /// @@ -1142,14 +1139,14 @@ impl< } impl< - K: KVStore + MaybeSend + MaybeSync + 'static, - S: FutureSpawner, - L: Logger + MaybeSend + MaybeSync + 'static, - ES: EntropySource + MaybeSend + MaybeSync + 'static, - SP: SignerProvider + MaybeSend + MaybeSync + 'static, - BI: BroadcasterInterface + MaybeSend + MaybeSync + 'static, - FE: FeeEstimator + MaybeSend + MaybeSync + 'static, - > MonitorUpdatingPersisterAsync + K: KVStore + MaybeSend + MaybeSync + 'static, + S: FutureSpawner, + L: Logger + MaybeSend + MaybeSync + 'static, + ES: EntropySource + MaybeSend + MaybeSync + 'static, + SP: SignerProvider + MaybeSend + MaybeSync + 'static, + BI: BroadcasterInterface + MaybeSend + MaybeSync + 'static, + FE: FeeEstimator + MaybeSend + MaybeSync + 'static, +> MonitorUpdatingPersisterAsync where SP::EcdsaSigner: MaybeSend + 'static, { @@ -1226,14 +1223,14 @@ trait MaybeSendableFuture: Future> + MaybeSend {} impl> + MaybeSend> MaybeSendableFuture for F {} impl< - K: KVStore, - S: FutureSpawner, - L: Logger, - ES: EntropySource, - SP: SignerProvider, - BI: BroadcasterInterface, - FE: FeeEstimator, - > MonitorUpdatingPersisterAsyncInner + K: KVStore, + S: FutureSpawner, + L: Logger, + ES: EntropySource, + SP: SignerProvider, + BI: BroadcasterInterface, + FE: FeeEstimator, +> MonitorUpdatingPersisterAsyncInner { pub async fn read_channel_monitor_with_updates( &self, monitor_key: &str, @@ -1257,9 +1254,9 @@ impl< ) -> Result)>, io::Error> { let monitor_name = MonitorName::from_str(monitor_key)?; let read_future = pin!(self.maybe_read_monitor(&monitor_name, monitor_key)); - let list_future = pin!(self - .kv_store - .list(CHANNEL_MONITOR_UPDATE_PERSISTENCE_PRIMARY_NAMESPACE, monitor_key)); + let list_future = pin!( + self.kv_store.list(CHANNEL_MONITOR_UPDATE_PERSISTENCE_PRIMARY_NAMESPACE, monitor_key) + ); let (read_res, list_res) = TwoFutureJoiner::new(read_future, list_future).await; let (best_block, monitor) = match read_res? { Some(res) => res, @@ -1413,9 +1410,6 @@ impl< // completion of the write. This ensures monitor persistence ordering is preserved. let primary = CHANNEL_MONITOR_PERSISTENCE_PRIMARY_NAMESPACE; let secondary = CHANNEL_MONITOR_PERSISTENCE_SECONDARY_NAMESPACE; - // There's no real reason why this needs to be boxed, but dropping it rams into the "hidden - // type for impl... captures lifetime that does not appear in bounds" issue. This can - // trivially be dropped once we upgrade to edition 2024/MSRV 1.85. Box::pin(self.kv_store.write(primary, secondary, monitor_key.as_str(), monitor_bytes)) } @@ -1787,18 +1781,22 @@ mod tests { #[test] fn fails_parsing_monitor_name() { - assert!(MonitorName::from_str( - "deadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef_" - ) - .is_err()); - assert!(MonitorName::from_str( - "deadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef_65536" - ) - .is_err()); - assert!(MonitorName::from_str( - "deadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef_21" - ) - .is_err()); + assert!( + MonitorName::from_str( + "deadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef_" + ) + .is_err() + ); + assert!( + MonitorName::from_str( + "deadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef_65536" + ) + .is_err() + ); + assert!( + MonitorName::from_str("deadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef_21") + .is_err() + ); } // Exercise the `MonitorUpdatingPersister` with real channels and payments. @@ -2116,13 +2114,15 @@ mod tests { persister_0.cleanup_stale_updates(false).unwrap(); // Confirm the stale update is unreadable/gone - assert!(KVStoreSync::read( - &kv_store_0, - CHANNEL_MONITOR_UPDATE_PERSISTENCE_PRIMARY_NAMESPACE, - &monitor_name.to_string(), - UpdateName::from(1).as_str() - ) - .is_err()); + assert!( + KVStoreSync::read( + &kv_store_0, + CHANNEL_MONITOR_UPDATE_PERSISTENCE_PRIMARY_NAMESPACE, + &monitor_name.to_string(), + UpdateName::from(1).as_str() + ) + .is_err() + ); } fn persist_fn(_persist: P) -> bool diff --git a/lightning/src/util/scid_utils.rs b/lightning/src/util/scid_utils.rs index 342c062d7f1..929ce31a245 100644 --- a/lightning/src/util/scid_utils.rs +++ b/lightning/src/util/scid_utils.rs @@ -76,8 +76,8 @@ pub(crate) mod fake_scid { use crate::prelude::*; use crate::sign::EntropySource; use crate::util::scid_utils; - use bitcoin::constants::ChainHash; use bitcoin::Network; + use bitcoin::constants::ChainHash; use chacha20_poly1305::chacha20::{ChaCha20, Key, Nonce}; const TEST_SEGWIT_ACTIVATION_HEIGHT: u32 = 1; @@ -200,9 +200,9 @@ pub(crate) mod fake_scid { use crate::sync::Arc; use crate::util::scid_utils; use crate::util::scid_utils::fake_scid::{ - is_valid_intercept, is_valid_phantom, segwit_activation_height, Namespace, MAINNET_SEGWIT_ACTIVATION_HEIGHT, MAX_NAMESPACES, MAX_TX_INDEX, NAMESPACE_ID_BITMASK, - TEST_SEGWIT_ACTIVATION_HEIGHT, + Namespace, TEST_SEGWIT_ACTIVATION_HEIGHT, is_valid_intercept, is_valid_phantom, + segwit_activation_height, }; use crate::util::test_utils; use bitcoin::constants::ChainHash; diff --git a/lightning/src/util/ser.rs b/lightning/src/util/ser.rs index bd2488bd8d1..27b69b97171 100644 --- a/lightning/src/util/ser.rs +++ b/lightning/src/util/ser.rs @@ -26,6 +26,7 @@ use core::str::FromStr; use alloc::collections::BTreeMap; +use bitcoin::FeeRate; use bitcoin::absolute::LockTime as AbsoluteLockTime; use bitcoin::address::Address; use bitcoin::amount::{Amount, SignedAmount}; @@ -43,8 +44,7 @@ use bitcoin::secp256k1::ecdsa; use bitcoin::secp256k1::schnorr; use bitcoin::secp256k1::{PublicKey, SecretKey}; use bitcoin::transaction::{OutPoint, Transaction, TxOut}; -use bitcoin::FeeRate; -use bitcoin::{consensus, Sequence, TxIn, Weight, Witness}; +use bitcoin::{Sequence, TxIn, Weight, Witness, consensus}; use dnssec_prover::rr::Name; @@ -125,11 +125,7 @@ impl<'a, R: Read> BufRead for BufReader<'a, R> { self.is_consumed = count == 0; } - if self.is_consumed { - Ok(&[]) - } else { - Ok(&self.buf[..]) - } + if self.is_consumed { Ok(&[]) } else { Ok(&self.buf[..]) } } #[inline] @@ -207,11 +203,7 @@ impl<'a, R: Read> FixedLengthReader<'a, R> { #[inline] pub fn eat_remaining(&mut self) -> Result<(), DecodeError> { copy(self, &mut sink()).unwrap(); - if self.bytes_read != self.total_bytes { - Err(DecodeError::ShortRead) - } else { - Ok(()) - } + if self.bytes_read != self.total_bytes { Err(DecodeError::ShortRead) } else { Ok(()) } } } impl<'a, R: Read> Read for FixedLengthReader<'a, R> { @@ -528,27 +520,15 @@ impl Readable for BigSize { match n { 0xFF => { let x: u64 = Readable::read(reader)?; - if x < 0x100000000 { - Err(DecodeError::InvalidValue) - } else { - Ok(BigSize(x)) - } + if x < 0x100000000 { Err(DecodeError::InvalidValue) } else { Ok(BigSize(x)) } }, 0xFE => { let x: u32 = Readable::read(reader)?; - if x < 0x10000 { - Err(DecodeError::InvalidValue) - } else { - Ok(BigSize(x as u64)) - } + if x < 0x10000 { Err(DecodeError::InvalidValue) } else { Ok(BigSize(x as u64)) } }, 0xFD => { let x: u16 = Readable::read(reader)?; - if x < 0xFD { - Err(DecodeError::InvalidValue) - } else { - Ok(BigSize(x as u64)) - } + if x < 0xFD { Err(DecodeError::InvalidValue) } else { Ok(BigSize(x as u64)) } }, n => Ok(BigSize(n as u64)), } @@ -786,7 +766,7 @@ impl Readable for UntrustedString { impl Writeable for WithoutLength<&UntrustedString> { #[inline] fn write(&self, w: &mut W) -> Result<(), io::Error> { - WithoutLength(&self.0 .0).write(w) + WithoutLength(&self.0.0).write(w) } } impl LengthReadable for WithoutLength { @@ -1697,22 +1677,14 @@ impl TryFrom> for Hostname { type Error = (); fn try_from(bytes: Vec) -> Result { - if let Ok(s) = String::from_utf8(bytes) { - Hostname::try_from(s) - } else { - Err(()) - } + if let Ok(s) = String::from_utf8(bytes) { Hostname::try_from(s) } else { Err(()) } } } impl TryFrom for Hostname { type Error = (); fn try_from(s: String) -> Result { - if Hostname::str_is_valid_hostname(&s) { - Ok(Hostname(s)) - } else { - Err(()) - } + if Hostname::str_is_valid_hostname(&s) { Ok(Hostname(s)) } else { Err(()) } } } impl Writeable for Hostname { diff --git a/lightning/src/util/ser_macros.rs b/lightning/src/util/ser_macros.rs index 946be54de65..6b23a1c9617 100644 --- a/lightning/src/util/ser_macros.rs +++ b/lightning/src/util/ser_macros.rs @@ -42,7 +42,7 @@ macro_rules! _encode_tlv { $crate::_encode_tlv!($stream, $type, $encoding($field), required); }; ($stream: expr, $optional_type: expr, $optional_field: expr, option $(, $self: ident)?) => { - if let Some(ref field) = $optional_field { + if let Some(field) = &$optional_field { BigSize($optional_type).write($stream)?; BigSize(field.serialized_length() as u64).write($stream)?; field.write($stream)?; @@ -227,7 +227,7 @@ macro_rules! _get_varint_length_prefixed_tlv_length { $crate::_get_varint_length_prefixed_tlv_length!($len, $type, field, required); }; ($len: expr, $optional_type: expr, $optional_field: expr, option $(, $self: ident)?) => { - if let Some(ref field) = $optional_field.as_ref() { + if let Some(field) = $optional_field.as_ref() { BigSize($optional_type) .write(&mut $len) .expect("No in-memory data may fail to serialize"); @@ -360,9 +360,7 @@ macro_rules! _check_decoded_tlv_order { ($last_seen_type: expr, $typ: expr, $type: expr, $field: ident, optional_vec) => {{ // no-op }}; - ($last_seen_type: expr, $typ: expr, $type: expr, $field: ident, upgradable_required) => {{ - _check_decoded_tlv_order!($last_seen_type, $typ, $type, $field, required) - }}; + ($last_seen_type: expr, $typ: expr, $type: expr, $field: ident, upgradable_required) => {{ _check_decoded_tlv_order!($last_seen_type, $typ, $type, $field, required) }}; ($last_seen_type: expr, $typ: expr, $type: expr, $field: ident, upgradable_option) => {{ // no-op }}; @@ -436,9 +434,7 @@ macro_rules! _check_missing_tlv { ($last_seen_type: expr, $type: expr, $field: ident, optional_vec) => {{ // no-op }}; - ($last_seen_type: expr, $type: expr, $field: ident, upgradable_required) => {{ - _check_missing_tlv!($last_seen_type, $type, $field, required) - }}; + ($last_seen_type: expr, $type: expr, $field: ident, upgradable_required) => {{ _check_missing_tlv!($last_seen_type, $type, $field, required) }}; ($last_seen_type: expr, $type: expr, $field: ident, upgradable_option) => {{ // no-op }}; @@ -1221,12 +1217,12 @@ macro_rules! _impl_writeable_tlv_based_enum_common { $(($type, $field, $fieldty, self)),* }); }),* - $($st::$tuple_variant_name (ref field) => { + $($st::$tuple_variant_name(ref field) => { let id: u8 = $tuple_variant_id; id.write(writer)?; field.write(writer)?; }),* - $($st::$length_prefixed_tuple_variant_name (ref field) => { + $($st::$length_prefixed_tuple_variant_name(ref field) => { let id: u8 = $length_prefixed_tuple_variant_id; id.write(writer)?; $crate::util::ser::BigSize(field.serialized_length() as u64).write(writer)?; @@ -1765,7 +1761,14 @@ mod tests { do_test!(concat!("0f", "fd26"), ShortRead); do_test!(concat!("0f", "fd2602"), ShortRead); do_test!(concat!("0f", "fd0001", "00"), InvalidValue); - do_test!(concat!("0f", "fd0201", "000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"), ShortRead); + do_test!( + concat!( + "0f", + "fd0201", + "000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000" + ), + ShortRead + ); do_test!(concat!("12", "00"), UnknownRequiredFeature); do_test!(concat!("fd0102", "00"), UnknownRequiredFeature); @@ -1806,10 +1809,38 @@ mod tests { ), ShortRead ); - do_test!(concat!("03", "29", "023da092f6980e58d2c037173180e9a465476026ee50f96695963e8efe436f54eb0000000000000001"), ShortRead); - do_test!(concat!("03", "30", "023da092f6980e58d2c037173180e9a465476026ee50f96695963e8efe436f54eb000000000000000100000000000001"), ShortRead); - do_test!(concat!("03", "31", "043da092f6980e58d2c037173180e9a465476026ee50f96695963e8efe436f54eb00000000000000010000000000000002"), InvalidValue); - do_test!(concat!("03", "32", "023da092f6980e58d2c037173180e9a465476026ee50f96695963e8efe436f54eb0000000000000001000000000000000001"), InvalidValue); + do_test!( + concat!( + "03", + "29", + "023da092f6980e58d2c037173180e9a465476026ee50f96695963e8efe436f54eb0000000000000001" + ), + ShortRead + ); + do_test!( + concat!( + "03", + "30", + "023da092f6980e58d2c037173180e9a465476026ee50f96695963e8efe436f54eb000000000000000100000000000001" + ), + ShortRead + ); + do_test!( + concat!( + "03", + "31", + "043da092f6980e58d2c037173180e9a465476026ee50f96695963e8efe436f54eb00000000000000010000000000000002" + ), + InvalidValue + ); + do_test!( + concat!( + "03", + "32", + "023da092f6980e58d2c037173180e9a465476026ee50f96695963e8efe436f54eb0000000000000001000000000000000001" + ), + InvalidValue + ); do_test!(concat!("fd00fe", "00"), ShortRead); do_test!(concat!("fd00fe", "01", "01"), ShortRead); do_test!(concat!("fd00fe", "03", "010101"), InvalidValue); @@ -1874,10 +1905,27 @@ mod tests { None, None ); - do_test!(concat!("03", "31", "023da092f6980e58d2c037173180e9a465476026ee50f96695963e8efe436f54eb00000000000000010000000000000002"), - None, None, Some(( - PublicKey::from_slice(&>::from_hex("023da092f6980e58d2c037173180e9a465476026ee50f96695963e8efe436f54eb").unwrap()[..]).unwrap(), 1, 2)), - None); + do_test!( + concat!( + "03", + "31", + "023da092f6980e58d2c037173180e9a465476026ee50f96695963e8efe436f54eb00000000000000010000000000000002" + ), + None, + None, + Some(( + PublicKey::from_slice( + &>::from_hex( + "023da092f6980e58d2c037173180e9a465476026ee50f96695963e8efe436f54eb" + ) + .unwrap()[..] + ) + .unwrap(), + 1, + 2 + )), + None + ); do_test!(concat!("fd00fe", "02", "0226"), None, None, None, Some(550)); } diff --git a/lightning/src/util/sweep.rs b/lightning/src/util/sweep.rs index 8d539b0a5e6..1efe2febc9d 100644 --- a/lightning/src/util/sweep.rs +++ b/lightning/src/util/sweep.rs @@ -37,12 +37,10 @@ use bitcoin::{BlockHash, ScriptBuf, Transaction, Txid}; use core::future::Future; use core::ops::Deref; -use core::pin::{pin, Pin}; +use core::pin::{Pin, pin}; use core::sync::atomic::{AtomicBool, Ordering}; use core::task; -use super::async_poll::dummy_waker; - /// The number of blocks we wait before we prune the tracked spendable outputs. pub const PRUNE_DELAY_BLOCKS: u32 = ARCHIVAL_DELAY_BLOCKS + ANTI_REORG_DELAY; @@ -179,7 +177,10 @@ impl OutputSpendStatus { Self::PendingInitialBroadcast { .. } => { // Generally we can't see any of our transactions confirmed if they haven't been // broadcasted yet, so this should never be reachable via `transactions_confirmed`. - debug_assert!(false, "We should never confirm when we haven't broadcasted. This a bug and should never happen, please report."); + debug_assert!( + false, + "We should never confirm when we haven't broadcasted. This a bug and should never happen, please report." + ); *self = Self::PendingThresholdConfirmations { first_broadcast_hash: confirmation_hash, latest_broadcast_height: confirmation_height, @@ -370,14 +371,14 @@ pub struct OutputSweeper< } impl< - B: BroadcasterInterface, - D: Deref, - E: FeeEstimator, - F: Filter, - K: KVStore, - L: Logger, - O: OutputSpender, - > OutputSweeper + B: BroadcasterInterface, + D: Deref, + E: FeeEstimator, + F: Filter, + K: KVStore, + L: Logger, + O: OutputSpender, +> OutputSweeper where D::Target: ChangeDestinationSource, { @@ -748,14 +749,14 @@ where } impl< - B: BroadcasterInterface, - D: Deref, - E: FeeEstimator, - F: Filter + Sync + Send, - K: KVStore, - L: Logger, - O: OutputSpender, - > Listen for OutputSweeper + B: BroadcasterInterface, + D: Deref, + E: FeeEstimator, + F: Filter + Sync + Send, + K: KVStore, + L: Logger, + O: OutputSpender, +> Listen for OutputSweeper where D::Target: ChangeDestinationSource, { @@ -763,10 +764,15 @@ where &self, header: &Header, txdata: &chain::transaction::TransactionData, height: u32, ) { let mut state_lock = self.sweeper_state.lock().unwrap(); - assert_eq!(state_lock.best_block.block_hash, header.prev_blockhash, - "Blocks must be connected in chain-order - the connected header must build on the last connected header"); - assert_eq!(state_lock.best_block.height, height - 1, - "Blocks must be connected in chain-order - the connected block height must be one greater than the previous height"); + assert_eq!( + state_lock.best_block.block_hash, header.prev_blockhash, + "Blocks must be connected in chain-order - the connected header must build on the last connected header" + ); + assert_eq!( + state_lock.best_block.height, + height - 1, + "Blocks must be connected in chain-order - the connected block height must be one greater than the previous height" + ); self.transactions_confirmed_internal(&mut state_lock, header, txdata, height); self.best_block_updated_internal(&mut state_lock, header, height); @@ -775,8 +781,10 @@ where fn blocks_disconnected(&self, fork_point: BlockLocator) { let mut state_lock = self.sweeper_state.lock().unwrap(); - assert!(state_lock.best_block.height > fork_point.height, - "Blocks disconnected must indicate disconnection from the current best height, i.e. the new chain tip must be lower than the previous best height"); + assert!( + state_lock.best_block.height > fork_point.height, + "Blocks disconnected must indicate disconnection from the current best height, i.e. the new chain tip must be lower than the previous best height" + ); state_lock.best_block = fork_point; for output_info in state_lock.outputs.iter_mut() { @@ -790,14 +798,14 @@ where } impl< - B: BroadcasterInterface, - D: Deref, - E: FeeEstimator, - F: Filter + Sync + Send, - K: KVStore, - L: Logger, - O: OutputSpender, - > Confirm for OutputSweeper + B: BroadcasterInterface, + D: Deref, + E: FeeEstimator, + F: Filter + Sync + Send, + K: KVStore, + L: Logger, + O: OutputSpender, +> Confirm for OutputSweeper where D::Target: ChangeDestinationSource, { @@ -888,14 +896,14 @@ pub enum SpendingDelay { } impl< - B: BroadcasterInterface, - D: Deref, - E: FeeEstimator, - F: Filter + Sync + Send, - K: KVStore, - L: Logger, - O: OutputSpender, - > ReadableArgs<(B, E, Option, O, D, K, L)> for (BlockLocator, OutputSweeper) + B: BroadcasterInterface, + D: Deref, + E: FeeEstimator, + F: Filter + Sync + Send, + K: KVStore, + L: Logger, + O: OutputSpender, +> ReadableArgs<(B, E, Option, O, D, K, L)> for (BlockLocator, OutputSweeper) where D::Target: ChangeDestinationSource, { @@ -975,14 +983,14 @@ pub struct OutputSweeperSync< } impl< - B: BroadcasterInterface, - D: Deref, - E: FeeEstimator, - F: Filter, - K: Deref, - L: Logger, - O: OutputSpender, - > OutputSweeperSync + B: BroadcasterInterface, + D: Deref, + E: FeeEstimator, + F: Filter, + K: Deref, + L: Logger, + O: OutputSpender, +> OutputSweeperSync where D::Target: ChangeDestinationSourceSync, K::Target: KVStoreSync, @@ -1040,13 +1048,14 @@ where exclude_static_outputs, delay_until_height, )); - let mut waker = dummy_waker(); - let mut ctx = task::Context::from_waker(&mut waker); + let mut ctx = task::Context::from_waker(core::task::Waker::noop()); match fut.as_mut().poll(&mut ctx) { task::Poll::Ready(result) => result, task::Poll::Pending => { // In a sync context, we can't wait for the future to complete. - unreachable!("OutputSweeper::track_spendable_outputs should not be pending in a sync context"); + unreachable!( + "OutputSweeper::track_spendable_outputs should not be pending in a sync context" + ); }, } } @@ -1070,13 +1079,14 @@ where /// Wraps [`OutputSweeper::regenerate_and_broadcast_spend_if_necessary`]. pub fn regenerate_and_broadcast_spend_if_necessary(&self) -> Result<(), ()> { let mut fut = pin!(self.sweeper.regenerate_and_broadcast_spend_if_necessary()); - let mut waker = dummy_waker(); - let mut ctx = task::Context::from_waker(&mut waker); + let mut ctx = task::Context::from_waker(core::task::Waker::noop()); match fut.as_mut().poll(&mut ctx) { task::Poll::Ready(result) => result, task::Poll::Pending => { // In a sync context, we can't wait for the future to complete. - unreachable!("OutputSweeper::regenerate_and_broadcast_spend_if_necessary should not be pending in a sync context"); + unreachable!( + "OutputSweeper::regenerate_and_broadcast_spend_if_necessary should not be pending in a sync context" + ); }, } } @@ -1099,14 +1109,14 @@ where } impl< - B: BroadcasterInterface, - D: Deref, - E: FeeEstimator, - F: Filter + Sync + Send, - K: Deref, - L: Logger, - O: OutputSpender, - > Listen for OutputSweeperSync + B: BroadcasterInterface, + D: Deref, + E: FeeEstimator, + F: Filter + Sync + Send, + K: Deref, + L: Logger, + O: OutputSpender, +> Listen for OutputSweeperSync where D::Target: ChangeDestinationSourceSync, K::Target: KVStoreSync, @@ -1123,14 +1133,14 @@ where } impl< - B: BroadcasterInterface, - D: Deref, - E: FeeEstimator, - F: Filter + Sync + Send, - K: Deref, - L: Logger, - O: OutputSpender, - > Confirm for OutputSweeperSync + B: BroadcasterInterface, + D: Deref, + E: FeeEstimator, + F: Filter + Sync + Send, + K: Deref, + L: Logger, + O: OutputSpender, +> Confirm for OutputSweeperSync where D::Target: ChangeDestinationSourceSync, K::Target: KVStoreSync, @@ -1155,14 +1165,14 @@ where } impl< - B: BroadcasterInterface, - D: Deref, - E: FeeEstimator, - F: Filter + Sync + Send, - K: Deref, - L: Logger, - O: OutputSpender, - > ReadableArgs<(B, E, Option, O, D, K, L)> + B: BroadcasterInterface, + D: Deref, + E: FeeEstimator, + F: Filter + Sync + Send, + K: Deref, + L: Logger, + O: OutputSpender, +> ReadableArgs<(B, E, Option, O, D, K, L)> for (BlockLocator, OutputSweeperSync) where D::Target: ChangeDestinationSourceSync, @@ -1188,7 +1198,6 @@ mod tests { use super::*; use crate::chain::transaction::OutPoint; use crate::sign::{ChangeDestinationSource, OutputSpender}; - use crate::util::async_poll::dummy_waker; use crate::util::logger::Record; use crate::util::native_async::MaybeSend; @@ -1314,8 +1323,7 @@ mod tests { // cancellation - the sort of thing a `tokio::time::timeout` wrapper produces. { let mut fut = pin!(sweeper.regenerate_and_broadcast_spend_if_necessary()); - let waker = dummy_waker(); - let mut ctx = task::Context::from_waker(&waker); + let mut ctx = task::Context::from_waker(core::task::Waker::noop()); assert!(matches!(fut.as_mut().poll(&mut ctx), Poll::Pending)); } diff --git a/lightning/src/util/test_channel_signer.rs b/lightning/src/util/test_channel_signer.rs index 8435e7fa437..7b19fda4eb3 100644 --- a/lightning/src/util/test_channel_signer.rs +++ b/lightning/src/util/test_channel_signer.rs @@ -14,8 +14,8 @@ use crate::ln::chan_utils::{ use crate::ln::channel::{ANCHOR_OUTPUT_VALUE_SATOSHI, MIN_CHAN_DUST_LIMIT_SATOSHIS}; use crate::ln::channel_keys::HtlcKey; use crate::ln::msgs; -use crate::sign::ecdsa::EcdsaChannelSigner; use crate::sign::ChannelSigner; +use crate::sign::ecdsa::EcdsaChannelSigner; use crate::types::payment::PaymentPreimage; #[allow(unused_imports)] @@ -28,17 +28,17 @@ use crate::sync::{Arc, Mutex}; use core::cmp; use core::sync::atomic::{AtomicBool, Ordering}; +use bitcoin::Txid; use bitcoin::hashes::Hash; use bitcoin::sighash; use bitcoin::sighash::EcdsaSighashType; use bitcoin::transaction::Transaction; -use bitcoin::Txid; use crate::sign::HTLCDescriptor; use crate::util::dyn_signer::DynSigner; use bitcoin::secp256k1; -use bitcoin::secp256k1::{ecdsa::Signature, Secp256k1}; use bitcoin::secp256k1::{PublicKey, SecretKey}; +use bitcoin::secp256k1::{Secp256k1, ecdsa::Signature}; /// Initial value for revoked commitment downward counter pub const INITIAL_REVOKED_COMMITMENT_NUMBER: u64 = 1 << 48; @@ -200,8 +200,19 @@ impl ChannelSigner for TestChannelSigner { } let mut state = self.state.lock().unwrap(); if !self.disable_all_state_policy_checks { - assert!(idx == state.last_holder_revoked_commitment || idx == state.last_holder_revoked_commitment - 1, "can only revoke the current or next unrevoked commitment - trying {}, last revoked {}", idx, state.last_holder_revoked_commitment); - assert!(idx > state.last_holder_commitment, "cannot revoke the last holder commitment - attempted to revoke {} last commitment {}", idx, state.last_holder_commitment); + assert!( + idx == state.last_holder_revoked_commitment + || idx == state.last_holder_revoked_commitment - 1, + "can only revoke the current or next unrevoked commitment - trying {}, last revoked {}", + idx, + state.last_holder_revoked_commitment + ); + assert!( + idx > state.last_holder_commitment, + "cannot revoke the last holder commitment - attempted to revoke {} last commitment {}", + idx, + state.last_holder_commitment + ); } state.last_holder_revoked_commitment = idx; self.inner.release_commitment_secret(idx) @@ -228,7 +239,13 @@ impl ChannelSigner for TestChannelSigner { fn validate_counterparty_revocation(&self, idx: u64, _secret: &SecretKey) -> Result<(), ()> { let mut state = self.state.lock().unwrap(); if !self.disable_all_state_policy_checks { - assert!(idx == state.last_counterparty_revoked_commitment || idx == state.last_counterparty_revoked_commitment - 1, "expecting to validate the current or next counterparty revocation - trying {}, current {}", idx, state.last_counterparty_revoked_commitment); + assert!( + idx == state.last_counterparty_revoked_commitment + || idx == state.last_counterparty_revoked_commitment - 1, + "expecting to validate the current or next counterparty revocation - trying {}, current {}", + idx, + state.last_counterparty_revoked_commitment + ); } state.last_counterparty_revoked_commitment = idx; Ok(()) @@ -316,8 +333,12 @@ impl EcdsaChannelSigner for TestChannelSigner { && state.last_holder_revoked_commitment - 2 != commitment_number { if !self.disable_revocation_policy_check { - panic!("can only sign the next two unrevoked commitment numbers, revoked={} vs requested={} for {}", - state.last_holder_revoked_commitment, commitment_number, self.inner.channel_keys_id()[0]) + panic!( + "can only sign the next two unrevoked commitment numbers, revoked={} vs requested={} for {}", + state.last_holder_revoked_commitment, + commitment_number, + self.inner.channel_keys_id()[0] + ) } } } @@ -392,8 +413,12 @@ impl EcdsaChannelSigner for TestChannelSigner { && state.last_holder_revoked_commitment - 2 != htlc_descriptor.per_commitment_number { if !self.disable_revocation_policy_check { - panic!("can only sign the next two unrevoked commitment numbers, revoked={} vs requested={} for {}", - state.last_holder_revoked_commitment, htlc_descriptor.per_commitment_number, self.inner.channel_keys_id()[0]) + panic!( + "can only sign the next two unrevoked commitment numbers, revoked={} vs requested={} for {}", + state.last_holder_revoked_commitment, + htlc_descriptor.per_commitment_number, + self.inner.channel_keys_id()[0] + ) } } } diff --git a/lightning/src/util/test_utils.rs b/lightning/src/util/test_utils.rs index d7320ff2ba9..24c0d9f211e 100644 --- a/lightning/src/util/test_utils.rs +++ b/lightning/src/util/test_utils.rs @@ -11,6 +11,8 @@ use crate::blinded_path::message::MessageContext; use crate::blinded_path::message::{BlindedMessagePath, MessageForwardNode}; use crate::blinded_path::payment::{BlindedPaymentPath, ReceiveTlvs}; use crate::chain; +use crate::chain::BlockLocator; +use crate::chain::WatchedOutput; use crate::chain::chaininterface; #[cfg(any(test, feature = "_externalize_tests"))] use crate::chain::chaininterface::FEERATE_FLOOR_SATS_PER_KW; @@ -20,8 +22,6 @@ use crate::chain::channelmonitor::{ ChannelMonitor, ChannelMonitorUpdate, ChannelMonitorUpdateStep, MonitorEvent, }; use crate::chain::transaction::OutPoint; -use crate::chain::BlockLocator; -use crate::chain::WatchedOutput; #[cfg(any(test, feature = "_externalize_tests"))] use crate::ln::chan_utils::CommitmentTransaction; use crate::ln::channel_state::ChannelDetails; @@ -65,15 +65,15 @@ use crate::util::wallet_utils::{ConfirmedUtxo, Utxo, WalletSourceSync}; use bitcoin::amount::Amount; use bitcoin::block::Block; -use bitcoin::constants::genesis_block; use bitcoin::constants::ChainHash; +use bitcoin::constants::genesis_block; use bitcoin::hash_types::Txid; -use bitcoin::hashes::{hex::FromHex, Hash}; +use bitcoin::hashes::{Hash, hex::FromHex}; use bitcoin::network::Network; use bitcoin::script::{Builder, Script, ScriptBuf}; use bitcoin::sighash::{EcdsaSighashType, SighashCache}; use bitcoin::transaction::{Transaction, TxOut}; -use bitcoin::{opcodes, Witness}; +use bitcoin::{Witness, opcodes}; use bitcoin::secp256k1::ecdh::SharedSecret; use bitcoin::secp256k1::ecdsa::{RecoverableSignature, Signature}; @@ -95,8 +95,8 @@ use core::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; use core::task::{Context, Poll, Waker}; use core::time::Duration; -use bitcoin::psbt::Psbt; use bitcoin::Sequence; +use bitcoin::psbt::Psbt; use super::test_channel_signer::SignerOp; @@ -807,18 +807,20 @@ impl Persist for WatchtowerPers ) -> chain::ChannelMonitorUpdateStatus { let res = self.persister.persist_new_channel(monitor_name, data); - assert!(self - .unsigned_justice_tx_data - .lock() - .unwrap() - .insert(data.channel_id(), VecDeque::new()) - .is_none()); - assert!(self - .watchtower_state - .lock() - .unwrap() - .insert(data.channel_id(), new_hash_map()) - .is_none()); + assert!( + self.unsigned_justice_tx_data + .lock() + .unwrap() + .insert(data.channel_id(), VecDeque::new()) + .is_none() + ); + assert!( + self.watchtower_state + .lock() + .unwrap() + .insert(data.channel_id(), new_hash_map()) + .is_none() + ); let initial_counterparty_commitment_tx = data.initial_counterparty_commitment_tx().expect("First and only call expects Some"); @@ -1255,19 +1257,23 @@ impl chaininterface::BroadcasterInterface for TestBroadcaster { assert!(txs.len() <= 2); if txs.len() == 2 { let parent_txid = txs[0].0.compute_txid(); - assert!(txs[1] - .0 - .input - .iter() - .map(|input| input.previous_output.txid) - .any(|txid| txid == parent_txid)); + assert!( + txs[1] + .0 + .input + .iter() + .map(|input| input.previous_output.txid) + .any(|txid| txid == parent_txid) + ); let child_txid = txs[1].0.compute_txid(); - assert!(txs[0] - .0 - .input - .iter() - .map(|input| input.previous_output.txid) - .all(|txid| txid != child_txid)); + assert!( + txs[0] + .0 + .input + .iter() + .map(|input| input.previous_output.txid) + .all(|txid| txid != child_txid) + ); } for (tx, _broadcast_type) in txs { diff --git a/lightning/src/util/transaction_utils.rs b/lightning/src/util/transaction_utils.rs index 5a77fbf06b8..58d05e756ae 100644 --- a/lightning/src/util/transaction_utils.rs +++ b/lightning/src/util/transaction_utils.rs @@ -8,8 +8,8 @@ // licenses. use bitcoin::amount::Amount; -use bitcoin::consensus::encode::VarInt; use bitcoin::consensus::Encodable; +use bitcoin::consensus::encode::VarInt; use bitcoin::script::ScriptBuf; use bitcoin::transaction::{Transaction, TxOut}; @@ -136,14 +136,18 @@ mod tests { fn sort_output_by_bip_test() { let txout1 = TxOut { value: Amount::from_sat(100000000), - script_pubkey: script_from_hex("41046a0765b5865641ce08dd39690aade26dfbf5511430ca428a3089261361cef170e3929a68aee3d8d4848b0c5111b0a37b82b86ad559fd2a745b44d8e8d9dfdc0cac") + script_pubkey: script_from_hex( + "41046a0765b5865641ce08dd39690aade26dfbf5511430ca428a3089261361cef170e3929a68aee3d8d4848b0c5111b0a37b82b86ad559fd2a745b44d8e8d9dfdc0cac", + ), }; let txout1_ = txout1.clone(); // doesn't deserialize cleanly: let txout2 = TxOut { value: Amount::from_sat(2400000000), - script_pubkey: script_from_hex("41044a656f065871a353f216ca26cef8dde2f03e8c16202d2e8ad769f02032cb86a5eb5e56842e92e19141d60a01928f8dd2c875a390f67c1f6c94cfc617c0ea45afac") + script_pubkey: script_from_hex( + "41044a656f065871a353f216ca26cef8dde2f03e8c16202d2e8ad769f02032cb86a5eb5e56842e92e19141d60a01928f8dd2c875a390f67c1f6c94cfc617c0ea45afac", + ), }; let txout2_ = txout2.clone(); @@ -206,8 +210,14 @@ mod tests { (40000000000, "76a9145be32612930b8323add2212a4ec03c1562084f8488ac"), ]; const TXOUT2: [(u64, &str); 2] = [ - (100000000, "41046a0765b5865641ce08dd39690aade26dfbf5511430ca428a3089261361cef170e3929a68aee3d8d4848b0c5111b0a37b82b86ad559fd2a745b44d8e8d9dfdc0cac"), - (2400000000, "41044a656f065871a353f216ca26cef8dde2f03e8c16202d2e8ad769f02032cb86a5eb5e56842e92e19141d60a01928f8dd2c875a390f67c1f6c94cfc617c0ea45afac"), + ( + 100000000, + "41046a0765b5865641ce08dd39690aade26dfbf5511430ca428a3089261361cef170e3929a68aee3d8d4848b0c5111b0a37b82b86ad559fd2a745b44d8e8d9dfdc0cac", + ), + ( + 2400000000, + "41044a656f065871a353f216ca26cef8dde2f03e8c16202d2e8ad769f02032cb86a5eb5e56842e92e19141d60a01928f8dd2c875a390f67c1f6c94cfc617c0ea45afac", + ), ]; bip_txout_tests! { bip69_txout_test_1: TXOUT1.to_vec(), diff --git a/lightning/src/util/wakers.rs b/lightning/src/util/wakers.rs index 1a0f08b5e66..f144a3e3359 100644 --- a/lightning/src/util/wakers.rs +++ b/lightning/src/util/wakers.rs @@ -430,10 +430,12 @@ mod tests { let exit_thread = Arc::new(AtomicBool::new(false)); let exit_thread_clone = Arc::clone(&exit_thread); - thread::spawn(move || loop { - thread_notifier.notify(); - if exit_thread_clone.load(Ordering::SeqCst) { - break; + thread::spawn(move || { + loop { + thread_notifier.notify(); + if exit_thread_clone.load(Ordering::SeqCst) { + break; + } } }); @@ -554,19 +556,22 @@ mod tests { const WAKER_V_TABLE: RawWakerVTable = RawWakerVTable::new(waker_clone, wake, wake_by_ref, drop); unsafe fn wake_by_ref(ptr: *const ()) { let p = ptr as *const Arc; - assert!(!(*p).fetch_or(true, Ordering::SeqCst)); + assert!(!unsafe { (*p).fetch_or(true, Ordering::SeqCst) }); } unsafe fn drop(ptr: *const ()) { let p = ptr as *mut Arc; - let _freed = Box::from_raw(p); + let _freed = unsafe { Box::from_raw(p) }; } unsafe fn wake(ptr: *const ()) { - wake_by_ref(ptr); - drop(ptr); + unsafe { wake_by_ref(ptr) }; + unsafe { drop(ptr) }; } unsafe fn waker_clone(ptr: *const ()) -> RawWaker { let p = ptr as *const Arc; - RawWaker::new(Box::into_raw(Box::new(Arc::clone(&*p))) as *const (), &WAKER_V_TABLE) + RawWaker::new( + Box::into_raw(Box::new(Arc::clone(unsafe { &*p }))) as *const (), + &WAKER_V_TABLE, + ) } fn create_waker() -> (Arc, Waker) { @@ -720,8 +725,10 @@ mod tests { Sleeper::from_futures([notifier_a.get_future(), notifier_b.get_future()]).wait(); // However once we've slept twice, we should no longer have any pending notifications - assert!(!Sleeper::from_futures([notifier_a.get_future(), notifier_b.get_future()]) - .wait_timeout(Duration::from_millis(10))); + assert!( + !Sleeper::from_futures([notifier_a.get_future(), notifier_b.get_future()]) + .wait_timeout(Duration::from_millis(10)) + ); // Test ordering somewhat more. notifier_a.notify(); @@ -767,8 +774,10 @@ mod tests { assert!(callback_a.load(Ordering::SeqCst) && callback_b.load(Ordering::SeqCst)); Sleeper::from_futures([notifier_a.get_future(), notifier_b.get_future()]).wait(); - assert!(!Sleeper::from_futures([notifier_a.get_future(), notifier_b.get_future()]) - .wait_timeout(Duration::from_millis(10))); + assert!( + !Sleeper::from_futures([notifier_a.get_future(), notifier_b.get_future()]) + .wait_timeout(Duration::from_millis(10)) + ); } #[test] diff --git a/lightning/src/util/wallet_utils.rs b/lightning/src/util/wallet_utils.rs index cd79b3615c7..5863d602a48 100644 --- a/lightning/src/util/wallet_utils.rs +++ b/lightning/src/util/wallet_utils.rs @@ -14,8 +14,8 @@ use core::ops::Deref; use core::pin::pin; use core::task; -use crate::chain::chaininterface::fee_for_weight; use crate::chain::ClaimId; +use crate::chain::chaininterface::fee_for_weight; use crate::io_extras::sink; use crate::ln::chan_utils::{ BASE_INPUT_WEIGHT, BASE_TX_SIZE, EMPTY_SCRIPT_SIG_WEIGHT, P2WSH_TXOUT_WEIGHT, @@ -24,8 +24,7 @@ use crate::ln::chan_utils::{ use crate::prelude::*; use crate::sign::{P2TR_KEY_PATH_WITNESS_WEIGHT, P2WPKH_WITNESS_WEIGHT}; use crate::sync::Mutex; -use crate::util::async_poll::dummy_waker; -use crate::util::hash_tables::{new_hash_map, HashMap}; +use crate::util::hash_tables::{HashMap, new_hash_map}; use crate::util::logger::Logger; use crate::util::native_async::{MaybeSend, MaybeSync}; @@ -851,8 +850,7 @@ where target_feerate_sat_per_1000_weight, max_tx_weight, ); - let mut waker = dummy_waker(); - let mut ctx = task::Context::from_waker(&mut waker); + let mut ctx = task::Context::from_waker(core::task::Waker::noop()); match pin!(fut).poll(&mut ctx) { task::Poll::Ready(result) => result, task::Poll::Pending => { @@ -865,8 +863,7 @@ where fn sign_psbt(&self, psbt: Psbt) -> Result { let fut = self.wallet.sign_psbt(psbt); - let mut waker = dummy_waker(); - let mut ctx = task::Context::from_waker(&mut waker); + let mut ctx = task::Context::from_waker(core::task::Waker::noop()); match pin!(fut).poll(&mut ctx) { task::Poll::Ready(result) => result, task::Poll::Pending => { diff --git a/msrv-no-dev-deps-check/Cargo.toml b/msrv-no-dev-deps-check/Cargo.toml index b0620c64331..354ff1dfde3 100644 --- a/msrv-no-dev-deps-check/Cargo.toml +++ b/msrv-no-dev-deps-check/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "msrv-check" version = "0.1.0" -edition = "2021" +edition = "2024" [dependencies] lightning = { path = "../lightning" } diff --git a/no-std-check/Cargo.toml b/no-std-check/Cargo.toml index dba9322f449..84cb222edd9 100644 --- a/no-std-check/Cargo.toml +++ b/no-std-check/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "no-std-check" version = "0.1.0" -edition = "2021" +edition = "2024" [features] default = [] diff --git a/pending_changelog/msrv-1.85.txt b/pending_changelog/msrv-1.85.txt new file mode 100644 index 00000000000..05dd3128c58 --- /dev/null +++ b/pending_changelog/msrv-1.85.txt @@ -0,0 +1,3 @@ +# API Updates + + * The LDK crate ecosystem MSRV has been increased to rustc 1.85.0. diff --git a/possiblyrandom/Cargo.toml b/possiblyrandom/Cargo.toml index 4508f690129..7cf70e8aedc 100644 --- a/possiblyrandom/Cargo.toml +++ b/possiblyrandom/Cargo.toml @@ -7,7 +7,8 @@ repository = "https://github.com/lightningdevkit/rust-lightning/" description = """ A crate that wraps getrandom and always compiles, returning 0s when no randomness is available. """ -edition = "2021" +edition = "2024" +rust-version = "1.85" [package.metadata.docs.rs] all-features = true