Skip to content

Commit f72a43c

Browse files
committed
Add async implementation of FilesystemStore
1 parent c2d9b97 commit f72a43c

File tree

9 files changed

+656
-85
lines changed

9 files changed

+656
-85
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/ci-fuzz.sh

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,8 @@ for TARGET in src/bin/*.rs; do
4040
HFUZZ_RUN_ARGS="$HFUZZ_RUN_ARGS -N10000"
4141
elif [ "$FILE" = "indexedmap_target" ]; then
4242
HFUZZ_RUN_ARGS="$HFUZZ_RUN_ARGS -N100000"
43+
elif [ "$FILE" = "fs_store_target" ]; then
44+
HFUZZ_RUN_ARGS="$HFUZZ_RUN_ARGS -F 64 -N10000"
4345
else
4446
HFUZZ_RUN_ARGS="$HFUZZ_RUN_ARGS -N1000000"
4547
fi

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: 184 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,184 @@
1+
use core::hash::{BuildHasher, Hasher};
2+
use lightning::util::persist::{KVStore, KVStoreSync};
3+
use lightning_persister::fs_store::FilesystemStore;
4+
use std::fs;
5+
use tokio::runtime::Runtime;
6+
7+
use crate::utils::test_logger;
8+
9+
struct TempFilesystemStore {
10+
temp_path: std::path::PathBuf,
11+
inner: FilesystemStore,
12+
}
13+
14+
impl TempFilesystemStore {
15+
fn new() -> Self {
16+
const SHM_PATH: &str = "/dev/shm";
17+
let mut temp_path = if std::path::Path::new(SHM_PATH).exists() {
18+
std::path::PathBuf::from(SHM_PATH)
19+
} else {
20+
std::env::temp_dir()
21+
};
22+
23+
let random_number = std::collections::hash_map::RandomState::new().build_hasher().finish();
24+
let random_folder_name = format!("fs_store_fuzz_{:016x}", random_number);
25+
temp_path.push(random_folder_name);
26+
27+
let inner = FilesystemStore::new(temp_path.clone());
28+
TempFilesystemStore { inner, temp_path }
29+
}
30+
}
31+
32+
impl Drop for TempFilesystemStore {
33+
fn drop(&mut self) {
34+
_ = fs::remove_dir_all(&self.temp_path)
35+
}
36+
}
37+
38+
/// Actual fuzz test, method signature and name are fixed
39+
fn do_test<Out: test_logger::Output>(data: &[u8], out: Out) {
40+
let rt = Runtime::new().unwrap();
41+
rt.block_on(do_test_internal(data, out));
42+
}
43+
44+
async fn do_test_internal<Out: test_logger::Output>(data: &[u8], _out: Out) {
45+
let mut read_pos = 0;
46+
macro_rules! get_slice {
47+
($len: expr) => {{
48+
let slice_len = $len as usize;
49+
if data.len() < read_pos + slice_len {
50+
None
51+
} else {
52+
read_pos += slice_len;
53+
Some(&data[read_pos - slice_len..read_pos])
54+
}
55+
}};
56+
}
57+
58+
let temp_fs_store = TempFilesystemStore::new();
59+
let fs_store = &temp_fs_store.inner;
60+
61+
let primary_namespace = "primary";
62+
let secondary_namespace = "secondary";
63+
let key = "key";
64+
65+
let mut next_data_value = 0u64;
66+
let mut get_next_data_value = || {
67+
let data_value = next_data_value.to_be_bytes().to_vec();
68+
next_data_value += 1;
69+
70+
data_value
71+
};
72+
73+
let mut current_data = None;
74+
75+
let mut handles = Vec::new();
76+
loop {
77+
let v = match get_slice!(1) {
78+
Some(b) => b[0],
79+
None => break,
80+
};
81+
match v % 13 {
82+
// Sync write
83+
0 => {
84+
let data_value = get_next_data_value();
85+
86+
KVStoreSync::write(
87+
fs_store,
88+
primary_namespace,
89+
secondary_namespace,
90+
key,
91+
data_value.clone(),
92+
)
93+
.unwrap();
94+
95+
current_data = Some(data_value);
96+
},
97+
// Sync remove
98+
1 => {
99+
KVStoreSync::remove(fs_store, primary_namespace, secondary_namespace, key, false)
100+
.unwrap();
101+
102+
current_data = None;
103+
},
104+
// Sync list
105+
2 => {
106+
KVStoreSync::list(fs_store, primary_namespace, secondary_namespace).unwrap();
107+
},
108+
// Sync read
109+
3 => {
110+
_ = KVStoreSync::read(fs_store, primary_namespace, secondary_namespace, key);
111+
},
112+
// Async write. Bias writes a bit.
113+
4..=9 => {
114+
let data_value = get_next_data_value();
115+
116+
let fut = KVStore::write(
117+
fs_store,
118+
primary_namespace,
119+
secondary_namespace,
120+
key,
121+
data_value.clone(),
122+
);
123+
124+
// Already set the current_data, even though writing hasn't finished yet. This supports the call-time
125+
// ordering semantics.
126+
current_data = Some(data_value);
127+
128+
let handle = tokio::task::spawn(fut);
129+
130+
// Store the handle to later await the result.
131+
handles.push(handle);
132+
},
133+
// Async remove
134+
10 | 11 => {
135+
let lazy = v == 10;
136+
let fut =
137+
KVStore::remove(fs_store, primary_namespace, secondary_namespace, key, lazy);
138+
139+
// Already set the current_data, even though writing hasn't finished yet. This supports the call-time
140+
// ordering semantics.
141+
current_data = None;
142+
143+
let handle = tokio::task::spawn(fut);
144+
handles.push(handle);
145+
},
146+
// Join tasks.
147+
12 => {
148+
for handle in handles.drain(..) {
149+
let _ = handle.await.unwrap();
150+
}
151+
},
152+
_ => unreachable!(),
153+
}
154+
155+
// If no more writes are pending, we can reliably see if the data is consistent.
156+
if handles.is_empty() {
157+
let data_value =
158+
KVStoreSync::read(fs_store, primary_namespace, secondary_namespace, key).ok();
159+
assert_eq!(data_value, current_data);
160+
161+
let list = KVStoreSync::list(fs_store, primary_namespace, secondary_namespace).unwrap();
162+
assert_eq!(list.is_empty(), current_data.is_none());
163+
164+
assert_eq!(0, fs_store.state_size());
165+
}
166+
}
167+
168+
// Always make sure that all async tasks are completed before returning. Otherwise the temporary storage dir could
169+
// be removed, and then again recreated by unfinished tasks.
170+
for handle in handles.drain(..) {
171+
let _ = handle.await.unwrap();
172+
}
173+
}
174+
175+
/// Method that needs to be added manually, {name}_test
176+
pub fn fs_store_test<Out: test_logger::Output>(data: &[u8], out: Out) {
177+
do_test(data, out);
178+
}
179+
180+
/// Method that needs to be added manually, {name}_run
181+
#[no_mangle]
182+
pub extern "C" fn fs_store_run(data: *const u8, datalen: usize) {
183+
do_test(unsafe { std::slice::from_raw_parts(data, datalen) }, test_logger::DevNull {});
184+
}

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/Cargo.toml

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ rustdoc-args = ["--cfg", "docsrs"]
1616
[dependencies]
1717
bitcoin = "0.32.2"
1818
lightning = { version = "0.2.0", path = "../lightning" }
19+
tokio = { version = "1.35", optional = true, default-features = false, features = ["rt-multi-thread"] }
1920

2021
[target.'cfg(windows)'.dependencies]
2122
windows-sys = { version = "0.48.0", default-features = false, features = ["Win32_Storage_FileSystem", "Win32_Foundation"] }
@@ -26,6 +27,7 @@ criterion = { version = "0.4", optional = true, default-features = false }
2627
[dev-dependencies]
2728
lightning = { version = "0.2.0", path = "../lightning", features = ["_test_utils"] }
2829
bitcoin = { version = "0.32.2", default-features = false }
30+
tokio = { version = "1.35", default-features = false, features = ["macros"] }
2931

3032
[lints]
3133
workspace = true

0 commit comments

Comments
 (0)