Skip to content

Commit c659e34

Browse files
committed
f: add fuzzing
1 parent 7a514d8 commit c659e34

File tree

7 files changed

+264
-2
lines changed

7 files changed

+264
-2
lines changed

fuzz/Cargo.toml

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,8 +22,10 @@ lightning = { path = "../lightning", features = ["regex", "_test_utils"] }
2222
lightning-invoice = { path = "../lightning-invoice" }
2323
lightning-liquidity = { path = "../lightning-liquidity" }
2424
lightning-rapid-gossip-sync = { path = "../lightning-rapid-gossip-sync" }
25+
lightning-persister = { path = "../lightning-persister", features = ["tokio"]}
2526
bech32 = "0.11.0"
2627
bitcoin = { version = "0.32.2", features = ["secp-lowmemory"] }
28+
tokio = { version = "1.35.*", default-features = false, features = ["rt-multi-thread"] }
2729

2830
afl = { version = "0.12", optional = true }
2931
honggfuzz = { version = "0.5", optional = true, default-features = false }

fuzz/src/bin/fs_store_target.rs

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

fuzz/src/bin/gen_target.sh

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@ GEN_TEST base32
2828
GEN_TEST fromstr_to_netaddress
2929
GEN_TEST feature_flags
3030
GEN_TEST lsps_message
31+
GEN_TEST fs_store
3132

3233
GEN_TEST msg_accept_channel msg_targets::
3334
GEN_TEST msg_announcement_signatures msg_targets::

fuzz/src/fs_store.rs

Lines changed: 135 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,135 @@
1+
use lightning::util::persist::{KVStore, KVStoreSync};
2+
use lightning_persister::fs_store::FilesystemStore;
3+
use tokio::runtime::Runtime;
4+
5+
use crate::utils::test_logger;
6+
7+
/// Actual fuzz test, method signature and name are fixed
8+
fn do_test<Out: test_logger::Output>(data: &[u8], out: Out) {
9+
let rt = Runtime::new().unwrap();
10+
rt.block_on(do_test_internal(data, out));
11+
}
12+
13+
async fn do_test_internal<Out: test_logger::Output>(data: &[u8], out: Out) {
14+
let mut read_pos = 0;
15+
macro_rules! get_slice {
16+
($len: expr) => {{
17+
let slice_len = $len as usize;
18+
if data.len() < read_pos + slice_len {
19+
return;
20+
}
21+
read_pos += slice_len;
22+
&data[read_pos - slice_len..read_pos]
23+
}};
24+
}
25+
26+
let mut temp_path = std::env::temp_dir();
27+
temp_path.push("fs_store_fuzz");
28+
let fs_store: FilesystemStore = FilesystemStore::new(temp_path);
29+
30+
let primary_namespace = "primary";
31+
let secondary_namespace = "secondary";
32+
let key = "key";
33+
34+
// Remove the key in case something was left over from a previous run.
35+
_ = KVStoreSync::remove(&fs_store, primary_namespace, secondary_namespace, key, false);
36+
37+
let mut next_data_value = 0u64;
38+
let mut get_next_data_value = || {
39+
let data_value = next_data_value.to_be_bytes().to_vec();
40+
next_data_value += 1;
41+
42+
data_value
43+
};
44+
45+
let mut current_data = None;
46+
47+
let mut futures = Vec::new();
48+
loop {
49+
let v = get_slice!(1)[0];
50+
match v {
51+
// Sync write
52+
0x00 => {
53+
let data_value = get_next_data_value();
54+
55+
KVStoreSync::write(
56+
&fs_store,
57+
primary_namespace,
58+
secondary_namespace,
59+
key,
60+
data_value.clone(),
61+
)
62+
.unwrap();
63+
64+
current_data = Some(data_value);
65+
},
66+
// Sync remove
67+
0x01 => {
68+
KVStoreSync::remove(&fs_store, primary_namespace, secondary_namespace, key, false)
69+
.unwrap();
70+
71+
current_data = None;
72+
},
73+
// Async write
74+
0x02 => {
75+
let data_value = get_next_data_value();
76+
77+
let fut = KVStore::write(
78+
&fs_store,
79+
primary_namespace,
80+
secondary_namespace,
81+
key,
82+
data_value.clone(),
83+
);
84+
85+
// Already set the current_data, even though writing hasn't finished yet. This supports the call-time
86+
// ordering semantics.
87+
current_data = Some(data_value);
88+
89+
// Store the future for later completion.
90+
futures.push(fut);
91+
if futures.len() > 10 {
92+
return;
93+
}
94+
},
95+
// Async write completion
96+
0x10..=0x19 => {
97+
let fut_idx = (v - 0x10) as usize;
98+
if fut_idx >= futures.len() {
99+
return;
100+
}
101+
102+
let fut = futures.remove(fut_idx);
103+
104+
fut.await.unwrap();
105+
},
106+
_ => {
107+
return;
108+
},
109+
}
110+
111+
// If no more writes are pending, we can reliably see if the data is consistent.
112+
if futures.is_empty() {
113+
let data_value =
114+
KVStoreSync::read(&fs_store, primary_namespace, secondary_namespace, key).ok();
115+
assert_eq!(data_value, current_data);
116+
117+
let list =
118+
KVStoreSync::list(&fs_store, primary_namespace, secondary_namespace).unwrap();
119+
assert_eq!(list.is_empty(), current_data.is_none());
120+
121+
assert_eq!(0, fs_store.state_size());
122+
}
123+
}
124+
}
125+
126+
/// Method that needs to be added manually, {name}_test
127+
pub fn fs_store_test<Out: test_logger::Output>(data: &[u8], out: Out) {
128+
do_test(data, out);
129+
}
130+
131+
/// Method that needs to be added manually, {name}_run
132+
#[no_mangle]
133+
pub extern "C" fn fs_store_run(data: *const u8, datalen: usize) {
134+
do_test(unsafe { std::slice::from_raw_parts(data, datalen) }, test_logger::DevNull {});
135+
}

