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