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