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