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