Adopting new bitcoin hash types and crate version
[rust-lightning] / lightning / src / ln / functional_tests.rs
index f37c55887fd635887a53ae0e50bf9894d0bd3780..3a440fb323c82e0ba55c1b09b2745ab1d9480a0d 100644 (file)
@@ -25,7 +25,8 @@ use util::config::UserConfig;
 use util::logger::Logger;
 
 use bitcoin::util::hash::BitcoinHash;
-use bitcoin_hashes::sha256d::Hash as Sha256dHash;
+use bitcoin::hashes::sha256d::Hash as Sha256dHash;
+use bitcoin::hash_types::{Txid, BlockHash};
 use bitcoin::util::bip143;
 use bitcoin::util::address::Address;
 use bitcoin::util::bip32::{ChildNumber, ExtendedPubKey, ExtendedPrivKey};
@@ -36,11 +37,11 @@ use bitcoin::blockdata::opcodes;
 use bitcoin::blockdata::constants::genesis_block;
 use bitcoin::network::constants::Network;
 
-use bitcoin_hashes::sha256::Hash as Sha256;
-use bitcoin_hashes::Hash;
+use bitcoin::hashes::sha256::Hash as Sha256;
+use bitcoin::hashes::Hash;
 
-use secp256k1::{Secp256k1, Message};
-use secp256k1::key::{PublicKey,SecretKey};
+use bitcoin::secp256k1::{Secp256k1, Message};
+use bitcoin::secp256k1::key::{PublicKey,SecretKey};
 
 use std::collections::{BTreeSet, HashMap, HashSet};
 use std::default::Default;
