Allow(unused_imports) on prelude imports
[rust-lightning] / lightning / src / offers / merkle.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 //! Tagged hashes for use in signature calculation and verification.
11
12 use bitcoin::hashes::{Hash, HashEngine, sha256};
13 use bitcoin::secp256k1::{Message, PublicKey, Secp256k1, self};
14 use bitcoin::secp256k1::schnorr::Signature;
15 use core::convert::AsRef;
16 use crate::io;
17 use crate::util::ser::{BigSize, Readable, Writeable, Writer};
18
19 #[allow(unused_imports)]
20 use crate::prelude::*;
21
22 /// Valid type range for signature TLV records.
23 const SIGNATURE_TYPES: core::ops::RangeInclusive<u64> = 240..=1000;
24
25 tlv_stream!(SignatureTlvStream, SignatureTlvStreamRef, SIGNATURE_TYPES, {
26         (240, signature: Signature),
27 });
28
29 /// A hash for use in a specific context by tweaking with a context-dependent tag as per [BIP 340]
30 /// and computed over the merkle root of a TLV stream to sign as defined in [BOLT 12].
31 ///
32 /// [BIP 340]: https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki
33 /// [BOLT 12]: https://github.com/rustyrussell/lightning-rfc/blob/guilt/offers/12-offer-encoding.md#signature-calculation
34 #[derive(Clone, Debug, PartialEq)]
35 pub struct TaggedHash {
36         tag: &'static str,
37         merkle_root: sha256::Hash,
38         digest: Message,
39 }
40
41 impl TaggedHash {
42         /// Creates a tagged hash with the given parameters.
43         ///
44         /// Panics if `tlv_stream` is not a well-formed TLV stream containing at least one TLV record.
45         pub(super) fn new(tag: &'static str, tlv_stream: &[u8]) -> Self {
46                 let tag_hash = sha256::Hash::hash(tag.as_bytes());
47                 let merkle_root = root_hash(tlv_stream);
48                 let digest = Message::from_slice(tagged_hash(tag_hash, merkle_root).as_byte_array()).unwrap();
49                 Self {
50                         tag,
51                         merkle_root,
52                         digest,
53                 }
54         }
55
56         /// Returns the digest to sign.
57         pub fn as_digest(&self) -> &Message {
58                 &self.digest
59         }
60
61         /// Returns the tag used in the tagged hash.
62         pub fn tag(&self) -> &str {
63                 &self.tag
64         }
65
66         /// Returns the merkle root used in the tagged hash.
67         pub fn merkle_root(&self) -> sha256::Hash {
68                 self.merkle_root
69         }
70 }
71
72 impl AsRef<TaggedHash> for TaggedHash {
73         fn as_ref(&self) -> &TaggedHash {
74                 self
75         }
76 }
77
78 /// Error when signing messages.
79 #[derive(Debug, PartialEq)]
80 pub enum SignError {
81         /// User-defined error when signing the message.
82         Signing,
83         /// Error when verifying the produced signature using the given pubkey.
84         Verification(secp256k1::Error),
85 }
86
87 /// A function for signing a [`TaggedHash`].
88 pub(super) trait SignFn<T: AsRef<TaggedHash>> {
89         /// Signs a [`TaggedHash`] computed over the merkle root of `message`'s TLV stream.
90         fn sign(&self, message: &T) -> Result<Signature, ()>;
91 }
92
93 impl<F> SignFn<TaggedHash> for F
94 where
95         F: Fn(&TaggedHash) -> Result<Signature, ()>,
96 {
97         fn sign(&self, message: &TaggedHash) -> Result<Signature, ()> {
98                 self(message)
99         }
100 }
101
102 /// Signs a [`TaggedHash`] computed over the merkle root of `message`'s TLV stream, checking if it
103 /// can be verified with the supplied `pubkey`.
104 ///
105 /// Since `message` is any type that implements [`AsRef<TaggedHash>`], `sign` may be a closure that
106 /// takes a message such as [`Bolt12Invoice`] or [`InvoiceRequest`]. This allows further message
107 /// verification before signing its [`TaggedHash`].
108 ///
109 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
110 /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
111 pub(super) fn sign_message<F, T>(
112         f: F, message: &T, pubkey: PublicKey,
113 ) -> Result<Signature, SignError>
114 where
115         F: SignFn<T>,
116         T: AsRef<TaggedHash>,
117 {
118         let signature = f.sign(message).map_err(|()| SignError::Signing)?;
119
120         let digest = message.as_ref().as_digest();
121         let pubkey = pubkey.into();
122         let secp_ctx = Secp256k1::verification_only();
123         secp_ctx.verify_schnorr(&signature, digest, &pubkey).map_err(|e| SignError::Verification(e))?;
124
125         Ok(signature)
126 }
127
128 /// Verifies the signature with a pubkey over the given message using a tagged hash as the message
129 /// digest.
130 pub(super) fn verify_signature(
131         signature: &Signature, message: &TaggedHash, pubkey: PublicKey,
132 ) -> Result<(), secp256k1::Error> {
133         let digest = message.as_digest();
134         let pubkey = pubkey.into();
135         let secp_ctx = Secp256k1::verification_only();
136         secp_ctx.verify_schnorr(signature, digest, &pubkey)
137 }
138
139 /// Computes a merkle root hash for the given data, which must be a well-formed TLV stream
140 /// containing at least one TLV record.
141 fn root_hash(data: &[u8]) -> sha256::Hash {
142         let nonce_tag = tagged_hash_engine(sha256::Hash::from_engine({
143                 let first_tlv_record = TlvStream::new(&data[..]).next().unwrap();
144                 let mut engine = sha256::Hash::engine();
145                 engine.input("LnNonce".as_bytes());
146                 engine.input(first_tlv_record.record_bytes);
147                 engine
148         }));
149         let leaf_tag = tagged_hash_engine(sha256::Hash::hash("LnLeaf".as_bytes()));
150         let branch_tag = tagged_hash_engine(sha256::Hash::hash("LnBranch".as_bytes()));
151
152         let mut leaves = Vec::new();
153         let tlv_stream = TlvStream::new(&data[..]);
154         for record in tlv_stream.skip_signatures() {
155                 leaves.push(tagged_hash_from_engine(leaf_tag.clone(), &record.record_bytes));
156                 leaves.push(tagged_hash_from_engine(nonce_tag.clone(), &record.type_bytes));
157         }
158
159         // Calculate the merkle root hash in place.
160         let num_leaves = leaves.len();
161         for level in 0.. {
162                 let step = 2 << level;
163                 let offset = step / 2;
164                 if offset >= num_leaves {
165                         break;
166                 }
167
168                 let left_branches = (0..num_leaves).step_by(step);
169                 let right_branches = (offset..num_leaves).step_by(step);
170                 for (i, j) in left_branches.zip(right_branches) {
171                         leaves[i] = tagged_branch_hash_from_engine(branch_tag.clone(), leaves[i], leaves[j]);
172                 }
173         }
174
175         *leaves.first().unwrap()
176 }
177
178 fn tagged_hash<T: AsRef<[u8]>>(tag: sha256::Hash, msg: T) -> sha256::Hash {
179         let engine = tagged_hash_engine(tag);
180         tagged_hash_from_engine(engine, msg)
181 }
182
183 fn tagged_hash_engine(tag: sha256::Hash) -> sha256::HashEngine {
184         let mut engine = sha256::Hash::engine();
185         engine.input(tag.as_ref());
186         engine.input(tag.as_ref());
187         engine
188 }
189
190 fn tagged_hash_from_engine<T: AsRef<[u8]>>(mut engine: sha256::HashEngine, msg: T) -> sha256::Hash {
191         engine.input(msg.as_ref());
192         sha256::Hash::from_engine(engine)
193 }
194
195 fn tagged_branch_hash_from_engine(
196         mut engine: sha256::HashEngine, leaf1: sha256::Hash, leaf2: sha256::Hash,
197 ) -> sha256::Hash {
198         if leaf1 < leaf2 {
199                 engine.input(leaf1.as_ref());
200                 engine.input(leaf2.as_ref());
201         } else {
202                 engine.input(leaf2.as_ref());
203                 engine.input(leaf1.as_ref());
204         };
205         sha256::Hash::from_engine(engine)
206 }
207
208 /// [`Iterator`] over a sequence of bytes yielding [`TlvRecord`]s. The input is assumed to be a
209 /// well-formed TLV stream.
210 #[derive(Clone)]
211 pub(super) struct TlvStream<'a> {
212         data: io::Cursor<&'a [u8]>,
213 }
214
215 impl<'a> TlvStream<'a> {
216         pub fn new(data: &'a [u8]) -> Self {
217                 Self {
218                         data: io::Cursor::new(data),
219                 }
220         }
221
222         pub fn range<T>(self, types: T) -> impl core::iter::Iterator<Item = TlvRecord<'a>>
223         where
224                 T: core::ops::RangeBounds<u64> + Clone,
225         {
226                 let take_range = types.clone();
227                 self.skip_while(move |record| !types.contains(&record.r#type))
228                         .take_while(move |record| take_range.contains(&record.r#type))
229         }
230
231         fn skip_signatures(self) -> core::iter::Filter<TlvStream<'a>, fn(&TlvRecord) -> bool> {
232                 self.filter(|record| !SIGNATURE_TYPES.contains(&record.r#type))
233         }
234 }
235
236 /// A slice into a [`TlvStream`] for a record.
237 pub(super) struct TlvRecord<'a> {
238         pub(super) r#type: u64,
239         type_bytes: &'a [u8],
240         // The entire TLV record.
241         pub(super) record_bytes: &'a [u8],
242 }
243
244 impl<'a> Iterator for TlvStream<'a> {
245         type Item = TlvRecord<'a>;
246
247         fn next(&mut self) -> Option<Self::Item> {
248                 if self.data.position() < self.data.get_ref().len() as u64 {
249                         let start = self.data.position();
250
251                         let r#type = <BigSize as Readable>::read(&mut self.data).unwrap().0;
252                         let offset = self.data.position();
253                         let type_bytes = &self.data.get_ref()[start as usize..offset as usize];
254
255                         let length = <BigSize as Readable>::read(&mut self.data).unwrap().0;
256                         let offset = self.data.position();
257                         let end = offset + length;
258
259                         let _value = &self.data.get_ref()[offset as usize..end as usize];
260                         let record_bytes = &self.data.get_ref()[start as usize..end as usize];
261
262                         self.data.set_position(end);
263
264                         Some(TlvRecord { r#type, type_bytes, record_bytes })
265                 } else {
266                         None
267                 }
268         }
269 }
270
271 /// Encoding for a pre-serialized TLV stream that excludes any signature TLV records.
272 ///
273 /// Panics if the wrapped bytes are not a well-formed TLV stream.
274 pub(super) struct WithoutSignatures<'a>(pub &'a [u8]);
275
276 impl<'a> Writeable for WithoutSignatures<'a> {
277         #[inline]
278         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
279                 let tlv_stream = TlvStream::new(self.0);
280                 for record in tlv_stream.skip_signatures() {
281                         writer.write_all(record.record_bytes)?;
282                 }
283                 Ok(())
284         }
285 }
286
287 #[cfg(test)]
288 mod tests {
289         use super::{SIGNATURE_TYPES, TlvStream, WithoutSignatures};
290
291         use bitcoin::hashes::{Hash, sha256};
292         use bitcoin::hashes::hex::FromHex;
293         use bitcoin::secp256k1::{KeyPair, Message, Secp256k1, SecretKey};
294         use bitcoin::secp256k1::schnorr::Signature;
295         use crate::offers::offer::{Amount, OfferBuilder};
296         use crate::offers::invoice_request::{InvoiceRequest, UnsignedInvoiceRequest};
297         use crate::offers::parse::Bech32Encode;
298         use crate::offers::test_utils::{payer_pubkey, recipient_pubkey};
299         use crate::util::ser::Writeable;
300
301         #[test]
302         fn calculates_merkle_root_hash() {
303                 // BOLT 12 test vectors
304                 macro_rules! tlv1 { () => { "010203e8" } }
305                 macro_rules! tlv2 { () => { "02080000010000020003" } }
306                 macro_rules! tlv3 { () => { "03310266e4598d1d3c415f572a8488830b60f7e744ed9235eb0b1ba93283b315c0351800000000000000010000000000000002" } }
307                 assert_eq!(
308                         super::root_hash(&<Vec<u8>>::from_hex(tlv1!()).unwrap()),
309                         sha256::Hash::from_slice(&<Vec<u8>>::from_hex("b013756c8fee86503a0b4abdab4cddeb1af5d344ca6fc2fa8b6c08938caa6f93").unwrap()).unwrap(),
310                 );
311                 assert_eq!(
312                         super::root_hash(&<Vec<u8>>::from_hex(concat!(tlv1!(), tlv2!())).unwrap()),
313                         sha256::Hash::from_slice(&<Vec<u8>>::from_hex("c3774abbf4815aa54ccaa026bff6581f01f3be5fe814c620a252534f434bc0d1").unwrap()).unwrap(),
314                 );
315                 assert_eq!(
316                         super::root_hash(&<Vec<u8>>::from_hex(concat!(tlv1!(), tlv2!(), tlv3!())).unwrap()),
317                         sha256::Hash::from_slice(&<Vec<u8>>::from_hex("ab2e79b1283b0b31e0b035258de23782df6b89a38cfa7237bde69aed1a658c5d").unwrap()).unwrap(),
318                 );
319         }
320
321         #[test]
322         fn calculates_merkle_root_hash_from_invoice_request() {
323                 let secp_ctx = Secp256k1::new();
324                 let recipient_pubkey = {
325                         let secret_key = SecretKey::from_slice(&<Vec<u8>>::from_hex("4141414141414141414141414141414141414141414141414141414141414141").unwrap()).unwrap();
326                         KeyPair::from_secret_key(&secp_ctx, &secret_key).public_key()
327                 };
328                 let payer_keys = {
329                         let secret_key = SecretKey::from_slice(&<Vec<u8>>::from_hex("4242424242424242424242424242424242424242424242424242424242424242").unwrap()).unwrap();
330                         KeyPair::from_secret_key(&secp_ctx, &secret_key)
331                 };
332
333                 // BOLT 12 test vectors
334                 let invoice_request = OfferBuilder::new("A Mathematical Treatise".into(), recipient_pubkey)
335                         .amount(Amount::Currency { iso4217_code: *b"USD", amount: 100 })
336                         .build_unchecked()
337                         .request_invoice(vec![0; 8], payer_keys.public_key()).unwrap()
338                         .build_unchecked()
339                         .sign(|message: &UnsignedInvoiceRequest|
340                                 Ok(secp_ctx.sign_schnorr_no_aux_rand(message.as_ref().as_digest(), &payer_keys))
341                         )
342                         .unwrap();
343                 assert_eq!(
344                         invoice_request.to_string(),
345                         "lnr1qqyqqqqqqqqqqqqqqcp4256ypqqkgzshgysy6ct5dpjk6ct5d93kzmpq23ex2ct5d9ek293pqthvwfzadd7jejes8q9lhc4rvjxd022zv5l44g6qah82ru5rdpnpjkppqvjx204vgdzgsqpvcp4mldl3plscny0rt707gvpdh6ndydfacz43euzqhrurageg3n7kafgsek6gz3e9w52parv8gs2hlxzk95tzeswywffxlkeyhml0hh46kndmwf4m6xma3tkq2lu04qz3slje2rfthc89vss",
346                 );
347                 assert_eq!(
348                         super::root_hash(&invoice_request.bytes[..]),
349                         sha256::Hash::from_slice(&<Vec<u8>>::from_hex("608407c18ad9a94d9ea2bcdbe170b6c20c462a7833a197621c916f78cf18e624").unwrap()).unwrap(),
350                 );
351                 assert_eq!(
352                         invoice_request.signature(),
353                         Signature::from_slice(&<Vec<u8>>::from_hex("b8f83ea3288cfd6ea510cdb481472575141e8d8744157f98562d162cc1c472526fdb24befefbdebab4dbb726bbd1b7d8aec057f8fa805187e5950d2bbe0e5642").unwrap()).unwrap(),
354                 );
355         }
356
357         #[test]
358         fn compute_tagged_hash() {
359                 let unsigned_invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
360                         .amount_msats(1000)
361                         .build().unwrap()
362                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
363                         .payer_note("bar".into())
364                         .build().unwrap();
365
366                 // Simply test that we can grab the tag and merkle root exposed by the accessor
367                 // functions, then use them to succesfully compute a tagged hash.
368                 let tagged_hash = unsigned_invoice_request.as_ref();
369                 let expected_digest = unsigned_invoice_request.as_ref().as_digest();
370                 let tag = sha256::Hash::hash(tagged_hash.tag().as_bytes());
371                 let actual_digest = Message::from_slice(super::tagged_hash(tag, tagged_hash.merkle_root()).as_byte_array())
372                         .unwrap();
373                 assert_eq!(*expected_digest, actual_digest);
374         }
375
376         #[test]
377         fn skips_encoding_signature_tlv_records() {
378                 let secp_ctx = Secp256k1::new();
379                 let recipient_pubkey = {
380                         let secret_key = SecretKey::from_slice(&[41; 32]).unwrap();
381                         KeyPair::from_secret_key(&secp_ctx, &secret_key).public_key()
382                 };
383                 let payer_keys = {
384                         let secret_key = SecretKey::from_slice(&[42; 32]).unwrap();
385                         KeyPair::from_secret_key(&secp_ctx, &secret_key)
386                 };
387
388                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey)
389                         .amount_msats(100)
390                         .build_unchecked()
391                         .request_invoice(vec![0; 8], payer_keys.public_key()).unwrap()
392                         .build_unchecked()
393                         .sign(|message: &UnsignedInvoiceRequest|
394                                 Ok(secp_ctx.sign_schnorr_no_aux_rand(message.as_ref().as_digest(), &payer_keys))
395                         )
396                         .unwrap();
397
398                 let mut bytes_without_signature = Vec::new();
399                 WithoutSignatures(&invoice_request.bytes).write(&mut bytes_without_signature).unwrap();
400
401                 assert_ne!(bytes_without_signature, invoice_request.bytes);
402                 assert_eq!(
403                         TlvStream::new(&bytes_without_signature).count(),
404                         TlvStream::new(&invoice_request.bytes).count() - 1,
405                 );
406         }
407
408         #[test]
409         fn iterates_over_tlv_stream_range() {
410                 let secp_ctx = Secp256k1::new();
411                 let recipient_pubkey = {
412                         let secret_key = SecretKey::from_slice(&[41; 32]).unwrap();
413                         KeyPair::from_secret_key(&secp_ctx, &secret_key).public_key()
414                 };
415                 let payer_keys = {
416                         let secret_key = SecretKey::from_slice(&[42; 32]).unwrap();
417                         KeyPair::from_secret_key(&secp_ctx, &secret_key)
418                 };
419
420                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey)
421                         .amount_msats(100)
422                         .build_unchecked()
423                         .request_invoice(vec![0; 8], payer_keys.public_key()).unwrap()
424                         .build_unchecked()
425                         .sign(|message: &UnsignedInvoiceRequest|
426                                 Ok(secp_ctx.sign_schnorr_no_aux_rand(message.as_ref().as_digest(), &payer_keys))
427                         )
428                         .unwrap();
429
430                 let tlv_stream = TlvStream::new(&invoice_request.bytes).range(0..1)
431                         .chain(TlvStream::new(&invoice_request.bytes).range(1..80))
432                         .chain(TlvStream::new(&invoice_request.bytes).range(80..160))
433                         .chain(TlvStream::new(&invoice_request.bytes).range(160..240))
434                         .chain(TlvStream::new(&invoice_request.bytes).range(SIGNATURE_TYPES))
435                         .map(|r| r.record_bytes.to_vec())
436                         .flatten()
437                         .collect::<Vec<u8>>();
438
439                 assert_eq!(tlv_stream, invoice_request.bytes);
440         }
441
442         impl AsRef<[u8]> for InvoiceRequest {
443                 fn as_ref(&self) -> &[u8] {
444                         &self.bytes
445                 }
446         }
447
448         impl Bech32Encode for InvoiceRequest {
449                 const BECH32_HRP: &'static str = "lnr";
450         }
451
452         impl core::fmt::Display for InvoiceRequest {
453                 fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
454                         self.fmt_bech32_str(f)
455                 }
456         }
457 }