Skip to content

Commit e6c9228

Browse files
authored
Merge pull request #844 from sr-gi/843-ln-signing
Adds lightning message signing/verification/pk_recovery
2 parents 52f1d45 + 7bcf5a1 commit e6c9228

File tree

8 files changed

+425
-0
lines changed

8 files changed

+425
-0
lines changed

fuzz/src/bin/gen_target.sh

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ GEN_TEST chanmon_consistency
1111
GEN_TEST full_stack
1212
GEN_TEST peer_crypt
1313
GEN_TEST router
14+
GEN_TEST zbase32
1415

1516
GEN_TEST msg_accept_channel msg_targets::
1617
GEN_TEST msg_announcement_signatures msg_targets::

fuzz/src/bin/zbase32_target.rs

Lines changed: 102 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,102 @@
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+
// This file is auto-generated by gen_target.sh based on target_template.txt
11+
// To modify it, modify target_template.txt and run gen_target.sh instead.
12+
13+
#![cfg_attr(feature = "libfuzzer_fuzz", no_main)]
14+
15+
extern crate lightning_fuzz;
16+
use lightning_fuzz::zbase32::*;
17+
18+
#[cfg(feature = "afl")]
19+
#[macro_use] extern crate afl;
20+
#[cfg(feature = "afl")]
21+
fn main() {
22+
fuzz!(|data| {
23+
zbase32_run(data.as_ptr(), data.len());
24+
});
25+
}
26+
27+
#[cfg(feature = "honggfuzz")]
28+
#[macro_use] extern crate honggfuzz;
29+
#[cfg(feature = "honggfuzz")]
30+
fn main() {
31+
loop {
32+
fuzz!(|data| {
33+
zbase32_run(data.as_ptr(), data.len());
34+
});
35+
}
36+
}
37+
38+
#[cfg(feature = "libfuzzer_fuzz")]
39+
#[macro_use] extern crate libfuzzer_sys;
40+
#[cfg(feature = "libfuzzer_fuzz")]
41+
fuzz_target!(|data: &[u8]| {
42+
zbase32_run(data.as_ptr(), data.len());
43+
});
44+
45+
#[cfg(feature = "stdin_fuzz")]
46+
fn main() {
47+
use std::io::Read;
48+
49+
let mut data = Vec::with_capacity(8192);
50+
std::io::stdin().read_to_end(&mut data).unwrap();
51+
zbase32_run(data.as_ptr(), data.len());
52+
}
53+
54+
#[test]
55+
fn run_test_cases() {
56+
use std::fs;
57+
use std::io::Read;
58+
use lightning_fuzz::utils::test_logger::StringBuffer;
59+
60+
use std::sync::{atomic, Arc};
61+
{
62+
let data: Vec<u8> = vec![0];
63+
zbase32_run(data.as_ptr(), data.len());
64+
}
65+
let mut threads = Vec::new();
66+
let threads_running = Arc::new(atomic::AtomicUsize::new(0));
67+
if let Ok(tests) = fs::read_dir("test_cases/zbase32") {
68+
for test in tests {
69+
let mut data: Vec<u8> = Vec::new();
70+
let path = test.unwrap().path();
71+
fs::File::open(&path).unwrap().read_to_end(&mut data).unwrap();
72+
threads_running.fetch_add(1, atomic::Ordering::AcqRel);
73+
74+
let thread_count_ref = Arc::clone(&threads_running);
75+
let main_thread_ref = std::thread::current();
76+
threads.push((path.file_name().unwrap().to_str().unwrap().to_string(),
77+
std::thread::spawn(move || {
78+
let string_logger = StringBuffer::new();
79+
80+
let panic_logger = string_logger.clone();
81+
let res = if ::std::panic::catch_unwind(move || {
82+
zbase32_test(&data, panic_logger);
83+
}).is_err() {
84+
Some(string_logger.into_string())
85+
} else { None };
86+
thread_count_ref.fetch_sub(1, atomic::Ordering::AcqRel);
87+
main_thread_ref.unpark();
88+
res
89+
})
90+
));
91+
while threads_running.load(atomic::Ordering::Acquire) > 32 {
92+
std::thread::park();
93+
}
94+
}
95+
}
96+
for (test, thread) in threads.drain(..) {
97+
if let Some(output) = thread.join().unwrap() {
98+
println!("Output of {}:\n{}", test, output);
99+
panic!();
100+
}
101+
}
102+
}

fuzz/src/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,5 +18,6 @@ pub mod chanmon_consistency;
1818
pub mod full_stack;
1919
pub mod peer_crypt;
2020
pub mod router;
21+
pub mod zbase32;
2122

2223
pub mod msg_targets;

