Merge pull request #1540 from wpaulino/rename-config-fields
[rust-lightning] / lightning / src / ln / functional_test_utils.rs
index 8929a9774381e9342f20790e094e51c64b36d959..38c05998e6a2769db297179d4f0ce0dc76589b9e 100644 (file)
@@ -15,7 +15,7 @@ use chain::channelmonitor::ChannelMonitor;
 use chain::transaction::OutPoint;
 use ln::{PaymentPreimage, PaymentHash, PaymentSecret};
 use ln::channelmanager::{ChainParameters, ChannelManager, ChannelManagerReadArgs, RAACommitmentOrder, PaymentSendFailure, PaymentId, MIN_CLTV_EXPIRY_DELTA};
-use routing::network_graph::{NetGraphMsgHandler, NetworkGraph};
+use routing::gossip::{P2PGossipSync, NetworkGraph, NetworkUpdate};
 use routing::router::{PaymentParameters, Route, get_route};
 use ln::features::{InitFeatures, InvoiceFeatures};
 use ln::msgs;
@@ -27,7 +27,7 @@ use util::test_utils::{panicking, TestChainMonitor};
 use util::events::{Event, MessageSendEvent, MessageSendEventsProvider, PaymentPurpose};
 use util::errors::APIError;
 use util::config::UserConfig;
-use util::ser::{ReadableArgs, Writeable, Readable};
+use util::ser::{ReadableArgs, Writeable};
 
 use bitcoin::blockdata::block::{Block, BlockHeader};
 use bitcoin::blockdata::constants::genesis_block;
@@ -257,7 +257,6 @@ pub struct TestChanMonCfg {
        pub persister: test_utils::TestPersister,
        pub logger: test_utils::TestLogger,
        pub keys_manager: test_utils::TestKeysInterface,
-       pub network_graph: NetworkGraph,
 }
 
 pub struct NodeCfg<'a> {
@@ -267,7 +266,7 @@ pub struct NodeCfg<'a> {
        pub chain_monitor: test_utils::TestChainMonitor<'a>,
        pub keys_manager: &'a test_utils::TestKeysInterface,
        pub logger: &'a test_utils::TestLogger,
-       pub network_graph: &'a NetworkGraph,
+       pub network_graph: NetworkGraph<&'a test_utils::TestLogger>,
        pub node_seed: [u8; 32],
        pub features: InitFeatures,
 }
@@ -278,8 +277,8 @@ pub struct Node<'a, 'b: 'a, 'c: 'b> {
        pub chain_monitor: &'b test_utils::TestChainMonitor<'c>,
        pub keys_manager: &'b test_utils::TestKeysInterface,
        pub node: &'a ChannelManager<EnforcingSigner, &'b TestChainMonitor<'c>, &'c test_utils::TestBroadcaster, &'b test_utils::TestKeysInterface, &'c test_utils::TestFeeEstimator, &'c test_utils::TestLogger>,
-       pub network_graph: &'c NetworkGraph,
-       pub net_graph_msg_handler: NetGraphMsgHandler<&'c NetworkGraph, &'c test_utils::TestChainSource, &'c test_utils::TestLogger>,
+       pub network_graph: &'b NetworkGraph<&'c test_utils::TestLogger>,
+       pub gossip_sync: P2PGossipSync<&'b NetworkGraph<&'c test_utils::TestLogger>, &'c test_utils::TestChainSource, &'c test_utils::TestLogger>,
        pub node_seed: [u8; 32],
        pub network_payment_count: Rc<RefCell<u8>>,
        pub network_chan_count: Rc<RefCell<u32>>,
