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