7a5b62e00d55226bbccc6bde57dfd3a395a398a9
[rust-lightning] / lightning / src / ln / priv_short_conf_tests.rs
1 // This file is Copyright its original authors, visible in version control
2 // history.
3 //
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
8 // licenses.
9
10 //! Tests that test ChannelManager behavior with fewer confirmations required than the default and
11 //! other behavior that exists only on private channels or with a semi-trusted counterparty (eg
12 //! LSP).
13
14 use chain::{ChannelMonitorUpdateStatus, Watch};
15 use chain::channelmonitor::ChannelMonitor;
16 use chain::keysinterface::{Recipient, KeysInterface};
17 use ln::channelmanager::{self, ChannelManager, ChannelManagerReadArgs, MIN_CLTV_EXPIRY_DELTA};
18 use routing::gossip::RoutingFees;
19 use routing::router::{PaymentParameters, RouteHint, RouteHintHop};
20 use ln::features::ChannelTypeFeatures;
21 use ln::msgs;
22 use ln::msgs::{ChannelMessageHandler, RoutingMessageHandler, ChannelUpdate, ErrorAction};
23 use ln::wire::Encode;
24 use util::enforcing_trait_impls::EnforcingSigner;
25 use util::events::{ClosureReason, Event, HTLCDestination, MessageSendEvent, MessageSendEventsProvider};
26 use util::config::UserConfig;
27 use util::ser::{Writeable, ReadableArgs};
28 use util::test_utils;
29
30 use prelude::*;
31 use core::default::Default;
32
33 use ln::functional_test_utils::*;
34
35 use bitcoin::blockdata::constants::genesis_block;
36 use bitcoin::hash_types::BlockHash;
37 use bitcoin::hashes::Hash;
38 use bitcoin::hashes::sha256d::Hash as Sha256dHash;
39 use bitcoin::network::constants::Network;
40 use bitcoin::secp256k1::Secp256k1;
41
42 #[test]
43 fn test_priv_forwarding_rejection() {
44         // If we have a private channel with outbound liquidity, and
45         // UserConfig::accept_forwards_to_priv_channels is set to false, we should reject any attempts
46         // to forward through that channel.
47         let chanmon_cfgs = create_chanmon_cfgs(3);
48         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
49         let mut no_announce_cfg = test_default_channel_config();
50         no_announce_cfg.accept_forwards_to_priv_channels = false;
51         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, Some(no_announce_cfg), None]);
52         let persister: test_utils::TestPersister;
53         let new_chain_monitor: test_utils::TestChainMonitor;
54         let nodes_1_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
55         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
56
57         let chan_id_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 500_000_000, channelmanager::provided_init_features(), channelmanager::provided_init_features()).2;
58         let chan_id_2 = create_unannounced_chan_between_nodes_with_value(&nodes, 1, 2, 1_000_000, 500_000_000, channelmanager::provided_init_features(), channelmanager::provided_init_features()).0.channel_id;
59
60         // We should always be able to forward through nodes[1] as long as its out through a public
61         // channel:
62         send_payment(&nodes[2], &[&nodes[1], &nodes[0]], 10_000);
63
64         // ... however, if we send to nodes[2], we will have to pass the private channel from nodes[1]
65         // to nodes[2], which should be rejected:
66         let route_hint = RouteHint(vec![RouteHintHop {
67                 src_node_id: nodes[1].node.get_our_node_id(),
68                 short_channel_id: nodes[2].node.list_channels()[0].short_channel_id.unwrap(),
69                 fees: RoutingFees { base_msat: 1000, proportional_millionths: 0 },
70                 cltv_expiry_delta: MIN_CLTV_EXPIRY_DELTA,
71                 htlc_minimum_msat: None,
72                 htlc_maximum_msat: None,
73         }]);
74         let last_hops = vec![route_hint];
75         let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id())
76                 .with_features(channelmanager::provided_invoice_features())
77                 .with_route_hints(last_hops);
78         let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], payment_params, 10_000, TEST_FINAL_CLTV);
79
80         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
81         check_added_monitors!(nodes[0], 1);
82         let payment_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
83         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
84         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false, true);
85
86         let htlc_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
87         assert!(htlc_fail_updates.update_add_htlcs.is_empty());
88         assert_eq!(htlc_fail_updates.update_fail_htlcs.len(), 1);
89         assert!(htlc_fail_updates.update_fail_malformed_htlcs.is_empty());
90         assert!(htlc_fail_updates.update_fee.is_none());
91
92         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_fail_updates.update_fail_htlcs[0]);
93         commitment_signed_dance!(nodes[0], nodes[1], htlc_fail_updates.commitment_signed, true, true);
94         expect_payment_failed_with_update!(nodes[0], our_payment_hash, false, nodes[2].node.list_channels()[0].short_channel_id.unwrap(), true);
95
96         // Now disconnect nodes[1] from its peers and restart with accept_forwards_to_priv_channels set
97         // to true. Sadly there is currently no way to change it at runtime.
98
99         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
100         nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
101
102         let nodes_1_serialized = nodes[1].node.encode();
103         let mut monitor_a_serialized = test_utils::TestVecWriter(Vec::new());
104         let mut monitor_b_serialized = test_utils::TestVecWriter(Vec::new());
105         get_monitor!(nodes[1], chan_id_1).write(&mut monitor_a_serialized).unwrap();
106         get_monitor!(nodes[1], chan_id_2).write(&mut monitor_b_serialized).unwrap();
107
108         persister = test_utils::TestPersister::new();
109         let keys_manager = &chanmon_cfgs[1].keys_manager;
110         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);
111         nodes[1].chain_monitor = &new_chain_monitor;
112
113         let mut monitor_a_read = &monitor_a_serialized.0[..];
114         let mut monitor_b_read = &monitor_b_serialized.0[..];
115         let (_, mut monitor_a) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut monitor_a_read, keys_manager).unwrap();
116         let (_, mut monitor_b) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut monitor_b_read, keys_manager).unwrap();
117         assert!(monitor_a_read.is_empty());
118         assert!(monitor_b_read.is_empty());
119
120         no_announce_cfg.accept_forwards_to_priv_channels = true;
121
122         let mut nodes_1_read = &nodes_1_serialized[..];
123         let (_, nodes_1_deserialized_tmp) = {
124                 let mut channel_monitors = HashMap::new();
125                 channel_monitors.insert(monitor_a.get_funding_txo().0, &mut monitor_a);
126                 channel_monitors.insert(monitor_b.get_funding_txo().0, &mut monitor_b);
127                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_1_read, ChannelManagerReadArgs {
128                         default_config: no_announce_cfg,
129                         keys_manager,
130                         fee_estimator: node_cfgs[1].fee_estimator,
131                         chain_monitor: nodes[1].chain_monitor,
132                         tx_broadcaster: nodes[1].tx_broadcaster.clone(),
133                         logger: nodes[1].logger,
134                         channel_monitors,
135                 }).unwrap()
136         };
137         assert!(nodes_1_read.is_empty());
138         nodes_1_deserialized = nodes_1_deserialized_tmp;
139
140         assert_eq!(nodes[1].chain_monitor.watch_channel(monitor_a.get_funding_txo().0, monitor_a),
141                 ChannelMonitorUpdateStatus::Completed);
142         assert_eq!(nodes[1].chain_monitor.watch_channel(monitor_b.get_funding_txo().0, monitor_b),
143                 ChannelMonitorUpdateStatus::Completed);
144         check_added_monitors!(nodes[1], 2);
145         nodes[1].node = &nodes_1_deserialized;
146
147         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
148         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
149         let as_reestablish = get_chan_reestablish_msgs!(nodes[0], nodes[1]).pop().unwrap();
150         let bs_reestablish = get_chan_reestablish_msgs!(nodes[1], nodes[0]).pop().unwrap();
151         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &as_reestablish);
152         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bs_reestablish);
153         get_event_msg!(nodes[0], MessageSendEvent::SendChannelUpdate, nodes[1].node.get_our_node_id());
154         get_event_msg!(nodes[1], MessageSendEvent::SendChannelUpdate, nodes[0].node.get_our_node_id());
155
156         nodes[1].node.peer_connected(&nodes[2].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
157         nodes[2].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
158         let bs_reestablish = get_chan_reestablish_msgs!(nodes[1], nodes[2]).pop().unwrap();
159         let cs_reestablish = get_chan_reestablish_msgs!(nodes[2], nodes[1]).pop().unwrap();
160         nodes[2].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bs_reestablish);
161         nodes[1].node.handle_channel_reestablish(&nodes[2].node.get_our_node_id(), &cs_reestablish);
162         get_event_msg!(nodes[1], MessageSendEvent::SendChannelUpdate, nodes[2].node.get_our_node_id());
163         get_event_msg!(nodes[2], MessageSendEvent::SendChannelUpdate, nodes[1].node.get_our_node_id());
164
165         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
166         check_added_monitors!(nodes[0], 1);
167         pass_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], 10_000, our_payment_hash, our_payment_secret);
168         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], our_payment_preimage);
169 }
170
171 fn do_test_1_conf_open(connect_style: ConnectStyle) {
172         // Previously, if the minium_depth config was set to 1, we'd never send a channel_ready. This
173         // tests that we properly send one in that case.
174         let mut alice_config = UserConfig::default();
175         alice_config.channel_handshake_config.minimum_depth = 1;
176         alice_config.channel_handshake_config.announced_channel = true;
177         alice_config.channel_handshake_limits.force_announced_channel_preference = false;
178         let mut bob_config = UserConfig::default();
179         bob_config.channel_handshake_config.minimum_depth = 1;
180         bob_config.channel_handshake_config.announced_channel = true;
181         bob_config.channel_handshake_limits.force_announced_channel_preference = false;
182         let chanmon_cfgs = create_chanmon_cfgs(2);
183         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
184         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(alice_config), Some(bob_config)]);
185         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
186         *nodes[0].connect_style.borrow_mut() = connect_style;
187
188         let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features());
189         mine_transaction(&nodes[1], &tx);
190         nodes[0].node.handle_channel_ready(&nodes[1].node.get_our_node_id(), &get_event_msg!(nodes[1], MessageSendEvent::SendChannelReady, nodes[0].node.get_our_node_id()));
191         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
192
193         mine_transaction(&nodes[0], &tx);
194         let as_msg_events = nodes[0].node.get_and_clear_pending_msg_events();
195         assert_eq!(as_msg_events.len(), 2);
196         let as_channel_ready = if let MessageSendEvent::SendChannelReady { ref node_id, ref msg } = as_msg_events[0] {
197                 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
198                 msg.clone()
199         } else { panic!("Unexpected event"); };
200         if let MessageSendEvent::SendChannelUpdate { ref node_id, msg: _ } = as_msg_events[1] {
201                 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
202         } else { panic!("Unexpected event"); }
203
204         nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready);
205         let bs_msg_events = nodes[1].node.get_and_clear_pending_msg_events();
206         assert_eq!(bs_msg_events.len(), 1);
207         if let MessageSendEvent::SendChannelUpdate { ref node_id, msg: _ } = bs_msg_events[0] {
208                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
209         } else { panic!("Unexpected event"); }
210
211         send_payment(&nodes[0], &[&nodes[1]], 100_000);
212
213         // After 6 confirmations, as required by the spec, we'll send announcement_signatures and
214         // broadcast the channel_announcement (but not before exactly 6 confirmations).
215         connect_blocks(&nodes[0], 4);
216         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
217         connect_blocks(&nodes[0], 1);
218         nodes[1].node.handle_announcement_signatures(&nodes[0].node.get_our_node_id(), &get_event_msg!(nodes[0], MessageSendEvent::SendAnnouncementSignatures, nodes[1].node.get_our_node_id()));
219         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
220
221         connect_blocks(&nodes[1], 5);
222         let bs_announce_events = nodes[1].node.get_and_clear_pending_msg_events();
223         assert_eq!(bs_announce_events.len(), 2);
224         let bs_announcement_sigs = if let MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } = bs_announce_events[0] {
225                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
226                 msg.clone()
227         } else { panic!("Unexpected event"); };
228         let (bs_announcement, bs_update) = if let MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } = bs_announce_events[1] {
229                 (msg.clone(), update_msg.clone())
230         } else { panic!("Unexpected event"); };
231
232         nodes[0].node.handle_announcement_signatures(&nodes[1].node.get_our_node_id(), &bs_announcement_sigs);
233         let as_announce_events = nodes[0].node.get_and_clear_pending_msg_events();
234         assert_eq!(as_announce_events.len(), 1);
235         let (announcement, as_update) = if let MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } = as_announce_events[0] {
236                 (msg.clone(), update_msg.clone())
237         } else { panic!("Unexpected event"); };
238         assert_eq!(announcement, bs_announcement);
239
240         for node in nodes {
241                 assert!(node.gossip_sync.handle_channel_announcement(&announcement).unwrap());
242                 node.gossip_sync.handle_channel_update(&as_update).unwrap();
243                 node.gossip_sync.handle_channel_update(&bs_update).unwrap();
244         }
245 }
246 #[test]
247 fn test_1_conf_open() {
248         do_test_1_conf_open(ConnectStyle::BestBlockFirst);
249         do_test_1_conf_open(ConnectStyle::TransactionsFirst);
250         do_test_1_conf_open(ConnectStyle::FullBlockViaListen);
251 }
252
253 #[test]
254 fn test_routed_scid_alias() {
255         // Trivially test sending a payment which is routed through an SCID alias.
256         let chanmon_cfgs = create_chanmon_cfgs(3);
257         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
258         let mut no_announce_cfg = test_default_channel_config();
259         no_announce_cfg.accept_forwards_to_priv_channels = true;
260         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, Some(no_announce_cfg), None]);
261         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
262
263         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 500_000_000, channelmanager::provided_init_features(), channelmanager::provided_init_features()).2;
264         let mut as_channel_ready = create_unannounced_chan_between_nodes_with_value(&nodes, 1, 2, 1_000_000, 500_000_000, channelmanager::provided_init_features(), channelmanager::provided_init_features()).0;
265
266         let last_hop = nodes[2].node.list_usable_channels();
267         let hop_hints = vec![RouteHint(vec![RouteHintHop {
268                 src_node_id: nodes[1].node.get_our_node_id(),
269                 short_channel_id: last_hop[0].inbound_scid_alias.unwrap(),
270                 fees: RoutingFees {
271                         base_msat: last_hop[0].counterparty.forwarding_info.as_ref().unwrap().fee_base_msat,
272                         proportional_millionths: last_hop[0].counterparty.forwarding_info.as_ref().unwrap().fee_proportional_millionths,
273                 },
274                 cltv_expiry_delta: last_hop[0].counterparty.forwarding_info.as_ref().unwrap().cltv_expiry_delta,
275                 htlc_maximum_msat: None,
276                 htlc_minimum_msat: None,
277         }])];
278         let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id())
279                 .with_features(channelmanager::provided_invoice_features())
280                 .with_route_hints(hop_hints);
281         let (route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], payment_params, 100_000, 42);
282         assert_eq!(route.paths[0][1].short_channel_id, last_hop[0].inbound_scid_alias.unwrap());
283         nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
284         check_added_monitors!(nodes[0], 1);
285
286         pass_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], 100_000, payment_hash, payment_secret);
287         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
288
289         // Now test that if a peer sends us a second channel_ready after the channel is operational we
290         // will use the new alias.
291         as_channel_ready.short_channel_id_alias = Some(0xdeadbeef);
292         nodes[2].node.handle_channel_ready(&nodes[1].node.get_our_node_id(), &as_channel_ready);
293         // Note that we always respond to a channel_ready with a channel_update. Not a lot of reason
294         // to bother updating that code, so just drop the message here.
295         get_event_msg!(nodes[2], MessageSendEvent::SendChannelUpdate, nodes[1].node.get_our_node_id());
296         let updated_channel_info = nodes[2].node.list_usable_channels();
297         assert_eq!(updated_channel_info.len(), 1);
298         assert_eq!(updated_channel_info[0].inbound_scid_alias.unwrap(), 0xdeadbeef);
299         // Note that because we never send a duplicate channel_ready we can't send a payment through
300         // the 0xdeadbeef SCID alias.
301 }
302
303 #[test]
304 fn test_scid_privacy_on_pub_channel() {
305         // Tests rejecting the scid_privacy feature for public channels and that we don't ever try to
306         // send them.
307         let chanmon_cfgs = create_chanmon_cfgs(2);
308         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
309         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
310         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
311
312         let mut scid_privacy_cfg = test_default_channel_config();
313         scid_privacy_cfg.channel_handshake_config.announced_channel = true;
314         scid_privacy_cfg.channel_handshake_config.negotiate_scid_privacy = true;
315         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(scid_privacy_cfg)).unwrap();
316         let mut open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
317
318         assert!(!open_channel.channel_type.as_ref().unwrap().supports_scid_privacy()); // we ignore `negotiate_scid_privacy` on pub channels
319         open_channel.channel_type.as_mut().unwrap().set_scid_privacy_required();
320         assert_eq!(open_channel.channel_flags & 1, 1); // The `announce_channel` bit is set.
321
322         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &open_channel);
323         let err = get_err_msg!(nodes[1], nodes[0].node.get_our_node_id());
324         assert_eq!(err.data, "SCID Alias/Privacy Channel Type cannot be set on a public channel");
325 }
326
327 #[test]
328 fn test_scid_privacy_negotiation() {
329         // Tests of the negotiation of SCID alias and falling back to non-SCID-alias if our
330         // counterparty doesn't support it.
331         let chanmon_cfgs = create_chanmon_cfgs(2);
332         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
333         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
334         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
335
336         let mut scid_privacy_cfg = test_default_channel_config();
337         scid_privacy_cfg.channel_handshake_config.announced_channel = false;
338         scid_privacy_cfg.channel_handshake_config.negotiate_scid_privacy = true;
339         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(scid_privacy_cfg)).unwrap();
340
341         let init_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
342         assert!(init_open_channel.channel_type.as_ref().unwrap().supports_scid_privacy());
343         assert!(nodes[0].node.list_channels()[0].channel_type.is_none()); // channel_type is none until counterparty accepts
344
345         // now simulate nodes[1] responding with an Error message, indicating it doesn't understand
346         // SCID alias.
347         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage {
348                 channel_id: init_open_channel.temporary_channel_id,
349                 data: "Yo, no SCID aliases, no privacy here!".to_string()
350         });
351         assert!(nodes[0].node.list_channels()[0].channel_type.is_none()); // channel_type is none until counterparty accepts
352
353         let second_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
354         assert!(!second_open_channel.channel_type.as_ref().unwrap().supports_scid_privacy());
355         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &second_open_channel);
356         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), channelmanager::provided_init_features(), &get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id()));
357
358         let events = nodes[0].node.get_and_clear_pending_events();
359         assert_eq!(events.len(), 1);
360         match events[0] {
361                 Event::FundingGenerationReady { .. } => {},
362                 _ => panic!("Unexpected event"),
363         }
364
365         assert!(!nodes[0].node.list_channels()[0].channel_type.as_ref().unwrap().supports_scid_privacy());
366         assert!(!nodes[1].node.list_channels()[0].channel_type.as_ref().unwrap().supports_scid_privacy());
367 }
368
369 #[test]
370 fn test_inbound_scid_privacy() {
371         // Tests accepting channels with the scid_privacy feature and rejecting forwards using the
372         // channel's real SCID as required by the channel feature.
373         let chanmon_cfgs = create_chanmon_cfgs(3);
374         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
375         let mut accept_forward_cfg = test_default_channel_config();
376         accept_forward_cfg.accept_forwards_to_priv_channels = true;
377         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, Some(accept_forward_cfg), None]);
378         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
379
380         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
381
382         let mut no_announce_cfg = test_default_channel_config();
383         no_announce_cfg.channel_handshake_config.announced_channel = false;
384         no_announce_cfg.channel_handshake_config.negotiate_scid_privacy = true;
385         nodes[1].node.create_channel(nodes[2].node.get_our_node_id(), 100_000, 10_000, 42, Some(no_announce_cfg)).unwrap();
386         let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[2].node.get_our_node_id());
387
388         assert!(open_channel.channel_type.as_ref().unwrap().requires_scid_privacy());
389
390         nodes[2].node.handle_open_channel(&nodes[1].node.get_our_node_id(), channelmanager::provided_init_features(), &open_channel);
391         let accept_channel = get_event_msg!(nodes[2], MessageSendEvent::SendAcceptChannel, nodes[1].node.get_our_node_id());
392         nodes[1].node.handle_accept_channel(&nodes[2].node.get_our_node_id(), channelmanager::provided_init_features(), &accept_channel);
393
394         let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[1], &nodes[2].node.get_our_node_id(), 100_000, 42);
395         nodes[1].node.funding_transaction_generated(&temporary_channel_id, &nodes[2].node.get_our_node_id(), tx.clone()).unwrap();
396         nodes[2].node.handle_funding_created(&nodes[1].node.get_our_node_id(), &get_event_msg!(nodes[1], MessageSendEvent::SendFundingCreated, nodes[2].node.get_our_node_id()));
397         check_added_monitors!(nodes[2], 1);
398
399         let cs_funding_signed = get_event_msg!(nodes[2], MessageSendEvent::SendFundingSigned, nodes[1].node.get_our_node_id());
400         nodes[1].node.handle_funding_signed(&nodes[2].node.get_our_node_id(), &cs_funding_signed);
401         check_added_monitors!(nodes[1], 1);
402
403         let conf_height = core::cmp::max(nodes[1].best_block_info().1 + 1, nodes[2].best_block_info().1 + 1);
404         confirm_transaction_at(&nodes[1], &tx, conf_height);
405         connect_blocks(&nodes[1], CHAN_CONFIRM_DEPTH - 1);
406         confirm_transaction_at(&nodes[2], &tx, conf_height);
407         connect_blocks(&nodes[2], CHAN_CONFIRM_DEPTH - 1);
408         let bs_channel_ready = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReady, nodes[2].node.get_our_node_id());
409         nodes[1].node.handle_channel_ready(&nodes[2].node.get_our_node_id(), &get_event_msg!(nodes[2], MessageSendEvent::SendChannelReady, nodes[1].node.get_our_node_id()));
410         let bs_update = get_event_msg!(nodes[1], MessageSendEvent::SendChannelUpdate, nodes[2].node.get_our_node_id());
411         nodes[2].node.handle_channel_ready(&nodes[1].node.get_our_node_id(), &bs_channel_ready);
412         let cs_update = get_event_msg!(nodes[2], MessageSendEvent::SendChannelUpdate, nodes[1].node.get_our_node_id());
413
414         nodes[1].node.handle_channel_update(&nodes[2].node.get_our_node_id(), &cs_update);
415         nodes[2].node.handle_channel_update(&nodes[1].node.get_our_node_id(), &bs_update);
416
417         // Now we can pay just fine using the SCID alias nodes[2] gave to nodes[1]...
418
419         let last_hop = nodes[2].node.list_usable_channels();
420         let mut hop_hints = vec![RouteHint(vec![RouteHintHop {
421                 src_node_id: nodes[1].node.get_our_node_id(),
422                 short_channel_id: last_hop[0].inbound_scid_alias.unwrap(),
423                 fees: RoutingFees {
424                         base_msat: last_hop[0].counterparty.forwarding_info.as_ref().unwrap().fee_base_msat,
425                         proportional_millionths: last_hop[0].counterparty.forwarding_info.as_ref().unwrap().fee_proportional_millionths,
426                 },
427                 cltv_expiry_delta: last_hop[0].counterparty.forwarding_info.as_ref().unwrap().cltv_expiry_delta,
428                 htlc_maximum_msat: None,
429                 htlc_minimum_msat: None,
430         }])];
431         let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id())
432                 .with_features(channelmanager::provided_invoice_features())
433                 .with_route_hints(hop_hints.clone());
434         let (route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], payment_params, 100_000, 42);
435         assert_eq!(route.paths[0][1].short_channel_id, last_hop[0].inbound_scid_alias.unwrap());
436         nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
437         check_added_monitors!(nodes[0], 1);
438
439         pass_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], 100_000, payment_hash, payment_secret);
440         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
441
442         // ... but if we try to pay using the real SCID, nodes[1] will just tell us they don't know
443         // what channel we're talking about.
444         hop_hints[0].0[0].short_channel_id = last_hop[0].short_channel_id.unwrap();
445
446         let payment_params_2 = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id())
447                 .with_features(channelmanager::provided_invoice_features())
448                 .with_route_hints(hop_hints);
449         let (route_2, payment_hash_2, _, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[2], payment_params_2, 100_000, 42);
450         assert_eq!(route_2.paths[0][1].short_channel_id, last_hop[0].short_channel_id.unwrap());
451         nodes[0].node.send_payment(&route_2, payment_hash_2, &Some(payment_secret_2)).unwrap();
452         check_added_monitors!(nodes[0], 1);
453
454         let payment_event = SendEvent::from_node(&nodes[0]);
455         assert_eq!(nodes[1].node.get_our_node_id(), payment_event.node_id);
456         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
457         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, true, true);
458
459         nodes[1].logger.assert_log_regex("lightning::ln::channelmanager".to_string(), regex::Regex::new(r"Refusing to forward over real channel SCID as our counterparty requested").unwrap(), 1);
460
461         let mut updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
462         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
463         commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, false);
464
465         expect_payment_failed_conditions(&nodes[0], payment_hash_2, false,
466                 PaymentFailedConditions::new().blamed_scid(last_hop[0].short_channel_id.unwrap())
467                         .blamed_chan_closed(true).expected_htlc_error_data(0x4000|10, &[0; 0]));
468 }
469
470 #[test]
471 fn test_scid_alias_returned() {
472         // Tests that when we fail an HTLC (in this case due to attempting to forward more than the
473         // channel's available balance) we use the correct (in this case the aliased) SCID in the
474         // channel_update which is returned in the onion to the sender.
475         let chanmon_cfgs = create_chanmon_cfgs(3);
476         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
477         let mut accept_forward_cfg = test_default_channel_config();
478         accept_forward_cfg.accept_forwards_to_priv_channels = true;
479         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, Some(accept_forward_cfg), None]);
480         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
481
482         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
483         let chan = create_unannounced_chan_between_nodes_with_value(&nodes, 1, 2, 10_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
484
485         let last_hop = nodes[2].node.list_usable_channels();
486         let mut hop_hints = vec![RouteHint(vec![RouteHintHop {
487                 src_node_id: nodes[1].node.get_our_node_id(),
488                 short_channel_id: last_hop[0].inbound_scid_alias.unwrap(),
489                 fees: RoutingFees {
490                         base_msat: last_hop[0].counterparty.forwarding_info.as_ref().unwrap().fee_base_msat,
491                         proportional_millionths: last_hop[0].counterparty.forwarding_info.as_ref().unwrap().fee_proportional_millionths,
492                 },
493                 cltv_expiry_delta: last_hop[0].counterparty.forwarding_info.as_ref().unwrap().cltv_expiry_delta,
494                 htlc_maximum_msat: None,
495                 htlc_minimum_msat: None,
496         }])];
497         let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id())
498                 .with_features(channelmanager::provided_invoice_features())
499                 .with_route_hints(hop_hints);
500         let (mut route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], payment_params, 10_000, 42);
501         assert_eq!(route.paths[0][1].short_channel_id, nodes[2].node.list_usable_channels()[0].inbound_scid_alias.unwrap());
502
503         route.paths[0][1].fee_msat = 10_000_000; // Overshoot the last channel's value
504
505         // Route the HTLC through to the destination.
506         nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
507         check_added_monitors!(nodes[0], 1);
508         let as_updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
509         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_updates.update_add_htlcs[0]);
510         commitment_signed_dance!(nodes[1], nodes[0], &as_updates.commitment_signed, false, true);
511
512         expect_pending_htlcs_forwardable!(nodes[1]);
513         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::NextHopChannel { node_id: Some(nodes[2].node.get_our_node_id()), channel_id: chan.0.channel_id }]);
514         check_added_monitors!(nodes[1], 1);
515
516         let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
517         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fail_htlcs[0]);
518         commitment_signed_dance!(nodes[0], nodes[1], bs_updates.commitment_signed, false, true);
519
520         // Build the expected channel update
521         let contents = msgs::UnsignedChannelUpdate {
522                 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
523                 short_channel_id: last_hop[0].inbound_scid_alias.unwrap(),
524                 timestamp: 21,
525                 flags: 1,
526                 cltv_expiry_delta: accept_forward_cfg.channel_config.cltv_expiry_delta,
527                 htlc_minimum_msat: 1_000,
528                 htlc_maximum_msat: 1_000_000, // Defaults to 10% of the channel value
529                 fee_base_msat: last_hop[0].counterparty.forwarding_info.as_ref().unwrap().fee_base_msat,
530                 fee_proportional_millionths: last_hop[0].counterparty.forwarding_info.as_ref().unwrap().fee_proportional_millionths,
531                 excess_data: Vec::new(),
532         };
533         let msg_hash = Sha256dHash::hash(&contents.encode()[..]);
534         let signature = Secp256k1::new().sign_ecdsa(&hash_to_message!(&msg_hash[..]), &nodes[1].keys_manager.get_node_secret(Recipient::Node).unwrap());
535         let msg = msgs::ChannelUpdate { signature, contents };
536
537         let mut err_data = Vec::new();
538         err_data.extend_from_slice(&(msg.serialized_length() as u16 + 2).to_be_bytes());
539         err_data.extend_from_slice(&ChannelUpdate::TYPE.to_be_bytes());
540         err_data.extend_from_slice(&msg.encode());
541
542         expect_payment_failed_conditions(&nodes[0], payment_hash, false,
543                 PaymentFailedConditions::new().blamed_scid(last_hop[0].inbound_scid_alias.unwrap())
544                         .blamed_chan_closed(false).expected_htlc_error_data(0x1000|7, &err_data));
545
546         route.paths[0][1].fee_msat = 10_000; // Reset to the correct payment amount
547         route.paths[0][0].fee_msat = 0; // But set fee paid to the middle hop to 0
548
549         // Route the HTLC through to the destination.
550         nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
551         check_added_monitors!(nodes[0], 1);
552         let as_updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
553         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_updates.update_add_htlcs[0]);
554         commitment_signed_dance!(nodes[1], nodes[0], &as_updates.commitment_signed, false, true);
555
556         let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
557         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fail_htlcs[0]);
558         commitment_signed_dance!(nodes[0], nodes[1], bs_updates.commitment_signed, false, true);
559
560         let mut err_data = Vec::new();
561         err_data.extend_from_slice(&10_000u64.to_be_bytes());
562         err_data.extend_from_slice(&(msg.serialized_length() as u16 + 2).to_be_bytes());
563         err_data.extend_from_slice(&ChannelUpdate::TYPE.to_be_bytes());
564         err_data.extend_from_slice(&msg.encode());
565         expect_payment_failed_conditions(&nodes[0], payment_hash, false,
566                 PaymentFailedConditions::new().blamed_scid(last_hop[0].inbound_scid_alias.unwrap())
567                         .blamed_chan_closed(false).expected_htlc_error_data(0x1000|12, &err_data));
568 }
569
570 #[test]
571 fn test_simple_0conf_channel() {
572         // If our peer tells us they will accept our channel with 0 confs, and we funded the channel,
573         // we should trust the funding won't be double-spent (assuming `trust_own_funding_0conf` is
574         // set)!
575         // Further, if we `accept_inbound_channel_from_trusted_peer_0conf`, `channel_ready` messages
576         // should fly immediately and the channel should be available for use as soon as they are
577         // received.
578
579         let chanmon_cfgs = create_chanmon_cfgs(2);
580         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
581         let mut chan_config = test_default_channel_config();
582         chan_config.manually_accept_inbound_channels = true;
583
584         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(chan_config)]);
585         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
586
587         open_zero_conf_channel(&nodes[0], &nodes[1], None);
588
589         send_payment(&nodes[0], &[&nodes[1]], 100_000);
590 }
591
592 #[test]
593 fn test_0conf_channel_with_async_monitor() {
594         // Test that we properly send out channel_ready in (both inbound- and outbound-) zero-conf
595         // channels if ChannelMonitor updates return a `TemporaryFailure` during the initial channel
596         // negotiation.
597
598         let chanmon_cfgs = create_chanmon_cfgs(3);
599         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
600         let mut chan_config = test_default_channel_config();
601         chan_config.manually_accept_inbound_channels = true;
602         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, Some(chan_config), None]);
603         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
604
605         create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1_000_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
606
607         chan_config.channel_handshake_config.announced_channel = false;
608         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(chan_config)).unwrap();
609         let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
610
611         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &open_channel);
612         let events = nodes[1].node.get_and_clear_pending_events();
613         assert_eq!(events.len(), 1);
614         match events[0] {
615                 Event::OpenChannelRequest { temporary_channel_id, .. } => {
616                         nodes[1].node.accept_inbound_channel_from_trusted_peer_0conf(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 0).unwrap();
617                 },
618                 _ => panic!("Unexpected event"),
619         };
620
621         let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
622         assert_eq!(accept_channel.minimum_depth, 0);
623         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), channelmanager::provided_init_features(), &accept_channel);
624
625         let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
626         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
627         let funding_created = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
628
629         chanmon_cfgs[1].persister.set_update_ret(ChannelMonitorUpdateStatus::InProgress);
630         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
631         check_added_monitors!(nodes[1], 1);
632         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
633
634         let channel_id = funding_output.to_channel_id();
635         nodes[1].chain_monitor.complete_sole_pending_chan_update(&channel_id);
636
637         let bs_signed_locked = nodes[1].node.get_and_clear_pending_msg_events();
638         assert_eq!(bs_signed_locked.len(), 2);
639         chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::InProgress);
640
641         match &bs_signed_locked[0] {
642                 MessageSendEvent::SendFundingSigned { node_id, msg } => {
643                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
644                         nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &msg);
645                         check_added_monitors!(nodes[0], 1);
646                 }
647                 _ => panic!("Unexpected event"),
648         }
649         match &bs_signed_locked[1] {
650                 MessageSendEvent::SendChannelReady { node_id, msg } => {
651                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
652                         nodes[0].node.handle_channel_ready(&nodes[1].node.get_our_node_id(), &msg);
653                 }
654                 _ => panic!("Unexpected event"),
655         }
656
657         assert!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
658
659         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
660         nodes[0].chain_monitor.complete_sole_pending_chan_update(&channel_id);
661         let as_locked_update = nodes[0].node.get_and_clear_pending_msg_events();
662
663         // Note that the funding transaction is actually released when
664         // get_and_clear_pending_msg_events, above, checks for monitor events.
665         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
666         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0)[0], tx);
667
668         match &as_locked_update[0] {
669                 MessageSendEvent::SendChannelReady { node_id, msg } => {
670                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
671                         nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &msg);
672                 }
673                 _ => panic!("Unexpected event"),
674         }
675         let bs_channel_update = get_event_msg!(nodes[1], MessageSendEvent::SendChannelUpdate, nodes[0].node.get_our_node_id());
676
677         let as_channel_update = match &as_locked_update[1] {
678                 MessageSendEvent::SendChannelUpdate { node_id, msg } => {
679                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
680                         msg.clone()
681                 }
682                 _ => panic!("Unexpected event"),
683         };
684
685         chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::Completed);
686         chanmon_cfgs[1].persister.set_update_ret(ChannelMonitorUpdateStatus::Completed);
687
688         nodes[0].node.handle_channel_update(&nodes[1].node.get_our_node_id(), &bs_channel_update);
689         nodes[1].node.handle_channel_update(&nodes[0].node.get_our_node_id(), &as_channel_update);
690
691         assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
692         assert_eq!(nodes[1].node.list_usable_channels().len(), 2);
693
694         send_payment(&nodes[0], &[&nodes[1]], 100_000);
695
696         // Now that we have useful channels, try sending a payment where the we hit a temporary monitor
697         // failure before we've ever confirmed the funding transaction. This previously caused a panic.
698         let (route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 1_000_000);
699
700         nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
701         check_added_monitors!(nodes[0], 1);
702
703         let as_send = SendEvent::from_node(&nodes[0]);
704         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_send.msgs[0]);
705         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_send.commitment_msg);
706         check_added_monitors!(nodes[1], 1);
707
708         let (bs_raa, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
709         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
710         check_added_monitors!(nodes[0], 1);
711
712         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
713         check_added_monitors!(nodes[0], 1);
714
715         chanmon_cfgs[1].persister.set_update_ret(ChannelMonitorUpdateStatus::InProgress);
716         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id()));
717         check_added_monitors!(nodes[1], 1);
718         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
719
720         chanmon_cfgs[1].persister.set_update_ret(ChannelMonitorUpdateStatus::Completed);
721         let (outpoint, _, latest_update) = nodes[1].chain_monitor.latest_monitor_update_id.lock().unwrap().get(&bs_raa.channel_id).unwrap().clone();
722         nodes[1].chain_monitor.chain_monitor.channel_monitor_updated(outpoint, latest_update).unwrap();
723         check_added_monitors!(nodes[1], 0);
724         expect_pending_htlcs_forwardable!(nodes[1]);
725         check_added_monitors!(nodes[1], 1);
726
727         let bs_send = SendEvent::from_node(&nodes[1]);
728         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &bs_send.msgs[0]);
729         commitment_signed_dance!(nodes[2], nodes[1], bs_send.commitment_msg, false);
730         expect_pending_htlcs_forwardable!(nodes[2]);
731         expect_payment_received!(nodes[2], payment_hash, payment_secret, 1_000_000);
732         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
733
734         confirm_transaction(&nodes[0], &tx);
735         confirm_transaction(&nodes[1], &tx);
736
737         send_payment(&nodes[0], &[&nodes[1]], 100_000);
738 }
739
740 #[test]
741 fn test_0conf_close_no_early_chan_update() {
742         // Tests that even with a public channel 0conf channel, we don't generate a channel_update on
743         // closing.
744         let chanmon_cfgs = create_chanmon_cfgs(2);
745         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
746         let mut chan_config = test_default_channel_config();
747         chan_config.manually_accept_inbound_channels = true;
748
749         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(chan_config)]);
750         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
751
752         // This is the default but we force it on anyway
753         chan_config.channel_handshake_config.announced_channel = true;
754         open_zero_conf_channel(&nodes[0], &nodes[1], Some(chan_config));
755
756         // We can use the channel immediately, but won't generate a channel_update until we get confs
757         send_payment(&nodes[0], &[&nodes[1]], 100_000);
758
759         nodes[0].node.force_close_all_channels_broadcasting_latest_txn();
760         check_added_monitors!(nodes[0], 1);
761         check_closed_event!(&nodes[0], 1, ClosureReason::HolderForceClosed);
762         let _ = get_err_msg!(nodes[0], nodes[1].node.get_our_node_id());
763 }
764
765 #[test]
766 fn test_public_0conf_channel() {
767         // Tests that we will announce a public channel (after confirmation) even if its 0conf.
768         let chanmon_cfgs = create_chanmon_cfgs(2);
769         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
770         let mut chan_config = test_default_channel_config();
771         chan_config.manually_accept_inbound_channels = true;
772
773         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(chan_config)]);
774         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
775
776         // This is the default but we force it on anyway
777         chan_config.channel_handshake_config.announced_channel = true;
778         let (tx, ..) = open_zero_conf_channel(&nodes[0], &nodes[1], Some(chan_config));
779
780         // We can use the channel immediately, but we can't announce it until we get 6+ confirmations
781         send_payment(&nodes[0], &[&nodes[1]], 100_000);
782
783         let scid = confirm_transaction(&nodes[0], &tx);
784         let as_announcement_sigs = get_event_msg!(nodes[0], MessageSendEvent::SendAnnouncementSignatures, nodes[1].node.get_our_node_id());
785         assert_eq!(confirm_transaction(&nodes[1], &tx), scid);
786         let bs_announcement_sigs = get_event_msg!(nodes[1], MessageSendEvent::SendAnnouncementSignatures, nodes[0].node.get_our_node_id());
787
788         nodes[1].node.handle_announcement_signatures(&nodes[0].node.get_our_node_id(), &as_announcement_sigs);
789         nodes[0].node.handle_announcement_signatures(&nodes[1].node.get_our_node_id(), &bs_announcement_sigs);
790
791         let bs_announcement = nodes[1].node.get_and_clear_pending_msg_events();
792         assert_eq!(bs_announcement.len(), 1);
793         let announcement;
794         let bs_update;
795         match bs_announcement[0] {
796                 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
797                         announcement = msg.clone();
798                         bs_update = update_msg.clone();
799                 },
800                 _ => panic!("Unexpected event"),
801         };
802
803         let as_announcement = nodes[0].node.get_and_clear_pending_msg_events();
804         assert_eq!(as_announcement.len(), 1);
805         match as_announcement[0] {
806                 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
807                         assert!(announcement == *msg);
808                         assert_eq!(update_msg.contents.short_channel_id, scid);
809                         assert_eq!(update_msg.contents.short_channel_id, announcement.contents.short_channel_id);
810                         assert_eq!(update_msg.contents.short_channel_id, bs_update.contents.short_channel_id);
811                 },
812                 _ => panic!("Unexpected event"),
813         };
814 }
815
816 #[test]
817 fn test_0conf_channel_reorg() {
818         // If we accept a 0conf channel, which is then confirmed, but then changes SCID in a reorg, we
819         // have to make sure we handle this correctly (or, currently, just force-close the channel).
820
821         let chanmon_cfgs = create_chanmon_cfgs(2);
822         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
823         let mut chan_config = test_default_channel_config();
824         chan_config.manually_accept_inbound_channels = true;
825
826         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(chan_config)]);
827         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
828
829         // This is the default but we force it on anyway
830         chan_config.channel_handshake_config.announced_channel = true;
831         let (tx, ..) = open_zero_conf_channel(&nodes[0], &nodes[1], Some(chan_config));
832
833         // We can use the channel immediately, but we can't announce it until we get 6+ confirmations
834         send_payment(&nodes[0], &[&nodes[1]], 100_000);
835
836         mine_transaction(&nodes[0], &tx);
837         mine_transaction(&nodes[1], &tx);
838
839         // Send a payment using the channel's real SCID, which will be public in a few blocks once we
840         // can generate a channel_announcement.
841         let real_scid = nodes[0].node.list_usable_channels()[0].short_channel_id.unwrap();
842         assert_eq!(nodes[1].node.list_usable_channels()[0].short_channel_id.unwrap(), real_scid);
843
844         let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 10_000);
845         assert_eq!(route.paths[0][0].short_channel_id, real_scid);
846         send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1]]], 10_000, payment_hash, payment_secret);
847         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage);
848
849         disconnect_blocks(&nodes[0], 1);
850         disconnect_blocks(&nodes[1], 1);
851
852         // At this point the channel no longer has an SCID again. In the future we should likely
853         // support simply un-setting the SCID and waiting until the channel gets re-confirmed, but for
854         // now we force-close the channel here.
855         check_closed_event!(&nodes[0], 1, ClosureReason::ProcessingError {
856                 err: "Funding transaction was un-confirmed. Locked at 0 confs, now have 0 confs.".to_owned()
857         });
858         check_closed_broadcast!(nodes[0], true);
859         check_closed_event!(&nodes[1], 1, ClosureReason::ProcessingError {
860                 err: "Funding transaction was un-confirmed. Locked at 0 confs, now have 0 confs.".to_owned()
861         });
862         check_closed_broadcast!(nodes[1], true);
863 }
864
865 #[test]
866 fn test_zero_conf_accept_reject() {
867         let mut channel_type_features = ChannelTypeFeatures::only_static_remote_key();
868         channel_type_features.set_zero_conf_required();
869
870         // 1. Check we reject zero conf channels by default
871         let chanmon_cfgs = create_chanmon_cfgs(2);
872         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
873         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
874         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
875
876         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
877         let mut open_channel_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
878
879         open_channel_msg.channel_type = Some(channel_type_features.clone());
880
881         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &open_channel_msg);
882
883         let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
884         match msg_events[0] {
885                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg, .. }, .. } => {
886                         assert_eq!(msg.data, "No zero confirmation channels accepted".to_owned());
887                 },
888                 _ => panic!(),
889         }
890
891         // 2. Check we can manually accept zero conf channels via the right method
892         let mut manually_accept_conf = UserConfig::default();
893         manually_accept_conf.manually_accept_inbound_channels = true;
894
895         let chanmon_cfgs = create_chanmon_cfgs(2);
896         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
897         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs,
898                 &[None, Some(manually_accept_conf.clone())]);
899         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
900
901         // 2.1 First try the non-0conf method to manually accept
902         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42,
903                 Some(manually_accept_conf)).unwrap();
904         let mut open_channel_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel,
905                 nodes[1].node.get_our_node_id());
906
907         open_channel_msg.channel_type = Some(channel_type_features.clone());
908
909         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(),
910                 &open_channel_msg);
911
912         // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in the `msg_events`.
913         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
914
915         let events = nodes[1].node.get_and_clear_pending_events();
916
917         match events[0] {
918                 Event::OpenChannelRequest { temporary_channel_id, .. } => {
919                         // Assert we fail to accept via the non-0conf method
920                         assert!(nodes[1].node.accept_inbound_channel(&temporary_channel_id,
921                                 &nodes[0].node.get_our_node_id(), 0).is_err());
922                 },
923                 _ => panic!(),
924         }
925
926         let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
927         match msg_events[0] {
928                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg, .. }, .. } => {
929                         assert_eq!(msg.data, "No zero confirmation channels accepted".to_owned());
930                 },
931                 _ => panic!(),
932         }
933
934         // 2.2 Try again with the 0conf method to manually accept
935         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42,
936                 Some(manually_accept_conf)).unwrap();
937         let mut open_channel_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel,
938                 nodes[1].node.get_our_node_id());
939
940         open_channel_msg.channel_type = Some(channel_type_features);
941
942         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(),
943                 &open_channel_msg);
944
945         let events = nodes[1].node.get_and_clear_pending_events();
946
947         match events[0] {
948                 Event::OpenChannelRequest { temporary_channel_id, .. } => {
949                         // Assert we can accept via the 0conf method
950                         assert!(nodes[1].node.accept_inbound_channel_from_trusted_peer_0conf(
951                                 &temporary_channel_id, &nodes[0].node.get_our_node_id(), 0).is_ok());
952                 },
953                 _ => panic!(),
954         }
955
956         // Check we would send accept
957         let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
958         match msg_events[0] {
959                 MessageSendEvent::SendAcceptChannel { .. } => {},
960                 _ => panic!(),
961         }
962 }
963
964 #[test]
965 fn test_connect_before_funding() {
966         // Tests for a particularly dumb explicit panic that existed prior to 0.0.111 for 0conf
967         // channels. If we received a block while awaiting funding for 0-conf channels we'd hit an
968         // explicit panic when deciding if we should broadcast our channel_ready message.
969         let chanmon_cfgs = create_chanmon_cfgs(2);
970         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
971
972         let mut manually_accept_conf = test_default_channel_config();
973         manually_accept_conf.manually_accept_inbound_channels = true;
974
975         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf)]);
976         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
977
978         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 10_001, 42, None).unwrap();
979         let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
980
981         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &open_channel);
982         let events = nodes[1].node.get_and_clear_pending_events();
983         assert_eq!(events.len(), 1);
984         match events[0] {
985                 Event::OpenChannelRequest { temporary_channel_id, .. } => {
986                         nodes[1].node.accept_inbound_channel_from_trusted_peer_0conf(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 0).unwrap();
987                 },
988                 _ => panic!("Unexpected event"),
989         };
990
991         let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
992         assert_eq!(accept_channel.minimum_depth, 0);
993         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), channelmanager::provided_init_features(), &accept_channel);
994
995         let events = nodes[0].node.get_and_clear_pending_events();
996         assert_eq!(events.len(), 1);
997         match events[0] {
998                 Event::FundingGenerationReady { .. } => {},
999                 _ => panic!("Unexpected event"),
1000         }
1001
1002         connect_blocks(&nodes[0], 1);
1003         connect_blocks(&nodes[1], 1);
1004 }