From 8eda4360cf4ea64cbc0b3e6a887d3a13a80eac00 Mon Sep 17 00:00:00 2001 From: Srikanth Iyengar Date: Fri, 29 Mar 2024 19:39:27 +0530 Subject: [PATCH] refactor channelmanager tests into more appropriate submodule tests --- .../ln/anchor_channel_configuration_tests.rs | 163 ++ lightning/src/ln/channelmanager.rs | 1362 +---------------- .../src/ln/channelmanager_limits_tests.rs | 655 ++++++++ lightning/src/ln/keysend_payments_tests.rs | 550 +++++++ 4 files changed, 1379 insertions(+), 1351 deletions(-) create mode 100644 lightning/src/ln/anchor_channel_configuration_tests.rs create mode 100644 lightning/src/ln/channelmanager_limits_tests.rs create mode 100644 lightning/src/ln/keysend_payments_tests.rs diff --git a/lightning/src/ln/anchor_channel_configuration_tests.rs b/lightning/src/ln/anchor_channel_configuration_tests.rs new file mode 100644 index 00000000000..24c9b37b5fc --- /dev/null +++ b/lightning/src/ln/anchor_channel_configuration_tests.rs @@ -0,0 +1,163 @@ +use crate::events::{Event, MessageSendEvent, MessageSendEventsProvider}; +use crate::ln::msgs::ChannelMessageHandler; +use crate::ln::msgs::ErrorAction; +use crate::ln::{functional_test_utils::*, ChannelId}; +use crate::prelude::*; +use crate::util::config::ChannelConfigUpdate; +use crate::util::errors::APIError; + +#[test] +fn test_inbound_anchors_manual_acceptance() { + // Tests that we properly limit inbound channels when we have the manual-channel-acceptance + // flag set and (sometimes) accept channels as 0conf. + let mut anchors_cfg = test_default_channel_config(); + anchors_cfg.channel_handshake_config.negotiate_anchors_zero_fee_htlc_tx = true; + + let mut anchors_manual_accept_cfg = anchors_cfg.clone(); + anchors_manual_accept_cfg.manually_accept_inbound_channels = true; + + 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 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[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()); + let msg_events = nodes[1].node.get_and_clear_pending_msg_events(); + match &msg_events[0] { + 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()), + _ => 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(), + _ => panic!("Unexpected event"), + } + get_event_msg!(nodes[2], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id()); +} + +#[test] +fn test_anchors_zero_fee_htlc_tx_fallback() { + // Tests that if both nodes support anchors, but the remote node does not want to accept + // anchor channels at the moment, an error it sent to the local node such that it can retry + // the channel without the anchors feature. + 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.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 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[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(); + } + _ => 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()); + + // Since nodes[1] should not have accepted the channel, it should + // not have generated any events. + assert!(nodes[1].node.get_and_clear_pending_events().is_empty()); +} + +#[test] +fn test_update_channel_config() { + let chanmon_cfg = create_chanmon_cfgs(2); + let node_cfg = create_node_cfgs(2, &chanmon_cfg); + let mut user_config = test_default_channel_config(); + let node_chanmgr = create_node_chanmgrs(2, &node_cfg, &[Some(user_config), Some(user_config)]); + let nodes = create_network(2, &node_cfg, &node_chanmgr); + 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(); + 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); + let events = nodes[0].node.get_and_clear_pending_msg_events(); + assert_eq!(events.len(), 1); + match &events[0] { + MessageSendEvent::BroadcastChannelUpdate { .. } => {}, + _ => panic!("expected BroadcastChannelUpdate event"), + } + + 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); + let events = nodes[0].node.get_and_clear_pending_msg_events(); + assert_eq!(events.len(), 1); + match &events[0] { + MessageSendEvent::BroadcastChannelUpdate { .. } => {}, + _ => panic!("expected BroadcastChannelUpdate event"), + } + + 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); + let events = nodes[0].node.get_and_clear_pending_msg_events(); + assert_eq!(events.len(), 1); + match &events[0] { + MessageSendEvent::BroadcastChannelUpdate { .. } => {}, + _ => panic!("expected BroadcastChannelUpdate event"), + } + + // 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 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 { + forwarding_fee_proportional_millionths: Some(new_fee), + ..Default::default() + }), + 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); + let events = nodes[0].node.get_and_clear_pending_msg_events(); + assert_eq!(events.len(), 0); +} diff --git a/lightning/src/ln/channelmanager.rs b/lightning/src/ln/channelmanager.rs index bddcd4c9b81..df074511cd2 100644 --- a/lightning/src/ln/channelmanager.rs +++ b/lightning/src/ln/channelmanager.rs @@ -106,6 +106,17 @@ use core::ops::Deref; pub use crate::ln::outbound_payment::{PaymentSendFailure, ProbeSendFailure, Retry, RetryableSendFailure, RecipientOnionFields}; use crate::ln::script::ShutdownScript; +// Test submodules for channelmanager +#[path ="./anchor_channel_configuration_tests.rs"] +#[cfg(test)] +mod anchor_channel_configuration_tests; +#[path ="./channelmanager_limits_tests.rs"] +#[cfg(test)] +mod channelmanager_limits_tests; +#[cfg(test)] +#[path ="./keysend_payments_tests.rs"] +mod keysend_payments_tests; + // We hold various information about HTLC relay in the HTLC objects in Channel itself: // // Upon receipt of an HTLC from a peer, we'll give it a PendingHTLCStatus indicating if it should @@ -11422,1357 +11433,6 @@ where } } -#[cfg(test)] -mod tests { - use bitcoin::hashes::Hash; - use bitcoin::hashes::sha256::Hash as Sha256; - use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey}; - use core::sync::atomic::Ordering; - use crate::events::{Event, HTLCDestination, MessageSendEvent, MessageSendEventsProvider, ClosureReason}; - use crate::ln::{PaymentPreimage, PaymentHash, PaymentSecret}; - use crate::ln::ChannelId; - use crate::ln::channelmanager::{create_recv_pending_htlc_info, HTLCForwardInfo, inbound_payment, PaymentId, PaymentSendFailure, RecipientOnionFields, InterceptId}; - use crate::ln::functional_test_utils::*; - use crate::ln::msgs::{self, ErrorAction}; - use crate::ln::msgs::ChannelMessageHandler; - use crate::prelude::*; - use crate::routing::router::{PaymentParameters, RouteParameters, find_route}; - use crate::util::errors::APIError; - use crate::util::ser::Writeable; - use crate::util::test_utils; - use crate::util::config::{ChannelConfig, ChannelConfigUpdate}; - use crate::sign::EntropySource; - - #[test] - fn test_notify_limits() { - // Check that a few cases which don't require the persistence of a new ChannelManager, - // indeed, do not cause the persistence of a new ChannelManager. - 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 nodes = create_network(3, &node_cfgs, &node_chanmgrs); - - // All nodes start with a persistable update pending as `create_network` connects each node - // with all other nodes to make most tests simpler. - assert!(nodes[0].node.get_event_or_persistence_needed_future().poll_is_complete()); - assert!(nodes[1].node.get_event_or_persistence_needed_future().poll_is_complete()); - assert!(nodes[2].node.get_event_or_persistence_needed_future().poll_is_complete()); - - let mut chan = create_announced_chan_between_nodes(&nodes, 0, 1); - - // We check that the channel info nodes have doesn't change too early, even though we try - // 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(); - - // 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()); - assert!(nodes[1].node.get_event_or_persistence_needed_future().poll_is_complete()); - // ... but the last node should not. - assert!(!nodes[2].node.get_event_or_persistence_needed_future().poll_is_complete()); - // After persisting the first two nodes they should no longer need fresh persistence. - assert!(!nodes[0].node.get_event_or_persistence_needed_future().poll_is_complete()); - assert!(!nodes[1].node.get_event_or_persistence_needed_future().poll_is_complete()); - - // Node 3, unrelated to the only channel, shouldn't care if it receives a channel_update - // about the channel. - nodes[2].node.handle_channel_update(&nodes[1].node.get_our_node_id(), &chan.0); - nodes[2].node.handle_channel_update(&nodes[1].node.get_our_node_id(), &chan.1); - assert!(!nodes[2].node.get_event_or_persistence_needed_future().poll_is_complete()); - - // The nodes which are a party to the channel should also ignore messages from unrelated - // parties. - nodes[0].node.handle_channel_update(&nodes[2].node.get_our_node_id(), &chan.0); - nodes[0].node.handle_channel_update(&nodes[2].node.get_our_node_id(), &chan.1); - nodes[1].node.handle_channel_update(&nodes[2].node.get_our_node_id(), &chan.0); - nodes[1].node.handle_channel_update(&nodes[2].node.get_our_node_id(), &chan.1); - assert!(!nodes[0].node.get_event_or_persistence_needed_future().poll_is_complete()); - assert!(!nodes[1].node.get_event_or_persistence_needed_future().poll_is_complete()); - - // At this point the channel info given by peers should still be the same. - assert_eq!(nodes[0].node.list_channels()[0], node_a_chan_info); - assert_eq!(nodes[1].node.list_channels()[0], node_b_chan_info); - - // 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 }; - - // First deliver each peers' own message, checking that the node doesn't need to be - // persisted and that its channel info remains the same. - nodes[0].node.handle_channel_update(&nodes[1].node.get_our_node_id(), &as_update); - nodes[1].node.handle_channel_update(&nodes[0].node.get_our_node_id(), &bs_update); - assert!(!nodes[0].node.get_event_or_persistence_needed_future().poll_is_complete()); - assert!(!nodes[1].node.get_event_or_persistence_needed_future().poll_is_complete()); - assert_eq!(nodes[0].node.list_channels()[0], node_a_chan_info); - assert_eq!(nodes[1].node.list_channels()[0], node_b_chan_info); - - // Finally, deliver the other peers' message, ensuring each node needs to be persisted and - // the channel info has updated. - nodes[0].node.handle_channel_update(&nodes[1].node.get_our_node_id(), &bs_update); - nodes[1].node.handle_channel_update(&nodes[0].node.get_our_node_id(), &as_update); - assert!(nodes[0].node.get_event_or_persistence_needed_future().poll_is_complete()); - assert!(nodes[1].node.get_event_or_persistence_needed_future().poll_is_complete()); - assert_ne!(nodes[0].node.list_channels()[0], node_a_chan_info); - assert_ne!(nodes[1].node.list_channels()[0], node_b_chan_info); - } - - #[test] - fn test_keysend_dup_hash_partial_mpp() { - // Test that a keysend payment with a duplicate hash to an existing partial MPP payment fails as - // expected. - 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); - 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 mut mpp_route = route.clone(); - mpp_route.paths.push(mpp_route.paths[0].clone()); - - let payment_id = PaymentId([42; 32]); - // 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(); - 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); - - // 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(); - check_added_monitors!(nodes[0], 1); - let mut events = nodes[0].node.get_and_clear_pending_msg_events(); - assert_eq!(events.len(), 1); - let ev = events.drain(..).next().unwrap(); - 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); - 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 }]); - 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()); - assert!(updates.update_fulfill_htlcs.is_empty()); - 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]); - 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(); - 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); - - // 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 - // payment to be put in the holding cell, which confuses the test utilities. So we exchange the - // lightning messages manually. - nodes[1].node.claim_funds(payment_preimage); - expect_payment_claimed!(nodes[1], our_payment_hash, 200_000); - 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]); - 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); - 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()); - 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); - check_added_monitors!(nodes[0], 1); - 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); - check_added_monitors!(nodes[1], 1); - 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); - - // Note that successful MPP payments will generate a single PaymentSent event upon the first - // path's success and a PaymentPathSuccessful event for each path's success. - 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 } => { - assert_eq!(payment_id, *actual_payment_id); - assert_eq!(our_payment_hash, *payment_hash.as_ref().unwrap()); - assert_eq!(route.paths[0], *path); - }, - _ => panic!("Unexpected event"), - } - match events[1] { - 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); - }, - _ => panic!("Unexpected event"), - } - } - - #[test] - fn test_keysend_dup_payment_hash() { - do_test_keysend_dup_payment_hash(false); - do_test_keysend_dup_payment_hash(true); - } - - fn do_test_keysend_dup_payment_hash(accept_mpp_keysend: bool) { - // (1): Test that a keysend payment with a duplicate payment hash to an existing pending - // outbound regular payment fails as expected. - // (2): Test that a regular payment with a duplicate payment hash to an existing keysend payment - // fails as expected. - // (3): Test that a keysend payment with a duplicate payment hash to an existing keysend - // payment fails as expected. When `accept_mpp_keysend` is false, this tests that we - // reject MPP keysend payments, since in this case where the payment has no payment - // secret, a keysend payment with a duplicate hash is basically an MPP keysend. If - // `accept_mpp_keysend` is true, this tests that we only accept MPP keysends with - // payment secrets and reject otherwise. - let chanmon_cfgs = create_chanmon_cfgs(2); - let node_cfgs = create_node_cfgs(2, &chanmon_cfgs); - let mut mpp_keysend_cfg = test_default_channel_config(); - mpp_keysend_cfg.accept_mpp_keysend = accept_mpp_keysend; - let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(mpp_keysend_cfg)]); - let nodes = create_network(2, &node_cfgs, &node_chanmgrs); - create_announced_chan_between_nodes(&nodes, 0, 1); - let scorer = test_utils::TestScorer::new(); - let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes(); - - // To start (1), send a regular payment but don't claim it. - let expected_route = [&nodes[1]]; - let (payment_preimage, payment_hash, ..) = route_payment(&nodes[0], &expected_route, 100_000); - - // 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); - 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(); - check_added_monitors!(nodes[0], 1); - let mut events = nodes[0].node.get_and_clear_pending_msg_events(); - assert_eq!(events.len(), 1); - let ev = events.drain(..).next().unwrap(); - 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); - commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false); - // 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 }]); - 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()); - assert!(updates.update_fulfill_htlcs.is_empty()); - 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]); - commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, true, true); - expect_payment_failed!(nodes[0], payment_hash, true); - - // Finally, claim the original payment. - claim_payment(&nodes[0], &expected_route, payment_preimage); - - // 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(); - 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)); - - // 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(); - check_added_monitors!(nodes[0], 1); - let mut events = nodes[0].node.get_and_clear_pending_msg_events(); - assert_eq!(events.len(), 1); - let ev = events.drain(..).next().unwrap(); - 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); - 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 }]); - 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()); - assert!(updates.update_fulfill_htlcs.is_empty()); - 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]); - commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, true, true); - expect_payment_failed!(nodes[0], payment_hash, true); - - // Finally, succeed the keysend payment. - claim_payment(&nodes[0], &expected_route, payment_preimage); - - // 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(); - 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)); - - // 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 - ); - 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_id_2 = PaymentId([45; 32]); - 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); - let ev = events.drain(..).next().unwrap(); - 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); - 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 }]); - 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()); - assert!(updates.update_fulfill_htlcs.is_empty()); - 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]); - commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, true, true); - expect_payment_failed!(nodes[0], payment_hash, true); - - // Finally, claim the original payment. - claim_payment(&nodes[0], &expected_route, payment_preimage); - } - - #[test] - fn test_keysend_hash_mismatch() { - // Test that if we receive a keysend `update_add_htlc` msg, we fail as expected if the keysend - // preimage doesn't match the msg's payment hash. - 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); - - let payer_pubkey = nodes[0].node.get_our_node_id(); - let payee_pubkey = nodes[1].node.get_our_node_id(); - - 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); - 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(); - - 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(); - check_added_monitors!(nodes[0], 1); - - let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id()); - assert_eq!(updates.update_add_htlcs.len(), 1); - assert!(updates.update_fulfill_htlcs.is_empty()); - 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); - } - - #[test] - fn test_keysend_msg_with_secret_err() { - // Test that we error as expected if we receive a keysend payment that includes a payment - // secret when we don't support MPP keysend. - let mut reject_mpp_keysend_cfg = test_default_channel_config(); - reject_mpp_keysend_cfg.accept_mpp_keysend = false; - 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, Some(reject_mpp_keysend_cfg)]); - let nodes = create_network(2, &node_cfgs, &node_chanmgrs); - - let payer_pubkey = nodes[0].node.get_our_node_id(); - let payee_pubkey = nodes[1].node.get_our_node_id(); - - 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); - 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(); - - 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(); - check_added_monitors!(nodes[0], 1); - - let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id()); - assert_eq!(updates.update_add_htlcs.len(), 1); - assert!(updates.update_fulfill_htlcs.is_empty()); - 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); - } - - #[test] - fn test_multi_hop_missing_secret() { - 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 nodes = create_network(4, &node_cfgs, &node_chanmgrs); - - let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id; - let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2).0.contents.short_channel_id; - let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3).0.contents.short_channel_id; - let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3).0.contents.short_channel_id; - - // Marshall an MPP route. - let (mut route, payment_hash, _, _) = get_route_and_payment_hash!(&nodes[0], nodes[3], 100000); - let path = route.paths[0].clone(); - route.paths.push(path); - route.paths[0].hops[0].pubkey = nodes[1].node.get_our_node_id(); - route.paths[0].hops[0].short_channel_id = chan_1_id; - route.paths[0].hops[1].short_channel_id = chan_3_id; - route.paths[1].hops[0].pubkey = nodes[2].node.get_our_node_id(); - 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() { - PaymentSendFailure::ParameterError(APIError::APIMisuseError { ref err }) => { - assert!(regex::Regex::new(r"Payment secret is required for multi-path payments").unwrap().is_match(err)) - }, - _ => panic!("unexpected error") - } - } - - #[test] - fn test_drop_disconnected_peers_when_removing_channels() { - 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); - - let chan = 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.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); - - { - // Assert that nodes[1] is awaiting removal for nodes[0] once nodes[1] has been - // disconnected and the channel between has been force closed. - let nodes_0_per_peer_state = nodes[0].node.per_peer_state.read().unwrap(); - // Assert that nodes[1] isn't removed before `timer_tick_occurred` has been executed. - assert_eq!(nodes_0_per_peer_state.len(), 1); - assert!(nodes_0_per_peer_state.get(&nodes[1].node.get_our_node_id()).is_some()); - } - - nodes[0].node.timer_tick_occurred(); - - { - // Assert that nodes[1] has now been removed. - assert_eq!(nodes[0].node.per_peer_state.read().unwrap().len(), 0); - } - } - - #[test] - fn bad_inbound_payment_hash() { - // Add coverage for checking that a user-provided payment hash matches the payment secret. - 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); - - let (_, payment_hash, payment_secret) = get_payment_preimage_hash!(&nodes[0]); - 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) { - Ok(_) => panic!("Unexpected ok"), - Err(()) => { - 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()); - } - - #[test] - fn test_outpoint_to_peer_coverage() { - // Test that the `ChannelManager:outpoint_to_peer` contains channels which have been assigned - // a `channel_id` (i.e. have had the funding tx created), and that they are removed once - // the channel is successfully closed. - 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); - - 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()); - 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 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 - // funding transaction, and have the real `channel_id`. - assert_eq!(nodes[0].node.outpoint_to_peer.lock().unwrap().len(), 0); - 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(); - { - // Assert that `nodes[0]`'s `outpoint_to_peer` map is populated with the channel as soon as - // as it has the funding transaction. - let nodes_0_lock = nodes[0].node.outpoint_to_peer.lock().unwrap(); - assert_eq!(nodes_0_lock.len(), 1); - assert!(nodes_0_lock.contains_key(&funding_output)); - } - - 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()); - - nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg); - { - let nodes_0_lock = nodes[0].node.outpoint_to_peer.lock().unwrap(); - assert_eq!(nodes_0_lock.len(), 1); - assert!(nodes_0_lock.contains_key(&funding_output)); - } - expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id()); - - { - // Assert that `nodes[1]`'s `outpoint_to_peer` map is populated with the channel as - // soon as it has the funding transaction. - let nodes_1_lock = nodes[1].node.outpoint_to_peer.lock().unwrap(); - assert_eq!(nodes_1_lock.len(), 1); - 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()); - 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); - 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[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()); - 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 - // channel can be fully closed by both parties (i.e. no outstanding htlcs exists, the - // fee for the closing transaction has been negotiated and the parties has the other - // party's signature for the fee negotiated closing transaction.) - let nodes_0_lock = nodes[0].node.outpoint_to_peer.lock().unwrap(); - assert_eq!(nodes_0_lock.len(), 1); - assert!(nodes_0_lock.contains_key(&funding_output)); - } - - { - // At this stage, `nodes[1]` has proposed a fee for the closing transaction in the - // `handle_closing_signed` call above. As `nodes[1]` has not yet received the signature - // from `nodes[0]` for the closing transaction with the proposed fee, the channel is - // kept in the `nodes[1]`'s `outpoint_to_peer` map. - let nodes_1_lock = nodes[1].node.outpoint_to_peer.lock().unwrap(); - assert_eq!(nodes_1_lock.len(), 1); - 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]` 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 - // closing transaction). - // Assert that the channel is removed from `nodes[0]`'s `outpoint_to_peer` map as it can be - // fully closed by `nodes[0]`. - assert_eq!(nodes[0].node.outpoint_to_peer.lock().unwrap().len(), 0); - - // Assert that the channel is still in `nodes[1]`'s `outpoint_to_peer` map, as `nodes[1]` - // doesn't have `nodes[0]`'s signature for the closing transaction yet. - let nodes_1_lock = nodes[1].node.outpoint_to_peer.lock().unwrap(); - assert_eq!(nodes_1_lock.len(), 1); - 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()); - - 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); - } - - 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); - 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); - check_api_error_message(expected_message, res_err) - } - - fn check_api_misuse_error(res_err: Result) { - let expected_message = "No such channel awaiting to be accepted.".to_string(); - check_api_error_message(expected_message, res_err) - } - - fn check_api_error_message(expected_err_message: String, res_err: Result) { - match res_err { - Err(APIError::APIMisuseError { err }) => { - assert_eq!(err, expected_err_message); - }, - Err(APIError::ChannelUnavailable { err }) => { - assert_eq!(err, expected_err_message); - }, - Ok(_) => panic!("Unexpected Ok"), - Err(_) => panic!("Unexpected Error"), - } - } - - #[test] - fn test_api_calls_with_unkown_counterparty_node() { - // Tests that our API functions that expects a `counterparty_node_id` as input, behaves as - // expected if the `counterparty_node_id` is an unkown peer in the - // `ChannelManager::per_peer_state` map. - let chanmon_cfg = create_chanmon_cfgs(2); - let node_cfg = create_node_cfgs(2, &chanmon_cfg); - let node_chanmgr = create_node_chanmgrs(2, &node_cfg, &[None, None]); - let nodes = create_network(2, &node_cfg, &node_chanmgr); - - // 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 intercept_id = 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_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.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.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); - } - - #[test] - fn test_api_calls_with_unavailable_channel() { - // Tests that our API functions that expects a `counterparty_node_id` and a `channel_id` - // as input, behaves as expected if the `counterparty_node_id` is a known peer in the - // `ChannelManager::per_peer_state` map, but the peer state doesn't contain a channel with - // the given `channel_id`. - let chanmon_cfg = create_chanmon_cfgs(2); - let node_cfg = create_node_cfgs(2, &chanmon_cfg); - let node_chanmgr = create_node_chanmgrs(2, &node_cfg, &[None, None]); - let nodes = create_network(2, &node_cfg, &node_chanmgr); - - let counterparty_node_id = nodes[1].node.get_our_node_id(); - - // Dummy values - 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_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.forward_intercepted_htlc(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); - } - - #[test] - fn test_connection_limiting() { - // Test that we limit un-channel'd peers and un-funded channels properly. - 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); - - // 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()); - - let mut funding_tx = None; - for idx in 0..super::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()); - - 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); - 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); - 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()); - - 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); - } - - // 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); - 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); - - // 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(super::MAX_NO_CHANNEL_PEERS); - for _ in 1..super::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()); - 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(); - } - 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. - nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id()); - let chan_closed_events = nodes[1].node.get_and_clear_pending_events(); - assert_eq!(chan_closed_events.len(), super::MAX_UNFUNDED_CHANS_PER_PEER - 1); - for ev in chan_closed_events { - 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(); - - // 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_disconnected(&nodes[0].node.get_our_node_id()); - - // Now nodes[0] is disconnected but still has a pending, un-funded channel lying around. - // Even though we accept one more connection from new peers, we won't actually let them - // open channels. - assert!(peer_pks.len() > super::MAX_UNFUNDED_CHANNEL_PEERS - 1); - for i in 0..super::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); - } - 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); - - // Of course, however, outbound channels are always allowed - nodes[1].node.create_channel(last_random_pk, 100_000, 0, 42, None, None).unwrap(); - get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, last_random_pk); - - // 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()); - - // Further, because the first channel was funded, we can open another channel with - // last_random_pk. - nodes[1].node.handle_open_channel(&last_random_pk, &open_channel_msg); - get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, last_random_pk); - } - - #[test] - fn test_outbound_chans_unlimited() { - // Test that we never refuse an outbound channel even if a peer is unfuned-channel-limited - 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); - - // 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()); - - for _ in 0..super::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); - } - - // 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); - - // 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(); - 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); - } - - #[test] - fn test_0conf_limiting() { - // Tests that we properly limit inbound channels when we have the manual-channel-acceptance - // flag set and (sometimes) accept channels as 0conf. - let chanmon_cfgs = create_chanmon_cfgs(2); - let node_cfgs = create_node_cfgs(2, &chanmon_cfgs); - let mut settings = test_default_channel_config(); - settings.manually_accept_inbound_channels = true; - let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(settings)]); - let nodes = create_network(2, &node_cfgs, &node_chanmgrs); - - // 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()); - - // First, get us up to MAX_UNFUNDED_CHANNEL_PEERS so we can test at the edge - for _ in 0..super::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(); - - 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(); - } - _ => 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); - } - - // 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(); - 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"), - _ => panic!(), - } - } - _ => panic!("Unexpected event"), - } - 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(); - } - _ => panic!("Unexpected event"), - } - get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, last_random_pk); - } - - #[test] - fn reject_excessively_underpaying_htlcs() { - 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 sender_intended_amt_msat = 100; - let extra_fee_msat = 10; - let hop_data = msgs::InboundOnionPayload::Receive { - 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, - }), - custom_tlvs: Vec::new(), - }; - // Check that if the amount we received + the penultimate hop extra fee is less than the sender - // 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) - { - assert_eq!(err_code, 19); - } 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 - 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, - }), - 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()); - } - - #[test] - 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); - - // Should not return an error as this condition: - // https://github.com/lightning/bolts/blob/4dcc377209509b13cf89a4b91fde7d478f5b46d8/04-onion-routing.md?plain=1#L334 - // is not satisfied. - assert!(result.is_ok()); - } - - #[test] - fn test_inbound_anchors_manual_acceptance() { - // Tests that we properly limit inbound channels when we have the manual-channel-acceptance - // flag set and (sometimes) accept channels as 0conf. - let mut anchors_cfg = test_default_channel_config(); - anchors_cfg.channel_handshake_config.negotiate_anchors_zero_fee_htlc_tx = true; - - let mut anchors_manual_accept_cfg = anchors_cfg.clone(); - anchors_manual_accept_cfg.manually_accept_inbound_channels = true; - - 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 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[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()); - let msg_events = nodes[1].node.get_and_clear_pending_msg_events(); - match &msg_events[0] { - 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()), - _ => 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(), - _ => panic!("Unexpected event"), - } - get_event_msg!(nodes[2], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id()); - } - - #[test] - fn test_anchors_zero_fee_htlc_tx_fallback() { - // Tests that if both nodes support anchors, but the remote node does not want to accept - // anchor channels at the moment, an error it sent to the local node such that it can retry - // the channel without the anchors feature. - 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.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 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[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(); - } - _ => 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()); - - // Since nodes[1] should not have accepted the channel, it should - // not have generated any events. - assert!(nodes[1].node.get_and_clear_pending_events().is_empty()); - } - - #[test] - fn test_update_channel_config() { - let chanmon_cfg = create_chanmon_cfgs(2); - let node_cfg = create_node_cfgs(2, &chanmon_cfg); - let mut user_config = test_default_channel_config(); - let node_chanmgr = create_node_chanmgrs(2, &node_cfg, &[Some(user_config), Some(user_config)]); - let nodes = create_network(2, &node_cfg, &node_chanmgr); - 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(); - 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); - let events = nodes[0].node.get_and_clear_pending_msg_events(); - assert_eq!(events.len(), 1); - match &events[0] { - MessageSendEvent::BroadcastChannelUpdate { .. } => {}, - _ => panic!("expected BroadcastChannelUpdate event"), - } - - 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); - let events = nodes[0].node.get_and_clear_pending_msg_events(); - assert_eq!(events.len(), 1); - match &events[0] { - MessageSendEvent::BroadcastChannelUpdate { .. } => {}, - _ => panic!("expected BroadcastChannelUpdate event"), - } - - 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); - let events = nodes[0].node.get_and_clear_pending_msg_events(); - assert_eq!(events.len(), 1); - match &events[0] { - MessageSendEvent::BroadcastChannelUpdate { .. } => {}, - _ => panic!("expected BroadcastChannelUpdate event"), - } - - // 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 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 { - forwarding_fee_proportional_millionths: Some(new_fee), - ..Default::default() - }), - 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); - let events = nodes[0].node.get_and_clear_pending_msg_events(); - assert_eq!(events.len(), 0); - } - - #[test] - fn test_payment_display() { - let payment_id = PaymentId([42; 32]); - assert_eq!(format!("{}", &payment_id), "2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a"); - let payment_hash = PaymentHash([42; 32]); - assert_eq!(format!("{}", &payment_hash), "2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a"); - let payment_preimage = PaymentPreimage([42; 32]); - assert_eq!(format!("{}", &payment_preimage), "2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a"); - } - - #[test] - fn test_trigger_lnd_force_close() { - let chanmon_cfg = create_chanmon_cfgs(2); - let node_cfg = create_node_cfgs(2, &chanmon_cfg); - let user_config = test_default_channel_config(); - let node_chanmgr = create_node_chanmgrs(2, &node_cfg, &[Some(user_config), Some(user_config)]); - let nodes = create_network(2, &node_cfg, &node_chanmgr); - - // Open a channel, immediately disconnect each other, and broadcast Alice's latest state. - 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(); - 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); - { - let txn = nodes[0].tx_broadcaster.txn_broadcast(); - assert_eq!(txn.len(), 1); - check_spends!(txn[0], funding_tx); - } - - // 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(); - 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[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 - // close even if it was an lnd node. - let msg_events = nodes[0].node.get_and_clear_pending_msg_events(); - assert_eq!(msg_events.len(), 2); - if let MessageSendEvent::SendChannelReestablish { node_id, msg } = &msg_events[0] { - assert_eq!(*node_id, nodes[1].node.get_our_node_id()); - 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!() }; - 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() - }; - 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); - check_spends!(txn[0], funding_tx); - } - } - - #[test] - fn test_malformed_forward_htlcs_ser() { - // Ensure that `HTLCForwardInfo::FailMalformedHTLC`s are (de)serialized properly. - let chanmon_cfg = create_chanmon_cfgs(1); - let node_cfg = create_node_cfgs(1, &chanmon_cfg); - let persister; - let chain_monitor; - let chanmgrs = create_node_chanmgrs(1, &node_cfg, &[None]); - 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_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 (scid_1, scid_2) = (42, 43); - let mut forward_htlcs = new_hash_map(); - forward_htlcs.insert(scid_1, dummy_htlcs_1.clone()); - forward_htlcs.insert(scid_2, dummy_htlcs_2.clone()); - - let mut chanmgr_fwd_htlcs = nodes[0].node.forward_htlcs.lock().unwrap(); - *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); - - let mut deserialized_fwd_htlcs = nodes[0].node.forward_htlcs.lock().unwrap(); - for scid in [scid_1, scid_2].iter() { - let deserialized_htlcs = deserialized_fwd_htlcs.remove(scid).unwrap(); - assert_eq!(forward_htlcs.remove(scid).unwrap(), deserialized_htlcs); - } - assert!(deserialized_fwd_htlcs.is_empty()); - core::mem::drop(deserialized_fwd_htlcs); - - expect_pending_htlcs_forwardable!(nodes[0]); - } -} - #[cfg(ldk_bench)] pub mod bench { use crate::chain::Listen; diff --git a/lightning/src/ln/channelmanager_limits_tests.rs b/lightning/src/ln/channelmanager_limits_tests.rs new file mode 100644 index 00000000000..930ebc1a619 --- /dev/null +++ b/lightning/src/ln/channelmanager_limits_tests.rs @@ -0,0 +1,655 @@ +use bitcoin::hashes::Hash; +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::prelude::*; +use crate::util::config::ChannelConfig; +use crate::sign::EntropySource; + + +#[test] +fn test_notify_limits() { + // Check that a few cases which don't require the persistence of a new ChannelManager, + // indeed, do not cause the persistence of a new ChannelManager. + 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 nodes = create_network(3, &node_cfgs, &node_chanmgrs); + + // All nodes start with a persistable update pending as `create_network` connects each node + // with all other nodes to make most tests simpler. + assert!(nodes[0].node.get_event_or_persistence_needed_future().poll_is_complete()); + assert!(nodes[1].node.get_event_or_persistence_needed_future().poll_is_complete()); + assert!(nodes[2].node.get_event_or_persistence_needed_future().poll_is_complete()); + + let mut chan = create_announced_chan_between_nodes(&nodes, 0, 1); + + // We check that the channel info nodes have doesn't change too early, even though we try + // 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(); + + // 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()); + assert!(nodes[1].node.get_event_or_persistence_needed_future().poll_is_complete()); + // ... but the last node should not. + assert!(!nodes[2].node.get_event_or_persistence_needed_future().poll_is_complete()); + // After persisting the first two nodes they should no longer need fresh persistence. + assert!(!nodes[0].node.get_event_or_persistence_needed_future().poll_is_complete()); + assert!(!nodes[1].node.get_event_or_persistence_needed_future().poll_is_complete()); + + // Node 3, unrelated to the only channel, shouldn't care if it receives a channel_update + // about the channel. + nodes[2].node.handle_channel_update(&nodes[1].node.get_our_node_id(), &chan.0); + nodes[2].node.handle_channel_update(&nodes[1].node.get_our_node_id(), &chan.1); + assert!(!nodes[2].node.get_event_or_persistence_needed_future().poll_is_complete()); + + // The nodes which are a party to the channel should also ignore messages from unrelated + // parties. + nodes[0].node.handle_channel_update(&nodes[2].node.get_our_node_id(), &chan.0); + nodes[0].node.handle_channel_update(&nodes[2].node.get_our_node_id(), &chan.1); + nodes[1].node.handle_channel_update(&nodes[2].node.get_our_node_id(), &chan.0); + nodes[1].node.handle_channel_update(&nodes[2].node.get_our_node_id(), &chan.1); + assert!(!nodes[0].node.get_event_or_persistence_needed_future().poll_is_complete()); + assert!(!nodes[1].node.get_event_or_persistence_needed_future().poll_is_complete()); + + // At this point the channel info given by peers should still be the same. + assert_eq!(nodes[0].node.list_channels()[0], node_a_chan_info); + assert_eq!(nodes[1].node.list_channels()[0], node_b_chan_info); + + // 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 }; + + // First deliver each peers' own message, checking that the node doesn't need to be + // persisted and that its channel info remains the same. + nodes[0].node.handle_channel_update(&nodes[1].node.get_our_node_id(), &as_update); + nodes[1].node.handle_channel_update(&nodes[0].node.get_our_node_id(), &bs_update); + assert!(!nodes[0].node.get_event_or_persistence_needed_future().poll_is_complete()); + assert!(!nodes[1].node.get_event_or_persistence_needed_future().poll_is_complete()); + assert_eq!(nodes[0].node.list_channels()[0], node_a_chan_info); + assert_eq!(nodes[1].node.list_channels()[0], node_b_chan_info); + + // Finally, deliver the other peers' message, ensuring each node needs to be persisted and + // the channel info has updated. + nodes[0].node.handle_channel_update(&nodes[1].node.get_our_node_id(), &bs_update); + nodes[1].node.handle_channel_update(&nodes[0].node.get_our_node_id(), &as_update); + assert!(nodes[0].node.get_event_or_persistence_needed_future().poll_is_complete()); + assert!(nodes[1].node.get_event_or_persistence_needed_future().poll_is_complete()); + assert_ne!(nodes[0].node.list_channels()[0], node_a_chan_info); + assert_ne!(nodes[1].node.list_channels()[0], node_b_chan_info); +} + +#[test] +fn test_drop_disconnected_peers_when_removing_channels() { + 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); + + let chan = 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.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); + + { + // Assert that nodes[1] is awaiting removal for nodes[0] once nodes[1] has been + // disconnected and the channel between has been force closed. + let nodes_0_per_peer_state = nodes[0].node.per_peer_state.read().unwrap(); + // Assert that nodes[1] isn't removed before `timer_tick_occurred` has been executed. + assert_eq!(nodes_0_per_peer_state.len(), 1); + assert!(nodes_0_per_peer_state.get(&nodes[1].node.get_our_node_id()).is_some()); + } + + nodes[0].node.timer_tick_occurred(); + + { + // Assert that nodes[1] has now been removed. + assert_eq!(nodes[0].node.per_peer_state.read().unwrap().len(), 0); + } +} + +#[test] +fn test_outpoint_to_peer_coverage() { + // Test that the `ChannelManager:outpoint_to_peer` contains channels which have been assigned + // a `channel_id` (i.e. have had the funding tx created), and that they are removed once + // the channel is successfully closed. + 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); + + 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()); + 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 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 + // funding transaction, and have the real `channel_id`. + assert_eq!(nodes[0].node.outpoint_to_peer.lock().unwrap().len(), 0); + 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(); + { + // Assert that `nodes[0]`'s `outpoint_to_peer` map is populated with the channel as soon as + // as it has the funding transaction. + let nodes_0_lock = nodes[0].node.outpoint_to_peer.lock().unwrap(); + assert_eq!(nodes_0_lock.len(), 1); + assert!(nodes_0_lock.contains_key(&funding_output)); + } + + 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()); + + nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg); + { + let nodes_0_lock = nodes[0].node.outpoint_to_peer.lock().unwrap(); + assert_eq!(nodes_0_lock.len(), 1); + assert!(nodes_0_lock.contains_key(&funding_output)); + } + expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id()); + + { + // Assert that `nodes[1]`'s `outpoint_to_peer` map is populated with the channel as + // soon as it has the funding transaction. + let nodes_1_lock = nodes[1].node.outpoint_to_peer.lock().unwrap(); + assert_eq!(nodes_1_lock.len(), 1); + 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()); + 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); + 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[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()); + 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 + // channel can be fully closed by both parties (i.e. no outstanding htlcs exists, the + // fee for the closing transaction has been negotiated and the parties has the other + // party's signature for the fee negotiated closing transaction.) + let nodes_0_lock = nodes[0].node.outpoint_to_peer.lock().unwrap(); + assert_eq!(nodes_0_lock.len(), 1); + assert!(nodes_0_lock.contains_key(&funding_output)); + } + + { + // At this stage, `nodes[1]` has proposed a fee for the closing transaction in the + // `handle_closing_signed` call above. As `nodes[1]` has not yet received the signature + // from `nodes[0]` for the closing transaction with the proposed fee, the channel is + // kept in the `nodes[1]`'s `outpoint_to_peer` map. + let nodes_1_lock = nodes[1].node.outpoint_to_peer.lock().unwrap(); + assert_eq!(nodes_1_lock.len(), 1); + 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]` 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 + // closing transaction). + // Assert that the channel is removed from `nodes[0]`'s `outpoint_to_peer` map as it can be + // fully closed by `nodes[0]`. + assert_eq!(nodes[0].node.outpoint_to_peer.lock().unwrap().len(), 0); + + // Assert that the channel is still in `nodes[1]`'s `outpoint_to_peer` map, as `nodes[1]` + // doesn't have `nodes[0]`'s signature for the closing transaction yet. + let nodes_1_lock = nodes[1].node.outpoint_to_peer.lock().unwrap(); + assert_eq!(nodes_1_lock.len(), 1); + 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()); + + 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); +} + + +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); + 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); + check_api_error_message(expected_message, res_err) +} + +fn check_api_misuse_error(res_err: Result) { + let expected_message = "No such channel awaiting to be accepted.".to_string(); + check_api_error_message(expected_message, res_err) +} + +fn check_api_error_message(expected_err_message: String, res_err: Result) { + match res_err { + Err(APIError::APIMisuseError { err }) => { + assert_eq!(err, expected_err_message); + }, + Err(APIError::ChannelUnavailable { err }) => { + assert_eq!(err, expected_err_message); + }, + Ok(_) => panic!("Unexpected Ok"), + Err(_) => panic!("Unexpected Error"), + } +} + +#[test] +fn test_api_calls_with_unkown_counterparty_node() { + // Tests that our API functions that expects a `counterparty_node_id` as input, behaves as + // expected if the `counterparty_node_id` is an unkown peer in the + // `ChannelManager::per_peer_state` map. + let chanmon_cfg = create_chanmon_cfgs(2); + let node_cfg = create_node_cfgs(2, &chanmon_cfg); + let node_chanmgr = create_node_chanmgrs(2, &node_cfg, &[None, None]); + let nodes = create_network(2, &node_cfg, &node_chanmgr); + + // 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 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_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.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.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); +} + +#[test] +fn test_api_calls_with_unavailable_channel() { + // Tests that our API functions that expects a `counterparty_node_id` and a `channel_id` + // as input, behaves as expected if the `counterparty_node_id` is a known peer in the + // `ChannelManager::per_peer_state` map, but the peer state doesn't contain a channel with + // the given `channel_id`. + let chanmon_cfg = create_chanmon_cfgs(2); + let node_cfg = create_node_cfgs(2, &chanmon_cfg); + let node_chanmgr = create_node_chanmgrs(2, &node_cfg, &[None, None]); + let nodes = create_network(2, &node_cfg, &node_chanmgr); + + let counterparty_node_id = nodes[1].node.get_our_node_id(); + + // Dummy values + 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_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.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); +} + +#[test] +fn test_connection_limiting() { + // Test that we limit un-channel'd peers and un-funded channels properly. + 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); + + // 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()); + + 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()); + + 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); + 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); + 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()); + + 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); + } + + // 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); + 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); + + // 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()); + 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(); + } + 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. + nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id()); + 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!(); } + } + 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_disconnected(&nodes[0].node.get_our_node_id()); + + // Now nodes[0] is disconnected but still has a pending, un-funded channel lying around. + // Even though we accept one more connection from new peers, we won't actually let them + // open channels. + assert!(peer_pks.len() > channelmanager::MAX_UNFUNDED_CHANNEL_PEERS - 1); + 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); + } + 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); + + // Of course, however, outbound channels are always allowed + nodes[1].node.create_channel(last_random_pk, 100_000, 0, 42, None, None).unwrap(); + get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, last_random_pk); + + // 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()); + + // Further, because the first channel was funded, we can open another channel with + // last_random_pk. + nodes[1].node.handle_open_channel(&last_random_pk, &open_channel_msg); + get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, last_random_pk); +} + +#[test] +fn test_outbound_chans_unlimited() { + // Test that we never refuse an outbound channel even if a peer is unfuned-channel-limited + 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); + + // 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()); + + 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); + } + + // 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); + + // 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(); + 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); +} + +#[test] +fn test_0conf_limiting() { + // Tests that we properly limit inbound channels when we have the manual-channel-acceptance + // flag set and (sometimes) accept channels as 0conf. + let chanmon_cfgs = create_chanmon_cfgs(2); + let node_cfgs = create_node_cfgs(2, &chanmon_cfgs); + let mut settings = test_default_channel_config(); + settings.manually_accept_inbound_channels = true; + let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(settings)]); + let nodes = create_network(2, &node_cfgs, &node_chanmgrs); + + // 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()); + + // 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(); + + 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(); + } + _ => 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); + } + + // 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(); + 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"), + _ => panic!(), + } + } + _ => panic!("Unexpected event"), + } + 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(); + } + _ => panic!("Unexpected event"), + } + get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, last_random_pk); +} + +#[test] +fn test_trigger_lnd_force_close() { + let chanmon_cfg = create_chanmon_cfgs(2); + let node_cfg = create_node_cfgs(2, &chanmon_cfg); + let user_config = test_default_channel_config(); + let node_chanmgr = create_node_chanmgrs(2, &node_cfg, &[Some(user_config), Some(user_config)]); + let nodes = create_network(2, &node_cfg, &node_chanmgr); + + // Open a channel, immediately disconnect each other, and broadcast Alice's latest state. + 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(); + 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); + { + let txn = nodes[0].tx_broadcaster.txn_broadcast(); + assert_eq!(txn.len(), 1); + check_spends!(txn[0], funding_tx); + } + + // 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(); + 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[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 + // close even if it was an lnd node. + let msg_events = nodes[0].node.get_and_clear_pending_msg_events(); + assert_eq!(msg_events.len(), 2); + if let MessageSendEvent::SendChannelReestablish { node_id, msg } = &msg_events[0] { + assert_eq!(*node_id, nodes[1].node.get_our_node_id()); + 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!() }; + 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() + }; + 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); + check_spends!(txn[0], funding_tx); + } +} + +#[test] +fn test_multi_hop_missing_secret() { + 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 nodes = create_network(4, &node_cfgs, &node_chanmgrs); + + let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id; + let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2).0.contents.short_channel_id; + let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3).0.contents.short_channel_id; + let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3).0.contents.short_channel_id; + + // Marshall an MPP route. + let (mut route, payment_hash, _, _) = get_route_and_payment_hash!(&nodes[0], nodes[3], 100000); + let path = route.paths[0].clone(); + route.paths.push(path); + route.paths[0].hops[0].pubkey = nodes[1].node.get_our_node_id(); + route.paths[0].hops[0].short_channel_id = chan_1_id; + route.paths[0].hops[1].short_channel_id = chan_3_id; + route.paths[1].hops[0].pubkey = nodes[2].node.get_our_node_id(); + 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() { + PaymentSendFailure::ParameterError(APIError::APIMisuseError { ref err }) => { + assert!(regex::Regex::new(r"Payment secret is required for multi-path payments").unwrap().is_match(err)) + }, + _ => panic!("unexpected error") + } +} diff --git a/lightning/src/ln/keysend_payments_tests.rs b/lightning/src/ln/keysend_payments_tests.rs new file mode 100644 index 00000000000..df9acf60cae --- /dev/null +++ b/lightning/src/ln/keysend_payments_tests.rs @@ -0,0 +1,550 @@ +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::msgs::ChannelMessageHandler; +use crate::prelude::*; +use crate::routing::router::{PaymentParameters, RouteParameters, find_route}; +use crate::util::ser::Writeable; +use crate::util::test_utils; +use crate::sign::EntropySource; + +#[test] +fn test_keysend_dup_hash_partial_mpp() { + // Test that a keysend payment with a duplicate hash to an existing partial MPP payment fails as + // expected. + 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); + 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 mut mpp_route = route.clone(); + mpp_route.paths.push(mpp_route.paths[0].clone()); + + let payment_id = PaymentId([42; 32]); + // 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(); + 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); + + // 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(); + check_added_monitors!(nodes[0], 1); + let mut events = nodes[0].node.get_and_clear_pending_msg_events(); + assert_eq!(events.len(), 1); + let ev = events.drain(..).next().unwrap(); + 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); + 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 }]); + 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()); + assert!(updates.update_fulfill_htlcs.is_empty()); + 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]); + 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(); + 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); + + // 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 + // payment to be put in the holding cell, which confuses the test utilities. So we exchange the + // lightning messages manually. + nodes[1].node.claim_funds(payment_preimage); + expect_payment_claimed!(nodes[1], our_payment_hash, 200_000); + 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]); + 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); + 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()); + 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); + check_added_monitors!(nodes[0], 1); + 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); + check_added_monitors!(nodes[1], 1); + 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); + + // Note that successful MPP payments will generate a single PaymentSent event upon the first + // path's success and a PaymentPathSuccessful event for each path's success. + 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 } => { + assert_eq!(payment_id, *actual_payment_id); + assert_eq!(our_payment_hash, *payment_hash.as_ref().unwrap()); + assert_eq!(route.paths[0], *path); + }, + _ => panic!("Unexpected event"), + } + match events[1] { + 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); + }, + _ => panic!("Unexpected event"), + } +} + + +#[test] +fn test_keysend_dup_payment_hash() { + do_test_keysend_dup_payment_hash(false); + do_test_keysend_dup_payment_hash(true); +} + +fn do_test_keysend_dup_payment_hash(accept_mpp_keysend: bool) { + // (1): Test that a keysend payment with a duplicate payment hash to an existing pending + // outbound regular payment fails as expected. + // (2): Test that a regular payment with a duplicate payment hash to an existing keysend payment + // fails as expected. + // (3): Test that a keysend payment with a duplicate payment hash to an existing keysend + // payment fails as expected. When `accept_mpp_keysend` is false, this tests that we + // reject MPP keysend payments, since in this case where the payment has no payment + // secret, a keysend payment with a duplicate hash is basically an MPP keysend. If + // `accept_mpp_keysend` is true, this tests that we only accept MPP keysends with + // payment secrets and reject otherwise. + let chanmon_cfgs = create_chanmon_cfgs(2); + let node_cfgs = create_node_cfgs(2, &chanmon_cfgs); + let mut mpp_keysend_cfg = test_default_channel_config(); + mpp_keysend_cfg.accept_mpp_keysend = accept_mpp_keysend; + let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(mpp_keysend_cfg)]); + let nodes = create_network(2, &node_cfgs, &node_chanmgrs); + create_announced_chan_between_nodes(&nodes, 0, 1); + let scorer = test_utils::TestScorer::new(); + let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes(); + + // To start (1), send a regular payment but don't claim it. + let expected_route = [&nodes[1]]; + let (payment_preimage, payment_hash, ..) = route_payment(&nodes[0], &expected_route, 100_000); + + // 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); + 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(); + check_added_monitors!(nodes[0], 1); + let mut events = nodes[0].node.get_and_clear_pending_msg_events(); + assert_eq!(events.len(), 1); + let ev = events.drain(..).next().unwrap(); + 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); + commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false); + // 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 }]); + 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()); + assert!(updates.update_fulfill_htlcs.is_empty()); + 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]); + commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, true, true); + expect_payment_failed!(nodes[0], payment_hash, true); + + // Finally, claim the original payment. + claim_payment(&nodes[0], &expected_route, payment_preimage); + + // 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(); + 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)); + + // 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(); + check_added_monitors!(nodes[0], 1); + let mut events = nodes[0].node.get_and_clear_pending_msg_events(); + assert_eq!(events.len(), 1); + let ev = events.drain(..).next().unwrap(); + 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); + 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 }]); + 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()); + assert!(updates.update_fulfill_htlcs.is_empty()); + 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]); + commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, true, true); + expect_payment_failed!(nodes[0], payment_hash, true); + + // Finally, succeed the keysend payment. + claim_payment(&nodes[0], &expected_route, payment_preimage); + + // 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(); + 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)); + + // 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 + ); + 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_id_2 = PaymentId([45; 32]); + 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); + let ev = events.drain(..).next().unwrap(); + 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); + 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 }]); + 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()); + assert!(updates.update_fulfill_htlcs.is_empty()); + 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]); + commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, true, true); + expect_payment_failed!(nodes[0], payment_hash, true); + + // Finally, claim the original payment. + claim_payment(&nodes[0], &expected_route, payment_preimage); +} + +#[test] +fn test_keysend_hash_mismatch() { + // Test that if we receive a keysend `update_add_htlc` msg, we fail as expected if the keysend + // preimage doesn't match the msg's payment hash. + 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); + + let payer_pubkey = nodes[0].node.get_our_node_id(); + let payee_pubkey = nodes[1].node.get_our_node_id(); + + 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); + 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(); + + 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(); + check_added_monitors!(nodes[0], 1); + + let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id()); + assert_eq!(updates.update_add_htlcs.len(), 1); + assert!(updates.update_fulfill_htlcs.is_empty()); + 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); +} + +#[test] +fn test_keysend_msg_with_secret_err() { + // Test that we error as expected if we receive a keysend payment that includes a payment + // secret when we don't support MPP keysend. + let mut reject_mpp_keysend_cfg = test_default_channel_config(); + reject_mpp_keysend_cfg.accept_mpp_keysend = false; + 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, Some(reject_mpp_keysend_cfg)]); + let nodes = create_network(2, &node_cfgs, &node_chanmgrs); + + let payer_pubkey = nodes[0].node.get_our_node_id(); + let payee_pubkey = nodes[1].node.get_our_node_id(); + + 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); + 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(); + + 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(); + check_added_monitors!(nodes[0], 1); + + let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id()); + assert_eq!(updates.update_add_htlcs.len(), 1); + assert!(updates.update_fulfill_htlcs.is_empty()); + 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); +} + +#[test] +fn bad_inbound_payment_hash() { + // Add coverage for checking that a user-provided payment hash matches the payment secret. + 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); + + let (_, payment_hash, payment_secret) = get_payment_preimage_hash!(&nodes[0]); + 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) { + Ok(_) => panic!("Unexpected ok"), + Err(()) => { + 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()); +} + +#[test] +fn reject_excessively_underpaying_htlcs() { + 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 sender_intended_amt_msat = 100; + let extra_fee_msat = 10; + let hop_data = msgs::InboundOnionPayload::Receive { + 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, + }), + custom_tlvs: Vec::new(), + }; + // Check that if the amount we received + the penultimate hop extra fee is less than the sender + // 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) + { + assert_eq!(err_code, 19); + } 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 + 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, + }), + 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()); +} + +#[test] +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); + + // Should not return an error as this condition: + // https://github.com/lightning/bolts/blob/4dcc377209509b13cf89a4b91fde7d478f5b46d8/04-onion-routing.md?plain=1#L334 + // is not satisfied. + assert!(result.is_ok()); +} + +#[test] +fn test_payment_display() { + let payment_id = PaymentId([42; 32]); + assert_eq!(format!("{}", &payment_id), "2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a"); + let payment_hash = PaymentHash([42; 32]); + assert_eq!(format!("{}", &payment_hash), "2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a"); + let payment_preimage = PaymentPreimage([42; 32]); + assert_eq!(format!("{}", &payment_preimage), "2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a"); +} + +#[test] +fn test_malformed_forward_htlcs_ser() { + // Ensure that `HTLCForwardInfo::FailMalformedHTLC`s are (de)serialized properly. + let chanmon_cfg = create_chanmon_cfgs(1); + let node_cfg = create_node_cfgs(1, &chanmon_cfg); + let persister; + let chain_monitor; + let chanmgrs = create_node_chanmgrs(1, &node_cfg, &[None]); + 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_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 (scid_1, scid_2) = (42, 43); + let mut forward_htlcs = new_hash_map(); + forward_htlcs.insert(scid_1, dummy_htlcs_1.clone()); + forward_htlcs.insert(scid_2, dummy_htlcs_2.clone()); + + let mut chanmgr_fwd_htlcs = nodes[0].node.forward_htlcs.lock().unwrap(); + *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); + + let mut deserialized_fwd_htlcs = nodes[0].node.forward_htlcs.lock().unwrap(); + for scid in [scid_1, scid_2].iter() { + let deserialized_htlcs = deserialized_fwd_htlcs.remove(scid).unwrap(); + assert_eq!(forward_htlcs.remove(scid).unwrap(), deserialized_htlcs); + } + assert!(deserialized_fwd_htlcs.is_empty()); + core::mem::drop(deserialized_fwd_htlcs); + + expect_pending_htlcs_forwardable!(nodes[0]); +}