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