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