Let some tests disable revocation policy check
[rust-lightning] / fuzz / src / chanmon_consistency.rs
1 // This file is Copyright its original authors, visible in version control
2 // history.
3 //
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
8 // licenses.
9
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.
20
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;
26
27 use bitcoin::hashes::Hash as TraitImport;
28 use bitcoin::hashes::sha256::Hash as Sha256;
29 use bitcoin::hash_types::{BlockHash, WPubkeyHash};
30
31 use lightning::chain;
32 use lightning::chain::chainmonitor;
33 use lightning::chain::channelmonitor;
34 use lightning::chain::channelmonitor::{ChannelMonitor, ChannelMonitorUpdateErr, MonitorEvent};
35 use lightning::chain::transaction::OutPoint;
36 use lightning::chain::chaininterface::{BroadcasterInterface, ConfirmationTarget, FeeEstimator};
37 use lightning::chain::keysinterface::{KeysInterface, InMemoryChannelKeys};
38 use lightning::ln::channelmanager::{ChannelManager, PaymentHash, PaymentPreimage, PaymentSecret, PaymentSendFailure, ChannelManagerReadArgs};
39 use lightning::ln::features::{ChannelFeatures, InitFeatures, NodeFeatures};
40 use lightning::ln::msgs::{CommitmentUpdate, ChannelMessageHandler, DecodeError, ErrorAction, UpdateAddHTLC, Init};
41 use lightning::util::enforcing_trait_impls::{EnforcingChannelKeys, INITIAL_REVOKED_COMMITMENT_NUMBER};
42 use lightning::util::errors::APIError;
43 use lightning::util::events;
44 use lightning::util::logger::Logger;
45 use lightning::util::config::UserConfig;
46 use lightning::util::events::{EventsProvider, MessageSendEventsProvider};
47 use lightning::util::ser::{Readable, ReadableArgs, Writeable, Writer};
48 use lightning::util::test_utils::OnlyReadsKeysInterface;
49 use lightning::routing::router::{Route, RouteHop};
50
51
52 use utils::test_logger;
53 use utils::test_persister::TestPersister;
54
55 use bitcoin::secp256k1::key::{PublicKey,SecretKey};
56 use bitcoin::secp256k1::Secp256k1;
57
58 use std::mem;
59 use std::cmp::Ordering;
60 use std::collections::{HashSet, hash_map, HashMap};
61 use std::sync::{Arc,Mutex};
62 use std::sync::atomic;
63 use std::io::Cursor;
64
65 struct FuzzEstimator {}
66 impl FeeEstimator for FuzzEstimator {
67         fn get_est_sat_per_1000_weight(&self, _: ConfirmationTarget) -> u32 {
68                 253
69         }
70 }
71
72 pub struct TestBroadcaster {}
73 impl BroadcasterInterface for TestBroadcaster {
74         fn broadcast_transaction(&self, _tx: &Transaction) { }
75 }
76
77 pub struct VecWriter(pub Vec<u8>);
78 impl Writer for VecWriter {
79         fn write_all(&mut self, buf: &[u8]) -> Result<(), ::std::io::Error> {
80                 self.0.extend_from_slice(buf);
81                 Ok(())
82         }
83         fn size_hint(&mut self, size: usize) {
84                 self.0.reserve_exact(size);
85         }
86 }
87
88 struct TestChainMonitor {
89         pub logger: Arc<dyn Logger>,
90         pub chain_monitor: Arc<chainmonitor::ChainMonitor<EnforcingChannelKeys, Arc<dyn chain::Filter>, Arc<TestBroadcaster>, Arc<FuzzEstimator>, Arc<dyn Logger>, Arc<TestPersister>>>,
91         pub update_ret: Mutex<Result<(), channelmonitor::ChannelMonitorUpdateErr>>,
92         // If we reload a node with an old copy of ChannelMonitors, the ChannelManager deserialization
93         // logic will automatically force-close our channels for us (as we don't have an up-to-date
94         // monitor implying we are not able to punish misbehaving counterparties). Because this test
95         // "fails" if we ever force-close a channel, we avoid doing so, always saving the latest
96         // fully-serialized monitor state here, as well as the corresponding update_id.
97         pub latest_monitors: Mutex<HashMap<OutPoint, (u64, Vec<u8>)>>,
98         pub should_update_manager: atomic::AtomicBool,
99 }
100 impl TestChainMonitor {
101         pub fn new(broadcaster: Arc<TestBroadcaster>, logger: Arc<dyn Logger>, feeest: Arc<FuzzEstimator>, persister: Arc<TestPersister>) -> Self {
102                 Self {
103                         chain_monitor: Arc::new(chainmonitor::ChainMonitor::new(None, broadcaster, logger.clone(), feeest, persister)),
104                         logger,
105                         update_ret: Mutex::new(Ok(())),
106                         latest_monitors: Mutex::new(HashMap::new()),
107                         should_update_manager: atomic::AtomicBool::new(false),
108                 }
109         }
110 }
111 impl chain::Watch for TestChainMonitor {
112         type Keys = EnforcingChannelKeys;
113
114         fn watch_channel(&self, funding_txo: OutPoint, monitor: channelmonitor::ChannelMonitor<EnforcingChannelKeys>) -> Result<(), channelmonitor::ChannelMonitorUpdateErr> {
115                 let mut ser = VecWriter(Vec::new());
116                 monitor.write(&mut ser).unwrap();
117                 if let Some(_) = self.latest_monitors.lock().unwrap().insert(funding_txo, (monitor.get_latest_update_id(), ser.0)) {
118                         panic!("Already had monitor pre-watch_channel");
119                 }
120                 self.should_update_manager.store(true, atomic::Ordering::Relaxed);
121                 assert!(self.chain_monitor.watch_channel(funding_txo, monitor).is_ok());
122                 self.update_ret.lock().unwrap().clone()
123         }
124
125         fn update_channel(&self, funding_txo: OutPoint, update: channelmonitor::ChannelMonitorUpdate) -> Result<(), channelmonitor::ChannelMonitorUpdateErr> {
126                 let mut map_lock = self.latest_monitors.lock().unwrap();
127                 let mut map_entry = match map_lock.entry(funding_txo) {
128                         hash_map::Entry::Occupied(entry) => entry,
129                         hash_map::Entry::Vacant(_) => panic!("Didn't have monitor on update call"),
130                 };
131                 let mut deserialized_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingChannelKeys>)>::
132                         read(&mut Cursor::new(&map_entry.get().1), &OnlyReadsKeysInterface {}).unwrap().1;
133                 deserialized_monitor.update_monitor(&update, &&TestBroadcaster{}, &&FuzzEstimator{}, &self.logger).unwrap();
134                 let mut ser = VecWriter(Vec::new());
135                 deserialized_monitor.write(&mut ser).unwrap();
136                 map_entry.insert((update.update_id, ser.0));
137                 self.should_update_manager.store(true, atomic::Ordering::Relaxed);
138                 self.update_ret.lock().unwrap().clone()
139         }
140
141         fn release_pending_monitor_events(&self) -> Vec<MonitorEvent> {
142                 return self.chain_monitor.release_pending_monitor_events();
143         }
144 }
145
146 struct KeyProvider {
147         node_id: u8,
148         rand_bytes_id: atomic::AtomicU8,
149         revoked_commitments: Mutex<HashMap<[u8;32], Arc<Mutex<u64>>>>,
150 }
151 impl KeysInterface for KeyProvider {
152         type ChanKeySigner = EnforcingChannelKeys;
153
154         fn get_node_secret(&self) -> SecretKey {
155                 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()
156         }
157
158         fn get_destination_script(&self) -> Script {
159                 let secp_ctx = Secp256k1::signing_only();
160                 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();
161                 let our_channel_monitor_claim_key_hash = WPubkeyHash::hash(&PublicKey::from_secret_key(&secp_ctx, &channel_monitor_claim_key).serialize());
162                 Builder::new().push_opcode(opcodes::all::OP_PUSHBYTES_0).push_slice(&our_channel_monitor_claim_key_hash[..]).into_script()
163         }
164
165         fn get_shutdown_pubkey(&self) -> PublicKey {
166                 let secp_ctx = Secp256k1::signing_only();
167                 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())
168         }
169
170         fn get_channel_keys(&self, _inbound: bool, channel_value_satoshis: u64) -> EnforcingChannelKeys {
171                 let secp_ctx = Secp256k1::signing_only();
172                 let id = self.rand_bytes_id.fetch_add(1, atomic::Ordering::Relaxed);
173                 let keys = InMemoryChannelKeys::new(
174                         &secp_ctx,
175                         SecretKey::from_slice(&[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, self.node_id]).unwrap(),
176                         SecretKey::from_slice(&[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, self.node_id]).unwrap(),
177                         SecretKey::from_slice(&[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, self.node_id]).unwrap(),
178                         SecretKey::from_slice(&[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, self.node_id]).unwrap(),
179                         SecretKey::from_slice(&[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, self.node_id]).unwrap(),
180                         [id, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, self.node_id],
181                         channel_value_satoshis,
182                         (0, 0),
183                 );
184                 let revoked_commitment = self.make_revoked_commitment_cell(keys.commitment_seed);
185                 EnforcingChannelKeys::new_with_revoked(keys, revoked_commitment, false)
186         }
187
188         fn get_secure_random_bytes(&self) -> [u8; 32] {
189                 let id = self.rand_bytes_id.fetch_add(1, atomic::Ordering::Relaxed);
190                 [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]
191         }
192
193         fn read_chan_signer(&self, buffer: &[u8]) -> Result<Self::ChanKeySigner, DecodeError> {
194                 let mut reader = std::io::Cursor::new(buffer);
195
196                 let inner: InMemoryChannelKeys = Readable::read(&mut reader)?;
197                 let revoked_commitment = self.make_revoked_commitment_cell(inner.commitment_seed);
198
199                 let last_commitment_number = Readable::read(&mut reader)?;
200
201                 Ok(EnforcingChannelKeys {
202                         inner,
203                         last_commitment_number: Arc::new(Mutex::new(last_commitment_number)),
204                         revoked_commitment,
205                         disable_revocation_policy_check: false,
206                 })
207         }
208 }
209
210 impl KeyProvider {
211         fn make_revoked_commitment_cell(&self, commitment_seed: [u8; 32]) -> Arc<Mutex<u64>> {
212                 let mut revoked_commitments = self.revoked_commitments.lock().unwrap();
213                 if !revoked_commitments.contains_key(&commitment_seed) {
214                         revoked_commitments.insert(commitment_seed, Arc::new(Mutex::new(INITIAL_REVOKED_COMMITMENT_NUMBER)));
215                 }
216                 let cell = revoked_commitments.get(&commitment_seed).unwrap();
217                 Arc::clone(cell)
218         }
219 }
220
221 #[inline]
222 fn check_api_err(api_err: APIError) {
223         match api_err {
224                 APIError::APIMisuseError { .. } => panic!("We can't misuse the API"),
225                 APIError::FeeRateTooHigh { .. } => panic!("We can't send too much fee?"),
226                 APIError::RouteError { .. } => panic!("Our routes should work"),
227                 APIError::ChannelUnavailable { err } => {
228                         // Test the error against a list of errors we can hit, and reject
229                         // all others. If you hit this panic, the list of acceptable errors
230                         // is probably just stale and you should add new messages here.
231                         match err.as_str() {
232                                 "Peer for first hop currently disconnected/pending monitor update!" => {},
233                                 _ if err.starts_with("Cannot push more than their max accepted HTLCs ") => {},
234                                 _ if err.starts_with("Cannot send value that would put us over the max HTLC value in flight our peer will accept ") => {},
235                                 _ if err.starts_with("Cannot send value that would put our balance under counterparty-announced channel reserve value") => {},
236                                 _ if err.starts_with("Cannot send value that would overdraw remaining funds.") => {},
237                                 _ if err.starts_with("Cannot send value that would not leave enough to pay for fees.") => {},
238                                 _ => panic!(err),
239                         }
240                 },
241                 APIError::MonitorUpdateFailed => {
242                         // We can (obviously) temp-fail a monitor update
243                 },
244         }
245 }
246 #[inline]
247 fn check_payment_err(send_err: PaymentSendFailure) {
248         match send_err {
249                 PaymentSendFailure::ParameterError(api_err) => check_api_err(api_err),
250                 PaymentSendFailure::PathParameterError(per_path_results) => {
251                         for res in per_path_results { if let Err(api_err) = res { check_api_err(api_err); } }
252                 },
253                 PaymentSendFailure::AllFailedRetrySafe(per_path_results) => {
254                         for api_err in per_path_results { check_api_err(api_err); }
255                 },
256                 PaymentSendFailure::PartialFailure(per_path_results) => {
257                         for res in per_path_results { if let Err(api_err) = res { check_api_err(api_err); } }
258                 },
259         }
260 }
261
262 type ChanMan = ChannelManager<EnforcingChannelKeys, Arc<TestChainMonitor>, Arc<TestBroadcaster>, Arc<KeyProvider>, Arc<FuzzEstimator>, Arc<dyn Logger>>;
263
264 #[inline]
265 fn send_payment(source: &ChanMan, dest: &ChanMan, dest_chan_id: u64, amt: u64, payment_id: &mut u8) -> bool {
266         let payment_hash = Sha256::hash(&[*payment_id; 1]);
267         *payment_id = payment_id.wrapping_add(1);
268         if let Err(err) = source.send_payment(&Route {
269                 paths: vec![vec![RouteHop {
270                         pubkey: dest.get_our_node_id(),
271                         node_features: NodeFeatures::empty(),
272                         short_channel_id: dest_chan_id,
273                         channel_features: ChannelFeatures::empty(),
274                         fee_msat: amt,
275                         cltv_expiry_delta: 200,
276                 }]],
277         }, PaymentHash(payment_hash.into_inner()), &None) {
278                 check_payment_err(err);
279                 false
280         } else { true }
281 }
282 #[inline]
283 fn send_hop_payment(source: &ChanMan, middle: &ChanMan, middle_chan_id: u64, dest: &ChanMan, dest_chan_id: u64, amt: u64, payment_id: &mut u8) -> bool {
284         let payment_hash = Sha256::hash(&[*payment_id; 1]);
285         *payment_id = payment_id.wrapping_add(1);
286         if let Err(err) = source.send_payment(&Route {
287                 paths: vec![vec![RouteHop {
288                         pubkey: middle.get_our_node_id(),
289                         node_features: NodeFeatures::empty(),
290                         short_channel_id: middle_chan_id,
291                         channel_features: ChannelFeatures::empty(),
292                         fee_msat: 50000,
293                         cltv_expiry_delta: 100,
294                 },RouteHop {
295                         pubkey: dest.get_our_node_id(),
296                         node_features: NodeFeatures::empty(),
297                         short_channel_id: dest_chan_id,
298                         channel_features: ChannelFeatures::empty(),
299                         fee_msat: amt,
300                         cltv_expiry_delta: 200,
301                 }]],
302         }, PaymentHash(payment_hash.into_inner()), &None) {
303                 check_payment_err(err);
304                 false
305         } else { true }
306 }
307
308 #[inline]
309 pub fn do_test<Out: test_logger::Output>(data: &[u8], out: Out) {
310         let fee_est = Arc::new(FuzzEstimator{});
311         let broadcast = Arc::new(TestBroadcaster{});
312
313         macro_rules! make_node {
314                 ($node_id: expr) => { {
315                         let logger: Arc<dyn Logger> = Arc::new(test_logger::TestLogger::new($node_id.to_string(), out.clone()));
316                         let monitor = Arc::new(TestChainMonitor::new(broadcast.clone(), logger.clone(), fee_est.clone(), Arc::new(TestPersister{})));
317
318                         let keys_manager = Arc::new(KeyProvider { node_id: $node_id, rand_bytes_id: atomic::AtomicU8::new(0), revoked_commitments: Mutex::new(HashMap::new()) });
319                         let mut config = UserConfig::default();
320                         config.channel_options.fee_proportional_millionths = 0;
321                         config.channel_options.announced_channel = true;
322                         config.peer_channel_config_limits.min_dust_limit_satoshis = 0;
323                         (ChannelManager::new(Network::Bitcoin, fee_est.clone(), monitor.clone(), broadcast.clone(), Arc::clone(&logger), keys_manager.clone(), config, 0),
324                         monitor, keys_manager)
325                 } }
326         }
327
328         macro_rules! reload_node {
329                 ($ser: expr, $node_id: expr, $old_monitors: expr, $keys_manager: expr) => { {
330                     let keys_manager = Arc::clone(& $keys_manager);
331                         let logger: Arc<dyn Logger> = Arc::new(test_logger::TestLogger::new($node_id.to_string(), out.clone()));
332                         let chain_monitor = Arc::new(TestChainMonitor::new(broadcast.clone(), logger.clone(), fee_est.clone(), Arc::new(TestPersister{})));
333
334                         let mut config = UserConfig::default();
335                         config.channel_options.fee_proportional_millionths = 0;
336                         config.channel_options.announced_channel = true;
337                         config.peer_channel_config_limits.min_dust_limit_satoshis = 0;
338
339                         let mut monitors = HashMap::new();
340                         let mut old_monitors = $old_monitors.latest_monitors.lock().unwrap();
341                         for (outpoint, (update_id, monitor_ser)) in old_monitors.drain() {
342                                 monitors.insert(outpoint, <(BlockHash, ChannelMonitor<EnforcingChannelKeys>)>::read(&mut Cursor::new(&monitor_ser), &OnlyReadsKeysInterface {}).expect("Failed to read monitor").1);
343                                 chain_monitor.latest_monitors.lock().unwrap().insert(outpoint, (update_id, monitor_ser));
344                         }
345                         let mut monitor_refs = HashMap::new();
346                         for (outpoint, monitor) in monitors.iter_mut() {
347                                 monitor_refs.insert(*outpoint, monitor);
348                         }
349
350                         let read_args = ChannelManagerReadArgs {
351                                 keys_manager,
352                                 fee_estimator: fee_est.clone(),
353                                 chain_monitor: chain_monitor.clone(),
354                                 tx_broadcaster: broadcast.clone(),
355                                 logger,
356                                 default_config: config,
357                                 channel_monitors: monitor_refs,
358                         };
359
360                         (<(BlockHash, ChanMan)>::read(&mut Cursor::new(&$ser.0), read_args).expect("Failed to read manager").1, chain_monitor)
361                 } }
362         }
363
364         let mut channel_txn = Vec::new();
365         macro_rules! make_channel {
366                 ($source: expr, $dest: expr, $chan_id: expr) => { {
367                         $source.create_channel($dest.get_our_node_id(), 100_000, 42, 0, None).unwrap();
368                         let open_channel = {
369                                 let events = $source.get_and_clear_pending_msg_events();
370                                 assert_eq!(events.len(), 1);
371                                 if let events::MessageSendEvent::SendOpenChannel { ref msg, .. } = events[0] {
372                                         msg.clone()
373                                 } else { panic!("Wrong event type"); }
374                         };
375
376                         $dest.handle_open_channel(&$source.get_our_node_id(), InitFeatures::known(), &open_channel);
377                         let accept_channel = {
378                                 let events = $dest.get_and_clear_pending_msg_events();
379                                 assert_eq!(events.len(), 1);
380                                 if let events::MessageSendEvent::SendAcceptChannel { ref msg, .. } = events[0] {
381                                         msg.clone()
382                                 } else { panic!("Wrong event type"); }
383                         };
384
385                         $source.handle_accept_channel(&$dest.get_our_node_id(), InitFeatures::known(), &accept_channel);
386                         let funding_output;
387                         {
388                                 let events = $source.get_and_clear_pending_events();
389                                 assert_eq!(events.len(), 1);
390                                 if let events::Event::FundingGenerationReady { ref temporary_channel_id, ref channel_value_satoshis, ref output_script, .. } = events[0] {
391                                         let tx = Transaction { version: $chan_id, lock_time: 0, input: Vec::new(), output: vec![TxOut {
392                                                 value: *channel_value_satoshis, script_pubkey: output_script.clone(),
393                                         }]};
394                                         funding_output = OutPoint { txid: tx.txid(), index: 0 };
395                                         $source.funding_transaction_generated(&temporary_channel_id, funding_output);
396                                         channel_txn.push(tx);
397                                 } else { panic!("Wrong event type"); }
398                         }
399
400                         let funding_created = {
401                                 let events = $source.get_and_clear_pending_msg_events();
402                                 assert_eq!(events.len(), 1);
403                                 if let events::MessageSendEvent::SendFundingCreated { ref msg, .. } = events[0] {
404                                         msg.clone()
405                                 } else { panic!("Wrong event type"); }
406                         };
407                         $dest.handle_funding_created(&$source.get_our_node_id(), &funding_created);
408
409                         let funding_signed = {
410                                 let events = $dest.get_and_clear_pending_msg_events();
411                                 assert_eq!(events.len(), 1);
412                                 if let events::MessageSendEvent::SendFundingSigned { ref msg, .. } = events[0] {
413                                         msg.clone()
414                                 } else { panic!("Wrong event type"); }
415                         };
416                         $source.handle_funding_signed(&$dest.get_our_node_id(), &funding_signed);
417
418                         {
419                                 let events = $source.get_and_clear_pending_events();
420                                 assert_eq!(events.len(), 1);
421                                 if let events::Event::FundingBroadcastSafe { .. } = events[0] {
422                                 } else { panic!("Wrong event type"); }
423                         }
424                         funding_output
425                 } }
426         }
427
428         macro_rules! confirm_txn {
429                 ($node: expr) => { {
430                         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
431                         let txdata: Vec<_> = channel_txn.iter().enumerate().map(|(i, tx)| (i + 1, tx)).collect();
432                         $node.block_connected(&header, &txdata, 1);
433                         for i in 2..100 {
434                                 header = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
435                                 $node.block_connected(&header, &[], i);
436                         }
437                 } }
438         }
439
440         macro_rules! lock_fundings {
441                 ($nodes: expr) => { {
442                         let mut node_events = Vec::new();
443                         for node in $nodes.iter() {
444                                 node_events.push(node.get_and_clear_pending_msg_events());
445                         }
446                         for (idx, node_event) in node_events.iter().enumerate() {
447                                 for event in node_event {
448                                         if let events::MessageSendEvent::SendFundingLocked { ref node_id, ref msg } = event {
449                                                 for node in $nodes.iter() {
450                                                         if node.get_our_node_id() == *node_id {
451                                                                 node.handle_funding_locked(&$nodes[idx].get_our_node_id(), msg);
452                                                         }
453                                                 }
454                                         } else { panic!("Wrong event type"); }
455                                 }
456                         }
457
458                         for node in $nodes.iter() {
459                                 let events = node.get_and_clear_pending_msg_events();
460                                 for event in events {
461                                         if let events::MessageSendEvent::SendAnnouncementSignatures { .. } = event {
462                                         } else { panic!("Wrong event type"); }
463                                 }
464                         }
465                 } }
466         }
467
468         // 3 nodes is enough to hit all the possible cases, notably unknown-source-unknown-dest
469         // forwarding.
470         let (node_a, mut monitor_a, keys_manager_a) = make_node!(0);
471         let (node_b, mut monitor_b, keys_manager_b) = make_node!(1);
472         let (node_c, mut monitor_c, keys_manager_c) = make_node!(2);
473
474         let mut nodes = [node_a, node_b, node_c];
475
476         let chan_1_funding = make_channel!(nodes[0], nodes[1], 0);
477         let chan_2_funding = make_channel!(nodes[1], nodes[2], 1);
478
479         for node in nodes.iter() {
480                 confirm_txn!(node);
481         }
482
483         lock_fundings!(nodes);
484
485         let chan_a = nodes[0].list_usable_channels()[0].short_channel_id.unwrap();
486         let chan_b = nodes[2].list_usable_channels()[0].short_channel_id.unwrap();
487
488         let mut payment_id: u8 = 0;
489
490         let mut chan_a_disconnected = false;
491         let mut chan_b_disconnected = false;
492         let mut ba_events = Vec::new();
493         let mut bc_events = Vec::new();
494
495         let mut node_a_ser = VecWriter(Vec::new());
496         nodes[0].write(&mut node_a_ser).unwrap();
497         let mut node_b_ser = VecWriter(Vec::new());
498         nodes[1].write(&mut node_b_ser).unwrap();
499         let mut node_c_ser = VecWriter(Vec::new());
500         nodes[2].write(&mut node_c_ser).unwrap();
501
502         macro_rules! test_return {
503                 () => { {
504                         assert_eq!(nodes[0].list_channels().len(), 1);
505                         assert_eq!(nodes[1].list_channels().len(), 2);
506                         assert_eq!(nodes[2].list_channels().len(), 1);
507                         return;
508                 } }
509         }
510
511         let mut read_pos = 0;
512         macro_rules! get_slice {
513                 ($len: expr) => {
514                         {
515                                 let slice_len = $len as usize;
516                                 if data.len() < read_pos + slice_len {
517                                         test_return!();
518                                 }
519                                 read_pos += slice_len;
520                                 &data[read_pos - slice_len..read_pos]
521                         }
522                 }
523         }
524
525         loop {
526                 macro_rules! send_payment_with_secret {
527                         ($source: expr, $middle: expr, $dest: expr) => { {
528                                 let payment_hash = Sha256::hash(&[payment_id; 1]);
529                                 payment_id = payment_id.wrapping_add(1);
530                                 let payment_secret = Sha256::hash(&[payment_id; 1]);
531                                 payment_id = payment_id.wrapping_add(1);
532                                 if let Err(err) = $source.send_payment(&Route {
533                                         paths: vec![vec![RouteHop {
534                                                 pubkey: $middle.0.get_our_node_id(),
535                                                 node_features: NodeFeatures::empty(),
536                                                 short_channel_id: $middle.1,
537                                                 channel_features: ChannelFeatures::empty(),
538                                                 fee_msat: 50_000,
539                                                 cltv_expiry_delta: 100,
540                                         },RouteHop {
541                                                 pubkey: $dest.0.get_our_node_id(),
542                                                 node_features: NodeFeatures::empty(),
543                                                 short_channel_id: $dest.1,
544                                                 channel_features: ChannelFeatures::empty(),
545                                                 fee_msat: 10_000_000,
546                                                 cltv_expiry_delta: 200,
547                                         }],vec![RouteHop {
548                                                 pubkey: $middle.0.get_our_node_id(),
549                                                 node_features: NodeFeatures::empty(),
550                                                 short_channel_id: $middle.1,
551                                                 channel_features: ChannelFeatures::empty(),
552                                                 fee_msat: 50_000,
553                                                 cltv_expiry_delta: 100,
554                                         },RouteHop {
555                                                 pubkey: $dest.0.get_our_node_id(),
556                                                 node_features: NodeFeatures::empty(),
557                                                 short_channel_id: $dest.1,
558                                                 channel_features: ChannelFeatures::empty(),
559                                                 fee_msat: 10_000_000,
560                                                 cltv_expiry_delta: 200,
561                                         }]],
562                                 }, PaymentHash(payment_hash.into_inner()), &Some(PaymentSecret(payment_secret.into_inner()))) {
563                                         check_payment_err(err);
564                                 }
565                         } }
566                 }
567
568                 macro_rules! process_msg_events {
569                         ($node: expr, $corrupt_forward: expr) => { {
570                                 let events = if $node == 1 {
571                                         let mut new_events = Vec::new();
572                                         mem::swap(&mut new_events, &mut ba_events);
573                                         new_events.extend_from_slice(&bc_events[..]);
574                                         bc_events.clear();
575                                         new_events
576                                 } else { Vec::new() };
577                                 let mut had_events = false;
578                                 for event in events.iter().chain(nodes[$node].get_and_clear_pending_msg_events().iter()) {
579                                         had_events = true;
580                                         match event {
581                                                 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 } } => {
582                                                         for dest in nodes.iter() {
583                                                                 if dest.get_our_node_id() == *node_id {
584                                                                         assert!(update_fee.is_none());
585                                                                         for update_add in update_add_htlcs {
586                                                                                 if !$corrupt_forward {
587                                                                                         dest.handle_update_add_htlc(&nodes[$node].get_our_node_id(), &update_add);
588                                                                                 } else {
589                                                                                         // Corrupt the update_add_htlc message so that its HMAC
590                                                                                         // check will fail and we generate a
591                                                                                         // update_fail_malformed_htlc instead of an
592                                                                                         // update_fail_htlc as we do when we reject a payment.
593                                                                                         let mut msg_ser = update_add.encode();
594                                                                                         msg_ser[1000] ^= 0xff;
595                                                                                         let new_msg = UpdateAddHTLC::read(&mut Cursor::new(&msg_ser)).unwrap();
596                                                                                         dest.handle_update_add_htlc(&nodes[$node].get_our_node_id(), &new_msg);
597                                                                                 }
598                                                                         }
599                                                                         for update_fulfill in update_fulfill_htlcs {
600                                                                                 dest.handle_update_fulfill_htlc(&nodes[$node].get_our_node_id(), &update_fulfill);
601                                                                         }
602                                                                         for update_fail in update_fail_htlcs {
603                                                                                 dest.handle_update_fail_htlc(&nodes[$node].get_our_node_id(), &update_fail);
604                                                                         }
605                                                                         for update_fail_malformed in update_fail_malformed_htlcs {
606                                                                                 dest.handle_update_fail_malformed_htlc(&nodes[$node].get_our_node_id(), &update_fail_malformed);
607                                                                         }
608                                                                         dest.handle_commitment_signed(&nodes[$node].get_our_node_id(), &commitment_signed);
609                                                                 }
610                                                         }
611                                                 },
612                                                 events::MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
613                                                         for dest in nodes.iter() {
614                                                                 if dest.get_our_node_id() == *node_id {
615                                                                         dest.handle_revoke_and_ack(&nodes[$node].get_our_node_id(), msg);
616                                                                 }
617                                                         }
618                                                 },
619                                                 events::MessageSendEvent::SendChannelReestablish { ref node_id, ref msg } => {
620                                                         for dest in nodes.iter() {
621                                                                 if dest.get_our_node_id() == *node_id {
622                                                                         dest.handle_channel_reestablish(&nodes[$node].get_our_node_id(), msg);
623                                                                 }
624                                                         }
625                                                 },
626                                                 events::MessageSendEvent::SendFundingLocked { .. } => {
627                                                         // Can be generated as a reestablish response
628                                                 },
629                                                 events::MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {
630                                                         // Can be generated due to a payment forward being rejected due to a
631                                                         // channel having previously failed a monitor update
632                                                 },
633                                                 _ => panic!("Unhandled message event"),
634                                         }
635                                 }
636                                 had_events
637                         } }
638                 }
639
640                 macro_rules! drain_msg_events_on_disconnect {
641                         ($counterparty_id: expr) => { {
642                                 if $counterparty_id == 0 {
643                                         for event in nodes[0].get_and_clear_pending_msg_events() {
644                                                 match event {
645                                                         events::MessageSendEvent::UpdateHTLCs { .. } => {},
646                                                         events::MessageSendEvent::SendRevokeAndACK { .. } => {},
647                                                         events::MessageSendEvent::SendChannelReestablish { .. } => {},
648                                                         events::MessageSendEvent::SendFundingLocked { .. } => {},
649                                                         events::MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
650                                                         events::MessageSendEvent::HandleError { action: ErrorAction::IgnoreError, .. } => {},
651                                                         _ => panic!("Unhandled message event"),
652                                                 }
653                                         }
654                                         ba_events.clear();
655                                 } else {
656                                         for event in nodes[2].get_and_clear_pending_msg_events() {
657                                                 match event {
658                                                         events::MessageSendEvent::UpdateHTLCs { .. } => {},
659                                                         events::MessageSendEvent::SendRevokeAndACK { .. } => {},
660                                                         events::MessageSendEvent::SendChannelReestablish { .. } => {},
661                                                         events::MessageSendEvent::SendFundingLocked { .. } => {},
662                                                         events::MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
663                                                         events::MessageSendEvent::HandleError { action: ErrorAction::IgnoreError, .. } => {},
664                                                         _ => panic!("Unhandled message event"),
665                                                 }
666                                         }
667                                         bc_events.clear();
668                                 }
669                                 let mut events = nodes[1].get_and_clear_pending_msg_events();
670                                 let drop_node_id = if $counterparty_id == 0 { nodes[0].get_our_node_id() } else { nodes[2].get_our_node_id() };
671                                 let msg_sink = if $counterparty_id == 0 { &mut bc_events } else { &mut ba_events };
672                                 for event in events.drain(..) {
673                                         let push = match event {
674                                                 events::MessageSendEvent::UpdateHTLCs { ref node_id, .. } => {
675                                                         if *node_id != drop_node_id { true } else { false }
676                                                 },
677                                                 events::MessageSendEvent::SendRevokeAndACK { ref node_id, .. } => {
678                                                         if *node_id != drop_node_id { true } else { false }
679                                                 },
680                                                 events::MessageSendEvent::SendChannelReestablish { ref node_id, .. } => {
681                                                         if *node_id != drop_node_id { true } else { false }
682                                                 },
683                                                 events::MessageSendEvent::SendFundingLocked { .. } => false,
684                                                 events::MessageSendEvent::PaymentFailureNetworkUpdate { .. } => false,
685                                                 events::MessageSendEvent::HandleError { action: ErrorAction::IgnoreError, .. } => false,
686                                                 _ => panic!("Unhandled message event"),
687                                         };
688                                         if push { msg_sink.push(event); }
689                                 }
690                         } }
691                 }
692
693                 macro_rules! process_events {
694                         ($node: expr, $fail: expr) => { {
695                                 // In case we get 256 payments we may have a hash collision, resulting in the
696                                 // second claim/fail call not finding the duplicate-hash HTLC, so we have to
697                                 // deduplicate the calls here.
698                                 let mut claim_set = HashSet::new();
699                                 let mut events = nodes[$node].get_and_clear_pending_events();
700                                 // Sort events so that PendingHTLCsForwardable get processed last. This avoids a
701                                 // case where we first process a PendingHTLCsForwardable, then claim/fail on a
702                                 // PaymentReceived, claiming/failing two HTLCs, but leaving a just-generated
703                                 // PaymentReceived event for the second HTLC in our pending_events (and breaking
704                                 // our claim_set deduplication).
705                                 events.sort_by(|a, b| {
706                                         if let events::Event::PaymentReceived { .. } = a {
707                                                 if let events::Event::PendingHTLCsForwardable { .. } = b {
708                                                         Ordering::Less
709                                                 } else { Ordering::Equal }
710                                         } else if let events::Event::PendingHTLCsForwardable { .. } = a {
711                                                 if let events::Event::PaymentReceived { .. } = b {
712                                                         Ordering::Greater
713                                                 } else { Ordering::Equal }
714                                         } else { Ordering::Equal }
715                                 });
716                                 let had_events = !events.is_empty();
717                                 for event in events.drain(..) {
718                                         match event {
719                                                 events::Event::PaymentReceived { payment_hash, payment_secret, amt } => {
720                                                         if claim_set.insert(payment_hash.0) {
721                                                                 if $fail {
722                                                                         assert!(nodes[$node].fail_htlc_backwards(&payment_hash, &payment_secret));
723                                                                 } else {
724                                                                         assert!(nodes[$node].claim_funds(PaymentPreimage(payment_hash.0), &payment_secret, amt));
725                                                                 }
726                                                         }
727                                                 },
728                                                 events::Event::PaymentSent { .. } => {},
729                                                 events::Event::PaymentFailed { .. } => {},
730                                                 events::Event::PendingHTLCsForwardable { .. } => {
731                                                         nodes[$node].process_pending_htlc_forwards();
732                                                 },
733                                                 _ => panic!("Unhandled event"),
734                                         }
735                                 }
736                                 had_events
737                         } }
738                 }
739
740                 match get_slice!(1)[0] {
741                         // In general, we keep related message groups close together in binary form, allowing
742                         // bit-twiddling mutations to have similar effects. This is probably overkill, but no
743                         // harm in doing so.
744
745                         0x00 => *monitor_a.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::TemporaryFailure),
746                         0x01 => *monitor_b.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::TemporaryFailure),
747                         0x02 => *monitor_c.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::TemporaryFailure),
748                         0x04 => *monitor_a.update_ret.lock().unwrap() = Ok(()),
749                         0x05 => *monitor_b.update_ret.lock().unwrap() = Ok(()),
750                         0x06 => *monitor_c.update_ret.lock().unwrap() = Ok(()),
751
752                         0x08 => {
753                                 if let Some((id, _)) = monitor_a.latest_monitors.lock().unwrap().get(&chan_1_funding) {
754                                         nodes[0].channel_monitor_updated(&chan_1_funding, *id);
755                                 }
756                         },
757                         0x09 => {
758                                 if let Some((id, _)) = monitor_b.latest_monitors.lock().unwrap().get(&chan_1_funding) {
759                                         nodes[1].channel_monitor_updated(&chan_1_funding, *id);
760                                 }
761                         },
762                         0x0a => {
763                                 if let Some((id, _)) = monitor_b.latest_monitors.lock().unwrap().get(&chan_2_funding) {
764                                         nodes[1].channel_monitor_updated(&chan_2_funding, *id);
765                                 }
766                         },
767                         0x0b => {
768                                 if let Some((id, _)) = monitor_c.latest_monitors.lock().unwrap().get(&chan_2_funding) {
769                                         nodes[2].channel_monitor_updated(&chan_2_funding, *id);
770                                 }
771                         },
772
773                         0x0c => {
774                                 if !chan_a_disconnected {
775                                         nodes[0].peer_disconnected(&nodes[1].get_our_node_id(), false);
776                                         nodes[1].peer_disconnected(&nodes[0].get_our_node_id(), false);
777                                         chan_a_disconnected = true;
778                                         drain_msg_events_on_disconnect!(0);
779                                 }
780                         },
781                         0x0d => {
782                                 if !chan_b_disconnected {
783                                         nodes[1].peer_disconnected(&nodes[2].get_our_node_id(), false);
784                                         nodes[2].peer_disconnected(&nodes[1].get_our_node_id(), false);
785                                         chan_b_disconnected = true;
786                                         drain_msg_events_on_disconnect!(2);
787                                 }
788                         },
789                         0x0e => {
790                                 if chan_a_disconnected {
791                                         nodes[0].peer_connected(&nodes[1].get_our_node_id(), &Init { features: InitFeatures::empty() });
792                                         nodes[1].peer_connected(&nodes[0].get_our_node_id(), &Init { features: InitFeatures::empty() });
793                                         chan_a_disconnected = false;
794                                 }
795                         },
796                         0x0f => {
797                                 if chan_b_disconnected {
798                                         nodes[1].peer_connected(&nodes[2].get_our_node_id(), &Init { features: InitFeatures::empty() });
799                                         nodes[2].peer_connected(&nodes[1].get_our_node_id(), &Init { features: InitFeatures::empty() });
800                                         chan_b_disconnected = false;
801                                 }
802                         },
803
804                         0x10 => { process_msg_events!(0, true); },
805                         0x11 => { process_msg_events!(0, false); },
806                         0x12 => { process_events!(0, true); },
807                         0x13 => { process_events!(0, false); },
808                         0x14 => { process_msg_events!(1, true); },
809                         0x15 => { process_msg_events!(1, false); },
810                         0x16 => { process_events!(1, true); },
811                         0x17 => { process_events!(1, false); },
812                         0x18 => { process_msg_events!(2, true); },
813                         0x19 => { process_msg_events!(2, false); },
814                         0x1a => { process_events!(2, true); },
815                         0x1b => { process_events!(2, false); },
816
817                         0x1c => {
818                                 if !chan_a_disconnected {
819                                         nodes[1].peer_disconnected(&nodes[0].get_our_node_id(), false);
820                                         chan_a_disconnected = true;
821                                         drain_msg_events_on_disconnect!(0);
822                                 }
823                                 let (new_node_a, new_monitor_a) = reload_node!(node_a_ser, 0, monitor_a, keys_manager_a);
824                                 nodes[0] = new_node_a;
825                                 monitor_a = new_monitor_a;
826                         },
827                         0x1d => {
828                                 if !chan_a_disconnected {
829                                         nodes[0].peer_disconnected(&nodes[1].get_our_node_id(), false);
830                                         chan_a_disconnected = true;
831                                         nodes[0].get_and_clear_pending_msg_events();
832                                         ba_events.clear();
833                                 }
834                                 if !chan_b_disconnected {
835                                         nodes[2].peer_disconnected(&nodes[1].get_our_node_id(), false);
836                                         chan_b_disconnected = true;
837                                         nodes[2].get_and_clear_pending_msg_events();
838                                         bc_events.clear();
839                                 }
840                                 let (new_node_b, new_monitor_b) = reload_node!(node_b_ser, 1, monitor_b, keys_manager_b);
841                                 nodes[1] = new_node_b;
842                                 monitor_b = new_monitor_b;
843                         },
844                         0x1e => {
845                                 if !chan_b_disconnected {
846                                         nodes[1].peer_disconnected(&nodes[2].get_our_node_id(), false);
847                                         chan_b_disconnected = true;
848                                         drain_msg_events_on_disconnect!(2);
849                                 }
850                                 let (new_node_c, new_monitor_c) = reload_node!(node_c_ser, 2, monitor_c, keys_manager_c);
851                                 nodes[2] = new_node_c;
852                                 monitor_c = new_monitor_c;
853                         },
854
855                         // 1/10th the channel size:
856                         0x20 => { send_payment(&nodes[0], &nodes[1], chan_a, 10_000_000, &mut payment_id); },
857                         0x21 => { send_payment(&nodes[1], &nodes[0], chan_a, 10_000_000, &mut payment_id); },
858                         0x22 => { send_payment(&nodes[1], &nodes[2], chan_b, 10_000_000, &mut payment_id); },
859                         0x23 => { send_payment(&nodes[2], &nodes[1], chan_b, 10_000_000, &mut payment_id); },
860                         0x24 => { send_hop_payment(&nodes[0], &nodes[1], chan_a, &nodes[2], chan_b, 10_000_000, &mut payment_id); },
861                         0x25 => { send_hop_payment(&nodes[2], &nodes[1], chan_b, &nodes[0], chan_a, 10_000_000, &mut payment_id); },
862
863                         0x26 => { send_payment_with_secret!(nodes[0], (&nodes[1], chan_a), (&nodes[2], chan_b)); },
864                         0x27 => { send_payment_with_secret!(nodes[2], (&nodes[1], chan_b), (&nodes[0], chan_a)); },
865
866                         0x28 => { send_payment(&nodes[0], &nodes[1], chan_a, 1_000_000, &mut payment_id); },
867                         0x29 => { send_payment(&nodes[1], &nodes[0], chan_a, 1_000_000, &mut payment_id); },
868                         0x2a => { send_payment(&nodes[1], &nodes[2], chan_b, 1_000_000, &mut payment_id); },
869                         0x2b => { send_payment(&nodes[2], &nodes[1], chan_b, 1_000_000, &mut payment_id); },
870                         0x2c => { send_hop_payment(&nodes[0], &nodes[1], chan_a, &nodes[2], chan_b, 1_000_000, &mut payment_id); },
871                         0x2d => { send_hop_payment(&nodes[2], &nodes[1], chan_b, &nodes[0], chan_a, 1_000_000, &mut payment_id); },
872
873                         0x30 => { send_payment(&nodes[0], &nodes[1], chan_a, 100_000, &mut payment_id); },
874                         0x31 => { send_payment(&nodes[1], &nodes[0], chan_a, 100_000, &mut payment_id); },
875                         0x32 => { send_payment(&nodes[1], &nodes[2], chan_b, 100_000, &mut payment_id); },
876                         0x33 => { send_payment(&nodes[2], &nodes[1], chan_b, 100_000, &mut payment_id); },
877                         0x34 => { send_hop_payment(&nodes[0], &nodes[1], chan_a, &nodes[2], chan_b, 100_000, &mut payment_id); },
878                         0x35 => { send_hop_payment(&nodes[2], &nodes[1], chan_b, &nodes[0], chan_a, 100_000, &mut payment_id); },
879
880                         0x38 => { send_payment(&nodes[0], &nodes[1], chan_a, 10_000, &mut payment_id); },
881                         0x39 => { send_payment(&nodes[1], &nodes[0], chan_a, 10_000, &mut payment_id); },
882                         0x3a => { send_payment(&nodes[1], &nodes[2], chan_b, 10_000, &mut payment_id); },
883                         0x3b => { send_payment(&nodes[2], &nodes[1], chan_b, 10_000, &mut payment_id); },
884                         0x3c => { send_hop_payment(&nodes[0], &nodes[1], chan_a, &nodes[2], chan_b, 10_000, &mut payment_id); },
885                         0x3d => { send_hop_payment(&nodes[2], &nodes[1], chan_b, &nodes[0], chan_a, 10_000, &mut payment_id); },
886
887                         0x40 => { send_payment(&nodes[0], &nodes[1], chan_a, 1_000, &mut payment_id); },
888                         0x41 => { send_payment(&nodes[1], &nodes[0], chan_a, 1_000, &mut payment_id); },
889                         0x42 => { send_payment(&nodes[1], &nodes[2], chan_b, 1_000, &mut payment_id); },
890                         0x43 => { send_payment(&nodes[2], &nodes[1], chan_b, 1_000, &mut payment_id); },
891                         0x44 => { send_hop_payment(&nodes[0], &nodes[1], chan_a, &nodes[2], chan_b, 1_000, &mut payment_id); },
892                         0x45 => { send_hop_payment(&nodes[2], &nodes[1], chan_b, &nodes[0], chan_a, 1_000, &mut payment_id); },
893
894                         0x48 => { send_payment(&nodes[0], &nodes[1], chan_a, 100, &mut payment_id); },
895                         0x49 => { send_payment(&nodes[1], &nodes[0], chan_a, 100, &mut payment_id); },
896                         0x4a => { send_payment(&nodes[1], &nodes[2], chan_b, 100, &mut payment_id); },
897                         0x4b => { send_payment(&nodes[2], &nodes[1], chan_b, 100, &mut payment_id); },
898                         0x4c => { send_hop_payment(&nodes[0], &nodes[1], chan_a, &nodes[2], chan_b, 100, &mut payment_id); },
899                         0x4d => { send_hop_payment(&nodes[2], &nodes[1], chan_b, &nodes[0], chan_a, 100, &mut payment_id); },
900
901                         0x50 => { send_payment(&nodes[0], &nodes[1], chan_a, 10, &mut payment_id); },
902                         0x51 => { send_payment(&nodes[1], &nodes[0], chan_a, 10, &mut payment_id); },
903                         0x52 => { send_payment(&nodes[1], &nodes[2], chan_b, 10, &mut payment_id); },
904                         0x53 => { send_payment(&nodes[2], &nodes[1], chan_b, 10, &mut payment_id); },
905                         0x54 => { send_hop_payment(&nodes[0], &nodes[1], chan_a, &nodes[2], chan_b, 10, &mut payment_id); },
906                         0x55 => { send_hop_payment(&nodes[2], &nodes[1], chan_b, &nodes[0], chan_a, 10, &mut payment_id); },
907
908                         0x58 => { send_payment(&nodes[0], &nodes[1], chan_a, 1, &mut payment_id); },
909                         0x59 => { send_payment(&nodes[1], &nodes[0], chan_a, 1, &mut payment_id); },
910                         0x5a => { send_payment(&nodes[1], &nodes[2], chan_b, 1, &mut payment_id); },
911                         0x5b => { send_payment(&nodes[2], &nodes[1], chan_b, 1, &mut payment_id); },
912                         0x5c => { send_hop_payment(&nodes[0], &nodes[1], chan_a, &nodes[2], chan_b, 1, &mut payment_id); },
913                         0x5d => { send_hop_payment(&nodes[2], &nodes[1], chan_b, &nodes[0], chan_a, 1, &mut payment_id); },
914
915                         0xff => {
916                                 // Test that no channel is in a stuck state where neither party can send funds even
917                                 // after we resolve all pending events.
918                                 // First make sure there are no pending monitor updates, resetting the error state
919                                 // and calling channel_monitor_updated for each monitor.
920                                 *monitor_a.update_ret.lock().unwrap() = Ok(());
921                                 *monitor_b.update_ret.lock().unwrap() = Ok(());
922                                 *monitor_c.update_ret.lock().unwrap() = Ok(());
923
924                                 if let Some((id, _)) = monitor_a.latest_monitors.lock().unwrap().get(&chan_1_funding) {
925                                         nodes[0].channel_monitor_updated(&chan_1_funding, *id);
926                                 }
927                                 if let Some((id, _)) = monitor_b.latest_monitors.lock().unwrap().get(&chan_1_funding) {
928                                         nodes[1].channel_monitor_updated(&chan_1_funding, *id);
929                                 }
930                                 if let Some((id, _)) = monitor_b.latest_monitors.lock().unwrap().get(&chan_2_funding) {
931                                         nodes[1].channel_monitor_updated(&chan_2_funding, *id);
932                                 }
933                                 if let Some((id, _)) = monitor_c.latest_monitors.lock().unwrap().get(&chan_2_funding) {
934                                         nodes[2].channel_monitor_updated(&chan_2_funding, *id);
935                                 }
936
937                                 // Next, make sure peers are all connected to each other
938                                 if chan_a_disconnected {
939                                         nodes[0].peer_connected(&nodes[1].get_our_node_id(), &Init { features: InitFeatures::empty() });
940                                         nodes[1].peer_connected(&nodes[0].get_our_node_id(), &Init { features: InitFeatures::empty() });
941                                         chan_a_disconnected = false;
942                                 }
943                                 if chan_b_disconnected {
944                                         nodes[1].peer_connected(&nodes[2].get_our_node_id(), &Init { features: InitFeatures::empty() });
945                                         nodes[2].peer_connected(&nodes[1].get_our_node_id(), &Init { features: InitFeatures::empty() });
946                                         chan_b_disconnected = false;
947                                 }
948
949                                 for i in 0..std::usize::MAX {
950                                         if i == 100 { panic!("It may take may iterations to settle the state, but it should not take forever"); }
951                                         // Then, make sure any current forwards make their way to their destination
952                                         if process_msg_events!(0, false) { continue; }
953                                         if process_msg_events!(1, false) { continue; }
954                                         if process_msg_events!(2, false) { continue; }
955                                         // ...making sure any pending PendingHTLCsForwardable events are handled and
956                                         // payments claimed.
957                                         if process_events!(0, false) { continue; }
958                                         if process_events!(1, false) { continue; }
959                                         if process_events!(2, false) { continue; }
960                                         break;
961                                 }
962
963                                 // Finally, make sure that at least one end of each channel can make a substantial payment.
964                                 assert!(
965                                         send_payment(&nodes[0], &nodes[1], chan_a, 10_000_000, &mut payment_id) ||
966                                         send_payment(&nodes[1], &nodes[0], chan_a, 10_000_000, &mut payment_id));
967                                 assert!(
968                                         send_payment(&nodes[1], &nodes[2], chan_b, 10_000_000, &mut payment_id) ||
969                                         send_payment(&nodes[2], &nodes[1], chan_b, 10_000_000, &mut payment_id));
970                         },
971                         _ => test_return!(),
972                 }
973
974                 node_a_ser.0.clear();
975                 nodes[0].write(&mut node_a_ser).unwrap();
976                 monitor_a.should_update_manager.store(false, atomic::Ordering::Relaxed);
977                 node_b_ser.0.clear();
978                 nodes[1].write(&mut node_b_ser).unwrap();
979                 monitor_b.should_update_manager.store(false, atomic::Ordering::Relaxed);
980                 node_c_ser.0.clear();
981                 nodes[2].write(&mut node_c_ser).unwrap();
982                 monitor_c.should_update_manager.store(false, atomic::Ordering::Relaxed);
983         }
984 }
985
986 pub fn chanmon_consistency_test<Out: test_logger::Output>(data: &[u8], out: Out) {
987         do_test(data, out);
988 }
989
990 #[no_mangle]
991 pub extern "C" fn chanmon_consistency_run(data: *const u8, datalen: usize) {
992         do_test(unsafe { std::slice::from_raw_parts(data, datalen) }, test_logger::DevNull{});
993 }