Skip to content

Commit 55bf814

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 f2c6779 commit 55bf814

File tree

2 files changed

+139
-0
lines changed

2 files changed

+139
-0
lines changed

lightning/src/offers/merkle.rs

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

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)