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