Skip to content

Commit e049e97

Browse files
committed
Fuzz test for parsing InvoiceRequest
An invoice request is serialized as a TLV stream and encoded as bytes. Add a fuzz test that parses the TLV stream and deserializes the underlying InvoiceRequest. Then compare the original bytes with those obtained by re-serializing the InvoiceRequest.
1 parent 9a65709 commit e049e97

File tree

6 files changed

+235
-2
lines changed

6 files changed

+235
-2
lines changed

fuzz/src/bin/gen_target.sh

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ GEN_TEST() {
99
GEN_TEST chanmon_deser
1010
GEN_TEST chanmon_consistency
1111
GEN_TEST full_stack
12+
GEN_TEST invoice_request_deser
1213
GEN_TEST offer_deser
1314
GEN_TEST onion_message
1415
GEN_TEST peer_crypt
Lines changed: 113 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,113 @@
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+
#[cfg(not(fuzzing))]
16+
compile_error!("Fuzz targets need cfg=fuzzing");
17+
18+
extern crate lightning_fuzz;
19+
use lightning_fuzz::invoice_request_deser::*;
20+
21+
#[cfg(feature = "afl")]
22+
#[macro_use] extern crate afl;
23+
#[cfg(feature = "afl")]
24+
fn main() {
25+
fuzz!(|data| {
26+
invoice_request_deser_run(data.as_ptr(), data.len());
27+
});
28+
}
29+
30+
#[cfg(feature = "honggfuzz")]
31+
#[macro_use] extern crate honggfuzz;
32+
#[cfg(feature = "honggfuzz")]
33+
fn main() {
34+
loop {
35+
fuzz!(|data| {
36+
invoice_request_deser_run(data.as_ptr(), data.len());
37+
});
38+
}
39+
}
40+
41+
#[cfg(feature = "libfuzzer_fuzz")]
42+
#[macro_use] extern crate libfuzzer_sys;
43+
#[cfg(feature = "libfuzzer_fuzz")]
44+
fuzz_target!(|data: &[u8]| {
45+
invoice_request_deser_run(data.as_ptr(), data.len());
46+
});
47+
48+
#[cfg(feature = "stdin_fuzz")]
49+
fn main() {
50+
use std::io::Read;
51+
52+
let mut data = Vec::with_capacity(8192);
53+
std::io::stdin().read_to_end(&mut data).unwrap();
54+
invoice_request_deser_run(data.as_ptr(), data.len());
55+
}
56+
57+
#[test]
58+
fn run_test_cases() {
59+
use std::fs;
60+
use std::io::Read;
61+
use lightning_fuzz::utils::test_logger::StringBuffer;
62+
63+
use std::sync::{atomic, Arc};
64+
{
65+
let data: Vec<u8> = vec![0];
66+
invoice_request_deser_run(data.as_ptr(), data.len());
67+
}
68+
let mut threads = Vec::new();
69+
let threads_running = Arc::new(atomic::AtomicUsize::new(0));
70+
if let Ok(tests) = fs::read_dir("test_cases/invoice_request_deser") {
71+
for test in tests {
72+
let mut data: Vec<u8> = Vec::new();
73+
let path = test.unwrap().path();
74+
fs::File::open(&path).unwrap().read_to_end(&mut data).unwrap();
75+
threads_running.fetch_add(1, atomic::Ordering::AcqRel);
76+
77+
let thread_count_ref = Arc::clone(&threads_running);
78+
let main_thread_ref = std::thread::current();
79+
threads.push((path.file_name().unwrap().to_str().unwrap().to_string(),
80+
std::thread::spawn(move || {
81+
let string_logger = StringBuffer::new();
82+
83+
let panic_logger = string_logger.clone();
84+
let res = if ::std::panic::catch_unwind(move || {
85+
invoice_request_deser_test(&data, panic_logger);
86+
}).is_err() {
87+
Some(string_logger.into_string())
88+
} else { None };
89+
thread_count_ref.fetch_sub(1, atomic::Ordering::AcqRel);
90+
main_thread_ref.unpark();
91+
res
92+
})
93+
));
94+
while threads_running.load(atomic::Ordering::Acquire) > 32 {
95+
std::thread::park();
96+
}
97+
}
98+
}
99+
let mut failed_outputs = Vec::new();
100+
for (test, thread) in threads.drain(..) {
101+
if let Some(output) = thread.join().unwrap() {
102+
println!("\nOutput of {}:\n{}\n", test, output);
103+
failed_outputs.push(test);
104+
}
105+
}
106+
if !failed_outputs.is_empty() {
107+
println!("Test cases which failed: ");
108+
for case in failed_outputs {
109+
println!("{}", case);
110+
}
111+
panic!();
112+
}
113+
}

fuzz/src/invoice_request_deser.rs

Lines changed: 112 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,112 @@
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 bitcoin::secp256k1::{KeyPair, Parity, PublicKey, Secp256k1, SecretKey, self};
11+
use crate::utils::test_logger;
12+
use core::convert::{Infallible, TryFrom};
13+
use lightning::chain::keysinterface::EntropySource;
14+
use lightning::ln::PaymentHash;
15+
use lightning::ln::features::BlindedHopFeatures;
16+
use lightning::offers::invoice::{BlindedPayInfo, UnsignedInvoice};
17+
use lightning::offers::invoice_request::InvoiceRequest;
18+
use lightning::offers::parse::SemanticError;
19+
use lightning::onion_message::BlindedPath;
20+
use lightning::util::ser::Writeable;
21+
22+
#[inline]
23+
pub fn do_test<Out: test_logger::Output>(data: &[u8], _out: Out) {
24+
if let Ok(invoice_request) = InvoiceRequest::try_from(data.to_vec()) {
25+
let mut bytes = Vec::with_capacity(data.len());
26+
invoice_request.write(&mut bytes).unwrap();
27+
assert_eq!(data, bytes);
28+
29+
let secp_ctx = Secp256k1::new();
30+
let keys = KeyPair::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
31+
let mut buffer = Vec::new();
32+
33+
if let Ok(unsigned_invoice) = build_response(&invoice_request, &secp_ctx) {
34+
let signing_pubkey = unsigned_invoice.signing_pubkey();
35+
let (x_only_pubkey, _) = keys.x_only_public_key();
36+
let odd_pubkey = x_only_pubkey.public_key(Parity::Odd);
37+
let even_pubkey = x_only_pubkey.public_key(Parity::Even);
38+
if signing_pubkey == odd_pubkey || signing_pubkey == even_pubkey {
39+
unsigned_invoice
40+
.sign::<_, Infallible>(
41+
|digest| Ok(secp_ctx.sign_schnorr_no_aux_rand(digest, &keys))
42+
)
43+
.unwrap()
44+
.write(&mut buffer)
45+
.unwrap();
46+
} else {
47+
unsigned_invoice
48+
.sign::<_, Infallible>(
49+
|digest| Ok(secp_ctx.sign_schnorr_no_aux_rand(digest, &keys))
50+
)
51+
.unwrap_err();
52+
}
53+
}
54+
}
55+
}
56+
57+
struct Randomness;
58+
59+
impl EntropySource for Randomness {
60+
fn get_secure_random_bytes(&self) -> [u8; 32] { [42; 32] }
61+
}
62+
63+
fn pubkey(byte: u8) -> PublicKey {
64+
let secp_ctx = Secp256k1::new();
65+
PublicKey::from_secret_key(&secp_ctx, &privkey(byte))
66+
}
67+
68+
fn privkey(byte: u8) -> SecretKey {
69+
SecretKey::from_slice(&[byte; 32]).unwrap()
70+
}
71+
72+
fn build_response<'a, T: secp256k1::Signing + secp256k1::Verification>(
73+
invoice_request: &'a InvoiceRequest, secp_ctx: &Secp256k1<T>
74+
) -> Result<UnsignedInvoice<'a>, SemanticError> {
75+
let entropy_source = Randomness {};
76+
let paths = vec![
77+
BlindedPath::new(&[pubkey(43), pubkey(44), pubkey(42)], &entropy_source, secp_ctx).unwrap(),
78+
BlindedPath::new(&[pubkey(45), pubkey(46), pubkey(42)], &entropy_source, secp_ctx).unwrap(),
79+
];
80+
81+
let payinfo = vec![
82+
BlindedPayInfo {
83+
fee_base_msat: 1,
84+
fee_proportional_millionths: 1_000,
85+
cltv_expiry_delta: 42,
86+
htlc_minimum_msat: 100,
87+
htlc_maximum_msat: 1_000_000_000_000,
88+
features: BlindedHopFeatures::empty(),
89+
},
90+
BlindedPayInfo {
91+
fee_base_msat: 1,
92+
fee_proportional_millionths: 1_000,
93+
cltv_expiry_delta: 42,
94+
htlc_minimum_msat: 100,
95+
htlc_maximum_msat: 1_000_000_000_000,
96+
features: BlindedHopFeatures::empty(),
97+
},
98+
];
99+
100+
let payment_paths = paths.into_iter().zip(payinfo.into_iter()).collect();
101+
let payment_hash = PaymentHash([42; 32]);
102+
invoice_request.respond_with(payment_paths, payment_hash)?.build()
103+
}
104+
105+
pub fn invoice_request_deser_test<Out: test_logger::Output>(data: &[u8], out: Out) {
106+
do_test(data, out);
107+
}
108+
109+
#[no_mangle]
110+
pub extern "C" fn invoice_request_deser_run(data: *const u8, datalen: usize) {
111+
do_test(unsafe { std::slice::from_raw_parts(data, datalen) }, test_logger::DevNull {});
112+
}

