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::amount::Amount;
22 use bitcoin::blockdata::constants::genesis_block;
23 use bitcoin::blockdata::transaction::{Transaction, TxOut};
24 use bitcoin::blockdata::script::{Builder, ScriptBuf};
25 use bitcoin::blockdata::opcodes;
26 use bitcoin::blockdata::locktime::absolute::LockTime;
27 use bitcoin::network::Network;
28 use bitcoin::transaction::Version;
30 use bitcoin::WPubkeyHash;
31 use bitcoin::hashes::Hash as TraitImport;
32 use bitcoin::hashes::sha256::Hash as Sha256;
33 use bitcoin::hashes::sha256d::Hash as Sha256dHash;
34 use bitcoin::hash_types::BlockHash;
36 use lightning::blinded_path::BlindedPath;
37 use lightning::blinded_path::payment::ReceiveTlvs;
39 use lightning::chain::{BestBlock, ChannelMonitorUpdateStatus, chainmonitor, channelmonitor, Confirm, Watch};
40 use lightning::chain::channelmonitor::{ChannelMonitor, MonitorEvent};
41 use lightning::chain::transaction::OutPoint;
42 use lightning::chain::chaininterface::{BroadcasterInterface, ConfirmationTarget, FeeEstimator};
43 use lightning::sign::{KeyMaterial, InMemorySigner, Recipient, EntropySource, NodeSigner, SignerProvider};
44 use lightning::events;
45 use lightning::events::MessageSendEventsProvider;
46 use lightning::ln::{ChannelId, PaymentHash, PaymentPreimage, PaymentSecret};
47 use lightning::ln::channel_state::ChannelDetails;
48 use lightning::ln::channelmanager::{ChainParameters,ChannelManager, PaymentSendFailure, ChannelManagerReadArgs, PaymentId, RecipientOnionFields};
49 use lightning::ln::channel::FEE_SPIKE_BUFFER_FEE_INCREASE_MULTIPLE;
50 use lightning::ln::msgs::{self, CommitmentUpdate, ChannelMessageHandler, DecodeError, UpdateAddHTLC, Init};
51 use lightning::ln::script::ShutdownScript;
52 use lightning::ln::functional_test_utils::*;
53 use lightning::offers::invoice::{BlindedPayInfo, UnsignedBolt12Invoice};
54 use lightning::offers::invoice_request::UnsignedInvoiceRequest;
55 use lightning::onion_message::messenger::{Destination, MessageRouter, OnionMessagePath};
56 use lightning::util::test_channel_signer::{TestChannelSigner, EnforcementState};
57 use lightning::util::errors::APIError;
58 use lightning::util::hash_tables::*;
59 use lightning::util::logger::Logger;
60 use lightning::util::config::UserConfig;
61 use lightning::util::ser::{Readable, ReadableArgs, Writeable, Writer};
62 use lightning::routing::router::{InFlightHtlcs, Path, Route, RouteHop, RouteParameters, Router};
64 use crate::utils::test_logger::{self, Output};
65 use crate::utils::test_persister::TestPersister;
67 use bitcoin::secp256k1::{Message, PublicKey, SecretKey, Scalar, Secp256k1, self};
68 use bitcoin::secp256k1::ecdh::SharedSecret;
69 use bitcoin::secp256k1::ecdsa::{RecoverableSignature, Signature};
70 use bitcoin::secp256k1::schnorr;
73 use std::cmp::{self, Ordering};
74 use std::sync::{Arc,Mutex};
75 use std::sync::atomic;
79 const MAX_FEE: u32 = 10_000;
80 struct FuzzEstimator {
81 ret_val: atomic::AtomicU32,
83 impl FeeEstimator for FuzzEstimator {
84 fn get_est_sat_per_1000_weight(&self, conf_target: ConfirmationTarget) -> u32 {
85 // We force-close channels if our counterparty sends us a feerate which is a small multiple
86 // of our HighPriority fee estimate or smaller than our Background fee estimate. Thus, we
87 // always return a HighPriority feerate here which is >= the maximum Normal feerate and a
88 // Background feerate which is <= the minimum Normal feerate.
90 ConfirmationTarget::OnChainSweep => MAX_FEE,
91 ConfirmationTarget::ChannelCloseMinimum|ConfirmationTarget::AnchorChannelFee|ConfirmationTarget::MinAllowedAnchorChannelRemoteFee|ConfirmationTarget::MinAllowedNonAnchorChannelRemoteFee|ConfirmationTarget::OutputSpendingFee => 253,
92 ConfirmationTarget::NonAnchorChannelFee => cmp::min(self.ret_val.load(atomic::Ordering::Acquire), MAX_FEE),
99 impl Router for FuzzRouter {
101 &self, _payer: &PublicKey, _params: &RouteParameters, _first_hops: Option<&[&ChannelDetails]>,
102 _inflight_htlcs: InFlightHtlcs
103 ) -> Result<Route, msgs::LightningError> {
104 Err(msgs::LightningError {
105 err: String::from("Not implemented"),
106 action: msgs::ErrorAction::IgnoreError
110 fn create_blinded_payment_paths<T: secp256k1::Signing + secp256k1::Verification>(
111 &self, _recipient: PublicKey, _first_hops: Vec<ChannelDetails>, _tlvs: ReceiveTlvs,
112 _amount_msats: u64, _secp_ctx: &Secp256k1<T>,
113 ) -> Result<Vec<(BlindedPayInfo, BlindedPath)>, ()> {
118 impl MessageRouter for FuzzRouter {
120 &self, _sender: PublicKey, _peers: Vec<PublicKey>, _destination: Destination
121 ) -> Result<OnionMessagePath, ()> {
125 fn create_blinded_paths<T: secp256k1::Signing + secp256k1::Verification>(
126 &self, _recipient: PublicKey, _peers: Vec<PublicKey>, _secp_ctx: &Secp256k1<T>,
127 ) -> Result<Vec<BlindedPath>, ()> {
132 pub struct TestBroadcaster {}
133 impl BroadcasterInterface for TestBroadcaster {
134 fn broadcast_transactions(&self, _txs: &[&Transaction]) { }
137 pub struct VecWriter(pub Vec<u8>);
138 impl Writer for VecWriter {
139 fn write_all(&mut self, buf: &[u8]) -> Result<(), ::std::io::Error> {
140 self.0.extend_from_slice(buf);
145 struct TestChainMonitor {
146 pub logger: Arc<dyn Logger>,
147 pub keys: Arc<KeyProvider>,
148 pub persister: Arc<TestPersister>,
149 pub chain_monitor: Arc<chainmonitor::ChainMonitor<TestChannelSigner, Arc<dyn chain::Filter>, Arc<TestBroadcaster>, Arc<FuzzEstimator>, Arc<dyn Logger>, Arc<TestPersister>>>,
150 // If we reload a node with an old copy of ChannelMonitors, the ChannelManager deserialization
151 // logic will automatically force-close our channels for us (as we don't have an up-to-date
152 // monitor implying we are not able to punish misbehaving counterparties). Because this test
153 // "fails" if we ever force-close a channel, we avoid doing so, always saving the latest
154 // fully-serialized monitor state here, as well as the corresponding update_id.
155 pub latest_monitors: Mutex<HashMap<OutPoint, (u64, Vec<u8>)>>,
157 impl TestChainMonitor {
158 pub fn new(broadcaster: Arc<TestBroadcaster>, logger: Arc<dyn Logger>, feeest: Arc<FuzzEstimator>, persister: Arc<TestPersister>, keys: Arc<KeyProvider>) -> Self {
160 chain_monitor: Arc::new(chainmonitor::ChainMonitor::new(None, broadcaster, logger.clone(), feeest, Arc::clone(&persister))),
164 latest_monitors: Mutex::new(new_hash_map()),
168 impl chain::Watch<TestChannelSigner> for TestChainMonitor {
169 fn watch_channel(&self, funding_txo: OutPoint, monitor: channelmonitor::ChannelMonitor<TestChannelSigner>) -> Result<chain::ChannelMonitorUpdateStatus, ()> {
170 let mut ser = VecWriter(Vec::new());
171 monitor.write(&mut ser).unwrap();
172 if let Some(_) = self.latest_monitors.lock().unwrap().insert(funding_txo, (monitor.get_latest_update_id(), ser.0)) {
173 panic!("Already had monitor pre-watch_channel");
175 self.chain_monitor.watch_channel(funding_txo, monitor)
178 fn update_channel(&self, funding_txo: OutPoint, update: &channelmonitor::ChannelMonitorUpdate) -> chain::ChannelMonitorUpdateStatus {
179 let mut map_lock = self.latest_monitors.lock().unwrap();
180 let map_entry = map_lock.get_mut(&funding_txo).expect("Didn't have monitor on update call");
181 let deserialized_monitor = <(BlockHash, channelmonitor::ChannelMonitor<TestChannelSigner>)>::
182 read(&mut Cursor::new(&map_entry.1), (&*self.keys, &*self.keys)).unwrap().1;
183 deserialized_monitor.update_monitor(update, &&TestBroadcaster{}, &&FuzzEstimator { ret_val: atomic::AtomicU32::new(253) }, &self.logger).unwrap();
184 let mut ser = VecWriter(Vec::new());
185 deserialized_monitor.write(&mut ser).unwrap();
186 *map_entry = (update.update_id, ser.0);
187 self.chain_monitor.update_channel(funding_txo, update)
190 fn release_pending_monitor_events(&self) -> Vec<(OutPoint, ChannelId, Vec<MonitorEvent>, Option<PublicKey>)> {
191 return self.chain_monitor.release_pending_monitor_events();
196 node_secret: SecretKey,
197 rand_bytes_id: atomic::AtomicU32,
198 enforcement_states: Mutex<HashMap<[u8;32], Arc<Mutex<EnforcementState>>>>,
201 impl EntropySource for KeyProvider {
202 fn get_secure_random_bytes(&self) -> [u8; 32] {
203 let id = self.rand_bytes_id.fetch_add(1, atomic::Ordering::Relaxed);
204 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]];
205 res[30-4..30].copy_from_slice(&id.to_le_bytes());
210 impl NodeSigner for KeyProvider {
211 fn get_node_id(&self, recipient: Recipient) -> Result<PublicKey, ()> {
212 let node_secret = match recipient {
213 Recipient::Node => Ok(&self.node_secret),
214 Recipient::PhantomNode => Err(())
216 Ok(PublicKey::from_secret_key(&Secp256k1::signing_only(), node_secret))
219 fn ecdh(&self, recipient: Recipient, other_key: &PublicKey, tweak: Option<&Scalar>) -> Result<SharedSecret, ()> {
220 let mut node_secret = match recipient {
221 Recipient::Node => Ok(self.node_secret.clone()),
222 Recipient::PhantomNode => Err(())
224 if let Some(tweak) = tweak {
225 node_secret = node_secret.mul_tweak(tweak).map_err(|_| ())?;
227 Ok(SharedSecret::new(other_key, &node_secret))
230 fn get_inbound_payment_key_material(&self) -> KeyMaterial {
231 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]])
234 fn sign_invoice(&self, _hrp_bytes: &[u8], _invoice_data: &[u5], _recipient: Recipient) -> Result<RecoverableSignature, ()> {
238 fn sign_bolt12_invoice_request(
239 &self, _invoice_request: &UnsignedInvoiceRequest
240 ) -> Result<schnorr::Signature, ()> {
244 fn sign_bolt12_invoice(
245 &self, _invoice: &UnsignedBolt12Invoice,
246 ) -> Result<schnorr::Signature, ()> {
250 fn sign_gossip_message(&self, msg: lightning::ln::msgs::UnsignedGossipMessage) -> Result<Signature, ()> {
251 let msg_hash = Message::from_digest(Sha256dHash::hash(&msg.encode()[..]).to_byte_array());
252 let secp_ctx = Secp256k1::signing_only();
253 Ok(secp_ctx.sign_ecdsa(&msg_hash, &self.node_secret))
257 impl SignerProvider for KeyProvider {
258 type EcdsaSigner = TestChannelSigner;
260 type TaprootSigner = TestChannelSigner;
262 fn generate_channel_keys_id(&self, _inbound: bool, _channel_value_satoshis: u64, _user_channel_id: u128) -> [u8; 32] {
263 let id = self.rand_bytes_id.fetch_add(1, atomic::Ordering::Relaxed) as u8;
267 fn derive_channel_signer(&self, channel_value_satoshis: u64, channel_keys_id: [u8; 32]) -> Self::EcdsaSigner {
268 let secp_ctx = Secp256k1::signing_only();
269 let id = channel_keys_id[0];
270 let keys = InMemorySigner::new(
272 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(),
273 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(),
274 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(),
275 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(),
276 SecretKey::from_slice(&[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, self.node_secret[31]]).unwrap(),
277 [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]],
278 channel_value_satoshis,
282 let revoked_commitment = self.make_enforcement_state_cell(keys.commitment_seed);
283 TestChannelSigner::new_with_revoked(keys, revoked_commitment, false)
286 fn read_chan_signer(&self, buffer: &[u8]) -> Result<Self::EcdsaSigner, DecodeError> {
287 let mut reader = std::io::Cursor::new(buffer);
289 let inner: InMemorySigner = ReadableArgs::read(&mut reader, self)?;
290 let state = self.make_enforcement_state_cell(inner.commitment_seed);
292 Ok(TestChannelSigner {
295 disable_revocation_policy_check: false,
296 available: Arc::new(Mutex::new(true)),
300 fn get_destination_script(&self, _channel_keys_id: [u8; 32]) -> Result<ScriptBuf, ()> {
301 let secp_ctx = Secp256k1::signing_only();
302 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();
303 let our_channel_monitor_claim_key_hash = WPubkeyHash::hash(&PublicKey::from_secret_key(&secp_ctx, &channel_monitor_claim_key).serialize());
304 Ok(Builder::new().push_opcode(opcodes::all::OP_PUSHBYTES_0).push_slice(our_channel_monitor_claim_key_hash).into_script())
307 fn get_shutdown_scriptpubkey(&self) -> Result<ShutdownScript, ()> {
308 let secp_ctx = Secp256k1::signing_only();
309 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();
310 let pubkey_hash = WPubkeyHash::hash(&PublicKey::from_secret_key(&secp_ctx, &secret_key).serialize());
311 Ok(ShutdownScript::new_p2wpkh(&pubkey_hash))
316 fn make_enforcement_state_cell(&self, commitment_seed: [u8; 32]) -> Arc<Mutex<EnforcementState>> {
317 let mut revoked_commitments = self.enforcement_states.lock().unwrap();
318 if !revoked_commitments.contains_key(&commitment_seed) {
319 revoked_commitments.insert(commitment_seed, Arc::new(Mutex::new(EnforcementState::new())));
321 let cell = revoked_commitments.get(&commitment_seed).unwrap();
327 fn check_api_err(api_err: APIError, sendable_bounds_violated: bool) {
329 APIError::APIMisuseError { .. } => panic!("We can't misuse the API"),
330 APIError::FeeRateTooHigh { .. } => panic!("We can't send too much fee?"),
331 APIError::InvalidRoute { .. } => panic!("Our routes should work"),
332 APIError::ChannelUnavailable { err } => {
333 // Test the error against a list of errors we can hit, and reject
334 // all others. If you hit this panic, the list of acceptable errors
335 // is probably just stale and you should add new messages here.
337 "Peer for first hop currently disconnected" => {},
338 _ if err.starts_with("Cannot send less than our next-HTLC minimum - ") => {},
339 _ if err.starts_with("Cannot send more than our next-HTLC maximum - ") => {},
340 _ => panic!("{}", err),
342 assert!(sendable_bounds_violated);
344 APIError::MonitorUpdateInProgress => {
345 // We can (obviously) temp-fail a monitor update
347 APIError::IncompatibleShutdownScript { .. } => panic!("Cannot send an incompatible shutdown script"),
351 fn check_payment_err(send_err: PaymentSendFailure, sendable_bounds_violated: bool) {
353 PaymentSendFailure::ParameterError(api_err) => check_api_err(api_err, sendable_bounds_violated),
354 PaymentSendFailure::PathParameterError(per_path_results) => {
355 for res in per_path_results { if let Err(api_err) = res { check_api_err(api_err, sendable_bounds_violated); } }
357 PaymentSendFailure::AllFailedResendSafe(per_path_results) => {
358 for api_err in per_path_results { check_api_err(api_err, sendable_bounds_violated); }
360 PaymentSendFailure::PartialFailure { results, .. } => {
361 for res in results { if let Err(api_err) = res { check_api_err(api_err, sendable_bounds_violated); } }
363 PaymentSendFailure::DuplicatePayment => panic!(),
367 type ChanMan<'a> = ChannelManager<Arc<TestChainMonitor>, Arc<TestBroadcaster>, Arc<KeyProvider>, Arc<KeyProvider>, Arc<KeyProvider>, Arc<FuzzEstimator>, &'a FuzzRouter, Arc<dyn Logger>>;
370 fn get_payment_secret_hash(dest: &ChanMan, payment_id: &mut u8) -> Option<(PaymentSecret, PaymentHash)> {
371 let mut payment_hash;
373 payment_hash = PaymentHash(Sha256::hash(&[*payment_id; 1]).to_byte_array());
374 if let Ok(payment_secret) = dest.create_inbound_payment_for_hash(payment_hash, None, 3600, None) {
375 return Some((payment_secret, payment_hash));
377 *payment_id = payment_id.wrapping_add(1);
383 fn send_payment(source: &ChanMan, dest: &ChanMan, dest_chan_id: u64, amt: u64, payment_id: &mut u8, payment_idx: &mut u64) -> bool {
384 let (payment_secret, payment_hash) =
385 if let Some((secret, hash)) = get_payment_secret_hash(dest, payment_id) { (secret, hash) } else { return true; };
386 let mut payment_id = [0; 32];
387 payment_id[0..8].copy_from_slice(&payment_idx.to_ne_bytes());
389 let (min_value_sendable, max_value_sendable) = source.list_usable_channels()
390 .iter().find(|chan| chan.short_channel_id == Some(dest_chan_id))
392 (chan.next_outbound_htlc_minimum_msat, chan.next_outbound_htlc_limit_msat))
394 if let Err(err) = source.send_payment_with_route(&Route {
395 paths: vec![Path { hops: vec![RouteHop {
396 pubkey: dest.get_our_node_id(),
397 node_features: dest.node_features(),
398 short_channel_id: dest_chan_id,
399 channel_features: dest.channel_features(),
401 cltv_expiry_delta: 200,
402 maybe_announced_channel: true,
403 }], blinded_tail: None }],
405 }, payment_hash, RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_id)) {
406 check_payment_err(err, amt > max_value_sendable || amt < min_value_sendable);
409 // Note that while the max is a strict upper-bound, we can occasionally send substantially
410 // below the minimum, with some gap which is unusable immediately below the minimum. Thus,
411 // we don't check against min_value_sendable here.
412 assert!(amt <= max_value_sendable);
417 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 {
418 let (payment_secret, payment_hash) =
419 if let Some((secret, hash)) = get_payment_secret_hash(dest, payment_id) { (secret, hash) } else { return true; };
420 let mut payment_id = [0; 32];
421 payment_id[0..8].copy_from_slice(&payment_idx.to_ne_bytes());
423 let (min_value_sendable, max_value_sendable) = source.list_usable_channels()
424 .iter().find(|chan| chan.short_channel_id == Some(middle_chan_id))
426 (chan.next_outbound_htlc_minimum_msat, chan.next_outbound_htlc_limit_msat))
428 let first_hop_fee = 50_000;
429 if let Err(err) = source.send_payment_with_route(&Route {
430 paths: vec![Path { hops: vec![RouteHop {
431 pubkey: middle.get_our_node_id(),
432 node_features: middle.node_features(),
433 short_channel_id: middle_chan_id,
434 channel_features: middle.channel_features(),
435 fee_msat: first_hop_fee,
436 cltv_expiry_delta: 100,
437 maybe_announced_channel: true,
439 pubkey: dest.get_our_node_id(),
440 node_features: dest.node_features(),
441 short_channel_id: dest_chan_id,
442 channel_features: dest.channel_features(),
444 cltv_expiry_delta: 200,
445 maybe_announced_channel: true,
446 }], blinded_tail: None }],
448 }, payment_hash, RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_id)) {
449 let sent_amt = amt + first_hop_fee;
450 check_payment_err(err, sent_amt < min_value_sendable || sent_amt > max_value_sendable);
453 // Note that while the max is a strict upper-bound, we can occasionally send substantially
454 // below the minimum, with some gap which is unusable immediately below the minimum. Thus,
455 // we don't check against min_value_sendable here.
456 assert!(amt + first_hop_fee <= max_value_sendable);
462 pub fn do_test<Out: Output>(data: &[u8], underlying_out: Out, anchors: bool) {
463 let out = SearchingOutput::new(underlying_out);
464 let broadcast = Arc::new(TestBroadcaster{});
465 let router = FuzzRouter {};
467 macro_rules! make_node {
468 ($node_id: expr, $fee_estimator: expr) => { {
469 let logger: Arc<dyn Logger> = Arc::new(test_logger::TestLogger::new($node_id.to_string(), out.clone()));
470 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();
471 let keys_manager = Arc::new(KeyProvider { node_secret, rand_bytes_id: atomic::AtomicU32::new(0), enforcement_states: Mutex::new(new_hash_map()) });
472 let monitor = Arc::new(TestChainMonitor::new(broadcast.clone(), logger.clone(), $fee_estimator.clone(),
473 Arc::new(TestPersister {
474 update_ret: Mutex::new(ChannelMonitorUpdateStatus::Completed)
475 }), Arc::clone(&keys_manager)));
477 let mut config = UserConfig::default();
478 config.channel_config.forwarding_fee_proportional_millionths = 0;
479 config.channel_handshake_config.announced_channel = true;
481 config.channel_handshake_config.negotiate_anchors_zero_fee_htlc_tx = true;
482 config.manually_accept_inbound_channels = true;
484 let network = Network::Bitcoin;
485 let best_block_timestamp = genesis_block(network).header.time;
486 let params = ChainParameters {
488 best_block: BestBlock::from_network(network),
490 (ChannelManager::new($fee_estimator.clone(), monitor.clone(), broadcast.clone(), &router, Arc::clone(&logger), keys_manager.clone(), keys_manager.clone(), keys_manager.clone(), config, params, best_block_timestamp),
491 monitor, keys_manager)
495 macro_rules! reload_node {
496 ($ser: expr, $node_id: expr, $old_monitors: expr, $keys_manager: expr, $fee_estimator: expr) => { {
497 let keys_manager = Arc::clone(& $keys_manager);
498 let logger: Arc<dyn Logger> = Arc::new(test_logger::TestLogger::new($node_id.to_string(), out.clone()));
499 let chain_monitor = Arc::new(TestChainMonitor::new(broadcast.clone(), logger.clone(), $fee_estimator.clone(),
500 Arc::new(TestPersister {
501 update_ret: Mutex::new(ChannelMonitorUpdateStatus::Completed)
502 }), Arc::clone(& $keys_manager)));
504 let mut config = UserConfig::default();
505 config.channel_config.forwarding_fee_proportional_millionths = 0;
506 config.channel_handshake_config.announced_channel = true;
508 config.channel_handshake_config.negotiate_anchors_zero_fee_htlc_tx = true;
509 config.manually_accept_inbound_channels = true;
512 let mut monitors = new_hash_map();
513 let mut old_monitors = $old_monitors.latest_monitors.lock().unwrap();
514 for (outpoint, (update_id, monitor_ser)) in old_monitors.drain() {
515 monitors.insert(outpoint, <(BlockHash, ChannelMonitor<TestChannelSigner>)>::read(&mut Cursor::new(&monitor_ser), (&*$keys_manager, &*$keys_manager)).expect("Failed to read monitor").1);
516 chain_monitor.latest_monitors.lock().unwrap().insert(outpoint, (update_id, monitor_ser));
518 let mut monitor_refs = new_hash_map();
519 for (outpoint, monitor) in monitors.iter_mut() {
520 monitor_refs.insert(*outpoint, monitor);
523 let read_args = ChannelManagerReadArgs {
524 entropy_source: keys_manager.clone(),
525 node_signer: keys_manager.clone(),
526 signer_provider: keys_manager.clone(),
527 fee_estimator: $fee_estimator.clone(),
528 chain_monitor: chain_monitor.clone(),
529 tx_broadcaster: broadcast.clone(),
532 default_config: config,
533 channel_monitors: monitor_refs,
536 let res = (<(BlockHash, ChanMan)>::read(&mut Cursor::new(&$ser.0), read_args).expect("Failed to read manager").1, chain_monitor.clone());
537 for (funding_txo, mon) in monitors.drain() {
538 assert_eq!(chain_monitor.chain_monitor.watch_channel(funding_txo, mon),
539 Ok(ChannelMonitorUpdateStatus::Completed));
545 let mut channel_txn = Vec::new();
546 macro_rules! make_channel {
547 ($source: expr, $dest: expr, $dest_keys_manager: expr, $chan_id: expr) => { {
548 $source.peer_connected(&$dest.get_our_node_id(), &Init {
549 features: $dest.init_features(), networks: None, remote_network_address: None
551 $dest.peer_connected(&$source.get_our_node_id(), &Init {
552 features: $source.init_features(), networks: None, remote_network_address: None
555 $source.create_channel($dest.get_our_node_id(), 100_000, 42, 0, None, None).unwrap();
557 let events = $source.get_and_clear_pending_msg_events();
558 assert_eq!(events.len(), 1);
559 if let events::MessageSendEvent::SendOpenChannel { ref msg, .. } = events[0] {
561 } else { panic!("Wrong event type"); }
564 $dest.handle_open_channel(&$source.get_our_node_id(), &open_channel);
565 let accept_channel = {
567 let events = $dest.get_and_clear_pending_events();
568 assert_eq!(events.len(), 1);
569 if let events::Event::OpenChannelRequest {
570 ref temporary_channel_id, ref counterparty_node_id, ..
572 let mut random_bytes = [0u8; 16];
573 random_bytes.copy_from_slice(&$dest_keys_manager.get_secure_random_bytes()[..16]);
574 let user_channel_id = u128::from_be_bytes(random_bytes);
575 $dest.accept_inbound_channel(
576 temporary_channel_id,
577 counterparty_node_id,
580 } else { panic!("Wrong event type"); }
582 let events = $dest.get_and_clear_pending_msg_events();
583 assert_eq!(events.len(), 1);
584 if let events::MessageSendEvent::SendAcceptChannel { ref msg, .. } = events[0] {
586 } else { panic!("Wrong event type"); }
589 $source.handle_accept_channel(&$dest.get_our_node_id(), &accept_channel);
592 let events = $source.get_and_clear_pending_events();
593 assert_eq!(events.len(), 1);
594 if let events::Event::FundingGenerationReady { ref temporary_channel_id, ref channel_value_satoshis, ref output_script, .. } = events[0] {
595 let tx = Transaction { version: Version($chan_id), lock_time: LockTime::ZERO, input: Vec::new(), output: vec![TxOut {
596 value: Amount::from_sat(*channel_value_satoshis), script_pubkey: output_script.clone(),
598 funding_output = OutPoint { txid: tx.txid(), index: 0 };
599 $source.funding_transaction_generated(&temporary_channel_id, &$dest.get_our_node_id(), tx.clone()).unwrap();
600 channel_txn.push(tx);
601 } else { panic!("Wrong event type"); }
604 let funding_created = {
605 let events = $source.get_and_clear_pending_msg_events();
606 assert_eq!(events.len(), 1);
607 if let events::MessageSendEvent::SendFundingCreated { ref msg, .. } = events[0] {
609 } else { panic!("Wrong event type"); }
611 $dest.handle_funding_created(&$source.get_our_node_id(), &funding_created);
613 let funding_signed = {
614 let events = $dest.get_and_clear_pending_msg_events();
615 assert_eq!(events.len(), 1);
616 if let events::MessageSendEvent::SendFundingSigned { ref msg, .. } = events[0] {
618 } else { panic!("Wrong event type"); }
620 let events = $dest.get_and_clear_pending_events();
621 assert_eq!(events.len(), 1);
622 if let events::Event::ChannelPending{ ref counterparty_node_id, .. } = events[0] {
623 assert_eq!(counterparty_node_id, &$source.get_our_node_id());
624 } else { panic!("Wrong event type"); }
626 $source.handle_funding_signed(&$dest.get_our_node_id(), &funding_signed);
627 let events = $source.get_and_clear_pending_events();
628 assert_eq!(events.len(), 1);
629 if let events::Event::ChannelPending{ ref counterparty_node_id, .. } = events[0] {
630 assert_eq!(counterparty_node_id, &$dest.get_our_node_id());
631 } else { panic!("Wrong event type"); }
637 macro_rules! confirm_txn {
639 let chain_hash = genesis_block(Network::Bitcoin).block_hash();
640 let mut header = create_dummy_header(chain_hash, 42);
641 let txdata: Vec<_> = channel_txn.iter().enumerate().map(|(i, tx)| (i + 1, tx)).collect();
642 $node.transactions_confirmed(&header, &txdata, 1);
644 header = create_dummy_header(header.block_hash(), 42);
646 $node.best_block_updated(&header, 99);
650 macro_rules! lock_fundings {
651 ($nodes: expr) => { {
652 let mut node_events = Vec::new();
653 for node in $nodes.iter() {
654 node_events.push(node.get_and_clear_pending_msg_events());
656 for (idx, node_event) in node_events.iter().enumerate() {
657 for event in node_event {
658 if let events::MessageSendEvent::SendChannelReady { ref node_id, ref msg } = event {
659 for node in $nodes.iter() {
660 if node.get_our_node_id() == *node_id {
661 node.handle_channel_ready(&$nodes[idx].get_our_node_id(), msg);
664 } else { panic!("Wrong event type"); }
668 for node in $nodes.iter() {
669 let events = node.get_and_clear_pending_msg_events();
670 for event in events {
671 if let events::MessageSendEvent::SendAnnouncementSignatures { .. } = event {
672 } else { panic!("Wrong event type"); }
678 let fee_est_a = Arc::new(FuzzEstimator { ret_val: atomic::AtomicU32::new(253) });
679 let mut last_htlc_clear_fee_a = 253;
680 let fee_est_b = Arc::new(FuzzEstimator { ret_val: atomic::AtomicU32::new(253) });
681 let mut last_htlc_clear_fee_b = 253;
682 let fee_est_c = Arc::new(FuzzEstimator { ret_val: atomic::AtomicU32::new(253) });
683 let mut last_htlc_clear_fee_c = 253;
685 // 3 nodes is enough to hit all the possible cases, notably unknown-source-unknown-dest
687 let (node_a, mut monitor_a, keys_manager_a) = make_node!(0, fee_est_a);
688 let (node_b, mut monitor_b, keys_manager_b) = make_node!(1, fee_est_b);
689 let (node_c, mut monitor_c, keys_manager_c) = make_node!(2, fee_est_c);
691 let mut nodes = [node_a, node_b, node_c];
693 let chan_1_funding = make_channel!(nodes[0], nodes[1], keys_manager_b, 0);
694 let chan_2_funding = make_channel!(nodes[1], nodes[2], keys_manager_c, 1);
696 for node in nodes.iter() {
700 lock_fundings!(nodes);
702 let chan_a = nodes[0].list_usable_channels()[0].short_channel_id.unwrap();
703 let chan_b = nodes[2].list_usable_channels()[0].short_channel_id.unwrap();
705 let mut payment_id: u8 = 0;
706 let mut payment_idx: u64 = 0;
708 let mut chan_a_disconnected = false;
709 let mut chan_b_disconnected = false;
710 let mut ab_events = Vec::new();
711 let mut ba_events = Vec::new();
712 let mut bc_events = Vec::new();
713 let mut cb_events = Vec::new();
715 let mut node_a_ser = VecWriter(Vec::new());
716 nodes[0].write(&mut node_a_ser).unwrap();
717 let mut node_b_ser = VecWriter(Vec::new());
718 nodes[1].write(&mut node_b_ser).unwrap();
719 let mut node_c_ser = VecWriter(Vec::new());
720 nodes[2].write(&mut node_c_ser).unwrap();
722 macro_rules! test_return {
724 assert_eq!(nodes[0].list_channels().len(), 1);
725 assert_eq!(nodes[1].list_channels().len(), 2);
726 assert_eq!(nodes[2].list_channels().len(), 1);
731 let mut read_pos = 0;
732 macro_rules! get_slice {
735 let slice_len = $len as usize;
736 if data.len() < read_pos + slice_len {
739 read_pos += slice_len;
740 &data[read_pos - slice_len..read_pos]
746 // Push any events from Node B onto ba_events and bc_events
747 macro_rules! push_excess_b_events {
748 ($excess_events: expr, $expect_drop_node: expr) => { {
749 let a_id = nodes[0].get_our_node_id();
750 let expect_drop_node: Option<usize> = $expect_drop_node;
751 let expect_drop_id = if let Some(id) = expect_drop_node { Some(nodes[id].get_our_node_id()) } else { None };
752 for event in $excess_events {
753 let push_a = match event {
754 events::MessageSendEvent::UpdateHTLCs { ref node_id, .. } => {
755 if Some(*node_id) == expect_drop_id { panic!("peer_disconnected should drop msgs bound for the disconnected peer"); }
758 events::MessageSendEvent::SendRevokeAndACK { ref node_id, .. } => {
759 if Some(*node_id) == expect_drop_id { panic!("peer_disconnected should drop msgs bound for the disconnected peer"); }
762 events::MessageSendEvent::SendChannelReestablish { ref node_id, .. } => {
763 if Some(*node_id) == expect_drop_id { panic!("peer_disconnected should drop msgs bound for the disconnected peer"); }
766 events::MessageSendEvent::SendChannelReady { .. } => continue,
767 events::MessageSendEvent::SendAnnouncementSignatures { .. } => continue,
768 events::MessageSendEvent::SendChannelUpdate { ref node_id, ref msg } => {
769 assert_eq!(msg.contents.flags & 2, 0); // The disable bit must never be set!
770 if Some(*node_id) == expect_drop_id { panic!("peer_disconnected should drop msgs bound for the disconnected peer"); }
773 _ => panic!("Unhandled message event {:?}", event),
775 if push_a { ba_events.push(event); } else { bc_events.push(event); }
780 // While delivering messages, we select across three possible message selection processes
781 // to ensure we get as much coverage as possible. See the individual enum variants for more
784 enum ProcessMessages {
785 /// Deliver all available messages, including fetching any new messages from
786 /// `get_and_clear_pending_msg_events()` (which may have side effects).
788 /// Call `get_and_clear_pending_msg_events()` first, and then deliver up to one
789 /// message (which may already be queued).
791 /// Deliver up to one already-queued message. This avoids any potential side-effects
792 /// of `get_and_clear_pending_msg_events()` (eg freeing the HTLC holding cell), which
793 /// provides potentially more coverage.
797 macro_rules! process_msg_events {
798 ($node: expr, $corrupt_forward: expr, $limit_events: expr) => { {
799 let mut events = if $node == 1 {
800 let mut new_events = Vec::new();
801 mem::swap(&mut new_events, &mut ba_events);
802 new_events.extend_from_slice(&bc_events[..]);
805 } else if $node == 0 {
806 let mut new_events = Vec::new();
807 mem::swap(&mut new_events, &mut ab_events);
810 let mut new_events = Vec::new();
811 mem::swap(&mut new_events, &mut cb_events);
814 let mut new_events = Vec::new();
815 if $limit_events != ProcessMessages::OnePendingMessage {
816 new_events = nodes[$node].get_and_clear_pending_msg_events();
818 let mut had_events = false;
819 let mut events_iter = events.drain(..).chain(new_events.drain(..));
820 let mut extra_ev = None;
821 for event in &mut events_iter {
824 events::MessageSendEvent::UpdateHTLCs { node_id, updates: CommitmentUpdate { update_add_htlcs, update_fail_htlcs, update_fulfill_htlcs, update_fail_malformed_htlcs, update_fee, commitment_signed } } => {
825 for (idx, dest) in nodes.iter().enumerate() {
826 if dest.get_our_node_id() == node_id {
827 for update_add in update_add_htlcs.iter() {
828 out.locked_write(format!("Delivering update_add_htlc to node {}.\n", idx).as_bytes());
829 if !$corrupt_forward {
830 dest.handle_update_add_htlc(&nodes[$node].get_our_node_id(), update_add);
832 // Corrupt the update_add_htlc message so that its HMAC
833 // check will fail and we generate a
834 // update_fail_malformed_htlc instead of an
835 // update_fail_htlc as we do when we reject a payment.
836 let mut msg_ser = update_add.encode();
837 msg_ser[1000] ^= 0xff;
838 let new_msg = UpdateAddHTLC::read(&mut Cursor::new(&msg_ser)).unwrap();
839 dest.handle_update_add_htlc(&nodes[$node].get_our_node_id(), &new_msg);
842 for update_fulfill in update_fulfill_htlcs.iter() {
843 out.locked_write(format!("Delivering update_fulfill_htlc to node {}.\n", idx).as_bytes());
844 dest.handle_update_fulfill_htlc(&nodes[$node].get_our_node_id(), update_fulfill);
846 for update_fail in update_fail_htlcs.iter() {
847 out.locked_write(format!("Delivering update_fail_htlc to node {}.\n", idx).as_bytes());
848 dest.handle_update_fail_htlc(&nodes[$node].get_our_node_id(), update_fail);
850 for update_fail_malformed in update_fail_malformed_htlcs.iter() {
851 out.locked_write(format!("Delivering update_fail_malformed_htlc to node {}.\n", idx).as_bytes());
852 dest.handle_update_fail_malformed_htlc(&nodes[$node].get_our_node_id(), update_fail_malformed);
854 if let Some(msg) = update_fee {
855 out.locked_write(format!("Delivering update_fee to node {}.\n", idx).as_bytes());
856 dest.handle_update_fee(&nodes[$node].get_our_node_id(), &msg);
858 let processed_change = !update_add_htlcs.is_empty() || !update_fulfill_htlcs.is_empty() ||
859 !update_fail_htlcs.is_empty() || !update_fail_malformed_htlcs.is_empty();
860 if $limit_events != ProcessMessages::AllMessages && processed_change {
861 // If we only want to process some messages, don't deliver the CS until later.
862 extra_ev = Some(events::MessageSendEvent::UpdateHTLCs { node_id, updates: CommitmentUpdate {
863 update_add_htlcs: Vec::new(),
864 update_fail_htlcs: Vec::new(),
865 update_fulfill_htlcs: Vec::new(),
866 update_fail_malformed_htlcs: Vec::new(),
872 out.locked_write(format!("Delivering commitment_signed to node {}.\n", idx).as_bytes());
873 dest.handle_commitment_signed(&nodes[$node].get_our_node_id(), &commitment_signed);
878 events::MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
879 for (idx, dest) in nodes.iter().enumerate() {
880 if dest.get_our_node_id() == *node_id {
881 out.locked_write(format!("Delivering revoke_and_ack to node {}.\n", idx).as_bytes());
882 dest.handle_revoke_and_ack(&nodes[$node].get_our_node_id(), msg);
886 events::MessageSendEvent::SendChannelReestablish { ref node_id, ref msg } => {
887 for (idx, dest) in nodes.iter().enumerate() {
888 if dest.get_our_node_id() == *node_id {
889 out.locked_write(format!("Delivering channel_reestablish to node {}.\n", idx).as_bytes());
890 dest.handle_channel_reestablish(&nodes[$node].get_our_node_id(), msg);
894 events::MessageSendEvent::SendChannelReady { .. } => {
895 // Can be generated as a reestablish response
897 events::MessageSendEvent::SendAnnouncementSignatures { .. } => {
898 // Can be generated as a reestablish response
900 events::MessageSendEvent::SendChannelUpdate { ref msg, .. } => {
901 // When we reconnect we will resend a channel_update to make sure our
902 // counterparty has the latest parameters for receiving payments
903 // through us. We do, however, check that the message does not include
904 // the "disabled" bit, as we should never ever have a channel which is
905 // disabled when we send such an update (or it may indicate channel
906 // force-close which we should detect as an error).
907 assert_eq!(msg.contents.flags & 2, 0);
909 _ => if out.may_fail.load(atomic::Ordering::Acquire) {
912 panic!("Unhandled message event {:?}", event)
915 if $limit_events != ProcessMessages::AllMessages {
920 push_excess_b_events!(extra_ev.into_iter().chain(events_iter), None);
921 } else if $node == 0 {
922 if let Some(ev) = extra_ev { ab_events.push(ev); }
923 for event in events_iter { ab_events.push(event); }
925 if let Some(ev) = extra_ev { cb_events.push(ev); }
926 for event in events_iter { cb_events.push(event); }
932 macro_rules! drain_msg_events_on_disconnect {
933 ($counterparty_id: expr) => { {
934 if $counterparty_id == 0 {
935 for event in nodes[0].get_and_clear_pending_msg_events() {
937 events::MessageSendEvent::UpdateHTLCs { .. } => {},
938 events::MessageSendEvent::SendRevokeAndACK { .. } => {},
939 events::MessageSendEvent::SendChannelReestablish { .. } => {},
940 events::MessageSendEvent::SendChannelReady { .. } => {},
941 events::MessageSendEvent::SendAnnouncementSignatures { .. } => {},
942 events::MessageSendEvent::SendChannelUpdate { ref msg, .. } => {
943 assert_eq!(msg.contents.flags & 2, 0); // The disable bit must never be set!
945 _ => if out.may_fail.load(atomic::Ordering::Acquire) {
948 panic!("Unhandled message event")
952 push_excess_b_events!(nodes[1].get_and_clear_pending_msg_events().drain(..), Some(0));
956 for event in nodes[2].get_and_clear_pending_msg_events() {
958 events::MessageSendEvent::UpdateHTLCs { .. } => {},
959 events::MessageSendEvent::SendRevokeAndACK { .. } => {},
960 events::MessageSendEvent::SendChannelReestablish { .. } => {},
961 events::MessageSendEvent::SendChannelReady { .. } => {},
962 events::MessageSendEvent::SendAnnouncementSignatures { .. } => {},
963 events::MessageSendEvent::SendChannelUpdate { ref msg, .. } => {
964 assert_eq!(msg.contents.flags & 2, 0); // The disable bit must never be set!
966 _ => if out.may_fail.load(atomic::Ordering::Acquire) {
969 panic!("Unhandled message event")
973 push_excess_b_events!(nodes[1].get_and_clear_pending_msg_events().drain(..), Some(2));
980 macro_rules! process_events {
981 ($node: expr, $fail: expr) => { {
982 // In case we get 256 payments we may have a hash collision, resulting in the
983 // second claim/fail call not finding the duplicate-hash HTLC, so we have to
984 // deduplicate the calls here.
985 let mut claim_set = new_hash_map();
986 let mut events = nodes[$node].get_and_clear_pending_events();
987 // Sort events so that PendingHTLCsForwardable get processed last. This avoids a
988 // case where we first process a PendingHTLCsForwardable, then claim/fail on a
989 // PaymentClaimable, claiming/failing two HTLCs, but leaving a just-generated
990 // PaymentClaimable event for the second HTLC in our pending_events (and breaking
991 // our claim_set deduplication).
992 events.sort_by(|a, b| {
993 if let events::Event::PaymentClaimable { .. } = a {
994 if let events::Event::PendingHTLCsForwardable { .. } = b {
996 } else { Ordering::Equal }
997 } else if let events::Event::PendingHTLCsForwardable { .. } = a {
998 if let events::Event::PaymentClaimable { .. } = b {
1000 } else { Ordering::Equal }
1001 } else { Ordering::Equal }
1003 let had_events = !events.is_empty();
1004 for event in events.drain(..) {
1006 events::Event::PaymentClaimable { payment_hash, .. } => {
1007 if claim_set.insert(payment_hash.0, ()).is_none() {
1009 nodes[$node].fail_htlc_backwards(&payment_hash);
1011 nodes[$node].claim_funds(PaymentPreimage(payment_hash.0));
1015 events::Event::PaymentSent { .. } => {},
1016 events::Event::PaymentClaimed { .. } => {},
1017 events::Event::PaymentPathSuccessful { .. } => {},
1018 events::Event::PaymentPathFailed { .. } => {},
1019 events::Event::PaymentFailed { .. } => {},
1020 events::Event::ProbeSuccessful { .. } | events::Event::ProbeFailed { .. } => {
1021 // Even though we don't explicitly send probes, because probes are
1022 // detected based on hashing the payment hash+preimage, its rather
1023 // trivial for the fuzzer to build payments that accidentally end up
1024 // looking like probes.
1026 events::Event::PaymentForwarded { .. } if $node == 1 => {},
1027 events::Event::ChannelReady { .. } => {},
1028 events::Event::PendingHTLCsForwardable { .. } => {
1029 nodes[$node].process_pending_htlc_forwards();
1031 events::Event::HTLCHandlingFailed { .. } => {},
1032 _ => if out.may_fail.load(atomic::Ordering::Acquire) {
1035 panic!("Unhandled event")
1043 let v = get_slice!(1)[0];
1044 out.locked_write(format!("READ A BYTE! HANDLING INPUT {:x}...........\n", v).as_bytes());
1046 // In general, we keep related message groups close together in binary form, allowing
1047 // bit-twiddling mutations to have similar effects. This is probably overkill, but no
1048 // harm in doing so.
1050 0x00 => *monitor_a.persister.update_ret.lock().unwrap() = ChannelMonitorUpdateStatus::InProgress,
1051 0x01 => *monitor_b.persister.update_ret.lock().unwrap() = ChannelMonitorUpdateStatus::InProgress,
1052 0x02 => *monitor_c.persister.update_ret.lock().unwrap() = ChannelMonitorUpdateStatus::InProgress,
1053 0x04 => *monitor_a.persister.update_ret.lock().unwrap() = ChannelMonitorUpdateStatus::Completed,
1054 0x05 => *monitor_b.persister.update_ret.lock().unwrap() = ChannelMonitorUpdateStatus::Completed,
1055 0x06 => *monitor_c.persister.update_ret.lock().unwrap() = ChannelMonitorUpdateStatus::Completed,
1058 if let Some((id, _)) = monitor_a.latest_monitors.lock().unwrap().get(&chan_1_funding) {
1059 monitor_a.chain_monitor.force_channel_monitor_updated(chan_1_funding, *id);
1060 nodes[0].process_monitor_events();
1064 if let Some((id, _)) = monitor_b.latest_monitors.lock().unwrap().get(&chan_1_funding) {
1065 monitor_b.chain_monitor.force_channel_monitor_updated(chan_1_funding, *id);
1066 nodes[1].process_monitor_events();
1070 if let Some((id, _)) = monitor_b.latest_monitors.lock().unwrap().get(&chan_2_funding) {
1071 monitor_b.chain_monitor.force_channel_monitor_updated(chan_2_funding, *id);
1072 nodes[1].process_monitor_events();
1076 if let Some((id, _)) = monitor_c.latest_monitors.lock().unwrap().get(&chan_2_funding) {
1077 monitor_c.chain_monitor.force_channel_monitor_updated(chan_2_funding, *id);
1078 nodes[2].process_monitor_events();
1083 if !chan_a_disconnected {
1084 nodes[0].peer_disconnected(&nodes[1].get_our_node_id());
1085 nodes[1].peer_disconnected(&nodes[0].get_our_node_id());
1086 chan_a_disconnected = true;
1087 drain_msg_events_on_disconnect!(0);
1091 if !chan_b_disconnected {
1092 nodes[1].peer_disconnected(&nodes[2].get_our_node_id());
1093 nodes[2].peer_disconnected(&nodes[1].get_our_node_id());
1094 chan_b_disconnected = true;
1095 drain_msg_events_on_disconnect!(2);
1099 if chan_a_disconnected {
1100 nodes[0].peer_connected(&nodes[1].get_our_node_id(), &Init {
1101 features: nodes[1].init_features(), networks: None, remote_network_address: None
1103 nodes[1].peer_connected(&nodes[0].get_our_node_id(), &Init {
1104 features: nodes[0].init_features(), networks: None, remote_network_address: None
1106 chan_a_disconnected = false;
1110 if chan_b_disconnected {
1111 nodes[1].peer_connected(&nodes[2].get_our_node_id(), &Init {
1112 features: nodes[2].init_features(), networks: None, remote_network_address: None
1114 nodes[2].peer_connected(&nodes[1].get_our_node_id(), &Init {
1115 features: nodes[1].init_features(), networks: None, remote_network_address: None
1117 chan_b_disconnected = false;
1121 0x10 => { process_msg_events!(0, true, ProcessMessages::AllMessages); },
1122 0x11 => { process_msg_events!(0, false, ProcessMessages::AllMessages); },
1123 0x12 => { process_msg_events!(0, true, ProcessMessages::OneMessage); },
1124 0x13 => { process_msg_events!(0, false, ProcessMessages::OneMessage); },
1125 0x14 => { process_msg_events!(0, true, ProcessMessages::OnePendingMessage); },
1126 0x15 => { process_msg_events!(0, false, ProcessMessages::OnePendingMessage); },
1128 0x16 => { process_events!(0, true); },
1129 0x17 => { process_events!(0, false); },
1131 0x18 => { process_msg_events!(1, true, ProcessMessages::AllMessages); },
1132 0x19 => { process_msg_events!(1, false, ProcessMessages::AllMessages); },
1133 0x1a => { process_msg_events!(1, true, ProcessMessages::OneMessage); },
1134 0x1b => { process_msg_events!(1, false, ProcessMessages::OneMessage); },
1135 0x1c => { process_msg_events!(1, true, ProcessMessages::OnePendingMessage); },
1136 0x1d => { process_msg_events!(1, false, ProcessMessages::OnePendingMessage); },
1138 0x1e => { process_events!(1, true); },
1139 0x1f => { process_events!(1, false); },
1141 0x20 => { process_msg_events!(2, true, ProcessMessages::AllMessages); },
1142 0x21 => { process_msg_events!(2, false, ProcessMessages::AllMessages); },
1143 0x22 => { process_msg_events!(2, true, ProcessMessages::OneMessage); },
1144 0x23 => { process_msg_events!(2, false, ProcessMessages::OneMessage); },
1145 0x24 => { process_msg_events!(2, true, ProcessMessages::OnePendingMessage); },
1146 0x25 => { process_msg_events!(2, false, ProcessMessages::OnePendingMessage); },
1148 0x26 => { process_events!(2, true); },
1149 0x27 => { process_events!(2, false); },
1152 if !chan_a_disconnected {
1153 nodes[1].peer_disconnected(&nodes[0].get_our_node_id());
1154 chan_a_disconnected = true;
1155 push_excess_b_events!(nodes[1].get_and_clear_pending_msg_events().drain(..), Some(0));
1159 let (new_node_a, new_monitor_a) = reload_node!(node_a_ser, 0, monitor_a, keys_manager_a, fee_est_a);
1160 nodes[0] = new_node_a;
1161 monitor_a = new_monitor_a;
1164 if !chan_a_disconnected {
1165 nodes[0].peer_disconnected(&nodes[1].get_our_node_id());
1166 chan_a_disconnected = true;
1167 nodes[0].get_and_clear_pending_msg_events();
1171 if !chan_b_disconnected {
1172 nodes[2].peer_disconnected(&nodes[1].get_our_node_id());
1173 chan_b_disconnected = true;
1174 nodes[2].get_and_clear_pending_msg_events();
1178 let (new_node_b, new_monitor_b) = reload_node!(node_b_ser, 1, monitor_b, keys_manager_b, fee_est_b);
1179 nodes[1] = new_node_b;
1180 monitor_b = new_monitor_b;
1183 if !chan_b_disconnected {
1184 nodes[1].peer_disconnected(&nodes[2].get_our_node_id());
1185 chan_b_disconnected = true;
1186 push_excess_b_events!(nodes[1].get_and_clear_pending_msg_events().drain(..), Some(2));
1190 let (new_node_c, new_monitor_c) = reload_node!(node_c_ser, 2, monitor_c, keys_manager_c, fee_est_c);
1191 nodes[2] = new_node_c;
1192 monitor_c = new_monitor_c;
1195 // 1/10th the channel size:
1196 0x30 => { send_payment(&nodes[0], &nodes[1], chan_a, 10_000_000, &mut payment_id, &mut payment_idx); },
1197 0x31 => { send_payment(&nodes[1], &nodes[0], chan_a, 10_000_000, &mut payment_id, &mut payment_idx); },
1198 0x32 => { send_payment(&nodes[1], &nodes[2], chan_b, 10_000_000, &mut payment_id, &mut payment_idx); },
1199 0x33 => { send_payment(&nodes[2], &nodes[1], chan_b, 10_000_000, &mut payment_id, &mut payment_idx); },
1200 0x34 => { send_hop_payment(&nodes[0], &nodes[1], chan_a, &nodes[2], chan_b, 10_000_000, &mut payment_id, &mut payment_idx); },
1201 0x35 => { send_hop_payment(&nodes[2], &nodes[1], chan_b, &nodes[0], chan_a, 10_000_000, &mut payment_id, &mut payment_idx); },
1203 0x38 => { send_payment(&nodes[0], &nodes[1], chan_a, 1_000_000, &mut payment_id, &mut payment_idx); },
1204 0x39 => { send_payment(&nodes[1], &nodes[0], chan_a, 1_000_000, &mut payment_id, &mut payment_idx); },
1205 0x3a => { send_payment(&nodes[1], &nodes[2], chan_b, 1_000_000, &mut payment_id, &mut payment_idx); },
1206 0x3b => { send_payment(&nodes[2], &nodes[1], chan_b, 1_000_000, &mut payment_id, &mut payment_idx); },
1207 0x3c => { send_hop_payment(&nodes[0], &nodes[1], chan_a, &nodes[2], chan_b, 1_000_000, &mut payment_id, &mut payment_idx); },
1208 0x3d => { send_hop_payment(&nodes[2], &nodes[1], chan_b, &nodes[0], chan_a, 1_000_000, &mut payment_id, &mut payment_idx); },
1210 0x40 => { send_payment(&nodes[0], &nodes[1], chan_a, 100_000, &mut payment_id, &mut payment_idx); },
1211 0x41 => { send_payment(&nodes[1], &nodes[0], chan_a, 100_000, &mut payment_id, &mut payment_idx); },
1212 0x42 => { send_payment(&nodes[1], &nodes[2], chan_b, 100_000, &mut payment_id, &mut payment_idx); },
1213 0x43 => { send_payment(&nodes[2], &nodes[1], chan_b, 100_000, &mut payment_id, &mut payment_idx); },
1214 0x44 => { send_hop_payment(&nodes[0], &nodes[1], chan_a, &nodes[2], chan_b, 100_000, &mut payment_id, &mut payment_idx); },
1215 0x45 => { send_hop_payment(&nodes[2], &nodes[1], chan_b, &nodes[0], chan_a, 100_000, &mut payment_id, &mut payment_idx); },
1217 0x48 => { send_payment(&nodes[0], &nodes[1], chan_a, 10_000, &mut payment_id, &mut payment_idx); },
1218 0x49 => { send_payment(&nodes[1], &nodes[0], chan_a, 10_000, &mut payment_id, &mut payment_idx); },
1219 0x4a => { send_payment(&nodes[1], &nodes[2], chan_b, 10_000, &mut payment_id, &mut payment_idx); },
1220 0x4b => { send_payment(&nodes[2], &nodes[1], chan_b, 10_000, &mut payment_id, &mut payment_idx); },
1221 0x4c => { send_hop_payment(&nodes[0], &nodes[1], chan_a, &nodes[2], chan_b, 10_000, &mut payment_id, &mut payment_idx); },
1222 0x4d => { send_hop_payment(&nodes[2], &nodes[1], chan_b, &nodes[0], chan_a, 10_000, &mut payment_id, &mut payment_idx); },
1224 0x50 => { send_payment(&nodes[0], &nodes[1], chan_a, 1_000, &mut payment_id, &mut payment_idx); },
1225 0x51 => { send_payment(&nodes[1], &nodes[0], chan_a, 1_000, &mut payment_id, &mut payment_idx); },
1226 0x52 => { send_payment(&nodes[1], &nodes[2], chan_b, 1_000, &mut payment_id, &mut payment_idx); },
1227 0x53 => { send_payment(&nodes[2], &nodes[1], chan_b, 1_000, &mut payment_id, &mut payment_idx); },
1228 0x54 => { send_hop_payment(&nodes[0], &nodes[1], chan_a, &nodes[2], chan_b, 1_000, &mut payment_id, &mut payment_idx); },
1229 0x55 => { send_hop_payment(&nodes[2], &nodes[1], chan_b, &nodes[0], chan_a, 1_000, &mut payment_id, &mut payment_idx); },
1231 0x58 => { send_payment(&nodes[0], &nodes[1], chan_a, 100, &mut payment_id, &mut payment_idx); },
1232 0x59 => { send_payment(&nodes[1], &nodes[0], chan_a, 100, &mut payment_id, &mut payment_idx); },
1233 0x5a => { send_payment(&nodes[1], &nodes[2], chan_b, 100, &mut payment_id, &mut payment_idx); },
1234 0x5b => { send_payment(&nodes[2], &nodes[1], chan_b, 100, &mut payment_id, &mut payment_idx); },
1235 0x5c => { send_hop_payment(&nodes[0], &nodes[1], chan_a, &nodes[2], chan_b, 100, &mut payment_id, &mut payment_idx); },
1236 0x5d => { send_hop_payment(&nodes[2], &nodes[1], chan_b, &nodes[0], chan_a, 100, &mut payment_id, &mut payment_idx); },
1238 0x60 => { send_payment(&nodes[0], &nodes[1], chan_a, 10, &mut payment_id, &mut payment_idx); },
1239 0x61 => { send_payment(&nodes[1], &nodes[0], chan_a, 10, &mut payment_id, &mut payment_idx); },
1240 0x62 => { send_payment(&nodes[1], &nodes[2], chan_b, 10, &mut payment_id, &mut payment_idx); },
1241 0x63 => { send_payment(&nodes[2], &nodes[1], chan_b, 10, &mut payment_id, &mut payment_idx); },
1242 0x64 => { send_hop_payment(&nodes[0], &nodes[1], chan_a, &nodes[2], chan_b, 10, &mut payment_id, &mut payment_idx); },
1243 0x65 => { send_hop_payment(&nodes[2], &nodes[1], chan_b, &nodes[0], chan_a, 10, &mut payment_id, &mut payment_idx); },
1245 0x68 => { send_payment(&nodes[0], &nodes[1], chan_a, 1, &mut payment_id, &mut payment_idx); },
1246 0x69 => { send_payment(&nodes[1], &nodes[0], chan_a, 1, &mut payment_id, &mut payment_idx); },
1247 0x6a => { send_payment(&nodes[1], &nodes[2], chan_b, 1, &mut payment_id, &mut payment_idx); },
1248 0x6b => { send_payment(&nodes[2], &nodes[1], chan_b, 1, &mut payment_id, &mut payment_idx); },
1249 0x6c => { send_hop_payment(&nodes[0], &nodes[1], chan_a, &nodes[2], chan_b, 1, &mut payment_id, &mut payment_idx); },
1250 0x6d => { send_hop_payment(&nodes[2], &nodes[1], chan_b, &nodes[0], chan_a, 1, &mut payment_id, &mut payment_idx); },
1253 let mut max_feerate = last_htlc_clear_fee_a;
1255 max_feerate *= FEE_SPIKE_BUFFER_FEE_INCREASE_MULTIPLE as u32;
1257 if fee_est_a.ret_val.fetch_add(250, atomic::Ordering::AcqRel) + 250 > max_feerate {
1258 fee_est_a.ret_val.store(max_feerate, atomic::Ordering::Release);
1260 nodes[0].maybe_update_chan_fees();
1262 0x81 => { fee_est_a.ret_val.store(253, atomic::Ordering::Release); nodes[0].maybe_update_chan_fees(); },
1265 let mut max_feerate = last_htlc_clear_fee_b;
1267 max_feerate *= FEE_SPIKE_BUFFER_FEE_INCREASE_MULTIPLE as u32;
1269 if fee_est_b.ret_val.fetch_add(250, atomic::Ordering::AcqRel) + 250 > max_feerate {
1270 fee_est_b.ret_val.store(max_feerate, atomic::Ordering::Release);
1272 nodes[1].maybe_update_chan_fees();
1274 0x85 => { fee_est_b.ret_val.store(253, atomic::Ordering::Release); nodes[1].maybe_update_chan_fees(); },
1277 let mut max_feerate = last_htlc_clear_fee_c;
1279 max_feerate *= FEE_SPIKE_BUFFER_FEE_INCREASE_MULTIPLE as u32;
1281 if fee_est_c.ret_val.fetch_add(250, atomic::Ordering::AcqRel) + 250 > max_feerate {
1282 fee_est_c.ret_val.store(max_feerate, atomic::Ordering::Release);
1284 nodes[2].maybe_update_chan_fees();
1286 0x89 => { fee_est_c.ret_val.store(253, atomic::Ordering::Release); nodes[2].maybe_update_chan_fees(); },
1289 let pending_updates = monitor_a.chain_monitor.list_pending_monitor_updates().remove(&chan_1_funding).unwrap();
1290 if let Some(id) = pending_updates.get(0) {
1291 monitor_a.chain_monitor.channel_monitor_updated(chan_1_funding, *id).unwrap();
1293 nodes[0].process_monitor_events();
1296 let pending_updates = monitor_a.chain_monitor.list_pending_monitor_updates().remove(&chan_1_funding).unwrap();
1297 if let Some(id) = pending_updates.get(1) {
1298 monitor_a.chain_monitor.channel_monitor_updated(chan_1_funding, *id).unwrap();
1300 nodes[0].process_monitor_events();
1303 let pending_updates = monitor_a.chain_monitor.list_pending_monitor_updates().remove(&chan_1_funding).unwrap();
1304 if let Some(id) = pending_updates.last() {
1305 monitor_a.chain_monitor.channel_monitor_updated(chan_1_funding, *id).unwrap();
1307 nodes[0].process_monitor_events();
1311 let pending_updates = monitor_b.chain_monitor.list_pending_monitor_updates().remove(&chan_1_funding).unwrap();
1312 if let Some(id) = pending_updates.get(0) {
1313 monitor_b.chain_monitor.channel_monitor_updated(chan_1_funding, *id).unwrap();
1315 nodes[1].process_monitor_events();
1318 let pending_updates = monitor_b.chain_monitor.list_pending_monitor_updates().remove(&chan_1_funding).unwrap();
1319 if let Some(id) = pending_updates.get(1) {
1320 monitor_b.chain_monitor.channel_monitor_updated(chan_1_funding, *id).unwrap();
1322 nodes[1].process_monitor_events();
1325 let pending_updates = monitor_b.chain_monitor.list_pending_monitor_updates().remove(&chan_1_funding).unwrap();
1326 if let Some(id) = pending_updates.last() {
1327 monitor_b.chain_monitor.channel_monitor_updated(chan_1_funding, *id).unwrap();
1329 nodes[1].process_monitor_events();
1333 let pending_updates = monitor_b.chain_monitor.list_pending_monitor_updates().remove(&chan_2_funding).unwrap();
1334 if let Some(id) = pending_updates.get(0) {
1335 monitor_b.chain_monitor.channel_monitor_updated(chan_2_funding, *id).unwrap();
1337 nodes[1].process_monitor_events();
1340 let pending_updates = monitor_b.chain_monitor.list_pending_monitor_updates().remove(&chan_2_funding).unwrap();
1341 if let Some(id) = pending_updates.get(1) {
1342 monitor_b.chain_monitor.channel_monitor_updated(chan_2_funding, *id).unwrap();
1344 nodes[1].process_monitor_events();
1347 let pending_updates = monitor_b.chain_monitor.list_pending_monitor_updates().remove(&chan_2_funding).unwrap();
1348 if let Some(id) = pending_updates.last() {
1349 monitor_b.chain_monitor.channel_monitor_updated(chan_2_funding, *id).unwrap();
1351 nodes[1].process_monitor_events();
1355 let pending_updates = monitor_c.chain_monitor.list_pending_monitor_updates().remove(&chan_2_funding).unwrap();
1356 if let Some(id) = pending_updates.get(0) {
1357 monitor_c.chain_monitor.channel_monitor_updated(chan_2_funding, *id).unwrap();
1359 nodes[2].process_monitor_events();
1362 let pending_updates = monitor_c.chain_monitor.list_pending_monitor_updates().remove(&chan_2_funding).unwrap();
1363 if let Some(id) = pending_updates.get(1) {
1364 monitor_c.chain_monitor.channel_monitor_updated(chan_2_funding, *id).unwrap();
1366 nodes[2].process_monitor_events();
1369 let pending_updates = monitor_c.chain_monitor.list_pending_monitor_updates().remove(&chan_2_funding).unwrap();
1370 if let Some(id) = pending_updates.last() {
1371 monitor_c.chain_monitor.channel_monitor_updated(chan_2_funding, *id).unwrap();
1373 nodes[2].process_monitor_events();
1377 // Test that no channel is in a stuck state where neither party can send funds even
1378 // after we resolve all pending events.
1379 // First make sure there are no pending monitor updates, resetting the error state
1380 // and calling force_channel_monitor_updated for each monitor.
1381 *monitor_a.persister.update_ret.lock().unwrap() = ChannelMonitorUpdateStatus::Completed;
1382 *monitor_b.persister.update_ret.lock().unwrap() = ChannelMonitorUpdateStatus::Completed;
1383 *monitor_c.persister.update_ret.lock().unwrap() = ChannelMonitorUpdateStatus::Completed;
1385 if let Some((id, _)) = monitor_a.latest_monitors.lock().unwrap().get(&chan_1_funding) {
1386 monitor_a.chain_monitor.force_channel_monitor_updated(chan_1_funding, *id);
1387 nodes[0].process_monitor_events();
1389 if let Some((id, _)) = monitor_b.latest_monitors.lock().unwrap().get(&chan_1_funding) {
1390 monitor_b.chain_monitor.force_channel_monitor_updated(chan_1_funding, *id);
1391 nodes[1].process_monitor_events();
1393 if let Some((id, _)) = monitor_b.latest_monitors.lock().unwrap().get(&chan_2_funding) {
1394 monitor_b.chain_monitor.force_channel_monitor_updated(chan_2_funding, *id);
1395 nodes[1].process_monitor_events();
1397 if let Some((id, _)) = monitor_c.latest_monitors.lock().unwrap().get(&chan_2_funding) {
1398 monitor_c.chain_monitor.force_channel_monitor_updated(chan_2_funding, *id);
1399 nodes[2].process_monitor_events();
1402 // Next, make sure peers are all connected to each other
1403 if chan_a_disconnected {
1404 nodes[0].peer_connected(&nodes[1].get_our_node_id(), &Init {
1405 features: nodes[1].init_features(), networks: None, remote_network_address: None
1407 nodes[1].peer_connected(&nodes[0].get_our_node_id(), &Init {
1408 features: nodes[0].init_features(), networks: None, remote_network_address: None
1410 chan_a_disconnected = false;
1412 if chan_b_disconnected {
1413 nodes[1].peer_connected(&nodes[2].get_our_node_id(), &Init {
1414 features: nodes[2].init_features(), networks: None, remote_network_address: None
1416 nodes[2].peer_connected(&nodes[1].get_our_node_id(), &Init {
1417 features: nodes[1].init_features(), networks: None, remote_network_address: None
1419 chan_b_disconnected = false;
1422 for i in 0..std::usize::MAX {
1423 if i == 100 { panic!("It may take may iterations to settle the state, but it should not take forever"); }
1424 // Then, make sure any current forwards make their way to their destination
1425 if process_msg_events!(0, false, ProcessMessages::AllMessages) { continue; }
1426 if process_msg_events!(1, false, ProcessMessages::AllMessages) { continue; }
1427 if process_msg_events!(2, false, ProcessMessages::AllMessages) { continue; }
1428 // ...making sure any pending PendingHTLCsForwardable events are handled and
1429 // payments claimed.
1430 if process_events!(0, false) { continue; }
1431 if process_events!(1, false) { continue; }
1432 if process_events!(2, false) { continue; }
1436 // Finally, make sure that at least one end of each channel can make a substantial payment
1438 send_payment(&nodes[0], &nodes[1], chan_a, 10_000_000, &mut payment_id, &mut payment_idx) ||
1439 send_payment(&nodes[1], &nodes[0], chan_a, 10_000_000, &mut payment_id, &mut payment_idx));
1441 send_payment(&nodes[1], &nodes[2], chan_b, 10_000_000, &mut payment_id, &mut payment_idx) ||
1442 send_payment(&nodes[2], &nodes[1], chan_b, 10_000_000, &mut payment_id, &mut payment_idx));
1444 last_htlc_clear_fee_a = fee_est_a.ret_val.load(atomic::Ordering::Acquire);
1445 last_htlc_clear_fee_b = fee_est_b.ret_val.load(atomic::Ordering::Acquire);
1446 last_htlc_clear_fee_c = fee_est_c.ret_val.load(atomic::Ordering::Acquire);
1448 _ => test_return!(),
1451 if nodes[0].get_and_clear_needs_persistence() == true {
1452 node_a_ser.0.clear();
1453 nodes[0].write(&mut node_a_ser).unwrap();
1455 if nodes[1].get_and_clear_needs_persistence() == true {
1456 node_b_ser.0.clear();
1457 nodes[1].write(&mut node_b_ser).unwrap();
1459 if nodes[2].get_and_clear_needs_persistence() == true {
1460 node_c_ser.0.clear();
1461 nodes[2].write(&mut node_c_ser).unwrap();
1466 /// We actually have different behavior based on if a certain log string has been seen, so we have
1467 /// to do a bit more tracking.
1469 struct SearchingOutput<O: Output> {
1471 may_fail: Arc<atomic::AtomicBool>,
1473 impl<O: Output> Output for SearchingOutput<O> {
1474 fn locked_write(&self, data: &[u8]) {
1475 // We hit a design limitation of LN state machine (see CONCURRENT_INBOUND_HTLC_FEE_BUFFER)
1476 if std::str::from_utf8(data).unwrap().contains("Outbound update_fee HTLC buffer overflow - counterparty should force-close this channel") {
1477 self.may_fail.store(true, atomic::Ordering::Release);
1479 self.output.locked_write(data)
1482 impl<O: Output> SearchingOutput<O> {
1483 pub fn new(output: O) -> Self {
1484 Self { output, may_fail: Arc::new(atomic::AtomicBool::new(false)) }
1488 pub fn chanmon_consistency_test<Out: Output>(data: &[u8], out: Out) {
1489 do_test(data, out.clone(), false);
1490 do_test(data, out, true);
1494 pub extern "C" fn chanmon_consistency_run(data: *const u8, datalen: usize) {
1495 do_test(unsafe { std::slice::from_raw_parts(data, datalen) }, test_logger::DevNull{}, false);
1496 do_test(unsafe { std::slice::from_raw_parts(data, datalen) }, test_logger::DevNull{}, true);