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