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