1 // This file is Copyright its original authors, visible in version control
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
10 //! Test that monitor update failures don't get our channel state out of sync.
11 //! One of the biggest concern with the monitor update failure handling code is that messages
12 //! resent after monitor updating is restored are delivered out-of-order, resulting in
13 //! commitment_signed messages having "invalid signatures".
14 //! To test this we stand up a network of three nodes and read bytes from the fuzz input to denote
15 //! actions such as sending payments, handling events, or changing monitor update return values on
16 //! a per-node basis. This should allow it to find any cases where the ordering of actions results
17 //! in us getting out of sync with ourselves, and, assuming at least one of our recieve- or
18 //! send-side handling is correct, other peers. We consider it a failure if any action results in a
19 //! channel being force-closed.
21 use bitcoin::BitcoinHash;
22 use bitcoin::blockdata::block::BlockHeader;
23 use bitcoin::blockdata::transaction::{Transaction, TxOut};
24 use bitcoin::blockdata::script::{Builder, Script};
25 use bitcoin::blockdata::opcodes;
26 use bitcoin::network::constants::Network;
28 use bitcoin::hashes::Hash as TraitImport;
29 use bitcoin::hashes::sha256::Hash as Sha256;
30 use bitcoin::hash_types::{BlockHash, WPubkeyHash};
32 use lightning::chain::chaininterface;
33 use lightning::chain::transaction::OutPoint;
34 use lightning::chain::chaininterface::{BroadcasterInterface,ConfirmationTarget,ChainListener,FeeEstimator,ChainWatchInterfaceUtil,ChainWatchInterface};
35 use lightning::chain::keysinterface::{KeysInterface, InMemoryChannelKeys};
36 use lightning::ln::channelmonitor;
37 use lightning::ln::channelmonitor::{ChannelMonitor, ChannelMonitorUpdateErr, HTLCUpdate};
38 use lightning::ln::channelmanager::{ChannelManager, PaymentHash, PaymentPreimage, PaymentSecret, ChannelManagerReadArgs};
39 use lightning::ln::features::{ChannelFeatures, InitFeatures, NodeFeatures};
40 use lightning::ln::msgs::{CommitmentUpdate, ChannelMessageHandler, ErrorAction, UpdateAddHTLC, Init};
41 use lightning::util::enforcing_trait_impls::EnforcingChannelKeys;
42 use lightning::util::events;
43 use lightning::util::logger::Logger;
44 use lightning::util::config::UserConfig;
45 use lightning::util::events::{EventsProvider, MessageSendEventsProvider};
46 use lightning::util::ser::{Readable, ReadableArgs, Writeable, Writer};
47 use lightning::routing::router::{Route, RouteHop};
50 use utils::test_logger;
52 use bitcoin::secp256k1::key::{PublicKey,SecretKey};
53 use bitcoin::secp256k1::Secp256k1;
56 use std::cmp::Ordering;
57 use std::collections::{HashSet, hash_map, HashMap};
58 use std::sync::{Arc,Mutex};
59 use std::sync::atomic;
62 struct FuzzEstimator {}
63 impl FeeEstimator for FuzzEstimator {
64 fn get_est_sat_per_1000_weight(&self, _: ConfirmationTarget) -> u32 {
69 pub struct TestBroadcaster {}
70 impl BroadcasterInterface for TestBroadcaster {
71 fn broadcast_transaction(&self, _tx: &Transaction) { }
74 pub struct VecWriter(pub Vec<u8>);
75 impl Writer for VecWriter {
76 fn write_all(&mut self, buf: &[u8]) -> Result<(), ::std::io::Error> {
77 self.0.extend_from_slice(buf);
80 fn size_hint(&mut self, size: usize) {
81 self.0.reserve_exact(size);
85 struct TestChannelMonitor {
86 pub logger: Arc<dyn Logger>,
87 pub simple_monitor: Arc<channelmonitor::SimpleManyChannelMonitor<OutPoint, EnforcingChannelKeys, Arc<TestBroadcaster>, Arc<FuzzEstimator>, Arc<dyn Logger>, Arc<dyn ChainWatchInterface>>>,
88 pub update_ret: Mutex<Result<(), channelmonitor::ChannelMonitorUpdateErr>>,
89 // If we reload a node with an old copy of ChannelMonitors, the ChannelManager deserialization
90 // logic will automatically force-close our channels for us (as we don't have an up-to-date
91 // monitor implying we are not able to punish misbehaving counterparties). Because this test
92 // "fails" if we ever force-close a channel, we avoid doing so, always saving the latest
93 // fully-serialized monitor state here, as well as the corresponding update_id.
94 pub latest_monitors: Mutex<HashMap<OutPoint, (u64, Vec<u8>)>>,
95 pub should_update_manager: atomic::AtomicBool,
97 impl TestChannelMonitor {
98 pub fn new(chain_monitor: Arc<dyn chaininterface::ChainWatchInterface>, broadcaster: Arc<TestBroadcaster>, logger: Arc<dyn Logger>, feeest: Arc<FuzzEstimator>) -> Self {
100 simple_monitor: Arc::new(channelmonitor::SimpleManyChannelMonitor::new(chain_monitor, broadcaster, logger.clone(), feeest)),
102 update_ret: Mutex::new(Ok(())),
103 latest_monitors: Mutex::new(HashMap::new()),
104 should_update_manager: atomic::AtomicBool::new(false),
108 impl channelmonitor::ManyChannelMonitor for TestChannelMonitor {
109 type Keys = EnforcingChannelKeys;
111 fn add_monitor(&self, funding_txo: OutPoint, monitor: channelmonitor::ChannelMonitor<EnforcingChannelKeys>) -> Result<(), channelmonitor::ChannelMonitorUpdateErr> {
112 let mut ser = VecWriter(Vec::new());
113 monitor.write_for_disk(&mut ser).unwrap();
114 if let Some(_) = self.latest_monitors.lock().unwrap().insert(funding_txo, (monitor.get_latest_update_id(), ser.0)) {
115 panic!("Already had monitor pre-add_monitor");
117 self.should_update_manager.store(true, atomic::Ordering::Relaxed);
118 assert!(self.simple_monitor.add_monitor(funding_txo, monitor).is_ok());
119 self.update_ret.lock().unwrap().clone()
122 fn update_monitor(&self, funding_txo: OutPoint, update: channelmonitor::ChannelMonitorUpdate) -> Result<(), channelmonitor::ChannelMonitorUpdateErr> {
123 let mut map_lock = self.latest_monitors.lock().unwrap();
124 let mut map_entry = match map_lock.entry(funding_txo) {
125 hash_map::Entry::Occupied(entry) => entry,
126 hash_map::Entry::Vacant(_) => panic!("Didn't have monitor on update call"),
128 let mut deserialized_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingChannelKeys>)>::
129 read(&mut Cursor::new(&map_entry.get().1)).unwrap().1;
130 deserialized_monitor.update_monitor(update.clone(), &&TestBroadcaster {}, &self.logger).unwrap();
131 let mut ser = VecWriter(Vec::new());
132 deserialized_monitor.write_for_disk(&mut ser).unwrap();
133 map_entry.insert((update.update_id, ser.0));
134 self.should_update_manager.store(true, atomic::Ordering::Relaxed);
135 self.update_ret.lock().unwrap().clone()
138 fn get_monitor_would_broadcast(&self, funding_txo: &OutPoint, height: u32) -> bool {
139 self.simple_monitor.get_monitor_would_broadcast(funding_txo, height)
142 fn get_and_clear_pending_htlcs_updated(&self) -> Vec<HTLCUpdate> {
143 return self.simple_monitor.get_and_clear_pending_htlcs_updated();
149 session_id: atomic::AtomicU8,
150 channel_id: atomic::AtomicU8,
152 impl KeysInterface for KeyProvider {
153 type ChanKeySigner = EnforcingChannelKeys;
155 fn get_node_secret(&self) -> SecretKey {
156 SecretKey::from_slice(&[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, self.node_id]).unwrap()
159 fn get_destination_script(&self) -> Script {
160 let secp_ctx = Secp256k1::signing_only();
161 let channel_monitor_claim_key = SecretKey::from_slice(&[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, self.node_id]).unwrap();
162 let our_channel_monitor_claim_key_hash = WPubkeyHash::hash(&PublicKey::from_secret_key(&secp_ctx, &channel_monitor_claim_key).serialize());
163 Builder::new().push_opcode(opcodes::all::OP_PUSHBYTES_0).push_slice(&our_channel_monitor_claim_key_hash[..]).into_script()
166 fn get_shutdown_pubkey(&self) -> PublicKey {
167 let secp_ctx = Secp256k1::signing_only();
168 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, self.node_id]).unwrap())
171 fn get_channel_keys(&self, _inbound: bool, channel_value_satoshis: u64) -> EnforcingChannelKeys {
172 let secp_ctx = Secp256k1::signing_only();
173 EnforcingChannelKeys::new(InMemoryChannelKeys::new(
175 SecretKey::from_slice(&[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, self.node_id]).unwrap(),
176 SecretKey::from_slice(&[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, self.node_id]).unwrap(),
177 SecretKey::from_slice(&[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, self.node_id]).unwrap(),
178 SecretKey::from_slice(&[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, self.node_id]).unwrap(),
179 SecretKey::from_slice(&[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, self.node_id]).unwrap(),
180 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, self.node_id],
181 channel_value_satoshis,
186 fn get_onion_rand(&self) -> (SecretKey, [u8; 32]) {
187 let id = self.session_id.fetch_add(1, atomic::Ordering::Relaxed);
188 (SecretKey::from_slice(&[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, id, 10, self.node_id]).unwrap(),
192 fn get_channel_id(&self) -> [u8; 32] {
193 let id = self.channel_id.fetch_add(1, atomic::Ordering::Relaxed);
194 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, id, 11, self.node_id]
199 pub fn do_test<Out: test_logger::Output>(data: &[u8], out: Out) {
200 let fee_est = Arc::new(FuzzEstimator{});
201 let broadcast = Arc::new(TestBroadcaster{});
203 macro_rules! make_node {
204 ($node_id: expr) => { {
205 let logger: Arc<dyn Logger> = Arc::new(test_logger::TestLogger::new($node_id.to_string(), out.clone()));
206 let watch = Arc::new(ChainWatchInterfaceUtil::new(Network::Bitcoin));
207 let monitor = Arc::new(TestChannelMonitor::new(watch.clone(), broadcast.clone(), logger.clone(), fee_est.clone()));
209 let keys_manager = Arc::new(KeyProvider { node_id: $node_id, session_id: atomic::AtomicU8::new(0), channel_id: atomic::AtomicU8::new(0) });
210 let mut config = UserConfig::default();
211 config.channel_options.fee_proportional_millionths = 0;
212 config.channel_options.announced_channel = true;
213 config.peer_channel_config_limits.min_dust_limit_satoshis = 0;
214 (Arc::new(ChannelManager::new(Network::Bitcoin, fee_est.clone(), monitor.clone(), broadcast.clone(), Arc::clone(&logger), keys_manager.clone(), config, 0)),
219 macro_rules! reload_node {
220 ($ser: expr, $node_id: expr, $old_monitors: expr) => { {
221 let logger: Arc<dyn Logger> = Arc::new(test_logger::TestLogger::new($node_id.to_string(), out.clone()));
222 let watch = Arc::new(ChainWatchInterfaceUtil::new(Network::Bitcoin));
223 let monitor = Arc::new(TestChannelMonitor::new(watch.clone(), broadcast.clone(), logger.clone(), fee_est.clone()));
225 let keys_manager = Arc::new(KeyProvider { node_id: $node_id, session_id: atomic::AtomicU8::new(0), channel_id: atomic::AtomicU8::new(0) });
226 let mut config = UserConfig::default();
227 config.channel_options.fee_proportional_millionths = 0;
228 config.channel_options.announced_channel = true;
229 config.peer_channel_config_limits.min_dust_limit_satoshis = 0;
231 let mut monitors = HashMap::new();
232 let mut old_monitors = $old_monitors.latest_monitors.lock().unwrap();
233 for (outpoint, (update_id, monitor_ser)) in old_monitors.drain() {
234 monitors.insert(outpoint, <(BlockHash, ChannelMonitor<EnforcingChannelKeys>)>::read(&mut Cursor::new(&monitor_ser)).expect("Failed to read monitor").1);
235 monitor.latest_monitors.lock().unwrap().insert(outpoint, (update_id, monitor_ser));
237 let mut monitor_refs = HashMap::new();
238 for (outpoint, monitor) in monitors.iter_mut() {
239 monitor_refs.insert(*outpoint, monitor);
242 let read_args = ChannelManagerReadArgs {
244 fee_estimator: fee_est.clone(),
245 monitor: monitor.clone(),
246 tx_broadcaster: broadcast.clone(),
248 default_config: config,
249 channel_monitors: &mut monitor_refs,
252 (<(BlockHash, ChannelManager<EnforcingChannelKeys, Arc<TestChannelMonitor>, Arc<TestBroadcaster>, Arc<KeyProvider>, Arc<FuzzEstimator>, Arc<dyn Logger>>)>::read(&mut Cursor::new(&$ser.0), read_args).expect("Failed to read manager").1, monitor)
256 let mut channel_txn = Vec::new();
257 macro_rules! make_channel {
258 ($source: expr, $dest: expr, $chan_id: expr) => { {
259 $source.create_channel($dest.get_our_node_id(), 10000000, 42, 0, None).unwrap();
261 let events = $source.get_and_clear_pending_msg_events();
262 assert_eq!(events.len(), 1);
263 if let events::MessageSendEvent::SendOpenChannel { ref msg, .. } = events[0] {
265 } else { panic!("Wrong event type"); }
268 $dest.handle_open_channel(&$source.get_our_node_id(), InitFeatures::known(), &open_channel);
269 let accept_channel = {
270 let events = $dest.get_and_clear_pending_msg_events();
271 assert_eq!(events.len(), 1);
272 if let events::MessageSendEvent::SendAcceptChannel { ref msg, .. } = events[0] {
274 } else { panic!("Wrong event type"); }
277 $source.handle_accept_channel(&$dest.get_our_node_id(), InitFeatures::known(), &accept_channel);
280 let events = $source.get_and_clear_pending_events();
281 assert_eq!(events.len(), 1);
282 if let events::Event::FundingGenerationReady { ref temporary_channel_id, ref channel_value_satoshis, ref output_script, .. } = events[0] {
283 let tx = Transaction { version: $chan_id, lock_time: 0, input: Vec::new(), output: vec![TxOut {
284 value: *channel_value_satoshis, script_pubkey: output_script.clone(),
286 funding_output = OutPoint { txid: tx.txid(), index: 0 };
287 $source.funding_transaction_generated(&temporary_channel_id, funding_output);
288 channel_txn.push(tx);
289 } else { panic!("Wrong event type"); }
292 let funding_created = {
293 let events = $source.get_and_clear_pending_msg_events();
294 assert_eq!(events.len(), 1);
295 if let events::MessageSendEvent::SendFundingCreated { ref msg, .. } = events[0] {
297 } else { panic!("Wrong event type"); }
299 $dest.handle_funding_created(&$source.get_our_node_id(), &funding_created);
301 let funding_signed = {
302 let events = $dest.get_and_clear_pending_msg_events();
303 assert_eq!(events.len(), 1);
304 if let events::MessageSendEvent::SendFundingSigned { ref msg, .. } = events[0] {
306 } else { panic!("Wrong event type"); }
308 $source.handle_funding_signed(&$dest.get_our_node_id(), &funding_signed);
311 let events = $source.get_and_clear_pending_events();
312 assert_eq!(events.len(), 1);
313 if let events::Event::FundingBroadcastSafe { .. } = events[0] {
314 } else { panic!("Wrong event type"); }
320 macro_rules! confirm_txn {
322 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
323 let mut txn = Vec::with_capacity(channel_txn.len());
324 let mut posn = Vec::with_capacity(channel_txn.len());
325 for i in 0..channel_txn.len() {
326 txn.push(&channel_txn[i]);
329 $node.block_connected(&header, 1, &txn, &posn);
331 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
332 $node.block_connected(&header, i, &Vec::new(), &[0; 0]);
337 macro_rules! lock_fundings {
338 ($nodes: expr) => { {
339 let mut node_events = Vec::new();
340 for node in $nodes.iter() {
341 node_events.push(node.get_and_clear_pending_msg_events());
343 for (idx, node_event) in node_events.iter().enumerate() {
344 for event in node_event {
345 if let events::MessageSendEvent::SendFundingLocked { ref node_id, ref msg } = event {
346 for node in $nodes.iter() {
347 if node.get_our_node_id() == *node_id {
348 node.handle_funding_locked(&$nodes[idx].get_our_node_id(), msg);
351 } else { panic!("Wrong event type"); }
355 for node in $nodes.iter() {
356 let events = node.get_and_clear_pending_msg_events();
357 for event in events {
358 if let events::MessageSendEvent::SendAnnouncementSignatures { .. } = event {
359 } else { panic!("Wrong event type"); }
365 // 3 nodes is enough to hit all the possible cases, notably unknown-source-unknown-dest
367 let (mut node_a, mut monitor_a) = make_node!(0);
368 let (mut node_b, mut monitor_b) = make_node!(1);
369 let (mut node_c, mut monitor_c) = make_node!(2);
371 let mut nodes = [node_a, node_b, node_c];
373 let chan_1_funding = make_channel!(nodes[0], nodes[1], 0);
374 let chan_2_funding = make_channel!(nodes[1], nodes[2], 1);
376 for node in nodes.iter() {
380 lock_fundings!(nodes);
382 let chan_a = nodes[0].list_usable_channels()[0].short_channel_id.unwrap();
383 let chan_b = nodes[2].list_usable_channels()[0].short_channel_id.unwrap();
385 let mut payment_id = 0;
387 let mut chan_a_disconnected = false;
388 let mut chan_b_disconnected = false;
389 let mut ba_events = Vec::new();
390 let mut bc_events = Vec::new();
392 let mut node_a_ser = VecWriter(Vec::new());
393 nodes[0].write(&mut node_a_ser).unwrap();
394 let mut node_b_ser = VecWriter(Vec::new());
395 nodes[1].write(&mut node_b_ser).unwrap();
396 let mut node_c_ser = VecWriter(Vec::new());
397 nodes[2].write(&mut node_c_ser).unwrap();
399 macro_rules! test_return {
401 assert_eq!(nodes[0].list_channels().len(), 1);
402 assert_eq!(nodes[1].list_channels().len(), 2);
403 assert_eq!(nodes[2].list_channels().len(), 1);
408 let mut read_pos = 0;
409 macro_rules! get_slice {
412 let slice_len = $len as usize;
413 if data.len() < read_pos + slice_len {
416 read_pos += slice_len;
417 &data[read_pos - slice_len..read_pos]
423 macro_rules! send_payment {
424 ($source: expr, $dest: expr, $amt: expr) => { {
425 let payment_hash = Sha256::hash(&[payment_id; 1]);
426 payment_id = payment_id.wrapping_add(1);
427 if let Err(_) = $source.send_payment(&Route {
428 paths: vec![vec![RouteHop {
429 pubkey: $dest.0.get_our_node_id(),
430 node_features: NodeFeatures::empty(),
431 short_channel_id: $dest.1,
432 channel_features: ChannelFeatures::empty(),
434 cltv_expiry_delta: 200,
436 }, PaymentHash(payment_hash.into_inner()), &None) {
437 // Probably ran out of funds
441 ($source: expr, $middle: expr, $dest: expr, $amt: expr) => { {
442 let payment_hash = Sha256::hash(&[payment_id; 1]);
443 payment_id = payment_id.wrapping_add(1);
444 if let Err(_) = $source.send_payment(&Route {
445 paths: vec![vec![RouteHop {
446 pubkey: $middle.0.get_our_node_id(),
447 node_features: NodeFeatures::empty(),
448 short_channel_id: $middle.1,
449 channel_features: ChannelFeatures::empty(),
451 cltv_expiry_delta: 100,
453 pubkey: $dest.0.get_our_node_id(),
454 node_features: NodeFeatures::empty(),
455 short_channel_id: $dest.1,
456 channel_features: ChannelFeatures::empty(),
458 cltv_expiry_delta: 200,
460 }, PaymentHash(payment_hash.into_inner()), &None) {
461 // Probably ran out of funds
466 macro_rules! send_payment_with_secret {
467 ($source: expr, $middle: expr, $dest: expr) => { {
468 let payment_hash = Sha256::hash(&[payment_id; 1]);
469 payment_id = payment_id.wrapping_add(1);
470 let payment_secret = Sha256::hash(&[payment_id; 1]);
471 payment_id = payment_id.wrapping_add(1);
472 if let Err(_) = $source.send_payment(&Route {
473 paths: vec![vec![RouteHop {
474 pubkey: $middle.0.get_our_node_id(),
475 node_features: NodeFeatures::empty(),
476 short_channel_id: $middle.1,
477 channel_features: ChannelFeatures::empty(),
479 cltv_expiry_delta: 100,
481 pubkey: $dest.0.get_our_node_id(),
482 node_features: NodeFeatures::empty(),
483 short_channel_id: $dest.1,
484 channel_features: ChannelFeatures::empty(),
486 cltv_expiry_delta: 200,
488 pubkey: $middle.0.get_our_node_id(),
489 node_features: NodeFeatures::empty(),
490 short_channel_id: $middle.1,
491 channel_features: ChannelFeatures::empty(),
493 cltv_expiry_delta: 100,
495 pubkey: $dest.0.get_our_node_id(),
496 node_features: NodeFeatures::empty(),
497 short_channel_id: $dest.1,
498 channel_features: ChannelFeatures::empty(),
500 cltv_expiry_delta: 200,
502 }, PaymentHash(payment_hash.into_inner()), &Some(PaymentSecret(payment_secret.into_inner()))) {
503 // Probably ran out of funds
509 macro_rules! process_msg_events {
510 ($node: expr, $corrupt_forward: expr) => { {
511 let events = if $node == 1 {
512 let mut new_events = Vec::new();
513 mem::swap(&mut new_events, &mut ba_events);
514 new_events.extend_from_slice(&bc_events[..]);
517 } else { Vec::new() };
518 for event in events.iter().chain(nodes[$node].get_and_clear_pending_msg_events().iter()) {
520 events::MessageSendEvent::UpdateHTLCs { ref node_id, updates: CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, ref update_fulfill_htlcs, ref update_fail_malformed_htlcs, ref update_fee, ref commitment_signed } } => {
521 for dest in nodes.iter() {
522 if dest.get_our_node_id() == *node_id {
523 assert!(update_fee.is_none());
524 for update_add in update_add_htlcs {
525 if !$corrupt_forward {
526 dest.handle_update_add_htlc(&nodes[$node].get_our_node_id(), &update_add);
528 // Corrupt the update_add_htlc message so that its HMAC
529 // check will fail and we generate a
530 // update_fail_malformed_htlc instead of an
531 // update_fail_htlc as we do when we reject a payment.
532 let mut msg_ser = update_add.encode();
533 msg_ser[1000] ^= 0xff;
534 let new_msg = UpdateAddHTLC::read(&mut Cursor::new(&msg_ser)).unwrap();
535 dest.handle_update_add_htlc(&nodes[$node].get_our_node_id(), &new_msg);
538 for update_fulfill in update_fulfill_htlcs {
539 dest.handle_update_fulfill_htlc(&nodes[$node].get_our_node_id(), &update_fulfill);
541 for update_fail in update_fail_htlcs {
542 dest.handle_update_fail_htlc(&nodes[$node].get_our_node_id(), &update_fail);
544 for update_fail_malformed in update_fail_malformed_htlcs {
545 dest.handle_update_fail_malformed_htlc(&nodes[$node].get_our_node_id(), &update_fail_malformed);
547 dest.handle_commitment_signed(&nodes[$node].get_our_node_id(), &commitment_signed);
551 events::MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
552 for dest in nodes.iter() {
553 if dest.get_our_node_id() == *node_id {
554 dest.handle_revoke_and_ack(&nodes[$node].get_our_node_id(), msg);
558 events::MessageSendEvent::SendChannelReestablish { ref node_id, ref msg } => {
559 for dest in nodes.iter() {
560 if dest.get_our_node_id() == *node_id {
561 dest.handle_channel_reestablish(&nodes[$node].get_our_node_id(), msg);
565 events::MessageSendEvent::SendFundingLocked { .. } => {
566 // Can be generated as a reestablish response
568 events::MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {
569 // Can be generated due to a payment forward being rejected due to a
570 // channel having previously failed a monitor update
572 events::MessageSendEvent::HandleError { action: ErrorAction::IgnoreError, .. } => {
573 // Can be generated at any processing step to send back an error, disconnect
574 // peer or just ignore
576 _ => panic!("Unhandled message event"),
582 macro_rules! drain_msg_events_on_disconnect {
583 ($counterparty_id: expr) => { {
584 if $counterparty_id == 0 {
585 for event in nodes[0].get_and_clear_pending_msg_events() {
587 events::MessageSendEvent::UpdateHTLCs { .. } => {},
588 events::MessageSendEvent::SendRevokeAndACK { .. } => {},
589 events::MessageSendEvent::SendChannelReestablish { .. } => {},
590 events::MessageSendEvent::SendFundingLocked { .. } => {},
591 events::MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
592 events::MessageSendEvent::HandleError { action: ErrorAction::IgnoreError, .. } => {},
593 _ => panic!("Unhandled message event"),
598 for event in nodes[2].get_and_clear_pending_msg_events() {
600 events::MessageSendEvent::UpdateHTLCs { .. } => {},
601 events::MessageSendEvent::SendRevokeAndACK { .. } => {},
602 events::MessageSendEvent::SendChannelReestablish { .. } => {},
603 events::MessageSendEvent::SendFundingLocked { .. } => {},
604 events::MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
605 events::MessageSendEvent::HandleError { action: ErrorAction::IgnoreError, .. } => {},
606 _ => panic!("Unhandled message event"),
611 let mut events = nodes[1].get_and_clear_pending_msg_events();
612 let drop_node_id = if $counterparty_id == 0 { nodes[0].get_our_node_id() } else { nodes[2].get_our_node_id() };
613 let msg_sink = if $counterparty_id == 0 { &mut bc_events } else { &mut ba_events };
614 for event in events.drain(..) {
615 let push = match event {
616 events::MessageSendEvent::UpdateHTLCs { ref node_id, .. } => {
617 if *node_id != drop_node_id { true } else { false }
619 events::MessageSendEvent::SendRevokeAndACK { ref node_id, .. } => {
620 if *node_id != drop_node_id { true } else { false }
622 events::MessageSendEvent::SendChannelReestablish { ref node_id, .. } => {
623 if *node_id != drop_node_id { true } else { false }
625 events::MessageSendEvent::SendFundingLocked { .. } => false,
626 events::MessageSendEvent::PaymentFailureNetworkUpdate { .. } => false,
627 events::MessageSendEvent::HandleError { action: ErrorAction::IgnoreError, .. } => false,
628 _ => panic!("Unhandled message event"),
630 if push { msg_sink.push(event); }
635 macro_rules! process_events {
636 ($node: expr, $fail: expr) => { {
637 // In case we get 256 payments we may have a hash collision, resulting in the
638 // second claim/fail call not finding the duplicate-hash HTLC, so we have to
639 // deduplicate the calls here.
640 let mut claim_set = HashSet::new();
641 let mut events = nodes[$node].get_and_clear_pending_events();
642 // Sort events so that PendingHTLCsForwardable get processed last. This avoids a
643 // case where we first process a PendingHTLCsForwardable, then claim/fail on a
644 // PaymentReceived, claiming/failing two HTLCs, but leaving a just-generated
645 // PaymentReceived event for the second HTLC in our pending_events (and breaking
646 // our claim_set deduplication).
647 events.sort_by(|a, b| {
648 if let events::Event::PaymentReceived { .. } = a {
649 if let events::Event::PendingHTLCsForwardable { .. } = b {
651 } else { Ordering::Equal }
652 } else if let events::Event::PendingHTLCsForwardable { .. } = a {
653 if let events::Event::PaymentReceived { .. } = b {
655 } else { Ordering::Equal }
656 } else { Ordering::Equal }
658 for event in events.drain(..) {
660 events::Event::PaymentReceived { payment_hash, payment_secret, amt } => {
661 if claim_set.insert(payment_hash.0) {
663 assert!(nodes[$node].fail_htlc_backwards(&payment_hash, &payment_secret));
665 assert!(nodes[$node].claim_funds(PaymentPreimage(payment_hash.0), &payment_secret, amt));
669 events::Event::PaymentSent { .. } => {},
670 events::Event::PaymentFailed { .. } => {},
671 events::Event::PendingHTLCsForwardable { .. } => {
672 nodes[$node].process_pending_htlc_forwards();
674 _ => panic!("Unhandled event"),
680 match get_slice!(1)[0] {
681 0x00 => *monitor_a.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::TemporaryFailure),
682 0x01 => *monitor_b.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::TemporaryFailure),
683 0x02 => *monitor_c.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::TemporaryFailure),
684 0x03 => *monitor_a.update_ret.lock().unwrap() = Ok(()),
685 0x04 => *monitor_b.update_ret.lock().unwrap() = Ok(()),
686 0x05 => *monitor_c.update_ret.lock().unwrap() = Ok(()),
688 if let Some((id, _)) = monitor_a.latest_monitors.lock().unwrap().get(&chan_1_funding) {
689 nodes[0].channel_monitor_updated(&chan_1_funding, *id);
693 if let Some((id, _)) = monitor_b.latest_monitors.lock().unwrap().get(&chan_1_funding) {
694 nodes[1].channel_monitor_updated(&chan_1_funding, *id);
698 if let Some((id, _)) = monitor_b.latest_monitors.lock().unwrap().get(&chan_2_funding) {
699 nodes[1].channel_monitor_updated(&chan_2_funding, *id);
703 if let Some((id, _)) = monitor_c.latest_monitors.lock().unwrap().get(&chan_2_funding) {
704 nodes[2].channel_monitor_updated(&chan_2_funding, *id);
707 0x09 => send_payment!(nodes[0], (&nodes[1], chan_a), 5_000_000),
708 0x0a => send_payment!(nodes[1], (&nodes[0], chan_a), 5_000_000),
709 0x0b => send_payment!(nodes[1], (&nodes[2], chan_b), 5_000_000),
710 0x0c => send_payment!(nodes[2], (&nodes[1], chan_b), 5_000_000),
711 0x0d => send_payment!(nodes[0], (&nodes[1], chan_a), (&nodes[2], chan_b), 5_000_000),
712 0x0e => send_payment!(nodes[2], (&nodes[1], chan_b), (&nodes[0], chan_a), 5_000_000),
714 if !chan_a_disconnected {
715 nodes[0].peer_disconnected(&nodes[1].get_our_node_id(), false);
716 nodes[1].peer_disconnected(&nodes[0].get_our_node_id(), false);
717 chan_a_disconnected = true;
718 drain_msg_events_on_disconnect!(0);
722 if !chan_b_disconnected {
723 nodes[1].peer_disconnected(&nodes[2].get_our_node_id(), false);
724 nodes[2].peer_disconnected(&nodes[1].get_our_node_id(), false);
725 chan_b_disconnected = true;
726 drain_msg_events_on_disconnect!(2);
730 if chan_a_disconnected {
731 nodes[0].peer_connected(&nodes[1].get_our_node_id(), &Init { features: InitFeatures::empty() });
732 nodes[1].peer_connected(&nodes[0].get_our_node_id(), &Init { features: InitFeatures::empty() });
733 chan_a_disconnected = false;
737 if chan_b_disconnected {
738 nodes[1].peer_connected(&nodes[2].get_our_node_id(), &Init { features: InitFeatures::empty() });
739 nodes[2].peer_connected(&nodes[1].get_our_node_id(), &Init { features: InitFeatures::empty() });
740 chan_b_disconnected = false;
743 0x13 => process_msg_events!(0, true),
744 0x14 => process_msg_events!(0, false),
745 0x15 => process_events!(0, true),
746 0x16 => process_events!(0, false),
747 0x17 => process_msg_events!(1, true),
748 0x18 => process_msg_events!(1, false),
749 0x19 => process_events!(1, true),
750 0x1a => process_events!(1, false),
751 0x1b => process_msg_events!(2, true),
752 0x1c => process_msg_events!(2, false),
753 0x1d => process_events!(2, true),
754 0x1e => process_events!(2, false),
756 if !chan_a_disconnected {
757 nodes[1].peer_disconnected(&nodes[0].get_our_node_id(), false);
758 chan_a_disconnected = true;
759 drain_msg_events_on_disconnect!(0);
761 let (new_node_a, new_monitor_a) = reload_node!(node_a_ser, 0, monitor_a);
762 node_a = Arc::new(new_node_a);
763 nodes[0] = node_a.clone();
764 monitor_a = new_monitor_a;
767 if !chan_a_disconnected {
768 nodes[0].peer_disconnected(&nodes[1].get_our_node_id(), false);
769 chan_a_disconnected = true;
770 nodes[0].get_and_clear_pending_msg_events();
773 if !chan_b_disconnected {
774 nodes[2].peer_disconnected(&nodes[1].get_our_node_id(), false);
775 chan_b_disconnected = true;
776 nodes[2].get_and_clear_pending_msg_events();
779 let (new_node_b, new_monitor_b) = reload_node!(node_b_ser, 1, monitor_b);
780 node_b = Arc::new(new_node_b);
781 nodes[1] = node_b.clone();
782 monitor_b = new_monitor_b;
785 if !chan_b_disconnected {
786 nodes[1].peer_disconnected(&nodes[2].get_our_node_id(), false);
787 chan_b_disconnected = true;
788 drain_msg_events_on_disconnect!(2);
790 let (new_node_c, new_monitor_c) = reload_node!(node_c_ser, 2, monitor_c);
791 node_c = Arc::new(new_node_c);
792 nodes[2] = node_c.clone();
793 monitor_c = new_monitor_c;
795 0x22 => send_payment_with_secret!(nodes[0], (&nodes[1], chan_a), (&nodes[2], chan_b)),
796 0x23 => send_payment_with_secret!(nodes[2], (&nodes[1], chan_b), (&nodes[0], chan_a)),
797 0x25 => send_payment!(nodes[0], (&nodes[1], chan_a), 10),
798 0x26 => send_payment!(nodes[1], (&nodes[0], chan_a), 10),
799 0x27 => send_payment!(nodes[1], (&nodes[2], chan_b), 10),
800 0x28 => send_payment!(nodes[2], (&nodes[1], chan_b), 10),
801 0x29 => send_payment!(nodes[0], (&nodes[1], chan_a), (&nodes[2], chan_b), 10),
802 0x2a => send_payment!(nodes[2], (&nodes[1], chan_b), (&nodes[0], chan_a), 10),
803 0x2b => send_payment!(nodes[0], (&nodes[1], chan_a), 1_000),
804 0x2c => send_payment!(nodes[1], (&nodes[0], chan_a), 1_000),
805 0x2d => send_payment!(nodes[1], (&nodes[2], chan_b), 1_000),
806 0x2e => send_payment!(nodes[2], (&nodes[1], chan_b), 1_000),
807 0x2f => send_payment!(nodes[0], (&nodes[1], chan_a), (&nodes[2], chan_b), 1_000),
808 0x30 => send_payment!(nodes[2], (&nodes[1], chan_b), (&nodes[0], chan_a), 1_000),
809 0x31 => send_payment!(nodes[0], (&nodes[1], chan_a), 100_000),
810 0x32 => send_payment!(nodes[1], (&nodes[0], chan_a), 100_000),
811 0x33 => send_payment!(nodes[1], (&nodes[2], chan_b), 100_000),
812 0x34 => send_payment!(nodes[2], (&nodes[1], chan_b), 100_000),
813 0x35 => send_payment!(nodes[0], (&nodes[1], chan_a), (&nodes[2], chan_b), 100_000),
814 0x36 => send_payment!(nodes[2], (&nodes[1], chan_b), (&nodes[0], chan_a), 100_000),
815 // 0x24 defined above
819 node_a_ser.0.clear();
820 nodes[0].write(&mut node_a_ser).unwrap();
821 monitor_a.should_update_manager.store(false, atomic::Ordering::Relaxed);
822 node_b_ser.0.clear();
823 nodes[1].write(&mut node_b_ser).unwrap();
824 monitor_b.should_update_manager.store(false, atomic::Ordering::Relaxed);
825 node_c_ser.0.clear();
826 nodes[2].write(&mut node_c_ser).unwrap();
827 monitor_c.should_update_manager.store(false, atomic::Ordering::Relaxed);
831 pub fn chanmon_consistency_test<Out: test_logger::Output>(data: &[u8], out: Out) {
836 pub extern "C" fn chanmon_consistency_run(data: *const u8, datalen: usize) {
837 do_test(unsafe { std::slice::from_raw_parts(data, datalen) }, test_logger::DevNull{});