Merge pull request #1203 from lightning-signer/2021-12-value-to-self
[rust-lightning] / lightning / src / ln / payment_tests.rs
index a364c7ccd562c88a572b70af5fbb23ccfd94e630..518ccd3b0efe5fd6fc75e4ba72eaadbec690205c 100644 (file)
 use chain::{ChannelMonitorUpdateErr, Confirm, Listen, Watch};
 use chain::channelmonitor::{ANTI_REORG_DELAY, ChannelMonitor, LATENCY_GRACE_PERIOD_BLOCKS};
 use chain::transaction::OutPoint;
-use ln::{PaymentPreimage, PaymentHash};
 use ln::channelmanager::{BREAKDOWN_TIMEOUT, ChannelManager, ChannelManagerReadArgs, PaymentId, PaymentSendFailure};
 use ln::features::InitFeatures;
 use ln::msgs;
-use ln::msgs::{ChannelMessageHandler, ErrorAction};
+use ln::msgs::ChannelMessageHandler;
 use util::events::{ClosureReason, Event, MessageSendEvent, MessageSendEventsProvider};
 use util::test_utils;
 use util::errors::APIError;
@@ -26,8 +25,6 @@ use util::enforcing_trait_impls::EnforcingSigner;
 use util::ser::{ReadableArgs, Writeable};
 use io;
 
-use bitcoin::hashes::sha256::Hash as Sha256;
-use bitcoin::hashes::Hash;
 use bitcoin::{Block, BlockHeader, BlockHash};
 
 use prelude::*;
@@ -296,7 +293,7 @@ fn do_retry_with_no_persist(confirm_before_reload: bool) {
        let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
 
        let (_, _, chan_id, funding_tx) = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
-       create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
+       let (_, _, chan_id_2, _) = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
 
        // Serialize the ChannelManager prior to sending payments
        let nodes_0_serialized = nodes[0].node.encode();
@@ -445,7 +442,13 @@ fn do_retry_with_no_persist(confirm_before_reload: bool) {
        // Finally, retry the payment (which was reloaded from the ChannelMonitor when nodes[0] was
        // reloaded) via a route over the new channel, which work without issue and eventually be
        // received and claimed at the recipient just like any other payment.
-       let (new_route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[2], 1_000_000);
+       let (mut new_route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[2], 1_000_000);
+
+       // Update the fee on the middle hop to ensure PaymentSent events have the correct (retried) fee
+       // and not the original fee. We also update node[1]'s relevant config as
+       // do_claim_payment_along_route expects us to never overpay.
+       nodes[1].node.channel_state.lock().unwrap().by_id.get_mut(&chan_id_2).unwrap().config.forwarding_fee_base_msat += 100_000;
+       new_route.paths[0][0].fee_msat += 100_000;
 
        assert!(nodes[0].node.retry_payment(&new_route, payment_id_1).is_err()); // Shouldn't be allowed to retry a fulfilled payment
        nodes[0].node.retry_payment(&new_route, payment_id).unwrap();
@@ -453,7 +456,8 @@ fn do_retry_with_no_persist(confirm_before_reload: bool) {
        let mut events = nodes[0].node.get_and_clear_pending_msg_events();
        assert_eq!(events.len(), 1);
        pass_along_path(&nodes[0], &[&nodes[1], &nodes[2]], 1_000_000, payment_hash, Some(payment_secret), events.pop().unwrap(), true, None);
-       claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], false, payment_preimage);
+       do_claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], false, payment_preimage);
+       expect_payment_sent!(nodes[0], payment_preimage, Some(new_route.paths[0][0].fee_msat));
 }
 
 #[test]
@@ -626,3 +630,79 @@ fn test_dup_htlc_onchain_fails_on_reload() {
        do_test_dup_htlc_onchain_fails_on_reload(false, true, false);
        do_test_dup_htlc_onchain_fails_on_reload(false, false, false);
 }
+
+#[test]
+fn test_fulfill_restart_failure() {
+       // When we receive an update_fulfill_htlc message, we immediately consider the HTLC fully
+       // fulfilled. At this point, the peer can reconnect and decide to either fulfill the HTLC
+       // again, or fail it, giving us free money.
+       //
+       // Of course probably they won't fail it and give us free money, but because we have code to
+       // handle it, we should test the logic for it anyway. We do that here.
+       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 persister: test_utils::TestPersister;
+       let new_chain_monitor: test_utils::TestChainMonitor;
+       let nodes_1_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
+       let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
+
+       let chan_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
+       let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 100_000);
+
+       // The simplest way to get a failure after a fulfill is to reload nodes[1] from a state
+       // pre-fulfill, which we do by serializing it here.
+       let mut chan_manager_serialized = test_utils::TestVecWriter(Vec::new());
+       nodes[1].node.write(&mut chan_manager_serialized).unwrap();
+       let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
+       get_monitor!(nodes[1], chan_id).write(&mut chan_0_monitor_serialized).unwrap();
+
+       nodes[1].node.claim_funds(payment_preimage);
+       check_added_monitors!(nodes[1], 1);
+       let htlc_fulfill_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(), &htlc_fulfill_updates.update_fulfill_htlcs[0]);
+       expect_payment_sent_without_paths!(nodes[0], payment_preimage);
+
+       // Now reload nodes[1]...
+       persister = test_utils::TestPersister::new();
+       let keys_manager = &chanmon_cfgs[1].keys_manager;
+       new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[1].chain_source), nodes[1].tx_broadcaster.clone(), nodes[1].logger, node_cfgs[1].fee_estimator, &persister, keys_manager);
+       nodes[1].chain_monitor = &new_chain_monitor;
+       let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
+       let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
+               &mut chan_0_monitor_read, keys_manager).unwrap();
+       assert!(chan_0_monitor_read.is_empty());
+
+       let (_, nodes_1_deserialized_tmp) = {
+               let mut channel_monitors = HashMap::new();
+               channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
+               <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>
+                       ::read(&mut io::Cursor::new(&chan_manager_serialized.0[..]), ChannelManagerReadArgs {
+                               default_config: Default::default(),
+                               keys_manager,
+                               fee_estimator: node_cfgs[1].fee_estimator,
+                               chain_monitor: nodes[1].chain_monitor,
+                               tx_broadcaster: nodes[1].tx_broadcaster.clone(),
+                               logger: nodes[1].logger,
+                               channel_monitors,
+                       }).unwrap()
+       };
+       nodes_1_deserialized = nodes_1_deserialized_tmp;
+
+       assert!(nodes[1].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
+       check_added_monitors!(nodes[1], 1);
+       nodes[1].node = &nodes_1_deserialized;
+
+       nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
+       reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
+
+       nodes[1].node.fail_htlc_backwards(&payment_hash);
+       expect_pending_htlcs_forwardable!(nodes[1]);
+       check_added_monitors!(nodes[1], 1);
+       let htlc_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
+       nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_fail_updates.update_fail_htlcs[0]);
+       commitment_signed_dance!(nodes[0], nodes[1], htlc_fail_updates.commitment_signed, false);
+       // nodes[0] shouldn't generate any events here, while it just got a payment failure completion
+       // it had already considered the payment fulfilled, and now they just got free money.
+       assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
+}