Drop various bounds on types passed to `MonitorUpdatingPersister`
[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::constants::genesis_block;
22 use bitcoin::blockdata::transaction::{Transaction, TxOut};
23 use bitcoin::blockdata::script::{Builder, Script};
24 use bitcoin::blockdata::opcodes;
25 use bitcoin::blockdata::locktime::PackedLockTime;
26 use bitcoin::network::constants::Network;
27
28 use bitcoin::hashes::Hash as TraitImport;
29 use bitcoin::hashes::sha256::Hash as Sha256;
30 use bitcoin::hashes::sha256d::Hash as Sha256dHash;
31 use bitcoin::hash_types::{BlockHash, WPubkeyHash};
32
33 use lightning::chain;
34 use lightning::chain::{BestBlock, ChannelMonitorUpdateStatus, chainmonitor, channelmonitor, Confirm, Watch};
35 use lightning::chain::channelmonitor::{ChannelMonitor, MonitorEvent};
36 use lightning::chain::transaction::OutPoint;
37 use lightning::chain::chaininterface::{BroadcasterInterface, ConfirmationTarget, FeeEstimator};
38 use lightning::sign::{KeyMaterial, InMemorySigner, Recipient, EntropySource, NodeSigner, SignerProvider};
39 use lightning::events;
40 use lightning::events::MessageSendEventsProvider;
41 use lightning::ln::{PaymentHash, PaymentPreimage, PaymentSecret};
42 use lightning::ln::channelmanager::{ChainParameters, ChannelDetails, ChannelManager, PaymentSendFailure, ChannelManagerReadArgs, PaymentId, RecipientOnionFields};
43 use lightning::ln::channel::FEE_SPIKE_BUFFER_FEE_INCREASE_MULTIPLE;
44 use lightning::ln::msgs::{self, CommitmentUpdate, ChannelMessageHandler, DecodeError, UpdateAddHTLC, Init};
45 use lightning::ln::script::ShutdownScript;
46 use lightning::ln::functional_test_utils::*;
47 use lightning::offers::invoice::UnsignedBolt12Invoice;
48 use lightning::offers::invoice_request::UnsignedInvoiceRequest;
49 use lightning::util::test_channel_signer::{TestChannelSigner, EnforcementState};
50 use lightning::util::errors::APIError;
51 use lightning::util::logger::Logger;
52 use lightning::util::config::UserConfig;
53 use lightning::util::ser::{Readable, ReadableArgs, Writeable, Writer};
54 use lightning::routing::router::{InFlightHtlcs, Path, Route, RouteHop, RouteParameters, Router};
55
56 use crate::utils::test_logger::{self, Output};
57 use crate::utils::test_persister::TestPersister;
58
59 use bitcoin::secp256k1::{Message, PublicKey, SecretKey, Scalar, Secp256k1};
60 use bitcoin::secp256k1::ecdh::SharedSecret;
61 use bitcoin::secp256k1::ecdsa::{RecoverableSignature, Signature};
62 use bitcoin::secp256k1::schnorr;
63
64 use std::mem;
65 use std::cmp::{self, Ordering};
66 use hashbrown::{HashSet, hash_map, HashMap};
67 use std::sync::{Arc,Mutex};
68 use std::sync::atomic;
69 use std::io::Cursor;
70 use bitcoin::bech32::u5;
71
72 const MAX_FEE: u32 = 10_000;
73 struct FuzzEstimator {
74         ret_val: atomic::AtomicU32,
75 }
76 impl FeeEstimator for FuzzEstimator {
77         fn get_est_sat_per_1000_weight(&self, conf_target: ConfirmationTarget) -> u32 {
78                 // We force-close channels if our counterparty sends us a feerate which is a small multiple
79                 // of our HighPriority fee estimate or smaller than our Background fee estimate. Thus, we
80                 // always return a HighPriority feerate here which is >= the maximum Normal feerate and a
81                 // Background feerate which is <= the minimum Normal feerate.
82                 match conf_target {
83                         ConfirmationTarget::HighPriority => MAX_FEE,
84                         ConfirmationTarget::Background|ConfirmationTarget::MempoolMinimum => 253,
85                         ConfirmationTarget::Normal => cmp::min(self.ret_val.load(atomic::Ordering::Acquire), MAX_FEE),
86                 }
87         }
88 }
89
90 struct FuzzRouter {}
91
92 impl Router for FuzzRouter {
93         fn find_route(
94                 &self, _payer: &PublicKey, _params: &RouteParameters, _first_hops: Option<&[&ChannelDetails]>,
95                 _inflight_htlcs: InFlightHtlcs
96         ) -> Result<Route, msgs::LightningError> {
97                 Err(msgs::LightningError {
98                         err: String::from("Not implemented"),
99                         action: msgs::ErrorAction::IgnoreError
100                 })
101         }
102 }
103
104 pub struct TestBroadcaster {}
105 impl BroadcasterInterface for TestBroadcaster {
106         fn broadcast_transactions(&self, _txs: &[&Transaction]) { }
107 }
108
109 pub struct VecWriter(pub Vec<u8>);
110 impl Writer for VecWriter {
111         fn write_all(&mut self, buf: &[u8]) -> Result<(), ::std::io::Error> {
112                 self.0.extend_from_slice(buf);
113                 Ok(())
114         }
115 }
116
117 struct TestChainMonitor {
118         pub logger: Arc<dyn Logger>,
119         pub keys: Arc<KeyProvider>,
120         pub persister: Arc<TestPersister>,
121         pub chain_monitor: Arc<chainmonitor::ChainMonitor<TestChannelSigner, Arc<dyn chain::Filter>, Arc<TestBroadcaster>, Arc<FuzzEstimator>, Arc<dyn Logger>, Arc<TestPersister>>>,
122         // If we reload a node with an old copy of ChannelMonitors, the ChannelManager deserialization
123         // logic will automatically force-close our channels for us (as we don't have an up-to-date
124         // monitor implying we are not able to punish misbehaving counterparties). Because this test
125         // "fails" if we ever force-close a channel, we avoid doing so, always saving the latest
126         // fully-serialized monitor state here, as well as the corresponding update_id.
127         pub latest_monitors: Mutex<HashMap<OutPoint, (u64, Vec<u8>)>>,
128 }
129 impl TestChainMonitor {
130         pub fn new(broadcaster: Arc<TestBroadcaster>, logger: Arc<dyn Logger>, feeest: Arc<FuzzEstimator>, persister: Arc<TestPersister>, keys: Arc<KeyProvider>) -> Self {
131                 Self {
132                         chain_monitor: Arc::new(chainmonitor::ChainMonitor::new(None, broadcaster, logger.clone(), feeest, Arc::clone(&persister))),
133                         logger,
134                         keys,
135                         persister,
136                         latest_monitors: Mutex::new(HashMap::new()),
137                 }
138         }
139 }
140 impl chain::Watch<TestChannelSigner> for TestChainMonitor {
141         fn watch_channel(&self, funding_txo: OutPoint, monitor: channelmonitor::ChannelMonitor<TestChannelSigner>) -> Result<chain::ChannelMonitorUpdateStatus, ()> {
142                 let mut ser = VecWriter(Vec::new());
143                 monitor.write(&mut ser).unwrap();
144                 if let Some(_) = self.latest_monitors.lock().unwrap().insert(funding_txo, (monitor.get_latest_update_id(), ser.0)) {
145                         panic!("Already had monitor pre-watch_channel");
146                 }
147                 self.chain_monitor.watch_channel(funding_txo, monitor)
148         }
149
150         fn update_channel(&self, funding_txo: OutPoint, update: &channelmonitor::ChannelMonitorUpdate) -> chain::ChannelMonitorUpdateStatus {
151                 let mut map_lock = self.latest_monitors.lock().unwrap();
152                 let mut map_entry = match map_lock.entry(funding_txo) {
153                         hash_map::Entry::Occupied(entry) => entry,
154                         hash_map::Entry::Vacant(_) => panic!("Didn't have monitor on update call"),
155                 };
156                 let deserialized_monitor = <(BlockHash, channelmonitor::ChannelMonitor<TestChannelSigner>)>::
157                         read(&mut Cursor::new(&map_entry.get().1), (&*self.keys, &*self.keys)).unwrap().1;
158                 deserialized_monitor.update_monitor(update, &&TestBroadcaster{}, &&FuzzEstimator { ret_val: atomic::AtomicU32::new(253) }, &self.logger).unwrap();
159                 let mut ser = VecWriter(Vec::new());
160                 deserialized_monitor.write(&mut ser).unwrap();
161                 map_entry.insert((update.update_id, ser.0));
162                 self.chain_monitor.update_channel(funding_txo, update)
163         }
164
165         fn release_pending_monitor_events(&self) -> Vec<(OutPoint, Vec<MonitorEvent>, Option<PublicKey>)> {
166                 return self.chain_monitor.release_pending_monitor_events();
167         }
168 }
169
170 struct KeyProvider {
171         node_secret: SecretKey,
172         rand_bytes_id: atomic::AtomicU32,
173         enforcement_states: Mutex<HashMap<[u8;32], Arc<Mutex<EnforcementState>>>>,
174 }
175
176 impl EntropySource for KeyProvider {
177         fn get_secure_random_bytes(&self) -> [u8; 32] {
178                 let id = self.rand_bytes_id.fetch_add(1, atomic::Ordering::Relaxed);
179                 let mut res = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 11, self.node_secret[31]];
180                 res[30-4..30].copy_from_slice(&id.to_le_bytes());
181                 res
182         }
183 }
184
185 impl NodeSigner for KeyProvider {
186         fn get_node_id(&self, recipient: Recipient) -> Result<PublicKey, ()> {
187                 let node_secret = match recipient {
188                         Recipient::Node => Ok(&self.node_secret),
189                         Recipient::PhantomNode => Err(())
190                 }?;
191                 Ok(PublicKey::from_secret_key(&Secp256k1::signing_only(), node_secret))
192         }
193
194         fn ecdh(&self, recipient: Recipient, other_key: &PublicKey, tweak: Option<&Scalar>) -> Result<SharedSecret, ()> {
195                 let mut node_secret = match recipient {
196                         Recipient::Node => Ok(self.node_secret.clone()),
197                         Recipient::PhantomNode => Err(())
198                 }?;
199                 if let Some(tweak) = tweak {
200                         node_secret = node_secret.mul_tweak(tweak).map_err(|_| ())?;
201                 }
202                 Ok(SharedSecret::new(other_key, &node_secret))
203         }
204
205         fn get_inbound_payment_key_material(&self) -> KeyMaterial {
206                 KeyMaterial([0, 0, 0, 0, 0, 0, 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_secret[31]])
207         }
208
209         fn sign_invoice(&self, _hrp_bytes: &[u8], _invoice_data: &[u5], _recipient: Recipient) -> Result<RecoverableSignature, ()> {
210                 unreachable!()
211         }
212
213         fn sign_bolt12_invoice_request(
214                 &self, _invoice_request: &UnsignedInvoiceRequest
215         ) -> Result<schnorr::Signature, ()> {
216                 unreachable!()
217         }
218
219         fn sign_bolt12_invoice(
220                 &self, _invoice: &UnsignedBolt12Invoice,
221         ) -> Result<schnorr::Signature, ()> {
222                 unreachable!()
223         }
224
225         fn sign_gossip_message(&self, msg: lightning::ln::msgs::UnsignedGossipMessage) -> Result<Signature, ()> {
226                 let msg_hash = Message::from_slice(&Sha256dHash::hash(&msg.encode()[..])[..]).map_err(|_| ())?;
227                 let secp_ctx = Secp256k1::signing_only();
228                 Ok(secp_ctx.sign_ecdsa(&msg_hash, &self.node_secret))
229         }
230 }
231
232 impl SignerProvider for KeyProvider {
233         type Signer = TestChannelSigner;
234
235         fn generate_channel_keys_id(&self, _inbound: bool, _channel_value_satoshis: u64, _user_channel_id: u128) -> [u8; 32] {
236                 let id = self.rand_bytes_id.fetch_add(1, atomic::Ordering::Relaxed) as u8;
237                 [id; 32]
238         }
239
240         fn derive_channel_signer(&self, channel_value_satoshis: u64, channel_keys_id: [u8; 32]) -> Self::Signer {
241                 let secp_ctx = Secp256k1::signing_only();
242                 let id = channel_keys_id[0];
243                 let keys = InMemorySigner::new(
244                         &secp_ctx,
245                         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_secret[31]]).unwrap(),
246                         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_secret[31]]).unwrap(),
247                         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_secret[31]]).unwrap(),
248                         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_secret[31]]).unwrap(),
249                         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_secret[31]]).unwrap(),
250                         [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_secret[31]],
251                         channel_value_satoshis,
252                         channel_keys_id,
253                         channel_keys_id,
254                 );
255                 let revoked_commitment = self.make_enforcement_state_cell(keys.commitment_seed);
256                 TestChannelSigner::new_with_revoked(keys, revoked_commitment, false)
257         }
258
259         fn read_chan_signer(&self, buffer: &[u8]) -> Result<Self::Signer, DecodeError> {
260                 let mut reader = std::io::Cursor::new(buffer);
261
262                 let inner: InMemorySigner = ReadableArgs::read(&mut reader, self)?;
263                 let state = self.make_enforcement_state_cell(inner.commitment_seed);
264
265                 Ok(TestChannelSigner {
266                         inner,
267                         state,
268                         disable_revocation_policy_check: false,
269                 })
270         }
271
272         fn get_destination_script(&self) -> Result<Script, ()> {
273                 let secp_ctx = Secp256k1::signing_only();
274                 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_secret[31]]).unwrap();
275                 let our_channel_monitor_claim_key_hash = WPubkeyHash::hash(&PublicKey::from_secret_key(&secp_ctx, &channel_monitor_claim_key).serialize());
276                 Ok(Builder::new().push_opcode(opcodes::all::OP_PUSHBYTES_0).push_slice(&our_channel_monitor_claim_key_hash[..]).into_script())
277         }
278
279         fn get_shutdown_scriptpubkey(&self) -> Result<ShutdownScript, ()> {
280                 let secp_ctx = Secp256k1::signing_only();
281                 let secret_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, 3, self.node_secret[31]]).unwrap();
282                 let pubkey_hash = WPubkeyHash::hash(&PublicKey::from_secret_key(&secp_ctx, &secret_key).serialize());
283                 Ok(ShutdownScript::new_p2wpkh(&pubkey_hash))
284         }
285 }
286
287 impl KeyProvider {
288         fn make_enforcement_state_cell(&self, commitment_seed: [u8; 32]) -> Arc<Mutex<EnforcementState>> {
289                 let mut revoked_commitments = self.enforcement_states.lock().unwrap();
290                 if !revoked_commitments.contains_key(&commitment_seed) {
291                         revoked_commitments.insert(commitment_seed, Arc::new(Mutex::new(EnforcementState::new())));
292                 }
293                 let cell = revoked_commitments.get(&commitment_seed).unwrap();
294                 Arc::clone(cell)
295         }
296 }
297
298 #[inline]
299 fn check_api_err(api_err: APIError, sendable_bounds_violated: bool) {
300         match api_err {
301                 APIError::APIMisuseError { .. } => panic!("We can't misuse the API"),
302                 APIError::FeeRateTooHigh { .. } => panic!("We can't send too much fee?"),
303                 APIError::InvalidRoute { .. } => panic!("Our routes should work"),
304                 APIError::ChannelUnavailable { err } => {
305                         // Test the error against a list of errors we can hit, and reject
306                         // all others. If you hit this panic, the list of acceptable errors
307                         // is probably just stale and you should add new messages here.
308                         match err.as_str() {
309                                 "Peer for first hop currently disconnected" => {},
310                                 _ if err.starts_with("Cannot send less than our next-HTLC minimum - ") => {},
311                                 _ if err.starts_with("Cannot send more than our next-HTLC maximum - ") => {},
312                                 _ => panic!("{}", err),
313                         }
314                         assert!(sendable_bounds_violated);
315                 },
316                 APIError::MonitorUpdateInProgress => {
317                         // We can (obviously) temp-fail a monitor update
318                 },
319                 APIError::IncompatibleShutdownScript { .. } => panic!("Cannot send an incompatible shutdown script"),
320         }
321 }
322 #[inline]
323 fn check_payment_err(send_err: PaymentSendFailure, sendable_bounds_violated: bool) {
324         match send_err {
325                 PaymentSendFailure::ParameterError(api_err) => check_api_err(api_err, sendable_bounds_violated),
326                 PaymentSendFailure::PathParameterError(per_path_results) => {
327                         for res in per_path_results { if let Err(api_err) = res { check_api_err(api_err, sendable_bounds_violated); } }
328                 },
329                 PaymentSendFailure::AllFailedResendSafe(per_path_results) => {
330                         for api_err in per_path_results { check_api_err(api_err, sendable_bounds_violated); }
331                 },
332                 PaymentSendFailure::PartialFailure { results, .. } => {
333                         for res in results { if let Err(api_err) = res { check_api_err(api_err, sendable_bounds_violated); } }
334                 },
335                 PaymentSendFailure::DuplicatePayment => panic!(),
336         }
337 }
338
339 type ChanMan<'a> = ChannelManager<Arc<TestChainMonitor>, Arc<TestBroadcaster>, Arc<KeyProvider>, Arc<KeyProvider>, Arc<KeyProvider>, Arc<FuzzEstimator>, &'a FuzzRouter, Arc<dyn Logger>>;
340
341 #[inline]
342 fn get_payment_secret_hash(dest: &ChanMan, payment_id: &mut u8) -> Option<(PaymentSecret, PaymentHash)> {
343         let mut payment_hash;
344         for _ in 0..256 {
345                 payment_hash = PaymentHash(Sha256::hash(&[*payment_id; 1]).into_inner());
346                 if let Ok(payment_secret) = dest.create_inbound_payment_for_hash(payment_hash, None, 3600, None) {
347                         return Some((payment_secret, payment_hash));
348                 }
349                 *payment_id = payment_id.wrapping_add(1);
350         }
351         None
352 }
353
354 #[inline]
355 fn send_payment(source: &ChanMan, dest: &ChanMan, dest_chan_id: u64, amt: u64, payment_id: &mut u8, payment_idx: &mut u64) -> bool {
356         let (payment_secret, payment_hash) =
357                 if let Some((secret, hash)) = get_payment_secret_hash(dest, payment_id) { (secret, hash) } else { return true; };
358         let mut payment_id = [0; 32];
359         payment_id[0..8].copy_from_slice(&payment_idx.to_ne_bytes());
360         *payment_idx += 1;
361         let (min_value_sendable, max_value_sendable) = source.list_usable_channels()
362                 .iter().find(|chan| chan.short_channel_id == Some(dest_chan_id))
363                 .map(|chan|
364                         (chan.next_outbound_htlc_minimum_msat, chan.next_outbound_htlc_limit_msat))
365                 .unwrap_or((0, 0));
366         if let Err(err) = source.send_payment_with_route(&Route {
367                 paths: vec![Path { hops: vec![RouteHop {
368                         pubkey: dest.get_our_node_id(),
369                         node_features: dest.node_features(),
370                         short_channel_id: dest_chan_id,
371                         channel_features: dest.channel_features(),
372                         fee_msat: amt,
373                         cltv_expiry_delta: 200,
374                         maybe_announced_channel: true,
375                 }], blinded_tail: None }],
376                 route_params: None,
377         }, payment_hash, RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_id)) {
378                 check_payment_err(err, amt > max_value_sendable || amt < min_value_sendable);
379                 false
380         } else {
381                 // Note that while the max is a strict upper-bound, we can occasionally send substantially
382                 // below the minimum, with some gap which is unusable immediately below the minimum. Thus,
383                 // we don't check against min_value_sendable here.
384                 assert!(amt <= max_value_sendable);
385                 true
386         }
387 }
388 #[inline]
389 fn send_hop_payment(source: &ChanMan, middle: &ChanMan, middle_chan_id: u64, dest: &ChanMan, dest_chan_id: u64, amt: u64, payment_id: &mut u8, payment_idx: &mut u64) -> bool {
390         let (payment_secret, payment_hash) =
391                 if let Some((secret, hash)) = get_payment_secret_hash(dest, payment_id) { (secret, hash) } else { return true; };
392         let mut payment_id = [0; 32];
393         payment_id[0..8].copy_from_slice(&payment_idx.to_ne_bytes());
394         *payment_idx += 1;
395         let (min_value_sendable, max_value_sendable) = source.list_usable_channels()
396                 .iter().find(|chan| chan.short_channel_id == Some(middle_chan_id))
397                 .map(|chan|
398                         (chan.next_outbound_htlc_minimum_msat, chan.next_outbound_htlc_limit_msat))
399                 .unwrap_or((0, 0));
400         let first_hop_fee = 50_000;
401         if let Err(err) = source.send_payment_with_route(&Route {
402                 paths: vec![Path { hops: vec![RouteHop {
403                         pubkey: middle.get_our_node_id(),
404                         node_features: middle.node_features(),
405                         short_channel_id: middle_chan_id,
406                         channel_features: middle.channel_features(),
407                         fee_msat: first_hop_fee,
408                         cltv_expiry_delta: 100,
409                         maybe_announced_channel: true,
410                 }, RouteHop {
411                         pubkey: dest.get_our_node_id(),
412                         node_features: dest.node_features(),
413                         short_channel_id: dest_chan_id,
414                         channel_features: dest.channel_features(),
415                         fee_msat: amt,
416                         cltv_expiry_delta: 200,
417                         maybe_announced_channel: true,
418                 }], blinded_tail: None }],
419                 route_params: None,
420         }, payment_hash, RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_id)) {
421                 let sent_amt = amt + first_hop_fee;
422                 check_payment_err(err, sent_amt < min_value_sendable || sent_amt > max_value_sendable);
423                 false
424         } else {
425                 // Note that while the max is a strict upper-bound, we can occasionally send substantially
426                 // below the minimum, with some gap which is unusable immediately below the minimum. Thus,
427                 // we don't check against min_value_sendable here.
428                 assert!(amt + first_hop_fee <= max_value_sendable);
429                 true
430         }
431 }
432
433 #[inline]
434 pub fn do_test<Out: Output>(data: &[u8], underlying_out: Out) {
435         let out = SearchingOutput::new(underlying_out);
436         let broadcast = Arc::new(TestBroadcaster{});
437         let router = FuzzRouter {};
438
439         macro_rules! make_node {
440                 ($node_id: expr, $fee_estimator: expr) => { {
441                         let logger: Arc<dyn Logger> = Arc::new(test_logger::TestLogger::new($node_id.to_string(), out.clone()));
442                         let node_secret = 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, $node_id]).unwrap();
443                         let keys_manager = Arc::new(KeyProvider { node_secret, rand_bytes_id: atomic::AtomicU32::new(0), enforcement_states: Mutex::new(HashMap::new()) });
444                         let monitor = Arc::new(TestChainMonitor::new(broadcast.clone(), logger.clone(), $fee_estimator.clone(),
445                                 Arc::new(TestPersister {
446                                         update_ret: Mutex::new(ChannelMonitorUpdateStatus::Completed)
447                                 }), Arc::clone(&keys_manager)));
448
449                         let mut config = UserConfig::default();
450                         config.channel_config.forwarding_fee_proportional_millionths = 0;
451                         config.channel_handshake_config.announced_channel = true;
452                         let network = Network::Bitcoin;
453                         let best_block_timestamp = genesis_block(network).header.time;
454                         let params = ChainParameters {
455                                 network,
456                                 best_block: BestBlock::from_network(network),
457                         };
458                         (ChannelManager::new($fee_estimator.clone(), monitor.clone(), broadcast.clone(), &router, Arc::clone(&logger), keys_manager.clone(), keys_manager.clone(), keys_manager.clone(), config, params, best_block_timestamp),
459                         monitor, keys_manager)
460                 } }
461         }
462
463         macro_rules! reload_node {
464                 ($ser: expr, $node_id: expr, $old_monitors: expr, $keys_manager: expr, $fee_estimator: expr) => { {
465                     let keys_manager = Arc::clone(& $keys_manager);
466                         let logger: Arc<dyn Logger> = Arc::new(test_logger::TestLogger::new($node_id.to_string(), out.clone()));
467                         let chain_monitor = Arc::new(TestChainMonitor::new(broadcast.clone(), logger.clone(), $fee_estimator.clone(),
468                                 Arc::new(TestPersister {
469                                         update_ret: Mutex::new(ChannelMonitorUpdateStatus::Completed)
470                                 }), Arc::clone(& $keys_manager)));
471
472                         let mut config = UserConfig::default();
473                         config.channel_config.forwarding_fee_proportional_millionths = 0;
474                         config.channel_handshake_config.announced_channel = true;
475
476                         let mut monitors = HashMap::new();
477                         let mut old_monitors = $old_monitors.latest_monitors.lock().unwrap();
478                         for (outpoint, (update_id, monitor_ser)) in old_monitors.drain() {
479                                 monitors.insert(outpoint, <(BlockHash, ChannelMonitor<TestChannelSigner>)>::read(&mut Cursor::new(&monitor_ser), (&*$keys_manager, &*$keys_manager)).expect("Failed to read monitor").1);
480                                 chain_monitor.latest_monitors.lock().unwrap().insert(outpoint, (update_id, monitor_ser));
481                         }
482                         let mut monitor_refs = HashMap::new();
483                         for (outpoint, monitor) in monitors.iter_mut() {
484                                 monitor_refs.insert(*outpoint, monitor);
485                         }
486
487                         let read_args = ChannelManagerReadArgs {
488                                 entropy_source: keys_manager.clone(),
489                                 node_signer: keys_manager.clone(),
490                                 signer_provider: keys_manager.clone(),
491                                 fee_estimator: $fee_estimator.clone(),
492                                 chain_monitor: chain_monitor.clone(),
493                                 tx_broadcaster: broadcast.clone(),
494                                 router: &router,
495                                 logger,
496                                 default_config: config,
497                                 channel_monitors: monitor_refs,
498                         };
499
500                         let res = (<(BlockHash, ChanMan)>::read(&mut Cursor::new(&$ser.0), read_args).expect("Failed to read manager").1, chain_monitor.clone());
501                         for (funding_txo, mon) in monitors.drain() {
502                                 assert_eq!(chain_monitor.chain_monitor.watch_channel(funding_txo, mon),
503                                         Ok(ChannelMonitorUpdateStatus::Completed));
504                         }
505                         res
506                 } }
507         }
508
509         let mut channel_txn = Vec::new();
510         macro_rules! make_channel {
511                 ($source: expr, $dest: expr, $chan_id: expr) => { {
512                         $source.peer_connected(&$dest.get_our_node_id(), &Init {
513                                 features: $dest.init_features(), networks: None, remote_network_address: None
514                         }, true).unwrap();
515                         $dest.peer_connected(&$source.get_our_node_id(), &Init {
516                                 features: $source.init_features(), networks: None, remote_network_address: None
517                         }, false).unwrap();
518
519                         $source.create_channel($dest.get_our_node_id(), 100_000, 42, 0, None).unwrap();
520                         let open_channel = {
521                                 let events = $source.get_and_clear_pending_msg_events();
522                                 assert_eq!(events.len(), 1);
523                                 if let events::MessageSendEvent::SendOpenChannel { ref msg, .. } = events[0] {
524                                         msg.clone()
525                                 } else { panic!("Wrong event type"); }
526                         };
527
528                         $dest.handle_open_channel(&$source.get_our_node_id(), &open_channel);
529                         let accept_channel = {
530                                 let events = $dest.get_and_clear_pending_msg_events();
531                                 assert_eq!(events.len(), 1);
532                                 if let events::MessageSendEvent::SendAcceptChannel { ref msg, .. } = events[0] {
533                                         msg.clone()
534                                 } else { panic!("Wrong event type"); }
535                         };
536
537                         $source.handle_accept_channel(&$dest.get_our_node_id(), &accept_channel);
538                         let funding_output;
539                         {
540                                 let events = $source.get_and_clear_pending_events();
541                                 assert_eq!(events.len(), 1);
542                                 if let events::Event::FundingGenerationReady { ref temporary_channel_id, ref channel_value_satoshis, ref output_script, .. } = events[0] {
543                                         let tx = Transaction { version: $chan_id, lock_time: PackedLockTime::ZERO, input: Vec::new(), output: vec![TxOut {
544                                                 value: *channel_value_satoshis, script_pubkey: output_script.clone(),
545                                         }]};
546                                         funding_output = OutPoint { txid: tx.txid(), index: 0 };
547                                         $source.funding_transaction_generated(&temporary_channel_id, &$dest.get_our_node_id(), tx.clone()).unwrap();
548                                         channel_txn.push(tx);
549                                 } else { panic!("Wrong event type"); }
550                         }
551
552                         let funding_created = {
553                                 let events = $source.get_and_clear_pending_msg_events();
554                                 assert_eq!(events.len(), 1);
555                                 if let events::MessageSendEvent::SendFundingCreated { ref msg, .. } = events[0] {
556                                         msg.clone()
557                                 } else { panic!("Wrong event type"); }
558                         };
559                         $dest.handle_funding_created(&$source.get_our_node_id(), &funding_created);
560
561                         let funding_signed = {
562                                 let events = $dest.get_and_clear_pending_msg_events();
563                                 assert_eq!(events.len(), 1);
564                                 if let events::MessageSendEvent::SendFundingSigned { ref msg, .. } = events[0] {
565                                         msg.clone()
566                                 } else { panic!("Wrong event type"); }
567                         };
568                         let events = $dest.get_and_clear_pending_events();
569                         assert_eq!(events.len(), 1);
570                         if let events::Event::ChannelPending{ ref counterparty_node_id, .. } = events[0] {
571                                 assert_eq!(counterparty_node_id, &$source.get_our_node_id());
572                         } else { panic!("Wrong event type"); }
573
574                         $source.handle_funding_signed(&$dest.get_our_node_id(), &funding_signed);
575                         let events = $source.get_and_clear_pending_events();
576                         assert_eq!(events.len(), 1);
577                         if let events::Event::ChannelPending{ ref counterparty_node_id, .. } = events[0] {
578                                 assert_eq!(counterparty_node_id, &$dest.get_our_node_id());
579                         } else { panic!("Wrong event type"); }
580
581                         funding_output
582                 } }
583         }
584
585         macro_rules! confirm_txn {
586                 ($node: expr) => { {
587                         let chain_hash = genesis_block(Network::Bitcoin).block_hash();
588                         let mut header = create_dummy_header(chain_hash, 42);
589                         let txdata: Vec<_> = channel_txn.iter().enumerate().map(|(i, tx)| (i + 1, tx)).collect();
590                         $node.transactions_confirmed(&header, &txdata, 1);
591                         for _ in 2..100 {
592                                 header = create_dummy_header(header.block_hash(), 42);
593                         }
594                         $node.best_block_updated(&header, 99);
595                 } }
596         }
597
598         macro_rules! lock_fundings {
599                 ($nodes: expr) => { {
600                         let mut node_events = Vec::new();
601                         for node in $nodes.iter() {
602                                 node_events.push(node.get_and_clear_pending_msg_events());
603                         }
604                         for (idx, node_event) in node_events.iter().enumerate() {
605                                 for event in node_event {
606                                         if let events::MessageSendEvent::SendChannelReady { ref node_id, ref msg } = event {
607                                                 for node in $nodes.iter() {
608                                                         if node.get_our_node_id() == *node_id {
609                                                                 node.handle_channel_ready(&$nodes[idx].get_our_node_id(), msg);
610                                                         }
611                                                 }
612                                         } else { panic!("Wrong event type"); }
613                                 }
614                         }
615
616                         for node in $nodes.iter() {
617                                 let events = node.get_and_clear_pending_msg_events();
618                                 for event in events {
619                                         if let events::MessageSendEvent::SendAnnouncementSignatures { .. } = event {
620                                         } else { panic!("Wrong event type"); }
621                                 }
622                         }
623                 } }
624         }
625
626         let fee_est_a = Arc::new(FuzzEstimator { ret_val: atomic::AtomicU32::new(253) });
627         let mut last_htlc_clear_fee_a =  253;
628         let fee_est_b = Arc::new(FuzzEstimator { ret_val: atomic::AtomicU32::new(253) });
629         let mut last_htlc_clear_fee_b =  253;
630         let fee_est_c = Arc::new(FuzzEstimator { ret_val: atomic::AtomicU32::new(253) });
631         let mut last_htlc_clear_fee_c =  253;
632
633         // 3 nodes is enough to hit all the possible cases, notably unknown-source-unknown-dest
634         // forwarding.
635         let (node_a, mut monitor_a, keys_manager_a) = make_node!(0, fee_est_a);
636         let (node_b, mut monitor_b, keys_manager_b) = make_node!(1, fee_est_b);
637         let (node_c, mut monitor_c, keys_manager_c) = make_node!(2, fee_est_c);
638
639         let mut nodes = [node_a, node_b, node_c];
640
641         let chan_1_funding = make_channel!(nodes[0], nodes[1], 0);
642         let chan_2_funding = make_channel!(nodes[1], nodes[2], 1);
643
644         for node in nodes.iter() {
645                 confirm_txn!(node);
646         }
647
648         lock_fundings!(nodes);
649
650         let chan_a = nodes[0].list_usable_channels()[0].short_channel_id.unwrap();
651         let chan_b = nodes[2].list_usable_channels()[0].short_channel_id.unwrap();
652
653         let mut payment_id: u8 = 0;
654         let mut payment_idx: u64 = 0;
655
656         let mut chan_a_disconnected = false;
657         let mut chan_b_disconnected = false;
658         let mut ab_events = Vec::new();
659         let mut ba_events = Vec::new();
660         let mut bc_events = Vec::new();
661         let mut cb_events = Vec::new();
662
663         let mut node_a_ser = VecWriter(Vec::new());
664         nodes[0].write(&mut node_a_ser).unwrap();
665         let mut node_b_ser = VecWriter(Vec::new());
666         nodes[1].write(&mut node_b_ser).unwrap();
667         let mut node_c_ser = VecWriter(Vec::new());
668         nodes[2].write(&mut node_c_ser).unwrap();
669
670         macro_rules! test_return {
671                 () => { {
672                         assert_eq!(nodes[0].list_channels().len(), 1);
673                         assert_eq!(nodes[1].list_channels().len(), 2);
674                         assert_eq!(nodes[2].list_channels().len(), 1);
675                         return;
676                 } }
677         }
678
679         let mut read_pos = 0;
680         macro_rules! get_slice {
681                 ($len: expr) => {
682                         {
683                                 let slice_len = $len as usize;
684                                 if data.len() < read_pos + slice_len {
685                                         test_return!();
686                                 }
687                                 read_pos += slice_len;
688                                 &data[read_pos - slice_len..read_pos]
689                         }
690                 }
691         }
692
693         loop {
694                 // Push any events from Node B onto ba_events and bc_events
695                 macro_rules! push_excess_b_events {
696                         ($excess_events: expr, $expect_drop_node: expr) => { {
697                                 let a_id = nodes[0].get_our_node_id();
698                                 let expect_drop_node: Option<usize> = $expect_drop_node;
699                                 let expect_drop_id = if let Some(id) = expect_drop_node { Some(nodes[id].get_our_node_id()) } else { None };
700                                 for event in $excess_events {
701                                         let push_a = match event {
702                                                 events::MessageSendEvent::UpdateHTLCs { ref node_id, .. } => {
703                                                         if Some(*node_id) == expect_drop_id { panic!("peer_disconnected should drop msgs bound for the disconnected peer"); }
704                                                         *node_id == a_id
705                                                 },
706                                                 events::MessageSendEvent::SendRevokeAndACK { ref node_id, .. } => {
707                                                         if Some(*node_id) == expect_drop_id { panic!("peer_disconnected should drop msgs bound for the disconnected peer"); }
708                                                         *node_id == a_id
709                                                 },
710                                                 events::MessageSendEvent::SendChannelReestablish { ref node_id, .. } => {
711                                                         if Some(*node_id) == expect_drop_id { panic!("peer_disconnected should drop msgs bound for the disconnected peer"); }
712                                                         *node_id == a_id
713                                                 },
714                                                 events::MessageSendEvent::SendChannelReady { .. } => continue,
715                                                 events::MessageSendEvent::SendAnnouncementSignatures { .. } => continue,
716                                                 events::MessageSendEvent::SendChannelUpdate { ref node_id, ref msg } => {
717                                                         assert_eq!(msg.contents.flags & 2, 0); // The disable bit must never be set!
718                                                         if Some(*node_id) == expect_drop_id { panic!("peer_disconnected should drop msgs bound for the disconnected peer"); }
719                                                         *node_id == a_id
720                                                 },
721                                                 _ => panic!("Unhandled message event {:?}", event),
722                                         };
723                                         if push_a { ba_events.push(event); } else { bc_events.push(event); }
724                                 }
725                         } }
726                 }
727
728                 // While delivering messages, we select across three possible message selection processes
729                 // to ensure we get as much coverage as possible. See the individual enum variants for more
730                 // details.
731                 #[derive(PartialEq)]
732                 enum ProcessMessages {
733                         /// Deliver all available messages, including fetching any new messages from
734                         /// `get_and_clear_pending_msg_events()` (which may have side effects).
735                         AllMessages,
736                         /// Call `get_and_clear_pending_msg_events()` first, and then deliver up to one
737                         /// message (which may already be queued).
738                         OneMessage,
739                         /// Deliver up to one already-queued message. This avoids any potential side-effects
740                         /// of `get_and_clear_pending_msg_events()` (eg freeing the HTLC holding cell), which
741                         /// provides potentially more coverage.
742                         OnePendingMessage,
743                 }
744
745                 macro_rules! process_msg_events {
746                         ($node: expr, $corrupt_forward: expr, $limit_events: expr) => { {
747                                 let mut events = if $node == 1 {
748                                         let mut new_events = Vec::new();
749                                         mem::swap(&mut new_events, &mut ba_events);
750                                         new_events.extend_from_slice(&bc_events[..]);
751                                         bc_events.clear();
752                                         new_events
753                                 } else if $node == 0 {
754                                         let mut new_events = Vec::new();
755                                         mem::swap(&mut new_events, &mut ab_events);
756                                         new_events
757                                 } else {
758                                         let mut new_events = Vec::new();
759                                         mem::swap(&mut new_events, &mut cb_events);
760                                         new_events
761                                 };
762                                 let mut new_events = Vec::new();
763                                 if $limit_events != ProcessMessages::OnePendingMessage {
764                                         new_events = nodes[$node].get_and_clear_pending_msg_events();
765                                 }
766                                 let mut had_events = false;
767                                 let mut events_iter = events.drain(..).chain(new_events.drain(..));
768                                 let mut extra_ev = None;
769                                 for event in &mut events_iter {
770                                         had_events = true;
771                                         match event {
772                                                 events::MessageSendEvent::UpdateHTLCs { node_id, updates: CommitmentUpdate { update_add_htlcs, update_fail_htlcs, update_fulfill_htlcs, update_fail_malformed_htlcs, update_fee, commitment_signed } } => {
773                                                         for (idx, dest) in nodes.iter().enumerate() {
774                                                                 if dest.get_our_node_id() == node_id {
775                                                                         for update_add in update_add_htlcs.iter() {
776                                                                                 out.locked_write(format!("Delivering update_add_htlc to node {}.\n", idx).as_bytes());
777                                                                                 if !$corrupt_forward {
778                                                                                         dest.handle_update_add_htlc(&nodes[$node].get_our_node_id(), update_add);
779                                                                                 } else {
780                                                                                         // Corrupt the update_add_htlc message so that its HMAC
781                                                                                         // check will fail and we generate a
782                                                                                         // update_fail_malformed_htlc instead of an
783                                                                                         // update_fail_htlc as we do when we reject a payment.
784                                                                                         let mut msg_ser = update_add.encode();
785                                                                                         msg_ser[1000] ^= 0xff;
786                                                                                         let new_msg = UpdateAddHTLC::read(&mut Cursor::new(&msg_ser)).unwrap();
787                                                                                         dest.handle_update_add_htlc(&nodes[$node].get_our_node_id(), &new_msg);
788                                                                                 }
789                                                                         }
790                                                                         for update_fulfill in update_fulfill_htlcs.iter() {
791                                                                                 out.locked_write(format!("Delivering update_fulfill_htlc to node {}.\n", idx).as_bytes());
792                                                                                 dest.handle_update_fulfill_htlc(&nodes[$node].get_our_node_id(), update_fulfill);
793                                                                         }
794                                                                         for update_fail in update_fail_htlcs.iter() {
795                                                                                 out.locked_write(format!("Delivering update_fail_htlc to node {}.\n", idx).as_bytes());
796                                                                                 dest.handle_update_fail_htlc(&nodes[$node].get_our_node_id(), update_fail);
797                                                                         }
798                                                                         for update_fail_malformed in update_fail_malformed_htlcs.iter() {
799                                                                                 out.locked_write(format!("Delivering update_fail_malformed_htlc to node {}.\n", idx).as_bytes());
800                                                                                 dest.handle_update_fail_malformed_htlc(&nodes[$node].get_our_node_id(), update_fail_malformed);
801                                                                         }
802                                                                         if let Some(msg) = update_fee {
803                                                                                 out.locked_write(format!("Delivering update_fee to node {}.\n", idx).as_bytes());
804                                                                                 dest.handle_update_fee(&nodes[$node].get_our_node_id(), &msg);
805                                                                         }
806                                                                         let processed_change = !update_add_htlcs.is_empty() || !update_fulfill_htlcs.is_empty() ||
807                                                                                 !update_fail_htlcs.is_empty() || !update_fail_malformed_htlcs.is_empty();
808                                                                         if $limit_events != ProcessMessages::AllMessages && processed_change {
809                                                                                 // If we only want to process some messages, don't deliver the CS until later.
810                                                                                 extra_ev = Some(events::MessageSendEvent::UpdateHTLCs { node_id, updates: CommitmentUpdate {
811                                                                                         update_add_htlcs: Vec::new(),
812                                                                                         update_fail_htlcs: Vec::new(),
813                                                                                         update_fulfill_htlcs: Vec::new(),
814                                                                                         update_fail_malformed_htlcs: Vec::new(),
815                                                                                         update_fee: None,
816                                                                                         commitment_signed
817                                                                                 } });
818                                                                                 break;
819                                                                         }
820                                                                         out.locked_write(format!("Delivering commitment_signed to node {}.\n", idx).as_bytes());
821                                                                         dest.handle_commitment_signed(&nodes[$node].get_our_node_id(), &commitment_signed);
822                                                                         break;
823                                                                 }
824                                                         }
825                                                 },
826                                                 events::MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
827                                                         for (idx, dest) in nodes.iter().enumerate() {
828                                                                 if dest.get_our_node_id() == *node_id {
829                                                                         out.locked_write(format!("Delivering revoke_and_ack to node {}.\n", idx).as_bytes());
830                                                                         dest.handle_revoke_and_ack(&nodes[$node].get_our_node_id(), msg);
831                                                                 }
832                                                         }
833                                                 },
834                                                 events::MessageSendEvent::SendChannelReestablish { ref node_id, ref msg } => {
835                                                         for (idx, dest) in nodes.iter().enumerate() {
836                                                                 if dest.get_our_node_id() == *node_id {
837                                                                         out.locked_write(format!("Delivering channel_reestablish to node {}.\n", idx).as_bytes());
838                                                                         dest.handle_channel_reestablish(&nodes[$node].get_our_node_id(), msg);
839                                                                 }
840                                                         }
841                                                 },
842                                                 events::MessageSendEvent::SendChannelReady { .. } => {
843                                                         // Can be generated as a reestablish response
844                                                 },
845                                                 events::MessageSendEvent::SendAnnouncementSignatures { .. } => {
846                                                         // Can be generated as a reestablish response
847                                                 },
848                                                 events::MessageSendEvent::SendChannelUpdate { ref msg, .. } => {
849                                                         // When we reconnect we will resend a channel_update to make sure our
850                                                         // counterparty has the latest parameters for receiving payments
851                                                         // through us. We do, however, check that the message does not include
852                                                         // the "disabled" bit, as we should never ever have a channel which is
853                                                         // disabled when we send such an update (or it may indicate channel
854                                                         // force-close which we should detect as an error).
855                                                         assert_eq!(msg.contents.flags & 2, 0);
856                                                 },
857                                                 _ => if out.may_fail.load(atomic::Ordering::Acquire) {
858                                                         return;
859                                                 } else {
860                                                         panic!("Unhandled message event {:?}", event)
861                                                 },
862                                         }
863                                         if $limit_events != ProcessMessages::AllMessages {
864                                                 break;
865                                         }
866                                 }
867                                 if $node == 1 {
868                                         push_excess_b_events!(extra_ev.into_iter().chain(events_iter), None);
869                                 } else if $node == 0 {
870                                         if let Some(ev) = extra_ev { ab_events.push(ev); }
871                                         for event in events_iter { ab_events.push(event); }
872                                 } else {
873                                         if let Some(ev) = extra_ev { cb_events.push(ev); }
874                                         for event in events_iter { cb_events.push(event); }
875                                 }
876                                 had_events
877                         } }
878                 }
879
880                 macro_rules! drain_msg_events_on_disconnect {
881                         ($counterparty_id: expr) => { {
882                                 if $counterparty_id == 0 {
883                                         for event in nodes[0].get_and_clear_pending_msg_events() {
884                                                 match event {
885                                                         events::MessageSendEvent::UpdateHTLCs { .. } => {},
886                                                         events::MessageSendEvent::SendRevokeAndACK { .. } => {},
887                                                         events::MessageSendEvent::SendChannelReestablish { .. } => {},
888                                                         events::MessageSendEvent::SendChannelReady { .. } => {},
889                                                         events::MessageSendEvent::SendAnnouncementSignatures { .. } => {},
890                                                         events::MessageSendEvent::SendChannelUpdate { ref msg, .. } => {
891                                                                 assert_eq!(msg.contents.flags & 2, 0); // The disable bit must never be set!
892                                                         },
893                                                         _ => if out.may_fail.load(atomic::Ordering::Acquire) {
894                                                                 return;
895                                                         } else {
896                                                                 panic!("Unhandled message event")
897                                                         },
898                                                 }
899                                         }
900                                         push_excess_b_events!(nodes[1].get_and_clear_pending_msg_events().drain(..), Some(0));
901                                         ab_events.clear();
902                                         ba_events.clear();
903                                 } else {
904                                         for event in nodes[2].get_and_clear_pending_msg_events() {
905                                                 match event {
906                                                         events::MessageSendEvent::UpdateHTLCs { .. } => {},
907                                                         events::MessageSendEvent::SendRevokeAndACK { .. } => {},
908                                                         events::MessageSendEvent::SendChannelReestablish { .. } => {},
909                                                         events::MessageSendEvent::SendChannelReady { .. } => {},
910                                                         events::MessageSendEvent::SendAnnouncementSignatures { .. } => {},
911                                                         events::MessageSendEvent::SendChannelUpdate { ref msg, .. } => {
912                                                                 assert_eq!(msg.contents.flags & 2, 0); // The disable bit must never be set!
913                                                         },
914                                                         _ => if out.may_fail.load(atomic::Ordering::Acquire) {
915                                                                 return;
916                                                         } else {
917                                                                 panic!("Unhandled message event")
918                                                         },
919                                                 }
920                                         }
921                                         push_excess_b_events!(nodes[1].get_and_clear_pending_msg_events().drain(..), Some(2));
922                                         bc_events.clear();
923                                         cb_events.clear();
924                                 }
925                         } }
926                 }
927
928                 macro_rules! process_events {
929                         ($node: expr, $fail: expr) => { {
930                                 // In case we get 256 payments we may have a hash collision, resulting in the
931                                 // second claim/fail call not finding the duplicate-hash HTLC, so we have to
932                                 // deduplicate the calls here.
933                                 let mut claim_set = HashSet::new();
934                                 let mut events = nodes[$node].get_and_clear_pending_events();
935                                 // Sort events so that PendingHTLCsForwardable get processed last. This avoids a
936                                 // case where we first process a PendingHTLCsForwardable, then claim/fail on a
937                                 // PaymentClaimable, claiming/failing two HTLCs, but leaving a just-generated
938                                 // PaymentClaimable event for the second HTLC in our pending_events (and breaking
939                                 // our claim_set deduplication).
940                                 events.sort_by(|a, b| {
941                                         if let events::Event::PaymentClaimable { .. } = a {
942                                                 if let events::Event::PendingHTLCsForwardable { .. } = b {
943                                                         Ordering::Less
944                                                 } else { Ordering::Equal }
945                                         } else if let events::Event::PendingHTLCsForwardable { .. } = a {
946                                                 if let events::Event::PaymentClaimable { .. } = b {
947                                                         Ordering::Greater
948                                                 } else { Ordering::Equal }
949                                         } else { Ordering::Equal }
950                                 });
951                                 let had_events = !events.is_empty();
952                                 for event in events.drain(..) {
953                                         match event {
954                                                 events::Event::PaymentClaimable { payment_hash, .. } => {
955                                                         if claim_set.insert(payment_hash.0) {
956                                                                 if $fail {
957                                                                         nodes[$node].fail_htlc_backwards(&payment_hash);
958                                                                 } else {
959                                                                         nodes[$node].claim_funds(PaymentPreimage(payment_hash.0));
960                                                                 }
961                                                         }
962                                                 },
963                                                 events::Event::PaymentSent { .. } => {},
964                                                 events::Event::PaymentClaimed { .. } => {},
965                                                 events::Event::PaymentPathSuccessful { .. } => {},
966                                                 events::Event::PaymentPathFailed { .. } => {},
967                                                 events::Event::PaymentFailed { .. } => {},
968                                                 events::Event::ProbeSuccessful { .. } | events::Event::ProbeFailed { .. } => {
969                                                         // Even though we don't explicitly send probes, because probes are
970                                                         // detected based on hashing the payment hash+preimage, its rather
971                                                         // trivial for the fuzzer to build payments that accidentally end up
972                                                         // looking like probes.
973                                                 },
974                                                 events::Event::PaymentForwarded { .. } if $node == 1 => {},
975                                                 events::Event::ChannelReady { .. } => {},
976                                                 events::Event::PendingHTLCsForwardable { .. } => {
977                                                         nodes[$node].process_pending_htlc_forwards();
978                                                 },
979                                                 events::Event::HTLCHandlingFailed { .. } => {},
980                                                 _ => if out.may_fail.load(atomic::Ordering::Acquire) {
981                                                         return;
982                                                 } else {
983                                                         panic!("Unhandled event")
984                                                 },
985                                         }
986                                 }
987                                 had_events
988                         } }
989                 }
990
991                 let v = get_slice!(1)[0];
992                 out.locked_write(format!("READ A BYTE! HANDLING INPUT {:x}...........\n", v).as_bytes());
993                 match v {
994                         // In general, we keep related message groups close together in binary form, allowing
995                         // bit-twiddling mutations to have similar effects. This is probably overkill, but no
996                         // harm in doing so.
997
998                         0x00 => *monitor_a.persister.update_ret.lock().unwrap() = ChannelMonitorUpdateStatus::InProgress,
999                         0x01 => *monitor_b.persister.update_ret.lock().unwrap() = ChannelMonitorUpdateStatus::InProgress,
1000                         0x02 => *monitor_c.persister.update_ret.lock().unwrap() = ChannelMonitorUpdateStatus::InProgress,
1001                         0x04 => *monitor_a.persister.update_ret.lock().unwrap() = ChannelMonitorUpdateStatus::Completed,
1002                         0x05 => *monitor_b.persister.update_ret.lock().unwrap() = ChannelMonitorUpdateStatus::Completed,
1003                         0x06 => *monitor_c.persister.update_ret.lock().unwrap() = ChannelMonitorUpdateStatus::Completed,
1004
1005                         0x08 => {
1006                                 if let Some((id, _)) = monitor_a.latest_monitors.lock().unwrap().get(&chan_1_funding) {
1007                                         monitor_a.chain_monitor.force_channel_monitor_updated(chan_1_funding, *id);
1008                                         nodes[0].process_monitor_events();
1009                                 }
1010                         },
1011                         0x09 => {
1012                                 if let Some((id, _)) = monitor_b.latest_monitors.lock().unwrap().get(&chan_1_funding) {
1013                                         monitor_b.chain_monitor.force_channel_monitor_updated(chan_1_funding, *id);
1014                                         nodes[1].process_monitor_events();
1015                                 }
1016                         },
1017                         0x0a => {
1018                                 if let Some((id, _)) = monitor_b.latest_monitors.lock().unwrap().get(&chan_2_funding) {
1019                                         monitor_b.chain_monitor.force_channel_monitor_updated(chan_2_funding, *id);
1020                                         nodes[1].process_monitor_events();
1021                                 }
1022                         },
1023                         0x0b => {
1024                                 if let Some((id, _)) = monitor_c.latest_monitors.lock().unwrap().get(&chan_2_funding) {
1025                                         monitor_c.chain_monitor.force_channel_monitor_updated(chan_2_funding, *id);
1026                                         nodes[2].process_monitor_events();
1027                                 }
1028                         },
1029
1030                         0x0c => {
1031                                 if !chan_a_disconnected {
1032                                         nodes[0].peer_disconnected(&nodes[1].get_our_node_id());
1033                                         nodes[1].peer_disconnected(&nodes[0].get_our_node_id());
1034                                         chan_a_disconnected = true;
1035                                         drain_msg_events_on_disconnect!(0);
1036                                 }
1037                         },
1038                         0x0d => {
1039                                 if !chan_b_disconnected {
1040                                         nodes[1].peer_disconnected(&nodes[2].get_our_node_id());
1041                                         nodes[2].peer_disconnected(&nodes[1].get_our_node_id());
1042                                         chan_b_disconnected = true;
1043                                         drain_msg_events_on_disconnect!(2);
1044                                 }
1045                         },
1046                         0x0e => {
1047                                 if chan_a_disconnected {
1048                                         nodes[0].peer_connected(&nodes[1].get_our_node_id(), &Init {
1049                                                 features: nodes[1].init_features(), networks: None, remote_network_address: None
1050                                         }, true).unwrap();
1051                                         nodes[1].peer_connected(&nodes[0].get_our_node_id(), &Init {
1052                                                 features: nodes[0].init_features(), networks: None, remote_network_address: None
1053                                         }, false).unwrap();
1054                                         chan_a_disconnected = false;
1055                                 }
1056                         },
1057                         0x0f => {
1058                                 if chan_b_disconnected {
1059                                         nodes[1].peer_connected(&nodes[2].get_our_node_id(), &Init {
1060                                                 features: nodes[2].init_features(), networks: None, remote_network_address: None
1061                                         }, true).unwrap();
1062                                         nodes[2].peer_connected(&nodes[1].get_our_node_id(), &Init {
1063                                                 features: nodes[1].init_features(), networks: None, remote_network_address: None
1064                                         }, false).unwrap();
1065                                         chan_b_disconnected = false;
1066                                 }
1067                         },
1068
1069                         0x10 => { process_msg_events!(0, true, ProcessMessages::AllMessages); },
1070                         0x11 => { process_msg_events!(0, false, ProcessMessages::AllMessages); },
1071                         0x12 => { process_msg_events!(0, true, ProcessMessages::OneMessage); },
1072                         0x13 => { process_msg_events!(0, false, ProcessMessages::OneMessage); },
1073                         0x14 => { process_msg_events!(0, true, ProcessMessages::OnePendingMessage); },
1074                         0x15 => { process_msg_events!(0, false, ProcessMessages::OnePendingMessage); },
1075
1076                         0x16 => { process_events!(0, true); },
1077                         0x17 => { process_events!(0, false); },
1078
1079                         0x18 => { process_msg_events!(1, true, ProcessMessages::AllMessages); },
1080                         0x19 => { process_msg_events!(1, false, ProcessMessages::AllMessages); },
1081                         0x1a => { process_msg_events!(1, true, ProcessMessages::OneMessage); },
1082                         0x1b => { process_msg_events!(1, false, ProcessMessages::OneMessage); },
1083                         0x1c => { process_msg_events!(1, true, ProcessMessages::OnePendingMessage); },
1084                         0x1d => { process_msg_events!(1, false, ProcessMessages::OnePendingMessage); },
1085
1086                         0x1e => { process_events!(1, true); },
1087                         0x1f => { process_events!(1, false); },
1088
1089                         0x20 => { process_msg_events!(2, true, ProcessMessages::AllMessages); },
1090                         0x21 => { process_msg_events!(2, false, ProcessMessages::AllMessages); },
1091                         0x22 => { process_msg_events!(2, true, ProcessMessages::OneMessage); },
1092                         0x23 => { process_msg_events!(2, false, ProcessMessages::OneMessage); },
1093                         0x24 => { process_msg_events!(2, true, ProcessMessages::OnePendingMessage); },
1094                         0x25 => { process_msg_events!(2, false, ProcessMessages::OnePendingMessage); },
1095
1096                         0x26 => { process_events!(2, true); },
1097                         0x27 => { process_events!(2, false); },
1098
1099                         0x2c => {
1100                                 if !chan_a_disconnected {
1101                                         nodes[1].peer_disconnected(&nodes[0].get_our_node_id());
1102                                         chan_a_disconnected = true;
1103                                         push_excess_b_events!(nodes[1].get_and_clear_pending_msg_events().drain(..), Some(0));
1104                                         ab_events.clear();
1105                                         ba_events.clear();
1106                                 }
1107                                 let (new_node_a, new_monitor_a) = reload_node!(node_a_ser, 0, monitor_a, keys_manager_a, fee_est_a);
1108                                 nodes[0] = new_node_a;
1109                                 monitor_a = new_monitor_a;
1110                         },
1111                         0x2d => {
1112                                 if !chan_a_disconnected {
1113                                         nodes[0].peer_disconnected(&nodes[1].get_our_node_id());
1114                                         chan_a_disconnected = true;
1115                                         nodes[0].get_and_clear_pending_msg_events();
1116                                         ab_events.clear();
1117                                         ba_events.clear();
1118                                 }
1119                                 if !chan_b_disconnected {
1120                                         nodes[2].peer_disconnected(&nodes[1].get_our_node_id());
1121                                         chan_b_disconnected = true;
1122                                         nodes[2].get_and_clear_pending_msg_events();
1123                                         bc_events.clear();
1124                                         cb_events.clear();
1125                                 }
1126                                 let (new_node_b, new_monitor_b) = reload_node!(node_b_ser, 1, monitor_b, keys_manager_b, fee_est_b);
1127                                 nodes[1] = new_node_b;
1128                                 monitor_b = new_monitor_b;
1129                         },
1130                         0x2e => {
1131                                 if !chan_b_disconnected {
1132                                         nodes[1].peer_disconnected(&nodes[2].get_our_node_id());
1133                                         chan_b_disconnected = true;
1134                                         push_excess_b_events!(nodes[1].get_and_clear_pending_msg_events().drain(..), Some(2));
1135                                         bc_events.clear();
1136                                         cb_events.clear();
1137                                 }
1138                                 let (new_node_c, new_monitor_c) = reload_node!(node_c_ser, 2, monitor_c, keys_manager_c, fee_est_c);
1139                                 nodes[2] = new_node_c;
1140                                 monitor_c = new_monitor_c;
1141                         },
1142
1143                         // 1/10th the channel size:
1144                         0x30 => { send_payment(&nodes[0], &nodes[1], chan_a, 10_000_000, &mut payment_id, &mut payment_idx); },
1145                         0x31 => { send_payment(&nodes[1], &nodes[0], chan_a, 10_000_000, &mut payment_id, &mut payment_idx); },
1146                         0x32 => { send_payment(&nodes[1], &nodes[2], chan_b, 10_000_000, &mut payment_id, &mut payment_idx); },
1147                         0x33 => { send_payment(&nodes[2], &nodes[1], chan_b, 10_000_000, &mut payment_id, &mut payment_idx); },
1148                         0x34 => { send_hop_payment(&nodes[0], &nodes[1], chan_a, &nodes[2], chan_b, 10_000_000, &mut payment_id, &mut payment_idx); },
1149                         0x35 => { send_hop_payment(&nodes[2], &nodes[1], chan_b, &nodes[0], chan_a, 10_000_000, &mut payment_id, &mut payment_idx); },
1150
1151                         0x38 => { send_payment(&nodes[0], &nodes[1], chan_a, 1_000_000, &mut payment_id, &mut payment_idx); },
1152                         0x39 => { send_payment(&nodes[1], &nodes[0], chan_a, 1_000_000, &mut payment_id, &mut payment_idx); },
1153                         0x3a => { send_payment(&nodes[1], &nodes[2], chan_b, 1_000_000, &mut payment_id, &mut payment_idx); },
1154                         0x3b => { send_payment(&nodes[2], &nodes[1], chan_b, 1_000_000, &mut payment_id, &mut payment_idx); },
1155                         0x3c => { send_hop_payment(&nodes[0], &nodes[1], chan_a, &nodes[2], chan_b, 1_000_000, &mut payment_id, &mut payment_idx); },
1156                         0x3d => { send_hop_payment(&nodes[2], &nodes[1], chan_b, &nodes[0], chan_a, 1_000_000, &mut payment_id, &mut payment_idx); },
1157
1158                         0x40 => { send_payment(&nodes[0], &nodes[1], chan_a, 100_000, &mut payment_id, &mut payment_idx); },
1159                         0x41 => { send_payment(&nodes[1], &nodes[0], chan_a, 100_000, &mut payment_id, &mut payment_idx); },
1160                         0x42 => { send_payment(&nodes[1], &nodes[2], chan_b, 100_000, &mut payment_id, &mut payment_idx); },
1161                         0x43 => { send_payment(&nodes[2], &nodes[1], chan_b, 100_000, &mut payment_id, &mut payment_idx); },
1162                         0x44 => { send_hop_payment(&nodes[0], &nodes[1], chan_a, &nodes[2], chan_b, 100_000, &mut payment_id, &mut payment_idx); },
1163                         0x45 => { send_hop_payment(&nodes[2], &nodes[1], chan_b, &nodes[0], chan_a, 100_000, &mut payment_id, &mut payment_idx); },
1164
1165                         0x48 => { send_payment(&nodes[0], &nodes[1], chan_a, 10_000, &mut payment_id, &mut payment_idx); },
1166                         0x49 => { send_payment(&nodes[1], &nodes[0], chan_a, 10_000, &mut payment_id, &mut payment_idx); },
1167                         0x4a => { send_payment(&nodes[1], &nodes[2], chan_b, 10_000, &mut payment_id, &mut payment_idx); },
1168                         0x4b => { send_payment(&nodes[2], &nodes[1], chan_b, 10_000, &mut payment_id, &mut payment_idx); },
1169                         0x4c => { send_hop_payment(&nodes[0], &nodes[1], chan_a, &nodes[2], chan_b, 10_000, &mut payment_id, &mut payment_idx); },
1170                         0x4d => { send_hop_payment(&nodes[2], &nodes[1], chan_b, &nodes[0], chan_a, 10_000, &mut payment_id, &mut payment_idx); },
1171
1172                         0x50 => { send_payment(&nodes[0], &nodes[1], chan_a, 1_000, &mut payment_id, &mut payment_idx); },
1173                         0x51 => { send_payment(&nodes[1], &nodes[0], chan_a, 1_000, &mut payment_id, &mut payment_idx); },
1174                         0x52 => { send_payment(&nodes[1], &nodes[2], chan_b, 1_000, &mut payment_id, &mut payment_idx); },
1175                         0x53 => { send_payment(&nodes[2], &nodes[1], chan_b, 1_000, &mut payment_id, &mut payment_idx); },
1176                         0x54 => { send_hop_payment(&nodes[0], &nodes[1], chan_a, &nodes[2], chan_b, 1_000, &mut payment_id, &mut payment_idx); },
1177                         0x55 => { send_hop_payment(&nodes[2], &nodes[1], chan_b, &nodes[0], chan_a, 1_000, &mut payment_id, &mut payment_idx); },
1178
1179                         0x58 => { send_payment(&nodes[0], &nodes[1], chan_a, 100, &mut payment_id, &mut payment_idx); },
1180                         0x59 => { send_payment(&nodes[1], &nodes[0], chan_a, 100, &mut payment_id, &mut payment_idx); },
1181                         0x5a => { send_payment(&nodes[1], &nodes[2], chan_b, 100, &mut payment_id, &mut payment_idx); },
1182                         0x5b => { send_payment(&nodes[2], &nodes[1], chan_b, 100, &mut payment_id, &mut payment_idx); },
1183                         0x5c => { send_hop_payment(&nodes[0], &nodes[1], chan_a, &nodes[2], chan_b, 100, &mut payment_id, &mut payment_idx); },
1184                         0x5d => { send_hop_payment(&nodes[2], &nodes[1], chan_b, &nodes[0], chan_a, 100, &mut payment_id, &mut payment_idx); },
1185
1186                         0x60 => { send_payment(&nodes[0], &nodes[1], chan_a, 10, &mut payment_id, &mut payment_idx); },
1187                         0x61 => { send_payment(&nodes[1], &nodes[0], chan_a, 10, &mut payment_id, &mut payment_idx); },
1188                         0x62 => { send_payment(&nodes[1], &nodes[2], chan_b, 10, &mut payment_id, &mut payment_idx); },
1189                         0x63 => { send_payment(&nodes[2], &nodes[1], chan_b, 10, &mut payment_id, &mut payment_idx); },
1190                         0x64 => { send_hop_payment(&nodes[0], &nodes[1], chan_a, &nodes[2], chan_b, 10, &mut payment_id, &mut payment_idx); },
1191                         0x65 => { send_hop_payment(&nodes[2], &nodes[1], chan_b, &nodes[0], chan_a, 10, &mut payment_id, &mut payment_idx); },
1192
1193                         0x68 => { send_payment(&nodes[0], &nodes[1], chan_a, 1, &mut payment_id, &mut payment_idx); },
1194                         0x69 => { send_payment(&nodes[1], &nodes[0], chan_a, 1, &mut payment_id, &mut payment_idx); },
1195                         0x6a => { send_payment(&nodes[1], &nodes[2], chan_b, 1, &mut payment_id, &mut payment_idx); },
1196                         0x6b => { send_payment(&nodes[2], &nodes[1], chan_b, 1, &mut payment_id, &mut payment_idx); },
1197                         0x6c => { send_hop_payment(&nodes[0], &nodes[1], chan_a, &nodes[2], chan_b, 1, &mut payment_id, &mut payment_idx); },
1198                         0x6d => { send_hop_payment(&nodes[2], &nodes[1], chan_b, &nodes[0], chan_a, 1, &mut payment_id, &mut payment_idx); },
1199
1200                         0x80 => {
1201                                 let max_feerate = last_htlc_clear_fee_a * FEE_SPIKE_BUFFER_FEE_INCREASE_MULTIPLE as u32;
1202                                 if fee_est_a.ret_val.fetch_add(250, atomic::Ordering::AcqRel) + 250 > max_feerate {
1203                                         fee_est_a.ret_val.store(max_feerate, atomic::Ordering::Release);
1204                                 }
1205                                 nodes[0].maybe_update_chan_fees();
1206                         },
1207                         0x81 => { fee_est_a.ret_val.store(253, atomic::Ordering::Release); nodes[0].maybe_update_chan_fees(); },
1208
1209                         0x84 => {
1210                                 let max_feerate = last_htlc_clear_fee_b * FEE_SPIKE_BUFFER_FEE_INCREASE_MULTIPLE as u32;
1211                                 if fee_est_b.ret_val.fetch_add(250, atomic::Ordering::AcqRel) + 250 > max_feerate {
1212                                         fee_est_b.ret_val.store(max_feerate, atomic::Ordering::Release);
1213                                 }
1214                                 nodes[1].maybe_update_chan_fees();
1215                         },
1216                         0x85 => { fee_est_b.ret_val.store(253, atomic::Ordering::Release); nodes[1].maybe_update_chan_fees(); },
1217
1218                         0x88 => {
1219                                 let max_feerate = last_htlc_clear_fee_c * FEE_SPIKE_BUFFER_FEE_INCREASE_MULTIPLE as u32;
1220                                 if fee_est_c.ret_val.fetch_add(250, atomic::Ordering::AcqRel) + 250 > max_feerate {
1221                                         fee_est_c.ret_val.store(max_feerate, atomic::Ordering::Release);
1222                                 }
1223                                 nodes[2].maybe_update_chan_fees();
1224                         },
1225                         0x89 => { fee_est_c.ret_val.store(253, atomic::Ordering::Release); nodes[2].maybe_update_chan_fees(); },
1226
1227                         0xff => {
1228                                 // Test that no channel is in a stuck state where neither party can send funds even
1229                                 // after we resolve all pending events.
1230                                 // First make sure there are no pending monitor updates, resetting the error state
1231                                 // and calling force_channel_monitor_updated for each monitor.
1232                                 *monitor_a.persister.update_ret.lock().unwrap() = ChannelMonitorUpdateStatus::Completed;
1233                                 *monitor_b.persister.update_ret.lock().unwrap() = ChannelMonitorUpdateStatus::Completed;
1234                                 *monitor_c.persister.update_ret.lock().unwrap() = ChannelMonitorUpdateStatus::Completed;
1235
1236                                 if let Some((id, _)) = monitor_a.latest_monitors.lock().unwrap().get(&chan_1_funding) {
1237                                         monitor_a.chain_monitor.force_channel_monitor_updated(chan_1_funding, *id);
1238                                         nodes[0].process_monitor_events();
1239                                 }
1240                                 if let Some((id, _)) = monitor_b.latest_monitors.lock().unwrap().get(&chan_1_funding) {
1241                                         monitor_b.chain_monitor.force_channel_monitor_updated(chan_1_funding, *id);
1242                                         nodes[1].process_monitor_events();
1243                                 }
1244                                 if let Some((id, _)) = monitor_b.latest_monitors.lock().unwrap().get(&chan_2_funding) {
1245                                         monitor_b.chain_monitor.force_channel_monitor_updated(chan_2_funding, *id);
1246                                         nodes[1].process_monitor_events();
1247                                 }
1248                                 if let Some((id, _)) = monitor_c.latest_monitors.lock().unwrap().get(&chan_2_funding) {
1249                                         monitor_c.chain_monitor.force_channel_monitor_updated(chan_2_funding, *id);
1250                                         nodes[2].process_monitor_events();
1251                                 }
1252
1253                                 // Next, make sure peers are all connected to each other
1254                                 if chan_a_disconnected {
1255                                         nodes[0].peer_connected(&nodes[1].get_our_node_id(), &Init {
1256                                                 features: nodes[1].init_features(), networks: None, remote_network_address: None
1257                                         }, true).unwrap();
1258                                         nodes[1].peer_connected(&nodes[0].get_our_node_id(), &Init {
1259                                                 features: nodes[0].init_features(), networks: None, remote_network_address: None
1260                                         }, false).unwrap();
1261                                         chan_a_disconnected = false;
1262                                 }
1263                                 if chan_b_disconnected {
1264                                         nodes[1].peer_connected(&nodes[2].get_our_node_id(), &Init {
1265                                                 features: nodes[2].init_features(), networks: None, remote_network_address: None
1266                                         }, true).unwrap();
1267                                         nodes[2].peer_connected(&nodes[1].get_our_node_id(), &Init {
1268                                                 features: nodes[1].init_features(), networks: None, remote_network_address: None
1269                                         }, false).unwrap();
1270                                         chan_b_disconnected = false;
1271                                 }
1272
1273                                 for i in 0..std::usize::MAX {
1274                                         if i == 100 { panic!("It may take may iterations to settle the state, but it should not take forever"); }
1275                                         // Then, make sure any current forwards make their way to their destination
1276                                         if process_msg_events!(0, false, ProcessMessages::AllMessages) { continue; }
1277                                         if process_msg_events!(1, false, ProcessMessages::AllMessages) { continue; }
1278                                         if process_msg_events!(2, false, ProcessMessages::AllMessages) { continue; }
1279                                         // ...making sure any pending PendingHTLCsForwardable events are handled and
1280                                         // payments claimed.
1281                                         if process_events!(0, false) { continue; }
1282                                         if process_events!(1, false) { continue; }
1283                                         if process_events!(2, false) { continue; }
1284                                         break;
1285                                 }
1286
1287                                 // Finally, make sure that at least one end of each channel can make a substantial payment
1288                                 assert!(
1289                                         send_payment(&nodes[0], &nodes[1], chan_a, 10_000_000, &mut payment_id, &mut payment_idx) ||
1290                                         send_payment(&nodes[1], &nodes[0], chan_a, 10_000_000, &mut payment_id, &mut payment_idx));
1291                                 assert!(
1292                                         send_payment(&nodes[1], &nodes[2], chan_b, 10_000_000, &mut payment_id, &mut payment_idx) ||
1293                                         send_payment(&nodes[2], &nodes[1], chan_b, 10_000_000, &mut payment_id, &mut payment_idx));
1294
1295                                 last_htlc_clear_fee_a = fee_est_a.ret_val.load(atomic::Ordering::Acquire);
1296                                 last_htlc_clear_fee_b = fee_est_b.ret_val.load(atomic::Ordering::Acquire);
1297                                 last_htlc_clear_fee_c = fee_est_c.ret_val.load(atomic::Ordering::Acquire);
1298                         },
1299                         _ => test_return!(),
1300                 }
1301
1302                 if nodes[0].get_and_clear_needs_persistence() == true {
1303                         node_a_ser.0.clear();
1304                         nodes[0].write(&mut node_a_ser).unwrap();
1305                 }
1306                 if nodes[1].get_and_clear_needs_persistence() == true {
1307                         node_b_ser.0.clear();
1308                         nodes[1].write(&mut node_b_ser).unwrap();
1309                 }
1310                 if nodes[2].get_and_clear_needs_persistence() == true {
1311                         node_c_ser.0.clear();
1312                         nodes[2].write(&mut node_c_ser).unwrap();
1313                 }
1314         }
1315 }
1316
1317 /// We actually have different behavior based on if a certain log string has been seen, so we have
1318 /// to do a bit more tracking.
1319 #[derive(Clone)]
1320 struct SearchingOutput<O: Output> {
1321         output: O,
1322         may_fail: Arc<atomic::AtomicBool>,
1323 }
1324 impl<O: Output> Output for SearchingOutput<O> {
1325         fn locked_write(&self, data: &[u8]) {
1326                 // We hit a design limitation of LN state machine (see CONCURRENT_INBOUND_HTLC_FEE_BUFFER)
1327                 if std::str::from_utf8(data).unwrap().contains("Outbound update_fee HTLC buffer overflow - counterparty should force-close this channel") {
1328                         self.may_fail.store(true, atomic::Ordering::Release);
1329                 }
1330                 self.output.locked_write(data)
1331         }
1332 }
1333 impl<O: Output> SearchingOutput<O> {
1334         pub fn new(output: O) -> Self {
1335                 Self { output, may_fail: Arc::new(atomic::AtomicBool::new(false)) }
1336         }
1337 }
1338
1339 pub fn chanmon_consistency_test<Out: Output>(data: &[u8], out: Out) {
1340         do_test(data, out);
1341 }
1342
1343 #[no_mangle]
1344 pub extern "C" fn chanmon_consistency_run(data: *const u8, datalen: usize) {
1345         do_test(unsafe { std::slice::from_raw_parts(data, datalen) }, test_logger::DevNull{});
1346 }