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