Remove `Outpoint::to_channel_id` method
[rust-lightning] / lightning / src / ln / blinded_payment_tests.rs
index 0558de52ec04ab2dd9d0011f379b98a7fef0b927..3232cd0d33e2381a44dc0afa98ea87dd1be39086 100644 (file)
@@ -10,7 +10,7 @@
 use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey};
 use crate::blinded_path::BlindedPath;
 use crate::blinded_path::payment::{ForwardNode, ForwardTlvs, PaymentConstraints, PaymentRelay, ReceiveTlvs};
-use crate::events::{HTLCDestination, MessageSendEvent, MessageSendEventsProvider};
+use crate::events::{Event, HTLCDestination, MessageSendEvent, MessageSendEventsProvider, PaymentFailureReason};
 use crate::ln::PaymentSecret;
 use crate::ln::channelmanager;
 use crate::ln::channelmanager::{PaymentId, RecipientOnionFields};
@@ -21,15 +21,16 @@ use crate::ln::msgs::ChannelMessageHandler;
 use crate::ln::onion_utils;
 use crate::ln::onion_utils::INVALID_ONION_BLINDING;
 use crate::ln::outbound_payment::Retry;
+use crate::offers::invoice::BlindedPayInfo;
 use crate::prelude::*;
-use crate::routing::router::{PaymentParameters, RouteParameters};
+use crate::routing::router::{Payee, PaymentParameters, RouteParameters};
 use crate::util::config::UserConfig;
 use crate::util::test_utils;
 
