Skip to content

Commit 0f60c81

Browse files
committed
Merkle root hash computation
Offers uses a merkle root hash construction for signature calculation and verification. Add a submodule implementing this so that it can be used when parsing and signing invoice_request and invoice messages.
1 parent 2e46700 commit 0f60c81

File tree

2 files changed

+140
-0
lines changed

2 files changed

+140
-0
lines changed

lightning/src/offers/merkle.rs

Lines changed: 139 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,139 @@
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 crate::io;
14+
use crate::util::ser::{BigSize, Readable};
15+
16+
use crate::prelude::*;
17+
18+
/// Valid type range for signature TLV records.
19+
const SIGNATURE_TYPES: core::ops::RangeInclusive<u64> = 240..=1000;
20+
21+
/// Computes a merkle root hash for the given data, which must be a well-formed TLV stream
22+
/// containing at least one TLV record.
23+
fn root_hash(data: &[u8]) -> sha256::Hash {
24+
let mut tlv_stream = TlvStream::new(&data[..]).peekable();
25+
let nonce_tag = tagged_hash_engine(sha256::Hash::from_engine({
26+
let mut engine = sha256::Hash::engine();
27+
engine.input("LnNonce".as_bytes());
28+
engine.input(tlv_stream.peek().unwrap().type_bytes);
29+
engine
30+
}));
31+
let leaf_tag = tagged_hash_engine(sha256::Hash::hash("LnLeaf".as_bytes()));
32+
let branch_tag = tagged_hash_engine(sha256::Hash::hash("LnBranch".as_bytes()));
33+
34+
let mut leaves = Vec::new();
35+
for record in tlv_stream {
36+
if !SIGNATURE_TYPES.contains(&record.r#type.0) {
37+
leaves.push(tagged_hash_from_engine(leaf_tag.clone(), &record));
38+
leaves.push(tagged_hash_from_engine(nonce_tag.clone(), &record.type_bytes));
39+
}
40+
}
41+
42+
// Calculate the merkle root hash in place.
43+
let num_leaves = leaves.len();
44+
for level in 0.. {
45+
let step = 2 << level;
46+
let offset = step / 2;
47+
if offset >= num_leaves {
48+
break;
49+
}
50+
51+
for (i, j) in (0..num_leaves).step_by(step).zip((offset..num_leaves).step_by(step)) {
52+
leaves[i] = tagged_branch_hash_from_engine(branch_tag.clone(), leaves[i], leaves[j]);
53+
}
54+
}
55+
56+
*leaves.first().unwrap()
57+
}
58+
59+
fn tagged_hash<T: AsRef<[u8]>>(tag: sha256::Hash, msg: T) -> sha256::Hash {
60+
let engine = tagged_hash_engine(tag);
61+
tagged_hash_from_engine(engine, msg)
62+
}
63+
64+
fn tagged_hash_engine(tag: sha256::Hash) -> sha256::HashEngine {
65+
let mut engine = sha256::Hash::engine();
66+
engine.input(tag.as_ref());
67+
engine.input(tag.as_ref());
68+
engine
69+
}
70+
71+
fn tagged_hash_from_engine<T: AsRef<[u8]>>(mut engine: sha256::HashEngine, msg: T) -> sha256::Hash {
72+
engine.input(msg.as_ref());
73+
sha256::Hash::from_engine(engine)
74+
}
75+
76+
fn tagged_branch_hash_from_engine(
77+
mut engine: sha256::HashEngine, leaf1: sha256::Hash, leaf2: sha256::Hash,
78+
) -> sha256::Hash {
79+
if leaf1 < leaf2 {
80+
engine.input(leaf1.as_ref());
81+
engine.input(leaf2.as_ref());
82+
} else {
83+
engine.input(leaf2.as_ref());
84+
engine.input(leaf1.as_ref());
85+
};
86+
sha256::Hash::from_engine(engine)
87+
}
88+
89+
/// [`Iterator`] over a sequence of bytes yielding [`TlvRecord`]s. The input is assumed to be a
90+
/// well-formed TLV stream.
91+
struct TlvStream<'a> {
92+
data: io::Cursor<&'a [u8]>,
93+
}
94+
95+
impl<'a> TlvStream<'a> {
96+
fn new(data: &'a [u8]) -> Self {
97+
Self {
98+
data: io::Cursor::new(data),
99+
}
100+
}
101+
}
102+
103+
/// A slice into a [`TlvStream`] for a record.
104+
struct TlvRecord<'a> {
105+
r#type: BigSize,
106+
type_bytes: &'a [u8],
107+
data: &'a [u8],
108+
}
109+
110+
impl AsRef<[u8]> for TlvRecord<'_> {
111+
fn as_ref(&self) -> &[u8] { &self.data }
112+
}
113+
114+
impl<'a> Iterator for TlvStream<'a> {
115+
type Item = TlvRecord<'a>;
116+
117+
fn next(&mut self) -> Option<Self::Item> {
118+
if self.data.position() < self.data.get_ref().len() as u64 {
119+
let start = self.data.position();
120+
121+
let r#type: BigSize = Readable::read(&mut self.data).unwrap();
122+
let offset = self.data.position();
123+
let type_bytes = &self.data.get_ref()[start as usize..offset as usize];
124+
125+
let length: BigSize = Readable::read(&mut self.data).unwrap();
126+
let offset = self.data.position();
127+
let end = offset + length.0;
128+
129+
let _value = &self.data.get_ref()[offset as usize..end as usize];
130+
let data = &self.data.get_ref()[start as usize..end as usize];
131+
132+
self.data.set_position(end);
133+
134+
Some(TlvRecord { r#type, type_bytes, data })
135+
} else {
136+
None
137+
}
138+
}
139+
}

lightning/src/offers/mod.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313
//! Offers are a flexible protocol for Lightning payments.
1414
1515
pub mod invoice_request;
16+
mod merkle;
1617
pub mod offer;
1718
pub mod parse;
1819
mod payer;

0 commit comments

Comments
 (0)