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