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