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