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