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