fuzz/src/zbase32.rs

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
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+
use lightning::util::zbase32;
11+
12+
use utils::test_logger;
13+
14+
#[inline]
15+
pub fn do_test(data: &[u8]) {
16+
let res = zbase32::encode(data);
17+
assert_eq!(&zbase32::decode(&res).unwrap()[..], data);
18+
19+
if let Ok(s) = std::str::from_utf8(data) {
20+
if let Ok(decoded) = zbase32::decode(s) {
21+
assert_eq!(&zbase32::encode(&decoded), &s.to_ascii_lowercase());
22+
}
23+
}
24+
}
25+
26+
pub fn zbase32_test<Out: test_logger::Output>(data: &[u8], _out: Out) {
27+
do_test(data);
28+
}
29+
30+
#[no_mangle]
31+
pub extern "C" fn zbase32_run(data: *const u8, datalen: usize) {
32+
do_test(unsafe { std::slice::from_raw_parts(data, datalen) });
33+
}

fuzz/targets.h

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ void chanmon_consistency_run(const unsigned char* data, size_t data_len);
44
void full_stack_run(const unsigned char* data, size_t data_len);
55
void peer_crypt_run(const unsigned char* data, size_t data_len);
66
void router_run(const unsigned char* data, size_t data_len);
7+
void zbase32_run(const unsigned char* data, size_t data_len);
78
void msg_accept_channel_run(const unsigned char* data, size_t data_len);
89
void msg_announcement_signatures_run(const unsigned char* data, size_t data_len);
910
void msg_channel_reestablish_run(const unsigned char* data, size_t data_len);
Lines changed: 140 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,140 @@
1+
// This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
2+
// or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
3+
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
4+
// You may not use this file except in accordance with one or both of these
5+
// licenses.
6+
7+
//! Lightning message signing and verification lives here. These tools can be used to sign messages using the node's
8+
//! secret so receivers are sure that they come from you. You can also use this to verify that a given message comes
9+
//! from a specific node.
10+
//! Furthermore, these tools can be used to sign / verify messages using ephemeral keys not tied to node's identities.
11+
//!
12+
//! Note this is not part of the specs, but follows lnd's signing and verifying protocol, which can is defined as follows:
13+
//!
14+
//! signature = zbase32(SigRec(sha256d(("Lightning Signed Message:" + msg)))
15+
//! zbase32 from https://philzimmermann.com/docs/human-oriented-base-32-encoding.txt
16+
//! SigRec has first byte 31 + recovery id, followed by 64 byte sig.
17+
//!
18+
//! This implementation is compatible with both lnd's and c-lightning's
19+
//!
20+
//! https://lightning.readthedocs.io/lightning-signmessage.7.html
21+
//! https://api.lightning.community/#signmessage
22+
23+
use crate::util::zbase32;
24+
use bitcoin::hashes::{sha256d, Hash};
25+
use bitcoin::secp256k1::recovery::{RecoverableSignature, RecoveryId};
26+
use bitcoin::secp256k1::{Error, Message, PublicKey, Secp256k1, SecretKey};
27+
28+
static LN_MESSAGE_PREFIX: &[u8] = b"Lightning Signed Message:";
29+
30+
fn sigrec_encode(sig_rec: RecoverableSignature) -> Vec<u8> {
31+
let (rid, rsig) = sig_rec.serialize_compact();
32+
let prefix = rid.to_i32() as u8 + 31;
33+
34+
[&[prefix], &rsig[..]].concat()
35+
}
36+
37+
fn sigrec_decode(sig_rec: Vec<u8>) -> Result<RecoverableSignature, Error> {
38+
let rsig = &sig_rec[1..];
39+
let rid = sig_rec[0] as i32 - 31;
40+
41+
match RecoveryId::from_i32(rid) {
42+
Ok(x) => RecoverableSignature::from_compact(rsig, x),
43+
Err(e) => Err(e)
44+
}
45+
}
46+
47+
/// Creates a digital signature of a message given a SecretKey, like the node's secret.
48+
/// A receiver knowing the PublicKey (e.g. the node's id) and the message can be sure that the signature was generated by the caller.
49+
/// Signatures are EC recoverable, meaning that given the message and the signature the PublicKey of the signer can be extracted.
50+
pub fn sign(msg: &[u8], sk: SecretKey) -> Result<String, Error> {
51+
let secp_ctx = Secp256k1::signing_only();
52+
let msg_hash = sha256d::Hash::hash(&[LN_MESSAGE_PREFIX, msg].concat());
53+
54+
let sig = secp_ctx.sign_recoverable(&Message::from_slice(&msg_hash)?, &sk);
55+
Ok(zbase32::encode(&sigrec_encode(sig)))
56+
}
57+
58+
/// Recovers the PublicKey of the signer of the message given the message and the signature.
59+
pub fn recover_pk(msg: &[u8], sig: &str) -> Result<PublicKey, Error> {
60+
let secp_ctx = Secp256k1::verification_only();
61+
let msg_hash = sha256d::Hash::hash(&[LN_MESSAGE_PREFIX, msg].concat());
62+
63+
match zbase32::decode(&sig) {
64+
Ok(sig_rec) => {
65+
match sigrec_decode(sig_rec) {
66+
Ok(sig) => secp_ctx.recover(&Message::from_slice(&msg_hash)?, &sig),
67+
Err(e) => Err(e)
68+
}
69+
},
70+
Err(_) => Err(Error::InvalidSignature)
71+
}
72+
}
73+
74+
/// Verifies a message was signed by a PrivateKey that derives to a given PublicKey, given a message, a signature,
75+
/// and the PublicKey.
76+
pub fn verify(msg: &[u8], sig: &str, pk: PublicKey) -> bool {
77+
match recover_pk(msg, sig) {
78+
Ok(x) => x == pk,
79+
Err(_) => false
80+
}
81+
}
82+
83+
#[cfg(test)]
84+
mod test {
85+
use std::str::FromStr;
86+
use util::message_signing::{sign, recover_pk, verify};
87+
use bitcoin::secp256k1::key::ONE_KEY;
88+
use bitcoin::secp256k1::{PublicKey, Secp256k1};
89+
90+
#[test]
91+
fn test_sign() {
92+
let message = "test message";
93+
let zbase32_sig = sign(message.as_bytes(), ONE_KEY);
94+
95+
assert_eq!(zbase32_sig.unwrap(), "d9tibmnic9t5y41hg7hkakdcra94akas9ku3rmmj4ag9mritc8ok4p5qzefs78c9pqfhpuftqqzhydbdwfg7u6w6wdxcqpqn4sj4e73e")
96+
}
97+
98+
#[test]
99+
fn test_recover_pk() {
100+
let message = "test message";
101+
let sig = "d9tibmnic9t5y41hg7hkakdcra94akas9ku3rmmj4ag9mritc8ok4p5qzefs78c9pqfhpuftqqzhydbdwfg7u6w6wdxcqpqn4sj4e73e";
102+
let pk = recover_pk(message.as_bytes(), sig);
103+
104+
assert_eq!(pk.unwrap(), PublicKey::from_secret_key(&Secp256k1::signing_only(), &ONE_KEY))
105+
}
106+
107+
#[test]
108+
fn test_verify() {
109+
let message = "another message";
110+
let sig = sign(message.as_bytes(), ONE_KEY).unwrap();
111+
let pk = PublicKey::from_secret_key(&Secp256k1::signing_only(), &ONE_KEY);
112+
113+
assert!(verify(message.as_bytes(), &sig, pk))
114+
}
115+
116+
#[test]
117+
fn test_verify_ground_truth_ish() {
118+
// There are no standard tests vectors for Sign/Verify, using the same tests vectors as c-lightning to see if they are compatible.
119+
// Taken from https://github.com/ElementsProject/lightning/blob/1275af6fbb02460c8eb2f00990bb0ef9179ce8f3/tests/test_misc.py#L1925-L1938
120+
121+
let corpus = [
122+
["@bitconner",
123+
"is this compatible?",
124+
"rbgfioj114mh48d8egqx8o9qxqw4fmhe8jbeeabdioxnjk8z3t1ma1hu1fiswpakgucwwzwo6ofycffbsqusqdimugbh41n1g698hr9t",
125+
"02b80cabdf82638aac86948e4c06e82064f547768dcef977677b9ea931ea75bab5"],
126+
["@duck1123",
127+
"hi",
128+
"rnrphcjswusbacjnmmmrynh9pqip7sy5cx695h6mfu64iac6qmcmsd8xnsyczwmpqp9shqkth3h4jmkgyqu5z47jfn1q7gpxtaqpx4xg",
129+
"02de60d194e1ca5947b59fe8e2efd6aadeabfb67f2e89e13ae1a799c1e08e4a43b"],
130+
["@jochemin",
131+
"hi",
132+
"ry8bbsopmduhxy3dr5d9ekfeabdpimfx95kagdem7914wtca79jwamtbw4rxh69hg7n6x9ty8cqk33knbxaqftgxsfsaeprxkn1k48p3",
133+
"022b8ece90ee891cbcdac0c1cc6af46b73c47212d8defbce80265ac81a6b794931"],
134+
];
135+
136+
for c in &corpus {
137+
assert!(verify(c[1].as_bytes(), c[2], PublicKey::from_str(c[3]).unwrap()))
138+
}
139+
}
140+
}

lightning/src/util/mod.rs

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,9 +15,14 @@ pub(crate) mod fuzz_wrappers;
1515
pub mod events;
1616
pub mod errors;
1717
pub mod ser;
18+
pub mod message_signing;
1819

1920
pub(crate) mod byte_utils;
2021
pub(crate) mod chacha20;
22+
#[cfg(feature = "fuzztarget")]
23+
pub mod zbase32;
24+
#[cfg(not(feature = "fuzztarget"))]
25+
pub(crate) mod zbase32;
2126
#[cfg(not(feature = "fuzztarget"))]
2227
pub(crate) mod poly1305;
2328
pub(crate) mod chacha20poly1305rfc;

0 commit comments

Comments
 (0)