Add a `PaymentClaimed` event to indicate a payment was claimed
[rust-lightning] / lightning / src / ln / functional_test_utils.rs
index dbeb9cc44a33f1840593f77cc59844fe1d153b3d..458601542ca149bb2944ddf888eb7d3e0f5f1172 100644 (file)
@@ -34,8 +34,10 @@ use bitcoin::blockdata::transaction::{Transaction, TxOut};
 use bitcoin::network::constants::Network;
 
 use bitcoin::hash_types::BlockHash;
+use bitcoin::hashes::sha256::Hash as Sha256;
+use bitcoin::hashes::Hash as _;
 
-use bitcoin::secp256k1::key::PublicKey;
+use bitcoin::secp256k1::PublicKey;
 
 use io;
 use prelude::*;
@@ -553,13 +555,14 @@ macro_rules! check_added_monitors {
        }
 }
 
-pub fn create_funding_transaction<'a, 'b, 'c>(node: &Node<'a, 'b, 'c>, expected_chan_value: u64, expected_user_chan_id: u64) -> ([u8; 32], Transaction, OutPoint) {
+pub fn create_funding_transaction<'a, 'b, 'c>(node: &Node<'a, 'b, 'c>, expected_counterparty_node_id: &PublicKey, expected_chan_value: u64, expected_user_chan_id: u64) -> ([u8; 32], Transaction, OutPoint) {
        let chan_id = *node.network_chan_count.borrow();
 
        let events = node.node.get_and_clear_pending_events();
        assert_eq!(events.len(), 1);
        match events[0] {
-               Event::FundingGenerationReady { ref temporary_channel_id, ref channel_value_satoshis, ref output_script, user_channel_id } => {
+               Event::FundingGenerationReady { ref temporary_channel_id, ref counterparty_node_id, ref channel_value_satoshis, ref output_script, user_channel_id } => {
+                       assert_eq!(counterparty_node_id, expected_counterparty_node_id);
                        assert_eq!(*channel_value_satoshis, expected_chan_value);
                        assert_eq!(user_channel_id, expected_user_chan_id);
 
@@ -573,10 +576,10 @@ pub fn create_funding_transaction<'a, 'b, 'c>(node: &Node<'a, 'b, 'c>, expected_
        }
 }
 pub fn sign_funding_transaction<'a, 'b, 'c>(node_a: &Node<'a, 'b, 'c>, node_b: &Node<'a, 'b, 'c>, channel_value: u64, expected_temporary_channel_id: [u8; 32]) -> Transaction {
-       let (temporary_channel_id, tx, funding_output) = create_funding_transaction(node_a, channel_value, 42);
+       let (temporary_channel_id, tx, funding_output) = create_funding_transaction(node_a, &node_b.node.get_our_node_id(), channel_value, 42);
        assert_eq!(temporary_channel_id, expected_temporary_channel_id);
 
-       assert!(node_a.node.funding_transaction_generated(&temporary_channel_id, tx.clone()).is_ok());
+       assert!(node_a.node.funding_transaction_generated(&temporary_channel_id, &node_b.node.get_our_node_id(), tx.clone()).is_ok());
        check_added_monitors!(node_a, 0);
 
        let funding_created_msg = get_event_msg!(node_a, MessageSendEvent::SendFundingCreated, node_b.node.get_our_node_id());
@@ -605,7 +608,7 @@ pub fn sign_funding_transaction<'a, 'b, 'c>(node_a: &Node<'a, 'b, 'c>, node_b: &
        node_a.tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
 
        // Ensure that funding_transaction_generated is idempotent.
-       assert!(node_a.node.funding_transaction_generated(&temporary_channel_id, tx.clone()).is_err());
+       assert!(node_a.node.funding_transaction_generated(&temporary_channel_id, &node_b.node.get_our_node_id(), tx.clone()).is_err());
        assert!(node_a.node.get_and_clear_pending_msg_events().is_empty());
        check_added_monitors!(node_a, 0);
 
@@ -722,8 +725,8 @@ pub fn create_unannounced_chan_between_nodes_with_value<'a, 'b, 'c, 'd>(nodes: &
        let accept_channel = get_event_msg!(nodes[b], MessageSendEvent::SendAcceptChannel, nodes[a].node.get_our_node_id());
        nodes[a].node.handle_accept_channel(&nodes[b].node.get_our_node_id(), b_flags, &accept_channel);
 
-       let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[a], channel_value, 42);
-       nodes[a].node.funding_transaction_generated(&temporary_channel_id, tx.clone()).unwrap();
+       let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[a], &nodes[b].node.get_our_node_id(), channel_value, 42);
+       nodes[a].node.funding_transaction_generated(&temporary_channel_id, &nodes[b].node.get_our_node_id(), tx.clone()).unwrap();
        nodes[b].node.handle_funding_created(&nodes[a].node.get_our_node_id(), &get_event_msg!(nodes[a], MessageSendEvent::SendFundingCreated, nodes[b].node.get_our_node_id()));
        check_added_monitors!(nodes[b], 1);
 
@@ -859,7 +862,7 @@ macro_rules! check_spends {
                        for output in $tx.output.iter() {
                                total_value_out += output.value;
                        }
-                       let min_fee = ($tx.get_weight() as u64 + 3) / 4; // One sat per vbyte (ie per weight/4, rounded up)
+                       let min_fee = ($tx.weight() as u64 + 3) / 4; // One sat per vbyte (ie per weight/4, rounded up)
                        // Input amount - output amount = fee, so check that out + min_fee is smaller than input
                        assert!(total_value_out + min_fee <= total_value_in);
                        $tx.verify(get_output).unwrap();
@@ -968,7 +971,7 @@ pub fn close_channel<'a, 'b, 'c>(outbound_node: &Node<'a, 'b, 'c>, inbound_node:
        let (node_b, broadcaster_b, struct_b) = if close_inbound_first { (&outbound_node.node, &outbound_node.tx_broadcaster, outbound_node) } else { (&inbound_node.node, &inbound_node.tx_broadcaster, inbound_node) };
        let (tx_a, tx_b);
 
-       node_a.close_channel(channel_id).unwrap();
+       node_a.close_channel(channel_id, &node_b.get_our_node_id()).unwrap();
        node_b.handle_shutdown(&node_a.get_our_node_id(), &InitFeatures::known(), &get_event_msg!(struct_a, MessageSendEvent::SendShutdown, node_b.get_our_node_id()));
 
        let events_1 = node_b.get_and_clear_pending_msg_events();
@@ -1167,6 +1170,21 @@ macro_rules! get_payment_preimage_hash {
        }
 }
 
+#[macro_export]
+macro_rules! get_route {
+       ($send_node: expr, $payment_params: expr, $recv_value: expr, $cltv: expr) => {{
+               use $crate::chain::keysinterface::KeysInterface;
+               let scorer = $crate::util::test_utils::TestScorer::with_penalty(0);
+               let keys_manager = $crate::util::test_utils::TestKeysInterface::new(&[0u8; 32], bitcoin::network::constants::Network::Testnet);
+               let random_seed_bytes = keys_manager.get_secure_random_bytes();
+               $crate::routing::router::get_route(
+                       &$send_node.node.get_our_node_id(), &$payment_params, &$send_node.network_graph.read_only(),
+                       Some(&$send_node.node.list_usable_channels().iter().collect::<Vec<_>>()),
+                       $recv_value, $cltv, $send_node.logger, &scorer, &random_seed_bytes
+               )
+       }}
+}
+
 #[cfg(test)]
 #[macro_export]
 macro_rules! get_route_and_payment_hash {
@@ -1176,17 +1194,9 @@ macro_rules! get_route_and_payment_hash {
                $crate::get_route_and_payment_hash!($send_node, $recv_node, payment_params, $recv_value, TEST_FINAL_CLTV)
        }};
        ($send_node: expr, $recv_node: expr, $payment_params: expr, $recv_value: expr, $cltv: expr) => {{
-               use $crate::chain::keysinterface::KeysInterface;
                let (payment_preimage, payment_hash, payment_secret) = $crate::get_payment_preimage_hash!($recv_node, Some($recv_value));
-               let scorer = $crate::util::test_utils::TestScorer::with_penalty(0);
-               let keys_manager = $crate::util::test_utils::TestKeysInterface::new(&[0u8; 32], bitcoin::network::constants::Network::Testnet);
-               let random_seed_bytes = keys_manager.get_secure_random_bytes();
-               let route = $crate::routing::router::get_route(
-                       &$send_node.node.get_our_node_id(), &$payment_params, &$send_node.network_graph.read_only(),
-                       Some(&$send_node.node.list_usable_channels().iter().collect::<Vec<_>>()),
-                       $recv_value, $cltv, $send_node.logger, &scorer, &random_seed_bytes
-               ).unwrap();
-               (route, payment_hash, payment_preimage, payment_secret)
+               let route = $crate::get_route!($send_node, $payment_params, $recv_value, $cltv);
+               (route.unwrap(), payment_hash, payment_preimage, payment_secret)
        }}
 }
 
