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