Add assert_log method to TestLogger to harden test
[rust-lightning] / lightning / src / ln / functional_test_utils.rs
index ba30330719e1fd0bd7a2ad66f943b7b7d44f3b00..e99e96097aade150ee0ffed542ef7ce5ec72098b 100644 (file)
@@ -8,6 +8,7 @@ use ln::channelmanager::{ChannelManager,RAACommitmentOrder, PaymentPreimage, Pay
 use ln::router::{Route, Router};
 use ln::msgs;
 use ln::msgs::{ChannelMessageHandler,RoutingMessageHandler, LocalFeatures};
+use util::enforcing_trait_impls::EnforcingChannelKeys;
 use util::test_utils;
 use util::events::{Event, EventsProvider, MessageSendEvent, MessageSendEventsProvider};
 use util::errors::APIError;
@@ -34,36 +35,38 @@ use std::sync::{Arc, Mutex};
 use std::mem;
 
 pub const CHAN_CONFIRM_DEPTH: u32 = 100;
-pub fn confirm_transaction(chain: &chaininterface::ChainWatchInterfaceUtil, tx: &Transaction, chan_id: u32) {
+pub fn confirm_transaction(notifier: &chaininterface::BlockNotifier, chain: &chaininterface::ChainWatchInterfaceUtil, tx: &Transaction, chan_id: u32) {
        assert!(chain.does_match_tx(tx));
        let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
-       chain.block_connected_checked(&header, 1, &[tx; 1], &[chan_id; 1]);
+       notifier.block_connected_checked(&header, 1, &[tx; 1], &[chan_id; 1]);
        for i in 2..CHAN_CONFIRM_DEPTH {
                header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
-               chain.block_connected_checked(&header, i, &[tx; 0], &[0; 0]);
+               notifier.block_connected_checked(&header, i, &vec![], &[0; 0]);
        }
 }
 
-pub fn connect_blocks(chain: &chaininterface::ChainWatchInterfaceUtil, depth: u32, height: u32, parent: bool, prev_blockhash: Sha256d) -> Sha256d {
+pub fn connect_blocks(notifier: &chaininterface::BlockNotifier, depth: u32, height: u32, parent: bool, prev_blockhash: Sha256d) -> Sha256d {
        let mut header = BlockHeader { version: 0x2000000, prev_blockhash: if parent { prev_blockhash } else { Default::default() }, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
-       chain.block_connected_checked(&header, height + 1, &Vec::new(), &Vec::new());
+       notifier.block_connected_checked(&header, height + 1, &Vec::new(), &Vec::new());
        for i in 2..depth + 1 {
                header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
-               chain.block_connected_checked(&header, height + i, &Vec::new(), &Vec::new());
+               notifier.block_connected_checked(&header, height + i, &Vec::new(), &Vec::new());
        }
        header.bitcoin_hash()
 }
 
 pub struct Node {
+       pub block_notifier: Arc<chaininterface::BlockNotifier>,
        pub chain_monitor: Arc<chaininterface::ChainWatchInterfaceUtil>,
        pub tx_broadcaster: Arc<test_utils::TestBroadcaster>,
        pub chan_monitor: Arc<test_utils::TestChannelMonitor>,
        pub keys_manager: Arc<test_utils::TestKeysInterface>,
-       pub node: Arc<ChannelManager>,
+       pub node: Arc<ChannelManager<EnforcingChannelKeys>>,
        pub router: Router,
        pub node_seed: [u8; 32],
        pub network_payment_count: Rc<RefCell<u8>>,
        pub network_chan_count: Rc<RefCell<u32>>,
+       pub logger: Arc<test_utils::TestLogger>
 }
 impl Drop for Node {
        fn drop(&mut self) {
@@ -220,7 +223,7 @@ pub fn create_chan_between_nodes_with_value_init(node_a: &Node, node_b: &Node, c
 }
 
 pub fn create_chan_between_nodes_with_value_confirm_first(node_recv: &Node, node_conf: &Node, tx: &Transaction) {
-       confirm_transaction(&node_conf.chain_monitor, &tx, tx.version);
+       confirm_transaction(&node_conf.block_notifier, &node_conf.chain_monitor, &tx, tx.version);
        node_recv.node.handle_funding_locked(&node_conf.node.get_our_node_id(), &get_event_msg!(node_conf, MessageSendEvent::SendFundingLocked, node_recv.node.get_our_node_id())).unwrap();
 }
 
@@ -246,7 +249,7 @@ pub fn create_chan_between_nodes_with_value_confirm_second(node_recv: &Node, nod
 
 pub fn create_chan_between_nodes_with_value_confirm(node_a: &Node, node_b: &Node, tx: &Transaction) -> ((msgs::FundingLocked, msgs::AnnouncementSignatures), [u8; 32]) {
        create_chan_between_nodes_with_value_confirm_first(node_a, node_b, tx);
-       confirm_transaction(&node_a.chain_monitor, &tx, tx.version);
+       confirm_transaction(&node_a.block_notifier, &node_a.chain_monitor, &tx, tx.version);
        create_chan_between_nodes_with_value_confirm_second(node_b, node_a)
 }
 
@@ -636,8 +639,8 @@ pub fn send_along_route(origin_node: &Node, route: Route, expected_route: &[&Nod
        (our_payment_preimage, our_payment_hash)
 }
 
-pub fn claim_payment_along_route(origin_node: &Node, expected_route: &[&Node], skip_last: bool, our_payment_preimage: PaymentPreimage) {
-       assert!(expected_route.last().unwrap().node.claim_funds(our_payment_preimage));
+pub fn claim_payment_along_route(origin_node: &Node, expected_route: &[&Node], skip_last: bool, our_payment_preimage: PaymentPreimage, expected_amount: u64) {
+       assert!(expected_route.last().unwrap().node.claim_funds(our_payment_preimage, expected_amount));
        check_added_monitors!(expected_route.last().unwrap(), 1);
 
        let mut next_msgs: Option<(msgs::UpdateFulfillHTLC, msgs::CommitmentSigned)> = None;
@@ -714,8 +717,8 @@ pub fn claim_payment_along_route(origin_node: &Node, expected_route: &[&Node], s
        }
 }
 
-pub fn claim_payment(origin_node: &Node, expected_route: &[&Node], our_payment_preimage: PaymentPreimage) {
-       claim_payment_along_route(origin_node, expected_route, false, our_payment_preimage);
+pub fn claim_payment(origin_node: &Node, expected_route: &[&Node], our_payment_preimage: PaymentPreimage, expected_amount: u64) {
+       claim_payment_along_route(origin_node, expected_route, false, our_payment_preimage, expected_amount);
 }
 
 pub const TEST_FINAL_CLTV: u32 = 32;
@@ -746,9 +749,9 @@ pub fn route_over_limit(origin_node: &Node, expected_route: &[&Node], recv_value
        };
 }
 
-pub fn send_payment(origin: &Node, expected_route: &[&Node], recv_value: u64) {
+pub fn send_payment(origin: &Node, expected_route: &[&Node], recv_value: u64, expected_value: u64) {
        let our_payment_preimage = route_payment(&origin, expected_route, recv_value).0;
-       claim_payment(&origin, expected_route, our_payment_preimage);
+       claim_payment(&origin, expected_route, our_payment_preimage, expected_value);
 }
 
 pub fn fail_payment_along_route(origin_node: &Node, expected_route: &[&Node], skip_last: bool, our_payment_hash: PaymentHash) {
@@ -833,22 +836,30 @@ pub fn create_network(node_count: usize, node_config: &[Option<UserConfig>]) ->
        let payment_count = Rc::new(RefCell::new(0));
 
        for i in 0..node_count {
-               let logger: Arc<Logger> = Arc::new(test_utils::TestLogger::with_id(format!("node {}", i)));
+               let test_logger = Arc::new(test_utils::TestLogger::with_id(format!("node {}", i)));
+               let logger = &(Arc::clone(&test_logger) as Arc<Logger>);
                let feeest = Arc::new(test_utils::TestFeeEstimator { sat_per_kw: 253 });
                let chain_monitor = Arc::new(chaininterface::ChainWatchInterfaceUtil::new(Network::Testnet, Arc::clone(&logger)));
+               let block_notifier = Arc::new(chaininterface::BlockNotifier::new(chain_monitor.clone()));
                let tx_broadcaster = Arc::new(test_utils::TestBroadcaster{txn_broadcasted: Mutex::new(Vec::new())});
                let mut seed = [0; 32];
                rng.fill_bytes(&mut seed);
                let keys_manager = Arc::new(test_utils::TestKeysInterface::new(&seed, Network::Testnet, Arc::clone(&logger)));
                let chan_monitor = Arc::new(test_utils::TestChannelMonitor::new(chain_monitor.clone(), tx_broadcaster.clone(), logger.clone(), feeest.clone()));
-               let mut default_config = UserConfig::new();
+               let weak_res = Arc::downgrade(&chan_monitor.simple_monitor);
+               block_notifier.register_listener(weak_res);
+               let mut default_config = UserConfig::default();
                default_config.channel_options.announced_channel = true;
                default_config.peer_channel_config_limits.force_announced_channel_preference = false;
-               let node = ChannelManager::new(Network::Testnet, feeest.clone(), chan_monitor.clone(), chain_monitor.clone(), tx_broadcaster.clone(), Arc::clone(&logger), keys_manager.clone(), if node_config[i].is_some() { node_config[i].clone().unwrap() } else { default_config }, 0).unwrap();
+               let node = ChannelManager::new(Network::Testnet, feeest.clone(), chan_monitor.clone(), tx_broadcaster.clone(), Arc::clone(&logger), keys_manager.clone(), if node_config[i].is_some() { node_config[i].clone().unwrap() } else { default_config }, 0).unwrap();
+               let weak_res = Arc::downgrade(&node);
+               block_notifier.register_listener(weak_res);
                let router = Router::new(PublicKey::from_secret_key(&secp_ctx, &keys_manager.get_node_secret()), chain_monitor.clone(), Arc::clone(&logger));
                nodes.push(Node { chain_monitor, tx_broadcaster, chan_monitor, node, router, keys_manager, node_seed: seed,
                        network_payment_count: payment_count.clone(),
                        network_chan_count: chan_count.clone(),
+                       block_notifier,
+                       logger: test_logger
                });
        }
 
@@ -913,15 +924,21 @@ pub fn test_txn_broadcast(node: &Node, chan: &(msgs::ChannelUpdate, msgs::Channe
 
 /// Tests that the given node has broadcast a claim transaction against the provided revoked
 /// HTLC transaction.
-pub fn test_revoked_htlc_claim_txn_broadcast(node: &Node, revoked_tx: Transaction) {
+pub fn test_revoked_htlc_claim_txn_broadcast(node: &Node, revoked_tx: Transaction, commitment_revoked_tx: Transaction) {
        let mut node_txn = node.tx_broadcaster.txn_broadcasted.lock().unwrap();
-       assert_eq!(node_txn.len(), 1);
+       // We should issue a 2nd transaction if one htlc is dropped from initial claiming tx
+       // but sometimes not as feerate is too-low
+       if node_txn.len() != 1 && node_txn.len() != 2 { assert!(false); }
        node_txn.retain(|tx| {
                if tx.input.len() == 1 && tx.input[0].previous_output.txid == revoked_tx.txid() {
-                       check_spends!(tx, revoked_tx.clone());
+                       check_spends!(tx, revoked_tx);
                        false
                } else { true }
        });
+       node_txn.retain(|tx| {
+               check_spends!(tx, commitment_revoked_tx);
+               false
+       });
        assert!(node_txn.is_empty());
 }