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