Make ChannelMonitor sign local transactions (at broadcast time)
[rust-lightning] / lightning / src / ln / chan_utils.rs
1 //! Various utilities for building scripts and deriving keys related to channels. These are
2 //! largely of interest for those implementing chain::keysinterface::ChannelKeys message signing
3 //! by hand.
4
5 use bitcoin::blockdata::script::{Script,Builder};
6 use bitcoin::blockdata::opcodes;
7 use bitcoin::blockdata::transaction::{TxIn,TxOut,OutPoint,Transaction, SigHashType};
8 use bitcoin::consensus::encode::{self, Decodable, Encodable};
9 use bitcoin::util::bip143;
10
11 use bitcoin_hashes::{Hash, HashEngine};
12 use bitcoin_hashes::sha256::Hash as Sha256;
13 use bitcoin_hashes::ripemd160::Hash as Ripemd160;
14 use bitcoin_hashes::hash160::Hash as Hash160;
15 use bitcoin_hashes::sha256d::Hash as Sha256dHash;
16
17 use ln::channelmanager::PaymentHash;
18 use ln::msgs::DecodeError;
19 use util::ser::{Readable, Writeable, Writer, WriterWriteAdaptor};
20
21 use secp256k1::key::{SecretKey,PublicKey};
22 use secp256k1::{Secp256k1, Signature};
23 use secp256k1;
24
25 pub(super) const HTLC_SUCCESS_TX_WEIGHT: u64 = 703;
26 pub(super) const HTLC_TIMEOUT_TX_WEIGHT: u64 = 663;
27
28 // Various functions for key derivation and transaction creation for use within channels. Primarily
29 // used in Channel and ChannelMonitor.
30
31 pub(super) fn build_commitment_secret(commitment_seed: &[u8; 32], idx: u64) -> [u8; 32] {
32         let mut res: [u8; 32] = commitment_seed.clone();
33         for i in 0..48 {
34                 let bitpos = 47 - i;
35                 if idx & (1 << bitpos) == (1 << bitpos) {
36                         res[bitpos / 8] ^= 1 << (bitpos & 7);
37                         res = Sha256::hash(&res).into_inner();
38                 }
39         }
40         res
41 }
42
43 /// Derives a per-commitment-transaction private key (eg an htlc key or payment key) from the base
44 /// private key for that type of key and the per_commitment_point (available in TxCreationKeys)
45 pub fn derive_private_key<T: secp256k1::Signing>(secp_ctx: &Secp256k1<T>, per_commitment_point: &PublicKey, base_secret: &SecretKey) -> Result<SecretKey, secp256k1::Error> {
46         let mut sha = Sha256::engine();
47         sha.input(&per_commitment_point.serialize());
48         sha.input(&PublicKey::from_secret_key(&secp_ctx, &base_secret).serialize());
49         let res = Sha256::from_engine(sha).into_inner();
50
51         let mut key = base_secret.clone();
52         key.add_assign(&res)?;
53         Ok(key)
54 }
55
56 pub(super) fn derive_public_key<T: secp256k1::Signing>(secp_ctx: &Secp256k1<T>, per_commitment_point: &PublicKey, base_point: &PublicKey) -> Result<PublicKey, secp256k1::Error> {
57         let mut sha = Sha256::engine();
58         sha.input(&per_commitment_point.serialize());
59         sha.input(&base_point.serialize());
60         let res = Sha256::from_engine(sha).into_inner();
61
62         let hashkey = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&res)?);
63         base_point.combine(&hashkey)
64 }
65
66 /// Derives a revocation key from its constituent parts
67 pub(super) fn derive_private_revocation_key<T: secp256k1::Signing>(secp_ctx: &Secp256k1<T>, per_commitment_secret: &SecretKey, revocation_base_secret: &SecretKey) -> Result<SecretKey, secp256k1::Error> {
68         let revocation_base_point = PublicKey::from_secret_key(&secp_ctx, &revocation_base_secret);
69         let per_commitment_point = PublicKey::from_secret_key(&secp_ctx, &per_commitment_secret);
70
71         let rev_append_commit_hash_key = {
72                 let mut sha = Sha256::engine();
73                 sha.input(&revocation_base_point.serialize());
74                 sha.input(&per_commitment_point.serialize());
75
76                 Sha256::from_engine(sha).into_inner()
77         };
78         let commit_append_rev_hash_key = {
79                 let mut sha = Sha256::engine();
80                 sha.input(&per_commitment_point.serialize());
81                 sha.input(&revocation_base_point.serialize());
82
83                 Sha256::from_engine(sha).into_inner()
84         };
85
86         let mut part_a = revocation_base_secret.clone();
87         part_a.mul_assign(&rev_append_commit_hash_key)?;
88         let mut part_b = per_commitment_secret.clone();
89         part_b.mul_assign(&commit_append_rev_hash_key)?;
90         part_a.add_assign(&part_b[..])?;
91         Ok(part_a)
92 }
93
94 pub(super) fn derive_public_revocation_key<T: secp256k1::Verification>(secp_ctx: &Secp256k1<T>, per_commitment_point: &PublicKey, revocation_base_point: &PublicKey) -> Result<PublicKey, secp256k1::Error> {
95         let rev_append_commit_hash_key = {
96                 let mut sha = Sha256::engine();
97                 sha.input(&revocation_base_point.serialize());
98                 sha.input(&per_commitment_point.serialize());
99
100                 Sha256::from_engine(sha).into_inner()
101         };
102         let commit_append_rev_hash_key = {
103                 let mut sha = Sha256::engine();
104                 sha.input(&per_commitment_point.serialize());
105                 sha.input(&revocation_base_point.serialize());
106
107                 Sha256::from_engine(sha).into_inner()
108         };
109
110         let mut part_a = revocation_base_point.clone();
111         part_a.mul_assign(&secp_ctx, &rev_append_commit_hash_key)?;
112         let mut part_b = per_commitment_point.clone();
113         part_b.mul_assign(&secp_ctx, &commit_append_rev_hash_key)?;
114         part_a.combine(&part_b)
115 }
116
117 /// The set of public keys which are used in the creation of one commitment transaction.
118 /// These are derived from the channel base keys and per-commitment data.
119 pub struct TxCreationKeys {
120         /// The per-commitment public key which was used to derive the other keys.
121         pub per_commitment_point: PublicKey,
122         /// The revocation key which is used to allow the owner of the commitment transaction to
123         /// provide their counterparty the ability to punish them if they broadcast an old state.
124         pub revocation_key: PublicKey,
125         /// A's HTLC Key
126         pub a_htlc_key: PublicKey,
127         /// B's HTLC Key
128         pub b_htlc_key: PublicKey,
129         /// A's Payment Key (which isn't allowed to be spent from for some delay)
130         pub a_delayed_payment_key: PublicKey,
131         /// B's Payment Key
132         pub b_payment_key: PublicKey,
133 }
134
135 impl TxCreationKeys {
136         pub(super) fn new<T: secp256k1::Signing + secp256k1::Verification>(secp_ctx: &Secp256k1<T>, per_commitment_point: &PublicKey, a_delayed_payment_base: &PublicKey, a_htlc_base: &PublicKey, b_revocation_base: &PublicKey, b_payment_base: &PublicKey, b_htlc_base: &PublicKey) -> Result<TxCreationKeys, secp256k1::Error> {
137                 Ok(TxCreationKeys {
138                         per_commitment_point: per_commitment_point.clone(),
139                         revocation_key: derive_public_revocation_key(&secp_ctx, &per_commitment_point, &b_revocation_base)?,
140                         a_htlc_key: derive_public_key(&secp_ctx, &per_commitment_point, &a_htlc_base)?,
141                         b_htlc_key: derive_public_key(&secp_ctx, &per_commitment_point, &b_htlc_base)?,
142                         a_delayed_payment_key: derive_public_key(&secp_ctx, &per_commitment_point, &a_delayed_payment_base)?,
143                         b_payment_key: derive_public_key(&secp_ctx, &per_commitment_point, &b_payment_base)?,
144                 })
145         }
146 }
147
148 /// Gets the "to_local" output redeemscript, ie the script which is time-locked or spendable by
149 /// the revocation key
150 pub(super) fn get_revokeable_redeemscript(revocation_key: &PublicKey, to_self_delay: u16, delayed_payment_key: &PublicKey) -> Script {
151         Builder::new().push_opcode(opcodes::all::OP_IF)
152                       .push_slice(&revocation_key.serialize())
153                       .push_opcode(opcodes::all::OP_ELSE)
154                       .push_int(to_self_delay as i64)
155                       .push_opcode(opcodes::all::OP_CSV)
156                       .push_opcode(opcodes::all::OP_DROP)
157                       .push_slice(&delayed_payment_key.serialize())
158                       .push_opcode(opcodes::all::OP_ENDIF)
159                       .push_opcode(opcodes::all::OP_CHECKSIG)
160                       .into_script()
161 }
162
163 #[derive(Clone, PartialEq)]
164 /// Information about an HTLC as it appears in a commitment transaction
165 pub struct HTLCOutputInCommitment {
166         /// Whether the HTLC was "offered" (ie outbound in relation to this commitment transaction).
167         /// Note that this is not the same as whether it is ountbound *from us*. To determine that you
168         /// need to compare this value to whether the commitment transaction in question is that of
169         /// the remote party or our own.
170         pub offered: bool,
171         /// The value, in msat, of the HTLC. The value as it appears in the commitment transaction is
172         /// this divided by 1000.
173         pub amount_msat: u64,
174         /// The CLTV lock-time at which this HTLC expires.
175         pub cltv_expiry: u32,
176         /// The hash of the preimage which unlocks this HTLC.
177         pub payment_hash: PaymentHash,
178         /// The position within the commitment transactions' outputs. This may be None if the value is
179         /// below the dust limit (in which case no output appears in the commitment transaction and the
180         /// value is spent to additional transaction fees).
181         pub transaction_output_index: Option<u32>,
182 }
183
184 #[inline]
185 pub(super) fn get_htlc_redeemscript_with_explicit_keys(htlc: &HTLCOutputInCommitment, a_htlc_key: &PublicKey, b_htlc_key: &PublicKey, revocation_key: &PublicKey) -> Script {
186         let payment_hash160 = Ripemd160::hash(&htlc.payment_hash.0[..]).into_inner();
187         if htlc.offered {
188                 Builder::new().push_opcode(opcodes::all::OP_DUP)
189                               .push_opcode(opcodes::all::OP_HASH160)
190                               .push_slice(&Hash160::hash(&revocation_key.serialize())[..])
191                               .push_opcode(opcodes::all::OP_EQUAL)
192                               .push_opcode(opcodes::all::OP_IF)
193                               .push_opcode(opcodes::all::OP_CHECKSIG)
194                               .push_opcode(opcodes::all::OP_ELSE)
195                               .push_slice(&b_htlc_key.serialize()[..])
196                               .push_opcode(opcodes::all::OP_SWAP)
197                               .push_opcode(opcodes::all::OP_SIZE)
198                               .push_int(32)
199                               .push_opcode(opcodes::all::OP_EQUAL)
200                               .push_opcode(opcodes::all::OP_NOTIF)
201                               .push_opcode(opcodes::all::OP_DROP)
202                               .push_int(2)
203                               .push_opcode(opcodes::all::OP_SWAP)
204                               .push_slice(&a_htlc_key.serialize()[..])
205                               .push_int(2)
206                               .push_opcode(opcodes::all::OP_CHECKMULTISIG)
207                               .push_opcode(opcodes::all::OP_ELSE)
208                               .push_opcode(opcodes::all::OP_HASH160)
209                               .push_slice(&payment_hash160)
210                               .push_opcode(opcodes::all::OP_EQUALVERIFY)
211                               .push_opcode(opcodes::all::OP_CHECKSIG)
212                               .push_opcode(opcodes::all::OP_ENDIF)
213                               .push_opcode(opcodes::all::OP_ENDIF)
214                               .into_script()
215         } else {
216                 Builder::new().push_opcode(opcodes::all::OP_DUP)
217                               .push_opcode(opcodes::all::OP_HASH160)
218                               .push_slice(&Hash160::hash(&revocation_key.serialize())[..])
219                               .push_opcode(opcodes::all::OP_EQUAL)
220                               .push_opcode(opcodes::all::OP_IF)
221                               .push_opcode(opcodes::all::OP_CHECKSIG)
222                               .push_opcode(opcodes::all::OP_ELSE)
223                               .push_slice(&b_htlc_key.serialize()[..])
224                               .push_opcode(opcodes::all::OP_SWAP)
225                               .push_opcode(opcodes::all::OP_SIZE)
226                               .push_int(32)
227                               .push_opcode(opcodes::all::OP_EQUAL)
228                               .push_opcode(opcodes::all::OP_IF)
229                               .push_opcode(opcodes::all::OP_HASH160)
230                               .push_slice(&payment_hash160)
231                               .push_opcode(opcodes::all::OP_EQUALVERIFY)
232                               .push_int(2)
233                               .push_opcode(opcodes::all::OP_SWAP)
234                               .push_slice(&a_htlc_key.serialize()[..])
235                               .push_int(2)
236                               .push_opcode(opcodes::all::OP_CHECKMULTISIG)
237                               .push_opcode(opcodes::all::OP_ELSE)
238                               .push_opcode(opcodes::all::OP_DROP)
239                               .push_int(htlc.cltv_expiry as i64)
240                               .push_opcode(opcodes::all::OP_CLTV)
241                               .push_opcode(opcodes::all::OP_DROP)
242                               .push_opcode(opcodes::all::OP_CHECKSIG)
243                               .push_opcode(opcodes::all::OP_ENDIF)
244                               .push_opcode(opcodes::all::OP_ENDIF)
245                               .into_script()
246         }
247 }
248
249 /// note here that 'a_revocation_key' is generated using b_revocation_basepoint and a's
250 /// commitment secret. 'htlc' does *not* need to have its previous_output_index filled.
251 #[inline]
252 pub fn get_htlc_redeemscript(htlc: &HTLCOutputInCommitment, keys: &TxCreationKeys) -> Script {
253         get_htlc_redeemscript_with_explicit_keys(htlc, &keys.a_htlc_key, &keys.b_htlc_key, &keys.revocation_key)
254 }
255
256 /// panics if htlc.transaction_output_index.is_none()!
257 pub fn build_htlc_transaction(prev_hash: &Sha256dHash, feerate_per_kw: u64, to_self_delay: u16, htlc: &HTLCOutputInCommitment, a_delayed_payment_key: &PublicKey, revocation_key: &PublicKey) -> Transaction {
258         let mut txins: Vec<TxIn> = Vec::new();
259         txins.push(TxIn {
260                 previous_output: OutPoint {
261                         txid: prev_hash.clone(),
262                         vout: htlc.transaction_output_index.expect("Can't build an HTLC transaction for a dust output"),
263                 },
264                 script_sig: Script::new(),
265                 sequence: 0,
266                 witness: Vec::new(),
267         });
268
269         let total_fee = if htlc.offered {
270                         feerate_per_kw * HTLC_TIMEOUT_TX_WEIGHT / 1000
271                 } else {
272                         feerate_per_kw * HTLC_SUCCESS_TX_WEIGHT / 1000
273                 };
274
275         let mut txouts: Vec<TxOut> = Vec::new();
276         txouts.push(TxOut {
277                 script_pubkey: get_revokeable_redeemscript(revocation_key, to_self_delay, a_delayed_payment_key).to_v0_p2wsh(),
278                 value: htlc.amount_msat / 1000 - total_fee //TODO: BOLT 3 does not specify if we should add amount_msat before dividing or if we should divide by 1000 before subtracting (as we do here)
279         });
280
281         Transaction {
282                 version: 2,
283                 lock_time: if htlc.offered { htlc.cltv_expiry } else { 0 },
284                 input: txins,
285                 output: txouts,
286         }
287 }
288
289 #[derive(Clone)]
290 /// We use this to track local commitment transactions and put off signing them until we are ready
291 /// to broadcast. Eventually this will require a signer which is possibly external, but for now we
292 /// just pass in the SecretKeys required.
293 pub(crate) struct LocalCommitmentTransaction {
294         tx: Transaction
295 }
296 impl LocalCommitmentTransaction {
297         #[cfg(test)]
298         pub fn dummy() -> Self {
299                 Self { tx: Transaction {
300                         version: 2,
301                         input: Vec::new(),
302                         output: Vec::new(),
303                         lock_time: 0,
304                 } }
305         }
306
307         pub fn new_missing_local_sig(mut tx: Transaction, their_sig: &Signature, our_funding_key: &PublicKey, their_funding_key: &PublicKey) -> LocalCommitmentTransaction {
308                 if tx.input.len() != 1 { panic!("Tried to store a commitment transaction that had input count != 1!"); }
309                 if tx.input[0].witness.len() != 0 { panic!("Tried to store a signed commitment transaction?"); }
310
311                 tx.input[0].witness.push(Vec::new()); // First is the multisig dummy
312
313                 if our_funding_key.serialize()[..] < their_funding_key.serialize()[..] {
314                         tx.input[0].witness.push(Vec::new());
315                         tx.input[0].witness.push(their_sig.serialize_der().to_vec());
316                         tx.input[0].witness[2].push(SigHashType::All as u8);
317                 } else {
318                         tx.input[0].witness.push(their_sig.serialize_der().to_vec());
319                         tx.input[0].witness[1].push(SigHashType::All as u8);
320                         tx.input[0].witness.push(Vec::new());
321                 }
322
323                 Self { tx }
324         }
325
326         pub fn txid(&self) -> Sha256dHash {
327                 self.tx.txid()
328         }
329
330         pub fn has_local_sig(&self) -> bool {
331                 if self.tx.input.len() != 1 { panic!("Commitment transactions must have input count == 1!"); }
332                 if self.tx.input[0].witness.len() == 4 {
333                         assert!(!self.tx.input[0].witness[1].is_empty());
334                         assert!(!self.tx.input[0].witness[2].is_empty());
335                         true
336                 } else {
337                         assert_eq!(self.tx.input[0].witness.len(), 3);
338                         assert!(self.tx.input[0].witness[0].is_empty());
339                         assert!(self.tx.input[0].witness[1].is_empty() || self.tx.input[0].witness[2].is_empty());
340                         false
341                 }
342         }
343
344         pub fn add_local_sig<T: secp256k1::Signing>(&mut self, funding_key: &SecretKey, funding_redeemscript: &Script, channel_value_satoshis: u64, secp_ctx: &Secp256k1<T>) {
345                 if self.has_local_sig() { return; }
346                 let sighash = hash_to_message!(&bip143::SighashComponents::new(&self.tx)
347                         .sighash_all(&self.tx.input[0], funding_redeemscript, channel_value_satoshis)[..]);
348                 let our_sig = secp_ctx.sign(&sighash, funding_key);
349
350                 if self.tx.input[0].witness[1].is_empty() {
351                         self.tx.input[0].witness[1] = our_sig.serialize_der().to_vec();
352                         self.tx.input[0].witness[1].push(SigHashType::All as u8);
353                 } else {
354                         self.tx.input[0].witness[2] = our_sig.serialize_der().to_vec();
355                         self.tx.input[0].witness[2].push(SigHashType::All as u8);
356                 }
357
358                 self.tx.input[0].witness.push(funding_redeemscript.as_bytes().to_vec());
359         }
360
361         pub fn without_valid_witness(&self) -> &Transaction { &self.tx }
362         pub fn with_valid_witness(&self) -> &Transaction {
363                 assert!(self.has_local_sig());
364                 &self.tx
365         }
366 }
367 impl PartialEq for LocalCommitmentTransaction {
368         // We dont care whether we are signed in equality comparison
369         fn eq(&self, o: &Self) -> bool {
370                 self.txid() == o.txid()
371         }
372 }
373 impl Writeable for LocalCommitmentTransaction {
374         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
375                 if let Err(e) = self.tx.consensus_encode(&mut WriterWriteAdaptor(writer)) {
376                         match e {
377                                 encode::Error::Io(e) => return Err(e),
378                                 _ => panic!("local tx must have been well-formed!"),
379                         }
380                 }
381                 Ok(())
382         }
383 }
384 impl<R: ::std::io::Read> Readable<R> for LocalCommitmentTransaction {
385         fn read(reader: &mut R) -> Result<Self, DecodeError> {
386                 let tx = match Transaction::consensus_decode(reader.by_ref()) {
387                         Ok(tx) => tx,
388                         Err(e) => match e {
389                                 encode::Error::Io(ioe) => return Err(DecodeError::Io(ioe)),
390                                 _ => return Err(DecodeError::InvalidValue),
391                         },
392                 };
393
394                 if tx.input.len() != 1 {
395                         // Ensure tx didn't hit the 0-input ambiguity case.
396                         return Err(DecodeError::InvalidValue);
397                 }
398                 Ok(Self { tx })
399         }
400 }