32c17af64dd877efcd8c07a7698e0049bdc739bd
[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 core::cmp;
15 use std::sync::{Mutex, Arc};
16
17 use bitcoin::blockdata::transaction::{Transaction, SigHashType};
18 use bitcoin::util::bip143;
19
20 use bitcoin::secp256k1;
21 use bitcoin::secp256k1::key::{SecretKey, PublicKey};
22 use bitcoin::secp256k1::{Secp256k1, Signature};
23 use util::ser::{Writeable, Writer, Readable};
24 use std::io::Error;
25 use ln::msgs::DecodeError;
26
27 /// Initial value for revoked commitment downward counter
28 pub const INITIAL_REVOKED_COMMITMENT_NUMBER: u64 = 1 << 48;
29
30 /// An implementation of Sign that enforces some policy checks.  The current checks
31 /// are an incomplete set.  They include:
32 ///
33 /// - When signing, the holder transaction has not been revoked
34 /// - When revoking, the holder transaction has not been signed
35 /// - The holder commitment number is monotonic and without gaps
36 /// - The counterparty commitment number is monotonic and without gaps
37 /// - The pre-derived keys and pre-built transaction in CommitmentTransaction were correctly built
38 ///
39 /// Eventually we will probably want to expose a variant of this which would essentially
40 /// be what you'd want to run on a hardware wallet.
41 #[derive(Clone)]
42 pub struct EnforcingSigner {
43         pub inner: InMemorySigner,
44         /// The last counterparty commitment number we signed, backwards counting
45         pub last_commitment_number: Arc<Mutex<Option<u64>>>,
46         /// The last holder commitment number we revoked, backwards counting
47         pub revoked_commitment: Arc<Mutex<u64>>,
48         pub disable_revocation_policy_check: bool,
49 }
50
51 impl EnforcingSigner {
52         /// Construct an EnforcingSigner
53         pub fn new(inner: InMemorySigner) -> Self {
54                 Self {
55                         inner,
56                         last_commitment_number: Arc::new(Mutex::new(None)),
57                         revoked_commitment: Arc::new(Mutex::new(INITIAL_REVOKED_COMMITMENT_NUMBER)),
58                         disable_revocation_policy_check: false
59                 }
60         }
61
62         /// Construct an EnforcingSigner with externally managed storage
63         ///
64         /// Since there are multiple copies of this struct for each channel, some coordination is needed
65         /// so that all copies are aware of revocations.  A pointer to this state is provided here, usually
66         /// by an implementation of KeysInterface.
67         pub fn new_with_revoked(inner: InMemorySigner, revoked_commitment: Arc<Mutex<u64>>, disable_revocation_policy_check: bool) -> Self {
68                 Self {
69                         inner,
70                         last_commitment_number: Arc::new(Mutex::new(None)),
71                         revoked_commitment,
72                         disable_revocation_policy_check
73                 }
74         }
75 }
76
77 impl BaseSign for EnforcingSigner {
78         fn get_per_commitment_point(&self, idx: u64, secp_ctx: &Secp256k1<secp256k1::All>) -> PublicKey {
79                 self.inner.get_per_commitment_point(idx, secp_ctx)
80         }
81
82         fn release_commitment_secret(&self, idx: u64) -> [u8; 32] {
83                 {
84                         let mut revoked = self.revoked_commitment.lock().unwrap();
85                         assert!(idx == *revoked || idx == *revoked - 1, "can only revoke the current or next unrevoked commitment - trying {}, revoked {}", idx, *revoked);
86                         *revoked = idx;
87                 }
88                 self.inner.release_commitment_secret(idx)
89         }
90
91         fn pubkeys(&self) -> &ChannelPublicKeys { self.inner.pubkeys() }
92         fn channel_keys_id(&self) -> [u8; 32] { self.inner.channel_keys_id() }
93
94         fn sign_counterparty_commitment(&self, commitment_tx: &CommitmentTransaction, secp_ctx: &Secp256k1<secp256k1::All>) -> Result<(Signature, Vec<Signature>), ()> {
95                 self.verify_counterparty_commitment_tx(commitment_tx, secp_ctx);
96
97                 {
98                         let mut last_commitment_number_guard = self.last_commitment_number.lock().unwrap();
99                         let actual_commitment_number = commitment_tx.commitment_number();
100                         let last_commitment_number = last_commitment_number_guard.unwrap_or(actual_commitment_number);
101                         // These commitment numbers are backwards counting.  We expect either the same as the previously encountered,
102                         // or the next one.
103                         assert!(last_commitment_number == actual_commitment_number || last_commitment_number - 1 == actual_commitment_number, "{} doesn't come after {}", actual_commitment_number, last_commitment_number);
104                         *last_commitment_number_guard = Some(cmp::min(last_commitment_number, actual_commitment_number))
105                 }
106
107                 Ok(self.inner.sign_counterparty_commitment(commitment_tx, secp_ctx).unwrap())
108         }
109
110         fn sign_holder_commitment_and_htlcs(&self, commitment_tx: &HolderCommitmentTransaction, secp_ctx: &Secp256k1<secp256k1::All>) -> Result<(Signature, Vec<Signature>), ()> {
111                 let trusted_tx = self.verify_holder_commitment_tx(commitment_tx, secp_ctx);
112                 let commitment_txid = trusted_tx.txid();
113                 let holder_csv = self.inner.counterparty_selected_contest_delay();
114
115                 let revoked = self.revoked_commitment.lock().unwrap();
116                 let commitment_number = trusted_tx.commitment_number();
117                 if *revoked - 1 != commitment_number && *revoked - 2 != commitment_number {
118                         if !self.disable_revocation_policy_check {
119                                 panic!("can only sign the next two unrevoked commitment numbers, revoked={} vs requested={} for {}",
120                                        *revoked, commitment_number, self.inner.commitment_seed[0])
121                         }
122                 }
123
124                 for (this_htlc, sig) in trusted_tx.htlcs().iter().zip(&commitment_tx.counterparty_htlc_sigs) {
125                         assert!(this_htlc.transaction_output_index.is_some());
126                         let keys = trusted_tx.keys();
127                         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);
128
129                         let htlc_redeemscript = chan_utils::get_htlc_redeemscript(&this_htlc, &keys);
130
131                         let sighash = hash_to_message!(&bip143::SigHashCache::new(&htlc_tx).signature_hash(0, &htlc_redeemscript, this_htlc.amount_msat / 1000, SigHashType::All)[..]);
132                         secp_ctx.verify(&sighash, sig, &keys.countersignatory_htlc_key).unwrap();
133                 }
134
135                 Ok(self.inner.sign_holder_commitment_and_htlcs(commitment_tx, secp_ctx).unwrap())
136         }
137
138         #[cfg(any(test,feature = "unsafe_revoked_tx_signing"))]
139         fn unsafe_sign_holder_commitment_and_htlcs(&self, commitment_tx: &HolderCommitmentTransaction, secp_ctx: &Secp256k1<secp256k1::All>) -> Result<(Signature, Vec<Signature>), ()> {
140                 Ok(self.inner.unsafe_sign_holder_commitment_and_htlcs(commitment_tx, secp_ctx).unwrap())
141         }
142
143         fn sign_justice_revoked_output(&self, justice_tx: &Transaction, input: usize, amount: u64, per_commitment_key: &SecretKey, secp_ctx: &Secp256k1<secp256k1::All>) -> Result<Signature, ()> {
144                 Ok(self.inner.sign_justice_revoked_output(justice_tx, input, amount, per_commitment_key, secp_ctx).unwrap())
145         }
146
147         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, ()> {
148                 Ok(self.inner.sign_justice_revoked_htlc(justice_tx, input, amount, per_commitment_key, htlc, secp_ctx).unwrap())
149         }
150
151         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, ()> {
152                 Ok(self.inner.sign_counterparty_htlc_transaction(htlc_tx, input, amount, per_commitment_point, htlc, secp_ctx).unwrap())
153         }
154
155         fn sign_closing_transaction(&self, closing_tx: &Transaction, secp_ctx: &Secp256k1<secp256k1::All>) -> Result<Signature, ()> {
156                 Ok(self.inner.sign_closing_transaction(closing_tx, secp_ctx).unwrap())
157         }
158
159         fn sign_channel_announcement(&self, msg: &msgs::UnsignedChannelAnnouncement, secp_ctx: &Secp256k1<secp256k1::All>) -> Result<Signature, ()> {
160                 self.inner.sign_channel_announcement(msg, secp_ctx)
161         }
162
163         fn ready_channel(&mut self, channel_parameters: &ChannelTransactionParameters) {
164                 self.inner.ready_channel(channel_parameters)
165         }
166 }
167
168 impl Sign for EnforcingSigner {}
169
170 impl Writeable for EnforcingSigner {
171         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), Error> {
172                 self.inner.write(writer)?;
173                 let last = *self.last_commitment_number.lock().unwrap();
174                 last.write(writer)?;
175                 Ok(())
176         }
177 }
178
179 impl Readable for EnforcingSigner {
180         fn read<R: ::std::io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
181                 let inner = Readable::read(reader)?;
182                 let last_commitment_number = Readable::read(reader)?;
183                 Ok(EnforcingSigner {
184                         inner,
185                         last_commitment_number: Arc::new(Mutex::new(last_commitment_number)),
186                         revoked_commitment: Arc::new(Mutex::new(INITIAL_REVOKED_COMMITMENT_NUMBER)),
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 }