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