-pub fn get_blinded_route_parameters(
-       amt_msat: u64, payment_secret: PaymentSecret, node_ids: Vec<PublicKey>,
+fn blinded_payment_path(
+       payment_secret: PaymentSecret, node_ids: Vec<PublicKey>,
        channel_upds: &[&msgs::UnsignedChannelUpdate], keys_manager: &test_utils::TestKeysInterface
-) -> RouteParameters {
+) -> (BlindedPayInfo, BlindedPath) {
        let mut intermediate_nodes = Vec::new();
        for (node_id, chan_upd) in node_ids.iter().zip(channel_upds) {
                intermediate_nodes.push(ForwardNode {
@@ -58,13 +59,20 @@ pub fn get_blinded_route_parameters(
                },
        };
        let mut secp_ctx = Secp256k1::new();
-       let blinded_path = BlindedPath::new_for_payment(
+       BlindedPath::new_for_payment(
                &intermediate_nodes[..], *node_ids.last().unwrap(), payee_tlvs,
                channel_upds.last().unwrap().htlc_maximum_msat, keys_manager, &secp_ctx
-       ).unwrap();
+       ).unwrap()
+}
 
+pub fn get_blinded_route_parameters(
+       amt_msat: u64, payment_secret: PaymentSecret, node_ids: Vec<PublicKey>,
+       channel_upds: &[&msgs::UnsignedChannelUpdate], keys_manager: &test_utils::TestKeysInterface
+) -> RouteParameters {
        RouteParameters::from_payment_params_and_value(
-               PaymentParameters::blinded(vec![blinded_path]), amt_msat
+               PaymentParameters::blinded(vec![
+                       blinded_payment_path(payment_secret, node_ids, channel_upds, keys_manager)
+               ]), amt_msat
        )
 }
 
@@ -490,6 +498,29 @@ fn two_hop_blinded_path_success() {
        claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
 }
 
+#[test]
+fn three_hop_blinded_path_success() {
+       let chanmon_cfgs = create_chanmon_cfgs(5);
+       let node_cfgs = create_node_cfgs(5, &chanmon_cfgs);
+       let node_chanmgrs = create_node_chanmgrs(5, &node_cfgs, &[None, None, None, None, None]);
+       let mut nodes = create_network(5, &node_cfgs, &node_chanmgrs);
+       create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0);
+       create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1_000_000, 0);
+       let chan_upd_2_3 = create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 1_000_000, 0).0.contents;
+       let chan_upd_3_4 = create_announced_chan_between_nodes_with_value(&nodes, 3, 4, 1_000_000, 0).0.contents;
+
+       let amt_msat = 5000;
+       let (payment_preimage, payment_hash, payment_secret) = get_payment_preimage_hash(&nodes[4], Some(amt_msat), None);
+       let route_params = get_blinded_route_parameters(amt_msat, payment_secret,
+               nodes.iter().skip(2).map(|n| n.node.get_our_node_id()).collect(),
+               &[&chan_upd_2_3, &chan_upd_3_4], &chanmon_cfgs[4].keys_manager);
+
+       nodes[0].node.send_payment(payment_hash, RecipientOnionFields::spontaneous_empty(), PaymentId(payment_hash.0), route_params, Retry::Attempts(0)).unwrap();
+       check_added_monitors(&nodes[0], 1);
+       pass_along_route(&nodes[0], &[&[&nodes[1], &nodes[2], &nodes[3], &nodes[4]]], amt_msat, payment_hash, payment_secret);
+       claim_payment(&nodes[0], &[&nodes[1], &nodes[2], &nodes[3], &nodes[4]], payment_preimage);
+}
+
 #[derive(PartialEq)]
 enum ReceiveCheckFail {
        // The recipient fails the payment upon `PaymentClaimable`.
@@ -505,6 +536,8 @@ enum ReceiveCheckFail {
        // The HTLC is successfully added to the inbound channel but fails receive checks in
        // process_pending_htlc_forwards.
        ProcessPendingHTLCsCheck,
+       // The HTLC violates the `PaymentConstraints` contained within the receiver's encrypted payload.
+       PaymentConstraints,
 }
 
 #[test]
@@ -514,6 +547,7 @@ fn multi_hop_receiver_fail() {
        do_multi_hop_receiver_fail(ReceiveCheckFail::ReceiveRequirements);
        do_multi_hop_receiver_fail(ReceiveCheckFail::ChannelCheck);
        do_multi_hop_receiver_fail(ReceiveCheckFail::ProcessPendingHTLCsCheck);
+       do_multi_hop_receiver_fail(ReceiveCheckFail::PaymentConstraints);
 }
 
 fn do_multi_hop_receiver_fail(check: ReceiveCheckFail) {
@@ -534,21 +568,40 @@ fn do_multi_hop_receiver_fail(check: ReceiveCheckFail) {
        };
 
        let amt_msat = 5000;
-       let final_cltv_delta = if check == ReceiveCheckFail::ProcessPendingHTLCsCheck {
+       let excess_final_cltv_delta_opt = if check == ReceiveCheckFail::ProcessPendingHTLCsCheck {
                // Set the final CLTV expiry too low to trigger the failure in process_pending_htlc_forwards.
                Some(TEST_FINAL_CLTV as u16 - 2)
        } else { None };
-       let (_, payment_hash, payment_secret) = get_payment_preimage_hash(&nodes[2], Some(amt_msat), final_cltv_delta);
-       let route_params = get_blinded_route_parameters(amt_msat, payment_secret,
+       let (_, payment_hash, payment_secret) = get_payment_preimage_hash(&nodes[2], Some(amt_msat), excess_final_cltv_delta_opt);
+       let mut route_params = get_blinded_route_parameters(amt_msat, payment_secret,
                nodes.iter().skip(1).map(|n| n.node.get_our_node_id()).collect(), &[&chan_upd_1_2],
                &chanmon_cfgs[2].keys_manager);
 
        let route = if check == ReceiveCheckFail::ProcessPendingHTLCsCheck {
                let mut route = get_route(&nodes[0], &route_params).unwrap();
                // Set the final CLTV expiry too low to trigger the failure in process_pending_htlc_forwards.
-               route.paths[0].blinded_tail.as_mut().map(|bt| bt.excess_final_cltv_expiry_delta = TEST_FINAL_CLTV - 2);
+               route.paths[0].hops.last_mut().map(|h| h.cltv_expiry_delta += excess_final_cltv_delta_opt.unwrap() as u32);
+               route.paths[0].blinded_tail.as_mut().map(|bt| bt.excess_final_cltv_expiry_delta = excess_final_cltv_delta_opt.unwrap() as u32);
                route
-       } else  {
+       } else if check == ReceiveCheckFail::PaymentConstraints {
+               // Create a blinded path where the receiver's encrypted payload has an htlc_minimum_msat that is
+               // violated by `amt_msat`, and stick it in the route_params without changing the corresponding
+               // BlindedPayInfo (to ensure pathfinding still succeeds).
+               let high_htlc_min_bp = {
+                       let mut high_htlc_minimum_upd = chan_upd_1_2.clone();
+                       high_htlc_minimum_upd.htlc_minimum_msat = amt_msat + 1000;
+                       let high_htlc_min_params = get_blinded_route_parameters(amt_msat, payment_secret,
+                               nodes.iter().skip(1).map(|n| n.node.get_our_node_id()).collect(), &[&high_htlc_minimum_upd],
+                               &chanmon_cfgs[2].keys_manager);
+                       if let Payee::Blinded { route_hints, .. } = high_htlc_min_params.payment_params.payee {
+                               route_hints[0].1.clone()
+                       } else { panic!() }
+               };
+               if let Payee::Blinded { ref mut route_hints, .. } = route_params.payment_params.payee {
+                       route_hints[0].1 = high_htlc_min_bp;
+               } else { panic!() }
+               find_route(&nodes[0], &route_params).unwrap()
+       } else {
                find_route(&nodes[0], &route_params).unwrap()
        };
        node_cfgs[0].router.expect_find_route(route_params.clone(), Ok(route.clone()));
@@ -636,6 +689,7 @@ fn do_multi_hop_receiver_fail(check: ReceiveCheckFail) {
                        commitment_signed_dance!(nodes[2], nodes[1], (), false, true, false, false);
                },
                ReceiveCheckFail::ProcessPendingHTLCsCheck => {
+                       assert_eq!(payment_event_1_2.msgs[0].cltv_expiry, nodes[0].best_block_info().1 + 1 + excess_final_cltv_delta_opt.unwrap() as u32);
                        nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_1_2.msgs[0]);
                        check_added_monitors!(nodes[2], 0);
                        do_commitment_signed_dance(&nodes[2], &nodes[1], &payment_event_1_2.commitment_msg, true, true);
@@ -643,6 +697,11 @@ fn do_multi_hop_receiver_fail(check: ReceiveCheckFail) {
                        expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[2],
                                vec![HTLCDestination::FailedPayment { payment_hash }]);
                        check_added_monitors!(nodes[2], 1);
+               },
+               ReceiveCheckFail::PaymentConstraints => {
+                       nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_1_2.msgs[0]);
+                       check_added_monitors!(nodes[2], 0);
+                       do_commitment_signed_dance(&nodes[2], &nodes[1], &payment_event_1_2.commitment_msg, true, true);
                }
        }
 
@@ -674,3 +733,108 @@ fn do_multi_hop_receiver_fail(check: ReceiveCheckFail) {
        expect_payment_failed_conditions(&nodes[0], payment_hash, false,
                PaymentFailedConditions::new().expected_htlc_error_data(INVALID_ONION_BLINDING, &[0; 32]));
 }
+
+#[test]
+fn blinded_path_retries() {
+       let chanmon_cfgs = create_chanmon_cfgs(4);
+       // Make one blinded path's fees slightly higher so they are tried in a deterministic order.
+       let mut higher_fee_chan_cfg = test_default_channel_config();
+       higher_fee_chan_cfg.channel_config.forwarding_fee_base_msat += 1;
+       let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
+       let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, Some(higher_fee_chan_cfg), None]);
+       let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
+
+       // Create this network topology so nodes[0] has a blinded route hint to retry over.
+       //      n1
+       //    /    \
+       // n0       n3
+       //    \    /
+       //      n2
+       create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0);
+       create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 1_000_000, 0);
+       let chan_1_3 = create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 1_000_000, 0);
+       let chan_2_3 = create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 1_000_000, 0);
+
+       let amt_msat = 5000;
+       let (_, payment_hash, payment_secret) = get_payment_preimage_hash(&nodes[3], Some(amt_msat), None);
+       let route_params = {
+               let pay_params = PaymentParameters::blinded(
+                       vec![
+                               blinded_payment_path(payment_secret,
+                                       vec![nodes[1].node.get_our_node_id(), nodes[3].node.get_our_node_id()], &[&chan_1_3.0.contents],
+                                       &chanmon_cfgs[3].keys_manager
+                               ),
+                               blinded_payment_path(payment_secret,
+                                       vec![nodes[2].node.get_our_node_id(), nodes[3].node.get_our_node_id()], &[&chan_2_3.0.contents],
+                                       &chanmon_cfgs[3].keys_manager
+                               ),
+                       ]
+               )
+                       .with_bolt12_features(channelmanager::provided_bolt12_invoice_features(&UserConfig::default()))
+                       .unwrap();
+               RouteParameters::from_payment_params_and_value(pay_params, amt_msat)
+       };
+
+       nodes[0].node.send_payment(payment_hash, RecipientOnionFields::spontaneous_empty(), PaymentId(payment_hash.0), route_params.clone(), Retry::Attempts(2)).unwrap();
+       check_added_monitors(&nodes[0], 1);
+       pass_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]]], amt_msat, payment_hash, payment_secret);
+
+       macro_rules! fail_payment_back {
+               ($intro_node: expr) => {
+                       nodes[3].node.fail_htlc_backwards(&payment_hash);
+                       expect_pending_htlcs_forwardable_conditions(
+                               nodes[3].node.get_and_clear_pending_events(), &[HTLCDestination::FailedPayment { payment_hash }]
+                       );
+                       nodes[3].node.process_pending_htlc_forwards();
+                       check_added_monitors!(nodes[3], 1);
+
+                       let updates = get_htlc_update_msgs!(nodes[3], $intro_node.node.get_our_node_id());
+                       assert_eq!(updates.update_fail_malformed_htlcs.len(), 1);
+                       let update_malformed = &updates.update_fail_malformed_htlcs[0];
+                       assert_eq!(update_malformed.sha256_of_onion, [0; 32]);
+                       assert_eq!(update_malformed.failure_code, INVALID_ONION_BLINDING);
+                       $intro_node.node.handle_update_fail_malformed_htlc(&nodes[3].node.get_our_node_id(), update_malformed);
+                       do_commitment_signed_dance(&$intro_node, &nodes[3], &updates.commitment_signed, true, false);
+
+                       let updates =  get_htlc_update_msgs!($intro_node, nodes[0].node.get_our_node_id());
+                       assert_eq!(updates.update_fail_htlcs.len(), 1);
+                       nodes[0].node.handle_update_fail_htlc(&$intro_node.node.get_our_node_id(), &updates.update_fail_htlcs[0]);
+                       do_commitment_signed_dance(&nodes[0], &$intro_node, &updates.commitment_signed, false, false);
+
+                       let mut events = nodes[0].node.get_and_clear_pending_events();
+                       assert_eq!(events.len(), 2);
+                       match events[0] {
+                               Event::PaymentPathFailed { payment_hash: ev_payment_hash, payment_failed_permanently, ..  } => {
+                                       assert_eq!(payment_hash, ev_payment_hash);
+                                       assert_eq!(payment_failed_permanently, false);
+                               },
+                               _ => panic!("Unexpected event"),
+                       }
+                       match events[1] {
+                               Event::PendingHTLCsForwardable { .. } => {},
+                               _ => panic!("Unexpected event"),
+                       }
+                       nodes[0].node.process_pending_htlc_forwards();
+               }
+       }
+
+       fail_payment_back!(nodes[1]);
+
+       // Pass the retry along.
+       check_added_monitors!(nodes[0], 1);
+       let mut msg_events = nodes[0].node.get_and_clear_pending_msg_events();
+       assert_eq!(msg_events.len(), 1);
+       pass_along_path(&nodes[0], &[&nodes[2], &nodes[3]], amt_msat, payment_hash, Some(payment_secret), msg_events.pop().unwrap(), true, None);
+
+       fail_payment_back!(nodes[2]);
+       let evs = nodes[0].node.get_and_clear_pending_events();
+       assert_eq!(evs.len(), 1);
+       match evs[0] {
+               Event::PaymentFailed { payment_hash: ev_payment_hash, reason, .. } => {
+                       assert_eq!(ev_payment_hash, payment_hash);
+                       // We have 1 retry attempt remaining, but we're out of blinded paths to try.
+                       assert_eq!(reason, Some(PaymentFailureReason::RouteNotFound));
+               },
+               _ => panic!()
+       }
+}