1 // This file is Copyright its original authors, visible in version control
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
10 //! Tagged hashes for use in signature calculation and verification.
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;
17 use crate::util::ser::{BigSize, Readable, Writeable, Writer};
19 use crate::prelude::*;
21 /// Valid type range for signature TLV records.
22 const SIGNATURE_TYPES: core::ops::RangeInclusive<u64> = 240..=1000;
24 tlv_stream!(SignatureTlvStream, SignatureTlvStreamRef, SIGNATURE_TYPES, {
25 (240, signature: Signature),
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].
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(Debug, PartialEq)]
34 pub struct TaggedHash(Message);
37 /// Creates a tagged hash with the given parameters.
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 Self(message_digest(tag, tlv_stream))
44 /// Returns the digest to sign.
45 pub fn as_digest(&self) -> &Message {
50 impl AsRef<TaggedHash> for TaggedHash {
51 fn as_ref(&self) -> &TaggedHash {
56 /// Error when signing messages.
57 #[derive(Debug, PartialEq)]
58 pub enum SignError<E> {
59 /// User-defined error when signing the message.
61 /// Error when verifying the produced signature using the given pubkey.
62 Verification(secp256k1::Error),
65 /// Signs a [`TaggedHash`] computed over the merkle root of `message`'s TLV stream, checking if it
66 /// can be verified with the supplied `pubkey`.
68 /// Since `message` is any type that implements [`AsRef<TaggedHash>`], `sign` may be a closure that
69 /// takes a message such as [`Bolt12Invoice`] or [`InvoiceRequest`]. This allows further message
70 /// verification before signing its [`TaggedHash`].
72 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
73 /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
74 pub(super) fn sign_message<F, E, T>(
75 sign: F, message: &T, pubkey: PublicKey,
76 ) -> Result<Signature, SignError<E>>
78 F: FnOnce(&T) -> Result<Signature, E>,
81 let signature = sign(message).map_err(|e| SignError::Signing(e))?;
83 let digest = message.as_ref().as_digest();
84 let pubkey = pubkey.into();
85 let secp_ctx = Secp256k1::verification_only();
86 secp_ctx.verify_schnorr(&signature, digest, &pubkey).map_err(|e| SignError::Verification(e))?;
91 /// Verifies the signature with a pubkey over the given bytes using a tagged hash as the message
94 /// Panics if `bytes` is not a well-formed TLV stream containing at least one TLV record.
95 pub(super) fn verify_signature(
96 signature: &Signature, tag: &str, bytes: &[u8], pubkey: PublicKey,
97 ) -> Result<(), secp256k1::Error> {
98 let digest = message_digest(tag, bytes);
99 let pubkey = pubkey.into();
100 let secp_ctx = Secp256k1::verification_only();
101 secp_ctx.verify_schnorr(signature, &digest, &pubkey)
104 pub(super) fn message_digest(tag: &str, bytes: &[u8]) -> Message {
105 let tag = sha256::Hash::hash(tag.as_bytes());
106 let merkle_root = root_hash(bytes);
107 Message::from_slice(&tagged_hash(tag, merkle_root)).unwrap()
110 /// Computes a merkle root hash for the given data, which must be a well-formed TLV stream
111 /// containing at least one TLV record.
112 fn root_hash(data: &[u8]) -> sha256::Hash {
113 let nonce_tag = tagged_hash_engine(sha256::Hash::from_engine({
114 let first_tlv_record = TlvStream::new(&data[..]).next().unwrap();
115 let mut engine = sha256::Hash::engine();
116 engine.input("LnNonce".as_bytes());
117 engine.input(first_tlv_record.record_bytes);
120 let leaf_tag = tagged_hash_engine(sha256::Hash::hash("LnLeaf".as_bytes()));
121 let branch_tag = tagged_hash_engine(sha256::Hash::hash("LnBranch".as_bytes()));
123 let mut leaves = Vec::new();
124 let tlv_stream = TlvStream::new(&data[..]);
125 for record in tlv_stream.skip_signatures() {
126 leaves.push(tagged_hash_from_engine(leaf_tag.clone(), &record.record_bytes));
127 leaves.push(tagged_hash_from_engine(nonce_tag.clone(), &record.type_bytes));
130 // Calculate the merkle root hash in place.
131 let num_leaves = leaves.len();
133 let step = 2 << level;
134 let offset = step / 2;
135 if offset >= num_leaves {
139 let left_branches = (0..num_leaves).step_by(step);
140 let right_branches = (offset..num_leaves).step_by(step);
141 for (i, j) in left_branches.zip(right_branches) {
142 leaves[i] = tagged_branch_hash_from_engine(branch_tag.clone(), leaves[i], leaves[j]);
146 *leaves.first().unwrap()
149 fn tagged_hash<T: AsRef<[u8]>>(tag: sha256::Hash, msg: T) -> sha256::Hash {
150 let engine = tagged_hash_engine(tag);
151 tagged_hash_from_engine(engine, msg)
154 fn tagged_hash_engine(tag: sha256::Hash) -> sha256::HashEngine {
155 let mut engine = sha256::Hash::engine();
156 engine.input(tag.as_ref());
157 engine.input(tag.as_ref());
161 fn tagged_hash_from_engine<T: AsRef<[u8]>>(mut engine: sha256::HashEngine, msg: T) -> sha256::Hash {
162 engine.input(msg.as_ref());
163 sha256::Hash::from_engine(engine)
166 fn tagged_branch_hash_from_engine(
167 mut engine: sha256::HashEngine, leaf1: sha256::Hash, leaf2: sha256::Hash,
170 engine.input(leaf1.as_ref());
171 engine.input(leaf2.as_ref());
173 engine.input(leaf2.as_ref());
174 engine.input(leaf1.as_ref());
176 sha256::Hash::from_engine(engine)
179 /// [`Iterator`] over a sequence of bytes yielding [`TlvRecord`]s. The input is assumed to be a
180 /// well-formed TLV stream.
182 pub(super) struct TlvStream<'a> {
183 data: io::Cursor<&'a [u8]>,
186 impl<'a> TlvStream<'a> {
187 pub fn new(data: &'a [u8]) -> Self {
189 data: io::Cursor::new(data),
193 pub fn range<T>(self, types: T) -> impl core::iter::Iterator<Item = TlvRecord<'a>>
195 T: core::ops::RangeBounds<u64> + Clone,
197 let take_range = types.clone();
198 self.skip_while(move |record| !types.contains(&record.r#type))
199 .take_while(move |record| take_range.contains(&record.r#type))
202 fn skip_signatures(self) -> core::iter::Filter<TlvStream<'a>, fn(&TlvRecord) -> bool> {
203 self.filter(|record| !SIGNATURE_TYPES.contains(&record.r#type))
207 /// A slice into a [`TlvStream`] for a record.
208 pub(super) struct TlvRecord<'a> {
209 pub(super) r#type: u64,
210 type_bytes: &'a [u8],
211 // The entire TLV record.
212 pub(super) record_bytes: &'a [u8],
215 impl<'a> Iterator for TlvStream<'a> {
216 type Item = TlvRecord<'a>;
218 fn next(&mut self) -> Option<Self::Item> {
219 if self.data.position() < self.data.get_ref().len() as u64 {
220 let start = self.data.position();
222 let r#type = <BigSize as Readable>::read(&mut self.data).unwrap().0;
223 let offset = self.data.position();
224 let type_bytes = &self.data.get_ref()[start as usize..offset as usize];
226 let length = <BigSize as Readable>::read(&mut self.data).unwrap().0;
227 let offset = self.data.position();
228 let end = offset + length;
230 let _value = &self.data.get_ref()[offset as usize..end as usize];
231 let record_bytes = &self.data.get_ref()[start as usize..end as usize];
233 self.data.set_position(end);
235 Some(TlvRecord { r#type, type_bytes, record_bytes })
242 /// Encoding for a pre-serialized TLV stream that excludes any signature TLV records.
244 /// Panics if the wrapped bytes are not a well-formed TLV stream.
245 pub(super) struct WithoutSignatures<'a>(pub &'a [u8]);
247 impl<'a> Writeable for WithoutSignatures<'a> {
249 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
250 let tlv_stream = TlvStream::new(self.0);
251 for record in tlv_stream.skip_signatures() {
252 writer.write_all(record.record_bytes)?;
260 use super::{SIGNATURE_TYPES, TlvStream, WithoutSignatures};
262 use bitcoin::hashes::{Hash, sha256};
263 use bitcoin::secp256k1::{KeyPair, Secp256k1, SecretKey};
264 use bitcoin::secp256k1::schnorr::Signature;
265 use core::convert::Infallible;
266 use crate::offers::offer::{Amount, OfferBuilder};
267 use crate::offers::invoice_request::InvoiceRequest;
268 use crate::offers::parse::Bech32Encode;
269 use crate::util::ser::Writeable;
272 fn calculates_merkle_root_hash() {
273 // BOLT 12 test vectors
274 macro_rules! tlv1 { () => { "010203e8" } }
275 macro_rules! tlv2 { () => { "02080000010000020003" } }
276 macro_rules! tlv3 { () => { "03310266e4598d1d3c415f572a8488830b60f7e744ed9235eb0b1ba93283b315c0351800000000000000010000000000000002" } }
278 super::root_hash(&hex::decode(tlv1!()).unwrap()),
279 sha256::Hash::from_slice(&hex::decode("b013756c8fee86503a0b4abdab4cddeb1af5d344ca6fc2fa8b6c08938caa6f93").unwrap()).unwrap(),
282 super::root_hash(&hex::decode(concat!(tlv1!(), tlv2!())).unwrap()),
283 sha256::Hash::from_slice(&hex::decode("c3774abbf4815aa54ccaa026bff6581f01f3be5fe814c620a252534f434bc0d1").unwrap()).unwrap(),
286 super::root_hash(&hex::decode(concat!(tlv1!(), tlv2!(), tlv3!())).unwrap()),
287 sha256::Hash::from_slice(&hex::decode("ab2e79b1283b0b31e0b035258de23782df6b89a38cfa7237bde69aed1a658c5d").unwrap()).unwrap(),
292 fn calculates_merkle_root_hash_from_invoice_request() {
293 let secp_ctx = Secp256k1::new();
294 let recipient_pubkey = {
295 let secret_key = SecretKey::from_slice(&hex::decode("4141414141414141414141414141414141414141414141414141414141414141").unwrap()).unwrap();
296 KeyPair::from_secret_key(&secp_ctx, &secret_key).public_key()
299 let secret_key = SecretKey::from_slice(&hex::decode("4242424242424242424242424242424242424242424242424242424242424242").unwrap()).unwrap();
300 KeyPair::from_secret_key(&secp_ctx, &secret_key)
303 // BOLT 12 test vectors
304 let invoice_request = OfferBuilder::new("A Mathematical Treatise".into(), recipient_pubkey)
305 .amount(Amount::Currency { iso4217_code: *b"USD", amount: 100 })
307 .request_invoice(vec![0; 8], payer_keys.public_key()).unwrap()
309 .sign::<_, Infallible>(
310 |message| Ok(secp_ctx.sign_schnorr_no_aux_rand(message.as_ref().as_digest(), &payer_keys))
314 invoice_request.to_string(),
315 "lnr1qqyqqqqqqqqqqqqqqcp4256ypqqkgzshgysy6ct5dpjk6ct5d93kzmpq23ex2ct5d9ek293pqthvwfzadd7jejes8q9lhc4rvjxd022zv5l44g6qah82ru5rdpnpjkppqvjx204vgdzgsqpvcp4mldl3plscny0rt707gvpdh6ndydfacz43euzqhrurageg3n7kafgsek6gz3e9w52parv8gs2hlxzk95tzeswywffxlkeyhml0hh46kndmwf4m6xma3tkq2lu04qz3slje2rfthc89vss",
318 super::root_hash(&invoice_request.bytes[..]),
319 sha256::Hash::from_slice(&hex::decode("608407c18ad9a94d9ea2bcdbe170b6c20c462a7833a197621c916f78cf18e624").unwrap()).unwrap(),
322 invoice_request.signature(),
323 Signature::from_slice(&hex::decode("b8f83ea3288cfd6ea510cdb481472575141e8d8744157f98562d162cc1c472526fdb24befefbdebab4dbb726bbd1b7d8aec057f8fa805187e5950d2bbe0e5642").unwrap()).unwrap(),
328 fn skips_encoding_signature_tlv_records() {
329 let secp_ctx = Secp256k1::new();
330 let recipient_pubkey = {
331 let secret_key = SecretKey::from_slice(&[41; 32]).unwrap();
332 KeyPair::from_secret_key(&secp_ctx, &secret_key).public_key()
335 let secret_key = SecretKey::from_slice(&[42; 32]).unwrap();
336 KeyPair::from_secret_key(&secp_ctx, &secret_key)
339 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey)
342 .request_invoice(vec![0; 8], payer_keys.public_key()).unwrap()
344 .sign::<_, Infallible>(
345 |message| Ok(secp_ctx.sign_schnorr_no_aux_rand(message.as_ref().as_digest(), &payer_keys))
349 let mut bytes_without_signature = Vec::new();
350 WithoutSignatures(&invoice_request.bytes).write(&mut bytes_without_signature).unwrap();
352 assert_ne!(bytes_without_signature, invoice_request.bytes);
354 TlvStream::new(&bytes_without_signature).count(),
355 TlvStream::new(&invoice_request.bytes).count() - 1,
360 fn iterates_over_tlv_stream_range() {
361 let secp_ctx = Secp256k1::new();
362 let recipient_pubkey = {
363 let secret_key = SecretKey::from_slice(&[41; 32]).unwrap();
364 KeyPair::from_secret_key(&secp_ctx, &secret_key).public_key()
367 let secret_key = SecretKey::from_slice(&[42; 32]).unwrap();
368 KeyPair::from_secret_key(&secp_ctx, &secret_key)
371 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey)
374 .request_invoice(vec![0; 8], payer_keys.public_key()).unwrap()
376 .sign::<_, Infallible>(
377 |message| Ok(secp_ctx.sign_schnorr_no_aux_rand(message.as_ref().as_digest(), &payer_keys))
381 let tlv_stream = TlvStream::new(&invoice_request.bytes).range(0..1)
382 .chain(TlvStream::new(&invoice_request.bytes).range(1..80))
383 .chain(TlvStream::new(&invoice_request.bytes).range(80..160))
384 .chain(TlvStream::new(&invoice_request.bytes).range(160..240))
385 .chain(TlvStream::new(&invoice_request.bytes).range(SIGNATURE_TYPES))
386 .map(|r| r.record_bytes.to_vec())
388 .collect::<Vec<u8>>();
390 assert_eq!(tlv_stream, invoice_request.bytes);
393 impl AsRef<[u8]> for InvoiceRequest {
394 fn as_ref(&self) -> &[u8] {
399 impl Bech32Encode for InvoiceRequest {
400 const BECH32_HRP: &'static str = "lnr";
403 impl core::fmt::Display for InvoiceRequest {
404 fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
405 self.fmt_bech32_str(f)