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