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