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