@@ -3078,7 +3079,7 @@ fn test_force_close_fail_back() {
        // Now check that if we add the preimage to ChannelMonitor it broadcasts our HTLC-Success..
        {
                let mut monitors = nodes[2].chan_monitor.simple_monitor.monitors.lock().unwrap();
-               monitors.get_mut(&OutPoint::new(Sha256dHash::from_slice(&payment_event.commitment_msg.channel_id[..]).unwrap(), 0)).unwrap()
+               monitors.get_mut(&OutPoint::new(Txid::from_slice(&payment_event.commitment_msg.channel_id[..]).unwrap(), 0)).unwrap()
                        .provide_payment_preimage(&our_payment_hash, &our_payment_preimage);
        }
        nodes[2].block_notifier.block_connected_checked(&header, 1, &[&tx], &[1]);
@@ -3678,6 +3679,83 @@ fn test_htlc_timeout() {
        do_test_htlc_timeout(false);
 }
 
+fn do_test_holding_cell_htlc_add_timeouts(forwarded_htlc: bool) {
+       // Tests that HTLCs in the holding cell are timed out after the requisite number of blocks.
+       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 mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
+       create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
+       create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::supported(), InitFeatures::supported());
+
+       // Route a first payment to get the 1 -> 2 channel in awaiting_raa...
+       let route = nodes[1].router.get_route(&nodes[2].node.get_our_node_id(), None, &Vec::new(), 100000, TEST_FINAL_CLTV).unwrap();
+       let (_, first_payment_hash) = get_payment_preimage_hash!(nodes[0]);
+       nodes[1].node.send_payment(&route, first_payment_hash, &None).unwrap();
+       assert_eq!(nodes[1].node.get_and_clear_pending_msg_events().len(), 1);
+       check_added_monitors!(nodes[1], 1);
+
+       // Now attempt to route a second payment, which should be placed in the holding cell
+       let (_, second_payment_hash) = get_payment_preimage_hash!(nodes[0]);
+       if forwarded_htlc {
+               let route = nodes[0].router.get_route(&nodes[2].node.get_our_node_id(), None, &Vec::new(), 100000, TEST_FINAL_CLTV).unwrap();
+               nodes[0].node.send_payment(&route, second_payment_hash, &None).unwrap();
+               check_added_monitors!(nodes[0], 1);
+               let payment_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
+               nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
+               commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
+               expect_pending_htlcs_forwardable!(nodes[1]);
+               check_added_monitors!(nodes[1], 0);
+       } else {
+               nodes[1].node.send_payment(&route, second_payment_hash, &None).unwrap();
+               check_added_monitors!(nodes[1], 0);
+       }
+
+       let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
+       nodes[1].block_notifier.block_connected_checked(&header, 101, &[], &[]);
+       for i in 102..TEST_FINAL_CLTV + 100 - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS {
+               header.prev_blockhash = header.bitcoin_hash();
+               nodes[1].block_notifier.block_connected_checked(&header, i, &[], &[]);
+       }
+
+       assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
+       assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
+
+       header.prev_blockhash = header.bitcoin_hash();
+       nodes[1].block_notifier.block_connected_checked(&header, TEST_FINAL_CLTV + 100 - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS, &[], &[]);
+
+       if forwarded_htlc {
+               expect_pending_htlcs_forwardable!(nodes[1]);
+               check_added_monitors!(nodes[1], 1);
+               let fail_commit = nodes[1].node.get_and_clear_pending_msg_events();
+               assert_eq!(fail_commit.len(), 1);
+               match fail_commit[0] {
+                       MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, ref commitment_signed, .. }, .. } => {
+                               nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
+                               commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, true, true);
+                       },
+                       _ => unreachable!(),
+               }
+               expect_payment_failed!(nodes[0], second_payment_hash, false);
+               if let &MessageSendEvent::PaymentFailureNetworkUpdate { ref update } = &nodes[0].node.get_and_clear_pending_msg_events()[0] {
+                       match update {
+                               &HTLCFailChannelUpdate::ChannelUpdateMessage { .. } => {},
+                               _ => panic!("Unexpected event"),
+                       }
+               } else {
+                       panic!("Unexpected event");
+               }
+       } else {
+               expect_payment_failed!(nodes[1], second_payment_hash, true);
+       }
+}
+
+#[test]
+fn test_holding_cell_htlc_add_timeouts() {
+       do_test_holding_cell_htlc_add_timeouts(false);
+       do_test_holding_cell_htlc_add_timeouts(true);
+}
+
 #[test]
 fn test_invalid_channel_announcement() {
        //Test BOLT 7 channel_announcement msg requirement for final node, gather data to build customed channel_announcement msgs
@@ -3750,7 +3828,7 @@ fn test_invalid_channel_announcement() {
        assert!(nodes[0].router.handle_channel_announcement(&chan_announcement).is_err());
 
        let mut unsigned_msg = dummy_unsigned_msg!();
-       unsigned_msg.chain_hash = Sha256dHash::hash(&[1,2,3,4,5,6,7,8,9]);
+       unsigned_msg.chain_hash = BlockHash::hash(&[1,2,3,4,5,6,7,8,9]);
        sign_msg!(unsigned_msg);
        assert!(nodes[0].router.handle_channel_announcement(&chan_announcement).is_err());
 }
@@ -3778,7 +3856,7 @@ fn test_no_txn_manager_serialize_deserialize() {
        new_chan_monitor = test_utils::TestChannelMonitor::new(nodes[0].chain_monitor.clone(), nodes[0].tx_broadcaster.clone(), Arc::new(test_utils::TestLogger::new()), &fee_estimator);
        nodes[0].chan_monitor = &new_chan_monitor;
        let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
-       let (_, mut chan_0_monitor) = <(Sha256dHash, ChannelMonitor<EnforcingChannelKeys>)>::read(&mut chan_0_monitor_read, Arc::new(test_utils::TestLogger::new())).unwrap();
+       let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingChannelKeys>)>::read(&mut chan_0_monitor_read, Arc::new(test_utils::TestLogger::new())).unwrap();
        assert!(chan_0_monitor_read.is_empty());
 
        let mut nodes_0_read = &nodes_0_serialized[..];
@@ -3787,7 +3865,7 @@ fn test_no_txn_manager_serialize_deserialize() {
        let (_, nodes_0_deserialized_tmp) = {
                let mut channel_monitors = HashMap::new();
                channel_monitors.insert(chan_0_monitor.get_funding_txo(), &mut chan_0_monitor);
-               <(Sha256dHash, ChannelManager<EnforcingChannelKeys, &test_utils::TestChannelMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
+               <(BlockHash, ChannelManager<EnforcingChannelKeys, &test_utils::TestChannelMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
                        default_config: config,
                        keys_manager: &keys_manager,
                        fee_estimator: &fee_estimator,
@@ -3852,7 +3930,7 @@ fn test_simple_manager_serialize_deserialize() {
        new_chan_monitor = test_utils::TestChannelMonitor::new(nodes[0].chain_monitor.clone(), nodes[0].tx_broadcaster.clone(), Arc::new(test_utils::TestLogger::new()), &fee_estimator);
        nodes[0].chan_monitor = &new_chan_monitor;
        let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
-       let (_, mut chan_0_monitor) = <(Sha256dHash, ChannelMonitor<EnforcingChannelKeys>)>::read(&mut chan_0_monitor_read, Arc::new(test_utils::TestLogger::new())).unwrap();
+       let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingChannelKeys>)>::read(&mut chan_0_monitor_read, Arc::new(test_utils::TestLogger::new())).unwrap();
        assert!(chan_0_monitor_read.is_empty());
 
        let mut nodes_0_read = &nodes_0_serialized[..];
@@ -3860,7 +3938,7 @@ fn test_simple_manager_serialize_deserialize() {
        let (_, nodes_0_deserialized_tmp) = {
                let mut channel_monitors = HashMap::new();
                channel_monitors.insert(chan_0_monitor.get_funding_txo(), &mut chan_0_monitor);
-               <(Sha256dHash, ChannelManager<EnforcingChannelKeys, &test_utils::TestChannelMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
+               <(BlockHash, ChannelManager<EnforcingChannelKeys, &test_utils::TestChannelMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
                        default_config: UserConfig::default(),
                        keys_manager: &keys_manager,
                        fee_estimator: &fee_estimator,
@@ -3931,7 +4009,7 @@ fn test_manager_serialize_deserialize_inconsistent_monitor() {
        let mut node_0_stale_monitors = Vec::new();
        for serialized in node_0_stale_monitors_serialized.iter() {
                let mut read = &serialized[..];
-               let (_, monitor) = <(Sha256dHash, ChannelMonitor<EnforcingChannelKeys>)>::read(&mut read, Arc::new(test_utils::TestLogger::new())).unwrap();
+               let (_, monitor) = <(BlockHash, ChannelMonitor<EnforcingChannelKeys>)>::read(&mut read, Arc::new(test_utils::TestLogger::new())).unwrap();
                assert!(read.is_empty());
                node_0_stale_monitors.push(monitor);
        }
@@ -3939,7 +4017,7 @@ fn test_manager_serialize_deserialize_inconsistent_monitor() {
        let mut node_0_monitors = Vec::new();
        for serialized in node_0_monitors_serialized.iter() {
                let mut read = &serialized[..];
-               let (_, monitor) = <(Sha256dHash, ChannelMonitor<EnforcingChannelKeys>)>::read(&mut read, Arc::new(test_utils::TestLogger::new())).unwrap();
+               let (_, monitor) = <(BlockHash, ChannelMonitor<EnforcingChannelKeys>)>::read(&mut read, Arc::new(test_utils::TestLogger::new())).unwrap();
                assert!(read.is_empty());
                node_0_monitors.push(monitor);
        }
@@ -3948,7 +4026,7 @@ fn test_manager_serialize_deserialize_inconsistent_monitor() {
 
        let mut nodes_0_read = &nodes_0_serialized[..];
        if let Err(msgs::DecodeError::InvalidValue) =
-               <(Sha256dHash, ChannelManager<EnforcingChannelKeys, &test_utils::TestChannelMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
+               <(BlockHash, ChannelManager<EnforcingChannelKeys, &test_utils::TestChannelMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
                default_config: UserConfig::default(),
                keys_manager: &keys_manager,
                fee_estimator: &fee_estimator,
@@ -3962,7 +4040,7 @@ fn test_manager_serialize_deserialize_inconsistent_monitor() {
 
        let mut nodes_0_read = &nodes_0_serialized[..];
        let (_, nodes_0_deserialized_tmp) =
-               <(Sha256dHash, ChannelManager<EnforcingChannelKeys, &test_utils::TestChannelMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
+               <(BlockHash, ChannelManager<EnforcingChannelKeys, &test_utils::TestChannelMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
                default_config: UserConfig::default(),
                keys_manager: &keys_manager,
                fee_estimator: &fee_estimator,
@@ -5363,12 +5441,12 @@ fn run_onion_failure_test_with_fail_intercept<F1,F2,F3>(_name: &str, test_case:
 
 impl msgs::ChannelUpdate {
        fn dummy() -> msgs::ChannelUpdate {
-               use secp256k1::ffi::Signature as FFISignature;
-               use secp256k1::Signature;
+               use bitcoin::secp256k1::ffi::Signature as FFISignature;
+               use bitcoin::secp256k1::Signature;
                msgs::ChannelUpdate {
                        signature: Signature::from(FFISignature::new()),
                        contents: msgs::UnsignedChannelUpdate {
-                               chain_hash: Sha256dHash::hash(&vec![0u8][..]),
+                               chain_hash: BlockHash::hash(&vec![0u8][..]),
                                short_channel_id: 0,
                                timestamp: 0,
                                flags: 0,
@@ -5400,7 +5478,7 @@ impl Writeable for BogusOnionHopData {
 fn test_onion_failure() {
        use ln::msgs::ChannelUpdate;
        use ln::channelmanager::CLTV_FAR_FAR_AWAY;
-       use secp256k1;
+       use bitcoin::secp256k1;
 
        const BADONION: u16 = 0x8000;
        const PERM: u16 = 0x4000;
@@ -6756,7 +6834,7 @@ fn test_data_loss_protect() {
 
        // Restore node A from previous state
        let logger: Arc<Logger> = Arc::new(test_utils::TestLogger::with_id(format!("node {}", 0)));
-       let mut chan_monitor = <(Sha256dHash, ChannelMonitor<EnforcingChannelKeys>)>::read(&mut ::std::io::Cursor::new(previous_chan_monitor_state.0), Arc::clone(&logger)).unwrap().1;
+       let mut chan_monitor = <(BlockHash, ChannelMonitor<EnforcingChannelKeys>)>::read(&mut ::std::io::Cursor::new(previous_chan_monitor_state.0), Arc::clone(&logger)).unwrap().1;
        let chain_monitor = Arc::new(ChainWatchInterfaceUtil::new(Network::Testnet, Arc::clone(&logger)));
        tx_broadcaster = test_utils::TestBroadcaster{txn_broadcasted: Mutex::new(Vec::new())};
        fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
@@ -6765,7 +6843,7 @@ fn test_data_loss_protect() {
        node_state_0 = {
                let mut channel_monitors = HashMap::new();
                channel_monitors.insert(OutPoint { txid: chan.3.txid(), index: 0 }, &mut chan_monitor);
-               <(Sha256dHash, ChannelManager<EnforcingChannelKeys, &test_utils::TestChannelMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator>)>::read(&mut ::std::io::Cursor::new(previous_node_state), ChannelManagerReadArgs {
+               <(BlockHash, ChannelManager<EnforcingChannelKeys, &test_utils::TestChannelMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator>)>::read(&mut ::std::io::Cursor::new(previous_node_state), ChannelManagerReadArgs {
                        keys_manager: &keys_manager,
                        fee_estimator: &fee_estimator,
                        monitor: &monitor,
@@ -7580,7 +7658,7 @@ fn test_update_err_monitor_lockdown() {
                let monitor = monitors.get(&outpoint).unwrap();
                let mut w = test_utils::TestVecWriter(Vec::new());
                monitor.write_for_disk(&mut w).unwrap();
-               let new_monitor = <(Sha256dHash, channelmonitor::ChannelMonitor<EnforcingChannelKeys>)>::read(
+               let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingChannelKeys>)>::read(
                                &mut ::std::io::Cursor::new(&w.0), Arc::new(test_utils::TestLogger::new())).unwrap().1;
                assert!(new_monitor == *monitor);
                let chain_monitor = Arc::new(chaininterface::ChainWatchInterfaceUtil::new(Network::Testnet, logger.clone() as Arc<Logger>));