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