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, MonitorEvent};
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_and_clear_pending_monitor_events(&self) -> Vec<MonitorEvent> {
139 return self.simple_monitor.get_and_clear_pending_monitor_events();
145 rand_bytes_id: atomic::AtomicU8,
147 impl KeysInterface for KeyProvider {
148 type ChanKeySigner = EnforcingChannelKeys;
150 fn get_node_secret(&self) -> SecretKey {
151 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()
154 fn get_destination_script(&self) -> Script {
155 let secp_ctx = Secp256k1::signing_only();
156 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();
157 let our_channel_monitor_claim_key_hash = WPubkeyHash::hash(&PublicKey::from_secret_key(&secp_ctx, &channel_monitor_claim_key).serialize());
158 Builder::new().push_opcode(opcodes::all::OP_PUSHBYTES_0).push_slice(&our_channel_monitor_claim_key_hash[..]).into_script()
161 fn get_shutdown_pubkey(&self) -> PublicKey {
162 let secp_ctx = Secp256k1::signing_only();
163 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())
166 fn get_channel_keys(&self, _inbound: bool, channel_value_satoshis: u64) -> EnforcingChannelKeys {
167 let secp_ctx = Secp256k1::signing_only();
168 EnforcingChannelKeys::new(InMemoryChannelKeys::new(
170 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(),
171 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(),
172 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(),
173 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(),
174 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(),
175 [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],
176 channel_value_satoshis,
181 fn get_secure_random_bytes(&self) -> [u8; 32] {
182 let id = self.rand_bytes_id.fetch_add(1, atomic::Ordering::Relaxed);
183 [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]
188 pub fn do_test<Out: test_logger::Output>(data: &[u8], out: Out) {
189 let fee_est = Arc::new(FuzzEstimator{});
190 let broadcast = Arc::new(TestBroadcaster{});
192 macro_rules! make_node {
193 ($node_id: expr) => { {
194 let logger: Arc<dyn Logger> = Arc::new(test_logger::TestLogger::new($node_id.to_string(), out.clone()));
195 let watch = Arc::new(ChainWatchInterfaceUtil::new(Network::Bitcoin));
196 let monitor = Arc::new(TestChannelMonitor::new(watch.clone(), broadcast.clone(), logger.clone(), fee_est.clone()));
198 let keys_manager = Arc::new(KeyProvider { node_id: $node_id, rand_bytes_id: atomic::AtomicU8::new(0) });
199 let mut config = UserConfig::default();
200 config.channel_options.fee_proportional_millionths = 0;
201 config.channel_options.announced_channel = true;
202 config.peer_channel_config_limits.min_dust_limit_satoshis = 0;
203 (Arc::new(ChannelManager::new(Network::Bitcoin, fee_est.clone(), monitor.clone(), broadcast.clone(), Arc::clone(&logger), keys_manager.clone(), config, 0)),
208 macro_rules! reload_node {
209 ($ser: expr, $node_id: expr, $old_monitors: expr) => { {
210 let logger: Arc<dyn Logger> = Arc::new(test_logger::TestLogger::new($node_id.to_string(), out.clone()));
211 let watch = Arc::new(ChainWatchInterfaceUtil::new(Network::Bitcoin));
212 let monitor = Arc::new(TestChannelMonitor::new(watch.clone(), broadcast.clone(), logger.clone(), fee_est.clone()));
214 let keys_manager = Arc::new(KeyProvider { node_id: $node_id, rand_bytes_id: atomic::AtomicU8::new(0) });
215 let mut config = UserConfig::default();
216 config.channel_options.fee_proportional_millionths = 0;
217 config.channel_options.announced_channel = true;
218 config.peer_channel_config_limits.min_dust_limit_satoshis = 0;
220 let mut monitors = HashMap::new();
221 let mut old_monitors = $old_monitors.latest_monitors.lock().unwrap();
222 for (outpoint, (update_id, monitor_ser)) in old_monitors.drain() {
223 monitors.insert(outpoint, <(BlockHash, ChannelMonitor<EnforcingChannelKeys>)>::read(&mut Cursor::new(&monitor_ser)).expect("Failed to read monitor").1);
224 monitor.latest_monitors.lock().unwrap().insert(outpoint, (update_id, monitor_ser));
226 let mut monitor_refs = HashMap::new();
227 for (outpoint, monitor) in monitors.iter_mut() {
228 monitor_refs.insert(*outpoint, monitor);
231 let read_args = ChannelManagerReadArgs {
233 fee_estimator: fee_est.clone(),
234 monitor: monitor.clone(),
235 tx_broadcaster: broadcast.clone(),
237 default_config: config,
238 channel_monitors: monitor_refs,
241 (<(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)
245 let mut channel_txn = Vec::new();
246 macro_rules! make_channel {
247 ($source: expr, $dest: expr, $chan_id: expr) => { {
248 $source.create_channel($dest.get_our_node_id(), 10000000, 42, 0, None).unwrap();
250 let events = $source.get_and_clear_pending_msg_events();
251 assert_eq!(events.len(), 1);
252 if let events::MessageSendEvent::SendOpenChannel { ref msg, .. } = events[0] {
254 } else { panic!("Wrong event type"); }
257 $dest.handle_open_channel(&$source.get_our_node_id(), InitFeatures::known(), &open_channel);
258 let accept_channel = {
259 let events = $dest.get_and_clear_pending_msg_events();
260 assert_eq!(events.len(), 1);
261 if let events::MessageSendEvent::SendAcceptChannel { ref msg, .. } = events[0] {
263 } else { panic!("Wrong event type"); }
266 $source.handle_accept_channel(&$dest.get_our_node_id(), InitFeatures::known(), &accept_channel);
269 let events = $source.get_and_clear_pending_events();
270 assert_eq!(events.len(), 1);
271 if let events::Event::FundingGenerationReady { ref temporary_channel_id, ref channel_value_satoshis, ref output_script, .. } = events[0] {
272 let tx = Transaction { version: $chan_id, lock_time: 0, input: Vec::new(), output: vec![TxOut {
273 value: *channel_value_satoshis, script_pubkey: output_script.clone(),
275 funding_output = OutPoint { txid: tx.txid(), index: 0 };
276 $source.funding_transaction_generated(&temporary_channel_id, funding_output);
277 channel_txn.push(tx);
278 } else { panic!("Wrong event type"); }
281 let funding_created = {
282 let events = $source.get_and_clear_pending_msg_events();
283 assert_eq!(events.len(), 1);
284 if let events::MessageSendEvent::SendFundingCreated { ref msg, .. } = events[0] {
286 } else { panic!("Wrong event type"); }
288 $dest.handle_funding_created(&$source.get_our_node_id(), &funding_created);
290 let funding_signed = {
291 let events = $dest.get_and_clear_pending_msg_events();
292 assert_eq!(events.len(), 1);
293 if let events::MessageSendEvent::SendFundingSigned { ref msg, .. } = events[0] {
295 } else { panic!("Wrong event type"); }
297 $source.handle_funding_signed(&$dest.get_our_node_id(), &funding_signed);
300 let events = $source.get_and_clear_pending_events();
301 assert_eq!(events.len(), 1);
302 if let events::Event::FundingBroadcastSafe { .. } = events[0] {
303 } else { panic!("Wrong event type"); }
309 macro_rules! confirm_txn {
311 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
312 let mut txn = Vec::with_capacity(channel_txn.len());
313 let mut posn = Vec::with_capacity(channel_txn.len());
314 for i in 0..channel_txn.len() {
315 txn.push(&channel_txn[i]);
318 $node.block_connected(&header, 1, &txn, &posn);
320 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
321 $node.block_connected(&header, i, &Vec::new(), &[0; 0]);
326 macro_rules! lock_fundings {
327 ($nodes: expr) => { {
328 let mut node_events = Vec::new();
329 for node in $nodes.iter() {
330 node_events.push(node.get_and_clear_pending_msg_events());
332 for (idx, node_event) in node_events.iter().enumerate() {
333 for event in node_event {
334 if let events::MessageSendEvent::SendFundingLocked { ref node_id, ref msg } = event {
335 for node in $nodes.iter() {
336 if node.get_our_node_id() == *node_id {
337 node.handle_funding_locked(&$nodes[idx].get_our_node_id(), msg);
340 } else { panic!("Wrong event type"); }
344 for node in $nodes.iter() {
345 let events = node.get_and_clear_pending_msg_events();
346 for event in events {
347 if let events::MessageSendEvent::SendAnnouncementSignatures { .. } = event {
348 } else { panic!("Wrong event type"); }
354 // 3 nodes is enough to hit all the possible cases, notably unknown-source-unknown-dest
356 let (mut node_a, mut monitor_a) = make_node!(0);
357 let (mut node_b, mut monitor_b) = make_node!(1);
358 let (mut node_c, mut monitor_c) = make_node!(2);
360 let mut nodes = [node_a, node_b, node_c];
362 let chan_1_funding = make_channel!(nodes[0], nodes[1], 0);
363 let chan_2_funding = make_channel!(nodes[1], nodes[2], 1);
365 for node in nodes.iter() {
369 lock_fundings!(nodes);
371 let chan_a = nodes[0].list_usable_channels()[0].short_channel_id.unwrap();
372 let chan_b = nodes[2].list_usable_channels()[0].short_channel_id.unwrap();
374 let mut payment_id = 0;
376 let mut chan_a_disconnected = false;
377 let mut chan_b_disconnected = false;
378 let mut ba_events = Vec::new();
379 let mut bc_events = Vec::new();
381 let mut node_a_ser = VecWriter(Vec::new());
382 nodes[0].write(&mut node_a_ser).unwrap();
383 let mut node_b_ser = VecWriter(Vec::new());
384 nodes[1].write(&mut node_b_ser).unwrap();
385 let mut node_c_ser = VecWriter(Vec::new());
386 nodes[2].write(&mut node_c_ser).unwrap();
388 macro_rules! test_return {
390 assert_eq!(nodes[0].list_channels().len(), 1);
391 assert_eq!(nodes[1].list_channels().len(), 2);
392 assert_eq!(nodes[2].list_channels().len(), 1);
397 let mut read_pos = 0;
398 macro_rules! get_slice {
401 let slice_len = $len as usize;
402 if data.len() < read_pos + slice_len {
405 read_pos += slice_len;
406 &data[read_pos - slice_len..read_pos]
412 macro_rules! send_payment {
413 ($source: expr, $dest: expr, $amt: expr) => { {
414 let payment_hash = Sha256::hash(&[payment_id; 1]);
415 payment_id = payment_id.wrapping_add(1);
416 if let Err(_) = $source.send_payment(&Route {
417 paths: vec![vec![RouteHop {
418 pubkey: $dest.0.get_our_node_id(),
419 node_features: NodeFeatures::empty(),
420 short_channel_id: $dest.1,
421 channel_features: ChannelFeatures::empty(),
423 cltv_expiry_delta: 200,
425 }, PaymentHash(payment_hash.into_inner()), &None) {
426 // Probably ran out of funds
430 ($source: expr, $middle: expr, $dest: expr, $amt: expr) => { {
431 let payment_hash = Sha256::hash(&[payment_id; 1]);
432 payment_id = payment_id.wrapping_add(1);
433 if let Err(_) = $source.send_payment(&Route {
434 paths: vec![vec![RouteHop {
435 pubkey: $middle.0.get_our_node_id(),
436 node_features: NodeFeatures::empty(),
437 short_channel_id: $middle.1,
438 channel_features: ChannelFeatures::empty(),
440 cltv_expiry_delta: 100,
442 pubkey: $dest.0.get_our_node_id(),
443 node_features: NodeFeatures::empty(),
444 short_channel_id: $dest.1,
445 channel_features: ChannelFeatures::empty(),
447 cltv_expiry_delta: 200,
449 }, PaymentHash(payment_hash.into_inner()), &None) {
450 // Probably ran out of funds
455 macro_rules! send_payment_with_secret {
456 ($source: expr, $middle: expr, $dest: expr) => { {
457 let payment_hash = Sha256::hash(&[payment_id; 1]);
458 payment_id = payment_id.wrapping_add(1);
459 let payment_secret = Sha256::hash(&[payment_id; 1]);
460 payment_id = payment_id.wrapping_add(1);
461 if let Err(_) = $source.send_payment(&Route {
462 paths: vec![vec![RouteHop {
463 pubkey: $middle.0.get_our_node_id(),
464 node_features: NodeFeatures::empty(),
465 short_channel_id: $middle.1,
466 channel_features: ChannelFeatures::empty(),
468 cltv_expiry_delta: 100,
470 pubkey: $dest.0.get_our_node_id(),
471 node_features: NodeFeatures::empty(),
472 short_channel_id: $dest.1,
473 channel_features: ChannelFeatures::empty(),
475 cltv_expiry_delta: 200,
477 pubkey: $middle.0.get_our_node_id(),
478 node_features: NodeFeatures::empty(),
479 short_channel_id: $middle.1,
480 channel_features: ChannelFeatures::empty(),
482 cltv_expiry_delta: 100,
484 pubkey: $dest.0.get_our_node_id(),
485 node_features: NodeFeatures::empty(),
486 short_channel_id: $dest.1,
487 channel_features: ChannelFeatures::empty(),
489 cltv_expiry_delta: 200,
491 }, PaymentHash(payment_hash.into_inner()), &Some(PaymentSecret(payment_secret.into_inner()))) {
492 // Probably ran out of funds
498 macro_rules! process_msg_events {
499 ($node: expr, $corrupt_forward: expr) => { {
500 let events = if $node == 1 {
501 let mut new_events = Vec::new();
502 mem::swap(&mut new_events, &mut ba_events);
503 new_events.extend_from_slice(&bc_events[..]);
506 } else { Vec::new() };
507 for event in events.iter().chain(nodes[$node].get_and_clear_pending_msg_events().iter()) {
509 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 } } => {
510 for dest in nodes.iter() {
511 if dest.get_our_node_id() == *node_id {
512 assert!(update_fee.is_none());
513 for update_add in update_add_htlcs {
514 if !$corrupt_forward {
515 dest.handle_update_add_htlc(&nodes[$node].get_our_node_id(), &update_add);
517 // Corrupt the update_add_htlc message so that its HMAC
518 // check will fail and we generate a
519 // update_fail_malformed_htlc instead of an
520 // update_fail_htlc as we do when we reject a payment.
521 let mut msg_ser = update_add.encode();
522 msg_ser[1000] ^= 0xff;
523 let new_msg = UpdateAddHTLC::read(&mut Cursor::new(&msg_ser)).unwrap();
524 dest.handle_update_add_htlc(&nodes[$node].get_our_node_id(), &new_msg);
527 for update_fulfill in update_fulfill_htlcs {
528 dest.handle_update_fulfill_htlc(&nodes[$node].get_our_node_id(), &update_fulfill);
530 for update_fail in update_fail_htlcs {
531 dest.handle_update_fail_htlc(&nodes[$node].get_our_node_id(), &update_fail);
533 for update_fail_malformed in update_fail_malformed_htlcs {
534 dest.handle_update_fail_malformed_htlc(&nodes[$node].get_our_node_id(), &update_fail_malformed);
536 dest.handle_commitment_signed(&nodes[$node].get_our_node_id(), &commitment_signed);
540 events::MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
541 for dest in nodes.iter() {
542 if dest.get_our_node_id() == *node_id {
543 dest.handle_revoke_and_ack(&nodes[$node].get_our_node_id(), msg);
547 events::MessageSendEvent::SendChannelReestablish { ref node_id, ref msg } => {
548 for dest in nodes.iter() {
549 if dest.get_our_node_id() == *node_id {
550 dest.handle_channel_reestablish(&nodes[$node].get_our_node_id(), msg);
554 events::MessageSendEvent::SendFundingLocked { .. } => {
555 // Can be generated as a reestablish response
557 events::MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {
558 // Can be generated due to a payment forward being rejected due to a
559 // channel having previously failed a monitor update
561 events::MessageSendEvent::HandleError { action: ErrorAction::IgnoreError, .. } => {
562 // Can be generated at any processing step to send back an error, disconnect
563 // peer or just ignore
565 _ => panic!("Unhandled message event"),
571 macro_rules! drain_msg_events_on_disconnect {
572 ($counterparty_id: expr) => { {
573 if $counterparty_id == 0 {
574 for event in nodes[0].get_and_clear_pending_msg_events() {
576 events::MessageSendEvent::UpdateHTLCs { .. } => {},
577 events::MessageSendEvent::SendRevokeAndACK { .. } => {},
578 events::MessageSendEvent::SendChannelReestablish { .. } => {},
579 events::MessageSendEvent::SendFundingLocked { .. } => {},
580 events::MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
581 events::MessageSendEvent::HandleError { action: ErrorAction::IgnoreError, .. } => {},
582 _ => panic!("Unhandled message event"),
587 for event in nodes[2].get_and_clear_pending_msg_events() {
589 events::MessageSendEvent::UpdateHTLCs { .. } => {},
590 events::MessageSendEvent::SendRevokeAndACK { .. } => {},
591 events::MessageSendEvent::SendChannelReestablish { .. } => {},
592 events::MessageSendEvent::SendFundingLocked { .. } => {},
593 events::MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
594 events::MessageSendEvent::HandleError { action: ErrorAction::IgnoreError, .. } => {},
595 _ => panic!("Unhandled message event"),
600 let mut events = nodes[1].get_and_clear_pending_msg_events();
601 let drop_node_id = if $counterparty_id == 0 { nodes[0].get_our_node_id() } else { nodes[2].get_our_node_id() };
602 let msg_sink = if $counterparty_id == 0 { &mut bc_events } else { &mut ba_events };
603 for event in events.drain(..) {
604 let push = match event {
605 events::MessageSendEvent::UpdateHTLCs { ref node_id, .. } => {
606 if *node_id != drop_node_id { true } else { false }
608 events::MessageSendEvent::SendRevokeAndACK { ref node_id, .. } => {
609 if *node_id != drop_node_id { true } else { false }
611 events::MessageSendEvent::SendChannelReestablish { ref node_id, .. } => {
612 if *node_id != drop_node_id { true } else { false }
614 events::MessageSendEvent::SendFundingLocked { .. } => false,
615 events::MessageSendEvent::PaymentFailureNetworkUpdate { .. } => false,
616 events::MessageSendEvent::HandleError { action: ErrorAction::IgnoreError, .. } => false,
617 _ => panic!("Unhandled message event"),
619 if push { msg_sink.push(event); }
624 macro_rules! process_events {
625 ($node: expr, $fail: expr) => { {
626 // In case we get 256 payments we may have a hash collision, resulting in the
627 // second claim/fail call not finding the duplicate-hash HTLC, so we have to
628 // deduplicate the calls here.
629 let mut claim_set = HashSet::new();
630 let mut events = nodes[$node].get_and_clear_pending_events();
631 // Sort events so that PendingHTLCsForwardable get processed last. This avoids a
632 // case where we first process a PendingHTLCsForwardable, then claim/fail on a
633 // PaymentReceived, claiming/failing two HTLCs, but leaving a just-generated
634 // PaymentReceived event for the second HTLC in our pending_events (and breaking
635 // our claim_set deduplication).
636 events.sort_by(|a, b| {
637 if let events::Event::PaymentReceived { .. } = a {
638 if let events::Event::PendingHTLCsForwardable { .. } = b {
640 } else { Ordering::Equal }
641 } else if let events::Event::PendingHTLCsForwardable { .. } = a {
642 if let events::Event::PaymentReceived { .. } = b {
644 } else { Ordering::Equal }
645 } else { Ordering::Equal }
647 for event in events.drain(..) {
649 events::Event::PaymentReceived { payment_hash, payment_secret, amt } => {
650 if claim_set.insert(payment_hash.0) {
652 assert!(nodes[$node].fail_htlc_backwards(&payment_hash, &payment_secret));
654 assert!(nodes[$node].claim_funds(PaymentPreimage(payment_hash.0), &payment_secret, amt));
658 events::Event::PaymentSent { .. } => {},
659 events::Event::PaymentFailed { .. } => {},
660 events::Event::PendingHTLCsForwardable { .. } => {
661 nodes[$node].process_pending_htlc_forwards();
663 _ => panic!("Unhandled event"),
669 match get_slice!(1)[0] {
670 0x00 => *monitor_a.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::TemporaryFailure),
671 0x01 => *monitor_b.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::TemporaryFailure),
672 0x02 => *monitor_c.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::TemporaryFailure),
673 0x03 => *monitor_a.update_ret.lock().unwrap() = Ok(()),
674 0x04 => *monitor_b.update_ret.lock().unwrap() = Ok(()),
675 0x05 => *monitor_c.update_ret.lock().unwrap() = Ok(()),
677 if let Some((id, _)) = monitor_a.latest_monitors.lock().unwrap().get(&chan_1_funding) {
678 nodes[0].channel_monitor_updated(&chan_1_funding, *id);
682 if let Some((id, _)) = monitor_b.latest_monitors.lock().unwrap().get(&chan_1_funding) {
683 nodes[1].channel_monitor_updated(&chan_1_funding, *id);
687 if let Some((id, _)) = monitor_b.latest_monitors.lock().unwrap().get(&chan_2_funding) {
688 nodes[1].channel_monitor_updated(&chan_2_funding, *id);
692 if let Some((id, _)) = monitor_c.latest_monitors.lock().unwrap().get(&chan_2_funding) {
693 nodes[2].channel_monitor_updated(&chan_2_funding, *id);
696 0x09 => send_payment!(nodes[0], (&nodes[1], chan_a), 5_000_000),
697 0x0a => send_payment!(nodes[1], (&nodes[0], chan_a), 5_000_000),
698 0x0b => send_payment!(nodes[1], (&nodes[2], chan_b), 5_000_000),
699 0x0c => send_payment!(nodes[2], (&nodes[1], chan_b), 5_000_000),
700 0x0d => send_payment!(nodes[0], (&nodes[1], chan_a), (&nodes[2], chan_b), 5_000_000),
701 0x0e => send_payment!(nodes[2], (&nodes[1], chan_b), (&nodes[0], chan_a), 5_000_000),
703 if !chan_a_disconnected {
704 nodes[0].peer_disconnected(&nodes[1].get_our_node_id(), false);
705 nodes[1].peer_disconnected(&nodes[0].get_our_node_id(), false);
706 chan_a_disconnected = true;
707 drain_msg_events_on_disconnect!(0);
711 if !chan_b_disconnected {
712 nodes[1].peer_disconnected(&nodes[2].get_our_node_id(), false);
713 nodes[2].peer_disconnected(&nodes[1].get_our_node_id(), false);
714 chan_b_disconnected = true;
715 drain_msg_events_on_disconnect!(2);
719 if chan_a_disconnected {
720 nodes[0].peer_connected(&nodes[1].get_our_node_id(), &Init { features: InitFeatures::empty() });
721 nodes[1].peer_connected(&nodes[0].get_our_node_id(), &Init { features: InitFeatures::empty() });
722 chan_a_disconnected = false;
726 if chan_b_disconnected {
727 nodes[1].peer_connected(&nodes[2].get_our_node_id(), &Init { features: InitFeatures::empty() });
728 nodes[2].peer_connected(&nodes[1].get_our_node_id(), &Init { features: InitFeatures::empty() });
729 chan_b_disconnected = false;
732 0x13 => process_msg_events!(0, true),
733 0x14 => process_msg_events!(0, false),
734 0x15 => process_events!(0, true),
735 0x16 => process_events!(0, false),
736 0x17 => process_msg_events!(1, true),
737 0x18 => process_msg_events!(1, false),
738 0x19 => process_events!(1, true),
739 0x1a => process_events!(1, false),
740 0x1b => process_msg_events!(2, true),
741 0x1c => process_msg_events!(2, false),
742 0x1d => process_events!(2, true),
743 0x1e => process_events!(2, false),
745 if !chan_a_disconnected {
746 nodes[1].peer_disconnected(&nodes[0].get_our_node_id(), false);
747 chan_a_disconnected = true;
748 drain_msg_events_on_disconnect!(0);
750 let (new_node_a, new_monitor_a) = reload_node!(node_a_ser, 0, monitor_a);
751 node_a = Arc::new(new_node_a);
752 nodes[0] = node_a.clone();
753 monitor_a = new_monitor_a;
756 if !chan_a_disconnected {
757 nodes[0].peer_disconnected(&nodes[1].get_our_node_id(), false);
758 chan_a_disconnected = true;
759 nodes[0].get_and_clear_pending_msg_events();
762 if !chan_b_disconnected {
763 nodes[2].peer_disconnected(&nodes[1].get_our_node_id(), false);
764 chan_b_disconnected = true;
765 nodes[2].get_and_clear_pending_msg_events();
768 let (new_node_b, new_monitor_b) = reload_node!(node_b_ser, 1, monitor_b);
769 node_b = Arc::new(new_node_b);
770 nodes[1] = node_b.clone();
771 monitor_b = new_monitor_b;
774 if !chan_b_disconnected {
775 nodes[1].peer_disconnected(&nodes[2].get_our_node_id(), false);
776 chan_b_disconnected = true;
777 drain_msg_events_on_disconnect!(2);
779 let (new_node_c, new_monitor_c) = reload_node!(node_c_ser, 2, monitor_c);
780 node_c = Arc::new(new_node_c);
781 nodes[2] = node_c.clone();
782 monitor_c = new_monitor_c;
784 0x22 => send_payment_with_secret!(nodes[0], (&nodes[1], chan_a), (&nodes[2], chan_b)),
785 0x23 => send_payment_with_secret!(nodes[2], (&nodes[1], chan_b), (&nodes[0], chan_a)),
786 0x25 => send_payment!(nodes[0], (&nodes[1], chan_a), 10),
787 0x26 => send_payment!(nodes[1], (&nodes[0], chan_a), 10),
788 0x27 => send_payment!(nodes[1], (&nodes[2], chan_b), 10),
789 0x28 => send_payment!(nodes[2], (&nodes[1], chan_b), 10),
790 0x29 => send_payment!(nodes[0], (&nodes[1], chan_a), (&nodes[2], chan_b), 10),
791 0x2a => send_payment!(nodes[2], (&nodes[1], chan_b), (&nodes[0], chan_a), 10),
792 0x2b => send_payment!(nodes[0], (&nodes[1], chan_a), 1_000),
793 0x2c => send_payment!(nodes[1], (&nodes[0], chan_a), 1_000),
794 0x2d => send_payment!(nodes[1], (&nodes[2], chan_b), 1_000),
795 0x2e => send_payment!(nodes[2], (&nodes[1], chan_b), 1_000),
796 0x2f => send_payment!(nodes[0], (&nodes[1], chan_a), (&nodes[2], chan_b), 1_000),
797 0x30 => send_payment!(nodes[2], (&nodes[1], chan_b), (&nodes[0], chan_a), 1_000),
798 0x31 => send_payment!(nodes[0], (&nodes[1], chan_a), 100_000),
799 0x32 => send_payment!(nodes[1], (&nodes[0], chan_a), 100_000),
800 0x33 => send_payment!(nodes[1], (&nodes[2], chan_b), 100_000),
801 0x34 => send_payment!(nodes[2], (&nodes[1], chan_b), 100_000),
802 0x35 => send_payment!(nodes[0], (&nodes[1], chan_a), (&nodes[2], chan_b), 100_000),
803 0x36 => send_payment!(nodes[2], (&nodes[1], chan_b), (&nodes[0], chan_a), 100_000),
804 // 0x24 defined above
808 node_a_ser.0.clear();
809 nodes[0].write(&mut node_a_ser).unwrap();
810 monitor_a.should_update_manager.store(false, atomic::Ordering::Relaxed);
811 node_b_ser.0.clear();
812 nodes[1].write(&mut node_b_ser).unwrap();
813 monitor_b.should_update_manager.store(false, atomic::Ordering::Relaxed);
814 node_c_ser.0.clear();
815 nodes[2].write(&mut node_c_ser).unwrap();
816 monitor_c.should_update_manager.store(false, atomic::Ordering::Relaxed);
820 pub fn chanmon_consistency_test<Out: test_logger::Output>(data: &[u8], out: Out) {
825 pub extern "C" fn chanmon_consistency_run(data: *const u8, datalen: usize) {
826 do_test(unsafe { std::slice::from_raw_parts(data, datalen) }, test_logger::DevNull{});