1 // This file is Copyright its original authors, visible in version control
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
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.
21 use bitcoin::TxMerkleNode;
22 use bitcoin::blockdata::block::BlockHeader;
23 use bitcoin::blockdata::constants::genesis_block;
24 use bitcoin::blockdata::transaction::{Transaction, TxOut};
25 use bitcoin::blockdata::script::{Builder, Script};
26 use bitcoin::blockdata::opcodes;
27 use bitcoin::blockdata::locktime::PackedLockTime;
28 use bitcoin::network::constants::Network;
30 use bitcoin::hashes::Hash as TraitImport;
31 use bitcoin::hashes::sha256::Hash as Sha256;
32 use bitcoin::hashes::sha256d::Hash as Sha256dHash;
33 use bitcoin::hash_types::{BlockHash, WPubkeyHash};
36 use lightning::chain::{BestBlock, ChannelMonitorUpdateStatus, chainmonitor, channelmonitor, Confirm, Watch};
37 use lightning::chain::channelmonitor::{ChannelMonitor, MonitorEvent};
38 use lightning::chain::transaction::OutPoint;
39 use lightning::chain::chaininterface::{BroadcasterInterface, ConfirmationTarget, FeeEstimator};
40 use lightning::chain::keysinterface::{KeyMaterial, InMemorySigner, Recipient, EntropySource, NodeSigner, SignerProvider};
41 use lightning::ln::{PaymentHash, PaymentPreimage, PaymentSecret};
42 use lightning::ln::channelmanager::{ChainParameters, ChannelDetails, ChannelManager, PaymentSendFailure, ChannelManagerReadArgs, PaymentId};
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::util::enforcing_trait_impls::{EnforcingSigner, EnforcementState};
47 use lightning::util::errors::APIError;
48 use lightning::util::events;
49 use lightning::util::logger::Logger;
50 use lightning::util::config::UserConfig;
51 use lightning::util::events::MessageSendEventsProvider;
52 use lightning::util::ser::{Readable, ReadableArgs, Writeable, Writer};
53 use lightning::routing::router::{InFlightHtlcs, Route, RouteHop, RouteParameters, Router};
55 use crate::utils::test_logger::{self, Output};
56 use crate::utils::test_persister::TestPersister;
58 use bitcoin::secp256k1::{Message, PublicKey, SecretKey, Scalar, Secp256k1};
59 use bitcoin::secp256k1::ecdh::SharedSecret;
60 use bitcoin::secp256k1::ecdsa::{RecoverableSignature, Signature};
63 use std::cmp::{self, Ordering};
64 use hashbrown::{HashSet, hash_map, HashMap};
65 use std::sync::{Arc,Mutex};
66 use std::sync::atomic;
68 use bitcoin::bech32::u5;
70 const MAX_FEE: u32 = 10_000;
71 struct FuzzEstimator {
72 ret_val: atomic::AtomicU32,
74 impl FeeEstimator for FuzzEstimator {
75 fn get_est_sat_per_1000_weight(&self, conf_target: ConfirmationTarget) -> u32 {
76 // We force-close channels if our counterparty sends us a feerate which is a small multiple
77 // of our HighPriority fee estimate or smaller than our Background fee estimate. Thus, we
78 // always return a HighPriority feerate here which is >= the maximum Normal feerate and a
79 // Background feerate which is <= the minimum Normal feerate.
81 ConfirmationTarget::HighPriority => MAX_FEE,
82 ConfirmationTarget::Background => 253,
83 ConfirmationTarget::Normal => cmp::min(self.ret_val.load(atomic::Ordering::Acquire), MAX_FEE),
90 impl Router for FuzzRouter {
92 &self, _payer: &PublicKey, _params: &RouteParameters, _first_hops: Option<&[&ChannelDetails]>,
93 _inflight_htlcs: &InFlightHtlcs
94 ) -> Result<Route, msgs::LightningError> {
95 Err(msgs::LightningError {
96 err: String::from("Not implemented"),
97 action: msgs::ErrorAction::IgnoreError
102 pub struct TestBroadcaster {}
103 impl BroadcasterInterface for TestBroadcaster {
104 fn broadcast_transaction(&self, _tx: &Transaction) { }
107 pub struct VecWriter(pub Vec<u8>);
108 impl Writer for VecWriter {
109 fn write_all(&mut self, buf: &[u8]) -> Result<(), ::std::io::Error> {
110 self.0.extend_from_slice(buf);
115 struct TestChainMonitor {
116 pub logger: Arc<dyn Logger>,
117 pub keys: Arc<KeyProvider>,
118 pub persister: Arc<TestPersister>,
119 pub chain_monitor: Arc<chainmonitor::ChainMonitor<EnforcingSigner, Arc<dyn chain::Filter>, Arc<TestBroadcaster>, Arc<FuzzEstimator>, Arc<dyn Logger>, Arc<TestPersister>>>,
120 // If we reload a node with an old copy of ChannelMonitors, the ChannelManager deserialization
121 // logic will automatically force-close our channels for us (as we don't have an up-to-date
122 // monitor implying we are not able to punish misbehaving counterparties). Because this test
123 // "fails" if we ever force-close a channel, we avoid doing so, always saving the latest
124 // fully-serialized monitor state here, as well as the corresponding update_id.
125 pub latest_monitors: Mutex<HashMap<OutPoint, (u64, Vec<u8>)>>,
126 pub should_update_manager: atomic::AtomicBool,
128 impl TestChainMonitor {
129 pub fn new(broadcaster: Arc<TestBroadcaster>, logger: Arc<dyn Logger>, feeest: Arc<FuzzEstimator>, persister: Arc<TestPersister>, keys: Arc<KeyProvider>) -> Self {
131 chain_monitor: Arc::new(chainmonitor::ChainMonitor::new(None, broadcaster, logger.clone(), feeest, Arc::clone(&persister))),
135 latest_monitors: Mutex::new(HashMap::new()),
136 should_update_manager: atomic::AtomicBool::new(false),
140 impl chain::Watch<EnforcingSigner> for TestChainMonitor {
141 fn watch_channel(&self, funding_txo: OutPoint, monitor: channelmonitor::ChannelMonitor<EnforcingSigner>) -> chain::ChannelMonitorUpdateStatus {
142 let mut ser = VecWriter(Vec::new());
143 monitor.write(&mut ser).unwrap();
144 if let Some(_) = self.latest_monitors.lock().unwrap().insert(funding_txo, (monitor.get_latest_update_id(), ser.0)) {
145 panic!("Already had monitor pre-watch_channel");
147 self.should_update_manager.store(true, atomic::Ordering::Relaxed);
148 self.chain_monitor.watch_channel(funding_txo, monitor)
151 fn update_channel(&self, funding_txo: OutPoint, update: &channelmonitor::ChannelMonitorUpdate) -> chain::ChannelMonitorUpdateStatus {
152 let mut map_lock = self.latest_monitors.lock().unwrap();
153 let mut map_entry = match map_lock.entry(funding_txo) {
154 hash_map::Entry::Occupied(entry) => entry,
155 hash_map::Entry::Vacant(_) => panic!("Didn't have monitor on update call"),
157 let deserialized_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::
158 read(&mut Cursor::new(&map_entry.get().1), (&*self.keys, &*self.keys)).unwrap().1;
159 deserialized_monitor.update_monitor(update, &&TestBroadcaster{}, &FuzzEstimator { ret_val: atomic::AtomicU32::new(253) }, &self.logger).unwrap();
160 let mut ser = VecWriter(Vec::new());
161 deserialized_monitor.write(&mut ser).unwrap();
162 map_entry.insert((update.update_id, ser.0));
163 self.should_update_manager.store(true, atomic::Ordering::Relaxed);
164 self.chain_monitor.update_channel(funding_txo, update)
167 fn release_pending_monitor_events(&self) -> Vec<(OutPoint, Vec<MonitorEvent>, Option<PublicKey>)> {
168 return self.chain_monitor.release_pending_monitor_events();
173 node_secret: SecretKey,
174 rand_bytes_id: atomic::AtomicU32,
175 enforcement_states: Mutex<HashMap<[u8;32], Arc<Mutex<EnforcementState>>>>,
178 impl EntropySource for KeyProvider {
179 fn get_secure_random_bytes(&self) -> [u8; 32] {
180 let id = self.rand_bytes_id.fetch_add(1, atomic::Ordering::Relaxed);
181 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]];
182 res[30-4..30].copy_from_slice(&id.to_le_bytes());
187 impl NodeSigner for KeyProvider {
188 fn get_node_id(&self, recipient: Recipient) -> Result<PublicKey, ()> {
189 let node_secret = match recipient {
190 Recipient::Node => Ok(&self.node_secret),
191 Recipient::PhantomNode => Err(())
193 Ok(PublicKey::from_secret_key(&Secp256k1::signing_only(), node_secret))
196 fn ecdh(&self, recipient: Recipient, other_key: &PublicKey, tweak: Option<&Scalar>) -> Result<SharedSecret, ()> {
197 let mut node_secret = match recipient {
198 Recipient::Node => Ok(self.node_secret.clone()),
199 Recipient::PhantomNode => Err(())
201 if let Some(tweak) = tweak {
202 node_secret = node_secret.mul_tweak(tweak).map_err(|_| ())?;
204 Ok(SharedSecret::new(other_key, &node_secret))
207 fn get_inbound_payment_key_material(&self) -> KeyMaterial {
208 KeyMaterial([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, self.node_secret[31]])
211 fn sign_invoice(&self, _hrp_bytes: &[u8], _invoice_data: &[u5], _recipient: Recipient) -> Result<RecoverableSignature, ()> {
215 fn sign_gossip_message(&self, msg: lightning::ln::msgs::UnsignedGossipMessage) -> Result<Signature, ()> {
216 let msg_hash = Message::from_slice(&Sha256dHash::hash(&msg.encode()[..])[..]).map_err(|_| ())?;
217 let secp_ctx = Secp256k1::signing_only();
218 Ok(secp_ctx.sign_ecdsa(&msg_hash, &self.node_secret))
222 impl SignerProvider for KeyProvider {
223 type Signer = EnforcingSigner;
225 fn generate_channel_keys_id(&self, _inbound: bool, _channel_value_satoshis: u64, _user_channel_id: u128) -> [u8; 32] {
226 let id = self.rand_bytes_id.fetch_add(1, atomic::Ordering::Relaxed) as u8;
230 fn derive_channel_signer(&self, channel_value_satoshis: u64, channel_keys_id: [u8; 32]) -> Self::Signer {
231 let secp_ctx = Secp256k1::signing_only();
232 let id = channel_keys_id[0];
233 let keys = InMemorySigner::new(
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, 4, 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, 5, 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, 6, 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, 7, self.node_secret[31]]).unwrap(),
239 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(),
240 [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]],
241 channel_value_satoshis,
244 let revoked_commitment = self.make_enforcement_state_cell(keys.commitment_seed);
245 EnforcingSigner::new_with_revoked(keys, revoked_commitment, false)
248 fn read_chan_signer(&self, buffer: &[u8]) -> Result<Self::Signer, DecodeError> {
249 let mut reader = std::io::Cursor::new(buffer);
251 let inner: InMemorySigner = Readable::read(&mut reader)?;
252 let state = self.make_enforcement_state_cell(inner.commitment_seed);
257 disable_revocation_policy_check: false,
261 fn get_destination_script(&self) -> 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 Builder::new().push_opcode(opcodes::all::OP_PUSHBYTES_0).push_slice(&our_channel_monitor_claim_key_hash[..]).into_script()
268 fn get_shutdown_scriptpubkey(&self) -> 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 ShutdownScript::new_p2wpkh(&pubkey_hash)
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())));
282 let cell = revoked_commitments.get(&commitment_seed).unwrap();
288 fn check_api_err(api_err: APIError) {
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.
298 "Peer for first hop currently disconnected" => {},
299 _ if err.starts_with("Cannot push more than their max accepted HTLCs ") => {},
300 _ if err.starts_with("Cannot send value that would put us over the max HTLC value in flight our peer will accept ") => {},
301 _ if err.starts_with("Cannot send value that would put our balance under counterparty-announced channel reserve value") => {},
302 _ if err.starts_with("Cannot send value that would put counterparty balance under holder-announced channel reserve value") => {},
303 _ if err.starts_with("Cannot send value that would overdraw remaining funds.") => {},
304 _ if err.starts_with("Cannot send value that would not leave enough to pay for fees.") => {},
305 _ if err.starts_with("Cannot send value that would put our exposure to dust HTLCs at") => {},
306 _ => panic!("{}", err),
309 APIError::MonitorUpdateInProgress => {
310 // We can (obviously) temp-fail a monitor update
312 APIError::IncompatibleShutdownScript { .. } => panic!("Cannot send an incompatible shutdown script"),
316 fn check_payment_err(send_err: PaymentSendFailure) {
318 PaymentSendFailure::ParameterError(api_err) => check_api_err(api_err),
319 PaymentSendFailure::PathParameterError(per_path_results) => {
320 for res in per_path_results { if let Err(api_err) = res { check_api_err(api_err); } }
322 PaymentSendFailure::AllFailedResendSafe(per_path_results) => {
323 for api_err in per_path_results { check_api_err(api_err); }
325 PaymentSendFailure::PartialFailure { results, .. } => {
326 for res in results { if let Err(api_err) = res { check_api_err(api_err); } }
328 PaymentSendFailure::DuplicatePayment => panic!(),
332 type ChanMan<'a> = ChannelManager<Arc<TestChainMonitor>, Arc<TestBroadcaster>, Arc<KeyProvider>, Arc<KeyProvider>, Arc<KeyProvider>, Arc<FuzzEstimator>, &'a FuzzRouter, Arc<dyn Logger>>;
335 fn get_payment_secret_hash(dest: &ChanMan, payment_id: &mut u8) -> Option<(PaymentSecret, PaymentHash)> {
336 let mut payment_hash;
338 payment_hash = PaymentHash(Sha256::hash(&[*payment_id; 1]).into_inner());
339 if let Ok(payment_secret) = dest.create_inbound_payment_for_hash(payment_hash, None, 3600, None) {
340 return Some((payment_secret, payment_hash));
342 *payment_id = payment_id.wrapping_add(1);
348 fn send_payment(source: &ChanMan, dest: &ChanMan, dest_chan_id: u64, amt: u64, payment_id: &mut u8, payment_idx: &mut u64) -> bool {
349 let (payment_secret, payment_hash) =
350 if let Some((secret, hash)) = get_payment_secret_hash(dest, payment_id) { (secret, hash) } else { return true; };
351 let mut payment_id = [0; 32];
352 payment_id[0..8].copy_from_slice(&payment_idx.to_ne_bytes());
354 if let Err(err) = source.send_payment(&Route {
355 paths: vec![vec![RouteHop {
356 pubkey: dest.get_our_node_id(),
357 node_features: dest.node_features(),
358 short_channel_id: dest_chan_id,
359 channel_features: dest.channel_features(),
361 cltv_expiry_delta: 200,
363 payment_params: None,
364 }, payment_hash, &Some(payment_secret), PaymentId(payment_id)) {
365 check_payment_err(err);
370 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 {
371 let (payment_secret, payment_hash) =
372 if let Some((secret, hash)) = get_payment_secret_hash(dest, payment_id) { (secret, hash) } else { return true; };
373 let mut payment_id = [0; 32];
374 payment_id[0..8].copy_from_slice(&payment_idx.to_ne_bytes());
376 if let Err(err) = source.send_payment(&Route {
377 paths: vec![vec![RouteHop {
378 pubkey: middle.get_our_node_id(),
379 node_features: middle.node_features(),
380 short_channel_id: middle_chan_id,
381 channel_features: middle.channel_features(),
383 cltv_expiry_delta: 100,
385 pubkey: dest.get_our_node_id(),
386 node_features: dest.node_features(),
387 short_channel_id: dest_chan_id,
388 channel_features: dest.channel_features(),
390 cltv_expiry_delta: 200,
392 payment_params: None,
393 }, payment_hash, &Some(payment_secret), PaymentId(payment_id)) {
394 check_payment_err(err);
400 pub fn do_test<Out: Output>(data: &[u8], underlying_out: Out) {
401 let out = SearchingOutput::new(underlying_out);
402 let broadcast = Arc::new(TestBroadcaster{});
403 let router = FuzzRouter {};
405 macro_rules! make_node {
406 ($node_id: expr, $fee_estimator: expr) => { {
407 let logger: Arc<dyn Logger> = Arc::new(test_logger::TestLogger::new($node_id.to_string(), out.clone()));
408 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();
409 let keys_manager = Arc::new(KeyProvider { node_secret, rand_bytes_id: atomic::AtomicU32::new(0), enforcement_states: Mutex::new(HashMap::new()) });
410 let monitor = Arc::new(TestChainMonitor::new(broadcast.clone(), logger.clone(), $fee_estimator.clone(),
411 Arc::new(TestPersister {
412 update_ret: Mutex::new(ChannelMonitorUpdateStatus::Completed)
413 }), Arc::clone(&keys_manager)));
415 let mut config = UserConfig::default();
416 config.channel_config.forwarding_fee_proportional_millionths = 0;
417 config.channel_handshake_config.announced_channel = true;
418 let network = Network::Bitcoin;
419 let params = ChainParameters {
421 best_block: BestBlock::from_network(network),
423 (ChannelManager::new($fee_estimator.clone(), monitor.clone(), broadcast.clone(), &router, Arc::clone(&logger), keys_manager.clone(), keys_manager.clone(), keys_manager.clone(), config, params),
424 monitor, keys_manager)
428 macro_rules! reload_node {
429 ($ser: expr, $node_id: expr, $old_monitors: expr, $keys_manager: expr, $fee_estimator: expr) => { {
430 let keys_manager = Arc::clone(& $keys_manager);
431 let logger: Arc<dyn Logger> = Arc::new(test_logger::TestLogger::new($node_id.to_string(), out.clone()));
432 let chain_monitor = Arc::new(TestChainMonitor::new(broadcast.clone(), logger.clone(), $fee_estimator.clone(),
433 Arc::new(TestPersister {
434 update_ret: Mutex::new(ChannelMonitorUpdateStatus::Completed)
435 }), Arc::clone(& $keys_manager)));
437 let mut config = UserConfig::default();
438 config.channel_config.forwarding_fee_proportional_millionths = 0;
439 config.channel_handshake_config.announced_channel = true;
441 let mut monitors = HashMap::new();
442 let mut old_monitors = $old_monitors.latest_monitors.lock().unwrap();
443 for (outpoint, (update_id, monitor_ser)) in old_monitors.drain() {
444 monitors.insert(outpoint, <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut Cursor::new(&monitor_ser), (&*$keys_manager, &*$keys_manager)).expect("Failed to read monitor").1);
445 chain_monitor.latest_monitors.lock().unwrap().insert(outpoint, (update_id, monitor_ser));
447 let mut monitor_refs = HashMap::new();
448 for (outpoint, monitor) in monitors.iter_mut() {
449 monitor_refs.insert(*outpoint, monitor);
452 let read_args = ChannelManagerReadArgs {
453 entropy_source: keys_manager.clone(),
454 node_signer: keys_manager.clone(),
455 signer_provider: keys_manager.clone(),
456 fee_estimator: $fee_estimator.clone(),
457 chain_monitor: chain_monitor.clone(),
458 tx_broadcaster: broadcast.clone(),
461 default_config: config,
462 channel_monitors: monitor_refs,
465 let res = (<(BlockHash, ChanMan)>::read(&mut Cursor::new(&$ser.0), read_args).expect("Failed to read manager").1, chain_monitor.clone());
466 for (funding_txo, mon) in monitors.drain() {
467 assert_eq!(chain_monitor.chain_monitor.watch_channel(funding_txo, mon),
468 ChannelMonitorUpdateStatus::Completed);
474 let mut channel_txn = Vec::new();
475 macro_rules! make_channel {
476 ($source: expr, $dest: expr, $chan_id: expr) => { {
477 $source.peer_connected(&$dest.get_our_node_id(), &Init { features: $dest.init_features(), remote_network_address: None }, true).unwrap();
478 $dest.peer_connected(&$source.get_our_node_id(), &Init { features: $source.init_features(), remote_network_address: None }, false).unwrap();
480 $source.create_channel($dest.get_our_node_id(), 100_000, 42, 0, None).unwrap();
482 let events = $source.get_and_clear_pending_msg_events();
483 assert_eq!(events.len(), 1);
484 if let events::MessageSendEvent::SendOpenChannel { ref msg, .. } = events[0] {
486 } else { panic!("Wrong event type"); }
489 $dest.handle_open_channel(&$source.get_our_node_id(), &open_channel);
490 let accept_channel = {
491 let events = $dest.get_and_clear_pending_msg_events();
492 assert_eq!(events.len(), 1);
493 if let events::MessageSendEvent::SendAcceptChannel { ref msg, .. } = events[0] {
495 } else { panic!("Wrong event type"); }
498 $source.handle_accept_channel(&$dest.get_our_node_id(), &accept_channel);
501 let events = $source.get_and_clear_pending_events();
502 assert_eq!(events.len(), 1);
503 if let events::Event::FundingGenerationReady { ref temporary_channel_id, ref channel_value_satoshis, ref output_script, .. } = events[0] {
504 let tx = Transaction { version: $chan_id, lock_time: PackedLockTime::ZERO, input: Vec::new(), output: vec![TxOut {
505 value: *channel_value_satoshis, script_pubkey: output_script.clone(),
507 funding_output = OutPoint { txid: tx.txid(), index: 0 };
508 $source.funding_transaction_generated(&temporary_channel_id, &$dest.get_our_node_id(), tx.clone()).unwrap();
509 channel_txn.push(tx);
510 } else { panic!("Wrong event type"); }
513 let funding_created = {
514 let events = $source.get_and_clear_pending_msg_events();
515 assert_eq!(events.len(), 1);
516 if let events::MessageSendEvent::SendFundingCreated { ref msg, .. } = events[0] {
518 } else { panic!("Wrong event type"); }
520 $dest.handle_funding_created(&$source.get_our_node_id(), &funding_created);
522 let funding_signed = {
523 let events = $dest.get_and_clear_pending_msg_events();
524 assert_eq!(events.len(), 1);
525 if let events::MessageSendEvent::SendFundingSigned { ref msg, .. } = events[0] {
527 } else { panic!("Wrong event type"); }
529 $source.handle_funding_signed(&$dest.get_our_node_id(), &funding_signed);
535 macro_rules! confirm_txn {
537 let chain_hash = genesis_block(Network::Bitcoin).block_hash();
538 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: chain_hash, merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
539 let txdata: Vec<_> = channel_txn.iter().enumerate().map(|(i, tx)| (i + 1, tx)).collect();
540 $node.transactions_confirmed(&header, &txdata, 1);
542 header = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
544 $node.best_block_updated(&header, 99);
548 macro_rules! lock_fundings {
549 ($nodes: expr) => { {
550 let mut node_events = Vec::new();
551 for node in $nodes.iter() {
552 node_events.push(node.get_and_clear_pending_msg_events());
554 for (idx, node_event) in node_events.iter().enumerate() {
555 for event in node_event {
556 if let events::MessageSendEvent::SendChannelReady { ref node_id, ref msg } = event {
557 for node in $nodes.iter() {
558 if node.get_our_node_id() == *node_id {
559 node.handle_channel_ready(&$nodes[idx].get_our_node_id(), msg);
562 } else { panic!("Wrong event type"); }
566 for node in $nodes.iter() {
567 let events = node.get_and_clear_pending_msg_events();
568 for event in events {
569 if let events::MessageSendEvent::SendAnnouncementSignatures { .. } = event {
570 } else { panic!("Wrong event type"); }
576 let fee_est_a = Arc::new(FuzzEstimator { ret_val: atomic::AtomicU32::new(253) });
577 let mut last_htlc_clear_fee_a = 253;
578 let fee_est_b = Arc::new(FuzzEstimator { ret_val: atomic::AtomicU32::new(253) });
579 let mut last_htlc_clear_fee_b = 253;
580 let fee_est_c = Arc::new(FuzzEstimator { ret_val: atomic::AtomicU32::new(253) });
581 let mut last_htlc_clear_fee_c = 253;
583 // 3 nodes is enough to hit all the possible cases, notably unknown-source-unknown-dest
585 let (node_a, mut monitor_a, keys_manager_a) = make_node!(0, fee_est_a);
586 let (node_b, mut monitor_b, keys_manager_b) = make_node!(1, fee_est_b);
587 let (node_c, mut monitor_c, keys_manager_c) = make_node!(2, fee_est_c);
589 let mut nodes = [node_a, node_b, node_c];
591 let chan_1_funding = make_channel!(nodes[0], nodes[1], 0);
592 let chan_2_funding = make_channel!(nodes[1], nodes[2], 1);
594 for node in nodes.iter() {
598 lock_fundings!(nodes);
600 let chan_a = nodes[0].list_usable_channels()[0].short_channel_id.unwrap();
601 let chan_b = nodes[2].list_usable_channels()[0].short_channel_id.unwrap();
603 let mut payment_id: u8 = 0;
604 let mut payment_idx: u64 = 0;
606 let mut chan_a_disconnected = false;
607 let mut chan_b_disconnected = false;
608 let mut ab_events = Vec::new();
609 let mut ba_events = Vec::new();
610 let mut bc_events = Vec::new();
611 let mut cb_events = Vec::new();
613 let mut node_a_ser = VecWriter(Vec::new());
614 nodes[0].write(&mut node_a_ser).unwrap();
615 let mut node_b_ser = VecWriter(Vec::new());
616 nodes[1].write(&mut node_b_ser).unwrap();
617 let mut node_c_ser = VecWriter(Vec::new());
618 nodes[2].write(&mut node_c_ser).unwrap();
620 macro_rules! test_return {
622 assert_eq!(nodes[0].list_channels().len(), 1);
623 assert_eq!(nodes[1].list_channels().len(), 2);
624 assert_eq!(nodes[2].list_channels().len(), 1);
629 let mut read_pos = 0;
630 macro_rules! get_slice {
633 let slice_len = $len as usize;
634 if data.len() < read_pos + slice_len {
637 read_pos += slice_len;
638 &data[read_pos - slice_len..read_pos]
644 // Push any events from Node B onto ba_events and bc_events
645 macro_rules! push_excess_b_events {
646 ($excess_events: expr, $expect_drop_node: expr) => { {
647 let a_id = nodes[0].get_our_node_id();
648 let expect_drop_node: Option<usize> = $expect_drop_node;
649 let expect_drop_id = if let Some(id) = expect_drop_node { Some(nodes[id].get_our_node_id()) } else { None };
650 for event in $excess_events {
651 let push_a = match event {
652 events::MessageSendEvent::UpdateHTLCs { ref node_id, .. } => {
653 if Some(*node_id) == expect_drop_id { panic!("peer_disconnected should drop msgs bound for the disconnected peer"); }
656 events::MessageSendEvent::SendRevokeAndACK { ref node_id, .. } => {
657 if Some(*node_id) == expect_drop_id { panic!("peer_disconnected should drop msgs bound for the disconnected peer"); }
660 events::MessageSendEvent::SendChannelReestablish { ref node_id, .. } => {
661 if Some(*node_id) == expect_drop_id { panic!("peer_disconnected should drop msgs bound for the disconnected peer"); }
664 events::MessageSendEvent::SendChannelReady { .. } => continue,
665 events::MessageSendEvent::SendAnnouncementSignatures { .. } => continue,
666 events::MessageSendEvent::SendChannelUpdate { ref node_id, ref msg } => {
667 assert_eq!(msg.contents.flags & 2, 0); // The disable bit must never be set!
668 if Some(*node_id) == expect_drop_id { panic!("peer_disconnected should drop msgs bound for the disconnected peer"); }
671 _ => panic!("Unhandled message event {:?}", event),
673 if push_a { ba_events.push(event); } else { bc_events.push(event); }
678 // While delivering messages, we select across three possible message selection processes
679 // to ensure we get as much coverage as possible. See the individual enum variants for more
682 enum ProcessMessages {
683 /// Deliver all available messages, including fetching any new messages from
684 /// `get_and_clear_pending_msg_events()` (which may have side effects).
686 /// Call `get_and_clear_pending_msg_events()` first, and then deliver up to one
687 /// message (which may already be queued).
689 /// Deliver up to one already-queued message. This avoids any potential side-effects
690 /// of `get_and_clear_pending_msg_events()` (eg freeing the HTLC holding cell), which
691 /// provides potentially more coverage.
695 macro_rules! process_msg_events {
696 ($node: expr, $corrupt_forward: expr, $limit_events: expr) => { {
697 let mut events = if $node == 1 {
698 let mut new_events = Vec::new();
699 mem::swap(&mut new_events, &mut ba_events);
700 new_events.extend_from_slice(&bc_events[..]);
703 } else if $node == 0 {
704 let mut new_events = Vec::new();
705 mem::swap(&mut new_events, &mut ab_events);
708 let mut new_events = Vec::new();
709 mem::swap(&mut new_events, &mut cb_events);
712 let mut new_events = Vec::new();
713 if $limit_events != ProcessMessages::OnePendingMessage {
714 new_events = nodes[$node].get_and_clear_pending_msg_events();
716 let mut had_events = false;
717 let mut events_iter = events.drain(..).chain(new_events.drain(..));
718 let mut extra_ev = None;
719 for event in &mut events_iter {
722 events::MessageSendEvent::UpdateHTLCs { node_id, updates: CommitmentUpdate { update_add_htlcs, update_fail_htlcs, update_fulfill_htlcs, update_fail_malformed_htlcs, update_fee, commitment_signed } } => {
723 for (idx, dest) in nodes.iter().enumerate() {
724 if dest.get_our_node_id() == node_id {
725 for update_add in update_add_htlcs.iter() {
726 out.locked_write(format!("Delivering update_add_htlc to node {}.\n", idx).as_bytes());
727 if !$corrupt_forward {
728 dest.handle_update_add_htlc(&nodes[$node].get_our_node_id(), update_add);
730 // Corrupt the update_add_htlc message so that its HMAC
731 // check will fail and we generate a
732 // update_fail_malformed_htlc instead of an
733 // update_fail_htlc as we do when we reject a payment.
734 let mut msg_ser = update_add.encode();
735 msg_ser[1000] ^= 0xff;
736 let new_msg = UpdateAddHTLC::read(&mut Cursor::new(&msg_ser)).unwrap();
737 dest.handle_update_add_htlc(&nodes[$node].get_our_node_id(), &new_msg);
740 for update_fulfill in update_fulfill_htlcs.iter() {
741 out.locked_write(format!("Delivering update_fulfill_htlc to node {}.\n", idx).as_bytes());
742 dest.handle_update_fulfill_htlc(&nodes[$node].get_our_node_id(), update_fulfill);
744 for update_fail in update_fail_htlcs.iter() {
745 out.locked_write(format!("Delivering update_fail_htlc to node {}.\n", idx).as_bytes());
746 dest.handle_update_fail_htlc(&nodes[$node].get_our_node_id(), update_fail);
748 for update_fail_malformed in update_fail_malformed_htlcs.iter() {
749 out.locked_write(format!("Delivering update_fail_malformed_htlc to node {}.\n", idx).as_bytes());
750 dest.handle_update_fail_malformed_htlc(&nodes[$node].get_our_node_id(), update_fail_malformed);
752 if let Some(msg) = update_fee {
753 out.locked_write(format!("Delivering update_fee to node {}.\n", idx).as_bytes());
754 dest.handle_update_fee(&nodes[$node].get_our_node_id(), &msg);
756 let processed_change = !update_add_htlcs.is_empty() || !update_fulfill_htlcs.is_empty() ||
757 !update_fail_htlcs.is_empty() || !update_fail_malformed_htlcs.is_empty();
758 if $limit_events != ProcessMessages::AllMessages && processed_change {
759 // If we only want to process some messages, don't deliver the CS until later.
760 extra_ev = Some(events::MessageSendEvent::UpdateHTLCs { node_id, updates: CommitmentUpdate {
761 update_add_htlcs: Vec::new(),
762 update_fail_htlcs: Vec::new(),
763 update_fulfill_htlcs: Vec::new(),
764 update_fail_malformed_htlcs: Vec::new(),
770 out.locked_write(format!("Delivering commitment_signed to node {}.\n", idx).as_bytes());
771 dest.handle_commitment_signed(&nodes[$node].get_our_node_id(), &commitment_signed);
776 events::MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
777 for (idx, dest) in nodes.iter().enumerate() {
778 if dest.get_our_node_id() == *node_id {
779 out.locked_write(format!("Delivering revoke_and_ack to node {}.\n", idx).as_bytes());
780 dest.handle_revoke_and_ack(&nodes[$node].get_our_node_id(), msg);
784 events::MessageSendEvent::SendChannelReestablish { ref node_id, ref msg } => {
785 for (idx, dest) in nodes.iter().enumerate() {
786 if dest.get_our_node_id() == *node_id {
787 out.locked_write(format!("Delivering channel_reestablish to node {}.\n", idx).as_bytes());
788 dest.handle_channel_reestablish(&nodes[$node].get_our_node_id(), msg);
792 events::MessageSendEvent::SendChannelReady { .. } => {
793 // Can be generated as a reestablish response
795 events::MessageSendEvent::SendAnnouncementSignatures { .. } => {
796 // Can be generated as a reestablish response
798 events::MessageSendEvent::SendChannelUpdate { ref msg, .. } => {
799 // When we reconnect we will resend a channel_update to make sure our
800 // counterparty has the latest parameters for receiving payments
801 // through us. We do, however, check that the message does not include
802 // the "disabled" bit, as we should never ever have a channel which is
803 // disabled when we send such an update (or it may indicate channel
804 // force-close which we should detect as an error).
805 assert_eq!(msg.contents.flags & 2, 0);
807 _ => if out.may_fail.load(atomic::Ordering::Acquire) {
810 panic!("Unhandled message event {:?}", event)
813 if $limit_events != ProcessMessages::AllMessages {
818 push_excess_b_events!(extra_ev.into_iter().chain(events_iter), None);
819 } else if $node == 0 {
820 if let Some(ev) = extra_ev { ab_events.push(ev); }
821 for event in events_iter { ab_events.push(event); }
823 if let Some(ev) = extra_ev { cb_events.push(ev); }
824 for event in events_iter { cb_events.push(event); }
830 macro_rules! drain_msg_events_on_disconnect {
831 ($counterparty_id: expr) => { {
832 if $counterparty_id == 0 {
833 for event in nodes[0].get_and_clear_pending_msg_events() {
835 events::MessageSendEvent::UpdateHTLCs { .. } => {},
836 events::MessageSendEvent::SendRevokeAndACK { .. } => {},
837 events::MessageSendEvent::SendChannelReestablish { .. } => {},
838 events::MessageSendEvent::SendChannelReady { .. } => {},
839 events::MessageSendEvent::SendAnnouncementSignatures { .. } => {},
840 events::MessageSendEvent::SendChannelUpdate { ref msg, .. } => {
841 assert_eq!(msg.contents.flags & 2, 0); // The disable bit must never be set!
843 _ => if out.may_fail.load(atomic::Ordering::Acquire) {
846 panic!("Unhandled message event")
850 push_excess_b_events!(nodes[1].get_and_clear_pending_msg_events().drain(..), Some(0));
854 for event in nodes[2].get_and_clear_pending_msg_events() {
856 events::MessageSendEvent::UpdateHTLCs { .. } => {},
857 events::MessageSendEvent::SendRevokeAndACK { .. } => {},
858 events::MessageSendEvent::SendChannelReestablish { .. } => {},
859 events::MessageSendEvent::SendChannelReady { .. } => {},
860 events::MessageSendEvent::SendAnnouncementSignatures { .. } => {},
861 events::MessageSendEvent::SendChannelUpdate { ref msg, .. } => {
862 assert_eq!(msg.contents.flags & 2, 0); // The disable bit must never be set!
864 _ => if out.may_fail.load(atomic::Ordering::Acquire) {
867 panic!("Unhandled message event")
871 push_excess_b_events!(nodes[1].get_and_clear_pending_msg_events().drain(..), Some(2));
878 macro_rules! process_events {
879 ($node: expr, $fail: expr) => { {
880 // In case we get 256 payments we may have a hash collision, resulting in the
881 // second claim/fail call not finding the duplicate-hash HTLC, so we have to
882 // deduplicate the calls here.
883 let mut claim_set = HashSet::new();
884 let mut events = nodes[$node].get_and_clear_pending_events();
885 // Sort events so that PendingHTLCsForwardable get processed last. This avoids a
886 // case where we first process a PendingHTLCsForwardable, then claim/fail on a
887 // PaymentClaimable, claiming/failing two HTLCs, but leaving a just-generated
888 // PaymentClaimable event for the second HTLC in our pending_events (and breaking
889 // our claim_set deduplication).
890 events.sort_by(|a, b| {
891 if let events::Event::PaymentClaimable { .. } = a {
892 if let events::Event::PendingHTLCsForwardable { .. } = b {
894 } else { Ordering::Equal }
895 } else if let events::Event::PendingHTLCsForwardable { .. } = a {
896 if let events::Event::PaymentClaimable { .. } = b {
898 } else { Ordering::Equal }
899 } else { Ordering::Equal }
901 let had_events = !events.is_empty();
902 for event in events.drain(..) {
904 events::Event::PaymentClaimable { payment_hash, .. } => {
905 if claim_set.insert(payment_hash.0) {
907 nodes[$node].fail_htlc_backwards(&payment_hash);
909 nodes[$node].claim_funds(PaymentPreimage(payment_hash.0));
913 events::Event::PaymentSent { .. } => {},
914 events::Event::PaymentClaimed { .. } => {},
915 events::Event::PaymentPathSuccessful { .. } => {},
916 events::Event::PaymentPathFailed { .. } => {},
917 events::Event::PaymentFailed { .. } => {},
918 events::Event::ProbeSuccessful { .. } | events::Event::ProbeFailed { .. } => {
919 // Even though we don't explicitly send probes, because probes are
920 // detected based on hashing the payment hash+preimage, its rather
921 // trivial for the fuzzer to build payments that accidentally end up
922 // looking like probes.
924 events::Event::PaymentForwarded { .. } if $node == 1 => {},
925 events::Event::ChannelReady { .. } => {},
926 events::Event::PendingHTLCsForwardable { .. } => {
927 nodes[$node].process_pending_htlc_forwards();
929 events::Event::HTLCHandlingFailed { .. } => {},
930 _ => if out.may_fail.load(atomic::Ordering::Acquire) {
933 panic!("Unhandled event")
941 let v = get_slice!(1)[0];
942 out.locked_write(format!("READ A BYTE! HANDLING INPUT {:x}...........\n", v).as_bytes());
944 // In general, we keep related message groups close together in binary form, allowing
945 // bit-twiddling mutations to have similar effects. This is probably overkill, but no
948 0x00 => *monitor_a.persister.update_ret.lock().unwrap() = ChannelMonitorUpdateStatus::InProgress,
949 0x01 => *monitor_b.persister.update_ret.lock().unwrap() = ChannelMonitorUpdateStatus::InProgress,
950 0x02 => *monitor_c.persister.update_ret.lock().unwrap() = ChannelMonitorUpdateStatus::InProgress,
951 0x04 => *monitor_a.persister.update_ret.lock().unwrap() = ChannelMonitorUpdateStatus::Completed,
952 0x05 => *monitor_b.persister.update_ret.lock().unwrap() = ChannelMonitorUpdateStatus::Completed,
953 0x06 => *monitor_c.persister.update_ret.lock().unwrap() = ChannelMonitorUpdateStatus::Completed,
956 if let Some((id, _)) = monitor_a.latest_monitors.lock().unwrap().get(&chan_1_funding) {
957 monitor_a.chain_monitor.force_channel_monitor_updated(chan_1_funding, *id);
958 nodes[0].process_monitor_events();
962 if let Some((id, _)) = monitor_b.latest_monitors.lock().unwrap().get(&chan_1_funding) {
963 monitor_b.chain_monitor.force_channel_monitor_updated(chan_1_funding, *id);
964 nodes[1].process_monitor_events();
968 if let Some((id, _)) = monitor_b.latest_monitors.lock().unwrap().get(&chan_2_funding) {
969 monitor_b.chain_monitor.force_channel_monitor_updated(chan_2_funding, *id);
970 nodes[1].process_monitor_events();
974 if let Some((id, _)) = monitor_c.latest_monitors.lock().unwrap().get(&chan_2_funding) {
975 monitor_c.chain_monitor.force_channel_monitor_updated(chan_2_funding, *id);
976 nodes[2].process_monitor_events();
981 if !chan_a_disconnected {
982 nodes[0].peer_disconnected(&nodes[1].get_our_node_id());
983 nodes[1].peer_disconnected(&nodes[0].get_our_node_id());
984 chan_a_disconnected = true;
985 drain_msg_events_on_disconnect!(0);
989 if !chan_b_disconnected {
990 nodes[1].peer_disconnected(&nodes[2].get_our_node_id());
991 nodes[2].peer_disconnected(&nodes[1].get_our_node_id());
992 chan_b_disconnected = true;
993 drain_msg_events_on_disconnect!(2);
997 if chan_a_disconnected {
998 nodes[0].peer_connected(&nodes[1].get_our_node_id(), &Init { features: nodes[1].init_features(), remote_network_address: None }, true).unwrap();
999 nodes[1].peer_connected(&nodes[0].get_our_node_id(), &Init { features: nodes[0].init_features(), remote_network_address: None }, false).unwrap();
1000 chan_a_disconnected = false;
1004 if chan_b_disconnected {
1005 nodes[1].peer_connected(&nodes[2].get_our_node_id(), &Init { features: nodes[2].init_features(), remote_network_address: None }, true).unwrap();
1006 nodes[2].peer_connected(&nodes[1].get_our_node_id(), &Init { features: nodes[1].init_features(), remote_network_address: None }, false).unwrap();
1007 chan_b_disconnected = false;
1011 0x10 => { process_msg_events!(0, true, ProcessMessages::AllMessages); },
1012 0x11 => { process_msg_events!(0, false, ProcessMessages::AllMessages); },
1013 0x12 => { process_msg_events!(0, true, ProcessMessages::OneMessage); },
1014 0x13 => { process_msg_events!(0, false, ProcessMessages::OneMessage); },
1015 0x14 => { process_msg_events!(0, true, ProcessMessages::OnePendingMessage); },
1016 0x15 => { process_msg_events!(0, false, ProcessMessages::OnePendingMessage); },
1018 0x16 => { process_events!(0, true); },
1019 0x17 => { process_events!(0, false); },
1021 0x18 => { process_msg_events!(1, true, ProcessMessages::AllMessages); },
1022 0x19 => { process_msg_events!(1, false, ProcessMessages::AllMessages); },
1023 0x1a => { process_msg_events!(1, true, ProcessMessages::OneMessage); },
1024 0x1b => { process_msg_events!(1, false, ProcessMessages::OneMessage); },
1025 0x1c => { process_msg_events!(1, true, ProcessMessages::OnePendingMessage); },
1026 0x1d => { process_msg_events!(1, false, ProcessMessages::OnePendingMessage); },
1028 0x1e => { process_events!(1, true); },
1029 0x1f => { process_events!(1, false); },
1031 0x20 => { process_msg_events!(2, true, ProcessMessages::AllMessages); },
1032 0x21 => { process_msg_events!(2, false, ProcessMessages::AllMessages); },
1033 0x22 => { process_msg_events!(2, true, ProcessMessages::OneMessage); },
1034 0x23 => { process_msg_events!(2, false, ProcessMessages::OneMessage); },
1035 0x24 => { process_msg_events!(2, true, ProcessMessages::OnePendingMessage); },
1036 0x25 => { process_msg_events!(2, false, ProcessMessages::OnePendingMessage); },
1038 0x26 => { process_events!(2, true); },
1039 0x27 => { process_events!(2, false); },
1042 if !chan_a_disconnected {
1043 nodes[1].peer_disconnected(&nodes[0].get_our_node_id());
1044 chan_a_disconnected = true;
1045 drain_msg_events_on_disconnect!(0);
1047 if monitor_a.should_update_manager.load(atomic::Ordering::Relaxed) {
1048 node_a_ser.0.clear();
1049 nodes[0].write(&mut node_a_ser).unwrap();
1051 let (new_node_a, new_monitor_a) = reload_node!(node_a_ser, 0, monitor_a, keys_manager_a, fee_est_a);
1052 nodes[0] = new_node_a;
1053 monitor_a = new_monitor_a;
1056 if !chan_a_disconnected {
1057 nodes[0].peer_disconnected(&nodes[1].get_our_node_id());
1058 chan_a_disconnected = true;
1059 nodes[0].get_and_clear_pending_msg_events();
1063 if !chan_b_disconnected {
1064 nodes[2].peer_disconnected(&nodes[1].get_our_node_id());
1065 chan_b_disconnected = true;
1066 nodes[2].get_and_clear_pending_msg_events();
1070 let (new_node_b, new_monitor_b) = reload_node!(node_b_ser, 1, monitor_b, keys_manager_b, fee_est_b);
1071 nodes[1] = new_node_b;
1072 monitor_b = new_monitor_b;
1075 if !chan_b_disconnected {
1076 nodes[1].peer_disconnected(&nodes[2].get_our_node_id());
1077 chan_b_disconnected = true;
1078 drain_msg_events_on_disconnect!(2);
1080 if monitor_c.should_update_manager.load(atomic::Ordering::Relaxed) {
1081 node_c_ser.0.clear();
1082 nodes[2].write(&mut node_c_ser).unwrap();
1084 let (new_node_c, new_monitor_c) = reload_node!(node_c_ser, 2, monitor_c, keys_manager_c, fee_est_c);
1085 nodes[2] = new_node_c;
1086 monitor_c = new_monitor_c;
1089 // 1/10th the channel size:
1090 0x30 => { send_payment(&nodes[0], &nodes[1], chan_a, 10_000_000, &mut payment_id, &mut payment_idx); },
1091 0x31 => { send_payment(&nodes[1], &nodes[0], chan_a, 10_000_000, &mut payment_id, &mut payment_idx); },
1092 0x32 => { send_payment(&nodes[1], &nodes[2], chan_b, 10_000_000, &mut payment_id, &mut payment_idx); },
1093 0x33 => { send_payment(&nodes[2], &nodes[1], chan_b, 10_000_000, &mut payment_id, &mut payment_idx); },
1094 0x34 => { send_hop_payment(&nodes[0], &nodes[1], chan_a, &nodes[2], chan_b, 10_000_000, &mut payment_id, &mut payment_idx); },
1095 0x35 => { send_hop_payment(&nodes[2], &nodes[1], chan_b, &nodes[0], chan_a, 10_000_000, &mut payment_id, &mut payment_idx); },
1097 0x38 => { send_payment(&nodes[0], &nodes[1], chan_a, 1_000_000, &mut payment_id, &mut payment_idx); },
1098 0x39 => { send_payment(&nodes[1], &nodes[0], chan_a, 1_000_000, &mut payment_id, &mut payment_idx); },
1099 0x3a => { send_payment(&nodes[1], &nodes[2], chan_b, 1_000_000, &mut payment_id, &mut payment_idx); },
1100 0x3b => { send_payment(&nodes[2], &nodes[1], chan_b, 1_000_000, &mut payment_id, &mut payment_idx); },
1101 0x3c => { send_hop_payment(&nodes[0], &nodes[1], chan_a, &nodes[2], chan_b, 1_000_000, &mut payment_id, &mut payment_idx); },
1102 0x3d => { send_hop_payment(&nodes[2], &nodes[1], chan_b, &nodes[0], chan_a, 1_000_000, &mut payment_id, &mut payment_idx); },
1104 0x40 => { send_payment(&nodes[0], &nodes[1], chan_a, 100_000, &mut payment_id, &mut payment_idx); },
1105 0x41 => { send_payment(&nodes[1], &nodes[0], chan_a, 100_000, &mut payment_id, &mut payment_idx); },
1106 0x42 => { send_payment(&nodes[1], &nodes[2], chan_b, 100_000, &mut payment_id, &mut payment_idx); },
1107 0x43 => { send_payment(&nodes[2], &nodes[1], chan_b, 100_000, &mut payment_id, &mut payment_idx); },
1108 0x44 => { send_hop_payment(&nodes[0], &nodes[1], chan_a, &nodes[2], chan_b, 100_000, &mut payment_id, &mut payment_idx); },
1109 0x45 => { send_hop_payment(&nodes[2], &nodes[1], chan_b, &nodes[0], chan_a, 100_000, &mut payment_id, &mut payment_idx); },
1111 0x48 => { send_payment(&nodes[0], &nodes[1], chan_a, 10_000, &mut payment_id, &mut payment_idx); },
1112 0x49 => { send_payment(&nodes[1], &nodes[0], chan_a, 10_000, &mut payment_id, &mut payment_idx); },
1113 0x4a => { send_payment(&nodes[1], &nodes[2], chan_b, 10_000, &mut payment_id, &mut payment_idx); },
1114 0x4b => { send_payment(&nodes[2], &nodes[1], chan_b, 10_000, &mut payment_id, &mut payment_idx); },
1115 0x4c => { send_hop_payment(&nodes[0], &nodes[1], chan_a, &nodes[2], chan_b, 10_000, &mut payment_id, &mut payment_idx); },
1116 0x4d => { send_hop_payment(&nodes[2], &nodes[1], chan_b, &nodes[0], chan_a, 10_000, &mut payment_id, &mut payment_idx); },
1118 0x50 => { send_payment(&nodes[0], &nodes[1], chan_a, 1_000, &mut payment_id, &mut payment_idx); },
1119 0x51 => { send_payment(&nodes[1], &nodes[0], chan_a, 1_000, &mut payment_id, &mut payment_idx); },
1120 0x52 => { send_payment(&nodes[1], &nodes[2], chan_b, 1_000, &mut payment_id, &mut payment_idx); },
1121 0x53 => { send_payment(&nodes[2], &nodes[1], chan_b, 1_000, &mut payment_id, &mut payment_idx); },
1122 0x54 => { send_hop_payment(&nodes[0], &nodes[1], chan_a, &nodes[2], chan_b, 1_000, &mut payment_id, &mut payment_idx); },
1123 0x55 => { send_hop_payment(&nodes[2], &nodes[1], chan_b, &nodes[0], chan_a, 1_000, &mut payment_id, &mut payment_idx); },
1125 0x58 => { send_payment(&nodes[0], &nodes[1], chan_a, 100, &mut payment_id, &mut payment_idx); },
1126 0x59 => { send_payment(&nodes[1], &nodes[0], chan_a, 100, &mut payment_id, &mut payment_idx); },
1127 0x5a => { send_payment(&nodes[1], &nodes[2], chan_b, 100, &mut payment_id, &mut payment_idx); },
1128 0x5b => { send_payment(&nodes[2], &nodes[1], chan_b, 100, &mut payment_id, &mut payment_idx); },
1129 0x5c => { send_hop_payment(&nodes[0], &nodes[1], chan_a, &nodes[2], chan_b, 100, &mut payment_id, &mut payment_idx); },
1130 0x5d => { send_hop_payment(&nodes[2], &nodes[1], chan_b, &nodes[0], chan_a, 100, &mut payment_id, &mut payment_idx); },
1132 0x60 => { send_payment(&nodes[0], &nodes[1], chan_a, 10, &mut payment_id, &mut payment_idx); },
1133 0x61 => { send_payment(&nodes[1], &nodes[0], chan_a, 10, &mut payment_id, &mut payment_idx); },
1134 0x62 => { send_payment(&nodes[1], &nodes[2], chan_b, 10, &mut payment_id, &mut payment_idx); },
1135 0x63 => { send_payment(&nodes[2], &nodes[1], chan_b, 10, &mut payment_id, &mut payment_idx); },
1136 0x64 => { send_hop_payment(&nodes[0], &nodes[1], chan_a, &nodes[2], chan_b, 10, &mut payment_id, &mut payment_idx); },
1137 0x65 => { send_hop_payment(&nodes[2], &nodes[1], chan_b, &nodes[0], chan_a, 10, &mut payment_id, &mut payment_idx); },
1139 0x68 => { send_payment(&nodes[0], &nodes[1], chan_a, 1, &mut payment_id, &mut payment_idx); },
1140 0x69 => { send_payment(&nodes[1], &nodes[0], chan_a, 1, &mut payment_id, &mut payment_idx); },
1141 0x6a => { send_payment(&nodes[1], &nodes[2], chan_b, 1, &mut payment_id, &mut payment_idx); },
1142 0x6b => { send_payment(&nodes[2], &nodes[1], chan_b, 1, &mut payment_id, &mut payment_idx); },
1143 0x6c => { send_hop_payment(&nodes[0], &nodes[1], chan_a, &nodes[2], chan_b, 1, &mut payment_id, &mut payment_idx); },
1144 0x6d => { send_hop_payment(&nodes[2], &nodes[1], chan_b, &nodes[0], chan_a, 1, &mut payment_id, &mut payment_idx); },
1147 let max_feerate = last_htlc_clear_fee_a * FEE_SPIKE_BUFFER_FEE_INCREASE_MULTIPLE as u32;
1148 if fee_est_a.ret_val.fetch_add(250, atomic::Ordering::AcqRel) + 250 > max_feerate {
1149 fee_est_a.ret_val.store(max_feerate, atomic::Ordering::Release);
1151 nodes[0].maybe_update_chan_fees();
1153 0x81 => { fee_est_a.ret_val.store(253, atomic::Ordering::Release); nodes[0].maybe_update_chan_fees(); },
1156 let max_feerate = last_htlc_clear_fee_b * FEE_SPIKE_BUFFER_FEE_INCREASE_MULTIPLE as u32;
1157 if fee_est_b.ret_val.fetch_add(250, atomic::Ordering::AcqRel) + 250 > max_feerate {
1158 fee_est_b.ret_val.store(max_feerate, atomic::Ordering::Release);
1160 nodes[1].maybe_update_chan_fees();
1162 0x85 => { fee_est_b.ret_val.store(253, atomic::Ordering::Release); nodes[1].maybe_update_chan_fees(); },
1165 let max_feerate = last_htlc_clear_fee_c * FEE_SPIKE_BUFFER_FEE_INCREASE_MULTIPLE as u32;
1166 if fee_est_c.ret_val.fetch_add(250, atomic::Ordering::AcqRel) + 250 > max_feerate {
1167 fee_est_c.ret_val.store(max_feerate, atomic::Ordering::Release);
1169 nodes[2].maybe_update_chan_fees();
1171 0x89 => { fee_est_c.ret_val.store(253, atomic::Ordering::Release); nodes[2].maybe_update_chan_fees(); },
1174 // Test that no channel is in a stuck state where neither party can send funds even
1175 // after we resolve all pending events.
1176 // First make sure there are no pending monitor updates, resetting the error state
1177 // and calling force_channel_monitor_updated for each monitor.
1178 *monitor_a.persister.update_ret.lock().unwrap() = ChannelMonitorUpdateStatus::Completed;
1179 *monitor_b.persister.update_ret.lock().unwrap() = ChannelMonitorUpdateStatus::Completed;
1180 *monitor_c.persister.update_ret.lock().unwrap() = ChannelMonitorUpdateStatus::Completed;
1182 if let Some((id, _)) = monitor_a.latest_monitors.lock().unwrap().get(&chan_1_funding) {
1183 monitor_a.chain_monitor.force_channel_monitor_updated(chan_1_funding, *id);
1184 nodes[0].process_monitor_events();
1186 if let Some((id, _)) = monitor_b.latest_monitors.lock().unwrap().get(&chan_1_funding) {
1187 monitor_b.chain_monitor.force_channel_monitor_updated(chan_1_funding, *id);
1188 nodes[1].process_monitor_events();
1190 if let Some((id, _)) = monitor_b.latest_monitors.lock().unwrap().get(&chan_2_funding) {
1191 monitor_b.chain_monitor.force_channel_monitor_updated(chan_2_funding, *id);
1192 nodes[1].process_monitor_events();
1194 if let Some((id, _)) = monitor_c.latest_monitors.lock().unwrap().get(&chan_2_funding) {
1195 monitor_c.chain_monitor.force_channel_monitor_updated(chan_2_funding, *id);
1196 nodes[2].process_monitor_events();
1199 // Next, make sure peers are all connected to each other
1200 if chan_a_disconnected {
1201 nodes[0].peer_connected(&nodes[1].get_our_node_id(), &Init { features: nodes[1].init_features(), remote_network_address: None }, true).unwrap();
1202 nodes[1].peer_connected(&nodes[0].get_our_node_id(), &Init { features: nodes[0].init_features(), remote_network_address: None }, false).unwrap();
1203 chan_a_disconnected = false;
1205 if chan_b_disconnected {
1206 nodes[1].peer_connected(&nodes[2].get_our_node_id(), &Init { features: nodes[2].init_features(), remote_network_address: None }, true).unwrap();
1207 nodes[2].peer_connected(&nodes[1].get_our_node_id(), &Init { features: nodes[1].init_features(), remote_network_address: None }, false).unwrap();
1208 chan_b_disconnected = false;
1211 for i in 0..std::usize::MAX {
1212 if i == 100 { panic!("It may take may iterations to settle the state, but it should not take forever"); }
1213 // Then, make sure any current forwards make their way to their destination
1214 if process_msg_events!(0, false, ProcessMessages::AllMessages) { continue; }
1215 if process_msg_events!(1, false, ProcessMessages::AllMessages) { continue; }
1216 if process_msg_events!(2, false, ProcessMessages::AllMessages) { continue; }
1217 // ...making sure any pending PendingHTLCsForwardable events are handled and
1218 // payments claimed.
1219 if process_events!(0, false) { continue; }
1220 if process_events!(1, false) { continue; }
1221 if process_events!(2, false) { continue; }
1225 // Finally, make sure that at least one end of each channel can make a substantial payment
1227 send_payment(&nodes[0], &nodes[1], chan_a, 10_000_000, &mut payment_id, &mut payment_idx) ||
1228 send_payment(&nodes[1], &nodes[0], chan_a, 10_000_000, &mut payment_id, &mut payment_idx));
1230 send_payment(&nodes[1], &nodes[2], chan_b, 10_000_000, &mut payment_id, &mut payment_idx) ||
1231 send_payment(&nodes[2], &nodes[1], chan_b, 10_000_000, &mut payment_id, &mut payment_idx));
1233 last_htlc_clear_fee_a = fee_est_a.ret_val.load(atomic::Ordering::Acquire);
1234 last_htlc_clear_fee_b = fee_est_b.ret_val.load(atomic::Ordering::Acquire);
1235 last_htlc_clear_fee_c = fee_est_c.ret_val.load(atomic::Ordering::Acquire);
1237 _ => test_return!(),
1240 node_a_ser.0.clear();
1241 nodes[0].write(&mut node_a_ser).unwrap();
1242 monitor_a.should_update_manager.store(false, atomic::Ordering::Relaxed);
1243 node_b_ser.0.clear();
1244 nodes[1].write(&mut node_b_ser).unwrap();
1245 monitor_b.should_update_manager.store(false, atomic::Ordering::Relaxed);
1246 node_c_ser.0.clear();
1247 nodes[2].write(&mut node_c_ser).unwrap();
1248 monitor_c.should_update_manager.store(false, atomic::Ordering::Relaxed);
1252 /// We actually have different behavior based on if a certain log string has been seen, so we have
1253 /// to do a bit more tracking.
1255 struct SearchingOutput<O: Output> {
1257 may_fail: Arc<atomic::AtomicBool>,
1259 impl<O: Output> Output for SearchingOutput<O> {
1260 fn locked_write(&self, data: &[u8]) {
1261 // We hit a design limitation of LN state machine (see CONCURRENT_INBOUND_HTLC_FEE_BUFFER)
1262 if std::str::from_utf8(data).unwrap().contains("Outbound update_fee HTLC buffer overflow - counterparty should force-close this channel") {
1263 self.may_fail.store(true, atomic::Ordering::Release);
1265 self.output.locked_write(data)
1268 impl<O: Output> SearchingOutput<O> {
1269 pub fn new(output: O) -> Self {
1270 Self { output, may_fail: Arc::new(atomic::AtomicBool::new(false)) }
1274 pub fn chanmon_consistency_test<Out: Output>(data: &[u8], out: Out) {
1279 pub extern "C" fn chanmon_consistency_run(data: *const u8, datalen: usize) {
1280 do_test(unsafe { std::slice::from_raw_parts(data, datalen) }, test_logger::DevNull{});