diff --git a/lightning/src/ln/anchor_channel_configuration_tests.rs b/lightning/src/ln/anchor_channel_configuration_tests.rs index 24c9b37b5fc..8b020de5925 100644 --- a/lightning/src/ln/anchor_channel_configuration_tests.rs +++ b/lightning/src/ln/anchor_channel_configuration_tests.rs @@ -18,12 +18,23 @@ fn test_inbound_anchors_manual_acceptance() { 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, - &[Some(anchors_cfg.clone()), Some(anchors_cfg.clone()), Some(anchors_manual_accept_cfg.clone())]); + let user_cfgs = [ + Some(anchors_cfg.clone()), + Some(anchors_cfg.clone()), + Some(anchors_manual_accept_cfg.clone()), + ]; + let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &user_cfgs); let nodes = create_network(3, &node_cfgs, &node_chanmgrs); - nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None, None).unwrap(); - let open_channel_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id()); + nodes[0] + .node + .create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None, None) + .unwrap(); + let open_channel_msg = get_event_msg!( + nodes[0], + MessageSendEvent::SendOpenChannel, + nodes[1].node.get_our_node_id() + ); nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_msg); assert!(nodes[1].node.get_and_clear_pending_events().is_empty()); @@ -32,19 +43,22 @@ fn test_inbound_anchors_manual_acceptance() { MessageSendEvent::HandleError { node_id, action } => { assert_eq!(*node_id, nodes[0].node.get_our_node_id()); match action { - ErrorAction::SendErrorMessage { msg } => - assert_eq!(msg.data, "No channels with anchor outputs accepted".to_owned()), + ErrorAction::SendErrorMessage { msg } => { + assert_eq!(msg.data, "No channels with anchor outputs accepted".to_owned()) + }, _ => panic!("Unexpected error action"), } - } + }, _ => panic!("Unexpected event"), } nodes[2].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_msg); let events = nodes[2].node.get_and_clear_pending_events(); match events[0] { - Event::OpenChannelRequest { temporary_channel_id, .. } => - nodes[2].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 23).unwrap(), + Event::OpenChannelRequest { temporary_channel_id, .. } => nodes[2] + .node + .accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 23) + .unwrap(), _ => panic!("Unexpected event"), } get_event_msg!(nodes[2], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id()); @@ -60,27 +74,54 @@ fn test_anchors_zero_fee_htlc_tx_fallback() { let mut anchors_config = test_default_channel_config(); anchors_config.channel_handshake_config.negotiate_anchors_zero_fee_htlc_tx = true; anchors_config.manually_accept_inbound_channels = true; - let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(anchors_config.clone()), Some(anchors_config.clone())]); + let user_cfgs = [Some(anchors_config.clone()), Some(anchors_config.clone())]; + let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs); let nodes = create_network(2, &node_cfgs, &node_chanmgrs); - nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 0, None, None).unwrap(); - let open_channel_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id()); - assert!(open_channel_msg.common_fields.channel_type.as_ref().unwrap().supports_anchors_zero_fee_htlc_tx()); + nodes[0] + .node + .create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 0, None, None) + .unwrap(); + let open_channel_msg = get_event_msg!( + nodes[0], + MessageSendEvent::SendOpenChannel, + nodes[1].node.get_our_node_id() + ); + assert!(open_channel_msg + .common_fields + .channel_type + .as_ref() + .unwrap() + .supports_anchors_zero_fee_htlc_tx()); nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_msg); let events = nodes[1].node.get_and_clear_pending_events(); match events[0] { Event::OpenChannelRequest { temporary_channel_id, .. } => { - nodes[1].node.force_close_broadcasting_latest_txn(&temporary_channel_id, &nodes[0].node.get_our_node_id()).unwrap(); - } + nodes[1] + .node + .force_close_broadcasting_latest_txn( + &temporary_channel_id, + &nodes[0].node.get_our_node_id(), + ) + .unwrap(); + }, _ => panic!("Unexpected event"), } let error_msg = get_err_msg(&nodes[1], &nodes[0].node.get_our_node_id()); nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &error_msg); - let open_channel_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id()); - assert!(!open_channel_msg.common_fields.channel_type.unwrap().supports_anchors_zero_fee_htlc_tx()); + let open_channel_msg = get_event_msg!( + nodes[0], + MessageSendEvent::SendOpenChannel, + nodes[1].node.get_our_node_id() + ); + assert!(!open_channel_msg + .common_fields + .channel_type + .unwrap() + .supports_anchors_zero_fee_htlc_tx()); // Since nodes[1] should not have accepted the channel, it should // not have generated any events. @@ -97,13 +138,30 @@ fn test_update_channel_config() { let _ = create_announced_chan_between_nodes(&nodes, 0, 1); let channel = &nodes[0].node.list_channels()[0]; - nodes[0].node.update_channel_config(&channel.counterparty.node_id, &[channel.channel_id], &user_config.channel_config).unwrap(); + nodes[0] + .node + .update_channel_config( + &channel.counterparty.node_id, + &[channel.channel_id], + &user_config.channel_config, + ) + .unwrap(); let events = nodes[0].node.get_and_clear_pending_msg_events(); assert_eq!(events.len(), 0); user_config.channel_config.forwarding_fee_base_msat += 10; - nodes[0].node.update_channel_config(&channel.counterparty.node_id, &[channel.channel_id], &user_config.channel_config).unwrap(); - assert_eq!(nodes[0].node.list_channels()[0].config.unwrap().forwarding_fee_base_msat, user_config.channel_config.forwarding_fee_base_msat); + nodes[0] + .node + .update_channel_config( + &channel.counterparty.node_id, + &[channel.channel_id], + &user_config.channel_config, + ) + .unwrap(); + assert_eq!( + nodes[0].node.list_channels()[0].config.unwrap().forwarding_fee_base_msat, + user_config.channel_config.forwarding_fee_base_msat + ); let events = nodes[0].node.get_and_clear_pending_msg_events(); assert_eq!(events.len(), 1); match &events[0] { @@ -111,16 +169,33 @@ fn test_update_channel_config() { _ => panic!("expected BroadcastChannelUpdate event"), } - nodes[0].node.update_partial_channel_config(&channel.counterparty.node_id, &[channel.channel_id], &ChannelConfigUpdate::default()).unwrap(); + nodes[0] + .node + .update_partial_channel_config( + &channel.counterparty.node_id, + &[channel.channel_id], + &ChannelConfigUpdate::default(), + ) + .unwrap(); let events = nodes[0].node.get_and_clear_pending_msg_events(); assert_eq!(events.len(), 0); let new_cltv_expiry_delta = user_config.channel_config.cltv_expiry_delta + 6; - nodes[0].node.update_partial_channel_config(&channel.counterparty.node_id, &[channel.channel_id], &ChannelConfigUpdate { - cltv_expiry_delta: Some(new_cltv_expiry_delta), - ..Default::default() - }).unwrap(); - assert_eq!(nodes[0].node.list_channels()[0].config.unwrap().cltv_expiry_delta, new_cltv_expiry_delta); + nodes[0] + .node + .update_partial_channel_config( + &channel.counterparty.node_id, + &[channel.channel_id], + &ChannelConfigUpdate { + cltv_expiry_delta: Some(new_cltv_expiry_delta), + ..Default::default() + }, + ) + .unwrap(); + assert_eq!( + nodes[0].node.list_channels()[0].config.unwrap().cltv_expiry_delta, + new_cltv_expiry_delta + ); let events = nodes[0].node.get_and_clear_pending_msg_events(); assert_eq!(events.len(), 1); match &events[0] { @@ -129,12 +204,25 @@ fn test_update_channel_config() { } let new_fee = user_config.channel_config.forwarding_fee_proportional_millionths + 100; - nodes[0].node.update_partial_channel_config(&channel.counterparty.node_id, &[channel.channel_id], &ChannelConfigUpdate { - forwarding_fee_proportional_millionths: Some(new_fee), - ..Default::default() - }).unwrap(); - assert_eq!(nodes[0].node.list_channels()[0].config.unwrap().cltv_expiry_delta, new_cltv_expiry_delta); - assert_eq!(nodes[0].node.list_channels()[0].config.unwrap().forwarding_fee_proportional_millionths, new_fee); + nodes[0] + .node + .update_partial_channel_config( + &channel.counterparty.node_id, + &[channel.channel_id], + &ChannelConfigUpdate { + forwarding_fee_proportional_millionths: Some(new_fee), + ..Default::default() + }, + ) + .unwrap(); + assert_eq!( + nodes[0].node.list_channels()[0].config.unwrap().cltv_expiry_delta, + new_cltv_expiry_delta + ); + assert_eq!( + nodes[0].node.list_channels()[0].config.unwrap().forwarding_fee_proportional_millionths, + new_fee + ); let events = nodes[0].node.get_and_clear_pending_msg_events(); assert_eq!(events.len(), 1); match &events[0] { @@ -145,19 +233,25 @@ fn test_update_channel_config() { // If we provide a channel_id not associated with the peer, we should get an error and no updates // should be applied to ensure update atomicity as specified in the API docs. let bad_channel_id = ChannelId::v1_from_funding_txid(&[10; 32], 10); - let current_fee = nodes[0].node.list_channels()[0].config.unwrap().forwarding_fee_proportional_millionths; + let current_fee = + nodes[0].node.list_channels()[0].config.unwrap().forwarding_fee_proportional_millionths; let new_fee = current_fee + 100; - assert!( - matches!( - nodes[0].node.update_partial_channel_config(&channel.counterparty.node_id, &[channel.channel_id, bad_channel_id], &ChannelConfigUpdate { + assert!(matches!( + nodes[0].node.update_partial_channel_config( + &channel.counterparty.node_id, + &[channel.channel_id, bad_channel_id], + &ChannelConfigUpdate { forwarding_fee_proportional_millionths: Some(new_fee), ..Default::default() - }), - Err(APIError::ChannelUnavailable { err: _ }), - ) - ); + } + ), + Err(APIError::ChannelUnavailable { err: _ }), + )); // Check that the fee hasn't changed for the channel that exists. - assert_eq!(nodes[0].node.list_channels()[0].config.unwrap().forwarding_fee_proportional_millionths, current_fee); + assert_eq!( + nodes[0].node.list_channels()[0].config.unwrap().forwarding_fee_proportional_millionths, + current_fee + ); let events = nodes[0].node.get_and_clear_pending_msg_events(); assert_eq!(events.len(), 0); } diff --git a/lightning/src/ln/channelmanager_limits_tests.rs b/lightning/src/ln/channelmanager_limits_tests.rs index b005a00d171..0a467707c15 100644 --- a/lightning/src/ln/channelmanager_limits_tests.rs +++ b/lightning/src/ln/channelmanager_limits_tests.rs @@ -1,17 +1,16 @@ -use bitcoin::hashes::Hash; +use crate::events::{ClosureReason, Event, MessageSendEvent, MessageSendEventsProvider}; +use crate::ln::channelmanager; use crate::ln::channelmanager::{PaymentId, PaymentSendFailure, RecipientOnionFields}; use crate::ln::functional_test_utils::*; -use crate::util::errors::APIError; -use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey}; -use crate::events::{Event, MessageSendEvent, MessageSendEventsProvider, ClosureReason}; -use crate::ln::channelmanager; -use crate::ln::ChannelId; -use crate::ln::msgs::{self}; use crate::ln::msgs::ChannelMessageHandler; +use crate::ln::msgs::{self}; +use crate::ln::ChannelId; use crate::prelude::*; -use crate::util::config::ChannelConfig; use crate::sign::EntropySource; - +use crate::util::config::ChannelConfig; +use crate::util::errors::APIError; +use bitcoin::hashes::Hash; +use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey}; #[test] fn test_notify_limits() { @@ -34,10 +33,16 @@ fn test_notify_limits() { // to connect messages with new values chan.0.contents.fee_base_msat *= 2; chan.1.contents.fee_base_msat *= 2; - let node_a_chan_info = nodes[0].node.list_channels_with_counterparty( - &nodes[1].node.get_our_node_id()).pop().unwrap(); - let node_b_chan_info = nodes[1].node.list_channels_with_counterparty( - &nodes[0].node.get_our_node_id()).pop().unwrap(); + let node_a_chan_info = nodes[0] + .node + .list_channels_with_counterparty(&nodes[1].node.get_our_node_id()) + .pop() + .unwrap(); + let node_b_chan_info = nodes[1] + .node + .list_channels_with_counterparty(&nodes[0].node.get_our_node_id()) + .pop() + .unwrap(); // The first two nodes (which opened a channel) should now require fresh persistence assert!(nodes[0].node.get_event_or_persistence_needed_future().poll_is_complete()); @@ -70,9 +75,20 @@ fn test_notify_limits() { // An earlier version of handle_channel_update didn't check the directionality of the // update message and would always update the local fee info, even if our peer was // (spuriously) forwarding us our own channel_update. - let as_node_one = nodes[0].node.get_our_node_id().serialize()[..] < nodes[1].node.get_our_node_id().serialize()[..]; - let as_update = if as_node_one == (chan.0.contents.flags & 1 == 0 /* chan.0 is from node one */) { &chan.0 } else { &chan.1 }; - let bs_update = if as_node_one == (chan.0.contents.flags & 1 == 0 /* chan.0 is from node one */) { &chan.1 } else { &chan.0 }; + let as_node_one = nodes[0].node.get_our_node_id().serialize()[..] + < nodes[1].node.get_our_node_id().serialize()[..]; + let as_update = if as_node_one == (chan.0.contents.flags & 1 == 0/* chan.0 is from node one */) + { + &chan.0 + } else { + &chan.1 + }; + let bs_update = if as_node_one == (chan.0.contents.flags & 1 == 0/* chan.0 is from node one */) + { + &chan.1 + } else { + &chan.0 + }; // First deliver each peers' own message, checking that the node doesn't need to be // persisted and that its channel info remains the same. @@ -105,10 +121,19 @@ fn test_drop_disconnected_peers_when_removing_channels() { nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id()); nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id()); - nodes[0].node.force_close_broadcasting_latest_txn(&chan.2, &nodes[1].node.get_our_node_id()).unwrap(); + nodes[0] + .node + .force_close_broadcasting_latest_txn(&chan.2, &nodes[1].node.get_our_node_id()) + .unwrap(); check_closed_broadcast!(nodes[0], true); check_added_monitors!(nodes[0], 1); - check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed, [nodes[1].node.get_our_node_id()], 100000); + check_closed_event!( + nodes[0], + 1, + ClosureReason::HolderForceClosed, + [nodes[1].node.get_our_node_id()], + 100000 + ); { // Assert that nodes[1] is awaiting removal for nodes[0] once nodes[1] has been @@ -137,13 +162,25 @@ fn test_outpoint_to_peer_coverage() { let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]); let nodes = create_network(2, &node_cfgs, &node_chanmgrs); - nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1_000_000, 500_000_000, 42, None, None).unwrap(); - let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id()); + nodes[0] + .node + .create_channel(nodes[1].node.get_our_node_id(), 1_000_000, 500_000_000, 42, None, None) + .unwrap(); + let open_channel = get_event_msg!( + nodes[0], + MessageSendEvent::SendOpenChannel, + nodes[1].node.get_our_node_id() + ); nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel); - let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id()); + let accept_channel = get_event_msg!( + nodes[1], + MessageSendEvent::SendAcceptChannel, + nodes[0].node.get_our_node_id() + ); nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel); - let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 1_000_000, 42); + let (temporary_channel_id, tx, funding_output) = + create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 1_000_000, 42); let channel_id = ChannelId::from_bytes(tx.txid().to_byte_array()); { // Ensure that the `outpoint_to_peer` map is empty until either party has received the @@ -152,7 +189,14 @@ fn test_outpoint_to_peer_coverage() { assert_eq!(nodes[1].node.outpoint_to_peer.lock().unwrap().len(), 0); } - nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap(); + nodes[0] + .node + .funding_transaction_generated( + &temporary_channel_id, + &nodes[1].node.get_our_node_id(), + tx.clone(), + ) + .unwrap(); { // Assert that `nodes[0]`'s `outpoint_to_peer` map is populated with the channel as soon as // as it has the funding transaction. @@ -163,7 +207,11 @@ fn test_outpoint_to_peer_coverage() { assert_eq!(nodes[1].node.outpoint_to_peer.lock().unwrap().len(), 0); - let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id()); + let funding_created_msg = get_event_msg!( + nodes[0], + MessageSendEvent::SendFundingCreated, + nodes[1].node.get_our_node_id() + ); nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg); { @@ -181,20 +229,34 @@ fn test_outpoint_to_peer_coverage() { assert!(nodes_1_lock.contains_key(&funding_output)); } check_added_monitors!(nodes[1], 1); - let funding_signed = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id()); + let funding_signed = get_event_msg!( + nodes[1], + MessageSendEvent::SendFundingSigned, + nodes[0].node.get_our_node_id() + ); nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed); check_added_monitors!(nodes[0], 1); expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id()); - let (channel_ready, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx); - let (announcement, nodes_0_update, nodes_1_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready); + let (channel_ready, _) = + create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx); + let (announcement, nodes_0_update, nodes_1_update) = + create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready); update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &nodes_0_update, &nodes_1_update); nodes[0].node.close_channel(&channel_id, &nodes[1].node.get_our_node_id()).unwrap(); - nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id())); - let nodes_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id()); + nodes[1].node.handle_shutdown( + &nodes[0].node.get_our_node_id(), + &get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id()), + ); + let nodes_1_shutdown = + get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id()); nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &nodes_1_shutdown); - let closing_signed_node_0 = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id()); + let closing_signed_node_0 = get_event_msg!( + nodes[0], + MessageSendEvent::SendClosingSigned, + nodes[1].node.get_our_node_id() + ); nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &closing_signed_node_0); { // Assert that the channel is kept in the `outpoint_to_peer` map for both nodes until the @@ -216,7 +278,14 @@ fn test_outpoint_to_peer_coverage() { assert!(nodes_1_lock.contains_key(&funding_output)); } - nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &get_event_msg!(nodes[1], MessageSendEvent::SendClosingSigned, nodes[0].node.get_our_node_id())); + nodes[0].node.handle_closing_signed( + &nodes[1].node.get_our_node_id(), + &get_event_msg!( + nodes[1], + MessageSendEvent::SendClosingSigned, + nodes[0].node.get_our_node_id() + ), + ); { // `nodes[0]` accepts `nodes[1]`'s proposed fee for the closing transaction, and // therefore has all it needs to fully close the channel (both signatures for the @@ -232,33 +301,58 @@ fn test_outpoint_to_peer_coverage() { assert!(nodes_1_lock.contains_key(&funding_output)); } - let (_nodes_0_update, closing_signed_node_0) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id()); + let (_nodes_0_update, closing_signed_node_0) = + get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id()); - nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &closing_signed_node_0.unwrap()); + nodes[1] + .node + .handle_closing_signed(&nodes[0].node.get_our_node_id(), &closing_signed_node_0.unwrap()); { // Assert that the channel has now been removed from both parties `outpoint_to_peer` map once // they both have everything required to fully close the channel. assert_eq!(nodes[1].node.outpoint_to_peer.lock().unwrap().len(), 0); } - let (_nodes_1_update, _none) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id()); - - check_closed_event!(nodes[0], 1, ClosureReason::LocallyInitiatedCooperativeClosure, [nodes[1].node.get_our_node_id()], 1000000); - check_closed_event!(nodes[1], 1, ClosureReason::CounterpartyInitiatedCooperativeClosure, [nodes[0].node.get_our_node_id()], 1000000); + let (_nodes_1_update, _none) = + get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id()); + + check_closed_event!( + nodes[0], + 1, + ClosureReason::LocallyInitiatedCooperativeClosure, + [nodes[1].node.get_our_node_id()], + 1000000 + ); + check_closed_event!( + nodes[1], + 1, + ClosureReason::CounterpartyInitiatedCooperativeClosure, + [nodes[0].node.get_our_node_id()], + 1000000 + ); } - -fn check_not_connected_to_peer_error(res_err: Result, expected_public_key: PublicKey) { +fn check_not_connected_to_peer_error( + res_err: Result, expected_public_key: PublicKey, +) { let expected_message = format!("Not connected to node: {}", expected_public_key); check_api_error_message(expected_message, res_err) } fn check_unkown_peer_error(res_err: Result, expected_public_key: PublicKey) { - let expected_message = format!("Can't find a peer matching the passed counterparty node_id {}", expected_public_key); + let expected_message = format!( + "Can't find a peer matching the passed counterparty node_id {}", + expected_public_key + ); check_api_error_message(expected_message, res_err) } -fn check_channel_unavailable_error(res_err: Result, expected_channel_id: ChannelId, peer_node_id: PublicKey) { - let expected_message = format!("Channel with id {} not found for the passed counterparty node_id {}", expected_channel_id, peer_node_id); +fn check_channel_unavailable_error( + res_err: Result, expected_channel_id: ChannelId, peer_node_id: PublicKey, +) { + let expected_message = format!( + "Channel with id {} not found for the passed counterparty node_id {}", + expected_channel_id, peer_node_id + ); check_api_error_message(expected_message, res_err) } @@ -292,23 +386,56 @@ fn test_api_calls_with_unkown_counterparty_node() { // Dummy values let channel_id = ChannelId::from_bytes([4; 32]); - let unkown_public_key = PublicKey::from_secret_key(&Secp256k1::signing_only(), &SecretKey::from_slice(&[42; 32]).unwrap()); + let unkown_public_key = PublicKey::from_secret_key( + &Secp256k1::signing_only(), + &SecretKey::from_slice(&[42; 32]).unwrap(), + ); let intercept_id = super::InterceptId([0; 32]); // Test the API functions. - check_not_connected_to_peer_error(nodes[0].node.create_channel(unkown_public_key, 1_000_000, 500_000_000, 42, None, None), unkown_public_key); + check_not_connected_to_peer_error( + nodes[0].node.create_channel(unkown_public_key, 1_000_000, 500_000_000, 42, None, None), + unkown_public_key, + ); - check_unkown_peer_error(nodes[0].node.accept_inbound_channel(&channel_id, &unkown_public_key, 42), unkown_public_key); + check_unkown_peer_error( + nodes[0].node.accept_inbound_channel(&channel_id, &unkown_public_key, 42), + unkown_public_key, + ); - check_unkown_peer_error(nodes[0].node.close_channel(&channel_id, &unkown_public_key), unkown_public_key); + check_unkown_peer_error( + nodes[0].node.close_channel(&channel_id, &unkown_public_key), + unkown_public_key, + ); - check_unkown_peer_error(nodes[0].node.force_close_broadcasting_latest_txn(&channel_id, &unkown_public_key), unkown_public_key); + check_unkown_peer_error( + nodes[0].node.force_close_broadcasting_latest_txn(&channel_id, &unkown_public_key), + unkown_public_key, + ); - check_unkown_peer_error(nodes[0].node.force_close_without_broadcasting_txn(&channel_id, &unkown_public_key), unkown_public_key); + check_unkown_peer_error( + nodes[0].node.force_close_without_broadcasting_txn(&channel_id, &unkown_public_key), + unkown_public_key, + ); - check_unkown_peer_error(nodes[0].node.forward_intercepted_htlc(intercept_id, &channel_id, unkown_public_key, 1_000_000), unkown_public_key); + check_unkown_peer_error( + nodes[0].node.forward_intercepted_htlc( + intercept_id, + &channel_id, + unkown_public_key, + 1_000_000, + ), + unkown_public_key, + ); - check_unkown_peer_error(nodes[0].node.update_channel_config(&unkown_public_key, &[channel_id], &ChannelConfig::default()), unkown_public_key); + check_unkown_peer_error( + nodes[0].node.update_channel_config( + &unkown_public_key, + &[channel_id], + &ChannelConfig::default(), + ), + unkown_public_key, + ); } #[test] @@ -328,17 +455,50 @@ fn test_api_calls_with_unavailable_channel() { let channel_id = ChannelId::from_bytes([4; 32]); // Test the API functions. - check_api_misuse_error(nodes[0].node.accept_inbound_channel(&channel_id, &counterparty_node_id, 42)); - - check_channel_unavailable_error(nodes[0].node.close_channel(&channel_id, &counterparty_node_id), channel_id, counterparty_node_id); + check_api_misuse_error(nodes[0].node.accept_inbound_channel( + &channel_id, + &counterparty_node_id, + 42, + )); + + check_channel_unavailable_error( + nodes[0].node.close_channel(&channel_id, &counterparty_node_id), + channel_id, + counterparty_node_id, + ); - check_channel_unavailable_error(nodes[0].node.force_close_broadcasting_latest_txn(&channel_id, &counterparty_node_id), channel_id, counterparty_node_id); + check_channel_unavailable_error( + nodes[0].node.force_close_broadcasting_latest_txn(&channel_id, &counterparty_node_id), + channel_id, + counterparty_node_id, + ); - check_channel_unavailable_error(nodes[0].node.force_close_without_broadcasting_txn(&channel_id, &counterparty_node_id), channel_id, counterparty_node_id); + check_channel_unavailable_error( + nodes[0].node.force_close_without_broadcasting_txn(&channel_id, &counterparty_node_id), + channel_id, + counterparty_node_id, + ); - check_channel_unavailable_error(nodes[0].node.forward_intercepted_htlc(channelmanager::InterceptId([0; 32]), &channel_id, counterparty_node_id, 1_000_000), channel_id, counterparty_node_id); + check_channel_unavailable_error( + nodes[0].node.forward_intercepted_htlc( + channelmanager::InterceptId([0; 32]), + &channel_id, + counterparty_node_id, + 1_000_000, + ), + channel_id, + counterparty_node_id, + ); - check_channel_unavailable_error(nodes[0].node.update_channel_config(&counterparty_node_id, &[channel_id], &ChannelConfig::default()), channel_id, counterparty_node_id); + check_channel_unavailable_error( + nodes[0].node.update_channel_config( + &counterparty_node_id, + &[channel_id], + &ChannelConfig::default(), + ), + channel_id, + counterparty_node_id, + ); } #[test] @@ -351,58 +511,116 @@ fn test_connection_limiting() { // Note that create_network connects the nodes together for us - nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None, None).unwrap(); - let mut open_channel_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id()); + nodes[0] + .node + .create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None, None) + .unwrap(); + let mut open_channel_msg = get_event_msg!( + nodes[0], + MessageSendEvent::SendOpenChannel, + nodes[1].node.get_our_node_id() + ); let mut funding_tx = None; for idx in 0..channelmanager::MAX_UNFUNDED_CHANS_PER_PEER { nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_msg); - let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id()); + let accept_channel = get_event_msg!( + nodes[1], + MessageSendEvent::SendAcceptChannel, + nodes[0].node.get_our_node_id() + ); if idx == 0 { nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel); - let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100_000, 42); + let (temporary_channel_id, tx, _) = create_funding_transaction( + &nodes[0], + &nodes[1].node.get_our_node_id(), + 100_000, + 42, + ); funding_tx = Some(tx.clone()); - nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx).unwrap(); - let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id()); - - nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg); + nodes[0] + .node + .funding_transaction_generated( + &temporary_channel_id, + &nodes[1].node.get_our_node_id(), + tx, + ) + .unwrap(); + let funding_created_msg = get_event_msg!( + nodes[0], + MessageSendEvent::SendFundingCreated, + nodes[1].node.get_our_node_id() + ); + + nodes[1] + .node + .handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg); check_added_monitors!(nodes[1], 1); expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id()); - let funding_signed = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id()); + let funding_signed = get_event_msg!( + nodes[1], + MessageSendEvent::SendFundingSigned, + nodes[0].node.get_our_node_id() + ); nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed); check_added_monitors!(nodes[0], 1); expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id()); } - open_channel_msg.common_fields.temporary_channel_id = ChannelId::temporary_from_entropy_source(&nodes[0].keys_manager); + open_channel_msg.common_fields.temporary_channel_id = + ChannelId::temporary_from_entropy_source(&nodes[0].keys_manager); } // A MAX_UNFUNDED_CHANS_PER_PEER + 1 channel will be summarily rejected - open_channel_msg.common_fields.temporary_channel_id = ChannelId::temporary_from_entropy_source( - &nodes[0].keys_manager); + open_channel_msg.common_fields.temporary_channel_id = + ChannelId::temporary_from_entropy_source(&nodes[0].keys_manager); nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_msg); - assert_eq!(get_err_msg(&nodes[1], &nodes[0].node.get_our_node_id()).channel_id, - open_channel_msg.common_fields.temporary_channel_id); + assert_eq!( + get_err_msg(&nodes[1], &nodes[0].node.get_our_node_id()).channel_id, + open_channel_msg.common_fields.temporary_channel_id + ); // Further, because all of our channels with nodes[0] are inbound, and none of them funded, // it doesn't count as a "protected" peer, i.e. it counts towards the MAX_NO_CHANNEL_PEERS // limit. let mut peer_pks = Vec::with_capacity(channelmanager::MAX_NO_CHANNEL_PEERS); for _ in 1..channelmanager::MAX_NO_CHANNEL_PEERS { - let random_pk = PublicKey::from_secret_key(&nodes[0].node.secp_ctx, - &SecretKey::from_slice(&nodes[1].keys_manager.get_secure_random_bytes()).unwrap()); + let random_pk = PublicKey::from_secret_key( + &nodes[0].node.secp_ctx, + &SecretKey::from_slice(&nodes[1].keys_manager.get_secure_random_bytes()).unwrap(), + ); peer_pks.push(random_pk); - nodes[1].node.peer_connected(&random_pk, &msgs::Init { - features: nodes[0].node.init_features(), networks: None, remote_network_address: None - }, true).unwrap(); + nodes[1] + .node + .peer_connected( + &random_pk, + &msgs::Init { + features: nodes[0].node.init_features(), + networks: None, + remote_network_address: None, + }, + true, + ) + .unwrap(); } - let last_random_pk = PublicKey::from_secret_key(&nodes[0].node.secp_ctx, - &SecretKey::from_slice(&nodes[1].keys_manager.get_secure_random_bytes()).unwrap()); - nodes[1].node.peer_connected(&last_random_pk, &msgs::Init { - features: nodes[0].node.init_features(), networks: None, remote_network_address: None - }, true).unwrap_err(); + let last_random_pk = PublicKey::from_secret_key( + &nodes[0].node.secp_ctx, + &SecretKey::from_slice(&nodes[1].keys_manager.get_secure_random_bytes()).unwrap(), + ); + nodes[1] + .node + .peer_connected( + &last_random_pk, + &msgs::Init { + features: nodes[0].node.init_features(), + networks: None, + remote_network_address: None, + }, + true, + ) + .unwrap_err(); // Also importantly, because nodes[0] isn't "protected", we will refuse a reconnection from // them if we have too many un-channel'd peers. @@ -410,19 +628,49 @@ fn test_connection_limiting() { let chan_closed_events = nodes[1].node.get_and_clear_pending_events(); assert_eq!(chan_closed_events.len(), channelmanager::MAX_UNFUNDED_CHANS_PER_PEER - 1); for ev in chan_closed_events { - if let Event::ChannelClosed { .. } = ev { } else { panic!(); } + if let Event::ChannelClosed { .. } = ev { + } else { + panic!(); + } } - nodes[1].node.peer_connected(&last_random_pk, &msgs::Init { - features: nodes[0].node.init_features(), networks: None, remote_network_address: None - }, true).unwrap(); - nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { - features: nodes[0].node.init_features(), networks: None, remote_network_address: None - }, true).unwrap_err(); + nodes[1] + .node + .peer_connected( + &last_random_pk, + &msgs::Init { + features: nodes[0].node.init_features(), + networks: None, + remote_network_address: None, + }, + true, + ) + .unwrap(); + nodes[1] + .node + .peer_connected( + &nodes[0].node.get_our_node_id(), + &msgs::Init { + features: nodes[0].node.init_features(), + networks: None, + remote_network_address: None, + }, + true, + ) + .unwrap_err(); // but of course if the connection is outbound its allowed... - nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { - features: nodes[0].node.init_features(), networks: None, remote_network_address: None - }, false).unwrap(); + nodes[1] + .node + .peer_connected( + &nodes[0].node.get_our_node_id(), + &msgs::Init { + features: nodes[0].node.init_features(), + networks: None, + remote_network_address: None, + }, + false, + ) + .unwrap(); nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id()); // Now nodes[0] is disconnected but still has a pending, un-funded channel lying around. @@ -432,11 +680,14 @@ fn test_connection_limiting() { for i in 0..channelmanager::MAX_UNFUNDED_CHANNEL_PEERS - 1 { nodes[1].node.handle_open_channel(&peer_pks[i], &open_channel_msg); get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, peer_pks[i]); - open_channel_msg.common_fields.temporary_channel_id = ChannelId::temporary_from_entropy_source(&nodes[0].keys_manager); + open_channel_msg.common_fields.temporary_channel_id = + ChannelId::temporary_from_entropy_source(&nodes[0].keys_manager); } nodes[1].node.handle_open_channel(&last_random_pk, &open_channel_msg); - assert_eq!(get_err_msg(&nodes[1], &last_random_pk).channel_id, - open_channel_msg.common_fields.temporary_channel_id); + assert_eq!( + get_err_msg(&nodes[1], &last_random_pk).channel_id, + open_channel_msg.common_fields.temporary_channel_id + ); // Of course, however, outbound channels are always allowed nodes[1].node.create_channel(last_random_pk, 100_000, 0, 42, None, None).unwrap(); @@ -445,10 +696,23 @@ fn test_connection_limiting() { // If we fund the first channel, nodes[0] has a live on-chain channel with us, it is now // "protected" and can connect again. mine_transaction(&nodes[1], funding_tx.as_ref().unwrap()); - nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { - features: nodes[0].node.init_features(), networks: None, remote_network_address: None - }, true).unwrap(); - get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id()); + nodes[1] + .node + .peer_connected( + &nodes[0].node.get_our_node_id(), + &msgs::Init { + features: nodes[0].node.init_features(), + networks: None, + remote_network_address: None, + }, + true, + ) + .unwrap(); + get_event_msg!( + nodes[1], + MessageSendEvent::SendChannelReestablish, + nodes[0].node.get_our_node_id() + ); // Further, because the first channel was funded, we can open another channel with // last_random_pk. @@ -466,29 +730,48 @@ fn test_outbound_chans_unlimited() { // Note that create_network connects the nodes together for us - nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None, None).unwrap(); - let mut open_channel_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id()); + nodes[0] + .node + .create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None, None) + .unwrap(); + let mut open_channel_msg = get_event_msg!( + nodes[0], + MessageSendEvent::SendOpenChannel, + nodes[1].node.get_our_node_id() + ); for _ in 0..channelmanager::MAX_UNFUNDED_CHANS_PER_PEER { nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_msg); - get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id()); - open_channel_msg.common_fields.temporary_channel_id = ChannelId::temporary_from_entropy_source(&nodes[0].keys_manager); + get_event_msg!( + nodes[1], + MessageSendEvent::SendAcceptChannel, + nodes[0].node.get_our_node_id() + ); + open_channel_msg.common_fields.temporary_channel_id = + ChannelId::temporary_from_entropy_source(&nodes[0].keys_manager); } // Once we have MAX_UNFUNDED_CHANS_PER_PEER unfunded channels, new inbound channels will be // rejected. nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_msg); - assert_eq!(get_err_msg(&nodes[1], &nodes[0].node.get_our_node_id()).channel_id, - open_channel_msg.common_fields.temporary_channel_id); + assert_eq!( + get_err_msg(&nodes[1], &nodes[0].node.get_our_node_id()).channel_id, + open_channel_msg.common_fields.temporary_channel_id + ); // but we can still open an outbound channel. - nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 100_000, 0, 42, None, None).unwrap(); + nodes[1] + .node + .create_channel(nodes[0].node.get_our_node_id(), 100_000, 0, 42, None, None) + .unwrap(); get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id()); // but even with such an outbound channel, additional inbound channels will still fail. nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_msg); - assert_eq!(get_err_msg(&nodes[1], &nodes[0].node.get_our_node_id()).channel_id, - open_channel_msg.common_fields.temporary_channel_id); + assert_eq!( + get_err_msg(&nodes[1], &nodes[0].node.get_our_node_id()).channel_id, + open_channel_msg.common_fields.temporary_channel_id + ); } #[test] @@ -504,57 +787,101 @@ fn test_0conf_limiting() { // Note that create_network connects the nodes together for us - nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None, None).unwrap(); - let mut open_channel_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id()); + nodes[0] + .node + .create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None, None) + .unwrap(); + let mut open_channel_msg = get_event_msg!( + nodes[0], + MessageSendEvent::SendOpenChannel, + nodes[1].node.get_our_node_id() + ); // First, get us up to MAX_UNFUNDED_CHANNEL_PEERS so we can test at the edge for _ in 0..channelmanager::MAX_UNFUNDED_CHANNEL_PEERS - 1 { - let random_pk = PublicKey::from_secret_key(&nodes[0].node.secp_ctx, - &SecretKey::from_slice(&nodes[1].keys_manager.get_secure_random_bytes()).unwrap()); - nodes[1].node.peer_connected(&random_pk, &msgs::Init { - features: nodes[0].node.init_features(), networks: None, remote_network_address: None - }, true).unwrap(); + let random_pk = PublicKey::from_secret_key( + &nodes[0].node.secp_ctx, + &SecretKey::from_slice(&nodes[1].keys_manager.get_secure_random_bytes()).unwrap(), + ); + nodes[1] + .node + .peer_connected( + &random_pk, + &msgs::Init { + features: nodes[0].node.init_features(), + networks: None, + remote_network_address: None, + }, + true, + ) + .unwrap(); nodes[1].node.handle_open_channel(&random_pk, &open_channel_msg); let events = nodes[1].node.get_and_clear_pending_events(); match events[0] { Event::OpenChannelRequest { temporary_channel_id, .. } => { - nodes[1].node.accept_inbound_channel(&temporary_channel_id, &random_pk, 23).unwrap(); - } + nodes[1] + .node + .accept_inbound_channel(&temporary_channel_id, &random_pk, 23) + .unwrap(); + }, _ => panic!("Unexpected event"), } get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, random_pk); - open_channel_msg.common_fields.temporary_channel_id = ChannelId::temporary_from_entropy_source(&nodes[0].keys_manager); + open_channel_msg.common_fields.temporary_channel_id = + ChannelId::temporary_from_entropy_source(&nodes[0].keys_manager); } // If we try to accept a channel from another peer non-0conf it will fail. - let last_random_pk = PublicKey::from_secret_key(&nodes[0].node.secp_ctx, - &SecretKey::from_slice(&nodes[1].keys_manager.get_secure_random_bytes()).unwrap()); - nodes[1].node.peer_connected(&last_random_pk, &msgs::Init { - features: nodes[0].node.init_features(), networks: None, remote_network_address: None - }, true).unwrap(); + let last_random_pk = PublicKey::from_secret_key( + &nodes[0].node.secp_ctx, + &SecretKey::from_slice(&nodes[1].keys_manager.get_secure_random_bytes()).unwrap(), + ); + nodes[1] + .node + .peer_connected( + &last_random_pk, + &msgs::Init { + features: nodes[0].node.init_features(), + networks: None, + remote_network_address: None, + }, + true, + ) + .unwrap(); nodes[1].node.handle_open_channel(&last_random_pk, &open_channel_msg); let events = nodes[1].node.get_and_clear_pending_events(); match events[0] { Event::OpenChannelRequest { temporary_channel_id, .. } => { match nodes[1].node.accept_inbound_channel(&temporary_channel_id, &last_random_pk, 23) { - Err(APIError::APIMisuseError { err }) => - assert_eq!(err, "Too many peers with unfunded channels, refusing to accept new ones"), + Err(APIError::APIMisuseError { err }) => assert_eq!( + err, + "Too many peers with unfunded channels, refusing to accept new ones" + ), _ => panic!(), } - } + }, _ => panic!("Unexpected event"), } - assert_eq!(get_err_msg(&nodes[1], &last_random_pk).channel_id, - open_channel_msg.common_fields.temporary_channel_id); + assert_eq!( + get_err_msg(&nodes[1], &last_random_pk).channel_id, + open_channel_msg.common_fields.temporary_channel_id + ); // ...however if we accept the same channel 0conf it should work just fine. nodes[1].node.handle_open_channel(&last_random_pk, &open_channel_msg); let events = nodes[1].node.get_and_clear_pending_events(); match events[0] { Event::OpenChannelRequest { temporary_channel_id, .. } => { - nodes[1].node.accept_inbound_channel_from_trusted_peer_0conf(&temporary_channel_id, &last_random_pk, 23).unwrap(); - } + nodes[1] + .node + .accept_inbound_channel_from_trusted_peer_0conf( + &temporary_channel_id, + &last_random_pk, + 23, + ) + .unwrap(); + }, _ => panic!("Unexpected event"), } get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, last_random_pk); @@ -572,10 +899,19 @@ fn test_trigger_lnd_force_close() { let (_, _, chan_id, funding_tx) = create_announced_chan_between_nodes(&nodes, 0, 1); nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id()); nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id()); - nodes[0].node.force_close_broadcasting_latest_txn(&chan_id, &nodes[1].node.get_our_node_id()).unwrap(); + nodes[0] + .node + .force_close_broadcasting_latest_txn(&chan_id, &nodes[1].node.get_our_node_id()) + .unwrap(); check_closed_broadcast(&nodes[0], 1, true); check_added_monitors(&nodes[0], 1); - check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed, [nodes[1].node.get_our_node_id()], 100000); + check_closed_event!( + nodes[0], + 1, + ClosureReason::HolderForceClosed, + [nodes[1].node.get_our_node_id()], + 100000 + ); { let txn = nodes[0].tx_broadcaster.txn_broadcast(); assert_eq!(txn.len(), 1); @@ -585,17 +921,39 @@ fn test_trigger_lnd_force_close() { // Since they're disconnected, Bob won't receive Alice's `Error` message. Reconnect them // such that Bob sends a `ChannelReestablish` to Alice since the channel is still open from // their side. - nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { - features: nodes[1].node.init_features(), networks: None, remote_network_address: None - }, true).unwrap(); - nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { - features: nodes[0].node.init_features(), networks: None, remote_network_address: None - }, false).unwrap(); + nodes[0] + .node + .peer_connected( + &nodes[1].node.get_our_node_id(), + &msgs::Init { + features: nodes[1].node.init_features(), + networks: None, + remote_network_address: None, + }, + true, + ) + .unwrap(); + nodes[1] + .node + .peer_connected( + &nodes[0].node.get_our_node_id(), + &msgs::Init { + features: nodes[0].node.init_features(), + networks: None, + remote_network_address: None, + }, + false, + ) + .unwrap(); assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty()); let channel_reestablish = get_event_msg!( - nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id() + nodes[1], + MessageSendEvent::SendChannelReestablish, + nodes[0].node.get_our_node_id() ); - nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &channel_reestablish); + nodes[0] + .node + .handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &channel_reestablish); // Alice should respond with an error since the channel isn't known, but a bogus // `ChannelReestablish` should be sent first, such that we actually trigger Bob to force @@ -607,13 +965,22 @@ fn test_trigger_lnd_force_close() { assert_eq!(msg.next_local_commitment_number, 0); assert_eq!(msg.next_remote_commitment_number, 0); nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &msg); - } else { panic!() }; + } else { + panic!() + }; check_closed_broadcast(&nodes[1], 1, true); check_added_monitors(&nodes[1], 1); let expected_close_reason = ClosureReason::ProcessingError { - err: "Peer sent an invalid channel_reestablish to force close in a non-standard way".to_string() + err: "Peer sent an invalid channel_reestablish to force close in a non-standard way" + .to_string(), }; - check_closed_event!(nodes[1], 1, expected_close_reason, [nodes[0].node.get_our_node_id()], 100000); + check_closed_event!( + nodes[1], + 1, + expected_close_reason, + [nodes[0].node.get_our_node_id()], + 100000 + ); { let txn = nodes[1].tx_broadcaster.txn_broadcast(); assert_eq!(txn.len(), 1); @@ -644,13 +1011,22 @@ fn test_multi_hop_missing_secret() { route.paths[1].hops[0].short_channel_id = chan_2_id; route.paths[1].hops[1].short_channel_id = chan_4_id; - match nodes[0].node.send_payment_with_route(&route, payment_hash, - RecipientOnionFields::spontaneous_empty(), PaymentId(payment_hash.0)) - .unwrap_err() { + match nodes[0] + .node + .send_payment_with_route( + &route, + payment_hash, + RecipientOnionFields::spontaneous_empty(), + PaymentId(payment_hash.0), + ) + .unwrap_err() + { PaymentSendFailure::ParameterError(APIError::APIMisuseError { ref err }) => { - assert!(regex::Regex::new(r"Payment secret is required for multi-path payments").unwrap().is_match(err)) + assert!(regex::Regex::new(r"Payment secret is required for multi-path payments") + .unwrap() + .is_match(err)) }, - _ => panic!("unexpected error") + _ => panic!("unexpected error"), } } @@ -663,9 +1039,18 @@ fn test_channel_update_cached() { let chan = create_announced_chan_between_nodes(&nodes, 0, 1); - nodes[0].node.force_close_channel_with_peer(&chan.2, &nodes[1].node.get_our_node_id(), None, true).unwrap(); + nodes[0] + .node + .force_close_channel_with_peer(&chan.2, &nodes[1].node.get_our_node_id(), None, true) + .unwrap(); check_added_monitors!(nodes[0], 1); - check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed, [nodes[1].node.get_our_node_id()], 100000); + check_closed_event!( + nodes[0], + 1, + ClosureReason::HolderForceClosed, + [nodes[1].node.get_our_node_id()], + 100000 + ); // Confirm that the channel_update was not sent immediately to node[1] but was cached. let node_1_events = nodes[1].node.get_and_clear_pending_msg_events(); @@ -673,7 +1058,7 @@ fn test_channel_update_cached() { { // Assert that ChannelUpdate message has been added to node[0] pending broadcast messages - let pending_broadcast_messages= nodes[0].node.pending_broadcast_messages.lock().unwrap(); + let pending_broadcast_messages = nodes[0].node.pending_broadcast_messages.lock().unwrap(); assert_eq!(pending_broadcast_messages.len(), 1); } @@ -688,12 +1073,30 @@ fn test_channel_update_cached() { assert_eq!(node_0_events.len(), 0); // Now we reconnect to a peer - nodes[0].node.peer_connected(&nodes[2].node.get_our_node_id(), &msgs::Init { - features: nodes[2].node.init_features(), networks: None, remote_network_address: None - }, true).unwrap(); - nodes[2].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { - features: nodes[0].node.init_features(), networks: None, remote_network_address: None - }, false).unwrap(); + nodes[0] + .node + .peer_connected( + &nodes[2].node.get_our_node_id(), + &msgs::Init { + features: nodes[2].node.init_features(), + networks: None, + remote_network_address: None, + }, + true, + ) + .unwrap(); + nodes[2] + .node + .peer_connected( + &nodes[0].node.get_our_node_id(), + &msgs::Init { + features: nodes[0].node.init_features(), + networks: None, + remote_network_address: None, + }, + false, + ) + .unwrap(); // Confirm that get_and_clear_pending_msg_events correctly captures pending broadcast messages let node_0_events = nodes[0].node.get_and_clear_pending_msg_events(); @@ -704,7 +1107,7 @@ fn test_channel_update_cached() { } { // Assert that ChannelUpdate message has been cleared from nodes[0] pending broadcast messages - let pending_broadcast_messages= nodes[0].node.pending_broadcast_messages.lock().unwrap(); + let pending_broadcast_messages = nodes[0].node.pending_broadcast_messages.lock().unwrap(); assert_eq!(pending_broadcast_messages.len(), 0); } -} \ No newline at end of file +} diff --git a/lightning/src/ln/keysend_payments_tests.rs b/lightning/src/ln/keysend_payments_tests.rs index df9acf60cae..7f2a42fdf21 100644 --- a/lightning/src/ln/keysend_payments_tests.rs +++ b/lightning/src/ln/keysend_payments_tests.rs @@ -1,19 +1,19 @@ -use bitcoin::hashes::Hash; -use bitcoin::hashes::sha256::Hash as Sha256; -use core::sync::atomic::Ordering; use crate::events::{Event, HTLCDestination, MessageSendEvent, MessageSendEventsProvider}; -use crate::ln::{PaymentPreimage, PaymentHash, PaymentSecret}; use crate::ln::channelmanager::{HTLCForwardInfo, PaymentId, RecipientOnionFields}; -use crate::ln::onion_payment::create_recv_pending_htlc_info; -use crate::ln::inbound_payment; use crate::ln::functional_test_utils::*; -use crate::ln::msgs::{self}; +use crate::ln::inbound_payment; use crate::ln::msgs::ChannelMessageHandler; +use crate::ln::msgs::{self}; +use crate::ln::onion_payment::create_recv_pending_htlc_info; +use crate::ln::{PaymentHash, PaymentPreimage, PaymentSecret}; use crate::prelude::*; -use crate::routing::router::{PaymentParameters, RouteParameters, find_route}; +use crate::routing::router::{find_route, PaymentParameters, RouteParameters}; +use crate::sign::EntropySource; use crate::util::ser::Writeable; use crate::util::test_utils; -use crate::sign::EntropySource; +use bitcoin::hashes::sha256::Hash as Sha256; +use bitcoin::hashes::Hash; +use core::sync::atomic::Ordering; #[test] fn test_keysend_dup_hash_partial_mpp() { @@ -26,7 +26,8 @@ fn test_keysend_dup_hash_partial_mpp() { create_announced_chan_between_nodes(&nodes, 0, 1); // First, send a partial MPP payment. - let (route, our_payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], 100_000); + let (route, our_payment_hash, payment_preimage, payment_secret) = + get_route_and_payment_hash!(&nodes[0], nodes[1], 100_000); let mut mpp_route = route.clone(); mpp_route.paths.push(mpp_route.paths[0].clone()); @@ -34,18 +35,52 @@ fn test_keysend_dup_hash_partial_mpp() { // Use the utility function send_payment_along_path to send the payment with MPP data which // indicates there are more HTLCs coming. let cur_height = CHAN_CONFIRM_DEPTH + 1; // route_payment calls send_payment, which adds 1 to the current height. So we do the same here to match. - let session_privs = nodes[0].node.test_add_new_pending_payment(our_payment_hash, - RecipientOnionFields::secret_only(payment_secret), payment_id, &mpp_route).unwrap(); - nodes[0].node.test_send_payment_along_path(&mpp_route.paths[0], &our_payment_hash, - RecipientOnionFields::secret_only(payment_secret), 200_000, cur_height, payment_id, &None, session_privs[0]).unwrap(); + let session_privs = nodes[0] + .node + .test_add_new_pending_payment( + our_payment_hash, + RecipientOnionFields::secret_only(payment_secret), + payment_id, + &mpp_route, + ) + .unwrap(); + nodes[0] + .node + .test_send_payment_along_path( + &mpp_route.paths[0], + &our_payment_hash, + RecipientOnionFields::secret_only(payment_secret), + 200_000, + cur_height, + payment_id, + &None, + session_privs[0], + ) + .unwrap(); check_added_monitors!(nodes[0], 1); let mut events = nodes[0].node.get_and_clear_pending_msg_events(); assert_eq!(events.len(), 1); - pass_along_path(&nodes[0], &[&nodes[1]], 200_000, our_payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), false, None); + pass_along_path( + &nodes[0], + &[&nodes[1]], + 200_000, + our_payment_hash, + Some(payment_secret), + events.drain(..).next().unwrap(), + false, + None, + ); // Next, send a keysend payment with the same payment_hash and make sure it fails. - nodes[0].node.send_spontaneous_payment(&route, Some(payment_preimage), - RecipientOnionFields::spontaneous_empty(), PaymentId(payment_preimage.0)).unwrap(); + nodes[0] + .node + .send_spontaneous_payment( + &route, + Some(payment_preimage), + RecipientOnionFields::spontaneous_empty(), + PaymentId(payment_preimage.0), + ) + .unwrap(); check_added_monitors!(nodes[0], 1); let mut events = nodes[0].node.get_and_clear_pending_msg_events(); assert_eq!(events.len(), 1); @@ -55,7 +90,10 @@ fn test_keysend_dup_hash_partial_mpp() { check_added_monitors!(nodes[1], 0); commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false); expect_pending_htlcs_forwardable!(nodes[1]); - expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]); + expect_pending_htlcs_forwardable_and_htlc_handling_failed!( + nodes[1], + vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }] + ); check_added_monitors!(nodes[1], 1); let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id()); assert!(updates.update_add_htlcs.is_empty()); @@ -63,17 +101,39 @@ fn test_keysend_dup_hash_partial_mpp() { assert_eq!(updates.update_fail_htlcs.len(), 1); assert!(updates.update_fail_malformed_htlcs.is_empty()); assert!(updates.update_fee.is_none()); - nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]); + nodes[0] + .node + .handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]); commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, true, true); expect_payment_failed!(nodes[0], our_payment_hash, true); // Send the second half of the original MPP payment. - nodes[0].node.test_send_payment_along_path(&mpp_route.paths[1], &our_payment_hash, - RecipientOnionFields::secret_only(payment_secret), 200_000, cur_height, payment_id, &None, session_privs[1]).unwrap(); + nodes[0] + .node + .test_send_payment_along_path( + &mpp_route.paths[1], + &our_payment_hash, + RecipientOnionFields::secret_only(payment_secret), + 200_000, + cur_height, + payment_id, + &None, + session_privs[1], + ) + .unwrap(); check_added_monitors!(nodes[0], 1); let mut events = nodes[0].node.get_and_clear_pending_msg_events(); assert_eq!(events.len(), 1); - pass_along_path(&nodes[0], &[&nodes[1]], 200_000, our_payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), true, None); + pass_along_path( + &nodes[0], + &[&nodes[1]], + 200_000, + our_payment_hash, + Some(payment_secret), + events.drain(..).next().unwrap(), + true, + None, + ); // Claim the full MPP payment. Note that we can't use a test utility like // claim_funds_along_route because the ordering of the messages causes the second half of the @@ -84,29 +144,57 @@ fn test_keysend_dup_hash_partial_mpp() { check_added_monitors!(nodes[1], 2); let bs_first_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id()); - nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_first_updates.update_fulfill_htlcs[0]); + nodes[0].node.handle_update_fulfill_htlc( + &nodes[1].node.get_our_node_id(), + &bs_first_updates.update_fulfill_htlcs[0], + ); expect_payment_sent(&nodes[0], payment_preimage, None, false, false); - nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_first_updates.commitment_signed); + nodes[0].node.handle_commitment_signed( + &nodes[1].node.get_our_node_id(), + &bs_first_updates.commitment_signed, + ); check_added_monitors!(nodes[0], 1); - let (as_first_raa, as_first_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id()); + let (as_first_raa, as_first_cs) = + get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id()); nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_first_raa); check_added_monitors!(nodes[1], 1); let bs_second_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id()); nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_first_cs); check_added_monitors!(nodes[1], 1); - let bs_first_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id()); - nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_second_updates.update_fulfill_htlcs[0]); - nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_updates.commitment_signed); + let bs_first_raa = get_event_msg!( + nodes[1], + MessageSendEvent::SendRevokeAndACK, + nodes[0].node.get_our_node_id() + ); + nodes[0].node.handle_update_fulfill_htlc( + &nodes[1].node.get_our_node_id(), + &bs_second_updates.update_fulfill_htlcs[0], + ); + nodes[0].node.handle_commitment_signed( + &nodes[1].node.get_our_node_id(), + &bs_second_updates.commitment_signed, + ); check_added_monitors!(nodes[0], 1); - let as_second_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id()); + let as_second_raa = get_event_msg!( + nodes[0], + MessageSendEvent::SendRevokeAndACK, + nodes[1].node.get_our_node_id() + ); nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_first_raa); let as_second_updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id()); check_added_monitors!(nodes[0], 1); nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_raa); check_added_monitors!(nodes[1], 1); - nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_second_updates.commitment_signed); + nodes[1].node.handle_commitment_signed( + &nodes[0].node.get_our_node_id(), + &as_second_updates.commitment_signed, + ); check_added_monitors!(nodes[1], 1); - let bs_third_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id()); + let bs_third_raa = get_event_msg!( + nodes[1], + MessageSendEvent::SendRevokeAndACK, + nodes[0].node.get_our_node_id() + ); nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_third_raa); check_added_monitors!(nodes[0], 1); @@ -115,7 +203,11 @@ fn test_keysend_dup_hash_partial_mpp() { let events = nodes[0].node.get_and_clear_pending_events(); assert_eq!(events.len(), 2); match events[0] { - Event::PaymentPathSuccessful { payment_id: ref actual_payment_id, ref payment_hash, ref path } => { + Event::PaymentPathSuccessful { + payment_id: ref actual_payment_id, + ref payment_hash, + ref path, + } => { assert_eq!(payment_id, *actual_payment_id); assert_eq!(our_payment_hash, *payment_hash.as_ref().unwrap()); assert_eq!(route.paths[0], *path); @@ -123,7 +215,11 @@ fn test_keysend_dup_hash_partial_mpp() { _ => panic!("Unexpected event"), } match events[1] { - Event::PaymentPathSuccessful { payment_id: ref actual_payment_id, ref payment_hash, ref path } => { + Event::PaymentPathSuccessful { + payment_id: ref actual_payment_id, + ref payment_hash, + ref path, + } => { assert_eq!(payment_id, *actual_payment_id); assert_eq!(our_payment_hash, *payment_hash.as_ref().unwrap()); assert_eq!(route.paths[0], *path); @@ -132,7 +228,6 @@ fn test_keysend_dup_hash_partial_mpp() { } } - #[test] fn test_keysend_dup_payment_hash() { do_test_keysend_dup_payment_hash(false); @@ -166,14 +261,33 @@ fn do_test_keysend_dup_payment_hash(accept_mpp_keysend: bool) { // Next, attempt a keysend payment and make sure it fails. let route_params = RouteParameters::from_payment_params_and_value( - PaymentParameters::for_keysend(expected_route.last().unwrap().node.get_our_node_id(), - TEST_FINAL_CLTV, false), 100_000); + PaymentParameters::for_keysend( + expected_route.last().unwrap().node.get_our_node_id(), + TEST_FINAL_CLTV, + false, + ), + 100_000, + ); let route = find_route( - &nodes[0].node.get_our_node_id(), &route_params, &nodes[0].network_graph, - None, nodes[0].logger, &scorer, &Default::default(), &random_seed_bytes - ).unwrap(); - nodes[0].node.send_spontaneous_payment(&route, Some(payment_preimage), - RecipientOnionFields::spontaneous_empty(), PaymentId(payment_preimage.0)).unwrap(); + &nodes[0].node.get_our_node_id(), + &route_params, + &nodes[0].network_graph, + None, + nodes[0].logger, + &scorer, + &Default::default(), + &random_seed_bytes, + ) + .unwrap(); + nodes[0] + .node + .send_spontaneous_payment( + &route, + Some(payment_preimage), + RecipientOnionFields::spontaneous_empty(), + PaymentId(payment_preimage.0), + ) + .unwrap(); check_added_monitors!(nodes[0], 1); let mut events = nodes[0].node.get_and_clear_pending_msg_events(); assert_eq!(events.len(), 1); @@ -185,7 +299,10 @@ fn do_test_keysend_dup_payment_hash(accept_mpp_keysend: bool) { // We have to forward pending HTLCs twice - once tries to forward the payment forward (and // fails), the second will process the resulting failure and fail the HTLC backward expect_pending_htlcs_forwardable!(nodes[1]); - expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash }]); + expect_pending_htlcs_forwardable_and_htlc_handling_failed!( + nodes[1], + vec![HTLCDestination::FailedPayment { payment_hash }] + ); check_added_monitors!(nodes[1], 1); let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id()); assert!(updates.update_add_htlcs.is_empty()); @@ -193,7 +310,9 @@ fn do_test_keysend_dup_payment_hash(accept_mpp_keysend: bool) { assert_eq!(updates.update_fail_htlcs.len(), 1); assert!(updates.update_fail_malformed_htlcs.is_empty()); assert!(updates.update_fee.is_none()); - nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]); + nodes[0] + .node + .handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]); commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, true, true); expect_payment_failed!(nodes[0], payment_hash, true); @@ -203,22 +322,52 @@ fn do_test_keysend_dup_payment_hash(accept_mpp_keysend: bool) { // To start (2), send a keysend payment but don't claim it. let payment_preimage = PaymentPreimage([42; 32]); let route = find_route( - &nodes[0].node.get_our_node_id(), &route_params, &nodes[0].network_graph, - None, nodes[0].logger, &scorer, &Default::default(), &random_seed_bytes - ).unwrap(); - let payment_hash = nodes[0].node.send_spontaneous_payment(&route, Some(payment_preimage), - RecipientOnionFields::spontaneous_empty(), PaymentId(payment_preimage.0)).unwrap(); + &nodes[0].node.get_our_node_id(), + &route_params, + &nodes[0].network_graph, + None, + nodes[0].logger, + &scorer, + &Default::default(), + &random_seed_bytes, + ) + .unwrap(); + let payment_hash = nodes[0] + .node + .send_spontaneous_payment( + &route, + Some(payment_preimage), + RecipientOnionFields::spontaneous_empty(), + PaymentId(payment_preimage.0), + ) + .unwrap(); check_added_monitors!(nodes[0], 1); let mut events = nodes[0].node.get_and_clear_pending_msg_events(); assert_eq!(events.len(), 1); let event = events.pop().unwrap(); let path = vec![&nodes[1]]; - pass_along_path(&nodes[0], &path, 100_000, payment_hash, None, event, true, Some(payment_preimage)); + pass_along_path( + &nodes[0], + &path, + 100_000, + payment_hash, + None, + event, + true, + Some(payment_preimage), + ); // Next, attempt a regular payment and make sure it fails. let payment_secret = PaymentSecret([43; 32]); - nodes[0].node.send_payment_with_route(&route, payment_hash, - RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap(); + nodes[0] + .node + .send_payment_with_route( + &route, + payment_hash, + RecipientOnionFields::secret_only(payment_secret), + PaymentId(payment_hash.0), + ) + .unwrap(); check_added_monitors!(nodes[0], 1); let mut events = nodes[0].node.get_and_clear_pending_msg_events(); assert_eq!(events.len(), 1); @@ -228,7 +377,10 @@ fn do_test_keysend_dup_payment_hash(accept_mpp_keysend: bool) { check_added_monitors!(nodes[1], 0); commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false); expect_pending_htlcs_forwardable!(nodes[1]); - expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash }]); + expect_pending_htlcs_forwardable_and_htlc_handling_failed!( + nodes[1], + vec![HTLCDestination::FailedPayment { payment_hash }] + ); check_added_monitors!(nodes[1], 1); let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id()); assert!(updates.update_add_htlcs.is_empty()); @@ -236,7 +388,9 @@ fn do_test_keysend_dup_payment_hash(accept_mpp_keysend: bool) { assert_eq!(updates.update_fail_htlcs.len(), 1); assert!(updates.update_fail_malformed_htlcs.is_empty()); assert!(updates.update_fee.is_none()); - nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]); + nodes[0] + .node + .handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]); commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, true, true); expect_payment_failed!(nodes[0], payment_hash, true); @@ -245,27 +399,61 @@ fn do_test_keysend_dup_payment_hash(accept_mpp_keysend: bool) { // To start (3), send a keysend payment but don't claim it. let payment_id_1 = PaymentId([44; 32]); - let payment_hash = nodes[0].node.send_spontaneous_payment(&route, Some(payment_preimage), - RecipientOnionFields::spontaneous_empty(), payment_id_1).unwrap(); + let payment_hash = nodes[0] + .node + .send_spontaneous_payment( + &route, + Some(payment_preimage), + RecipientOnionFields::spontaneous_empty(), + payment_id_1, + ) + .unwrap(); check_added_monitors!(nodes[0], 1); let mut events = nodes[0].node.get_and_clear_pending_msg_events(); assert_eq!(events.len(), 1); let event = events.pop().unwrap(); let path = vec![&nodes[1]]; - pass_along_path(&nodes[0], &path, 100_000, payment_hash, None, event, true, Some(payment_preimage)); + pass_along_path( + &nodes[0], + &path, + 100_000, + payment_hash, + None, + event, + true, + Some(payment_preimage), + ); // Next, attempt a keysend payment and make sure it fails. let route_params = RouteParameters::from_payment_params_and_value( - PaymentParameters::for_keysend(expected_route.last().unwrap().node.get_our_node_id(), TEST_FINAL_CLTV, false), - 100_000 + PaymentParameters::for_keysend( + expected_route.last().unwrap().node.get_our_node_id(), + TEST_FINAL_CLTV, + false, + ), + 100_000, ); let route = find_route( - &nodes[0].node.get_our_node_id(), &route_params, &nodes[0].network_graph, - None, nodes[0].logger, &scorer, &Default::default(), &random_seed_bytes - ).unwrap(); + &nodes[0].node.get_our_node_id(), + &route_params, + &nodes[0].network_graph, + None, + nodes[0].logger, + &scorer, + &Default::default(), + &random_seed_bytes, + ) + .unwrap(); let payment_id_2 = PaymentId([45; 32]); - nodes[0].node.send_spontaneous_payment(&route, Some(payment_preimage), - RecipientOnionFields::spontaneous_empty(), payment_id_2).unwrap(); + nodes[0] + .node + .send_spontaneous_payment( + &route, + Some(payment_preimage), + RecipientOnionFields::spontaneous_empty(), + payment_id_2, + ) + .unwrap(); check_added_monitors!(nodes[0], 1); let mut events = nodes[0].node.get_and_clear_pending_msg_events(); assert_eq!(events.len(), 1); @@ -275,7 +463,10 @@ fn do_test_keysend_dup_payment_hash(accept_mpp_keysend: bool) { check_added_monitors!(nodes[1], 0); commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false); expect_pending_htlcs_forwardable!(nodes[1]); - expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash }]); + expect_pending_htlcs_forwardable_and_htlc_handling_failed!( + nodes[1], + vec![HTLCDestination::FailedPayment { payment_hash }] + ); check_added_monitors!(nodes[1], 1); let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id()); assert!(updates.update_add_htlcs.is_empty()); @@ -283,7 +474,9 @@ fn do_test_keysend_dup_payment_hash(accept_mpp_keysend: bool) { assert_eq!(updates.update_fail_htlcs.len(), 1); assert!(updates.update_fail_malformed_htlcs.is_empty()); assert!(updates.update_fee.is_none()); - nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]); + nodes[0] + .node + .handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]); commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, true, true); expect_payment_failed!(nodes[0], payment_hash, true); @@ -305,22 +498,48 @@ fn test_keysend_hash_mismatch() { let _chan = create_chan_between_nodes(&nodes[0], &nodes[1]); let route_params = RouteParameters::from_payment_params_and_value( - PaymentParameters::for_keysend(payee_pubkey, 40, false), 10_000); + PaymentParameters::for_keysend(payee_pubkey, 40, false), + 10_000, + ); let network_graph = nodes[0].network_graph; let first_hops = nodes[0].node.list_usable_channels(); let scorer = test_utils::TestScorer::new(); let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes(); let route = find_route( - &payer_pubkey, &route_params, &network_graph, Some(&first_hops.iter().collect::>()), - nodes[0].logger, &scorer, &Default::default(), &random_seed_bytes - ).unwrap(); + &payer_pubkey, + &route_params, + &network_graph, + Some(&first_hops.iter().collect::>()), + nodes[0].logger, + &scorer, + &Default::default(), + &random_seed_bytes, + ) + .unwrap(); let test_preimage = PaymentPreimage([42; 32]); let mismatch_payment_hash = PaymentHash([43; 32]); - let session_privs = nodes[0].node.test_add_new_pending_payment(mismatch_payment_hash, - RecipientOnionFields::spontaneous_empty(), PaymentId(mismatch_payment_hash.0), &route).unwrap(); - nodes[0].node.test_send_payment_internal(&route, mismatch_payment_hash, - RecipientOnionFields::spontaneous_empty(), Some(test_preimage), PaymentId(mismatch_payment_hash.0), None, session_privs).unwrap(); + let session_privs = nodes[0] + .node + .test_add_new_pending_payment( + mismatch_payment_hash, + RecipientOnionFields::spontaneous_empty(), + PaymentId(mismatch_payment_hash.0), + &route, + ) + .unwrap(); + nodes[0] + .node + .test_send_payment_internal( + &route, + mismatch_payment_hash, + RecipientOnionFields::spontaneous_empty(), + Some(test_preimage), + PaymentId(mismatch_payment_hash.0), + None, + session_privs, + ) + .unwrap(); check_added_monitors!(nodes[0], 1); let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id()); @@ -329,9 +548,15 @@ fn test_keysend_hash_mismatch() { assert!(updates.update_fail_htlcs.is_empty()); assert!(updates.update_fail_malformed_htlcs.is_empty()); assert!(updates.update_fee.is_none()); - nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]); - - nodes[1].logger.assert_log_contains("lightning::ln::channelmanager", "Payment preimage didn't match payment hash", 1); + nodes[1] + .node + .handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]); + + nodes[1].logger.assert_log_contains( + "lightning::ln::channelmanager", + "Payment preimage didn't match payment hash", + 1, + ); } #[test] @@ -350,24 +575,49 @@ fn test_keysend_msg_with_secret_err() { let _chan = create_chan_between_nodes(&nodes[0], &nodes[1]); let route_params = RouteParameters::from_payment_params_and_value( - PaymentParameters::for_keysend(payee_pubkey, 40, false), 10_000); + PaymentParameters::for_keysend(payee_pubkey, 40, false), + 10_000, + ); let network_graph = nodes[0].network_graph; let first_hops = nodes[0].node.list_usable_channels(); let scorer = test_utils::TestScorer::new(); let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes(); let route = find_route( - &payer_pubkey, &route_params, &network_graph, Some(&first_hops.iter().collect::>()), - nodes[0].logger, &scorer, &Default::default(), &random_seed_bytes - ).unwrap(); + &payer_pubkey, + &route_params, + &network_graph, + Some(&first_hops.iter().collect::>()), + nodes[0].logger, + &scorer, + &Default::default(), + &random_seed_bytes, + ) + .unwrap(); let test_preimage = PaymentPreimage([42; 32]); let test_secret = PaymentSecret([43; 32]); let payment_hash = PaymentHash(Sha256::hash(&test_preimage.0).to_byte_array()); - let session_privs = nodes[0].node.test_add_new_pending_payment(payment_hash, - RecipientOnionFields::secret_only(test_secret), PaymentId(payment_hash.0), &route).unwrap(); - nodes[0].node.test_send_payment_internal(&route, payment_hash, - RecipientOnionFields::secret_only(test_secret), Some(test_preimage), - PaymentId(payment_hash.0), None, session_privs).unwrap(); + let session_privs = nodes[0] + .node + .test_add_new_pending_payment( + payment_hash, + RecipientOnionFields::secret_only(test_secret), + PaymentId(payment_hash.0), + &route, + ) + .unwrap(); + nodes[0] + .node + .test_send_payment_internal( + &route, + payment_hash, + RecipientOnionFields::secret_only(test_secret), + Some(test_preimage), + PaymentId(payment_hash.0), + None, + session_privs, + ) + .unwrap(); check_added_monitors!(nodes[0], 1); let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id()); @@ -376,9 +626,15 @@ fn test_keysend_msg_with_secret_err() { assert!(updates.update_fail_htlcs.is_empty()); assert!(updates.update_fail_malformed_htlcs.is_empty()); assert!(updates.update_fee.is_none()); - nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]); - - nodes[1].logger.assert_log_contains("lightning::ln::channelmanager", "We don't support MPP keysend payments", 1); + nodes[1] + .node + .handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]); + + nodes[1].logger.assert_log_contains( + "lightning::ln::channelmanager", + "We don't support MPP keysend payments", + 1, + ); } #[test] @@ -390,24 +646,38 @@ fn bad_inbound_payment_hash() { let nodes = create_network(2, &node_cfgs, &node_chanmgrs); let (_, payment_hash, payment_secret) = get_payment_preimage_hash!(&nodes[0]); - let payment_data = msgs::FinalOnionHopData { - payment_secret, - total_msat: 100_000, - }; + let payment_data = msgs::FinalOnionHopData { payment_secret, total_msat: 100_000 }; // Ensure that if the payment hash given to `inbound_payment::verify` differs from the original, // payment verification fails as expected. let mut bad_payment_hash = payment_hash.clone(); bad_payment_hash.0[0] += 1; - match inbound_payment::verify(bad_payment_hash, &payment_data, nodes[0].node.highest_seen_timestamp.load(Ordering::Acquire) as u64, &nodes[0].node.inbound_payment_key, &nodes[0].logger) { + match inbound_payment::verify( + bad_payment_hash, + &payment_data, + nodes[0].node.highest_seen_timestamp.load(Ordering::Acquire) as u64, + &nodes[0].node.inbound_payment_key, + &nodes[0].logger, + ) { Ok(_) => panic!("Unexpected ok"), Err(()) => { - nodes[0].logger.assert_log_contains("lightning::ln::inbound_payment", "Failing HTLC with user-generated payment_hash", 1); - } + nodes[0].logger.assert_log_contains( + "lightning::ln::inbound_payment", + "Failing HTLC with user-generated payment_hash", + 1, + ); + }, } // Check that using the original payment hash succeeds. - assert!(inbound_payment::verify(payment_hash, &payment_data, nodes[0].node.highest_seen_timestamp.load(Ordering::Acquire) as u64, &nodes[0].node.inbound_payment_key, &nodes[0].logger).is_ok()); + assert!(inbound_payment::verify( + payment_hash, + &payment_data, + nodes[0].node.highest_seen_timestamp.load(Ordering::Acquire) as u64, + &nodes[0].node.inbound_payment_key, + &nodes[0].logger + ) + .is_ok()); } #[test] @@ -424,7 +694,8 @@ fn reject_excessively_underpaying_htlcs() { payment_metadata: None, keysend_preimage: None, payment_data: Some(msgs::FinalOnionHopData { - payment_secret: PaymentSecret([0; 32]), total_msat: sender_intended_amt_msat, + payment_secret: PaymentSecret([0; 32]), + total_msat: sender_intended_amt_msat, }), custom_tlvs: Vec::new(), }; @@ -432,49 +703,82 @@ fn reject_excessively_underpaying_htlcs() { // intended amount, we fail the payment. let current_height: u32 = node[0].node.best_block.read().unwrap().height; if let Err(crate::ln::channelmanager::InboundHTLCErr { err_code, .. }) = - create_recv_pending_htlc_info(hop_data, [0; 32], PaymentHash([0; 32]), - sender_intended_amt_msat - extra_fee_msat - 1, 42, None, true, Some(extra_fee_msat), - current_height, node[0].node.default_configuration.accept_mpp_keysend) - { + create_recv_pending_htlc_info( + hop_data, + [0; 32], + PaymentHash([0; 32]), + sender_intended_amt_msat - extra_fee_msat - 1, + 42, + None, + true, + Some(extra_fee_msat), + current_height, + node[0].node.default_configuration.accept_mpp_keysend, + ) { assert_eq!(err_code, 19); - } else { panic!(); } + } else { + panic!(); + } // If amt_received + extra_fee is equal to the sender intended amount, we're fine. - let hop_data = msgs::InboundOnionPayload::Receive { // This is the same payload as above, InboundOnionPayload doesn't implement Clone + let hop_data = msgs::InboundOnionPayload::Receive { + // This is the same payload as above, InboundOnionPayload doesn't implement Clone sender_intended_htlc_amt_msat: 100, cltv_expiry_height: 42, payment_metadata: None, keysend_preimage: None, payment_data: Some(msgs::FinalOnionHopData { - payment_secret: PaymentSecret([0; 32]), total_msat: sender_intended_amt_msat, + payment_secret: PaymentSecret([0; 32]), + total_msat: sender_intended_amt_msat, }), custom_tlvs: Vec::new(), }; let current_height: u32 = node[0].node.best_block.read().unwrap().height; - assert!(create_recv_pending_htlc_info(hop_data, [0; 32], PaymentHash([0; 32]), - sender_intended_amt_msat - extra_fee_msat, 42, None, true, Some(extra_fee_msat), - current_height, node[0].node.default_configuration.accept_mpp_keysend).is_ok()); + assert!(create_recv_pending_htlc_info( + hop_data, + [0; 32], + PaymentHash([0; 32]), + sender_intended_amt_msat - extra_fee_msat, + 42, + None, + true, + Some(extra_fee_msat), + current_height, + node[0].node.default_configuration.accept_mpp_keysend + ) + .is_ok()); } #[test] -fn test_final_incorrect_cltv(){ +fn test_final_incorrect_cltv() { let chanmon_cfg = create_chanmon_cfgs(1); let node_cfg = create_node_cfgs(1, &chanmon_cfg); let node_chanmgr = create_node_chanmgrs(1, &node_cfg, &[None]); let node = create_network(1, &node_cfg, &node_chanmgr); let current_height: u32 = node[0].node.best_block.read().unwrap().height; - let result = create_recv_pending_htlc_info(msgs::InboundOnionPayload::Receive { - sender_intended_htlc_amt_msat: 100, - cltv_expiry_height: 22, - payment_metadata: None, - keysend_preimage: None, - payment_data: Some(msgs::FinalOnionHopData { - payment_secret: PaymentSecret([0; 32]), total_msat: 100, - }), - custom_tlvs: Vec::new(), - }, [0; 32], PaymentHash([0; 32]), 100, 23, None, true, None, current_height, - node[0].node.default_configuration.accept_mpp_keysend); + let result = create_recv_pending_htlc_info( + msgs::InboundOnionPayload::Receive { + sender_intended_htlc_amt_msat: 100, + cltv_expiry_height: 22, + payment_metadata: None, + keysend_preimage: None, + payment_data: Some(msgs::FinalOnionHopData { + payment_secret: PaymentSecret([0; 32]), + total_msat: 100, + }), + custom_tlvs: Vec::new(), + }, + [0; 32], + PaymentHash([0; 32]), + 100, + 23, + None, + true, + None, + current_height, + node[0].node.default_configuration.accept_mpp_keysend, + ); // Should not return an error as this condition: // https://github.com/lightning/bolts/blob/4dcc377209509b13cf89a4b91fde7d478f5b46d8/04-onion-routing.md?plain=1#L334 @@ -485,11 +789,20 @@ fn test_final_incorrect_cltv(){ #[test] fn test_payment_display() { let payment_id = PaymentId([42; 32]); - assert_eq!(format!("{}", &payment_id), "2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a"); + assert_eq!( + format!("{}", &payment_id), + "2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a" + ); let payment_hash = PaymentHash([42; 32]); - assert_eq!(format!("{}", &payment_hash), "2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a"); + assert_eq!( + format!("{}", &payment_hash), + "2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a" + ); let payment_preimage = PaymentPreimage([42; 32]); - assert_eq!(format!("{}", &payment_preimage), "2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a"); + assert_eq!( + format!("{}", &payment_preimage), + "2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a" + ); } #[test] @@ -503,29 +816,35 @@ fn test_malformed_forward_htlcs_ser() { let deserialized_chanmgr; let mut nodes = create_network(1, &node_cfg, &chanmgrs); - let dummy_failed_htlc = |htlc_id| { - HTLCForwardInfo::FailHTLC { htlc_id, err_packet: msgs::OnionErrorPacket { data: vec![42] }, } + let dummy_failed_htlc = |htlc_id| HTLCForwardInfo::FailHTLC { + htlc_id, + err_packet: msgs::OnionErrorPacket { data: vec![42] }, }; - let dummy_malformed_htlc = |htlc_id| { - HTLCForwardInfo::FailMalformedHTLC { htlc_id, failure_code: 0x4000, sha256_of_onion: [0; 32] } + let dummy_malformed_htlc = |htlc_id| HTLCForwardInfo::FailMalformedHTLC { + htlc_id, + failure_code: 0x4000, + sha256_of_onion: [0; 32], }; - let dummy_htlcs_1: Vec = (1..10).map(|htlc_id| { - if htlc_id % 2 == 0 { - dummy_failed_htlc(htlc_id) - } else { - dummy_malformed_htlc(htlc_id) - } - }).collect(); - - let dummy_htlcs_2: Vec = (1..10).map(|htlc_id| { - if htlc_id % 2 == 1 { - dummy_failed_htlc(htlc_id) - } else { - dummy_malformed_htlc(htlc_id) - } - }).collect(); - + let dummy_htlcs_1: Vec = (1..10) + .map(|htlc_id| { + if htlc_id % 2 == 0 { + dummy_failed_htlc(htlc_id) + } else { + dummy_malformed_htlc(htlc_id) + } + }) + .collect(); + + let dummy_htlcs_2: Vec = (1..10) + .map(|htlc_id| { + if htlc_id % 2 == 1 { + dummy_failed_htlc(htlc_id) + } else { + dummy_malformed_htlc(htlc_id) + } + }) + .collect(); let (scid_1, scid_2) = (42, 43); let mut forward_htlcs = new_hash_map(); @@ -536,7 +855,14 @@ fn test_malformed_forward_htlcs_ser() { *chanmgr_fwd_htlcs = forward_htlcs.clone(); core::mem::drop(chanmgr_fwd_htlcs); - reload_node!(nodes[0], nodes[0].node.encode(), &[], persister, chain_monitor, deserialized_chanmgr); + reload_node!( + nodes[0], + nodes[0].node.encode(), + &[], + persister, + chain_monitor, + deserialized_chanmgr + ); let mut deserialized_fwd_htlcs = nodes[0].node.forward_htlcs.lock().unwrap(); for scid in [scid_1, scid_2].iter() {