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