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