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