fuzz/src/lib.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99

1010
extern crate bitcoin;
1111
extern crate lightning;
12+
extern crate lightning_persister;
1213
extern crate lightning_rapid_gossip_sync;
1314

1415
#[cfg(not(fuzzing))]
@@ -45,4 +46,5 @@ pub mod router;
4546
pub mod static_invoice_deser;
4647
pub mod zbase32;
4748

49+
pub mod fs_store;
4850
pub mod msg_targets;

fuzz/targets.h

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ void base32_run(const unsigned char* data, size_t data_len);
2121
void fromstr_to_netaddress_run(const unsigned char* data, size_t data_len);
2222
void feature_flags_run(const unsigned char* data, size_t data_len);
2323
void lsps_message_run(const unsigned char* data, size_t data_len);
24+
void fs_store_run(const unsigned char* data, size_t data_len);
2425
void msg_accept_channel_run(const unsigned char* data, size_t data_len);
2526
void msg_announcement_signatures_run(const unsigned char* data, size_t data_len);
2627
void msg_channel_reestablish_run(const unsigned char* data, size_t data_len);

lightning-persister/src/fs_store.rs

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -80,8 +80,9 @@ impl FilesystemStore {
8080
self.inner.data_dir.clone()
8181
}
8282

83-
#[cfg(all(feature = "tokio", test))]
84-
pub(crate) fn state_size(&self) -> usize {
83+
#[cfg(any(all(feature = "tokio", test), fuzzing))]
84+
/// Returns the size of the async state.
85+
pub fn state_size(&self) -> usize {
8586
let outer_lock = self.inner.locks.lock().unwrap();
8687
outer_lock.len()
8788
}

0 commit comments

Comments
 (0)