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;
16 use crate::chain::channelmonitor::LATENCY_GRACE_PERIOD_BLOCKS;
17 use crate::events::bump_transaction::WalletSource;
18 use crate::events::{Event, MessageSendEvent, MessageSendEventsProvider, ClosureReason};
19 use crate::ln::functional_test_utils::*;
20 use crate::ln::msgs::ChannelMessageHandler;
21 use crate::ln::channelmanager::{PaymentId, RecipientOnionFields};
24 fn test_async_commitment_signature_for_funding_created() {
25 // Simulate acquiring the signature for `funding_created` asynchronously.
26 let chanmon_cfgs = create_chanmon_cfgs(2);
27 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
28 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
29 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
31 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None, None).unwrap();
33 // nodes[0] --- open_channel --> nodes[1]
34 let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
35 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
37 // nodes[0] <-- accept_channel --- nodes[1]
38 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()));
40 // nodes[0] --- funding_created --> nodes[1]
42 // But! Let's make node[0]'s signer be unavailable: we should *not* broadcast a funding_created
44 let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
45 nodes[0].set_channel_signer_available(&nodes[1].node.get_our_node_id(), &temporary_channel_id, false);
46 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
47 check_added_monitors(&nodes[0], 0);
49 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
51 // Now re-enable the signer and simulate a retry. The temporary_channel_id won't work anymore so
52 // we have to dig out the real channel ID.
54 let channels = nodes[0].node.list_channels();
55 assert_eq!(channels.len(), 1, "expected one channel, not {}", channels.len());
56 channels[0].channel_id
59 nodes[0].set_channel_signer_available(&nodes[1].node.get_our_node_id(), &chan_id, true);
60 nodes[0].node.signer_unblocked(Some((nodes[1].node.get_our_node_id(), chan_id)));
62 let mut funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
63 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
64 check_added_monitors(&nodes[1], 1);
65 expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
67 // nodes[0] <-- funding_signed --- nodes[1]
68 let funding_signed_msg = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
69 nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed_msg);
70 check_added_monitors(&nodes[0], 1);
71 expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
75 fn test_async_commitment_signature_for_funding_signed() {
76 // Simulate acquiring the signature for `funding_signed` asynchronously.
77 let chanmon_cfgs = create_chanmon_cfgs(2);
78 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
79 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
80 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
82 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None, None).unwrap();
84 // nodes[0] --- open_channel --> nodes[1]
85 let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
86 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
88 // nodes[0] <-- accept_channel --- nodes[1]
89 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()));
91 // nodes[0] --- funding_created --> nodes[1]
92 let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
93 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
94 check_added_monitors(&nodes[0], 0);
96 let mut funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
98 // Now let's make node[1]'s signer be unavailable while handling the `funding_created`. It should
99 // *not* broadcast a `funding_signed`...
100 nodes[1].set_channel_signer_available(&nodes[0].node.get_our_node_id(), &temporary_channel_id, false);
101 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
102 check_added_monitors(&nodes[1], 1);
104 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
106 // Now re-enable the signer and simulate a retry. The temporary_channel_id won't work anymore so
107 // we have to dig out the real channel ID.
109 let channels = nodes[0].node.list_channels();
110 assert_eq!(channels.len(), 1, "expected one channel, not {}", channels.len());
111 channels[0].channel_id
113 nodes[1].set_channel_signer_available(&nodes[0].node.get_our_node_id(), &chan_id, true);
114 nodes[1].node.signer_unblocked(Some((nodes[0].node.get_our_node_id(), chan_id)));
116 expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
118 // nodes[0] <-- funding_signed --- nodes[1]
119 let funding_signed_msg = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
120 nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed_msg);
121 check_added_monitors(&nodes[0], 1);
122 expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
126 fn test_async_commitment_signature_for_commitment_signed() {
127 let chanmon_cfgs = create_chanmon_cfgs(2);
128 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
129 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
130 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
131 let (_, _, chan_id, _) = create_announced_chan_between_nodes(&nodes, 0, 1);
136 let (route, our_payment_hash, _our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(src, dst, 8000000);
137 src.node.send_payment_with_route(&route, our_payment_hash,
138 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
139 check_added_monitors!(src, 1);
141 // Pass the payment along the route.
142 let payment_event = {
143 let mut events = src.node.get_and_clear_pending_msg_events();
144 assert_eq!(events.len(), 1);
145 SendEvent::from_event(events.remove(0))
147 assert_eq!(payment_event.node_id, dst.node.get_our_node_id());
148 assert_eq!(payment_event.msgs.len(), 1);
150 dst.node.handle_update_add_htlc(&src.node.get_our_node_id(), &payment_event.msgs[0]);
152 // Mark dst's signer as unavailable and handle src's commitment_signed: while dst won't yet have a
153 // `commitment_signed` of its own to offer, it should publish a `revoke_and_ack`.
154 dst.set_channel_signer_available(&src.node.get_our_node_id(), &chan_id, false);
155 dst.node.handle_commitment_signed(&src.node.get_our_node_id(), &payment_event.commitment_msg);
156 check_added_monitors(dst, 1);
158 get_event_msg!(dst, MessageSendEvent::SendRevokeAndACK, src.node.get_our_node_id());
160 // Mark dst's signer as available and retry: we now expect to see dst's `commitment_signed`.
161 dst.set_channel_signer_available(&src.node.get_our_node_id(), &chan_id, true);
162 dst.node.signer_unblocked(Some((src.node.get_our_node_id(), chan_id)));
164 let events = dst.node.get_and_clear_pending_msg_events();
165 assert_eq!(events.len(), 1, "expected one message, got {}", events.len());
166 if let MessageSendEvent::UpdateHTLCs { ref node_id, .. } = events[0] {
167 assert_eq!(node_id, &src.node.get_our_node_id());
169 panic!("expected UpdateHTLCs message, not {:?}", events[0]);
174 fn test_async_commitment_signature_for_funding_signed_0conf() {
175 // Simulate acquiring the signature for `funding_signed` asynchronously for a zero-conf channel.
176 let mut manually_accept_config = test_default_channel_config();
177 manually_accept_config.manually_accept_inbound_channels = true;
179 let chanmon_cfgs = create_chanmon_cfgs(2);
180 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
181 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_config)]);
182 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
184 // nodes[0] --- open_channel --> nodes[1]
185 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None, None).unwrap();
186 let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
188 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel);
191 let events = nodes[1].node.get_and_clear_pending_events();
192 assert_eq!(events.len(), 1, "Expected one event, got {}", events.len());
194 Event::OpenChannelRequest { temporary_channel_id, .. } => {
195 nodes[1].node.accept_inbound_channel_from_trusted_peer_0conf(
196 temporary_channel_id, &nodes[0].node.get_our_node_id(), 0)
197 .expect("Unable to accept inbound zero-conf channel");
199 ev => panic!("Expected OpenChannelRequest, not {:?}", ev)
203 // nodes[0] <-- accept_channel --- nodes[1]
204 let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
205 assert_eq!(accept_channel.common_fields.minimum_depth, 0, "Expected minimum depth of 0");
206 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
208 // nodes[0] --- funding_created --> nodes[1]
209 let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
210 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
211 check_added_monitors(&nodes[0], 0);
213 let mut funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
215 // Now let's make node[1]'s signer be unavailable while handling the `funding_created`. It should
216 // *not* broadcast a `funding_signed`...
217 nodes[1].set_channel_signer_available(&nodes[0].node.get_our_node_id(), &temporary_channel_id, false);
218 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
219 check_added_monitors(&nodes[1], 1);
221 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
223 // Now re-enable the signer and simulate a retry. The temporary_channel_id won't work anymore so
224 // we have to dig out the real channel ID.
226 let channels = nodes[0].node.list_channels();
227 assert_eq!(channels.len(), 1, "expected one channel, not {}", channels.len());
228 channels[0].channel_id
231 // At this point, we basically expect the channel to open like a normal zero-conf channel.
232 nodes[1].set_channel_signer_available(&nodes[0].node.get_our_node_id(), &chan_id, true);
233 nodes[1].node.signer_unblocked(Some((nodes[0].node.get_our_node_id(), chan_id)));
235 let (funding_signed, channel_ready_1) = {
236 let events = nodes[1].node.get_and_clear_pending_msg_events();
237 assert_eq!(events.len(), 2);
238 let funding_signed = match &events[0] {
239 MessageSendEvent::SendFundingSigned { msg, .. } => msg.clone(),
240 ev => panic!("Expected SendFundingSigned, not {:?}", ev)
242 let channel_ready = match &events[1] {
243 MessageSendEvent::SendChannelReady { msg, .. } => msg.clone(),
244 ev => panic!("Expected SendChannelReady, not {:?}", ev)
246 (funding_signed, channel_ready)
249 nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed);
250 expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
251 expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
252 check_added_monitors(&nodes[0], 1);
254 let channel_ready_0 = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReady, nodes[1].node.get_our_node_id());
256 nodes[0].node.handle_channel_ready(&nodes[1].node.get_our_node_id(), &channel_ready_1);
257 expect_channel_ready_event(&nodes[0], &nodes[1].node.get_our_node_id());
259 nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &channel_ready_0);
260 expect_channel_ready_event(&nodes[1], &nodes[0].node.get_our_node_id());
262 let channel_update_0 = get_event_msg!(nodes[0], MessageSendEvent::SendChannelUpdate, nodes[1].node.get_our_node_id());
263 let channel_update_1 = get_event_msg!(nodes[1], MessageSendEvent::SendChannelUpdate, nodes[0].node.get_our_node_id());
265 nodes[0].node.handle_channel_update(&nodes[1].node.get_our_node_id(), &channel_update_1);
266 nodes[1].node.handle_channel_update(&nodes[0].node.get_our_node_id(), &channel_update_0);
268 assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
269 assert_eq!(nodes[1].node.list_usable_channels().len(), 1);
273 fn test_async_commitment_signature_for_peer_disconnect() {
274 let chanmon_cfgs = create_chanmon_cfgs(2);
275 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
276 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
277 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
278 let (_, _, chan_id, _) = create_announced_chan_between_nodes(&nodes, 0, 1);
283 let (route, our_payment_hash, _our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(src, dst, 8000000);
284 src.node.send_payment_with_route(&route, our_payment_hash,
285 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
286 check_added_monitors!(src, 1);
288 // Pass the payment along the route.
289 let payment_event = {
290 let mut events = src.node.get_and_clear_pending_msg_events();
291 assert_eq!(events.len(), 1);
292 SendEvent::from_event(events.remove(0))
294 assert_eq!(payment_event.node_id, dst.node.get_our_node_id());
295 assert_eq!(payment_event.msgs.len(), 1);
297 dst.node.handle_update_add_htlc(&src.node.get_our_node_id(), &payment_event.msgs[0]);
299 // Mark dst's signer as unavailable and handle src's commitment_signed: while dst won't yet have a
300 // `commitment_signed` of its own to offer, it should publish a `revoke_and_ack`.
301 dst.set_channel_signer_available(&src.node.get_our_node_id(), &chan_id, false);
302 dst.node.handle_commitment_signed(&src.node.get_our_node_id(), &payment_event.commitment_msg);
303 check_added_monitors(dst, 1);
305 get_event_msg!(dst, MessageSendEvent::SendRevokeAndACK, src.node.get_our_node_id());
307 // Now disconnect and reconnect the peers.
308 src.node.peer_disconnected(&dst.node.get_our_node_id());
309 dst.node.peer_disconnected(&src.node.get_our_node_id());
310 let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
311 reconnect_args.send_channel_ready = (false, false);
312 reconnect_args.pending_raa = (true, false);
313 reconnect_nodes(reconnect_args);
315 // Mark dst's signer as available and retry: we now expect to see dst's `commitment_signed`.
316 dst.set_channel_signer_available(&src.node.get_our_node_id(), &chan_id, true);
317 dst.node.signer_unblocked(Some((src.node.get_our_node_id(), chan_id)));
320 let events = dst.node.get_and_clear_pending_msg_events();
321 assert_eq!(events.len(), 1, "expected one message, got {}", events.len());
322 if let MessageSendEvent::UpdateHTLCs { ref node_id, .. } = events[0] {
323 assert_eq!(node_id, &src.node.get_our_node_id());
325 panic!("expected UpdateHTLCs message, not {:?}", events[0]);
330 fn do_test_async_holder_signatures(anchors: bool, remote_commitment: bool) {
331 // Ensures that we can obtain holder signatures for commitment and HTLC transactions
332 // asynchronously by allowing their retrieval to fail and retrying via
333 // `ChannelMonitor::signer_unblocked`.
334 let mut config = test_default_channel_config();
336 config.channel_handshake_config.negotiate_anchors_zero_fee_htlc_tx = true;
337 config.manually_accept_inbound_channels = true;
340 let chanmon_cfgs = create_chanmon_cfgs(2);
341 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
342 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(config), Some(config)]);
343 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
345 let closing_node = if remote_commitment { &nodes[1] } else { &nodes[0] };
346 let coinbase_tx = Transaction {
348 lock_time: LockTime::ZERO,
349 input: vec![TxIn { ..Default::default() }],
352 value: Amount::ONE_BTC.to_sat(),
353 script_pubkey: closing_node.wallet_source.get_change_script().unwrap(),
358 *nodes[0].fee_estimator.sat_per_kw.lock().unwrap() *= 2;
359 *nodes[1].fee_estimator.sat_per_kw.lock().unwrap() *= 2;
360 closing_node.wallet_source.add_utxo(bitcoin::OutPoint { txid: coinbase_tx.txid(), vout: 0 }, coinbase_tx.output[0].value);
363 // Route an HTLC and set the signer as unavailable.
364 let (_, _, chan_id, funding_tx) = create_announced_chan_between_nodes(&nodes, 0, 1);
365 route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
367 nodes[0].set_channel_signer_available(&nodes[1].node.get_our_node_id(), &chan_id, false);
369 if remote_commitment {
370 // Make the counterparty broadcast its latest commitment.
371 nodes[1].node.force_close_broadcasting_latest_txn(&chan_id, &nodes[0].node.get_our_node_id()).unwrap();
372 check_added_monitors(&nodes[1], 1);
373 check_closed_broadcast(&nodes[1], 1, true);
374 check_closed_event(&nodes[1], 1, ClosureReason::HolderForceClosed, false, &[nodes[0].node.get_our_node_id()], 100_000);
376 // We'll connect blocks until the sender has to go onchain to time out the HTLC.
377 connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
379 // No transaction should be broadcast since the signer is not available yet.
380 assert!(nodes[0].tx_broadcaster.txn_broadcast().is_empty());
381 assert!(nodes[0].chain_monitor.chain_monitor.get_and_clear_pending_events().is_empty());
383 // Mark it as available now, we should see the signed commitment transaction.
384 nodes[0].set_channel_signer_available(&nodes[1].node.get_our_node_id(), &chan_id, true);
385 get_monitor!(nodes[0], chan_id).signer_unblocked(nodes[0].tx_broadcaster, nodes[0].fee_estimator, &nodes[0].logger);
388 let commitment_tx = {
389 let mut txn = closing_node.tx_broadcaster.txn_broadcast();
390 if anchors || remote_commitment {
391 assert_eq!(txn.len(), 1);
392 check_spends!(txn[0], funding_tx);
395 assert_eq!(txn.len(), 2);
396 if txn[0].input[0].previous_output.txid == funding_tx.txid() {
397 check_spends!(txn[0], funding_tx);
398 check_spends!(txn[1], txn[0]);
401 check_spends!(txn[1], funding_tx);
402 check_spends!(txn[0], txn[1]);
408 // Mark it as unavailable again to now test the HTLC transaction. We'll mine the commitment such
409 // that the HTLC transaction is retried.
410 nodes[0].set_channel_signer_available(&nodes[1].node.get_our_node_id(), &chan_id, false);
411 mine_transaction(&nodes[0], &commitment_tx);
413 check_added_monitors(&nodes[0], 1);
414 check_closed_broadcast(&nodes[0], 1, true);
415 check_closed_event(&nodes[0], 1, ClosureReason::CommitmentTxConfirmed, false, &[nodes[1].node.get_our_node_id()], 100_000);
417 // If the counterparty broadcast its latest commitment, we need to mine enough blocks for the
419 if remote_commitment {
420 connect_blocks(&nodes[0], TEST_FINAL_CLTV);
423 // No HTLC transaction should be broadcast as the signer is not available yet.
424 if anchors && !remote_commitment {
425 handle_bump_htlc_event(&nodes[0], 1);
427 assert!(nodes[0].tx_broadcaster.txn_broadcast().is_empty());
429 // Mark it as available now, we should see the signed HTLC transaction.
430 nodes[0].set_channel_signer_available(&nodes[1].node.get_our_node_id(), &chan_id, true);
431 get_monitor!(nodes[0], chan_id).signer_unblocked(nodes[0].tx_broadcaster, nodes[0].fee_estimator, &nodes[0].logger);
433 if anchors && !remote_commitment {
434 handle_bump_htlc_event(&nodes[0], 1);
437 let txn = nodes[0].tx_broadcaster.txn_broadcast();
438 assert_eq!(txn.len(), 1);
439 check_spends!(txn[0], commitment_tx, coinbase_tx);
444 fn test_async_holder_signatures() {
445 do_test_async_holder_signatures(false, false);
446 do_test_async_holder_signatures(false, true);
447 do_test_async_holder_signatures(true, false);
448 do_test_async_holder_signatures(true, true);