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