fuzz/src/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ pub mod chanmon_deser;
1818
pub mod chanmon_consistency;
1919
pub mod full_stack;
2020
pub mod indexedmap;
21+
pub mod invoice_request_deser;
2122
pub mod offer_deser;
2223
pub mod onion_message;
2324
pub mod peer_crypt;

fuzz/targets.h

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
void chanmon_deser_run(const unsigned char* data, size_t data_len);
33
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);
5+
void invoice_request_deser_run(const unsigned char* data, size_t data_len);
56
void offer_deser_run(const unsigned char* data, size_t data_len);
67
void onion_message_run(const unsigned char* data, size_t data_len);
78
void peer_crypt_run(const unsigned char* data, size_t data_len);

lightning/src/offers/invoice.rs

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -267,6 +267,11 @@ pub struct UnsignedInvoice<'a> {
267267
}
268268

269269
impl<'a> UnsignedInvoice<'a> {
270+
/// The public key corresponding to the key needed to sign the invoice.
271+
pub fn signing_pubkey(&self) -> PublicKey {
272+
self.invoice.fields().signing_pubkey
273+
}
274+
270275
/// Signs the invoice using the given function.
271276
pub fn sign<F, E>(self, sign: F) -> Result<Invoice, SignError<E>>
272277
where
@@ -453,12 +458,12 @@ impl Invoice {
453458
&self.contents.fields().features
454459
}
455460

456-
/// The public key used to sign invoices.
461+
/// The public key corresponding to the key used to sign the invoice.
457462
pub fn signing_pubkey(&self) -> PublicKey {
458463
self.contents.fields().signing_pubkey
459464
}
460465

461-
/// Signature of the invoice using [`Invoice::signing_pubkey`].
466+
/// Signature of the invoice verified using [`Invoice::signing_pubkey`].
462467
pub fn signature(&self) -> Signature {
463468
self.signature
464469
}

0 commit comments

Comments
 (0)