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