@@ -311,15 +310,15 @@ impl<'a, 'b, 'c> Drop for Node<'a, 'b, 'c> {
                        {
                                let mut w = test_utils::TestVecWriter(Vec::new());
                                self.network_graph.write(&mut w).unwrap();
-                               let network_graph_deser = <NetworkGraph>::read(&mut io::Cursor::new(&w.0)).unwrap();
+                               let network_graph_deser = <NetworkGraph<_>>::read(&mut io::Cursor::new(&w.0), self.logger).unwrap();
                                assert!(network_graph_deser == *self.network_graph);
-                               let net_graph_msg_handler = NetGraphMsgHandler::new(
+                               let gossip_sync = P2PGossipSync::new(
                                        &network_graph_deser, Some(self.chain_source), self.logger
                                );
                                let mut chan_progress = 0;
                                loop {
-                                       let orig_announcements = self.net_graph_msg_handler.get_next_channel_announcements(chan_progress, 255);
-                                       let deserialized_announcements = net_graph_msg_handler.get_next_channel_announcements(chan_progress, 255);
+                                       let orig_announcements = self.gossip_sync.get_next_channel_announcements(chan_progress, 255);
+                                       let deserialized_announcements = gossip_sync.get_next_channel_announcements(chan_progress, 255);
                                        assert!(orig_announcements == deserialized_announcements);
                                        chan_progress = match orig_announcements.last() {
                                                Some(announcement) => announcement.0.contents.short_channel_id + 1,
@@ -328,8 +327,8 @@ impl<'a, 'b, 'c> Drop for Node<'a, 'b, 'c> {
                                }
                                let mut node_progress = None;
                                loop {
-                                       let orig_announcements = self.net_graph_msg_handler.get_next_node_announcements(node_progress.as_ref(), 255);
-                                       let deserialized_announcements = net_graph_msg_handler.get_next_node_announcements(node_progress.as_ref(), 255);
+                                       let orig_announcements = self.gossip_sync.get_next_node_announcements(node_progress.as_ref(), 255);
+                                       let deserialized_announcements = gossip_sync.get_next_node_announcements(node_progress.as_ref(), 255);
                                        assert!(orig_announcements == deserialized_announcements);
                                        node_progress = match orig_announcements.last() {
                                                Some(announcement) => Some(announcement.contents.node_id),
@@ -773,7 +772,7 @@ pub fn create_announced_chan_between_nodes_with_value<'a, 'b, 'c, 'd>(nodes: &'a
 
 pub fn create_unannounced_chan_between_nodes_with_value<'a, 'b, 'c, 'd>(nodes: &'a Vec<Node<'b, 'c, 'd>>, a: usize, b: usize, channel_value: u64, push_msat: u64, a_flags: InitFeatures, b_flags: InitFeatures) -> (msgs::ChannelReady, Transaction) {
        let mut no_announce_cfg = test_default_channel_config();
-       no_announce_cfg.channel_options.announced_channel = false;
+       no_announce_cfg.channel_handshake_config.announced_channel = false;
        nodes[a].node.create_channel(nodes[b].node.get_our_node_id(), channel_value, push_msat, 42, Some(no_announce_cfg)).unwrap();
        let open_channel = get_event_msg!(nodes[a], MessageSendEvent::SendOpenChannel, nodes[b].node.get_our_node_id());
        nodes[b].node.handle_open_channel(&nodes[a].node.get_our_node_id(), a_flags, &open_channel);
@@ -876,11 +875,11 @@ pub fn update_nodes_with_chan_announce<'a, 'b, 'c, 'd>(nodes: &'a Vec<Node<'b, '
        };
 
        for node in nodes {
-               assert!(node.net_graph_msg_handler.handle_channel_announcement(ann).unwrap());
-               node.net_graph_msg_handler.handle_channel_update(upd_1).unwrap();
-               node.net_graph_msg_handler.handle_channel_update(upd_2).unwrap();
-               node.net_graph_msg_handler.handle_node_announcement(&a_node_announcement).unwrap();
-               node.net_graph_msg_handler.handle_node_announcement(&b_node_announcement).unwrap();
+               assert!(node.gossip_sync.handle_channel_announcement(ann).unwrap());
+               node.gossip_sync.handle_channel_update(upd_1).unwrap();
+               node.gossip_sync.handle_channel_update(upd_2).unwrap();
+               node.gossip_sync.handle_node_announcement(&a_node_announcement).unwrap();
+               node.gossip_sync.handle_node_announcement(&b_node_announcement).unwrap();
 
                // Note that channel_updates are also delivered to ChannelManagers to ensure we have
                // forwarding info for local channels even if its not accepted in the network graph.
@@ -1467,8 +1466,10 @@ impl<'a> PaymentFailedConditions<'a> {
 #[cfg(test)]
 macro_rules! expect_payment_failed_with_update {
        ($node: expr, $expected_payment_hash: expr, $rejected_by_dest: expr, $scid: expr, $chan_closed: expr) => {
-               expect_payment_failed_conditions!($node, $expected_payment_hash, $rejected_by_dest,
-                       $crate::ln::functional_test_utils::PaymentFailedConditions::new().blamed_scid($scid).blamed_chan_closed($chan_closed));
+               $crate::ln::functional_test_utils::expect_payment_failed_conditions(
+                       &$node, $expected_payment_hash, $rejected_by_dest,
+                       $crate::ln::functional_test_utils::PaymentFailedConditions::new()
+                               .blamed_scid($scid).blamed_chan_closed($chan_closed));
        }
 }
 
@@ -1480,64 +1481,72 @@ macro_rules! expect_payment_failed {
                $(
                        conditions = conditions.expected_htlc_error_data($expected_error_code, &$expected_error_data);
                )*
-               expect_payment_failed_conditions!($node, $expected_payment_hash, $rejected_by_dest, conditions);
+               $crate::ln::functional_test_utils::expect_payment_failed_conditions(&$node, $expected_payment_hash, $rejected_by_dest, conditions);
        };
 }
 
-#[cfg(test)]
-macro_rules! expect_payment_failed_conditions {
-       ($node: expr, $expected_payment_hash: expr, $rejected_by_dest: expr, $conditions: expr) => {
-               let events = $node.node.get_and_clear_pending_events();
-               assert_eq!(events.len(), 1);
-               let expected_payment_id = match events[0] {
-                       Event::PaymentPathFailed { ref payment_hash, rejected_by_dest, ref error_code, ref error_data, ref path, ref retry, ref payment_id, ref network_update, .. } => {
-                               assert_eq!(*payment_hash, $expected_payment_hash, "unexpected payment_hash");
-                               assert_eq!(rejected_by_dest, $rejected_by_dest, "unexpected rejected_by_dest value");
-                               assert!(retry.is_some(), "expected retry.is_some()");
-                               assert_eq!(retry.as_ref().unwrap().final_value_msat, path.last().unwrap().fee_msat, "Retry amount should match last hop in path");
-                               assert_eq!(retry.as_ref().unwrap().payment_params.payee_pubkey, path.last().unwrap().pubkey, "Retry payee node_id should match last hop in path");
-
+pub fn expect_payment_failed_conditions<'a, 'b, 'c, 'd, 'e>(
+       node: &'a Node<'b, 'c, 'd>, expected_payment_hash: PaymentHash, expected_rejected_by_dest: bool,
+       conditions: PaymentFailedConditions<'e>
+) {
+       let mut events = node.node.get_and_clear_pending_events();
+       assert_eq!(events.len(), 1);
+       let expected_payment_id = match events.pop().unwrap() {
+               Event::PaymentPathFailed { payment_hash, rejected_by_dest, path, retry, payment_id, network_update,
+                       #[cfg(test)]
+                       error_code,
+                       #[cfg(test)]
+                       error_data, .. } => {
+                       assert_eq!(payment_hash, expected_payment_hash, "unexpected payment_hash");
+                       assert_eq!(rejected_by_dest, expected_rejected_by_dest, "unexpected rejected_by_dest value");
+                       assert!(retry.is_some(), "expected retry.is_some()");
+                       assert_eq!(retry.as_ref().unwrap().final_value_msat, path.last().unwrap().fee_msat, "Retry amount should match last hop in path");
+                       assert_eq!(retry.as_ref().unwrap().payment_params.payee_pubkey, path.last().unwrap().pubkey, "Retry payee node_id should match last hop in path");
+
+                       #[cfg(test)]
+                       {
                                assert!(error_code.is_some(), "expected error_code.is_some() = true");
                                assert!(error_data.is_some(), "expected error_data.is_some() = true");
-                               if let Some((code, data)) = $conditions.expected_htlc_error_data {
+                               if let Some((code, data)) = conditions.expected_htlc_error_data {
                                        assert_eq!(error_code.unwrap(), code, "unexpected error code");
                                        assert_eq!(&error_data.as_ref().unwrap()[..], data, "unexpected error data");
                                }
+                       }
 
-                               if let Some(chan_closed) = $conditions.expected_blamed_chan_closed {
-                                       match network_update {
-                                               &Some($crate::routing::network_graph::NetworkUpdate::ChannelUpdateMessage { ref msg }) if !chan_closed => {
-                                                       if let Some(scid) = $conditions.expected_blamed_scid {
-                                                               assert_eq!(msg.contents.short_channel_id, scid);
-                                                       }
-                                                       assert_eq!(msg.contents.flags & 2, 0);
-                                               },
-                                               &Some($crate::routing::network_graph::NetworkUpdate::ChannelClosed { short_channel_id, is_permanent }) if chan_closed => {
-                                                       if let Some(scid) = $conditions.expected_blamed_scid {
-                                                               assert_eq!(short_channel_id, scid);
-                                                       }
-                                                       assert!(is_permanent);
-                                               },
-                                               Some(_) => panic!("Unexpected update type"),
-                                               None => panic!("Expected update"),
-                                       }
+                       if let Some(chan_closed) = conditions.expected_blamed_chan_closed {
+                               match network_update {
+                                       Some(NetworkUpdate::ChannelUpdateMessage { ref msg }) if !chan_closed => {
+                                               if let Some(scid) = conditions.expected_blamed_scid {
+                                                       assert_eq!(msg.contents.short_channel_id, scid);
+                                               }
+                                               const CHAN_DISABLED_FLAG: u8 = 2;
+                                               assert_eq!(msg.contents.flags & CHAN_DISABLED_FLAG, 0);
+                                       },
+                                       Some(NetworkUpdate::ChannelFailure { short_channel_id, is_permanent }) if chan_closed => {
+                                               if let Some(scid) = conditions.expected_blamed_scid {
+                                                       assert_eq!(short_channel_id, scid);
+                                               }
+                                               assert!(is_permanent);
+                                       },
+                                       Some(_) => panic!("Unexpected update type"),
+                                       None => panic!("Expected update"),
                                }
+                       }
 
-                               payment_id.unwrap()
-                       },
-                       _ => panic!("Unexpected event"),
-               };
-               if !$conditions.expected_mpp_parts_remain {
-                       $node.node.abandon_payment(expected_payment_id);
-                       let events = $node.node.get_and_clear_pending_events();
-                       assert_eq!(events.len(), 1);
-                       match events[0] {
-                               Event::PaymentFailed { ref payment_hash, ref payment_id } => {
-                                       assert_eq!(*payment_hash, $expected_payment_hash, "unexpected second payment_hash");
-                                       assert_eq!(*payment_id, expected_payment_id);
-                               }
-                               _ => panic!("Unexpected second event"),
+                       payment_id.unwrap()
+               },
+               _ => panic!("Unexpected event"),
+       };
+       if !conditions.expected_mpp_parts_remain {
+               node.node.abandon_payment(expected_payment_id);
+               let events = node.node.get_and_clear_pending_events();
+               assert_eq!(events.len(), 1);
+               match events[0] {
+                       Event::PaymentFailed { ref payment_hash, ref payment_id } => {
+                               assert_eq!(*payment_hash, expected_payment_hash, "unexpected second payment_hash");
+                               assert_eq!(*payment_id, expected_payment_id);
                        }
+                       _ => panic!("Unexpected second event"),
                }
        }
 }
@@ -1680,7 +1689,9 @@ pub fn do_claim_payment_along_route<'a, 'b, 'c>(origin_node: &Node<'a, 'b, 'c>,
                        ($node: expr, $prev_node: expr, $next_node: expr, $new_msgs: expr) => {
                                {
                                        $node.node.handle_update_fulfill_htlc(&$prev_node.node.get_our_node_id(), &next_msgs.as_ref().unwrap().0);
-                                       let fee = $node.node.channel_state.lock().unwrap().by_id.get(&next_msgs.as_ref().unwrap().0.channel_id).unwrap().config.forwarding_fee_base_msat;
+                                       let fee = $node.node.channel_state.lock().unwrap()
+                                               .by_id.get(&next_msgs.as_ref().unwrap().0.channel_id).unwrap()
+                                               .config.options.forwarding_fee_base_msat;
                                        expect_payment_forwarded!($node, $next_node, $prev_node, Some(fee as u64), false, false);
                                        expected_total_fee_msat += fee as u64;
                                        check_added_monitors!($node, 1);
@@ -1923,9 +1934,8 @@ pub fn create_chanmon_cfgs(node_count: usize) -> Vec<TestChanMonCfg> {
                let persister = test_utils::TestPersister::new();
                let seed = [i as u8; 32];
                let keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
-               let network_graph = NetworkGraph::new(chain_source.genesis_hash);
 
-               chan_mon_cfgs.push(TestChanMonCfg{ tx_broadcaster, fee_estimator, chain_source, logger, persister, keys_manager, network_graph });
+               chan_mon_cfgs.push(TestChanMonCfg{ tx_broadcaster, fee_estimator, chain_source, logger, persister, keys_manager });
        }
 
        chan_mon_cfgs
@@ -1946,7 +1956,7 @@ pub fn create_node_cfgs<'a>(node_count: usize, chanmon_cfgs: &'a Vec<TestChanMon
                        keys_manager: &chanmon_cfgs[i].keys_manager,
                        node_seed: seed,
                        features: InitFeatures::known(),
-                       network_graph: &chanmon_cfgs[i].network_graph,
+                       network_graph: NetworkGraph::new(chanmon_cfgs[i].chain_source.genesis_hash, &chanmon_cfgs[i].logger),
                });
        }
 
@@ -1957,15 +1967,15 @@ pub fn test_default_channel_config() -> UserConfig {
        let mut default_config = UserConfig::default();
        // Set cltv_expiry_delta slightly lower to keep the final CLTV values inside one byte in our
        // tests so that our script-length checks don't fail (see ACCEPTED_HTLC_SCRIPT_WEIGHT).
-       default_config.channel_options.cltv_expiry_delta = MIN_CLTV_EXPIRY_DELTA;
-       default_config.channel_options.announced_channel = true;
-       default_config.peer_channel_config_limits.force_announced_channel_preference = false;
+       default_config.channel_config.cltv_expiry_delta = MIN_CLTV_EXPIRY_DELTA;
+       default_config.channel_handshake_config.announced_channel = true;
+       default_config.channel_handshake_limits.force_announced_channel_preference = false;
        // When most of our tests were written, the default HTLC minimum was fixed at 1000.
        // It now defaults to 1, so we simply set it to the expected value here.
-       default_config.own_channel_config.our_htlc_minimum_msat = 1000;
+       default_config.channel_handshake_config.our_htlc_minimum_msat = 1000;
        // When most of our tests were written, we didn't have the notion of a `max_dust_htlc_exposure_msat`,
        // It now defaults to 5_000_000 msat; to avoid interfering with tests we bump it to 50_000_000 msat.
-       default_config.channel_options.max_dust_htlc_exposure_msat = 50_000_000;
+       default_config.channel_config.max_dust_htlc_exposure_msat = 50_000_000;
        default_config
 }
 
@@ -1992,11 +2002,11 @@ pub fn create_network<'a, 'b: 'a, 'c: 'b>(node_count: usize, cfgs: &'b Vec<NodeC
        let connect_style = Rc::new(RefCell::new(ConnectStyle::random_style()));
 
        for i in 0..node_count {
-               let net_graph_msg_handler = NetGraphMsgHandler::new(cfgs[i].network_graph, None, cfgs[i].logger);
+               let gossip_sync = P2PGossipSync::new(&cfgs[i].network_graph, None, cfgs[i].logger);
                nodes.push(Node{
                        chain_source: cfgs[i].chain_source, tx_broadcaster: cfgs[i].tx_broadcaster,
                        chain_monitor: &cfgs[i].chain_monitor, keys_manager: &cfgs[i].keys_manager,
-                       node: &chan_mgrs[i], network_graph: &cfgs[i].network_graph, net_graph_msg_handler,
+                       node: &chan_mgrs[i], network_graph: &cfgs[i].network_graph, gossip_sync,
                        node_seed: cfgs[i].node_seed, network_chan_count: chan_count.clone(),
                        network_payment_count: payment_count.clone(), logger: cfgs[i].logger,
                        blocks: Arc::clone(&cfgs[i].tx_broadcaster.blocks),
@@ -2160,8 +2170,8 @@ pub fn handle_announce_close_broadcast_events<'a, 'b, 'c>(nodes: &Vec<Node<'a, '
        }
 
        for node in nodes {
-               node.net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
-               node.net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
+               node.gossip_sync.handle_channel_update(&as_update).unwrap();
+               node.gossip_sync.handle_channel_update(&bs_update).unwrap();
        }
 }