@@ -1258,6 +1268,22 @@ macro_rules! expect_payment_received {
        }
 }
 
+#[macro_export]
+#[cfg(any(test, feature = "_bench_unstable", feature = "_test_utils"))]
+macro_rules! expect_payment_claimed {
+       ($node: expr, $expected_payment_hash: expr, $expected_recv_value: expr) => {
+               let events = $node.node.get_and_clear_pending_events();
+               assert_eq!(events.len(), 1);
+               match events[0] {
+                       $crate::util::events::Event::PaymentClaimed { ref payment_hash, amt, .. } => {
+                               assert_eq!($expected_payment_hash, *payment_hash);
+                               assert_eq!($expected_recv_value, amt);
+                       },
+                       _ => panic!("Unexpected event"),
+               }
+       }
+}
+
 #[cfg(test)]
 #[macro_export]
 macro_rules! expect_payment_sent_without_paths {
@@ -1468,7 +1494,7 @@ pub fn send_along_route_with_secret<'a, 'b, 'c>(origin_node: &Node<'a, 'b, 'c>,
        payment_id
 }
 
-pub fn pass_along_path<'a, 'b, 'c>(origin_node: &Node<'a, 'b, 'c>, expected_path: &[&Node<'a, 'b, 'c>], recv_value: u64, our_payment_hash: PaymentHash, our_payment_secret: Option<PaymentSecret>, ev: MessageSendEvent, payment_received_expected: bool, expected_preimage: Option<PaymentPreimage>) {
+pub fn do_pass_along_path<'a, 'b, 'c>(origin_node: &Node<'a, 'b, 'c>, expected_path: &[&Node<'a, 'b, 'c>], recv_value: u64, our_payment_hash: PaymentHash, our_payment_secret: Option<PaymentSecret>, ev: MessageSendEvent, payment_received_expected: bool, clear_recipient_events: bool, expected_preimage: Option<PaymentPreimage>) {
        let mut payment_event = SendEvent::from_event(ev);
        let mut prev_node = origin_node;
 
@@ -1481,7 +1507,7 @@ pub fn pass_along_path<'a, 'b, 'c>(origin_node: &Node<'a, 'b, 'c>, expected_path
 
                expect_pending_htlcs_forwardable!(node);
 
-               if idx == expected_path.len() - 1 {
+               if idx == expected_path.len() - 1 && clear_recipient_events {
                        let events_2 = node.node.get_and_clear_pending_events();
                        if payment_received_expected {
                                assert_eq!(events_2.len(), 1);
@@ -1505,7 +1531,7 @@ pub fn pass_along_path<'a, 'b, 'c>(origin_node: &Node<'a, 'b, 'c>, expected_path
                        } else {
                                assert!(events_2.is_empty());
                        }
-               } else {
+               } else if idx != expected_path.len() - 1 {
                        let mut events_2 = node.node.get_and_clear_pending_msg_events();
                        assert_eq!(events_2.len(), 1);
                        check_added_monitors!(node, 1);
@@ -1517,6 +1543,10 @@ pub fn pass_along_path<'a, 'b, 'c>(origin_node: &Node<'a, 'b, 'c>, expected_path
        }
 }
 
+pub fn pass_along_path<'a, 'b, 'c>(origin_node: &Node<'a, 'b, 'c>, expected_path: &[&Node<'a, 'b, 'c>], recv_value: u64, our_payment_hash: PaymentHash, our_payment_secret: Option<PaymentSecret>, ev: MessageSendEvent, payment_received_expected: bool, expected_preimage: Option<PaymentPreimage>) {
+       do_pass_along_path(origin_node, expected_path, recv_value, our_payment_hash, our_payment_secret, ev, payment_received_expected, true, expected_preimage);
+}
+
 pub fn pass_along_route<'a, 'b, 'c>(origin_node: &Node<'a, 'b, 'c>, expected_route: &[&[&Node<'a, 'b, 'c>]], recv_value: u64, our_payment_hash: PaymentHash, our_payment_secret: PaymentSecret) {
        let mut events = origin_node.node.get_and_clear_pending_msg_events();
        assert_eq!(events.len(), expected_route.len());
@@ -1538,7 +1568,19 @@ pub fn do_claim_payment_along_route<'a, 'b, 'c>(origin_node: &Node<'a, 'b, 'c>,
        for path in expected_paths.iter() {
                assert_eq!(path.last().unwrap().node.get_our_node_id(), expected_paths[0].last().unwrap().node.get_our_node_id());
        }
-       assert!(expected_paths[0].last().unwrap().node.claim_funds(our_payment_preimage));
+       expected_paths[0].last().unwrap().node.claim_funds(our_payment_preimage);
+
+       let claim_event = expected_paths[0].last().unwrap().node.get_and_clear_pending_events();
+       assert_eq!(claim_event.len(), 1);
+       match claim_event[0] {
+               Event::PaymentClaimed { purpose: PaymentPurpose::SpontaneousPayment(preimage), .. }|
+               Event::PaymentClaimed { purpose: PaymentPurpose::InvoicePayment { payment_preimage: Some(preimage), ..}, .. } =>
+                       assert_eq!(preimage, our_payment_preimage),
+               Event::PaymentClaimed { purpose: PaymentPurpose::InvoicePayment { .. }, payment_hash, .. } =>
+                       assert_eq!(&payment_hash.0, &Sha256::hash(&our_payment_preimage.0)[..]),
+               _ => panic!(),
+       }
+
        check_added_monitors!(expected_paths[0].last().unwrap(), expected_paths.len());
 
        let mut expected_total_fee_msat = 0;
@@ -1633,7 +1675,7 @@ pub fn do_claim_payment_along_route<'a, 'b, 'c>(origin_node: &Node<'a, 'b, 'c>,
        }
 
        // Ensure that claim_funds is idempotent.
-       assert!(!expected_paths[0].last().unwrap().node.claim_funds(our_payment_preimage));
+       expected_paths[0].last().unwrap().node.claim_funds(our_payment_preimage);
        assert!(expected_paths[0].last().unwrap().node.get_and_clear_pending_msg_events().is_empty());
        check_added_monitors!(expected_paths[0].last().unwrap(), 0);
 
@@ -1655,15 +1697,7 @@ pub const TEST_FINAL_CLTV: u32 = 70;
 pub fn route_payment<'a, 'b, 'c>(origin_node: &Node<'a, 'b, 'c>, expected_route: &[&Node<'a, 'b, 'c>], recv_value: u64) -> (PaymentPreimage, PaymentHash, PaymentSecret) {
        let payment_params = PaymentParameters::from_node_id(expected_route.last().unwrap().node.get_our_node_id())
                .with_features(InvoiceFeatures::known());
-       let network_graph = origin_node.network_graph.read_only();
-       let scorer = test_utils::TestScorer::with_penalty(0);
-       let seed = [0u8; 32];
-       let keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
-       let random_seed_bytes = keys_manager.get_secure_random_bytes();
-       let route = get_route(
-               &origin_node.node.get_our_node_id(), &payment_params, &network_graph,
-               Some(&origin_node.node.list_usable_channels().iter().collect::<Vec<_>>()),
-               recv_value, TEST_FINAL_CLTV, origin_node.logger, &scorer, &random_seed_bytes).unwrap();
+       let route = get_route!(origin_node, payment_params, recv_value, TEST_FINAL_CLTV).unwrap();
        assert_eq!(route.paths.len(), 1);
        assert_eq!(route.paths[0].len(), expected_route.len());
        for (node, hop) in expected_route.iter().zip(route.paths[0].iter()) {
@@ -2010,7 +2044,10 @@ pub fn check_preimage_claim<'a, 'b, 'c>(node: &Node<'a, 'b, 'c>, prev_txn: &Vec<
        for tx in prev_txn {
                if node_txn[0].input[0].previous_output.txid == tx.txid() {
                        check_spends!(node_txn[0], tx);
-                       assert!(node_txn[0].input[0].witness[2].len() > 106); // must spend an htlc output
+                       let mut iter = node_txn[0].input[0].witness.iter();
+                       iter.next().expect("expected 3 witness items");
+                       iter.next().expect("expected 3 witness items");
+                       assert!(iter.next().expect("expected 3 witness items").len() > 106); // must spend an htlc output
                        assert_eq!(tx.input.len(), 1); // must spend a commitment tx
 
                        found_prev = true;