1 // This file is Copyright its original authors, visible in version control
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
10 //! Tests for asynchronous signing. These tests verify that the channel state machine behaves
11 //! properly with a signer implementation that asynchronously derives signatures.
13 use bitcoin::{Transaction, TxOut, TxIn, Amount};
14 use bitcoin::blockdata::locktime::absolute::LockTime;
15 use bitcoin::transaction::Version;
17 use crate::chain::channelmonitor::LATENCY_GRACE_PERIOD_BLOCKS;
18 use crate::events::bump_transaction::WalletSource;
19 use crate::events::{Event, MessageSendEvent, MessageSendEventsProvider, ClosureReason};
20 use crate::ln::functional_test_utils::*;
21 use crate::ln::msgs::ChannelMessageHandler;
22 use crate::ln::channelmanager::{PaymentId, RecipientOnionFields};
25 fn test_async_commitment_signature_for_funding_created() {
26 // Simulate acquiring the signature for `funding_created` asynchronously.
27 let chanmon_cfgs = create_chanmon_cfgs(2);
28 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
29 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
30 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
32 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None, None).unwrap();
34 // nodes[0] --- open_channel --> nodes[1]
35 let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
36 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
38 // nodes[0] <-- accept_channel --- nodes[1]
39 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id()));
41 // nodes[0] --- funding_created --> nodes[1]
43 // But! Let's make node[0]'s signer be unavailable: we should *not* broadcast a funding_created
45 let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
46 nodes[0].set_channel_signer_available(&nodes[1].node.get_our_node_id(), &temporary_channel_id, false);
47 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
48 check_added_monitors(&nodes[0], 0);
50 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
52 // Now re-enable the signer and simulate a retry. The temporary_channel_id won't work anymore so
53 // we have to dig out the real channel ID.
55 let channels = nodes[0].node.list_channels();
56 assert_eq!(channels.len(), 1, "expected one channel, not {}", channels.len());
57 channels[0].channel_id
60 nodes[0].set_channel_signer_available(&nodes[1].node.get_our_node_id(), &chan_id, true);
61 nodes[0].node.signer_unblocked(Some((nodes[1].node.get_our_node_id(), chan_id)));
63 let mut funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
64 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
65 check_added_monitors(&nodes[1], 1);
66 expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
68 // nodes[0] <-- funding_signed --- nodes[1]
69 let funding_signed_msg = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
70 nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed_msg);
71 check_added_monitors(&nodes[0], 1);
72 expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
76 fn test_async_commitment_signature_for_funding_signed() {
77 // Simulate acquiring the signature for `funding_signed` asynchronously.
78 let chanmon_cfgs = create_chanmon_cfgs(2);
79 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
80 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
81 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
83 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None, None).unwrap();
85 // nodes[0] --- open_channel --> nodes[1]
86 let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
87 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
89 // nodes[0] <-- accept_channel --- nodes[1]
90 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id()));
92 // nodes[0] --- funding_created --> nodes[1]
93 let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
94 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
95 check_added_monitors(&nodes[0], 0);
97 let mut funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
99 // Now let's make node[1]'s signer be unavailable while handling the `funding_created`. It should
100 // *not* broadcast a `funding_signed`...
101 nodes[1].set_channel_signer_available(&nodes[0].node.get_our_node_id(), &temporary_channel_id, false);
102 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
103 check_added_monitors(&nodes[1], 1);
105 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
107 // Now re-enable the signer and simulate a retry. The temporary_channel_id won't work anymore so
108 // we have to dig out the real channel ID.
110 let channels = nodes[0].node.list_channels();
111 assert_eq!(channels.len(), 1, "expected one channel, not {}", channels.len());
112 channels[0].channel_id
114 nodes[1].set_channel_signer_available(&nodes[0].node.get_our_node_id(), &chan_id, true);
115 nodes[1].node.signer_unblocked(Some((nodes[0].node.get_our_node_id(), chan_id)));
117 expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
119 // nodes[0] <-- funding_signed --- nodes[1]
120 let funding_signed_msg = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
121 nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed_msg);
122 check_added_monitors(&nodes[0], 1);
123 expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
127 fn test_async_commitment_signature_for_commitment_signed() {
128 let chanmon_cfgs = create_chanmon_cfgs(2);
129 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
130 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
131 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
132 let (_, _, chan_id, _) = create_announced_chan_between_nodes(&nodes, 0, 1);
137 let (route, our_payment_hash, _our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(src, dst, 8000000);
138 src.node.send_payment_with_route(&route, our_payment_hash,
139 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
140 check_added_monitors!(src, 1);
142 // Pass the payment along the route.
143 let payment_event = {
144 let mut events = src.node.get_and_clear_pending_msg_events();
145 assert_eq!(events.len(), 1);
146 SendEvent::from_event(events.remove(0))
148 assert_eq!(payment_event.node_id, dst.node.get_our_node_id());
149 assert_eq!(payment_event.msgs.len(), 1);
151 dst.node.handle_update_add_htlc(&src.node.get_our_node_id(), &payment_event.msgs[0]);
153 // Mark dst's signer as unavailable and handle src's commitment_signed: while dst won't yet have a
154 // `commitment_signed` of its own to offer, it should publish a `revoke_and_ack`.
155 dst.set_channel_signer_available(&src.node.get_our_node_id(), &chan_id, false);
156 dst.node.handle_commitment_signed(&src.node.get_our_node_id(), &payment_event.commitment_msg);
157 check_added_monitors(dst, 1);
159 get_event_msg!(dst, MessageSendEvent::SendRevokeAndACK, src.node.get_our_node_id());
161 // Mark dst's signer as available and retry: we now expect to see dst's `commitment_signed`.
162 dst.set_channel_signer_available(&src.node.get_our_node_id(), &chan_id, true);
163 dst.node.signer_unblocked(Some((src.node.get_our_node_id(), chan_id)));
165 let events = dst.node.get_and_clear_pending_msg_events();
166 assert_eq!(events.len(), 1, "expected one message, got {}", events.len());
167 if let MessageSendEvent::UpdateHTLCs { ref node_id, .. } = events[0] {
168 assert_eq!(node_id, &src.node.get_our_node_id());
170 panic!("expected UpdateHTLCs message, not {:?}", events[0]);
175 fn test_async_commitment_signature_for_funding_signed_0conf() {
176 // Simulate acquiring the signature for `funding_signed` asynchronously for a zero-conf channel.
177 let mut manually_accept_config = test_default_channel_config();
178 manually_accept_config.manually_accept_inbound_channels = true;
180 let chanmon_cfgs = create_chanmon_cfgs(2);
181 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
182 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_config)]);
183 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
185 // nodes[0] --- open_channel --> nodes[1]
186 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None, None).unwrap();
187 let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
189 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel);
192 let events = nodes[1].node.get_and_clear_pending_events();
193 assert_eq!(events.len(), 1, "Expected one event, got {}", events.len());
195 Event::OpenChannelRequest { temporary_channel_id, .. } => {
196 nodes[1].node.accept_inbound_channel_from_trusted_peer_0conf(
197 temporary_channel_id, &nodes[0].node.get_our_node_id(), 0)
198 .expect("Unable to accept inbound zero-conf channel");
200 ev => panic!("Expected OpenChannelRequest, not {:?}", ev)
204 // nodes[0] <-- accept_channel --- nodes[1]
205 let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
206 assert_eq!(accept_channel.common_fields.minimum_depth, 0, "Expected minimum depth of 0");
207 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
209 // nodes[0] --- funding_created --> nodes[1]
210 let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
211 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
212 check_added_monitors(&nodes[0], 0);
214 let mut funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
216 // Now let's make node[1]'s signer be unavailable while handling the `funding_created`. It should
217 // *not* broadcast a `funding_signed`...
218 nodes[1].set_channel_signer_available(&nodes[0].node.get_our_node_id(), &temporary_channel_id, false);
219 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
220 check_added_monitors(&nodes[1], 1);
222 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
224 // Now re-enable the signer and simulate a retry. The temporary_channel_id won't work anymore so
225 // we have to dig out the real channel ID.
227 let channels = nodes[0].node.list_channels();
228 assert_eq!(channels.len(), 1, "expected one channel, not {}", channels.len());
229 channels[0].channel_id
232 // At this point, we basically expect the channel to open like a normal zero-conf channel.
233 nodes[1].set_channel_signer_available(&nodes[0].node.get_our_node_id(), &chan_id, true);
234 nodes[1].node.signer_unblocked(Some((nodes[0].node.get_our_node_id(), chan_id)));
236 let (funding_signed, channel_ready_1) = {
237 let events = nodes[1].node.get_and_clear_pending_msg_events();
238 assert_eq!(events.len(), 2);
239 let funding_signed = match &events[0] {
240 MessageSendEvent::SendFundingSigned { msg, .. } => msg.clone(),
241 ev => panic!("Expected SendFundingSigned, not {:?}", ev)
243 let channel_ready = match &events[1] {
244 MessageSendEvent::SendChannelReady { msg, .. } => msg.clone(),
245 ev => panic!("Expected SendChannelReady, not {:?}", ev)
247 (funding_signed, channel_ready)
250 nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed);
251 expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
252 expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
253 check_added_monitors(&nodes[0], 1);
255 let channel_ready_0 = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReady, nodes[1].node.get_our_node_id());
257 nodes[0].node.handle_channel_ready(&nodes[1].node.get_our_node_id(), &channel_ready_1);
258 expect_channel_ready_event(&nodes[0], &nodes[1].node.get_our_node_id());
260 nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &channel_ready_0);
261 expect_channel_ready_event(&nodes[1], &nodes[0].node.get_our_node_id());
263 let channel_update_0 = get_event_msg!(nodes[0], MessageSendEvent::SendChannelUpdate, nodes[1].node.get_our_node_id());
264 let channel_update_1 = get_event_msg!(nodes[1], MessageSendEvent::SendChannelUpdate, nodes[0].node.get_our_node_id());
266 nodes[0].node.handle_channel_update(&nodes[1].node.get_our_node_id(), &channel_update_1);
267 nodes[1].node.handle_channel_update(&nodes[0].node.get_our_node_id(), &channel_update_0);
269 assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
270 assert_eq!(nodes[1].node.list_usable_channels().len(), 1);
274 fn test_async_commitment_signature_for_peer_disconnect() {
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 nodes = create_network(2, &node_cfgs, &node_chanmgrs);
279 let (_, _, chan_id, _) = create_announced_chan_between_nodes(&nodes, 0, 1);
284 let (route, our_payment_hash, _our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(src, dst, 8000000);
285 src.node.send_payment_with_route(&route, our_payment_hash,
286 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
287 check_added_monitors!(src, 1);
289 // Pass the payment along the route.
290 let payment_event = {
291 let mut events = src.node.get_and_clear_pending_msg_events();
292 assert_eq!(events.len(), 1);
293 SendEvent::from_event(events.remove(0))
295 assert_eq!(payment_event.node_id, dst.node.get_our_node_id());
296 assert_eq!(payment_event.msgs.len(), 1);
298 dst.node.handle_update_add_htlc(&src.node.get_our_node_id(), &payment_event.msgs[0]);
300 // Mark dst's signer as unavailable and handle src's commitment_signed: while dst won't yet have a
301 // `commitment_signed` of its own to offer, it should publish a `revoke_and_ack`.
302 dst.set_channel_signer_available(&src.node.get_our_node_id(), &chan_id, false);
303 dst.node.handle_commitment_signed(&src.node.get_our_node_id(), &payment_event.commitment_msg);
304 check_added_monitors(dst, 1);
306 get_event_msg!(dst, MessageSendEvent::SendRevokeAndACK, src.node.get_our_node_id());
308 // Now disconnect and reconnect the peers.
309 src.node.peer_disconnected(&dst.node.get_our_node_id());
310 dst.node.peer_disconnected(&src.node.get_our_node_id());
311 let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
312 reconnect_args.send_channel_ready = (false, false);
313 reconnect_args.pending_raa = (true, false);
314 reconnect_nodes(reconnect_args);
316 // Mark dst's signer as available and retry: we now expect to see dst's `commitment_signed`.
317 dst.set_channel_signer_available(&src.node.get_our_node_id(), &chan_id, true);
318 dst.node.signer_unblocked(Some((src.node.get_our_node_id(), chan_id)));
321 let events = dst.node.get_and_clear_pending_msg_events();
322 assert_eq!(events.len(), 1, "expected one message, got {}", events.len());
323 if let MessageSendEvent::UpdateHTLCs { ref node_id, .. } = events[0] {
324 assert_eq!(node_id, &src.node.get_our_node_id());
326 panic!("expected UpdateHTLCs message, not {:?}", events[0]);
331 fn do_test_async_holder_signatures(anchors: bool, remote_commitment: bool) {
332 // Ensures that we can obtain holder signatures for commitment and HTLC transactions
333 // asynchronously by allowing their retrieval to fail and retrying via
334 // `ChannelMonitor::signer_unblocked`.
335 let mut config = test_default_channel_config();
337 config.channel_handshake_config.negotiate_anchors_zero_fee_htlc_tx = true;
338 config.manually_accept_inbound_channels = true;
341 let chanmon_cfgs = create_chanmon_cfgs(2);
342 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
343 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(config), Some(config)]);
344 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
346 let closing_node = if remote_commitment { &nodes[1] } else { &nodes[0] };
347 let coinbase_tx = Transaction {
348 version: Version::TWO,
349 lock_time: LockTime::ZERO,
350 input: vec![TxIn { ..Default::default() }],
353 value: Amount::ONE_BTC,
354 script_pubkey: closing_node.wallet_source.get_change_script().unwrap(),
359 *nodes[0].fee_estimator.sat_per_kw.lock().unwrap() *= 2;
360 *nodes[1].fee_estimator.sat_per_kw.lock().unwrap() *= 2;
361 closing_node.wallet_source.add_utxo(bitcoin::OutPoint { txid: coinbase_tx.txid(), vout: 0 }, coinbase_tx.output[0].value);
364 // Route an HTLC and set the signer as unavailable.
365 let (_, _, chan_id, funding_tx) = create_announced_chan_between_nodes(&nodes, 0, 1);
366 route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
367 let error_message = "Channel force-closed";
369 nodes[0].set_channel_signer_available(&nodes[1].node.get_our_node_id(), &chan_id, false);
371 if remote_commitment {
372 // Make the counterparty broadcast its latest commitment.
373 nodes[1].node.force_close_broadcasting_latest_txn(&chan_id, &nodes[0].node.get_our_node_id(), error_message.to_string()).unwrap();
374 check_added_monitors(&nodes[1], 1);
375 check_closed_broadcast(&nodes[1], 1, true);
376 check_closed_event(&nodes[1], 1, ClosureReason::HolderForceClosed { broadcasted_latest_txn: Some(true) }, false, &[nodes[0].node.get_our_node_id()], 100_000);
378 // We'll connect blocks until the sender has to go onchain to time out the HTLC.
379 connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
381 // No transaction should be broadcast since the signer is not available yet.
382 assert!(nodes[0].tx_broadcaster.txn_broadcast().is_empty());
383 assert!(nodes[0].chain_monitor.chain_monitor.get_and_clear_pending_events().is_empty());
385 // Mark it as available now, we should see the signed commitment transaction.
386 nodes[0].set_channel_signer_available(&nodes[1].node.get_our_node_id(), &chan_id, true);
387 get_monitor!(nodes[0], chan_id).signer_unblocked(nodes[0].tx_broadcaster, nodes[0].fee_estimator, &nodes[0].logger);
390 let commitment_tx = {
391 let mut txn = closing_node.tx_broadcaster.txn_broadcast();
392 if anchors || remote_commitment {
393 assert_eq!(txn.len(), 1);
394 check_spends!(txn[0], funding_tx);
397 assert_eq!(txn.len(), 2);
398 if txn[0].input[0].previous_output.txid == funding_tx.txid() {
399 check_spends!(txn[0], funding_tx);
400 check_spends!(txn[1], txn[0]);
403 check_spends!(txn[1], funding_tx);
404 check_spends!(txn[0], txn[1]);
410 // Mark it as unavailable again to now test the HTLC transaction. We'll mine the commitment such
411 // that the HTLC transaction is retried.
412 nodes[0].set_channel_signer_available(&nodes[1].node.get_our_node_id(), &chan_id, false);
413 mine_transaction(&nodes[0], &commitment_tx);
415 check_added_monitors(&nodes[0], 1);
416 check_closed_broadcast(&nodes[0], 1, true);
417 check_closed_event(&nodes[0], 1, ClosureReason::CommitmentTxConfirmed, false, &[nodes[1].node.get_our_node_id()], 100_000);
419 // If the counterparty broadcast its latest commitment, we need to mine enough blocks for the
421 if remote_commitment {
422 connect_blocks(&nodes[0], TEST_FINAL_CLTV);
425 // No HTLC transaction should be broadcast as the signer is not available yet.
426 if anchors && !remote_commitment {
427 handle_bump_htlc_event(&nodes[0], 1);
429 assert!(nodes[0].tx_broadcaster.txn_broadcast().is_empty());
431 // Mark it as available now, we should see the signed HTLC transaction.
432 nodes[0].set_channel_signer_available(&nodes[1].node.get_our_node_id(), &chan_id, true);
433 get_monitor!(nodes[0], chan_id).signer_unblocked(nodes[0].tx_broadcaster, nodes[0].fee_estimator, &nodes[0].logger);
435 if anchors && !remote_commitment {
436 handle_bump_htlc_event(&nodes[0], 1);
439 let txn = nodes[0].tx_broadcaster.txn_broadcast();
440 assert_eq!(txn.len(), 1);
441 check_spends!(txn[0], commitment_tx, coinbase_tx);
446 fn test_async_holder_signatures() {
447 do_test_async_holder_signatures(false, false);
448 do_test_async_holder_signatures(false, true);
449 do_test_async_holder_signatures(true, false);
450 do_test_async_holder_signatures(true, true);