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