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