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