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