From: Chris Waterson Date: Wed, 6 Sep 2023 18:38:34 +0000 (-0700) Subject: Add basic async signer tests X-Git-Tag: v0.0.119~65^2 X-Git-Url: http://git.bitcoin.ninja/?a=commitdiff_plain;h=014a336e592bfc8cb49929b799b9d6d9286dab16;p=rust-lightning Add basic async signer tests Adds a `get_signer` method to the context so that a test can get ahold of the channel signer. Adds a `set_available` method on the `TestChannelSigner` to allow a test to enable and disable the signer: when disabled some of the signer's methods will return `Err` which will typically activate the error handling case. Adds a `set_channel_signer_available` function on the test `Node` class to make it easy to enable and disable a specific signer. Adds a new `async_signer_tests` module: * Check for asynchronous handling of `funding_created` and `funding_signed`. * Check that we correctly resume processing after awaiting an asynchronous signature for a `commitment_signed` event. * Verify correct handling during peer disconnect. * Verify correct handling for inbound zero-conf. --- diff --git a/fuzz/src/chanmon_consistency.rs b/fuzz/src/chanmon_consistency.rs index dddd97cae..ea0b78dc8 100644 --- a/fuzz/src/chanmon_consistency.rs +++ b/fuzz/src/chanmon_consistency.rs @@ -267,6 +267,7 @@ impl SignerProvider for KeyProvider { inner, state, disable_revocation_policy_check: false, + available: Arc::new(Mutex::new(true)), }) } diff --git a/lightning/src/ln/async_signer_tests.rs b/lightning/src/ln/async_signer_tests.rs new file mode 100644 index 000000000..a82fd2e42 --- /dev/null +++ b/lightning/src/ln/async_signer_tests.rs @@ -0,0 +1,323 @@ +// This file is Copyright its original authors, visible in version control +// history. +// +// This file is licensed under the Apache License, Version 2.0 or the MIT license +// , at your option. +// You may not use this file except in accordance with one or both of these +// licenses. + +//! Tests for asynchronous signing. These tests verify that the channel state machine behaves +//! properly with a signer implementation that asynchronously derives signatures. + +use crate::events::{Event, MessageSendEvent, MessageSendEventsProvider}; +use crate::ln::functional_test_utils::*; +use crate::ln::msgs::ChannelMessageHandler; +use crate::ln::channelmanager::{PaymentId, RecipientOnionFields}; + +#[test] +fn test_async_commitment_signature_for_funding_created() { + // Simulate acquiring the signature for `funding_created` asynchronously. + let chanmon_cfgs = create_chanmon_cfgs(2); + let node_cfgs = create_node_cfgs(2, &chanmon_cfgs); + let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]); + let nodes = create_network(2, &node_cfgs, &node_chanmgrs); + + nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap(); + + // nodes[0] --- open_channel --> nodes[1] + let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id()); + nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg); + + // nodes[0] <-- accept_channel --- nodes[1] + 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())); + + // nodes[0] --- funding_created --> nodes[1] + // + // But! Let's make node[0]'s signer be unavailable: we should *not* broadcast a funding_created + // message... + let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42); + nodes[0].set_channel_signer_available(&nodes[1].node.get_our_node_id(), &temporary_channel_id, false); + nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap(); + check_added_monitors(&nodes[0], 0); + + assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty()); + + // Now re-enable the signer and simulate a retry. The temporary_channel_id won't work anymore so + // we have to dig out the real channel ID. + let chan_id = { + let channels = nodes[0].node.list_channels(); + assert_eq!(channels.len(), 1, "expected one channel, not {}", channels.len()); + channels[0].channel_id + }; + + nodes[0].set_channel_signer_available(&nodes[1].node.get_our_node_id(), &chan_id, true); + nodes[0].node.signer_unblocked(Some((nodes[1].node.get_our_node_id(), chan_id))); + + let mut funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id()); + nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg); + check_added_monitors(&nodes[1], 1); + expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id()); + + // nodes[0] <-- funding_signed --- nodes[1] + let funding_signed_msg = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id()); + nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed_msg); + check_added_monitors(&nodes[0], 1); + expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id()); +} + +#[test] +fn test_async_commitment_signature_for_funding_signed() { + // Simulate acquiring the signature for `funding_signed` asynchronously. + let chanmon_cfgs = create_chanmon_cfgs(2); + let node_cfgs = create_node_cfgs(2, &chanmon_cfgs); + let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]); + let nodes = create_network(2, &node_cfgs, &node_chanmgrs); + + nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap(); + + // nodes[0] --- open_channel --> nodes[1] + let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id()); + nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg); + + // nodes[0] <-- accept_channel --- nodes[1] + 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())); + + // nodes[0] --- funding_created --> nodes[1] + let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42); + nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap(); + check_added_monitors(&nodes[0], 0); + + let mut funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id()); + + // Now let's make node[1]'s signer be unavailable while handling the `funding_created`. It should + // *not* broadcast a `funding_signed`... + nodes[1].set_channel_signer_available(&nodes[0].node.get_our_node_id(), &temporary_channel_id, false); + nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg); + check_added_monitors(&nodes[1], 1); + + assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty()); + + // Now re-enable the signer and simulate a retry. The temporary_channel_id won't work anymore so + // we have to dig out the real channel ID. + let chan_id = { + let channels = nodes[0].node.list_channels(); + assert_eq!(channels.len(), 1, "expected one channel, not {}", channels.len()); + channels[0].channel_id + }; + nodes[1].set_channel_signer_available(&nodes[0].node.get_our_node_id(), &chan_id, true); + nodes[1].node.signer_unblocked(Some((nodes[0].node.get_our_node_id(), chan_id))); + + expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id()); + + // nodes[0] <-- funding_signed --- nodes[1] + let funding_signed_msg = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id()); + nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed_msg); + check_added_monitors(&nodes[0], 1); + expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id()); +} + +#[test] +fn test_async_commitment_signature_for_commitment_signed() { + let chanmon_cfgs = create_chanmon_cfgs(2); + let node_cfgs = create_node_cfgs(2, &chanmon_cfgs); + let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]); + let nodes = create_network(2, &node_cfgs, &node_chanmgrs); + let (_, _, chan_id, _) = create_announced_chan_between_nodes(&nodes, 0, 1); + + // Send a payment. + let src = &nodes[0]; + let dst = &nodes[1]; + let (route, our_payment_hash, _our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(src, dst, 8000000); + src.node.send_payment_with_route(&route, our_payment_hash, + RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap(); + check_added_monitors!(src, 1); + + // Pass the payment along the route. + let payment_event = { + let mut events = src.node.get_and_clear_pending_msg_events(); + assert_eq!(events.len(), 1); + SendEvent::from_event(events.remove(0)) + }; + assert_eq!(payment_event.node_id, dst.node.get_our_node_id()); + assert_eq!(payment_event.msgs.len(), 1); + + dst.node.handle_update_add_htlc(&src.node.get_our_node_id(), &payment_event.msgs[0]); + + // Mark dst's signer as unavailable and handle src's commitment_signed: while dst won't yet have a + // `commitment_signed` of its own to offer, it should publish a `revoke_and_ack`. + dst.set_channel_signer_available(&src.node.get_our_node_id(), &chan_id, false); + dst.node.handle_commitment_signed(&src.node.get_our_node_id(), &payment_event.commitment_msg); + check_added_monitors(dst, 1); + + get_event_msg!(dst, MessageSendEvent::SendRevokeAndACK, src.node.get_our_node_id()); + + // Mark dst's signer as available and retry: we now expect to see dst's `commitment_signed`. + dst.set_channel_signer_available(&src.node.get_our_node_id(), &chan_id, true); + dst.node.signer_unblocked(Some((src.node.get_our_node_id(), chan_id))); + + let events = dst.node.get_and_clear_pending_msg_events(); + assert_eq!(events.len(), 1, "expected one message, got {}", events.len()); + if let MessageSendEvent::UpdateHTLCs { ref node_id, .. } = events[0] { + assert_eq!(node_id, &src.node.get_our_node_id()); + } else { + panic!("expected UpdateHTLCs message, not {:?}", events[0]); + }; +} + +#[test] +fn test_async_commitment_signature_for_funding_signed_0conf() { + // Simulate acquiring the signature for `funding_signed` asynchronously for a zero-conf channel. + let mut manually_accept_config = test_default_channel_config(); + manually_accept_config.manually_accept_inbound_channels = true; + + let chanmon_cfgs = create_chanmon_cfgs(2); + let node_cfgs = create_node_cfgs(2, &chanmon_cfgs); + let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_config)]); + let nodes = create_network(2, &node_cfgs, &node_chanmgrs); + + // nodes[0] --- open_channel --> nodes[1] + nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap(); + let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id()); + + nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel); + + { + let events = nodes[1].node.get_and_clear_pending_events(); + assert_eq!(events.len(), 1, "Expected one event, got {}", events.len()); + match &events[0] { + Event::OpenChannelRequest { temporary_channel_id, .. } => { + nodes[1].node.accept_inbound_channel_from_trusted_peer_0conf( + temporary_channel_id, &nodes[0].node.get_our_node_id(), 0) + .expect("Unable to accept inbound zero-conf channel"); + }, + ev => panic!("Expected OpenChannelRequest, not {:?}", ev) + } + } + + // nodes[0] <-- accept_channel --- nodes[1] + let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id()); + assert_eq!(accept_channel.minimum_depth, 0, "Expected minimum depth of 0"); + nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel); + + // nodes[0] --- funding_created --> nodes[1] + let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42); + nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap(); + check_added_monitors(&nodes[0], 0); + + let mut funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id()); + + // Now let's make node[1]'s signer be unavailable while handling the `funding_created`. It should + // *not* broadcast a `funding_signed`... + nodes[1].set_channel_signer_available(&nodes[0].node.get_our_node_id(), &temporary_channel_id, false); + nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg); + check_added_monitors(&nodes[1], 1); + + assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty()); + + // Now re-enable the signer and simulate a retry. The temporary_channel_id won't work anymore so + // we have to dig out the real channel ID. + let chan_id = { + let channels = nodes[0].node.list_channels(); + assert_eq!(channels.len(), 1, "expected one channel, not {}", channels.len()); + channels[0].channel_id + }; + + // At this point, we basically expect the channel to open like a normal zero-conf channel. + nodes[1].set_channel_signer_available(&nodes[0].node.get_our_node_id(), &chan_id, true); + nodes[1].node.signer_unblocked(Some((nodes[0].node.get_our_node_id(), chan_id))); + + let (funding_signed, channel_ready_1) = { + let events = nodes[1].node.get_and_clear_pending_msg_events(); + assert_eq!(events.len(), 2); + let funding_signed = match &events[0] { + MessageSendEvent::SendFundingSigned { msg, .. } => msg.clone(), + ev => panic!("Expected SendFundingSigned, not {:?}", ev) + }; + let channel_ready = match &events[1] { + MessageSendEvent::SendChannelReady { msg, .. } => msg.clone(), + ev => panic!("Expected SendChannelReady, not {:?}", ev) + }; + (funding_signed, channel_ready) + }; + + nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed); + expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id()); + expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id()); + check_added_monitors(&nodes[0], 1); + + let channel_ready_0 = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReady, nodes[1].node.get_our_node_id()); + + nodes[0].node.handle_channel_ready(&nodes[1].node.get_our_node_id(), &channel_ready_1); + expect_channel_ready_event(&nodes[0], &nodes[1].node.get_our_node_id()); + + nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &channel_ready_0); + expect_channel_ready_event(&nodes[1], &nodes[0].node.get_our_node_id()); + + let channel_update_0 = get_event_msg!(nodes[0], MessageSendEvent::SendChannelUpdate, nodes[1].node.get_our_node_id()); + let channel_update_1 = get_event_msg!(nodes[1], MessageSendEvent::SendChannelUpdate, nodes[0].node.get_our_node_id()); + + nodes[0].node.handle_channel_update(&nodes[1].node.get_our_node_id(), &channel_update_1); + nodes[1].node.handle_channel_update(&nodes[0].node.get_our_node_id(), &channel_update_0); + + assert_eq!(nodes[0].node.list_usable_channels().len(), 1); + assert_eq!(nodes[1].node.list_usable_channels().len(), 1); +} + +#[test] +fn test_async_commitment_signature_for_peer_disconnect() { + let chanmon_cfgs = create_chanmon_cfgs(2); + let node_cfgs = create_node_cfgs(2, &chanmon_cfgs); + let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]); + let nodes = create_network(2, &node_cfgs, &node_chanmgrs); + let (_, _, chan_id, _) = create_announced_chan_between_nodes(&nodes, 0, 1); + + // Send a payment. + let src = &nodes[0]; + let dst = &nodes[1]; + let (route, our_payment_hash, _our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(src, dst, 8000000); + src.node.send_payment_with_route(&route, our_payment_hash, + RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap(); + check_added_monitors!(src, 1); + + // Pass the payment along the route. + let payment_event = { + let mut events = src.node.get_and_clear_pending_msg_events(); + assert_eq!(events.len(), 1); + SendEvent::from_event(events.remove(0)) + }; + assert_eq!(payment_event.node_id, dst.node.get_our_node_id()); + assert_eq!(payment_event.msgs.len(), 1); + + dst.node.handle_update_add_htlc(&src.node.get_our_node_id(), &payment_event.msgs[0]); + + // Mark dst's signer as unavailable and handle src's commitment_signed: while dst won't yet have a + // `commitment_signed` of its own to offer, it should publish a `revoke_and_ack`. + dst.set_channel_signer_available(&src.node.get_our_node_id(), &chan_id, false); + dst.node.handle_commitment_signed(&src.node.get_our_node_id(), &payment_event.commitment_msg); + check_added_monitors(dst, 1); + + get_event_msg!(dst, MessageSendEvent::SendRevokeAndACK, src.node.get_our_node_id()); + + // Now disconnect and reconnect the peers. + src.node.peer_disconnected(&dst.node.get_our_node_id()); + dst.node.peer_disconnected(&src.node.get_our_node_id()); + let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]); + reconnect_args.send_channel_ready = (false, false); + reconnect_args.pending_raa = (true, false); + reconnect_nodes(reconnect_args); + + // Mark dst's signer as available and retry: we now expect to see dst's `commitment_signed`. + dst.set_channel_signer_available(&src.node.get_our_node_id(), &chan_id, true); + dst.node.signer_unblocked(Some((src.node.get_our_node_id(), chan_id))); + + { + let events = dst.node.get_and_clear_pending_msg_events(); + assert_eq!(events.len(), 1, "expected one message, got {}", events.len()); + if let MessageSendEvent::UpdateHTLCs { ref node_id, .. } = events[0] { + assert_eq!(node_id, &src.node.get_our_node_id()); + } else { + panic!("expected UpdateHTLCs message, not {:?}", events[0]); + }; + } +} diff --git a/lightning/src/ln/channel.rs b/lightning/src/ln/channel.rs index 0ca39c955..52db68c13 100644 --- a/lightning/src/ln/channel.rs +++ b/lightning/src/ln/channel.rs @@ -1077,6 +1077,12 @@ impl ChannelContext where SP::Target: SignerProvider { self.outbound_scid_alias } + /// Returns the holder signer for this channel. + #[cfg(test)] + pub fn get_signer(&self) -> &ChannelSignerType<::Signer> { + return &self.holder_signer + } + /// Only allowed immediately after deserialization if get_outbound_scid_alias returns 0, /// indicating we were written by LDK prior to 0.0.106 which did not set outbound SCID aliases /// or prior to any channel actions during `Channel` initialization. @@ -2165,7 +2171,6 @@ impl ChannelContext where SP::Target: SignerProvider { } } } - } // Internal utility functions for channels diff --git a/lightning/src/ln/functional_test_utils.rs b/lightning/src/ln/functional_test_utils.rs index 8f9c206f1..c09c1cbb0 100644 --- a/lightning/src/ln/functional_test_utils.rs +++ b/lightning/src/ln/functional_test_utils.rs @@ -30,6 +30,8 @@ use crate::util::test_utils::{panicking, TestChainMonitor, TestScorer, TestKeysI use crate::util::errors::APIError; use crate::util::config::{UserConfig, MaxDustHTLCExposure}; use crate::util::ser::{ReadableArgs, Writeable}; +#[cfg(test)] +use crate::util::logger::Logger; use bitcoin::blockdata::block::{Block, BlockHeader}; use bitcoin::blockdata::transaction::{Transaction, TxOut}; @@ -436,6 +438,25 @@ impl<'a, 'b, 'c> Node<'a, 'b, 'c> { pub fn get_block_header(&self, height: u32) -> BlockHeader { self.blocks.lock().unwrap()[height as usize].0.header } + /// Changes the channel signer's availability for the specified peer and channel. + /// + /// When `available` is set to `true`, the channel signer will behave normally. When set to + /// `false`, the channel signer will act like an off-line remote signer and will return `Err` for + /// several of the signing methods. Currently, only `get_per_commitment_point` and + /// `release_commitment_secret` are affected by this setting. + #[cfg(test)] + pub fn set_channel_signer_available(&self, peer_id: &PublicKey, chan_id: &ChannelId, available: bool) { + let per_peer_state = self.node.per_peer_state.read().unwrap(); + let chan_lock = per_peer_state.get(peer_id).unwrap().lock().unwrap(); + let signer = (|| { + match chan_lock.channel_by_id.get(chan_id) { + Some(phase) => phase.context().get_signer(), + None => panic!("Couldn't find a channel with id {}", chan_id), + } + })(); + log_debug!(self.logger, "Setting channel signer for {} as available={}", chan_id, available); + signer.as_ecdsa().unwrap().set_available(available); + } } /// If we need an unsafe pointer to a `Node` (ie to reference it in a thread @@ -924,7 +945,8 @@ macro_rules! unwrap_send_err { pub fn check_added_monitors>(node: &H, count: usize) { if let Some(chain_monitor) = node.chain_monitor() { let mut added_monitors = chain_monitor.added_monitors.lock().unwrap(); - assert_eq!(added_monitors.len(), count); + let n = added_monitors.len(); + assert_eq!(n, count, "expected {} monitors to be added, not {}", count, n); added_monitors.clear(); } } @@ -2119,12 +2141,13 @@ macro_rules! expect_channel_shutdown_state { } #[cfg(any(test, ldk_bench, feature = "_test_utils"))] -pub fn expect_channel_pending_event<'a, 'b, 'c, 'd>(node: &'a Node<'b, 'c, 'd>, expected_counterparty_node_id: &PublicKey) { +pub fn expect_channel_pending_event<'a, 'b, 'c, 'd>(node: &'a Node<'b, 'c, 'd>, expected_counterparty_node_id: &PublicKey) -> ChannelId { let events = node.node.get_and_clear_pending_events(); assert_eq!(events.len(), 1); - match events[0] { - crate::events::Event::ChannelPending { ref counterparty_node_id, .. } => { + match &events[0] { + crate::events::Event::ChannelPending { channel_id, counterparty_node_id, .. } => { assert_eq!(*expected_counterparty_node_id, *counterparty_node_id); + *channel_id }, _ => panic!("Unexpected event"), } @@ -3175,24 +3198,28 @@ pub fn reconnect_nodes<'a, 'b, 'c, 'd>(args: ReconnectArgs<'a, 'b, 'c, 'd>) { // If a expects a channel_ready, it better not think it has received a revoke_and_ack // from b for reestablish in reestablish_1.iter() { - assert_eq!(reestablish.next_remote_commitment_number, 0); + let n = reestablish.next_remote_commitment_number; + assert_eq!(n, 0, "expected a->b next_remote_commitment_number to be 0, got {}", n); } } if send_channel_ready.1 { // If b expects a channel_ready, it better not think it has received a revoke_and_ack // from a for reestablish in reestablish_2.iter() { - assert_eq!(reestablish.next_remote_commitment_number, 0); + let n = reestablish.next_remote_commitment_number; + assert_eq!(n, 0, "expected b->a next_remote_commitment_number to be 0, got {}", n); } } if send_channel_ready.0 || send_channel_ready.1 { // If we expect any channel_ready's, both sides better have set // next_holder_commitment_number to 1 for reestablish in reestablish_1.iter() { - assert_eq!(reestablish.next_local_commitment_number, 1); + let n = reestablish.next_local_commitment_number; + assert_eq!(n, 1, "expected a->b next_local_commitment_number to be 1, got {}", n); } for reestablish in reestablish_2.iter() { - assert_eq!(reestablish.next_local_commitment_number, 1); + let n = reestablish.next_local_commitment_number; + assert_eq!(n, 1, "expected b->a next_local_commitment_number to be 1, got {}", n); } } diff --git a/lightning/src/ln/mod.rs b/lightning/src/ln/mod.rs index beefd2d46..6a9a10c80 100644 --- a/lightning/src/ln/mod.rs +++ b/lightning/src/ln/mod.rs @@ -73,6 +73,9 @@ mod monitor_tests; #[cfg(test)] #[allow(unused_mut)] mod shutdown_tests; +#[cfg(test)] +#[allow(unused_mut)] +mod async_signer_tests; pub use self::peer_channel_encryptor::LN_MAX_MSG_LEN; diff --git a/lightning/src/util/test_channel_signer.rs b/lightning/src/util/test_channel_signer.rs index 942671cf4..ab576fee9 100644 --- a/lightning/src/util/test_channel_signer.rs +++ b/lightning/src/util/test_channel_signer.rs @@ -56,6 +56,9 @@ pub struct TestChannelSigner { /// Channel state used for policy enforcement pub state: Arc>, pub disable_revocation_policy_check: bool, + /// When `true` (the default), the signer will respond immediately with signatures. When `false`, + /// the signer will return an error indicating that it is unavailable. + pub available: Arc>, } impl PartialEq for TestChannelSigner { @@ -71,7 +74,8 @@ impl TestChannelSigner { Self { inner, state, - disable_revocation_policy_check: false + disable_revocation_policy_check: false, + available: Arc::new(Mutex::new(true)), } } @@ -84,7 +88,8 @@ impl TestChannelSigner { Self { inner, state, - disable_revocation_policy_check + disable_revocation_policy_check, + available: Arc::new(Mutex::new(true)), } } @@ -94,6 +99,16 @@ impl TestChannelSigner { pub fn get_enforcement_state(&self) -> MutexGuard { self.state.lock().unwrap() } + + /// Marks the signer's availability. + /// + /// When `true`, methods are forwarded to the underlying signer as normal. When `false`, some + /// methods will return `Err` indicating that the signer is unavailable. Intended to be used for + /// testing asynchronous signing. + #[cfg(test)] + pub fn set_available(&self, available: bool) { + *self.available.lock().unwrap() = available; + } } impl ChannelSigner for TestChannelSigner { @@ -133,6 +148,9 @@ impl EcdsaChannelSigner for TestChannelSigner { self.verify_counterparty_commitment_tx(commitment_tx, secp_ctx); { + if !*self.available.lock().unwrap() { + return Err(()); + } let mut state = self.state.lock().unwrap(); let actual_commitment_number = commitment_tx.commitment_number(); let last_commitment_number = state.last_counterparty_commitment; @@ -149,6 +167,9 @@ impl EcdsaChannelSigner for TestChannelSigner { } fn validate_counterparty_revocation(&self, idx: u64, _secret: &SecretKey) -> Result<(), ()> { + if !*self.available.lock().unwrap() { + return Err(()); + } let mut state = self.state.lock().unwrap(); assert!(idx == state.last_counterparty_revoked_commitment || idx == state.last_counterparty_revoked_commitment - 1, "expecting to validate the current or next counterparty revocation - trying {}, current {}", idx, state.last_counterparty_revoked_commitment); state.last_counterparty_revoked_commitment = idx; @@ -156,6 +177,9 @@ impl EcdsaChannelSigner for TestChannelSigner { } fn sign_holder_commitment(&self, commitment_tx: &HolderCommitmentTransaction, secp_ctx: &Secp256k1) -> Result { + if !*self.available.lock().unwrap() { + return Err(()); + } let trusted_tx = self.verify_holder_commitment_tx(commitment_tx, secp_ctx); let state = self.state.lock().unwrap(); let commitment_number = trusted_tx.commitment_number();