Skip to content

Commit 27ac85b

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

File tree

1 file changed

+150
-9
lines changed

1 file changed

+150
-9
lines changed

fuzz/fuzz_targets/chanmon_fail_consistency.rs

Lines changed: 150 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,60 @@ 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_ignored_update: Mutex<HashMap<OutPoint, Vec<u8>>>,
88+
pub should_update_manager: atomic::AtomicBool,
7489
}
7590
impl TestChannelMonitor {
7691
pub fn new(chain_monitor: Arc<chaininterface::ChainWatchInterface>, broadcaster: Arc<chaininterface::BroadcasterInterface>, logger: Arc<Logger>, feeest: Arc<chaininterface::FeeEstimator>) -> Self {
7792
Self {
7893
simple_monitor: channelmonitor::SimpleManyChannelMonitor::new(chain_monitor, broadcaster, logger, feeest),
7994
update_ret: Mutex::new(Ok(())),
95+
latest_good_update: Mutex::new(HashMap::new()),
96+
latest_ignored_update: Mutex::new(HashMap::new()),
97+
should_update_manager: atomic::AtomicBool::new(false),
8098
}
8199
}
82100
}
83101
impl channelmonitor::ManyChannelMonitor for TestChannelMonitor {
84102
fn add_update_monitor(&self, funding_txo: OutPoint, monitor: channelmonitor::ChannelMonitor) -> Result<(), channelmonitor::ChannelMonitorUpdateErr> {
103+
let ret = self.update_ret.lock().unwrap().clone();
104+
let mut ser = VecWriter(Vec::new());
105+
monitor.write_for_disk(&mut ser).unwrap();
106+
if let Ok(()) = ret {
107+
let mut latest_good_update = self.latest_good_update.lock().unwrap();
108+
let mut latest_ignored_update = self.latest_ignored_update.lock().unwrap();
109+
latest_good_update.insert(funding_txo, ser.0);
110+
111+
// Because we will panic if any channels get closed on us, we have to keep track of any
112+
// ChannelMonitor updates which we ignored, and include those in the serialized state
113+
// when we update the ChannelManager serialized copy. This is (obviously) not required
114+
// of actual clients, but ensures we should never get a channel closure in the test.
115+
for (ignored_funding, ignored_update) in latest_ignored_update.drain() {
116+
if ignored_funding != funding_txo {
117+
latest_good_update.insert(ignored_funding, ignored_update);
118+
}
119+
}
120+
self.should_update_manager.store(true, atomic::Ordering::Relaxed);
121+
} else {
122+
self.latest_ignored_update.lock().unwrap().insert(funding_txo, ser.0);
123+
}
85124
assert!(self.simple_monitor.add_update_monitor(funding_txo, monitor).is_ok());
86-
self.update_ret.lock().unwrap().clone()
125+
ret
87126
}
88127

89128
fn fetch_pending_htlc_updated(&self) -> Vec<HTLCUpdate> {
@@ -156,6 +195,45 @@ pub fn do_test(data: &[u8]) {
156195
} }
157196
}
158197

