Fold sign_holder_commitment_htlc_transactions into sign_holder_commitment
[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::{msgs, chan_utils};
12 use chain::keysinterface::{ChannelKeys, InMemoryChannelKeys};
13
14 use std::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 /// An implementation of ChannelKeys that enforces some policy checks.
28 ///
29 /// Eventually we will probably want to expose a variant of this which would essentially
30 /// be what you'd want to run on a hardware wallet.
31 #[derive(Clone)]
32 pub struct EnforcingChannelKeys {
33         pub inner: InMemoryChannelKeys,
34         last_commitment_number: Arc<Mutex<Option<u64>>>,
35 }
36
37 impl EnforcingChannelKeys {
38         pub fn new(inner: InMemoryChannelKeys) -> Self {
39                 Self {
40                         inner,
41                         last_commitment_number: Arc::new(Mutex::new(None)),
42                 }
43         }
44 }
45
46 impl ChannelKeys for EnforcingChannelKeys {
47         fn get_per_commitment_point<T: secp256k1::Signing + secp256k1::Verification>(&self, idx: u64, secp_ctx: &Secp256k1<T>) -> PublicKey {
48                 self.inner.get_per_commitment_point(idx, secp_ctx)
49         }
50
51         fn release_commitment_secret(&self, idx: u64) -> [u8; 32] {
52                 // TODO: enforce the ChannelKeys contract - error here if we already signed this commitment
53                 self.inner.release_commitment_secret(idx)
54         }
55
56         fn pubkeys(&self) -> &ChannelPublicKeys { self.inner.pubkeys() }
57         fn key_derivation_params(&self) -> (u64, u64) { self.inner.key_derivation_params() }
58
59         fn sign_counterparty_commitment<T: secp256k1::Signing + secp256k1::Verification>(&self, commitment_tx: &CommitmentTransaction, secp_ctx: &Secp256k1<T>) -> Result<(Signature, Vec<Signature>), ()> {
60                 self.verify_counterparty_commitment_tx(commitment_tx, secp_ctx);
61
62                 {
63                         let mut last_commitment_number_guard = self.last_commitment_number.lock().unwrap();
64                         let actual_commitment_number = commitment_tx.commitment_number();
65                         let last_commitment_number = last_commitment_number_guard.unwrap_or(actual_commitment_number);
66                         // These commitment numbers are backwards counting.  We expect either the same as the previously encountered,
67                         // or the next one.
68                         assert!(last_commitment_number == actual_commitment_number || last_commitment_number - 1 == actual_commitment_number, "{} doesn't come after {}", actual_commitment_number, last_commitment_number);
69                         *last_commitment_number_guard = Some(cmp::min(last_commitment_number, actual_commitment_number))
70                 }
71
72                 Ok(self.inner.sign_counterparty_commitment(commitment_tx, secp_ctx).unwrap())
73         }
74
75         fn sign_holder_commitment_and_htlcs<T: secp256k1::Signing + secp256k1::Verification>(&self, commitment_tx: &HolderCommitmentTransaction, secp_ctx: &Secp256k1<T>) -> Result<(Signature, Vec<Signature>), ()> {
76                 let trusted_tx = self.verify_holder_commitment_tx(commitment_tx, secp_ctx);
77                 let commitment_txid = trusted_tx.txid();
78                 let holder_csv = self.inner.counterparty_selected_contest_delay();
79
80                 for (this_htlc, sig) in trusted_tx.htlcs().iter().zip(&commitment_tx.counterparty_htlc_sigs) {
81                         assert!(this_htlc.transaction_output_index.is_some());
82                         let keys = trusted_tx.keys();
83                         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);
84
85                         let htlc_redeemscript = chan_utils::get_htlc_redeemscript(&this_htlc, &keys);
86
87                         let sighash = hash_to_message!(&bip143::SigHashCache::new(&htlc_tx).signature_hash(0, &htlc_redeemscript, this_htlc.amount_msat / 1000, SigHashType::All)[..]);
88                         secp_ctx.verify(&sighash, sig, &keys.countersignatory_htlc_key).unwrap();
89                 }
90
91                 // TODO: enforce the ChannelKeys contract - error if this commitment was already revoked
92                 // TODO: need the commitment number
93                 Ok(self.inner.sign_holder_commitment_and_htlcs(commitment_tx, secp_ctx).unwrap())
94         }
95
96         #[cfg(any(test,feature = "unsafe_revoked_tx_signing"))]
97         fn unsafe_sign_holder_commitment<T: secp256k1::Signing + secp256k1::Verification>(&self, commitment_tx: &HolderCommitmentTransaction, secp_ctx: &Secp256k1<T>) -> Result<Signature, ()> {
98                 Ok(self.inner.unsafe_sign_holder_commitment(commitment_tx, secp_ctx).unwrap())
99         }
100
101         fn sign_justice_transaction<T: secp256k1::Signing + secp256k1::Verification>(&self, justice_tx: &Transaction, input: usize, amount: u64, per_commitment_key: &SecretKey, htlc: &Option<HTLCOutputInCommitment>, secp_ctx: &Secp256k1<T>) -> Result<Signature, ()> {
102                 Ok(self.inner.sign_justice_transaction(justice_tx, input, amount, per_commitment_key, htlc, secp_ctx).unwrap())
103         }
104
105         fn sign_counterparty_htlc_transaction<T: secp256k1::Signing + secp256k1::Verification>(&self, htlc_tx: &Transaction, input: usize, amount: u64, per_commitment_point: &PublicKey, htlc: &HTLCOutputInCommitment, secp_ctx: &Secp256k1<T>) -> Result<Signature, ()> {
106                 Ok(self.inner.sign_counterparty_htlc_transaction(htlc_tx, input, amount, per_commitment_point, htlc, secp_ctx).unwrap())
107         }
108
109         fn sign_closing_transaction<T: secp256k1::Signing>(&self, closing_tx: &Transaction, secp_ctx: &Secp256k1<T>) -> Result<Signature, ()> {
110                 Ok(self.inner.sign_closing_transaction(closing_tx, secp_ctx).unwrap())
111         }
112
113         fn sign_channel_announcement<T: secp256k1::Signing>(&self, msg: &msgs::UnsignedChannelAnnouncement, secp_ctx: &Secp256k1<T>) -> Result<Signature, ()> {
114                 self.inner.sign_channel_announcement(msg, secp_ctx)
115         }
116
117         fn ready_channel(&mut self, channel_parameters: &ChannelTransactionParameters) {
118                 self.inner.ready_channel(channel_parameters)
119         }
120 }
121
122
123 impl Writeable for EnforcingChannelKeys {
124         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), Error> {
125                 self.inner.write(writer)?;
126                 let last = *self.last_commitment_number.lock().unwrap();
127                 last.write(writer)?;
128                 Ok(())
129         }
130 }
131
132 impl Readable for EnforcingChannelKeys {
133         fn read<R: ::std::io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
134                 let inner = Readable::read(reader)?;
135                 let last_commitment_number = Readable::read(reader)?;
136                 Ok(EnforcingChannelKeys {
137                         inner,
138                         last_commitment_number: Arc::new(Mutex::new(last_commitment_number))
139                 })
140         }
141 }
142
143 impl EnforcingChannelKeys {
144         fn verify_counterparty_commitment_tx<'a, T: secp256k1::Signing + secp256k1::Verification>(&self, commitment_tx: &'a CommitmentTransaction, secp_ctx: &Secp256k1<T>) -> TrustedCommitmentTransaction<'a> {
145                 commitment_tx.verify(&self.inner.get_channel_parameters().as_counterparty_broadcastable(),
146                                      self.inner.counterparty_pubkeys(), self.inner.pubkeys(), secp_ctx)
147                         .expect("derived different per-tx keys or built transaction")
148         }
149
150         fn verify_holder_commitment_tx<'a, T: secp256k1::Signing + secp256k1::Verification>(&self, commitment_tx: &'a CommitmentTransaction, secp_ctx: &Secp256k1<T>) -> TrustedCommitmentTransaction<'a> {
151                 commitment_tx.verify(&self.inner.get_channel_parameters().as_holder_broadcastable(),
152                                      self.inner.pubkeys(), self.inner.counterparty_pubkeys(), secp_ctx)
153                         .expect("derived different per-tx keys or built transaction")
154         }
155 }