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