198+
macro_rules! reload_node {
199+
($ser: expr, $node_id: expr, $old_monitors: expr) => { {
200+
let logger: Arc<Logger> = Arc::new(test_logger::TestLogger::new($node_id.to_string()));
201+
let watch = Arc::new(ChainWatchInterfaceUtil::new(Network::Bitcoin, Arc::clone(&logger)));
202+
let monitor = Arc::new(TestChannelMonitor::new(watch.clone(), broadcast.clone(), logger.clone(), fee_est.clone()));
203+
204+
let keys_manager = Arc::new(KeyProvider { node_id: $node_id, session_id: atomic::AtomicU8::new(0), channel_id: atomic::AtomicU8::new(0) });
205+
let mut config = UserConfig::new();
206+
config.channel_options.fee_proportional_millionths = 0;
207+
config.channel_options.announced_channel = true;
208+
config.peer_channel_config_limits.min_dust_limit_satoshis = 0;
209+
210+
let mut monitors = HashMap::new();
211+
let mut old_monitors = $old_monitors.lock().unwrap();
212+
for (outpoint, monitor_ser) in old_monitors.drain() {
213+
monitors.insert(outpoint, <(Sha256d, ChannelMonitor)>::read(&mut Cursor::new(&monitor_ser), Arc::clone(&logger)).expect("Failed to read monitor").1);
214+
monitor.latest_good_update.lock().unwrap().insert(outpoint, monitor_ser);
215+
}
216+
let mut monitor_refs = HashMap::new();
217+
for (outpoint, monitor) in monitors.iter() {
218+
monitor_refs.insert(*outpoint, monitor);
219+
}
220+
221+
let read_args = ChannelManagerReadArgs {
222+
keys_manager,
223+
fee_estimator: fee_est.clone(),
224+
monitor: monitor.clone(),
225+
chain_monitor: watch,
226+
tx_broadcaster: broadcast.clone(),
227+
logger,
228+
default_config: config,
229+
channel_monitors: &monitor_refs,
230+
};
231+
232+
(<(Sha256d, ChannelManager)>::read(&mut Cursor::new(&$ser.0), read_args).expect("Failed to read manager").1, monitor)
233+
} }
234+
}
235+
236+
159237
let mut channel_txn = Vec::new();
160238
macro_rules! make_channel {
161239
($source: expr, $dest: expr, $chan_id: expr) => { {
@@ -265,11 +343,11 @@ pub fn do_test(data: &[u8]) {
265343

266344
// 3 nodes is enough to hit all the possible cases, notably unknown-source-unknown-dest
267345
// 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);
346+
let (mut node_a, mut monitor_a) = make_node!(0);
347+
let (mut node_b, mut monitor_b) = make_node!(1);
348+
let (mut node_c, mut monitor_c) = make_node!(2);
271349

272-
let nodes = [node_a, node_b, node_c];
350+
let mut nodes = [node_a, node_b, node_c];
273351

274352
make_channel!(nodes[0], nodes[1], 0);
275353
make_channel!(nodes[1], nodes[2], 1);
@@ -290,6 +368,13 @@ pub fn do_test(data: &[u8]) {
290368
let mut ba_events = Vec::new();
291369
let mut bc_events = Vec::new();
292370

371+
let mut node_a_ser = VecWriter(Vec::new());
372+
nodes[0].write(&mut node_a_ser).unwrap();
373+
let mut node_b_ser = VecWriter(Vec::new());
374+
nodes[1].write(&mut node_b_ser).unwrap();
375+
let mut node_c_ser = VecWriter(Vec::new());
376+
nodes[2].write(&mut node_c_ser).unwrap();
377+
293378
macro_rules! test_err {
294379
($res: expr) => {
295380
match $res {
@@ -584,8 +669,64 @@ pub fn do_test(data: &[u8]) {
584669
0x1c => process_msg_events!(2, false),
585670
0x1d => process_events!(2, true),
586671
0x1e => process_events!(2, false),
672+
0x1f => {
673+
if !chan_a_disconnected {
674+
nodes[1].peer_disconnected(&nodes[0].get_our_node_id(), false);
675+
chan_a_disconnected = true;
676+
drain_msg_events_on_disconnect!(0);
677+
}
678+
let (new_node_a, new_monitor_a) = reload_node!(node_a_ser, 0, monitor_a.latest_good_update);
679+
node_a = Arc::new(new_node_a);
680+
nodes[0] = node_a.clone();
681+
monitor_a = new_monitor_a;
682+
},
683+
0x20 => {
684+
if !chan_a_disconnected {
685+
nodes[0].peer_disconnected(&nodes[1].get_our_node_id(), false);
686+
chan_a_disconnected = true;
687+
nodes[0].get_and_clear_pending_msg_events();
688+
ba_events.clear();
689+
}
690+
if !chan_b_disconnected {
691+
nodes[2].peer_disconnected(&nodes[1].get_our_node_id(), false);
692+
chan_b_disconnected = true;
693+
nodes[2].get_and_clear_pending_msg_events();
694+
bc_events.clear();
695+
}
696+
let (new_node_b, new_monitor_b) = reload_node!(node_b_ser, 1, monitor_b.latest_good_update);
697+
node_b = Arc::new(new_node_b);
698+
nodes[1] = node_b.clone();
699+
monitor_b = new_monitor_b;
700+
},
701+
0x21 => {
702+
if !chan_b_disconnected {
703+
nodes[1].peer_disconnected(&nodes[2].get_our_node_id(), false);
704+
chan_b_disconnected = true;
705+
drain_msg_events_on_disconnect!(2);
706+
}
707+
let (new_node_c, new_monitor_c) = reload_node!(node_c_ser, 2, monitor_c.latest_good_update);
708+
node_c = Arc::new(new_node_c);
709+
nodes[2] = node_c.clone();
710+
monitor_c = new_monitor_c;
711+
},
587712
_ => test_return!(),
588713
}
714+
715+
if monitor_a.should_update_manager.load(atomic::Ordering::Relaxed) {
716+
node_a_ser.0.clear();
717+
nodes[0].write(&mut node_a_ser).unwrap();
718+
monitor_a.should_update_manager.store(false, atomic::Ordering::Relaxed);
719+
}
720+
if monitor_b.should_update_manager.load(atomic::Ordering::Relaxed) {
721+
node_b_ser.0.clear();
722+
nodes[1].write(&mut node_b_ser).unwrap();
723+
monitor_b.should_update_manager.store(false, atomic::Ordering::Relaxed);
724+
}
725+
if monitor_c.should_update_manager.load(atomic::Ordering::Relaxed) {
726+
node_c_ser.0.clear();
727+
nodes[2].write(&mut node_c_ser).unwrap();
728+
monitor_c.should_update_manager.store(false, atomic::Ordering::Relaxed);
729+
}
589730
}
590731
}
591732

0 commit comments

Comments
 (0)