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