Add basic async signer tests
[rust-lightning] / lightning / src / util / test_channel_signer.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 use crate::ln::channel::{ANCHOR_OUTPUT_VALUE_SATOSHI, MIN_CHAN_DUST_LIMIT_SATOSHIS};
11 use crate::ln::chan_utils::{HTLCOutputInCommitment, ChannelPublicKeys, HolderCommitmentTransaction, CommitmentTransaction, ChannelTransactionParameters, TrustedCommitmentTransaction, ClosingTransaction};
12 use crate::ln::{chan_utils, msgs, PaymentPreimage};
13 use crate::sign::{WriteableEcdsaChannelSigner, InMemorySigner, ChannelSigner, EcdsaChannelSigner};
14
15 use crate::prelude::*;
16 use core::cmp;
17 use crate::sync::{Mutex, Arc};
18 #[cfg(test)] use crate::sync::MutexGuard;
19
20 use bitcoin::blockdata::transaction::{Transaction, EcdsaSighashType};
21 use bitcoin::util::sighash;
22
23 use bitcoin::secp256k1;
24 use bitcoin::secp256k1::{SecretKey, PublicKey};
25 use bitcoin::secp256k1::{Secp256k1, ecdsa::Signature};
26 use crate::sign::HTLCDescriptor;
27 use crate::util::ser::{Writeable, Writer};
28 use crate::io::Error;
29 use crate::ln::features::ChannelTypeFeatures;
30
31 /// Initial value for revoked commitment downward counter
32 pub const INITIAL_REVOKED_COMMITMENT_NUMBER: u64 = 1 << 48;
33
34 /// An implementation of Sign that enforces some policy checks.  The current checks
35 /// are an incomplete set.  They include:
36 ///
37 /// - When signing, the holder transaction has not been revoked
38 /// - When revoking, the holder transaction has not been signed
39 /// - The holder commitment number is monotonic and without gaps
40 /// - The revoked holder commitment number is monotonic and without gaps
41 /// - There is at least one unrevoked holder transaction at all times
42 /// - The counterparty commitment number is monotonic and without gaps
43 /// - The pre-derived keys and pre-built transaction in CommitmentTransaction were correctly built
44 ///
45 /// Eventually we will probably want to expose a variant of this which would essentially
46 /// be what you'd want to run on a hardware wallet.
47 ///
48 /// Note that counterparty signatures on the holder transaction are not checked, but it should
49 /// be in a complete implementation.
50 ///
51 /// Note that before we do so we should ensure its serialization format has backwards- and
52 /// forwards-compatibility prefix/suffixes!
53 #[derive(Clone)]
54 pub struct TestChannelSigner {
55         pub inner: InMemorySigner,
56         /// Channel state used for policy enforcement
57         pub state: Arc<Mutex<EnforcementState>>,
58         pub disable_revocation_policy_check: bool,
59         /// When `true` (the default), the signer will respond immediately with signatures. When `false`,
60         /// the signer will return an error indicating that it is unavailable.
61         pub available: Arc<Mutex<bool>>,
62 }
63
64 impl PartialEq for TestChannelSigner {
65         fn eq(&self, o: &Self) -> bool {
66                 Arc::ptr_eq(&self.state, &o.state)
67         }
68 }
69
70 impl TestChannelSigner {
71         /// Construct an TestChannelSigner
72         pub fn new(inner: InMemorySigner) -> Self {
73                 let state = Arc::new(Mutex::new(EnforcementState::new()));
74                 Self {
75                         inner,
76                         state,
77                         disable_revocation_policy_check: false,
78                         available: Arc::new(Mutex::new(true)),
79                 }
80         }
81
82         /// Construct an TestChannelSigner with externally managed storage
83         ///
84         /// Since there are multiple copies of this struct for each channel, some coordination is needed
85         /// so that all copies are aware of enforcement state.  A pointer to this state is provided
86         /// here, usually by an implementation of KeysInterface.
87         pub fn new_with_revoked(inner: InMemorySigner, state: Arc<Mutex<EnforcementState>>, disable_revocation_policy_check: bool) -> Self {
88                 Self {
89                         inner,
90                         state,
91                         disable_revocation_policy_check,
92                         available: Arc::new(Mutex::new(true)),
93                 }
94         }
95
96         pub fn channel_type_features(&self) -> &ChannelTypeFeatures { self.inner.channel_type_features().unwrap() }
97
98         #[cfg(test)]
99         pub fn get_enforcement_state(&self) -> MutexGuard<EnforcementState> {
100                 self.state.lock().unwrap()
101         }
102
103         /// Marks the signer's availability.
104         ///
105         /// When `true`, methods are forwarded to the underlying signer as normal. When `false`, some
106         /// methods will return `Err` indicating that the signer is unavailable. Intended to be used for
107         /// testing asynchronous signing.
108         #[cfg(test)]
109         pub fn set_available(&self, available: bool) {
110                 *self.available.lock().unwrap() = available;
111         }
112 }
113
114 impl ChannelSigner for TestChannelSigner {
115         fn get_per_commitment_point(&self, idx: u64, secp_ctx: &Secp256k1<secp256k1::All>) -> PublicKey {
116                 self.inner.get_per_commitment_point(idx, secp_ctx)
117         }
118
119         fn release_commitment_secret(&self, idx: u64) -> [u8; 32] {
120                 {
121                         let mut state = self.state.lock().unwrap();
122                         assert!(idx == state.last_holder_revoked_commitment || idx == state.last_holder_revoked_commitment - 1, "can only revoke the current or next unrevoked commitment - trying {}, last revoked {}", idx, state.last_holder_revoked_commitment);
123                         assert!(idx > state.last_holder_commitment, "cannot revoke the last holder commitment - attempted to revoke {} last commitment {}", idx, state.last_holder_commitment);
124                         state.last_holder_revoked_commitment = idx;
125                 }
126                 self.inner.release_commitment_secret(idx)
127         }
128
129         fn validate_holder_commitment(&self, holder_tx: &HolderCommitmentTransaction, _preimages: Vec<PaymentPreimage>) -> Result<(), ()> {
130                 let mut state = self.state.lock().unwrap();
131                 let idx = holder_tx.commitment_number();
132                 assert!(idx == state.last_holder_commitment || idx == state.last_holder_commitment - 1, "expecting to validate the current or next holder commitment - trying {}, current {}", idx, state.last_holder_commitment);
133                 state.last_holder_commitment = idx;
134                 Ok(())
135         }
136
137         fn pubkeys(&self) -> &ChannelPublicKeys { self.inner.pubkeys() }
138
139         fn channel_keys_id(&self) -> [u8; 32] { self.inner.channel_keys_id() }
140
141         fn provide_channel_parameters(&mut self, channel_parameters: &ChannelTransactionParameters) {
142                 self.inner.provide_channel_parameters(channel_parameters)
143         }
144 }
145
146 impl EcdsaChannelSigner for TestChannelSigner {
147         fn sign_counterparty_commitment(&self, commitment_tx: &CommitmentTransaction, preimages: Vec<PaymentPreimage>, secp_ctx: &Secp256k1<secp256k1::All>) -> Result<(Signature, Vec<Signature>), ()> {
148                 self.verify_counterparty_commitment_tx(commitment_tx, secp_ctx);
149
150                 {
151                         if !*self.available.lock().unwrap() {
152                                 return Err(());
153                         }
154                         let mut state = self.state.lock().unwrap();
155                         let actual_commitment_number = commitment_tx.commitment_number();
156                         let last_commitment_number = state.last_counterparty_commitment;
157                         // These commitment numbers are backwards counting.  We expect either the same as the previously encountered,
158                         // or the next one.
159                         assert!(last_commitment_number == actual_commitment_number || last_commitment_number - 1 == actual_commitment_number, "{} doesn't come after {}", actual_commitment_number, last_commitment_number);
160                         // Ensure that the counterparty doesn't get more than two broadcastable commitments -
161                         // the last and the one we are trying to sign
162                         assert!(actual_commitment_number >= state.last_counterparty_revoked_commitment - 2, "cannot sign a commitment if second to last wasn't revoked - signing {} revoked {}", actual_commitment_number, state.last_counterparty_revoked_commitment);
163                         state.last_counterparty_commitment = cmp::min(last_commitment_number, actual_commitment_number)
164                 }
165
166                 Ok(self.inner.sign_counterparty_commitment(commitment_tx, preimages, secp_ctx).unwrap())
167         }
168
169         fn validate_counterparty_revocation(&self, idx: u64, _secret: &SecretKey) -> Result<(), ()> {
170                 if !*self.available.lock().unwrap() {
171                         return Err(());
172                 }
173                 let mut state = self.state.lock().unwrap();
174                 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);
175                 state.last_counterparty_revoked_commitment = idx;
176                 Ok(())
177         }
178
179         fn sign_holder_commitment(&self, commitment_tx: &HolderCommitmentTransaction, secp_ctx: &Secp256k1<secp256k1::All>) -> Result<Signature, ()> {
180                 if !*self.available.lock().unwrap() {
181                         return Err(());
182                 }
183                 let trusted_tx = self.verify_holder_commitment_tx(commitment_tx, secp_ctx);
184                 let state = self.state.lock().unwrap();
185                 let commitment_number = trusted_tx.commitment_number();
186                 if state.last_holder_revoked_commitment - 1 != commitment_number && state.last_holder_revoked_commitment - 2 != commitment_number {
187                         if !self.disable_revocation_policy_check {
188                                 panic!("can only sign the next two unrevoked commitment numbers, revoked={} vs requested={} for {}",
189                                        state.last_holder_revoked_commitment, commitment_number, self.inner.commitment_seed[0])
190                         }
191                 }
192                 Ok(self.inner.sign_holder_commitment(commitment_tx, secp_ctx).unwrap())
193         }
194
195         #[cfg(any(test,feature = "unsafe_revoked_tx_signing"))]
196         fn unsafe_sign_holder_commitment(&self, commitment_tx: &HolderCommitmentTransaction, secp_ctx: &Secp256k1<secp256k1::All>) -> Result<Signature, ()> {
197                 Ok(self.inner.unsafe_sign_holder_commitment(commitment_tx, secp_ctx).unwrap())
198         }
199
200         fn sign_justice_revoked_output(&self, justice_tx: &Transaction, input: usize, amount: u64, per_commitment_key: &SecretKey, secp_ctx: &Secp256k1<secp256k1::All>) -> Result<Signature, ()> {
201                 Ok(self.inner.sign_justice_revoked_output(justice_tx, input, amount, per_commitment_key, secp_ctx).unwrap())
202         }
203
204         fn sign_justice_revoked_htlc(&self, justice_tx: &Transaction, input: usize, amount: u64, per_commitment_key: &SecretKey, htlc: &HTLCOutputInCommitment, secp_ctx: &Secp256k1<secp256k1::All>) -> Result<Signature, ()> {
205                 Ok(self.inner.sign_justice_revoked_htlc(justice_tx, input, amount, per_commitment_key, htlc, secp_ctx).unwrap())
206         }
207
208         fn sign_holder_htlc_transaction(
209                 &self, htlc_tx: &Transaction, input: usize, htlc_descriptor: &HTLCDescriptor,
210                 secp_ctx: &Secp256k1<secp256k1::All>
211         ) -> Result<Signature, ()> {
212                 let state = self.state.lock().unwrap();
213                 if state.last_holder_revoked_commitment - 1 != htlc_descriptor.per_commitment_number &&
214                         state.last_holder_revoked_commitment - 2 != htlc_descriptor.per_commitment_number
215                 {
216                         if !self.disable_revocation_policy_check {
217                                 panic!("can only sign the next two unrevoked commitment numbers, revoked={} vs requested={} for {}",
218                                        state.last_holder_revoked_commitment, htlc_descriptor.per_commitment_number, self.inner.commitment_seed[0])
219                         }
220                 }
221                 assert_eq!(htlc_tx.input[input], htlc_descriptor.unsigned_tx_input());
222                 assert_eq!(htlc_tx.output[input], htlc_descriptor.tx_output(secp_ctx));
223                 {
224                         let witness_script = htlc_descriptor.witness_script(secp_ctx);
225                         let sighash_type = if self.channel_type_features().supports_anchors_zero_fee_htlc_tx() {
226                                 EcdsaSighashType::SinglePlusAnyoneCanPay
227                         } else {
228                                 EcdsaSighashType::All
229                         };
230                         let sighash = &sighash::SighashCache::new(&*htlc_tx).segwit_signature_hash(
231                                 input, &witness_script, htlc_descriptor.htlc.amount_msat / 1000, sighash_type
232                         ).unwrap();
233                         let countersignatory_htlc_key = chan_utils::derive_public_key(
234                                 &secp_ctx, &htlc_descriptor.per_commitment_point, &self.inner.counterparty_pubkeys().unwrap().htlc_basepoint
235                         );
236                         secp_ctx.verify_ecdsa(
237                                 &hash_to_message!(&sighash), &htlc_descriptor.counterparty_sig, &countersignatory_htlc_key
238                         ).unwrap();
239                 }
240                 Ok(self.inner.sign_holder_htlc_transaction(htlc_tx, input, htlc_descriptor, secp_ctx).unwrap())
241         }
242
243         fn sign_counterparty_htlc_transaction(&self, htlc_tx: &Transaction, input: usize, amount: u64, per_commitment_point: &PublicKey, htlc: &HTLCOutputInCommitment, secp_ctx: &Secp256k1<secp256k1::All>) -> Result<Signature, ()> {
244                 Ok(self.inner.sign_counterparty_htlc_transaction(htlc_tx, input, amount, per_commitment_point, htlc, secp_ctx).unwrap())
245         }
246
247         fn sign_closing_transaction(&self, closing_tx: &ClosingTransaction, secp_ctx: &Secp256k1<secp256k1::All>) -> Result<Signature, ()> {
248                 closing_tx.verify(self.inner.funding_outpoint().unwrap().into_bitcoin_outpoint())
249                         .expect("derived different closing transaction");
250                 Ok(self.inner.sign_closing_transaction(closing_tx, secp_ctx).unwrap())
251         }
252
253         fn sign_holder_anchor_input(
254                 &self, anchor_tx: &Transaction, input: usize, secp_ctx: &Secp256k1<secp256k1::All>,
255         ) -> Result<Signature, ()> {
256                 debug_assert!(MIN_CHAN_DUST_LIMIT_SATOSHIS > ANCHOR_OUTPUT_VALUE_SATOSHI);
257                 // As long as our minimum dust limit is enforced and is greater than our anchor output
258                 // value, an anchor output can only have an index within [0, 1].
259                 assert!(anchor_tx.input[input].previous_output.vout == 0 || anchor_tx.input[input].previous_output.vout == 1);
260                 self.inner.sign_holder_anchor_input(anchor_tx, input, secp_ctx)
261         }
262
263         fn sign_channel_announcement_with_funding_key(
264                 &self, msg: &msgs::UnsignedChannelAnnouncement, secp_ctx: &Secp256k1<secp256k1::All>
265         ) -> Result<Signature, ()> {
266                 self.inner.sign_channel_announcement_with_funding_key(msg, secp_ctx)
267         }
268 }
269
270 impl WriteableEcdsaChannelSigner for TestChannelSigner {}
271
272 impl Writeable for TestChannelSigner {
273         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), Error> {
274                 // TestChannelSigner has two fields - `inner` ([`InMemorySigner`]) and `state`
275                 // ([`EnforcementState`]). `inner` is serialized here and deserialized by
276                 // [`SignerProvider::read_chan_signer`]. `state` is managed by [`SignerProvider`]
277                 // and will be serialized as needed by the implementation of that trait.
278                 self.inner.write(writer)?;
279                 Ok(())
280         }
281 }
282
283 impl TestChannelSigner {
284         fn verify_counterparty_commitment_tx<'a, T: secp256k1::Signing + secp256k1::Verification>(&self, commitment_tx: &'a CommitmentTransaction, secp_ctx: &Secp256k1<T>) -> TrustedCommitmentTransaction<'a> {
285                 commitment_tx.verify(
286                         &self.inner.get_channel_parameters().unwrap().as_counterparty_broadcastable(),
287                         self.inner.counterparty_pubkeys().unwrap(), self.inner.pubkeys(), secp_ctx
288                 ).expect("derived different per-tx keys or built transaction")
289         }
290
291         fn verify_holder_commitment_tx<'a, T: secp256k1::Signing + secp256k1::Verification>(&self, commitment_tx: &'a CommitmentTransaction, secp_ctx: &Secp256k1<T>) -> TrustedCommitmentTransaction<'a> {
292                 commitment_tx.verify(
293                         &self.inner.get_channel_parameters().unwrap().as_holder_broadcastable(),
294                         self.inner.pubkeys(), self.inner.counterparty_pubkeys().unwrap(), secp_ctx
295                 ).expect("derived different per-tx keys or built transaction")
296         }
297 }
298
299 /// The state used by [`TestChannelSigner`] in order to enforce policy checks
300 ///
301 /// This structure is maintained by KeysInterface since we may have multiple copies of
302 /// the signer and they must coordinate their state.
303 #[derive(Clone)]
304 pub struct EnforcementState {
305         /// The last counterparty commitment number we signed, backwards counting
306         pub last_counterparty_commitment: u64,
307         /// The last counterparty commitment they revoked, backwards counting
308         pub last_counterparty_revoked_commitment: u64,
309         /// The last holder commitment number we revoked, backwards counting
310         pub last_holder_revoked_commitment: u64,
311         /// The last validated holder commitment number, backwards counting
312         pub last_holder_commitment: u64,
313 }
314
315 impl EnforcementState {
316         /// Enforcement state for a new channel
317         pub fn new() -> Self {
318                 EnforcementState {
319                         last_counterparty_commitment: INITIAL_REVOKED_COMMITMENT_NUMBER,
320                         last_counterparty_revoked_commitment: INITIAL_REVOKED_COMMITMENT_NUMBER,
321                         last_holder_revoked_commitment: INITIAL_REVOKED_COMMITMENT_NUMBER,
322                         last_holder_commitment: INITIAL_REVOKED_COMMITMENT_NUMBER,
323                 }
324         }
325 }