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::transaction::OutPoint;
32 use lightning::chain::chaininterface::{BroadcasterInterface, ChainListener, ConfirmationTarget, FeeEstimator};
33 use lightning::chain::keysinterface::{KeysInterface, InMemoryChannelKeys};
34 use lightning::ln::channelmonitor;
35 use lightning::ln::channelmonitor::{ChannelMonitor, ChannelMonitorUpdateErr, MonitorEvent};
36 use lightning::ln::channelmanager::{ChannelManager, PaymentHash, PaymentPreimage, PaymentSecret, ChannelManagerReadArgs};
37 use lightning::ln::features::{ChannelFeatures, InitFeatures, NodeFeatures};
38 use lightning::ln::msgs::{CommitmentUpdate, ChannelMessageHandler, ErrorAction, UpdateAddHTLC, Init};
39 use lightning::util::enforcing_trait_impls::EnforcingChannelKeys;
40 use lightning::util::events;
41 use lightning::util::logger::Logger;
42 use lightning::util::config::UserConfig;
43 use lightning::util::events::{EventsProvider, MessageSendEventsProvider};
44 use lightning::util::ser::{Readable, ReadableArgs, Writeable, Writer};
45 use lightning::routing::router::{Route, RouteHop};
48 use utils::test_logger;
50 use bitcoin::secp256k1::key::{PublicKey,SecretKey};
51 use bitcoin::secp256k1::Secp256k1;
54 use std::cmp::Ordering;
55 use std::collections::{HashSet, hash_map, HashMap};
56 use std::sync::{Arc,Mutex};
57 use std::sync::atomic;
60 struct FuzzEstimator {}
61 impl FeeEstimator for FuzzEstimator {
62 fn get_est_sat_per_1000_weight(&self, _: ConfirmationTarget) -> u32 {
67 pub struct TestBroadcaster {}
68 impl BroadcasterInterface for TestBroadcaster {
69 fn broadcast_transaction(&self, _tx: &Transaction) { }
72 pub struct VecWriter(pub Vec<u8>);
73 impl Writer for VecWriter {
74 fn write_all(&mut self, buf: &[u8]) -> Result<(), ::std::io::Error> {
75 self.0.extend_from_slice(buf);
78 fn size_hint(&mut self, size: usize) {
79 self.0.reserve_exact(size);
83 struct TestChannelMonitor {
84 pub logger: Arc<dyn Logger>,
85 pub simple_monitor: Arc<channelmonitor::SimpleManyChannelMonitor<OutPoint, EnforcingChannelKeys, Arc<TestBroadcaster>, Arc<FuzzEstimator>, Arc<dyn Logger>>>,
86 pub update_ret: Mutex<Result<(), channelmonitor::ChannelMonitorUpdateErr>>,
87 // If we reload a node with an old copy of ChannelMonitors, the ChannelManager deserialization
88 // logic will automatically force-close our channels for us (as we don't have an up-to-date
89 // monitor implying we are not able to punish misbehaving counterparties). Because this test
90 // "fails" if we ever force-close a channel, we avoid doing so, always saving the latest
91 // fully-serialized monitor state here, as well as the corresponding update_id.
92 pub latest_monitors: Mutex<HashMap<OutPoint, (u64, Vec<u8>)>>,
93 pub should_update_manager: atomic::AtomicBool,
95 impl TestChannelMonitor {
96 pub fn new(broadcaster: Arc<TestBroadcaster>, logger: Arc<dyn Logger>, feeest: Arc<FuzzEstimator>) -> Self {
98 simple_monitor: Arc::new(channelmonitor::SimpleManyChannelMonitor::new(broadcaster, logger.clone(), feeest)),
100 update_ret: Mutex::new(Ok(())),
101 latest_monitors: Mutex::new(HashMap::new()),
102 should_update_manager: atomic::AtomicBool::new(false),
106 impl channelmonitor::ManyChannelMonitor for TestChannelMonitor {
107 type Keys = EnforcingChannelKeys;
109 fn add_monitor(&self, funding_txo: OutPoint, monitor: channelmonitor::ChannelMonitor<EnforcingChannelKeys>) -> Result<(), channelmonitor::ChannelMonitorUpdateErr> {
110 let mut ser = VecWriter(Vec::new());
111 monitor.write_for_disk(&mut ser).unwrap();
112 if let Some(_) = self.latest_monitors.lock().unwrap().insert(funding_txo, (monitor.get_latest_update_id(), ser.0)) {
113 panic!("Already had monitor pre-add_monitor");
115 self.should_update_manager.store(true, atomic::Ordering::Relaxed);
116 assert!(self.simple_monitor.add_monitor(funding_txo, monitor).is_ok());
117 self.update_ret.lock().unwrap().clone()
120 fn update_monitor(&self, funding_txo: OutPoint, update: channelmonitor::ChannelMonitorUpdate) -> Result<(), channelmonitor::ChannelMonitorUpdateErr> {
121 let mut map_lock = self.latest_monitors.lock().unwrap();
122 let mut map_entry = match map_lock.entry(funding_txo) {
123 hash_map::Entry::Occupied(entry) => entry,
124 hash_map::Entry::Vacant(_) => panic!("Didn't have monitor on update call"),
126 let mut deserialized_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingChannelKeys>)>::
127 read(&mut Cursor::new(&map_entry.get().1)).unwrap().1;
128 deserialized_monitor.update_monitor(update.clone(), &&TestBroadcaster {}, &self.logger).unwrap();
129 let mut ser = VecWriter(Vec::new());
130 deserialized_monitor.write_for_disk(&mut ser).unwrap();
131 map_entry.insert((update.update_id, ser.0));
132 self.should_update_manager.store(true, atomic::Ordering::Relaxed);
133 self.update_ret.lock().unwrap().clone()
136 fn get_and_clear_pending_monitor_events(&self) -> Vec<MonitorEvent> {
137 return self.simple_monitor.get_and_clear_pending_monitor_events();
143 rand_bytes_id: atomic::AtomicU8,
145 impl KeysInterface for KeyProvider {
146 type ChanKeySigner = EnforcingChannelKeys;
148 fn get_node_secret(&self) -> SecretKey {
149 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()
152 fn get_destination_script(&self) -> Script {
153 let secp_ctx = Secp256k1::signing_only();
154 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();
155 let our_channel_monitor_claim_key_hash = WPubkeyHash::hash(&PublicKey::from_secret_key(&secp_ctx, &channel_monitor_claim_key).serialize());
156 Builder::new().push_opcode(opcodes::all::OP_PUSHBYTES_0).push_slice(&our_channel_monitor_claim_key_hash[..]).into_script()
159 fn get_shutdown_pubkey(&self) -> PublicKey {
160 let secp_ctx = Secp256k1::signing_only();
161 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())
164 fn get_channel_keys(&self, _inbound: bool, channel_value_satoshis: u64) -> EnforcingChannelKeys {
165 let secp_ctx = Secp256k1::signing_only();
166 EnforcingChannelKeys::new(InMemoryChannelKeys::new(
168 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(),
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, 5, 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, 6, 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, 7, 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, 8, self.node_id]).unwrap(),
173 [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],
174 channel_value_satoshis,
179 fn get_secure_random_bytes(&self) -> [u8; 32] {
180 let id = self.rand_bytes_id.fetch_add(1, atomic::Ordering::Relaxed);
181 [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]
186 pub fn do_test<Out: test_logger::Output>(data: &[u8], out: Out) {
187 let fee_est = Arc::new(FuzzEstimator{});
188 let broadcast = Arc::new(TestBroadcaster{});
190 macro_rules! make_node {
191 ($node_id: expr) => { {
192 let logger: Arc<dyn Logger> = Arc::new(test_logger::TestLogger::new($node_id.to_string(), out.clone()));
193 let monitor = Arc::new(TestChannelMonitor::new(broadcast.clone(), logger.clone(), fee_est.clone()));
195 let keys_manager = Arc::new(KeyProvider { node_id: $node_id, rand_bytes_id: atomic::AtomicU8::new(0) });
196 let mut config = UserConfig::default();
197 config.channel_options.fee_proportional_millionths = 0;
198 config.channel_options.announced_channel = true;
199 config.peer_channel_config_limits.min_dust_limit_satoshis = 0;
200 (Arc::new(ChannelManager::new(Network::Bitcoin, fee_est.clone(), monitor.clone(), broadcast.clone(), Arc::clone(&logger), keys_manager.clone(), config, 0)),
205 macro_rules! reload_node {
206 ($ser: expr, $node_id: expr, $old_monitors: expr) => { {
207 let logger: Arc<dyn Logger> = Arc::new(test_logger::TestLogger::new($node_id.to_string(), out.clone()));
208 let monitor = Arc::new(TestChannelMonitor::new(broadcast.clone(), logger.clone(), fee_est.clone()));
210 let keys_manager = Arc::new(KeyProvider { node_id: $node_id, rand_bytes_id: atomic::AtomicU8::new(0) });
211 let mut config = UserConfig::default();
212 config.channel_options.fee_proportional_millionths = 0;
213 config.channel_options.announced_channel = true;
214 config.peer_channel_config_limits.min_dust_limit_satoshis = 0;
216 let mut monitors = HashMap::new();
217 let mut old_monitors = $old_monitors.latest_monitors.lock().unwrap();
218 for (outpoint, (update_id, monitor_ser)) in old_monitors.drain() {
219 monitors.insert(outpoint, <(BlockHash, ChannelMonitor<EnforcingChannelKeys>)>::read(&mut Cursor::new(&monitor_ser)).expect("Failed to read monitor").1);
220 monitor.latest_monitors.lock().unwrap().insert(outpoint, (update_id, monitor_ser));
222 let mut monitor_refs = HashMap::new();
223 for (outpoint, monitor) in monitors.iter_mut() {
224 monitor_refs.insert(*outpoint, monitor);
227 let read_args = ChannelManagerReadArgs {
229 fee_estimator: fee_est.clone(),
230 monitor: monitor.clone(),
231 tx_broadcaster: broadcast.clone(),
233 default_config: config,
234 channel_monitors: monitor_refs,
237 (<(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)
241 let mut channel_txn = Vec::new();
242 macro_rules! make_channel {
243 ($source: expr, $dest: expr, $chan_id: expr) => { {
244 $source.create_channel($dest.get_our_node_id(), 10000000, 42, 0, None).unwrap();
246 let events = $source.get_and_clear_pending_msg_events();
247 assert_eq!(events.len(), 1);
248 if let events::MessageSendEvent::SendOpenChannel { ref msg, .. } = events[0] {
250 } else { panic!("Wrong event type"); }
253 $dest.handle_open_channel(&$source.get_our_node_id(), InitFeatures::known(), &open_channel);
254 let accept_channel = {
255 let events = $dest.get_and_clear_pending_msg_events();
256 assert_eq!(events.len(), 1);
257 if let events::MessageSendEvent::SendAcceptChannel { ref msg, .. } = events[0] {
259 } else { panic!("Wrong event type"); }
262 $source.handle_accept_channel(&$dest.get_our_node_id(), InitFeatures::known(), &accept_channel);
265 let events = $source.get_and_clear_pending_events();
266 assert_eq!(events.len(), 1);
267 if let events::Event::FundingGenerationReady { ref temporary_channel_id, ref channel_value_satoshis, ref output_script, .. } = events[0] {
268 let tx = Transaction { version: $chan_id, lock_time: 0, input: Vec::new(), output: vec![TxOut {
269 value: *channel_value_satoshis, script_pubkey: output_script.clone(),
271 funding_output = OutPoint { txid: tx.txid(), index: 0 };
272 $source.funding_transaction_generated(&temporary_channel_id, funding_output);
273 channel_txn.push(tx);
274 } else { panic!("Wrong event type"); }
277 let funding_created = {
278 let events = $source.get_and_clear_pending_msg_events();
279 assert_eq!(events.len(), 1);
280 if let events::MessageSendEvent::SendFundingCreated { ref msg, .. } = events[0] {
282 } else { panic!("Wrong event type"); }
284 $dest.handle_funding_created(&$source.get_our_node_id(), &funding_created);
286 let funding_signed = {
287 let events = $dest.get_and_clear_pending_msg_events();
288 assert_eq!(events.len(), 1);
289 if let events::MessageSendEvent::SendFundingSigned { ref msg, .. } = events[0] {
291 } else { panic!("Wrong event type"); }
293 $source.handle_funding_signed(&$dest.get_our_node_id(), &funding_signed);
296 let events = $source.get_and_clear_pending_events();
297 assert_eq!(events.len(), 1);
298 if let events::Event::FundingBroadcastSafe { .. } = events[0] {
299 } else { panic!("Wrong event type"); }
305 macro_rules! confirm_txn {
307 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
308 let txdata: Vec<_> = channel_txn.iter().enumerate().map(|(i, tx)| (i + 1, tx)).collect();
309 $node.block_connected(&header, &txdata, 1);
311 header = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
312 $node.block_connected(&header, &[], i);
317 macro_rules! lock_fundings {
318 ($nodes: expr) => { {
319 let mut node_events = Vec::new();
320 for node in $nodes.iter() {
321 node_events.push(node.get_and_clear_pending_msg_events());
323 for (idx, node_event) in node_events.iter().enumerate() {
324 for event in node_event {
325 if let events::MessageSendEvent::SendFundingLocked { ref node_id, ref msg } = event {
326 for node in $nodes.iter() {
327 if node.get_our_node_id() == *node_id {
328 node.handle_funding_locked(&$nodes[idx].get_our_node_id(), msg);
331 } else { panic!("Wrong event type"); }
335 for node in $nodes.iter() {
336 let events = node.get_and_clear_pending_msg_events();
337 for event in events {
338 if let events::MessageSendEvent::SendAnnouncementSignatures { .. } = event {
339 } else { panic!("Wrong event type"); }
345 // 3 nodes is enough to hit all the possible cases, notably unknown-source-unknown-dest
347 let (mut node_a, mut monitor_a) = make_node!(0);
348 let (mut node_b, mut monitor_b) = make_node!(1);
349 let (mut node_c, mut monitor_c) = make_node!(2);
351 let mut nodes = [node_a, node_b, node_c];
353 let chan_1_funding = make_channel!(nodes[0], nodes[1], 0);
354 let chan_2_funding = make_channel!(nodes[1], nodes[2], 1);
356 for node in nodes.iter() {
360 lock_fundings!(nodes);
362 let chan_a = nodes[0].list_usable_channels()[0].short_channel_id.unwrap();
363 let chan_b = nodes[2].list_usable_channels()[0].short_channel_id.unwrap();
365 let mut payment_id = 0;
367 let mut chan_a_disconnected = false;
368 let mut chan_b_disconnected = false;
369 let mut ba_events = Vec::new();
370 let mut bc_events = Vec::new();
372 let mut node_a_ser = VecWriter(Vec::new());
373 nodes[0].write(&mut node_a_ser).unwrap();
374 let mut node_b_ser = VecWriter(Vec::new());
375 nodes[1].write(&mut node_b_ser).unwrap();
376 let mut node_c_ser = VecWriter(Vec::new());
377 nodes[2].write(&mut node_c_ser).unwrap();
379 macro_rules! test_return {
381 assert_eq!(nodes[0].list_channels().len(), 1);
382 assert_eq!(nodes[1].list_channels().len(), 2);
383 assert_eq!(nodes[2].list_channels().len(), 1);
388 let mut read_pos = 0;
389 macro_rules! get_slice {
392 let slice_len = $len as usize;
393 if data.len() < read_pos + slice_len {
396 read_pos += slice_len;
397 &data[read_pos - slice_len..read_pos]
403 macro_rules! send_payment {
404 ($source: expr, $dest: expr, $amt: expr) => { {
405 let payment_hash = Sha256::hash(&[payment_id; 1]);
406 payment_id = payment_id.wrapping_add(1);
407 if let Err(_) = $source.send_payment(&Route {
408 paths: vec![vec![RouteHop {
409 pubkey: $dest.0.get_our_node_id(),
410 node_features: NodeFeatures::empty(),
411 short_channel_id: $dest.1,
412 channel_features: ChannelFeatures::empty(),
414 cltv_expiry_delta: 200,
416 }, PaymentHash(payment_hash.into_inner()), &None) {
417 // Probably ran out of funds
421 ($source: expr, $middle: expr, $dest: expr, $amt: expr) => { {
422 let payment_hash = Sha256::hash(&[payment_id; 1]);
423 payment_id = payment_id.wrapping_add(1);
424 if let Err(_) = $source.send_payment(&Route {
425 paths: vec![vec![RouteHop {
426 pubkey: $middle.0.get_our_node_id(),
427 node_features: NodeFeatures::empty(),
428 short_channel_id: $middle.1,
429 channel_features: ChannelFeatures::empty(),
431 cltv_expiry_delta: 100,
433 pubkey: $dest.0.get_our_node_id(),
434 node_features: NodeFeatures::empty(),
435 short_channel_id: $dest.1,
436 channel_features: ChannelFeatures::empty(),
438 cltv_expiry_delta: 200,
440 }, PaymentHash(payment_hash.into_inner()), &None) {
441 // Probably ran out of funds
446 macro_rules! send_payment_with_secret {
447 ($source: expr, $middle: expr, $dest: expr) => { {
448 let payment_hash = Sha256::hash(&[payment_id; 1]);
449 payment_id = payment_id.wrapping_add(1);
450 let payment_secret = Sha256::hash(&[payment_id; 1]);
451 payment_id = payment_id.wrapping_add(1);
452 if let Err(_) = $source.send_payment(&Route {
453 paths: vec![vec![RouteHop {
454 pubkey: $middle.0.get_our_node_id(),
455 node_features: NodeFeatures::empty(),
456 short_channel_id: $middle.1,
457 channel_features: ChannelFeatures::empty(),
459 cltv_expiry_delta: 100,
461 pubkey: $dest.0.get_our_node_id(),
462 node_features: NodeFeatures::empty(),
463 short_channel_id: $dest.1,
464 channel_features: ChannelFeatures::empty(),
466 cltv_expiry_delta: 200,
468 pubkey: $middle.0.get_our_node_id(),
469 node_features: NodeFeatures::empty(),
470 short_channel_id: $middle.1,
471 channel_features: ChannelFeatures::empty(),
473 cltv_expiry_delta: 100,
475 pubkey: $dest.0.get_our_node_id(),
476 node_features: NodeFeatures::empty(),
477 short_channel_id: $dest.1,
478 channel_features: ChannelFeatures::empty(),
480 cltv_expiry_delta: 200,
482 }, PaymentHash(payment_hash.into_inner()), &Some(PaymentSecret(payment_secret.into_inner()))) {
483 // Probably ran out of funds
489 macro_rules! process_msg_events {
490 ($node: expr, $corrupt_forward: expr) => { {
491 let events = if $node == 1 {
492 let mut new_events = Vec::new();
493 mem::swap(&mut new_events, &mut ba_events);
494 new_events.extend_from_slice(&bc_events[..]);
497 } else { Vec::new() };
498 for event in events.iter().chain(nodes[$node].get_and_clear_pending_msg_events().iter()) {
500 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 } } => {
501 for dest in nodes.iter() {
502 if dest.get_our_node_id() == *node_id {
503 assert!(update_fee.is_none());
504 for update_add in update_add_htlcs {
505 if !$corrupt_forward {
506 dest.handle_update_add_htlc(&nodes[$node].get_our_node_id(), &update_add);
508 // Corrupt the update_add_htlc message so that its HMAC
509 // check will fail and we generate a
510 // update_fail_malformed_htlc instead of an
511 // update_fail_htlc as we do when we reject a payment.
512 let mut msg_ser = update_add.encode();
513 msg_ser[1000] ^= 0xff;
514 let new_msg = UpdateAddHTLC::read(&mut Cursor::new(&msg_ser)).unwrap();
515 dest.handle_update_add_htlc(&nodes[$node].get_our_node_id(), &new_msg);
518 for update_fulfill in update_fulfill_htlcs {
519 dest.handle_update_fulfill_htlc(&nodes[$node].get_our_node_id(), &update_fulfill);
521 for update_fail in update_fail_htlcs {
522 dest.handle_update_fail_htlc(&nodes[$node].get_our_node_id(), &update_fail);
524 for update_fail_malformed in update_fail_malformed_htlcs {
525 dest.handle_update_fail_malformed_htlc(&nodes[$node].get_our_node_id(), &update_fail_malformed);
527 dest.handle_commitment_signed(&nodes[$node].get_our_node_id(), &commitment_signed);
531 events::MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
532 for dest in nodes.iter() {
533 if dest.get_our_node_id() == *node_id {
534 dest.handle_revoke_and_ack(&nodes[$node].get_our_node_id(), msg);
538 events::MessageSendEvent::SendChannelReestablish { ref node_id, ref msg } => {
539 for dest in nodes.iter() {
540 if dest.get_our_node_id() == *node_id {
541 dest.handle_channel_reestablish(&nodes[$node].get_our_node_id(), msg);
545 events::MessageSendEvent::SendFundingLocked { .. } => {
546 // Can be generated as a reestablish response
548 events::MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {
549 // Can be generated due to a payment forward being rejected due to a
550 // channel having previously failed a monitor update
552 events::MessageSendEvent::HandleError { action: ErrorAction::IgnoreError, .. } => {
553 // Can be generated at any processing step to send back an error, disconnect
554 // peer or just ignore
556 _ => panic!("Unhandled message event"),
562 macro_rules! drain_msg_events_on_disconnect {
563 ($counterparty_id: expr) => { {
564 if $counterparty_id == 0 {
565 for event in nodes[0].get_and_clear_pending_msg_events() {
567 events::MessageSendEvent::UpdateHTLCs { .. } => {},
568 events::MessageSendEvent::SendRevokeAndACK { .. } => {},
569 events::MessageSendEvent::SendChannelReestablish { .. } => {},
570 events::MessageSendEvent::SendFundingLocked { .. } => {},
571 events::MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
572 events::MessageSendEvent::HandleError { action: ErrorAction::IgnoreError, .. } => {},
573 _ => panic!("Unhandled message event"),
578 for event in nodes[2].get_and_clear_pending_msg_events() {
580 events::MessageSendEvent::UpdateHTLCs { .. } => {},
581 events::MessageSendEvent::SendRevokeAndACK { .. } => {},
582 events::MessageSendEvent::SendChannelReestablish { .. } => {},
583 events::MessageSendEvent::SendFundingLocked { .. } => {},
584 events::MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
585 events::MessageSendEvent::HandleError { action: ErrorAction::IgnoreError, .. } => {},
586 _ => panic!("Unhandled message event"),
591 let mut events = nodes[1].get_and_clear_pending_msg_events();
592 let drop_node_id = if $counterparty_id == 0 { nodes[0].get_our_node_id() } else { nodes[2].get_our_node_id() };
593 let msg_sink = if $counterparty_id == 0 { &mut bc_events } else { &mut ba_events };
594 for event in events.drain(..) {
595 let push = match event {
596 events::MessageSendEvent::UpdateHTLCs { ref node_id, .. } => {
597 if *node_id != drop_node_id { true } else { false }
599 events::MessageSendEvent::SendRevokeAndACK { ref node_id, .. } => {
600 if *node_id != drop_node_id { true } else { false }
602 events::MessageSendEvent::SendChannelReestablish { ref node_id, .. } => {
603 if *node_id != drop_node_id { true } else { false }
605 events::MessageSendEvent::SendFundingLocked { .. } => false,
606 events::MessageSendEvent::PaymentFailureNetworkUpdate { .. } => false,
607 events::MessageSendEvent::HandleError { action: ErrorAction::IgnoreError, .. } => false,
608 _ => panic!("Unhandled message event"),
610 if push { msg_sink.push(event); }
615 macro_rules! process_events {
616 ($node: expr, $fail: expr) => { {
617 // In case we get 256 payments we may have a hash collision, resulting in the
618 // second claim/fail call not finding the duplicate-hash HTLC, so we have to
619 // deduplicate the calls here.
620 let mut claim_set = HashSet::new();
621 let mut events = nodes[$node].get_and_clear_pending_events();
622 // Sort events so that PendingHTLCsForwardable get processed last. This avoids a
623 // case where we first process a PendingHTLCsForwardable, then claim/fail on a
624 // PaymentReceived, claiming/failing two HTLCs, but leaving a just-generated
625 // PaymentReceived event for the second HTLC in our pending_events (and breaking
626 // our claim_set deduplication).
627 events.sort_by(|a, b| {
628 if let events::Event::PaymentReceived { .. } = a {
629 if let events::Event::PendingHTLCsForwardable { .. } = b {
631 } else { Ordering::Equal }
632 } else if let events::Event::PendingHTLCsForwardable { .. } = a {
633 if let events::Event::PaymentReceived { .. } = b {
635 } else { Ordering::Equal }
636 } else { Ordering::Equal }
638 for event in events.drain(..) {
640 events::Event::PaymentReceived { payment_hash, payment_secret, amt } => {
641 if claim_set.insert(payment_hash.0) {
643 assert!(nodes[$node].fail_htlc_backwards(&payment_hash, &payment_secret));
645 assert!(nodes[$node].claim_funds(PaymentPreimage(payment_hash.0), &payment_secret, amt));
649 events::Event::PaymentSent { .. } => {},
650 events::Event::PaymentFailed { .. } => {},
651 events::Event::PendingHTLCsForwardable { .. } => {
652 nodes[$node].process_pending_htlc_forwards();
654 _ => panic!("Unhandled event"),
660 match get_slice!(1)[0] {
661 0x00 => *monitor_a.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::TemporaryFailure),
662 0x01 => *monitor_b.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::TemporaryFailure),
663 0x02 => *monitor_c.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::TemporaryFailure),
664 0x03 => *monitor_a.update_ret.lock().unwrap() = Ok(()),
665 0x04 => *monitor_b.update_ret.lock().unwrap() = Ok(()),
666 0x05 => *monitor_c.update_ret.lock().unwrap() = Ok(()),
668 if let Some((id, _)) = monitor_a.latest_monitors.lock().unwrap().get(&chan_1_funding) {
669 nodes[0].channel_monitor_updated(&chan_1_funding, *id);
673 if let Some((id, _)) = monitor_b.latest_monitors.lock().unwrap().get(&chan_1_funding) {
674 nodes[1].channel_monitor_updated(&chan_1_funding, *id);
678 if let Some((id, _)) = monitor_b.latest_monitors.lock().unwrap().get(&chan_2_funding) {
679 nodes[1].channel_monitor_updated(&chan_2_funding, *id);
683 if let Some((id, _)) = monitor_c.latest_monitors.lock().unwrap().get(&chan_2_funding) {
684 nodes[2].channel_monitor_updated(&chan_2_funding, *id);
687 0x09 => send_payment!(nodes[0], (&nodes[1], chan_a), 5_000_000),
688 0x0a => send_payment!(nodes[1], (&nodes[0], chan_a), 5_000_000),
689 0x0b => send_payment!(nodes[1], (&nodes[2], chan_b), 5_000_000),
690 0x0c => send_payment!(nodes[2], (&nodes[1], chan_b), 5_000_000),
691 0x0d => send_payment!(nodes[0], (&nodes[1], chan_a), (&nodes[2], chan_b), 5_000_000),
692 0x0e => send_payment!(nodes[2], (&nodes[1], chan_b), (&nodes[0], chan_a), 5_000_000),
694 if !chan_a_disconnected {
695 nodes[0].peer_disconnected(&nodes[1].get_our_node_id(), false);
696 nodes[1].peer_disconnected(&nodes[0].get_our_node_id(), false);
697 chan_a_disconnected = true;
698 drain_msg_events_on_disconnect!(0);
702 if !chan_b_disconnected {
703 nodes[1].peer_disconnected(&nodes[2].get_our_node_id(), false);
704 nodes[2].peer_disconnected(&nodes[1].get_our_node_id(), false);
705 chan_b_disconnected = true;
706 drain_msg_events_on_disconnect!(2);
710 if chan_a_disconnected {
711 nodes[0].peer_connected(&nodes[1].get_our_node_id(), &Init { features: InitFeatures::empty() });
712 nodes[1].peer_connected(&nodes[0].get_our_node_id(), &Init { features: InitFeatures::empty() });
713 chan_a_disconnected = false;
717 if chan_b_disconnected {
718 nodes[1].peer_connected(&nodes[2].get_our_node_id(), &Init { features: InitFeatures::empty() });
719 nodes[2].peer_connected(&nodes[1].get_our_node_id(), &Init { features: InitFeatures::empty() });
720 chan_b_disconnected = false;
723 0x13 => process_msg_events!(0, true),
724 0x14 => process_msg_events!(0, false),
725 0x15 => process_events!(0, true),
726 0x16 => process_events!(0, false),
727 0x17 => process_msg_events!(1, true),
728 0x18 => process_msg_events!(1, false),
729 0x19 => process_events!(1, true),
730 0x1a => process_events!(1, false),
731 0x1b => process_msg_events!(2, true),
732 0x1c => process_msg_events!(2, false),
733 0x1d => process_events!(2, true),
734 0x1e => process_events!(2, false),
736 if !chan_a_disconnected {
737 nodes[1].peer_disconnected(&nodes[0].get_our_node_id(), false);
738 chan_a_disconnected = true;
739 drain_msg_events_on_disconnect!(0);
741 let (new_node_a, new_monitor_a) = reload_node!(node_a_ser, 0, monitor_a);
742 node_a = Arc::new(new_node_a);
743 nodes[0] = node_a.clone();
744 monitor_a = new_monitor_a;
747 if !chan_a_disconnected {
748 nodes[0].peer_disconnected(&nodes[1].get_our_node_id(), false);
749 chan_a_disconnected = true;
750 nodes[0].get_and_clear_pending_msg_events();
753 if !chan_b_disconnected {
754 nodes[2].peer_disconnected(&nodes[1].get_our_node_id(), false);
755 chan_b_disconnected = true;
756 nodes[2].get_and_clear_pending_msg_events();
759 let (new_node_b, new_monitor_b) = reload_node!(node_b_ser, 1, monitor_b);
760 node_b = Arc::new(new_node_b);
761 nodes[1] = node_b.clone();
762 monitor_b = new_monitor_b;
765 if !chan_b_disconnected {
766 nodes[1].peer_disconnected(&nodes[2].get_our_node_id(), false);
767 chan_b_disconnected = true;
768 drain_msg_events_on_disconnect!(2);
770 let (new_node_c, new_monitor_c) = reload_node!(node_c_ser, 2, monitor_c);
771 node_c = Arc::new(new_node_c);
772 nodes[2] = node_c.clone();
773 monitor_c = new_monitor_c;
775 0x22 => send_payment_with_secret!(nodes[0], (&nodes[1], chan_a), (&nodes[2], chan_b)),
776 0x23 => send_payment_with_secret!(nodes[2], (&nodes[1], chan_b), (&nodes[0], chan_a)),
777 0x25 => send_payment!(nodes[0], (&nodes[1], chan_a), 10),
778 0x26 => send_payment!(nodes[1], (&nodes[0], chan_a), 10),
779 0x27 => send_payment!(nodes[1], (&nodes[2], chan_b), 10),
780 0x28 => send_payment!(nodes[2], (&nodes[1], chan_b), 10),
781 0x29 => send_payment!(nodes[0], (&nodes[1], chan_a), (&nodes[2], chan_b), 10),
782 0x2a => send_payment!(nodes[2], (&nodes[1], chan_b), (&nodes[0], chan_a), 10),
783 0x2b => send_payment!(nodes[0], (&nodes[1], chan_a), 1_000),
784 0x2c => send_payment!(nodes[1], (&nodes[0], chan_a), 1_000),
785 0x2d => send_payment!(nodes[1], (&nodes[2], chan_b), 1_000),
786 0x2e => send_payment!(nodes[2], (&nodes[1], chan_b), 1_000),
787 0x2f => send_payment!(nodes[0], (&nodes[1], chan_a), (&nodes[2], chan_b), 1_000),
788 0x30 => send_payment!(nodes[2], (&nodes[1], chan_b), (&nodes[0], chan_a), 1_000),
789 0x31 => send_payment!(nodes[0], (&nodes[1], chan_a), 100_000),
790 0x32 => send_payment!(nodes[1], (&nodes[0], chan_a), 100_000),
791 0x33 => send_payment!(nodes[1], (&nodes[2], chan_b), 100_000),
792 0x34 => send_payment!(nodes[2], (&nodes[1], chan_b), 100_000),
793 0x35 => send_payment!(nodes[0], (&nodes[1], chan_a), (&nodes[2], chan_b), 100_000),
794 0x36 => send_payment!(nodes[2], (&nodes[1], chan_b), (&nodes[0], chan_a), 100_000),
795 // 0x24 defined above
799 node_a_ser.0.clear();
800 nodes[0].write(&mut node_a_ser).unwrap();
801 monitor_a.should_update_manager.store(false, atomic::Ordering::Relaxed);
802 node_b_ser.0.clear();
803 nodes[1].write(&mut node_b_ser).unwrap();
804 monitor_b.should_update_manager.store(false, atomic::Ordering::Relaxed);
805 node_c_ser.0.clear();
806 nodes[2].write(&mut node_c_ser).unwrap();
807 monitor_c.should_update_manager.store(false, atomic::Ordering::Relaxed);
811 pub fn chanmon_consistency_test<Out: test_logger::Output>(data: &[u8], out: Out) {
816 pub extern "C" fn chanmon_consistency_run(data: *const u8, datalen: usize) {
817 do_test(unsafe { std::slice::from_raw_parts(data, datalen) }, test_logger::DevNull{});