Skip to content

Commit 20efabd

Browse files
committed
Add deserialize+load steps to chanmon_fail_consistency (fixes #327)
1 parent c2f72b9 commit 20efabd

File tree

1 file changed

+154
-9
lines changed

1 file changed

+154
-9
lines changed

fuzz/fuzz_targets/chanmon_fail_consistency.rs

Lines changed: 154 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -27,21 +27,22 @@ use bitcoin::network::constants::Network;
2727
use bitcoin_hashes::Hash as TraitImport;
2828
use bitcoin_hashes::hash160::Hash as Hash160;
2929
use bitcoin_hashes::sha256::Hash as Sha256;
30+
use bitcoin_hashes::sha256d::Hash as Sha256d;
3031

3132
use lightning::chain::chaininterface;
3233
use lightning::chain::transaction::OutPoint;
3334
use lightning::chain::chaininterface::{BroadcasterInterface,ConfirmationTarget,ChainListener,FeeEstimator,ChainWatchInterfaceUtil};
3435
use lightning::chain::keysinterface::{ChannelKeys, KeysInterface};
3536
use lightning::ln::channelmonitor;
36-
use lightning::ln::channelmonitor::{ChannelMonitorUpdateErr, HTLCUpdate};
37-
use lightning::ln::channelmanager::{ChannelManager, PaymentHash, PaymentPreimage};
37+
use lightning::ln::channelmonitor::{ChannelMonitor, ChannelMonitorUpdateErr, HTLCUpdate};
38+
use lightning::ln::channelmanager::{ChannelManager, PaymentHash, PaymentPreimage, ChannelManagerReadArgs};
3839
use lightning::ln::router::{Route, RouteHop};
3940
use lightning::ln::msgs::{CommitmentUpdate, ChannelMessageHandler, ErrorAction, HandleError, UpdateAddHTLC, LocalFeatures};
4041
use lightning::util::events;
4142
use lightning::util::logger::Logger;
4243
use lightning::util::config::UserConfig;
4344
use lightning::util::events::{EventsProvider, MessageSendEventsProvider};
44-
use lightning::util::ser::{Readable, Writeable};
45+
use lightning::util::ser::{Readable, ReadableArgs, Writeable, Writer};
4546

4647
mod utils;
4748
use utils::test_logger;
@@ -51,7 +52,7 @@ use secp256k1::Secp256k1;
5152

5253
use std::mem;
5354
use std::cmp::Ordering;
54-
use std::collections::HashSet;
55+
use std::collections::{HashSet, HashMap};
5556
use std::sync::{Arc,Mutex};
5657
use std::sync::atomic;
5758
use std::io::Cursor;
@@ -68,22 +69,51 @@ impl BroadcasterInterface for TestBroadcaster {
6869
fn broadcast_transaction(&self, _tx: &Transaction) { }
6970
}
7071

72+
pub struct VecWriter(pub Vec<u8>);
73+
impl Writer for VecWriter {
74+
fn write_all(&mut self, buf: &[u8]) -> Result<(), ::std::io::Error> {
75+
self.0.extend_from_slice(buf);
76+
Ok(())
77+
}
78+
fn size_hint(&mut self, size: usize) {
79+
self.0.reserve_exact(size);
80+
}
81+
}
82+
7183
pub struct TestChannelMonitor {
7284
pub simple_monitor: Arc<channelmonitor::SimpleManyChannelMonitor<OutPoint>>,
7385
pub update_ret: Mutex<Result<(), channelmonitor::ChannelMonitorUpdateErr>>,
86+
pub latest_good_update: Mutex<HashMap<OutPoint, Vec<u8>>>,
87+
pub latest_update_good: Mutex<HashMap<OutPoint, bool>>,
88+
pub latest_updates_good_at_last_ser: Mutex<HashMap<OutPoint, bool>>,
89+
pub should_update_manager: atomic::AtomicBool,
7490
}
7591
impl TestChannelMonitor {
7692
pub fn new(chain_monitor: Arc<chaininterface::ChainWatchInterface>, broadcaster: Arc<chaininterface::BroadcasterInterface>, logger: Arc<Logger>, feeest: Arc<chaininterface::FeeEstimator>) -> Self {
7793
Self {
7894
simple_monitor: channelmonitor::SimpleManyChannelMonitor::new(chain_monitor, broadcaster, logger, feeest),
7995
update_ret: Mutex::new(Ok(())),
96+
latest_good_update: Mutex::new(HashMap::new()),
97+
latest_update_good: Mutex::new(HashMap::new()),
98+
latest_updates_good_at_last_ser: Mutex::new(HashMap::new()),
99+
should_update_manager: atomic::AtomicBool::new(false),
80100
}
81101
}
82102
}
83103
impl channelmonitor::ManyChannelMonitor for TestChannelMonitor {
84104
fn add_update_monitor(&self, funding_txo: OutPoint, monitor: channelmonitor::ChannelMonitor) -> Result<(), channelmonitor::ChannelMonitorUpdateErr> {
105+
let ret = self.update_ret.lock().unwrap().clone();
106+
if let Ok(()) = ret {
107+
let mut ser = VecWriter(Vec::new());
108+
monitor.write_for_disk(&mut ser).unwrap();
109+
self.latest_good_update.lock().unwrap().insert(funding_txo, ser.0);
110+
self.latest_update_good.lock().unwrap().insert(funding_txo, true);
111+
self.should_update_manager.store(true, atomic::Ordering::Relaxed);
112+
} else {
113+
self.latest_update_good.lock().unwrap().insert(funding_txo, false);
114+
}
85115
assert!(self.simple_monitor.add_update_monitor(funding_txo, monitor).is_ok());
86-
self.update_ret.lock().unwrap().clone()
116+
ret
87117
}
88118

89119
fn fetch_pending_htlc_updated(&self) -> Vec<HTLCUpdate> {
@@ -156,6 +186,55 @@ pub fn do_test(data: &[u8]) {
156186
} }
157187
}
158188

189+
macro_rules! reload_node {
190+
($ser: expr, $node_id: expr, $old_monitors: expr) => { {
191+
let logger: Arc<Logger> = Arc::new(test_logger::TestLogger::new($node_id.to_string()));
192+
let watch = Arc::new(ChainWatchInterfaceUtil::new(Network::Bitcoin, Arc::clone(&logger)));
193+
let monitor = Arc::new(TestChannelMonitor::new(watch.clone(), broadcast.clone(), logger.clone(), fee_est.clone()));
194+
195+
let keys_manager = Arc::new(KeyProvider { node_id: $node_id, session_id: atomic::AtomicU8::new(0), channel_id: atomic::AtomicU8::new(0) });
196+
let mut config = UserConfig::new();
197+
config.channel_options.fee_proportional_millionths = 0;
198+
config.channel_options.announced_channel = true;
199+
config.peer_channel_config_limits.min_dust_limit_satoshis = 0;
200+
201+
let mut monitors = HashMap::new();
202+
let mut old_monitors = $old_monitors.latest_good_update.lock().unwrap();
203+
for (outpoint, monitor_ser) in old_monitors.drain() {
204+
monitors.insert(outpoint, <(Sha256d, ChannelMonitor)>::read(&mut Cursor::new(&monitor_ser), Arc::clone(&logger)).expect("Failed to read monitor").1);
205+
monitor.latest_good_update.lock().unwrap().insert(outpoint, monitor_ser);
206+
}
207+
let mut monitor_refs = HashMap::new();
208+
for (outpoint, monitor) in monitors.iter() {
209+
monitor_refs.insert(*outpoint, monitor);
210+
}
211+
212+
let read_args = ChannelManagerReadArgs {
213+
keys_manager,
214+
fee_estimator: fee_est.clone(),
215+
monitor: monitor.clone(),
216+
chain_monitor: watch,
217+
tx_broadcaster: broadcast.clone(),
218+
logger,
219+
default_config: config,
220+
channel_monitors: &monitor_refs,
221+
};
222+
223+
let res = (<(Sha256d, ChannelManager)>::read(&mut Cursor::new(&$ser.0), read_args).expect("Failed to read manager").1, monitor);
224+
for (_, was_good) in $old_monitors.latest_updates_good_at_last_ser.lock().unwrap().iter() {
225+
if !was_good {
226+
// If the last time we updated a monitor we didn't successfully update (and we
227+
// have sense updated our serialized copy of the ChannelManager) we may
228+
// force-close the channel on our counterparty cause we know we're missing
229+
// something. Thus, we just return here since we can't continue to test.
230+
return;
231+
}
232+
}
233+
res
234+
} }
235+
}
236+
237+
159238
let mut channel_txn = Vec::new();
160239
macro_rules! make_channel {
161240
($source: expr, $dest: expr, $chan_id: expr) => { {
@@ -265,11 +344,11 @@ pub fn do_test(data: &[u8]) {
265344

266345
// 3 nodes is enough to hit all the possible cases, notably unknown-source-unknown-dest
267346
// forwarding.
268-
let (node_a, monitor_a) = make_node!(0);
269-
let (node_b, monitor_b) = make_node!(1);
270-
let (node_c, monitor_c) = make_node!(2);
347+
let (mut node_a, mut monitor_a) = make_node!(0);
348+
let (mut node_b, mut monitor_b) = make_node!(1);
349+
let (mut node_c, mut monitor_c) = make_node!(2);
271350

272-
let nodes = [node_a, node_b, node_c];
351+
let mut nodes = [node_a, node_b, node_c];
273352

274353
make_channel!(nodes[0], nodes[1], 0);
275354
make_channel!(nodes[1], nodes[2], 1);
@@ -290,6 +369,13 @@ pub fn do_test(data: &[u8]) {
290369
let mut ba_events = Vec::new();
291370
let mut bc_events = Vec::new();
292371

372+
let mut node_a_ser = VecWriter(Vec::new());
373+
nodes[0].write(&mut node_a_ser).unwrap();
374+
let mut node_b_ser = VecWriter(Vec::new());
375+
nodes[1].write(&mut node_b_ser).unwrap();
376+
let mut node_c_ser = VecWriter(Vec::new());
377+
nodes[2].write(&mut node_c_ser).unwrap();
378+
293379
macro_rules! test_err {
294380
($res: expr) => {
295381
match $res {
@@ -584,8 +670,67 @@ pub fn do_test(data: &[u8]) {
584670
0x1c => process_msg_events!(2, false),
585671
0x1d => process_events!(2, true),
586672
0x1e => process_events!(2, false),
673+
0x1f => {
674+
if !chan_a_disconnected {
675+
nodes[1].peer_disconnected(&nodes[0].get_our_node_id(), false);
676+
chan_a_disconnected = true;
677+
drain_msg_events_on_disconnect!(0);
678+
}
679+
let (new_node_a, new_monitor_a) = reload_node!(node_a_ser, 0, monitor_a);
680+
node_a = Arc::new(new_node_a);
681+
nodes[0] = node_a.clone();
682+
monitor_a = new_monitor_a;
683+
},
684+
0x20 => {
685+
if !chan_a_disconnected {
686+
nodes[0].peer_disconnected(&nodes[1].get_our_node_id(), false);
687+
chan_a_disconnected = true;
688+
nodes[0].get_and_clear_pending_msg_events();
689+
ba_events.clear();
690+
}
691+
if !chan_b_disconnected {
692+
nodes[2].peer_disconnected(&nodes[1].get_our_node_id(), false);
693+
chan_b_disconnected = true;
694+
nodes[2].get_and_clear_pending_msg_events();
695+
bc_events.clear();
696+
}
697+
let (new_node_b, new_monitor_b) = reload_node!(node_b_ser, 1, monitor_b);
698+
node_b = Arc::new(new_node_b);
699+
nodes[1] = node_b.clone();
700+
monitor_b = new_monitor_b;
701+
},
702+
0x21 => {
703+
if !chan_b_disconnected {
704+
nodes[1].peer_disconnected(&nodes[2].get_our_node_id(), false);
705+
chan_b_disconnected = true;
706+
drain_msg_events_on_disconnect!(2);
707+
}
708+
let (new_node_c, new_monitor_c) = reload_node!(node_c_ser, 2, monitor_c);
709+
node_c = Arc::new(new_node_c);
710+
nodes[2] = node_c.clone();
711+
monitor_c = new_monitor_c;
712+
},
587713
_ => test_return!(),
588714
}
715+
716+
if monitor_a.should_update_manager.load(atomic::Ordering::Relaxed) {
717+
node_a_ser.0.clear();
718+
nodes[0].write(&mut node_a_ser).unwrap();
719+
monitor_a.should_update_manager.store(false, atomic::Ordering::Relaxed);
720+
*monitor_a.latest_updates_good_at_last_ser.lock().unwrap() = monitor_a.latest_update_good.lock().unwrap().clone();
721+
}
722+
if monitor_b.should_update_manager.load(atomic::Ordering::Relaxed) {
723+
node_b_ser.0.clear();
724+
nodes[1].write(&mut node_b_ser).unwrap();
725+
monitor_b.should_update_manager.store(false, atomic::Ordering::Relaxed);
726+
*monitor_b.latest_updates_good_at_last_ser.lock().unwrap() = monitor_b.latest_update_good.lock().unwrap().clone();
727+
}
728+
if monitor_c.should_update_manager.load(atomic::Ordering::Relaxed) {
729+
node_c_ser.0.clear();
730+
nodes[2].write(&mut node_c_ser).unwrap();
731+
monitor_c.should_update_manager.store(false, atomic::Ordering::Relaxed);
732+
*monitor_c.latest_updates_good_at_last_ser.lock().unwrap() = monitor_c.latest_update_good.lock().unwrap().clone();
733+
}
589734
}
590735
}
591736

0 commit comments

Comments
 (0)