Actual no_std support
[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         /// The last counterparty commitment number we signed, backwards counting
50         pub last_commitment_number: Arc<Mutex<Option<u64>>>,
51         /// The last holder commitment number we revoked, backwards counting
52         pub revoked_commitment: Arc<Mutex<u64>>,
53         pub disable_revocation_policy_check: bool,
54 }
55
56 impl EnforcingSigner {
57         /// Construct an EnforcingSigner
58         pub fn new(inner: InMemorySigner) -> Self {
59                 Self {
60                         inner,
61                         last_commitment_number: Arc::new(Mutex::new(None)),
62                         revoked_commitment: Arc::new(Mutex::new(INITIAL_REVOKED_COMMITMENT_NUMBER)),
63                         disable_revocation_policy_check: false
64                 }
65         }
66
67         /// Construct an EnforcingSigner with externally managed storage
68         ///
69         /// Since there are multiple copies of this struct for each channel, some coordination is needed
70         /// so that all copies are aware of revocations.  A pointer to this state is provided here, usually
71         /// by an implementation of KeysInterface.
72         pub fn new_with_revoked(inner: InMemorySigner, revoked_commitment: Arc<Mutex<u64>>, disable_revocation_policy_check: bool) -> Self {
73                 Self {
74                         inner,
75                         last_commitment_number: Arc::new(Mutex::new(None)),
76                         revoked_commitment,
77                         disable_revocation_policy_check
78                 }
79         }
80 }
81
82 impl BaseSign for EnforcingSigner {
83         fn get_per_commitment_point(&self, idx: u64, secp_ctx: &Secp256k1<secp256k1::All>) -> PublicKey {
84                 self.inner.get_per_commitment_point(idx, secp_ctx)
85         }
86
87         fn release_commitment_secret(&self, idx: u64) -> [u8; 32] {
88                 {
89                         let mut revoked = self.revoked_commitment.lock().unwrap();
90                         assert!(idx == *revoked || idx == *revoked - 1, "can only revoke the current or next unrevoked commitment - trying {}, revoked {}", idx, *revoked);
91                         *revoked = idx;
92                 }
93                 self.inner.release_commitment_secret(idx)
94         }
95
96         fn pubkeys(&self) -> &ChannelPublicKeys { self.inner.pubkeys() }
97         fn channel_keys_id(&self) -> [u8; 32] { self.inner.channel_keys_id() }
98
99         fn sign_counterparty_commitment(&self, commitment_tx: &CommitmentTransaction, secp_ctx: &Secp256k1<secp256k1::All>) -> Result<(Signature, Vec<Signature>), ()> {
100                 self.verify_counterparty_commitment_tx(commitment_tx, secp_ctx);
101
102                 {
103                         let mut last_commitment_number_guard = self.last_commitment_number.lock().unwrap();
104                         let actual_commitment_number = commitment_tx.commitment_number();
105                         let last_commitment_number = last_commitment_number_guard.unwrap_or(actual_commitment_number);
106                         // These commitment numbers are backwards counting.  We expect either the same as the previously encountered,
107                         // or the next one.
108                         assert!(last_commitment_number == actual_commitment_number || last_commitment_number - 1 == actual_commitment_number, "{} doesn't come after {}", actual_commitment_number, last_commitment_number);
109                         *last_commitment_number_guard = Some(cmp::min(last_commitment_number, actual_commitment_number))
110                 }
111
112                 Ok(self.inner.sign_counterparty_commitment(commitment_tx, secp_ctx).unwrap())
113         }
114
115         fn sign_holder_commitment_and_htlcs(&self, commitment_tx: &HolderCommitmentTransaction, secp_ctx: &Secp256k1<secp256k1::All>) -> Result<(Signature, Vec<Signature>), ()> {
116                 let trusted_tx = self.verify_holder_commitment_tx(commitment_tx, secp_ctx);
117                 let commitment_txid = trusted_tx.txid();
118                 let holder_csv = self.inner.counterparty_selected_contest_delay();
119
120                 let revoked = self.revoked_commitment.lock().unwrap();
121                 let commitment_number = trusted_tx.commitment_number();
122                 if *revoked - 1 != commitment_number && *revoked - 2 != commitment_number {
123                         if !self.disable_revocation_policy_check {
124                                 panic!("can only sign the next two unrevoked commitment numbers, revoked={} vs requested={} for {}",
125                                        *revoked, commitment_number, self.inner.commitment_seed[0])
126                         }
127                 }
128
129                 for (this_htlc, sig) in trusted_tx.htlcs().iter().zip(&commitment_tx.counterparty_htlc_sigs) {
130                         assert!(this_htlc.transaction_output_index.is_some());
131                         let keys = trusted_tx.keys();
132                         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);
133
134                         let htlc_redeemscript = chan_utils::get_htlc_redeemscript(&this_htlc, &keys);
135
136                         let sighash = hash_to_message!(&bip143::SigHashCache::new(&htlc_tx).signature_hash(0, &htlc_redeemscript, this_htlc.amount_msat / 1000, SigHashType::All)[..]);
137                         secp_ctx.verify(&sighash, sig, &keys.countersignatory_htlc_key).unwrap();
138                 }
139
140                 Ok(self.inner.sign_holder_commitment_and_htlcs(commitment_tx, secp_ctx).unwrap())
141         }
142
143         #[cfg(any(test,feature = "unsafe_revoked_tx_signing"))]
144         fn unsafe_sign_holder_commitment_and_htlcs(&self, commitment_tx: &HolderCommitmentTransaction, secp_ctx: &Secp256k1<secp256k1::All>) -> Result<(Signature, Vec<Signature>), ()> {
145                 Ok(self.inner.unsafe_sign_holder_commitment_and_htlcs(commitment_tx, secp_ctx).unwrap())
146         }
147
148         fn sign_justice_revoked_output(&self, justice_tx: &Transaction, input: usize, amount: u64, per_commitment_key: &SecretKey, secp_ctx: &Secp256k1<secp256k1::All>) -> Result<Signature, ()> {
149                 Ok(self.inner.sign_justice_revoked_output(justice_tx, input, amount, per_commitment_key, secp_ctx).unwrap())
150         }
151
152         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, ()> {
153                 Ok(self.inner.sign_justice_revoked_htlc(justice_tx, input, amount, per_commitment_key, htlc, secp_ctx).unwrap())
154         }
155
156         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, ()> {
157                 Ok(self.inner.sign_counterparty_htlc_transaction(htlc_tx, input, amount, per_commitment_point, htlc, secp_ctx).unwrap())
158         }
159
160         fn sign_closing_transaction(&self, closing_tx: &Transaction, secp_ctx: &Secp256k1<secp256k1::All>) -> Result<Signature, ()> {
161                 Ok(self.inner.sign_closing_transaction(closing_tx, secp_ctx).unwrap())
162         }
163
164         fn sign_channel_announcement(&self, msg: &msgs::UnsignedChannelAnnouncement, secp_ctx: &Secp256k1<secp256k1::All>) -> Result<Signature, ()> {
165                 self.inner.sign_channel_announcement(msg, secp_ctx)
166         }
167
168         fn ready_channel(&mut self, channel_parameters: &ChannelTransactionParameters) {
169                 self.inner.ready_channel(channel_parameters)
170         }
171 }
172
173 impl Sign for EnforcingSigner {}
174
175 impl Writeable for EnforcingSigner {
176         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), Error> {
177                 self.inner.write(writer)?;
178                 let last = *self.last_commitment_number.lock().unwrap();
179                 last.write(writer)?;
180                 Ok(())
181         }
182 }
183
184 impl Readable for EnforcingSigner {
185         fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
186                 let inner = Readable::read(reader)?;
187                 let last_commitment_number = Readable::read(reader)?;
188                 Ok(EnforcingSigner {
189                         inner,
190                         last_commitment_number: Arc::new(Mutex::new(last_commitment_number)),
191                         revoked_commitment: Arc::new(Mutex::new(INITIAL_REVOKED_COMMITMENT_NUMBER)),
192                         disable_revocation_policy_check: false,
193                 })
194         }
195 }
196
197 impl EnforcingSigner {
198         fn verify_counterparty_commitment_tx<'a, T: secp256k1::Signing + secp256k1::Verification>(&self, commitment_tx: &'a CommitmentTransaction, secp_ctx: &Secp256k1<T>) -> TrustedCommitmentTransaction<'a> {
199                 commitment_tx.verify(&self.inner.get_channel_parameters().as_counterparty_broadcastable(),
200                                      self.inner.counterparty_pubkeys(), self.inner.pubkeys(), secp_ctx)
201                         .expect("derived different per-tx keys or built transaction")
202         }
203
204         fn verify_holder_commitment_tx<'a, T: secp256k1::Signing + secp256k1::Verification>(&self, commitment_tx: &'a CommitmentTransaction, secp_ctx: &Secp256k1<T>) -> TrustedCommitmentTransaction<'a> {
205                 commitment_tx.verify(&self.inner.get_channel_parameters().as_holder_broadcastable(),
206                                      self.inner.pubkeys(), self.inner.counterparty_pubkeys(), secp_ctx)
207                         .expect("derived different per-tx keys or built transaction")
208         }
209 }