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::blockdata::block::BlockHeader;
22 use bitcoin::blockdata::transaction::{Transaction, TxOut};
23 use bitcoin::blockdata::script::{Builder, Script};
24 use bitcoin::blockdata::opcodes;
25 use bitcoin::network::constants::Network;
27 use bitcoin::hashes::Hash as TraitImport;
28 use bitcoin::hashes::sha256::Hash as Sha256;
29 use bitcoin::hash_types::{BlockHash, WPubkeyHash};
31 use lightning::chain::chaininterface;
32 use lightning::chain::transaction::OutPoint;
33 use lightning::chain::chaininterface::{BroadcasterInterface,ConfirmationTarget,ChainListener,FeeEstimator,ChainWatchInterfaceUtil,ChainWatchInterface};
34 use lightning::chain::keysinterface::{KeysInterface, InMemoryChannelKeys};
35 use lightning::ln::channelmonitor;
36 use lightning::ln::channelmonitor::{ChannelMonitor, ChannelMonitorUpdateErr, MonitorEvent};
37 use lightning::ln::channelmanager::{ChannelManager, PaymentHash, PaymentPreimage, PaymentSecret, ChannelManagerReadArgs};
38 use lightning::ln::features::{ChannelFeatures, InitFeatures, NodeFeatures};
39 use lightning::ln::msgs::{CommitmentUpdate, ChannelMessageHandler, ErrorAction, UpdateAddHTLC, Init};
40 use lightning::util::enforcing_trait_impls::EnforcingChannelKeys;
41 use lightning::util::events;
42 use lightning::util::logger::Logger;
43 use lightning::util::config::UserConfig;
44 use lightning::util::events::{EventsProvider, MessageSendEventsProvider};
45 use lightning::util::ser::{Readable, ReadableArgs, Writeable, Writer};
46 use lightning::routing::router::{Route, RouteHop};
49 use utils::test_logger;
51 use bitcoin::secp256k1::key::{PublicKey,SecretKey};
52 use bitcoin::secp256k1::Secp256k1;
55 use std::cmp::Ordering;
56 use std::collections::{HashSet, hash_map, HashMap};
57 use std::sync::{Arc,Mutex};
58 use std::sync::atomic;
61 struct FuzzEstimator {}
62 impl FeeEstimator for FuzzEstimator {
63 fn get_est_sat_per_1000_weight(&self, _: ConfirmationTarget) -> u32 {
68 pub struct TestBroadcaster {}
69 impl BroadcasterInterface for TestBroadcaster {
70 fn broadcast_transaction(&self, _tx: &Transaction) { }
73 pub struct VecWriter(pub Vec<u8>);
74 impl Writer for VecWriter {
75 fn write_all(&mut self, buf: &[u8]) -> Result<(), ::std::io::Error> {
76 self.0.extend_from_slice(buf);
79 fn size_hint(&mut self, size: usize) {
80 self.0.reserve_exact(size);
84 struct TestChannelMonitor {
85 pub logger: Arc<dyn Logger>,
86 pub simple_monitor: Arc<channelmonitor::SimpleManyChannelMonitor<OutPoint, EnforcingChannelKeys, Arc<TestBroadcaster>, Arc<FuzzEstimator>, Arc<dyn Logger>, Arc<dyn ChainWatchInterface>>>,
87 pub update_ret: Mutex<Result<(), channelmonitor::ChannelMonitorUpdateErr>>,
88 // If we reload a node with an old copy of ChannelMonitors, the ChannelManager deserialization
89 // logic will automatically force-close our channels for us (as we don't have an up-to-date
90 // monitor implying we are not able to punish misbehaving counterparties). Because this test
91 // "fails" if we ever force-close a channel, we avoid doing so, always saving the latest
92 // fully-serialized monitor state here, as well as the corresponding update_id.
93 pub latest_monitors: Mutex<HashMap<OutPoint, (u64, Vec<u8>)>>,
94 pub should_update_manager: atomic::AtomicBool,
96 impl TestChannelMonitor {
97 pub fn new(chain_monitor: Arc<dyn chaininterface::ChainWatchInterface>, broadcaster: Arc<TestBroadcaster>, logger: Arc<dyn Logger>, feeest: Arc<FuzzEstimator>) -> Self {
99 simple_monitor: Arc::new(channelmonitor::SimpleManyChannelMonitor::new(chain_monitor, broadcaster, logger.clone(), feeest)),
101 update_ret: Mutex::new(Ok(())),
102 latest_monitors: Mutex::new(HashMap::new()),
103 should_update_manager: atomic::AtomicBool::new(false),
107 impl channelmonitor::ManyChannelMonitor for TestChannelMonitor {
108 type Keys = EnforcingChannelKeys;
110 fn add_monitor(&self, funding_txo: OutPoint, monitor: channelmonitor::ChannelMonitor<EnforcingChannelKeys>) -> Result<(), channelmonitor::ChannelMonitorUpdateErr> {
111 let mut ser = VecWriter(Vec::new());
112 monitor.write_for_disk(&mut ser).unwrap();
113 if let Some(_) = self.latest_monitors.lock().unwrap().insert(funding_txo, (monitor.get_latest_update_id(), ser.0)) {
114 panic!("Already had monitor pre-add_monitor");
116 self.should_update_manager.store(true, atomic::Ordering::Relaxed);
117 assert!(self.simple_monitor.add_monitor(funding_txo, monitor).is_ok());
118 self.update_ret.lock().unwrap().clone()
121 fn update_monitor(&self, funding_txo: OutPoint, update: channelmonitor::ChannelMonitorUpdate) -> Result<(), channelmonitor::ChannelMonitorUpdateErr> {
122 let mut map_lock = self.latest_monitors.lock().unwrap();
123 let mut map_entry = match map_lock.entry(funding_txo) {
124 hash_map::Entry::Occupied(entry) => entry,
125 hash_map::Entry::Vacant(_) => panic!("Didn't have monitor on update call"),
127 let mut deserialized_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingChannelKeys>)>::
128 read(&mut Cursor::new(&map_entry.get().1)).unwrap().1;
129 deserialized_monitor.update_monitor(update.clone(), &&TestBroadcaster {}, &self.logger).unwrap();
130 let mut ser = VecWriter(Vec::new());
131 deserialized_monitor.write_for_disk(&mut ser).unwrap();
132 map_entry.insert((update.update_id, ser.0));
133 self.should_update_manager.store(true, atomic::Ordering::Relaxed);
134 self.update_ret.lock().unwrap().clone()
137 fn get_and_clear_pending_monitor_events(&self) -> Vec<MonitorEvent> {
138 return self.simple_monitor.get_and_clear_pending_monitor_events();
144 rand_bytes_id: atomic::AtomicU8,
146 impl KeysInterface for KeyProvider {
147 type ChanKeySigner = EnforcingChannelKeys;
149 fn get_node_secret(&self) -> SecretKey {
150 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()
153 fn get_destination_script(&self) -> Script {
154 let secp_ctx = Secp256k1::signing_only();
155 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();
156 let our_channel_monitor_claim_key_hash = WPubkeyHash::hash(&PublicKey::from_secret_key(&secp_ctx, &channel_monitor_claim_key).serialize());
157 Builder::new().push_opcode(opcodes::all::OP_PUSHBYTES_0).push_slice(&our_channel_monitor_claim_key_hash[..]).into_script()
160 fn get_shutdown_pubkey(&self) -> PublicKey {
161 let secp_ctx = Secp256k1::signing_only();
162 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())
165 fn get_channel_keys(&self, _inbound: bool, channel_value_satoshis: u64) -> EnforcingChannelKeys {
166 let secp_ctx = Secp256k1::signing_only();
167 EnforcingChannelKeys::new(InMemoryChannelKeys::new(
169 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(),
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, 5, 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, 6, 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, 7, 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, 8, self.node_id]).unwrap(),
174 [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],
175 channel_value_satoshis,
180 fn get_secure_random_bytes(&self) -> [u8; 32] {
181 let id = self.rand_bytes_id.fetch_add(1, atomic::Ordering::Relaxed);
182 [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]
187 pub fn do_test<Out: test_logger::Output>(data: &[u8], out: Out) {
188 let fee_est = Arc::new(FuzzEstimator{});
189 let broadcast = Arc::new(TestBroadcaster{});
191 macro_rules! make_node {
192 ($node_id: expr) => { {
193 let logger: Arc<dyn Logger> = Arc::new(test_logger::TestLogger::new($node_id.to_string(), out.clone()));
194 let watch = Arc::new(ChainWatchInterfaceUtil::new(Network::Bitcoin));
195 let monitor = Arc::new(TestChannelMonitor::new(watch.clone(), broadcast.clone(), logger.clone(), fee_est.clone()));
197 let keys_manager = Arc::new(KeyProvider { node_id: $node_id, rand_bytes_id: atomic::AtomicU8::new(0) });
198 let mut config = UserConfig::default();
199 config.channel_options.fee_proportional_millionths = 0;
200 config.channel_options.announced_channel = true;
201 config.peer_channel_config_limits.min_dust_limit_satoshis = 0;
202 (Arc::new(ChannelManager::new(Network::Bitcoin, fee_est.clone(), monitor.clone(), broadcast.clone(), Arc::clone(&logger), keys_manager.clone(), config, 0)),
207 macro_rules! reload_node {
208 ($ser: expr, $node_id: expr, $old_monitors: expr) => { {
209 let logger: Arc<dyn Logger> = Arc::new(test_logger::TestLogger::new($node_id.to_string(), out.clone()));
210 let watch = Arc::new(ChainWatchInterfaceUtil::new(Network::Bitcoin));
211 let monitor = Arc::new(TestChannelMonitor::new(watch.clone(), broadcast.clone(), logger.clone(), fee_est.clone()));
213 let keys_manager = Arc::new(KeyProvider { node_id: $node_id, rand_bytes_id: atomic::AtomicU8::new(0) });
214 let mut config = UserConfig::default();
215 config.channel_options.fee_proportional_millionths = 0;
216 config.channel_options.announced_channel = true;
217 config.peer_channel_config_limits.min_dust_limit_satoshis = 0;
219 let mut monitors = HashMap::new();
220 let mut old_monitors = $old_monitors.latest_monitors.lock().unwrap();
221 for (outpoint, (update_id, monitor_ser)) in old_monitors.drain() {
222 monitors.insert(outpoint, <(BlockHash, ChannelMonitor<EnforcingChannelKeys>)>::read(&mut Cursor::new(&monitor_ser)).expect("Failed to read monitor").1);
223 monitor.latest_monitors.lock().unwrap().insert(outpoint, (update_id, monitor_ser));
225 let mut monitor_refs = HashMap::new();
226 for (outpoint, monitor) in monitors.iter_mut() {
227 monitor_refs.insert(*outpoint, monitor);
230 let read_args = ChannelManagerReadArgs {
232 fee_estimator: fee_est.clone(),
233 monitor: monitor.clone(),
234 tx_broadcaster: broadcast.clone(),
236 default_config: config,
237 channel_monitors: monitor_refs,
240 (<(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)
244 let mut channel_txn = Vec::new();
245 macro_rules! make_channel {
246 ($source: expr, $dest: expr, $chan_id: expr) => { {
247 $source.create_channel($dest.get_our_node_id(), 10000000, 42, 0, None).unwrap();
249 let events = $source.get_and_clear_pending_msg_events();
250 assert_eq!(events.len(), 1);
251 if let events::MessageSendEvent::SendOpenChannel { ref msg, .. } = events[0] {
253 } else { panic!("Wrong event type"); }
256 $dest.handle_open_channel(&$source.get_our_node_id(), InitFeatures::known(), &open_channel);
257 let accept_channel = {
258 let events = $dest.get_and_clear_pending_msg_events();
259 assert_eq!(events.len(), 1);
260 if let events::MessageSendEvent::SendAcceptChannel { ref msg, .. } = events[0] {
262 } else { panic!("Wrong event type"); }
265 $source.handle_accept_channel(&$dest.get_our_node_id(), InitFeatures::known(), &accept_channel);
268 let events = $source.get_and_clear_pending_events();
269 assert_eq!(events.len(), 1);
270 if let events::Event::FundingGenerationReady { ref temporary_channel_id, ref channel_value_satoshis, ref output_script, .. } = events[0] {
271 let tx = Transaction { version: $chan_id, lock_time: 0, input: Vec::new(), output: vec![TxOut {
272 value: *channel_value_satoshis, script_pubkey: output_script.clone(),
274 funding_output = OutPoint { txid: tx.txid(), index: 0 };
275 $source.funding_transaction_generated(&temporary_channel_id, funding_output);
276 channel_txn.push(tx);
277 } else { panic!("Wrong event type"); }
280 let funding_created = {
281 let events = $source.get_and_clear_pending_msg_events();
282 assert_eq!(events.len(), 1);
283 if let events::MessageSendEvent::SendFundingCreated { ref msg, .. } = events[0] {
285 } else { panic!("Wrong event type"); }
287 $dest.handle_funding_created(&$source.get_our_node_id(), &funding_created);
289 let funding_signed = {
290 let events = $dest.get_and_clear_pending_msg_events();
291 assert_eq!(events.len(), 1);
292 if let events::MessageSendEvent::SendFundingSigned { ref msg, .. } = events[0] {
294 } else { panic!("Wrong event type"); }
296 $source.handle_funding_signed(&$dest.get_our_node_id(), &funding_signed);
299 let events = $source.get_and_clear_pending_events();
300 assert_eq!(events.len(), 1);
301 if let events::Event::FundingBroadcastSafe { .. } = events[0] {
302 } else { panic!("Wrong event type"); }
308 macro_rules! confirm_txn {
310 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
311 let mut txn = Vec::with_capacity(channel_txn.len());
312 let mut posn = Vec::with_capacity(channel_txn.len());
313 for i in 0..channel_txn.len() {
314 txn.push(&channel_txn[i]);
317 $node.block_connected(&header, 1, &txn, &posn);
319 header = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
320 $node.block_connected(&header, i, &Vec::new(), &[0; 0]);
325 macro_rules! lock_fundings {
326 ($nodes: expr) => { {
327 let mut node_events = Vec::new();
328 for node in $nodes.iter() {
329 node_events.push(node.get_and_clear_pending_msg_events());
331 for (idx, node_event) in node_events.iter().enumerate() {
332 for event in node_event {
333 if let events::MessageSendEvent::SendFundingLocked { ref node_id, ref msg } = event {
334 for node in $nodes.iter() {
335 if node.get_our_node_id() == *node_id {
336 node.handle_funding_locked(&$nodes[idx].get_our_node_id(), msg);
339 } else { panic!("Wrong event type"); }
343 for node in $nodes.iter() {
344 let events = node.get_and_clear_pending_msg_events();
345 for event in events {
346 if let events::MessageSendEvent::SendAnnouncementSignatures { .. } = event {
347 } else { panic!("Wrong event type"); }
353 // 3 nodes is enough to hit all the possible cases, notably unknown-source-unknown-dest
355 let (mut node_a, mut monitor_a) = make_node!(0);
356 let (mut node_b, mut monitor_b) = make_node!(1);
357 let (mut node_c, mut monitor_c) = make_node!(2);
359 let mut nodes = [node_a, node_b, node_c];
361 let chan_1_funding = make_channel!(nodes[0], nodes[1], 0);
362 let chan_2_funding = make_channel!(nodes[1], nodes[2], 1);
364 for node in nodes.iter() {
368 lock_fundings!(nodes);
370 let chan_a = nodes[0].list_usable_channels()[0].short_channel_id.unwrap();
371 let chan_b = nodes[2].list_usable_channels()[0].short_channel_id.unwrap();
373 let mut payment_id = 0;
375 let mut chan_a_disconnected = false;
376 let mut chan_b_disconnected = false;
377 let mut ba_events = Vec::new();
378 let mut bc_events = Vec::new();
380 let mut node_a_ser = VecWriter(Vec::new());
381 nodes[0].write(&mut node_a_ser).unwrap();
382 let mut node_b_ser = VecWriter(Vec::new());
383 nodes[1].write(&mut node_b_ser).unwrap();
384 let mut node_c_ser = VecWriter(Vec::new());
385 nodes[2].write(&mut node_c_ser).unwrap();
387 macro_rules! test_return {
389 assert_eq!(nodes[0].list_channels().len(), 1);
390 assert_eq!(nodes[1].list_channels().len(), 2);
391 assert_eq!(nodes[2].list_channels().len(), 1);
396 let mut read_pos = 0;
397 macro_rules! get_slice {
400 let slice_len = $len as usize;
401 if data.len() < read_pos + slice_len {
404 read_pos += slice_len;
405 &data[read_pos - slice_len..read_pos]
411 macro_rules! send_payment {
412 ($source: expr, $dest: expr, $amt: expr) => { {
413 let payment_hash = Sha256::hash(&[payment_id; 1]);
414 payment_id = payment_id.wrapping_add(1);
415 if let Err(_) = $source.send_payment(&Route {
416 paths: vec![vec![RouteHop {
417 pubkey: $dest.0.get_our_node_id(),
418 node_features: NodeFeatures::empty(),
419 short_channel_id: $dest.1,
420 channel_features: ChannelFeatures::empty(),
422 cltv_expiry_delta: 200,
424 }, PaymentHash(payment_hash.into_inner()), &None) {
425 // Probably ran out of funds
429 ($source: expr, $middle: expr, $dest: expr, $amt: expr) => { {
430 let payment_hash = Sha256::hash(&[payment_id; 1]);
431 payment_id = payment_id.wrapping_add(1);
432 if let Err(_) = $source.send_payment(&Route {
433 paths: vec![vec![RouteHop {
434 pubkey: $middle.0.get_our_node_id(),
435 node_features: NodeFeatures::empty(),
436 short_channel_id: $middle.1,
437 channel_features: ChannelFeatures::empty(),
439 cltv_expiry_delta: 100,
441 pubkey: $dest.0.get_our_node_id(),
442 node_features: NodeFeatures::empty(),
443 short_channel_id: $dest.1,
444 channel_features: ChannelFeatures::empty(),
446 cltv_expiry_delta: 200,
448 }, PaymentHash(payment_hash.into_inner()), &None) {
449 // Probably ran out of funds
454 macro_rules! send_payment_with_secret {
455 ($source: expr, $middle: expr, $dest: expr) => { {
456 let payment_hash = Sha256::hash(&[payment_id; 1]);
457 payment_id = payment_id.wrapping_add(1);
458 let payment_secret = Sha256::hash(&[payment_id; 1]);
459 payment_id = payment_id.wrapping_add(1);
460 if let Err(_) = $source.send_payment(&Route {
461 paths: vec![vec![RouteHop {
462 pubkey: $middle.0.get_our_node_id(),
463 node_features: NodeFeatures::empty(),
464 short_channel_id: $middle.1,
465 channel_features: ChannelFeatures::empty(),
467 cltv_expiry_delta: 100,
469 pubkey: $dest.0.get_our_node_id(),
470 node_features: NodeFeatures::empty(),
471 short_channel_id: $dest.1,
472 channel_features: ChannelFeatures::empty(),
474 cltv_expiry_delta: 200,
476 pubkey: $middle.0.get_our_node_id(),
477 node_features: NodeFeatures::empty(),
478 short_channel_id: $middle.1,
479 channel_features: ChannelFeatures::empty(),
481 cltv_expiry_delta: 100,
483 pubkey: $dest.0.get_our_node_id(),
484 node_features: NodeFeatures::empty(),
485 short_channel_id: $dest.1,
486 channel_features: ChannelFeatures::empty(),
488 cltv_expiry_delta: 200,
490 }, PaymentHash(payment_hash.into_inner()), &Some(PaymentSecret(payment_secret.into_inner()))) {
491 // Probably ran out of funds
497 macro_rules! process_msg_events {
498 ($node: expr, $corrupt_forward: expr) => { {
499 let events = if $node == 1 {
500 let mut new_events = Vec::new();
501 mem::swap(&mut new_events, &mut ba_events);
502 new_events.extend_from_slice(&bc_events[..]);
505 } else { Vec::new() };
506 for event in events.iter().chain(nodes[$node].get_and_clear_pending_msg_events().iter()) {
508 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 } } => {
509 for dest in nodes.iter() {
510 if dest.get_our_node_id() == *node_id {
511 assert!(update_fee.is_none());
512 for update_add in update_add_htlcs {
513 if !$corrupt_forward {
514 dest.handle_update_add_htlc(&nodes[$node].get_our_node_id(), &update_add);
516 // Corrupt the update_add_htlc message so that its HMAC
517 // check will fail and we generate a
518 // update_fail_malformed_htlc instead of an
519 // update_fail_htlc as we do when we reject a payment.
520 let mut msg_ser = update_add.encode();
521 msg_ser[1000] ^= 0xff;
522 let new_msg = UpdateAddHTLC::read(&mut Cursor::new(&msg_ser)).unwrap();
523 dest.handle_update_add_htlc(&nodes[$node].get_our_node_id(), &new_msg);
526 for update_fulfill in update_fulfill_htlcs {
527 dest.handle_update_fulfill_htlc(&nodes[$node].get_our_node_id(), &update_fulfill);
529 for update_fail in update_fail_htlcs {
530 dest.handle_update_fail_htlc(&nodes[$node].get_our_node_id(), &update_fail);
532 for update_fail_malformed in update_fail_malformed_htlcs {
533 dest.handle_update_fail_malformed_htlc(&nodes[$node].get_our_node_id(), &update_fail_malformed);
535 dest.handle_commitment_signed(&nodes[$node].get_our_node_id(), &commitment_signed);
539 events::MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
540 for dest in nodes.iter() {
541 if dest.get_our_node_id() == *node_id {
542 dest.handle_revoke_and_ack(&nodes[$node].get_our_node_id(), msg);
546 events::MessageSendEvent::SendChannelReestablish { ref node_id, ref msg } => {
547 for dest in nodes.iter() {
548 if dest.get_our_node_id() == *node_id {
549 dest.handle_channel_reestablish(&nodes[$node].get_our_node_id(), msg);
553 events::MessageSendEvent::SendFundingLocked { .. } => {
554 // Can be generated as a reestablish response
556 events::MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {
557 // Can be generated due to a payment forward being rejected due to a
558 // channel having previously failed a monitor update
560 events::MessageSendEvent::HandleError { action: ErrorAction::IgnoreError, .. } => {
561 // Can be generated at any processing step to send back an error, disconnect
562 // peer or just ignore
564 _ => panic!("Unhandled message event"),
570 macro_rules! drain_msg_events_on_disconnect {
571 ($counterparty_id: expr) => { {
572 if $counterparty_id == 0 {
573 for event in nodes[0].get_and_clear_pending_msg_events() {
575 events::MessageSendEvent::UpdateHTLCs { .. } => {},
576 events::MessageSendEvent::SendRevokeAndACK { .. } => {},
577 events::MessageSendEvent::SendChannelReestablish { .. } => {},
578 events::MessageSendEvent::SendFundingLocked { .. } => {},
579 events::MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
580 events::MessageSendEvent::HandleError { action: ErrorAction::IgnoreError, .. } => {},
581 _ => panic!("Unhandled message event"),
586 for event in nodes[2].get_and_clear_pending_msg_events() {
588 events::MessageSendEvent::UpdateHTLCs { .. } => {},
589 events::MessageSendEvent::SendRevokeAndACK { .. } => {},
590 events::MessageSendEvent::SendChannelReestablish { .. } => {},
591 events::MessageSendEvent::SendFundingLocked { .. } => {},
592 events::MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
593 events::MessageSendEvent::HandleError { action: ErrorAction::IgnoreError, .. } => {},
594 _ => panic!("Unhandled message event"),
599 let mut events = nodes[1].get_and_clear_pending_msg_events();
600 let drop_node_id = if $counterparty_id == 0 { nodes[0].get_our_node_id() } else { nodes[2].get_our_node_id() };
601 let msg_sink = if $counterparty_id == 0 { &mut bc_events } else { &mut ba_events };
602 for event in events.drain(..) {
603 let push = match event {
604 events::MessageSendEvent::UpdateHTLCs { ref node_id, .. } => {
605 if *node_id != drop_node_id { true } else { false }
607 events::MessageSendEvent::SendRevokeAndACK { ref node_id, .. } => {
608 if *node_id != drop_node_id { true } else { false }
610 events::MessageSendEvent::SendChannelReestablish { ref node_id, .. } => {
611 if *node_id != drop_node_id { true } else { false }
613 events::MessageSendEvent::SendFundingLocked { .. } => false,
614 events::MessageSendEvent::PaymentFailureNetworkUpdate { .. } => false,
615 events::MessageSendEvent::HandleError { action: ErrorAction::IgnoreError, .. } => false,
616 _ => panic!("Unhandled message event"),
618 if push { msg_sink.push(event); }
623 macro_rules! process_events {
624 ($node: expr, $fail: expr) => { {
625 // In case we get 256 payments we may have a hash collision, resulting in the
626 // second claim/fail call not finding the duplicate-hash HTLC, so we have to
627 // deduplicate the calls here.
628 let mut claim_set = HashSet::new();
629 let mut events = nodes[$node].get_and_clear_pending_events();
630 // Sort events so that PendingHTLCsForwardable get processed last. This avoids a
631 // case where we first process a PendingHTLCsForwardable, then claim/fail on a
632 // PaymentReceived, claiming/failing two HTLCs, but leaving a just-generated
633 // PaymentReceived event for the second HTLC in our pending_events (and breaking
634 // our claim_set deduplication).
635 events.sort_by(|a, b| {
636 if let events::Event::PaymentReceived { .. } = a {
637 if let events::Event::PendingHTLCsForwardable { .. } = b {
639 } else { Ordering::Equal }
640 } else if let events::Event::PendingHTLCsForwardable { .. } = a {
641 if let events::Event::PaymentReceived { .. } = b {
643 } else { Ordering::Equal }
644 } else { Ordering::Equal }
646 for event in events.drain(..) {
648 events::Event::PaymentReceived { payment_hash, payment_secret, amt } => {
649 if claim_set.insert(payment_hash.0) {
651 assert!(nodes[$node].fail_htlc_backwards(&payment_hash, &payment_secret));
653 assert!(nodes[$node].claim_funds(PaymentPreimage(payment_hash.0), &payment_secret, amt));
657 events::Event::PaymentSent { .. } => {},
658 events::Event::PaymentFailed { .. } => {},
659 events::Event::PendingHTLCsForwardable { .. } => {
660 nodes[$node].process_pending_htlc_forwards();
662 _ => panic!("Unhandled event"),
668 match get_slice!(1)[0] {
669 0x00 => *monitor_a.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::TemporaryFailure),
670 0x01 => *monitor_b.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::TemporaryFailure),
671 0x02 => *monitor_c.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::TemporaryFailure),
672 0x03 => *monitor_a.update_ret.lock().unwrap() = Ok(()),
673 0x04 => *monitor_b.update_ret.lock().unwrap() = Ok(()),
674 0x05 => *monitor_c.update_ret.lock().unwrap() = Ok(()),
676 if let Some((id, _)) = monitor_a.latest_monitors.lock().unwrap().get(&chan_1_funding) {
677 nodes[0].channel_monitor_updated(&chan_1_funding, *id);
681 if let Some((id, _)) = monitor_b.latest_monitors.lock().unwrap().get(&chan_1_funding) {
682 nodes[1].channel_monitor_updated(&chan_1_funding, *id);
686 if let Some((id, _)) = monitor_b.latest_monitors.lock().unwrap().get(&chan_2_funding) {
687 nodes[1].channel_monitor_updated(&chan_2_funding, *id);
691 if let Some((id, _)) = monitor_c.latest_monitors.lock().unwrap().get(&chan_2_funding) {
692 nodes[2].channel_monitor_updated(&chan_2_funding, *id);
695 0x09 => send_payment!(nodes[0], (&nodes[1], chan_a), 5_000_000),
696 0x0a => send_payment!(nodes[1], (&nodes[0], chan_a), 5_000_000),
697 0x0b => send_payment!(nodes[1], (&nodes[2], chan_b), 5_000_000),
698 0x0c => send_payment!(nodes[2], (&nodes[1], chan_b), 5_000_000),
699 0x0d => send_payment!(nodes[0], (&nodes[1], chan_a), (&nodes[2], chan_b), 5_000_000),
700 0x0e => send_payment!(nodes[2], (&nodes[1], chan_b), (&nodes[0], chan_a), 5_000_000),
702 if !chan_a_disconnected {
703 nodes[0].peer_disconnected(&nodes[1].get_our_node_id(), false);
704 nodes[1].peer_disconnected(&nodes[0].get_our_node_id(), false);
705 chan_a_disconnected = true;
706 drain_msg_events_on_disconnect!(0);
710 if !chan_b_disconnected {
711 nodes[1].peer_disconnected(&nodes[2].get_our_node_id(), false);
712 nodes[2].peer_disconnected(&nodes[1].get_our_node_id(), false);
713 chan_b_disconnected = true;
714 drain_msg_events_on_disconnect!(2);
718 if chan_a_disconnected {
719 nodes[0].peer_connected(&nodes[1].get_our_node_id(), &Init { features: InitFeatures::empty() });
720 nodes[1].peer_connected(&nodes[0].get_our_node_id(), &Init { features: InitFeatures::empty() });
721 chan_a_disconnected = false;
725 if chan_b_disconnected {
726 nodes[1].peer_connected(&nodes[2].get_our_node_id(), &Init { features: InitFeatures::empty() });
727 nodes[2].peer_connected(&nodes[1].get_our_node_id(), &Init { features: InitFeatures::empty() });
728 chan_b_disconnected = false;
731 0x13 => process_msg_events!(0, true),
732 0x14 => process_msg_events!(0, false),
733 0x15 => process_events!(0, true),
734 0x16 => process_events!(0, false),
735 0x17 => process_msg_events!(1, true),
736 0x18 => process_msg_events!(1, false),
737 0x19 => process_events!(1, true),
738 0x1a => process_events!(1, false),
739 0x1b => process_msg_events!(2, true),
740 0x1c => process_msg_events!(2, false),
741 0x1d => process_events!(2, true),
742 0x1e => process_events!(2, false),
744 if !chan_a_disconnected {
745 nodes[1].peer_disconnected(&nodes[0].get_our_node_id(), false);
746 chan_a_disconnected = true;
747 drain_msg_events_on_disconnect!(0);
749 let (new_node_a, new_monitor_a) = reload_node!(node_a_ser, 0, monitor_a);
750 node_a = Arc::new(new_node_a);
751 nodes[0] = node_a.clone();
752 monitor_a = new_monitor_a;
755 if !chan_a_disconnected {
756 nodes[0].peer_disconnected(&nodes[1].get_our_node_id(), false);
757 chan_a_disconnected = true;
758 nodes[0].get_and_clear_pending_msg_events();
761 if !chan_b_disconnected {
762 nodes[2].peer_disconnected(&nodes[1].get_our_node_id(), false);
763 chan_b_disconnected = true;
764 nodes[2].get_and_clear_pending_msg_events();
767 let (new_node_b, new_monitor_b) = reload_node!(node_b_ser, 1, monitor_b);
768 node_b = Arc::new(new_node_b);
769 nodes[1] = node_b.clone();
770 monitor_b = new_monitor_b;
773 if !chan_b_disconnected {
774 nodes[1].peer_disconnected(&nodes[2].get_our_node_id(), false);
775 chan_b_disconnected = true;
776 drain_msg_events_on_disconnect!(2);
778 let (new_node_c, new_monitor_c) = reload_node!(node_c_ser, 2, monitor_c);
779 node_c = Arc::new(new_node_c);
780 nodes[2] = node_c.clone();
781 monitor_c = new_monitor_c;
783 0x22 => send_payment_with_secret!(nodes[0], (&nodes[1], chan_a), (&nodes[2], chan_b)),
784 0x23 => send_payment_with_secret!(nodes[2], (&nodes[1], chan_b), (&nodes[0], chan_a)),
785 0x25 => send_payment!(nodes[0], (&nodes[1], chan_a), 10),
786 0x26 => send_payment!(nodes[1], (&nodes[0], chan_a), 10),
787 0x27 => send_payment!(nodes[1], (&nodes[2], chan_b), 10),
788 0x28 => send_payment!(nodes[2], (&nodes[1], chan_b), 10),
789 0x29 => send_payment!(nodes[0], (&nodes[1], chan_a), (&nodes[2], chan_b), 10),
790 0x2a => send_payment!(nodes[2], (&nodes[1], chan_b), (&nodes[0], chan_a), 10),
791 0x2b => send_payment!(nodes[0], (&nodes[1], chan_a), 1_000),
792 0x2c => send_payment!(nodes[1], (&nodes[0], chan_a), 1_000),
793 0x2d => send_payment!(nodes[1], (&nodes[2], chan_b), 1_000),
794 0x2e => send_payment!(nodes[2], (&nodes[1], chan_b), 1_000),
795 0x2f => send_payment!(nodes[0], (&nodes[1], chan_a), (&nodes[2], chan_b), 1_000),
796 0x30 => send_payment!(nodes[2], (&nodes[1], chan_b), (&nodes[0], chan_a), 1_000),
797 0x31 => send_payment!(nodes[0], (&nodes[1], chan_a), 100_000),
798 0x32 => send_payment!(nodes[1], (&nodes[0], chan_a), 100_000),
799 0x33 => send_payment!(nodes[1], (&nodes[2], chan_b), 100_000),
800 0x34 => send_payment!(nodes[2], (&nodes[1], chan_b), 100_000),
801 0x35 => send_payment!(nodes[0], (&nodes[1], chan_a), (&nodes[2], chan_b), 100_000),
802 0x36 => send_payment!(nodes[2], (&nodes[1], chan_b), (&nodes[0], chan_a), 100_000),
803 // 0x24 defined above
807 node_a_ser.0.clear();
808 nodes[0].write(&mut node_a_ser).unwrap();
809 monitor_a.should_update_manager.store(false, atomic::Ordering::Relaxed);
810 node_b_ser.0.clear();
811 nodes[1].write(&mut node_b_ser).unwrap();
812 monitor_b.should_update_manager.store(false, atomic::Ordering::Relaxed);
813 node_c_ser.0.clear();
814 nodes[2].write(&mut node_c_ser).unwrap();
815 monitor_c.should_update_manager.store(false, atomic::Ordering::Relaxed);
819 pub fn chanmon_consistency_test<Out: test_logger::Output>(data: &[u8], out: Out) {
824 pub extern "C" fn chanmon_consistency_run(data: *const u8, datalen: usize) {
825 do_test(unsafe { std::slice::from_raw_parts(data, datalen) }, test_logger::DevNull{});