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 /// The LDK API requires that any time we tell it we're done persisting a `ChannelMonitor[Update]`
146 /// we never pass it in as the "latest" `ChannelMonitor` on startup. However, we can pass
147 /// out-of-date monitors as long as we never told LDK we finished persisting them, which we do by
148 /// storing both old `ChannelMonitor`s and ones that are "being persisted" here.
150 /// Note that such "being persisted" `ChannelMonitor`s are stored in `ChannelManager` and will
151 /// simply be replayed on startup.
152 struct LatestMonitorState {
153 /// The latest monitor id which we told LDK we've persisted
154 persisted_monitor_id: u64,
155 /// The latest serialized `ChannelMonitor` that we told LDK we persisted.
156 persisted_monitor: Vec<u8>,
157 /// A set of (monitor id, serialized `ChannelMonitor`)s which we're currently "persisting",
158 /// from LDK's perspective.
159 pending_monitors: Vec<(u64, Vec<u8>)>,
162 struct TestChainMonitor {
163 pub logger: Arc<dyn Logger>,
164 pub keys: Arc<KeyProvider>,
165 pub persister: Arc<TestPersister>,
166 pub chain_monitor: Arc<chainmonitor::ChainMonitor<TestChannelSigner, Arc<dyn chain::Filter>, Arc<TestBroadcaster>, Arc<FuzzEstimator>, Arc<dyn Logger>, Arc<TestPersister>>>,
167 pub latest_monitors: Mutex<HashMap<OutPoint, LatestMonitorState>>,
169 impl TestChainMonitor {
170 pub fn new(broadcaster: Arc<TestBroadcaster>, logger: Arc<dyn Logger>, feeest: Arc<FuzzEstimator>, persister: Arc<TestPersister>, keys: Arc<KeyProvider>) -> Self {
172 chain_monitor: Arc::new(chainmonitor::ChainMonitor::new(None, broadcaster, logger.clone(), feeest, Arc::clone(&persister))),
176 latest_monitors: Mutex::new(new_hash_map()),
180 impl chain::Watch<TestChannelSigner> for TestChainMonitor {
181 fn watch_channel(&self, funding_txo: OutPoint, monitor: channelmonitor::ChannelMonitor<TestChannelSigner>) -> Result<chain::ChannelMonitorUpdateStatus, ()> {
182 let mut ser = VecWriter(Vec::new());
183 monitor.write(&mut ser).unwrap();
184 let monitor_id = monitor.get_latest_update_id();
185 let res = self.chain_monitor.watch_channel(funding_txo, monitor);
186 let state = match res {
187 Ok(chain::ChannelMonitorUpdateStatus::Completed) => {
189 persisted_monitor_id: monitor_id, persisted_monitor: ser.0,
190 pending_monitors: Vec::new(),
193 Ok(chain::ChannelMonitorUpdateStatus::InProgress) =>
194 panic!("The test currently doesn't test initial-persistence via the async pipeline"),
195 Ok(chain::ChannelMonitorUpdateStatus::UnrecoverableError) => panic!(),
198 if self.latest_monitors.lock().unwrap().insert(funding_txo, state).is_some() {
199 panic!("Already had monitor pre-watch_channel");
204 fn update_channel(&self, funding_txo: OutPoint, update: &channelmonitor::ChannelMonitorUpdate) -> chain::ChannelMonitorUpdateStatus {
205 let mut map_lock = self.latest_monitors.lock().unwrap();
206 let map_entry = map_lock.get_mut(&funding_txo).expect("Didn't have monitor on update call");
207 let latest_monitor_data = map_entry.pending_monitors.last().as_ref().map(|(_, data)| data).unwrap_or(&map_entry.persisted_monitor);
208 let deserialized_monitor = <(BlockHash, channelmonitor::ChannelMonitor<TestChannelSigner>)>::
209 read(&mut Cursor::new(&latest_monitor_data), (&*self.keys, &*self.keys)).unwrap().1;
210 deserialized_monitor.update_monitor(update, &&TestBroadcaster{}, &&FuzzEstimator { ret_val: atomic::AtomicU32::new(253) }, &self.logger).unwrap();
211 let mut ser = VecWriter(Vec::new());
212 deserialized_monitor.write(&mut ser).unwrap();
213 let res = self.chain_monitor.update_channel(funding_txo, update);
215 chain::ChannelMonitorUpdateStatus::Completed => {
216 map_entry.persisted_monitor_id = update.update_id;
217 map_entry.persisted_monitor = ser.0;
219 chain::ChannelMonitorUpdateStatus::InProgress => {
220 map_entry.pending_monitors.push((update.update_id, ser.0));
222 chain::ChannelMonitorUpdateStatus::UnrecoverableError => panic!(),
227 fn release_pending_monitor_events(&self) -> Vec<(OutPoint, ChannelId, Vec<MonitorEvent>, Option<PublicKey>)> {
228 return self.chain_monitor.release_pending_monitor_events();
233 node_secret: SecretKey,
234 rand_bytes_id: atomic::AtomicU32,
235 enforcement_states: Mutex<HashMap<[u8;32], Arc<Mutex<EnforcementState>>>>,
238 impl EntropySource for KeyProvider {
239 fn get_secure_random_bytes(&self) -> [u8; 32] {
240 let id = self.rand_bytes_id.fetch_add(1, atomic::Ordering::Relaxed);
241 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]];
242 res[30-4..30].copy_from_slice(&id.to_le_bytes());
247 impl NodeSigner for KeyProvider {
248 fn get_node_id(&self, recipient: Recipient) -> Result<PublicKey, ()> {
249 let node_secret = match recipient {
250 Recipient::Node => Ok(&self.node_secret),
251 Recipient::PhantomNode => Err(())
253 Ok(PublicKey::from_secret_key(&Secp256k1::signing_only(), node_secret))
256 fn ecdh(&self, recipient: Recipient, other_key: &PublicKey, tweak: Option<&Scalar>) -> Result<SharedSecret, ()> {
257 let mut node_secret = match recipient {
258 Recipient::Node => Ok(self.node_secret.clone()),
259 Recipient::PhantomNode => Err(())
261 if let Some(tweak) = tweak {
262 node_secret = node_secret.mul_tweak(tweak).map_err(|_| ())?;
264 Ok(SharedSecret::new(other_key, &node_secret))
267 fn get_inbound_payment_key_material(&self) -> KeyMaterial {
268 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]])
271 fn sign_invoice(&self, _hrp_bytes: &[u8], _invoice_data: &[u5], _recipient: Recipient) -> Result<RecoverableSignature, ()> {
275 fn sign_bolt12_invoice_request(
276 &self, _invoice_request: &UnsignedInvoiceRequest
277 ) -> Result<schnorr::Signature, ()> {
281 fn sign_bolt12_invoice(
282 &self, _invoice: &UnsignedBolt12Invoice,
283 ) -> Result<schnorr::Signature, ()> {
287 fn sign_gossip_message(&self, msg: lightning::ln::msgs::UnsignedGossipMessage) -> Result<Signature, ()> {
288 let msg_hash = Message::from_digest(Sha256dHash::hash(&msg.encode()[..]).to_byte_array());
289 let secp_ctx = Secp256k1::signing_only();
290 Ok(secp_ctx.sign_ecdsa(&msg_hash, &self.node_secret))
294 impl SignerProvider for KeyProvider {
295 type EcdsaSigner = TestChannelSigner;
297 type TaprootSigner = TestChannelSigner;
299 fn generate_channel_keys_id(&self, _inbound: bool, _channel_value_satoshis: u64, _user_channel_id: u128) -> [u8; 32] {
300 let id = self.rand_bytes_id.fetch_add(1, atomic::Ordering::Relaxed) as u8;
304 fn derive_channel_signer(&self, channel_value_satoshis: u64, channel_keys_id: [u8; 32]) -> Self::EcdsaSigner {
305 let secp_ctx = Secp256k1::signing_only();
306 let id = channel_keys_id[0];
307 let keys = InMemorySigner::new(
309 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(),
310 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(),
311 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(),
312 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(),
313 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(),
314 [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]],
315 channel_value_satoshis,
319 let revoked_commitment = self.make_enforcement_state_cell(keys.commitment_seed);
320 TestChannelSigner::new_with_revoked(keys, revoked_commitment, false)
323 fn read_chan_signer(&self, buffer: &[u8]) -> Result<Self::EcdsaSigner, DecodeError> {
324 let mut reader = std::io::Cursor::new(buffer);
326 let inner: InMemorySigner = ReadableArgs::read(&mut reader, self)?;
327 let state = self.make_enforcement_state_cell(inner.commitment_seed);
329 Ok(TestChannelSigner {
332 disable_revocation_policy_check: false,
333 available: Arc::new(Mutex::new(true)),
337 fn get_destination_script(&self, _channel_keys_id: [u8; 32]) -> Result<ScriptBuf, ()> {
338 let secp_ctx = Secp256k1::signing_only();
339 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();
340 let our_channel_monitor_claim_key_hash = WPubkeyHash::hash(&PublicKey::from_secret_key(&secp_ctx, &channel_monitor_claim_key).serialize());
341 Ok(Builder::new().push_opcode(opcodes::all::OP_PUSHBYTES_0).push_slice(our_channel_monitor_claim_key_hash).into_script())
344 fn get_shutdown_scriptpubkey(&self) -> Result<ShutdownScript, ()> {
345 let secp_ctx = Secp256k1::signing_only();
346 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();
347 let pubkey_hash = WPubkeyHash::hash(&PublicKey::from_secret_key(&secp_ctx, &secret_key).serialize());
348 Ok(ShutdownScript::new_p2wpkh(&pubkey_hash))
353 fn make_enforcement_state_cell(&self, commitment_seed: [u8; 32]) -> Arc<Mutex<EnforcementState>> {
354 let mut revoked_commitments = self.enforcement_states.lock().unwrap();
355 if !revoked_commitments.contains_key(&commitment_seed) {
356 revoked_commitments.insert(commitment_seed, Arc::new(Mutex::new(EnforcementState::new())));
358 let cell = revoked_commitments.get(&commitment_seed).unwrap();
364 fn check_api_err(api_err: APIError, sendable_bounds_violated: bool) {
366 APIError::APIMisuseError { .. } => panic!("We can't misuse the API"),
367 APIError::FeeRateTooHigh { .. } => panic!("We can't send too much fee?"),
368 APIError::InvalidRoute { .. } => panic!("Our routes should work"),
369 APIError::ChannelUnavailable { err } => {
370 // Test the error against a list of errors we can hit, and reject
371 // all others. If you hit this panic, the list of acceptable errors
372 // is probably just stale and you should add new messages here.
374 "Peer for first hop currently disconnected" => {},
375 _ if err.starts_with("Cannot send less than our next-HTLC minimum - ") => {},
376 _ if err.starts_with("Cannot send more than our next-HTLC maximum - ") => {},
377 _ => panic!("{}", err),
379 assert!(sendable_bounds_violated);
381 APIError::MonitorUpdateInProgress => {
382 // We can (obviously) temp-fail a monitor update
384 APIError::IncompatibleShutdownScript { .. } => panic!("Cannot send an incompatible shutdown script"),
388 fn check_payment_err(send_err: PaymentSendFailure, sendable_bounds_violated: bool) {
390 PaymentSendFailure::ParameterError(api_err) => check_api_err(api_err, sendable_bounds_violated),
391 PaymentSendFailure::PathParameterError(per_path_results) => {
392 for res in per_path_results { if let Err(api_err) = res { check_api_err(api_err, sendable_bounds_violated); } }
394 PaymentSendFailure::AllFailedResendSafe(per_path_results) => {
395 for api_err in per_path_results { check_api_err(api_err, sendable_bounds_violated); }
397 PaymentSendFailure::PartialFailure { results, .. } => {
398 for res in results { if let Err(api_err) = res { check_api_err(api_err, sendable_bounds_violated); } }
400 PaymentSendFailure::DuplicatePayment => panic!(),
404 type ChanMan<'a> = ChannelManager<Arc<TestChainMonitor>, Arc<TestBroadcaster>, Arc<KeyProvider>, Arc<KeyProvider>, Arc<KeyProvider>, Arc<FuzzEstimator>, &'a FuzzRouter, Arc<dyn Logger>>;
407 fn get_payment_secret_hash(dest: &ChanMan, payment_id: &mut u8) -> Option<(PaymentSecret, PaymentHash)> {
408 let mut payment_hash;
410 payment_hash = PaymentHash(Sha256::hash(&[*payment_id; 1]).to_byte_array());
411 if let Ok(payment_secret) = dest.create_inbound_payment_for_hash(payment_hash, None, 3600, None) {
412 return Some((payment_secret, payment_hash));
414 *payment_id = payment_id.wrapping_add(1);
420 fn send_payment(source: &ChanMan, dest: &ChanMan, dest_chan_id: u64, amt: u64, payment_id: &mut u8, payment_idx: &mut u64) -> bool {
421 let (payment_secret, payment_hash) =
422 if let Some((secret, hash)) = get_payment_secret_hash(dest, payment_id) { (secret, hash) } else { return true; };
423 let mut payment_id = [0; 32];
424 payment_id[0..8].copy_from_slice(&payment_idx.to_ne_bytes());
426 let (min_value_sendable, max_value_sendable) = source.list_usable_channels()
427 .iter().find(|chan| chan.short_channel_id == Some(dest_chan_id))
429 (chan.next_outbound_htlc_minimum_msat, chan.next_outbound_htlc_limit_msat))
431 if let Err(err) = source.send_payment_with_route(&Route {
432 paths: vec![Path { hops: vec![RouteHop {
433 pubkey: dest.get_our_node_id(),
434 node_features: dest.node_features(),
435 short_channel_id: dest_chan_id,
436 channel_features: dest.channel_features(),
438 cltv_expiry_delta: 200,
439 maybe_announced_channel: true,
440 }], blinded_tail: None }],
442 }, payment_hash, RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_id)) {
443 check_payment_err(err, amt > max_value_sendable || amt < min_value_sendable);
446 // Note that while the max is a strict upper-bound, we can occasionally send substantially
447 // below the minimum, with some gap which is unusable immediately below the minimum. Thus,
448 // we don't check against min_value_sendable here.
449 assert!(amt <= max_value_sendable);
454 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 {
455 let (payment_secret, payment_hash) =
456 if let Some((secret, hash)) = get_payment_secret_hash(dest, payment_id) { (secret, hash) } else { return true; };
457 let mut payment_id = [0; 32];
458 payment_id[0..8].copy_from_slice(&payment_idx.to_ne_bytes());
460 let (min_value_sendable, max_value_sendable) = source.list_usable_channels()
461 .iter().find(|chan| chan.short_channel_id == Some(middle_chan_id))
463 (chan.next_outbound_htlc_minimum_msat, chan.next_outbound_htlc_limit_msat))
465 let first_hop_fee = 50_000;
466 if let Err(err) = source.send_payment_with_route(&Route {
467 paths: vec![Path { hops: vec![RouteHop {
468 pubkey: middle.get_our_node_id(),
469 node_features: middle.node_features(),
470 short_channel_id: middle_chan_id,
471 channel_features: middle.channel_features(),
472 fee_msat: first_hop_fee,
473 cltv_expiry_delta: 100,
474 maybe_announced_channel: true,
476 pubkey: dest.get_our_node_id(),
477 node_features: dest.node_features(),
478 short_channel_id: dest_chan_id,
479 channel_features: dest.channel_features(),
481 cltv_expiry_delta: 200,
482 maybe_announced_channel: true,
483 }], blinded_tail: None }],
485 }, payment_hash, RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_id)) {
486 let sent_amt = amt + first_hop_fee;
487 check_payment_err(err, sent_amt < min_value_sendable || sent_amt > max_value_sendable);
490 // Note that while the max is a strict upper-bound, we can occasionally send substantially
491 // below the minimum, with some gap which is unusable immediately below the minimum. Thus,
492 // we don't check against min_value_sendable here.
493 assert!(amt + first_hop_fee <= max_value_sendable);
499 pub fn do_test<Out: Output>(data: &[u8], underlying_out: Out, anchors: bool) {
500 let out = SearchingOutput::new(underlying_out);
501 let broadcast = Arc::new(TestBroadcaster{});
502 let router = FuzzRouter {};
504 macro_rules! make_node {
505 ($node_id: expr, $fee_estimator: expr) => { {
506 let logger: Arc<dyn Logger> = Arc::new(test_logger::TestLogger::new($node_id.to_string(), out.clone()));
507 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();
508 let keys_manager = Arc::new(KeyProvider { node_secret, rand_bytes_id: atomic::AtomicU32::new(0), enforcement_states: Mutex::new(new_hash_map()) });
509 let monitor = Arc::new(TestChainMonitor::new(broadcast.clone(), logger.clone(), $fee_estimator.clone(),
510 Arc::new(TestPersister {
511 update_ret: Mutex::new(ChannelMonitorUpdateStatus::Completed)
512 }), Arc::clone(&keys_manager)));
514 let mut config = UserConfig::default();
515 config.channel_config.forwarding_fee_proportional_millionths = 0;
516 config.channel_handshake_config.announced_channel = true;
518 config.channel_handshake_config.negotiate_anchors_zero_fee_htlc_tx = true;
519 config.manually_accept_inbound_channels = true;
521 let network = Network::Bitcoin;
522 let best_block_timestamp = genesis_block(network).header.time;
523 let params = ChainParameters {
525 best_block: BestBlock::from_network(network),
527 (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),
528 monitor, keys_manager)
532 macro_rules! reload_node {
533 ($ser: expr, $node_id: expr, $old_monitors: expr, $keys_manager: expr, $fee_estimator: expr) => { {
534 let keys_manager = Arc::clone(& $keys_manager);
535 let logger: Arc<dyn Logger> = Arc::new(test_logger::TestLogger::new($node_id.to_string(), out.clone()));
536 let chain_monitor = Arc::new(TestChainMonitor::new(broadcast.clone(), logger.clone(), $fee_estimator.clone(),
537 Arc::new(TestPersister {
538 update_ret: Mutex::new(ChannelMonitorUpdateStatus::Completed)
539 }), Arc::clone(& $keys_manager)));
541 let mut config = UserConfig::default();
542 config.channel_config.forwarding_fee_proportional_millionths = 0;
543 config.channel_handshake_config.announced_channel = true;
545 config.channel_handshake_config.negotiate_anchors_zero_fee_htlc_tx = true;
546 config.manually_accept_inbound_channels = true;
549 let mut monitors = new_hash_map();
550 let mut old_monitors = $old_monitors.latest_monitors.lock().unwrap();
551 for (outpoint, mut prev_state) in old_monitors.drain() {
552 monitors.insert(outpoint, <(BlockHash, ChannelMonitor<TestChannelSigner>)>::read(
553 &mut Cursor::new(&prev_state.persisted_monitor), (&*$keys_manager, &*$keys_manager)
554 ).expect("Failed to read monitor").1);
555 // Wipe any `ChannelMonitor`s which we never told LDK we finished persisting,
556 // considering them discarded. LDK should replay these for us as they're stored in
557 // the `ChannelManager`.
558 prev_state.pending_monitors.clear();
559 chain_monitor.latest_monitors.lock().unwrap().insert(outpoint, prev_state);
561 let mut monitor_refs = new_hash_map();
562 for (outpoint, monitor) in monitors.iter_mut() {
563 monitor_refs.insert(*outpoint, monitor);
566 let read_args = ChannelManagerReadArgs {
567 entropy_source: keys_manager.clone(),
568 node_signer: keys_manager.clone(),
569 signer_provider: keys_manager.clone(),
570 fee_estimator: $fee_estimator.clone(),
571 chain_monitor: chain_monitor.clone(),
572 tx_broadcaster: broadcast.clone(),
575 default_config: config,
576 channel_monitors: monitor_refs,
579 let res = (<(BlockHash, ChanMan)>::read(&mut Cursor::new(&$ser.0), read_args).expect("Failed to read manager").1, chain_monitor.clone());
580 for (funding_txo, mon) in monitors.drain() {
581 assert_eq!(chain_monitor.chain_monitor.watch_channel(funding_txo, mon),
582 Ok(ChannelMonitorUpdateStatus::Completed));
588 let mut channel_txn = Vec::new();
589 macro_rules! make_channel {
590 ($source: expr, $dest: expr, $dest_keys_manager: expr, $chan_id: expr) => { {
591 $source.peer_connected(&$dest.get_our_node_id(), &Init {
592 features: $dest.init_features(), networks: None, remote_network_address: None
594 $dest.peer_connected(&$source.get_our_node_id(), &Init {
595 features: $source.init_features(), networks: None, remote_network_address: None
598 $source.create_channel($dest.get_our_node_id(), 100_000, 42, 0, None, None).unwrap();
600 let events = $source.get_and_clear_pending_msg_events();
601 assert_eq!(events.len(), 1);
602 if let events::MessageSendEvent::SendOpenChannel { ref msg, .. } = events[0] {
604 } else { panic!("Wrong event type"); }
607 $dest.handle_open_channel(&$source.get_our_node_id(), &open_channel);
608 let accept_channel = {
610 let events = $dest.get_and_clear_pending_events();
611 assert_eq!(events.len(), 1);
612 if let events::Event::OpenChannelRequest {
613 ref temporary_channel_id, ref counterparty_node_id, ..
615 let mut random_bytes = [0u8; 16];
616 random_bytes.copy_from_slice(&$dest_keys_manager.get_secure_random_bytes()[..16]);
617 let user_channel_id = u128::from_be_bytes(random_bytes);
618 $dest.accept_inbound_channel(
619 temporary_channel_id,
620 counterparty_node_id,
623 } else { panic!("Wrong event type"); }
625 let events = $dest.get_and_clear_pending_msg_events();
626 assert_eq!(events.len(), 1);
627 if let events::MessageSendEvent::SendAcceptChannel { ref msg, .. } = events[0] {
629 } else { panic!("Wrong event type"); }
632 $source.handle_accept_channel(&$dest.get_our_node_id(), &accept_channel);
635 let events = $source.get_and_clear_pending_events();
636 assert_eq!(events.len(), 1);
637 if let events::Event::FundingGenerationReady { ref temporary_channel_id, ref channel_value_satoshis, ref output_script, .. } = events[0] {
638 let tx = Transaction { version: Version($chan_id), lock_time: LockTime::ZERO, input: Vec::new(), output: vec![TxOut {
639 value: Amount::from_sat(*channel_value_satoshis), script_pubkey: output_script.clone(),
641 funding_output = OutPoint { txid: tx.txid(), index: 0 };
642 $source.funding_transaction_generated(&temporary_channel_id, &$dest.get_our_node_id(), tx.clone()).unwrap();
643 channel_txn.push(tx);
644 } else { panic!("Wrong event type"); }
647 let funding_created = {
648 let events = $source.get_and_clear_pending_msg_events();
649 assert_eq!(events.len(), 1);
650 if let events::MessageSendEvent::SendFundingCreated { ref msg, .. } = events[0] {
652 } else { panic!("Wrong event type"); }
654 $dest.handle_funding_created(&$source.get_our_node_id(), &funding_created);
656 let funding_signed = {
657 let events = $dest.get_and_clear_pending_msg_events();
658 assert_eq!(events.len(), 1);
659 if let events::MessageSendEvent::SendFundingSigned { ref msg, .. } = events[0] {
661 } else { panic!("Wrong event type"); }
663 let events = $dest.get_and_clear_pending_events();
664 assert_eq!(events.len(), 1);
665 if let events::Event::ChannelPending{ ref counterparty_node_id, .. } = events[0] {
666 assert_eq!(counterparty_node_id, &$source.get_our_node_id());
667 } else { panic!("Wrong event type"); }
669 $source.handle_funding_signed(&$dest.get_our_node_id(), &funding_signed);
670 let events = $source.get_and_clear_pending_events();
671 assert_eq!(events.len(), 1);
672 if let events::Event::ChannelPending{ ref counterparty_node_id, .. } = events[0] {
673 assert_eq!(counterparty_node_id, &$dest.get_our_node_id());
674 } else { panic!("Wrong event type"); }
680 macro_rules! confirm_txn {
682 let chain_hash = genesis_block(Network::Bitcoin).block_hash();
683 let mut header = create_dummy_header(chain_hash, 42);
684 let txdata: Vec<_> = channel_txn.iter().enumerate().map(|(i, tx)| (i + 1, tx)).collect();
685 $node.transactions_confirmed(&header, &txdata, 1);
687 header = create_dummy_header(header.block_hash(), 42);
689 $node.best_block_updated(&header, 99);
693 macro_rules! lock_fundings {
694 ($nodes: expr) => { {
695 let mut node_events = Vec::new();
696 for node in $nodes.iter() {
697 node_events.push(node.get_and_clear_pending_msg_events());
699 for (idx, node_event) in node_events.iter().enumerate() {
700 for event in node_event {
701 if let events::MessageSendEvent::SendChannelReady { ref node_id, ref msg } = event {
702 for node in $nodes.iter() {
703 if node.get_our_node_id() == *node_id {
704 node.handle_channel_ready(&$nodes[idx].get_our_node_id(), msg);
707 } else { panic!("Wrong event type"); }
711 for node in $nodes.iter() {
712 let events = node.get_and_clear_pending_msg_events();
713 for event in events {
714 if let events::MessageSendEvent::SendAnnouncementSignatures { .. } = event {
715 } else { panic!("Wrong event type"); }
721 let fee_est_a = Arc::new(FuzzEstimator { ret_val: atomic::AtomicU32::new(253) });
722 let mut last_htlc_clear_fee_a = 253;
723 let fee_est_b = Arc::new(FuzzEstimator { ret_val: atomic::AtomicU32::new(253) });
724 let mut last_htlc_clear_fee_b = 253;
725 let fee_est_c = Arc::new(FuzzEstimator { ret_val: atomic::AtomicU32::new(253) });
726 let mut last_htlc_clear_fee_c = 253;
728 // 3 nodes is enough to hit all the possible cases, notably unknown-source-unknown-dest
730 let (node_a, mut monitor_a, keys_manager_a) = make_node!(0, fee_est_a);
731 let (node_b, mut monitor_b, keys_manager_b) = make_node!(1, fee_est_b);
732 let (node_c, mut monitor_c, keys_manager_c) = make_node!(2, fee_est_c);
734 let mut nodes = [node_a, node_b, node_c];
736 let chan_1_funding = make_channel!(nodes[0], nodes[1], keys_manager_b, 0);
737 let chan_2_funding = make_channel!(nodes[1], nodes[2], keys_manager_c, 1);
739 for node in nodes.iter() {
743 lock_fundings!(nodes);
745 let chan_a = nodes[0].list_usable_channels()[0].short_channel_id.unwrap();
746 let chan_b = nodes[2].list_usable_channels()[0].short_channel_id.unwrap();
748 let mut payment_id: u8 = 0;
749 let mut payment_idx: u64 = 0;
751 let mut chan_a_disconnected = false;
752 let mut chan_b_disconnected = false;
753 let mut ab_events = Vec::new();
754 let mut ba_events = Vec::new();
755 let mut bc_events = Vec::new();
756 let mut cb_events = Vec::new();
758 let mut node_a_ser = VecWriter(Vec::new());
759 nodes[0].write(&mut node_a_ser).unwrap();
760 let mut node_b_ser = VecWriter(Vec::new());
761 nodes[1].write(&mut node_b_ser).unwrap();
762 let mut node_c_ser = VecWriter(Vec::new());
763 nodes[2].write(&mut node_c_ser).unwrap();
765 macro_rules! test_return {
767 assert_eq!(nodes[0].list_channels().len(), 1);
768 assert_eq!(nodes[1].list_channels().len(), 2);
769 assert_eq!(nodes[2].list_channels().len(), 1);
774 let mut read_pos = 0;
775 macro_rules! get_slice {
778 let slice_len = $len as usize;
779 if data.len() < read_pos + slice_len {
782 read_pos += slice_len;
783 &data[read_pos - slice_len..read_pos]
789 // Push any events from Node B onto ba_events and bc_events
790 macro_rules! push_excess_b_events {
791 ($excess_events: expr, $expect_drop_node: expr) => { {
792 let a_id = nodes[0].get_our_node_id();
793 let expect_drop_node: Option<usize> = $expect_drop_node;
794 let expect_drop_id = if let Some(id) = expect_drop_node { Some(nodes[id].get_our_node_id()) } else { None };
795 for event in $excess_events {
796 let push_a = match event {
797 events::MessageSendEvent::UpdateHTLCs { ref node_id, .. } => {
798 if Some(*node_id) == expect_drop_id { panic!("peer_disconnected should drop msgs bound for the disconnected peer"); }
801 events::MessageSendEvent::SendRevokeAndACK { ref node_id, .. } => {
802 if Some(*node_id) == expect_drop_id { panic!("peer_disconnected should drop msgs bound for the disconnected peer"); }
805 events::MessageSendEvent::SendChannelReestablish { ref node_id, .. } => {
806 if Some(*node_id) == expect_drop_id { panic!("peer_disconnected should drop msgs bound for the disconnected peer"); }
809 events::MessageSendEvent::SendChannelReady { .. } => continue,
810 events::MessageSendEvent::SendAnnouncementSignatures { .. } => continue,
811 events::MessageSendEvent::SendChannelUpdate { ref node_id, ref msg } => {
812 assert_eq!(msg.contents.flags & 2, 0); // The disable bit must never be set!
813 if Some(*node_id) == expect_drop_id { panic!("peer_disconnected should drop msgs bound for the disconnected peer"); }
816 _ => panic!("Unhandled message event {:?}", event),
818 if push_a { ba_events.push(event); } else { bc_events.push(event); }
823 // While delivering messages, we select across three possible message selection processes
824 // to ensure we get as much coverage as possible. See the individual enum variants for more
827 enum ProcessMessages {
828 /// Deliver all available messages, including fetching any new messages from
829 /// `get_and_clear_pending_msg_events()` (which may have side effects).
831 /// Call `get_and_clear_pending_msg_events()` first, and then deliver up to one
832 /// message (which may already be queued).
834 /// Deliver up to one already-queued message. This avoids any potential side-effects
835 /// of `get_and_clear_pending_msg_events()` (eg freeing the HTLC holding cell), which
836 /// provides potentially more coverage.
840 macro_rules! process_msg_events {
841 ($node: expr, $corrupt_forward: expr, $limit_events: expr) => { {
842 let mut events = if $node == 1 {
843 let mut new_events = Vec::new();
844 mem::swap(&mut new_events, &mut ba_events);
845 new_events.extend_from_slice(&bc_events[..]);
848 } else if $node == 0 {
849 let mut new_events = Vec::new();
850 mem::swap(&mut new_events, &mut ab_events);
853 let mut new_events = Vec::new();
854 mem::swap(&mut new_events, &mut cb_events);
857 let mut new_events = Vec::new();
858 if $limit_events != ProcessMessages::OnePendingMessage {
859 new_events = nodes[$node].get_and_clear_pending_msg_events();
861 let mut had_events = false;
862 let mut events_iter = events.drain(..).chain(new_events.drain(..));
863 let mut extra_ev = None;
864 for event in &mut events_iter {
867 events::MessageSendEvent::UpdateHTLCs { node_id, updates: CommitmentUpdate { update_add_htlcs, update_fail_htlcs, update_fulfill_htlcs, update_fail_malformed_htlcs, update_fee, commitment_signed } } => {
868 for (idx, dest) in nodes.iter().enumerate() {
869 if dest.get_our_node_id() == node_id {
870 for update_add in update_add_htlcs.iter() {
871 out.locked_write(format!("Delivering update_add_htlc to node {}.\n", idx).as_bytes());
872 if !$corrupt_forward {
873 dest.handle_update_add_htlc(&nodes[$node].get_our_node_id(), update_add);
875 // Corrupt the update_add_htlc message so that its HMAC
876 // check will fail and we generate a
877 // update_fail_malformed_htlc instead of an
878 // update_fail_htlc as we do when we reject a payment.
879 let mut msg_ser = update_add.encode();
880 msg_ser[1000] ^= 0xff;
881 let new_msg = UpdateAddHTLC::read(&mut Cursor::new(&msg_ser)).unwrap();
882 dest.handle_update_add_htlc(&nodes[$node].get_our_node_id(), &new_msg);
885 for update_fulfill in update_fulfill_htlcs.iter() {
886 out.locked_write(format!("Delivering update_fulfill_htlc to node {}.\n", idx).as_bytes());
887 dest.handle_update_fulfill_htlc(&nodes[$node].get_our_node_id(), update_fulfill);
889 for update_fail in update_fail_htlcs.iter() {
890 out.locked_write(format!("Delivering update_fail_htlc to node {}.\n", idx).as_bytes());
891 dest.handle_update_fail_htlc(&nodes[$node].get_our_node_id(), update_fail);
893 for update_fail_malformed in update_fail_malformed_htlcs.iter() {
894 out.locked_write(format!("Delivering update_fail_malformed_htlc to node {}.\n", idx).as_bytes());
895 dest.handle_update_fail_malformed_htlc(&nodes[$node].get_our_node_id(), update_fail_malformed);
897 if let Some(msg) = update_fee {
898 out.locked_write(format!("Delivering update_fee to node {}.\n", idx).as_bytes());
899 dest.handle_update_fee(&nodes[$node].get_our_node_id(), &msg);
901 let processed_change = !update_add_htlcs.is_empty() || !update_fulfill_htlcs.is_empty() ||
902 !update_fail_htlcs.is_empty() || !update_fail_malformed_htlcs.is_empty();
903 if $limit_events != ProcessMessages::AllMessages && processed_change {
904 // If we only want to process some messages, don't deliver the CS until later.
905 extra_ev = Some(events::MessageSendEvent::UpdateHTLCs { node_id, updates: CommitmentUpdate {
906 update_add_htlcs: Vec::new(),
907 update_fail_htlcs: Vec::new(),
908 update_fulfill_htlcs: Vec::new(),
909 update_fail_malformed_htlcs: Vec::new(),
915 out.locked_write(format!("Delivering commitment_signed to node {}.\n", idx).as_bytes());
916 dest.handle_commitment_signed(&nodes[$node].get_our_node_id(), &commitment_signed);
921 events::MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
922 for (idx, dest) in nodes.iter().enumerate() {
923 if dest.get_our_node_id() == *node_id {
924 out.locked_write(format!("Delivering revoke_and_ack to node {}.\n", idx).as_bytes());
925 dest.handle_revoke_and_ack(&nodes[$node].get_our_node_id(), msg);
929 events::MessageSendEvent::SendChannelReestablish { ref node_id, ref msg } => {
930 for (idx, dest) in nodes.iter().enumerate() {
931 if dest.get_our_node_id() == *node_id {
932 out.locked_write(format!("Delivering channel_reestablish to node {}.\n", idx).as_bytes());
933 dest.handle_channel_reestablish(&nodes[$node].get_our_node_id(), msg);
937 events::MessageSendEvent::SendChannelReady { .. } => {
938 // Can be generated as a reestablish response
940 events::MessageSendEvent::SendAnnouncementSignatures { .. } => {
941 // Can be generated as a reestablish response
943 events::MessageSendEvent::SendChannelUpdate { ref msg, .. } => {
944 // When we reconnect we will resend a channel_update to make sure our
945 // counterparty has the latest parameters for receiving payments
946 // through us. We do, however, check that the message does not include
947 // the "disabled" bit, as we should never ever have a channel which is
948 // disabled when we send such an update (or it may indicate channel
949 // force-close which we should detect as an error).
950 assert_eq!(msg.contents.flags & 2, 0);
952 _ => if out.may_fail.load(atomic::Ordering::Acquire) {
955 panic!("Unhandled message event {:?}", event)
958 if $limit_events != ProcessMessages::AllMessages {
963 push_excess_b_events!(extra_ev.into_iter().chain(events_iter), None);
964 } else if $node == 0 {
965 if let Some(ev) = extra_ev { ab_events.push(ev); }
966 for event in events_iter { ab_events.push(event); }
968 if let Some(ev) = extra_ev { cb_events.push(ev); }
969 for event in events_iter { cb_events.push(event); }
975 macro_rules! drain_msg_events_on_disconnect {
976 ($counterparty_id: expr) => { {
977 if $counterparty_id == 0 {
978 for event in nodes[0].get_and_clear_pending_msg_events() {
980 events::MessageSendEvent::UpdateHTLCs { .. } => {},
981 events::MessageSendEvent::SendRevokeAndACK { .. } => {},
982 events::MessageSendEvent::SendChannelReestablish { .. } => {},
983 events::MessageSendEvent::SendChannelReady { .. } => {},
984 events::MessageSendEvent::SendAnnouncementSignatures { .. } => {},
985 events::MessageSendEvent::SendChannelUpdate { ref msg, .. } => {
986 assert_eq!(msg.contents.flags & 2, 0); // The disable bit must never be set!
988 _ => if out.may_fail.load(atomic::Ordering::Acquire) {
991 panic!("Unhandled message event")
995 push_excess_b_events!(nodes[1].get_and_clear_pending_msg_events().drain(..), Some(0));
999 for event in nodes[2].get_and_clear_pending_msg_events() {
1001 events::MessageSendEvent::UpdateHTLCs { .. } => {},
1002 events::MessageSendEvent::SendRevokeAndACK { .. } => {},
1003 events::MessageSendEvent::SendChannelReestablish { .. } => {},
1004 events::MessageSendEvent::SendChannelReady { .. } => {},
1005 events::MessageSendEvent::SendAnnouncementSignatures { .. } => {},
1006 events::MessageSendEvent::SendChannelUpdate { ref msg, .. } => {
1007 assert_eq!(msg.contents.flags & 2, 0); // The disable bit must never be set!
1009 _ => if out.may_fail.load(atomic::Ordering::Acquire) {
1012 panic!("Unhandled message event")
1016 push_excess_b_events!(nodes[1].get_and_clear_pending_msg_events().drain(..), Some(2));
1023 macro_rules! process_events {
1024 ($node: expr, $fail: expr) => { {
1025 // In case we get 256 payments we may have a hash collision, resulting in the
1026 // second claim/fail call not finding the duplicate-hash HTLC, so we have to
1027 // deduplicate the calls here.
1028 let mut claim_set = new_hash_map();
1029 let mut events = nodes[$node].get_and_clear_pending_events();
1030 // Sort events so that PendingHTLCsForwardable get processed last. This avoids a
1031 // case where we first process a PendingHTLCsForwardable, then claim/fail on a
1032 // PaymentClaimable, claiming/failing two HTLCs, but leaving a just-generated
1033 // PaymentClaimable event for the second HTLC in our pending_events (and breaking
1034 // our claim_set deduplication).
1035 events.sort_by(|a, b| {
1036 if let events::Event::PaymentClaimable { .. } = a {
1037 if let events::Event::PendingHTLCsForwardable { .. } = b {
1039 } else { Ordering::Equal }
1040 } else if let events::Event::PendingHTLCsForwardable { .. } = a {
1041 if let events::Event::PaymentClaimable { .. } = b {
1043 } else { Ordering::Equal }
1044 } else { Ordering::Equal }
1046 let had_events = !events.is_empty();
1047 for event in events.drain(..) {
1049 events::Event::PaymentClaimable { payment_hash, .. } => {
1050 if claim_set.insert(payment_hash.0, ()).is_none() {
1052 nodes[$node].fail_htlc_backwards(&payment_hash);
1054 nodes[$node].claim_funds(PaymentPreimage(payment_hash.0));
1058 events::Event::PaymentSent { .. } => {},
1059 events::Event::PaymentClaimed { .. } => {},
1060 events::Event::PaymentPathSuccessful { .. } => {},
1061 events::Event::PaymentPathFailed { .. } => {},
1062 events::Event::PaymentFailed { .. } => {},
1063 events::Event::ProbeSuccessful { .. } | events::Event::ProbeFailed { .. } => {
1064 // Even though we don't explicitly send probes, because probes are
1065 // detected based on hashing the payment hash+preimage, its rather
1066 // trivial for the fuzzer to build payments that accidentally end up
1067 // looking like probes.
1069 events::Event::PaymentForwarded { .. } if $node == 1 => {},
1070 events::Event::ChannelReady { .. } => {},
1071 events::Event::PendingHTLCsForwardable { .. } => {
1072 nodes[$node].process_pending_htlc_forwards();
1074 events::Event::HTLCHandlingFailed { .. } => {},
1075 _ => if out.may_fail.load(atomic::Ordering::Acquire) {
1078 panic!("Unhandled event")
1086 let complete_first = |v: &mut Vec<_>| if !v.is_empty() { Some(v.remove(0)) } else { None };
1087 let complete_second = |v: &mut Vec<_>| if v.len() > 1 { Some(v.remove(1)) } else { None };
1088 let complete_monitor_update = |
1089 monitor: &Arc<TestChainMonitor>, chan_funding,
1090 compl_selector: &dyn Fn(&mut Vec<(u64, Vec<u8>)>) -> Option<(u64, Vec<u8>)>,
1092 if let Some(state) = monitor.latest_monitors.lock().unwrap().get_mut(chan_funding) {
1094 state.pending_monitors.windows(2).all(|pair| pair[0].0 < pair[1].0),
1095 "updates should be sorted by id"
1097 if let Some((id, data)) = compl_selector(&mut state.pending_monitors) {
1098 monitor.chain_monitor.channel_monitor_updated(*chan_funding, id).unwrap();
1099 if id > state.persisted_monitor_id {
1100 state.persisted_monitor_id = id;
1101 state.persisted_monitor = data;
1107 let complete_all_monitor_updates = |monitor: &Arc<TestChainMonitor>, chan_funding| {
1108 if let Some(state) = monitor.latest_monitors.lock().unwrap().get_mut(chan_funding) {
1110 state.pending_monitors.windows(2).all(|pair| pair[0].0 < pair[1].0),
1111 "updates should be sorted by id"
1113 for (id, data) in state.pending_monitors.drain(..) {
1114 monitor.chain_monitor.channel_monitor_updated(*chan_funding, id).unwrap();
1115 if id > state.persisted_monitor_id {
1116 state.persisted_monitor_id = id;
1117 state.persisted_monitor = data;
1123 let v = get_slice!(1)[0];
1124 out.locked_write(format!("READ A BYTE! HANDLING INPUT {:x}...........\n", v).as_bytes());
1126 // In general, we keep related message groups close together in binary form, allowing
1127 // bit-twiddling mutations to have similar effects. This is probably overkill, but no
1128 // harm in doing so.
1130 0x00 => *monitor_a.persister.update_ret.lock().unwrap() = ChannelMonitorUpdateStatus::InProgress,
1131 0x01 => *monitor_b.persister.update_ret.lock().unwrap() = ChannelMonitorUpdateStatus::InProgress,
1132 0x02 => *monitor_c.persister.update_ret.lock().unwrap() = ChannelMonitorUpdateStatus::InProgress,
1133 0x04 => *monitor_a.persister.update_ret.lock().unwrap() = ChannelMonitorUpdateStatus::Completed,
1134 0x05 => *monitor_b.persister.update_ret.lock().unwrap() = ChannelMonitorUpdateStatus::Completed,
1135 0x06 => *monitor_c.persister.update_ret.lock().unwrap() = ChannelMonitorUpdateStatus::Completed,
1137 0x08 => complete_all_monitor_updates(&monitor_a, &chan_1_funding),
1138 0x09 => complete_all_monitor_updates(&monitor_b, &chan_1_funding),
1139 0x0a => complete_all_monitor_updates(&monitor_b, &chan_2_funding),
1140 0x0b => complete_all_monitor_updates(&monitor_c, &chan_2_funding),
1143 if !chan_a_disconnected {
1144 nodes[0].peer_disconnected(&nodes[1].get_our_node_id());
1145 nodes[1].peer_disconnected(&nodes[0].get_our_node_id());
1146 chan_a_disconnected = true;
1147 drain_msg_events_on_disconnect!(0);
1151 if !chan_b_disconnected {
1152 nodes[1].peer_disconnected(&nodes[2].get_our_node_id());
1153 nodes[2].peer_disconnected(&nodes[1].get_our_node_id());
1154 chan_b_disconnected = true;
1155 drain_msg_events_on_disconnect!(2);
1159 if chan_a_disconnected {
1160 nodes[0].peer_connected(&nodes[1].get_our_node_id(), &Init {
1161 features: nodes[1].init_features(), networks: None, remote_network_address: None
1163 nodes[1].peer_connected(&nodes[0].get_our_node_id(), &Init {
1164 features: nodes[0].init_features(), networks: None, remote_network_address: None
1166 chan_a_disconnected = false;
1170 if chan_b_disconnected {
1171 nodes[1].peer_connected(&nodes[2].get_our_node_id(), &Init {
1172 features: nodes[2].init_features(), networks: None, remote_network_address: None
1174 nodes[2].peer_connected(&nodes[1].get_our_node_id(), &Init {
1175 features: nodes[1].init_features(), networks: None, remote_network_address: None
1177 chan_b_disconnected = false;
1181 0x10 => { process_msg_events!(0, true, ProcessMessages::AllMessages); },
1182 0x11 => { process_msg_events!(0, false, ProcessMessages::AllMessages); },
1183 0x12 => { process_msg_events!(0, true, ProcessMessages::OneMessage); },
1184 0x13 => { process_msg_events!(0, false, ProcessMessages::OneMessage); },
1185 0x14 => { process_msg_events!(0, true, ProcessMessages::OnePendingMessage); },
1186 0x15 => { process_msg_events!(0, false, ProcessMessages::OnePendingMessage); },
1188 0x16 => { process_events!(0, true); },
1189 0x17 => { process_events!(0, false); },
1191 0x18 => { process_msg_events!(1, true, ProcessMessages::AllMessages); },
1192 0x19 => { process_msg_events!(1, false, ProcessMessages::AllMessages); },
1193 0x1a => { process_msg_events!(1, true, ProcessMessages::OneMessage); },
1194 0x1b => { process_msg_events!(1, false, ProcessMessages::OneMessage); },
1195 0x1c => { process_msg_events!(1, true, ProcessMessages::OnePendingMessage); },
1196 0x1d => { process_msg_events!(1, false, ProcessMessages::OnePendingMessage); },
1198 0x1e => { process_events!(1, true); },
1199 0x1f => { process_events!(1, false); },
1201 0x20 => { process_msg_events!(2, true, ProcessMessages::AllMessages); },
1202 0x21 => { process_msg_events!(2, false, ProcessMessages::AllMessages); },
1203 0x22 => { process_msg_events!(2, true, ProcessMessages::OneMessage); },
1204 0x23 => { process_msg_events!(2, false, ProcessMessages::OneMessage); },
1205 0x24 => { process_msg_events!(2, true, ProcessMessages::OnePendingMessage); },
1206 0x25 => { process_msg_events!(2, false, ProcessMessages::OnePendingMessage); },
1208 0x26 => { process_events!(2, true); },
1209 0x27 => { process_events!(2, false); },
1212 if !chan_a_disconnected {
1213 nodes[1].peer_disconnected(&nodes[0].get_our_node_id());
1214 chan_a_disconnected = true;
1215 push_excess_b_events!(nodes[1].get_and_clear_pending_msg_events().drain(..), Some(0));
1219 let (new_node_a, new_monitor_a) = reload_node!(node_a_ser, 0, monitor_a, keys_manager_a, fee_est_a);
1220 nodes[0] = new_node_a;
1221 monitor_a = new_monitor_a;
1224 if !chan_a_disconnected {
1225 nodes[0].peer_disconnected(&nodes[1].get_our_node_id());
1226 chan_a_disconnected = true;
1227 nodes[0].get_and_clear_pending_msg_events();
1231 if !chan_b_disconnected {
1232 nodes[2].peer_disconnected(&nodes[1].get_our_node_id());
1233 chan_b_disconnected = true;
1234 nodes[2].get_and_clear_pending_msg_events();
1238 let (new_node_b, new_monitor_b) = reload_node!(node_b_ser, 1, monitor_b, keys_manager_b, fee_est_b);
1239 nodes[1] = new_node_b;
1240 monitor_b = new_monitor_b;
1243 if !chan_b_disconnected {
1244 nodes[1].peer_disconnected(&nodes[2].get_our_node_id());
1245 chan_b_disconnected = true;
1246 push_excess_b_events!(nodes[1].get_and_clear_pending_msg_events().drain(..), Some(2));
1250 let (new_node_c, new_monitor_c) = reload_node!(node_c_ser, 2, monitor_c, keys_manager_c, fee_est_c);
1251 nodes[2] = new_node_c;
1252 monitor_c = new_monitor_c;
1255 // 1/10th the channel size:
1256 0x30 => { send_payment(&nodes[0], &nodes[1], chan_a, 10_000_000, &mut payment_id, &mut payment_idx); },
1257 0x31 => { send_payment(&nodes[1], &nodes[0], chan_a, 10_000_000, &mut payment_id, &mut payment_idx); },
1258 0x32 => { send_payment(&nodes[1], &nodes[2], chan_b, 10_000_000, &mut payment_id, &mut payment_idx); },
1259 0x33 => { send_payment(&nodes[2], &nodes[1], chan_b, 10_000_000, &mut payment_id, &mut payment_idx); },
1260 0x34 => { send_hop_payment(&nodes[0], &nodes[1], chan_a, &nodes[2], chan_b, 10_000_000, &mut payment_id, &mut payment_idx); },
1261 0x35 => { send_hop_payment(&nodes[2], &nodes[1], chan_b, &nodes[0], chan_a, 10_000_000, &mut payment_id, &mut payment_idx); },
1263 0x38 => { send_payment(&nodes[0], &nodes[1], chan_a, 1_000_000, &mut payment_id, &mut payment_idx); },
1264 0x39 => { send_payment(&nodes[1], &nodes[0], chan_a, 1_000_000, &mut payment_id, &mut payment_idx); },
1265 0x3a => { send_payment(&nodes[1], &nodes[2], chan_b, 1_000_000, &mut payment_id, &mut payment_idx); },
1266 0x3b => { send_payment(&nodes[2], &nodes[1], chan_b, 1_000_000, &mut payment_id, &mut payment_idx); },
1267 0x3c => { send_hop_payment(&nodes[0], &nodes[1], chan_a, &nodes[2], chan_b, 1_000_000, &mut payment_id, &mut payment_idx); },
1268 0x3d => { send_hop_payment(&nodes[2], &nodes[1], chan_b, &nodes[0], chan_a, 1_000_000, &mut payment_id, &mut payment_idx); },
1270 0x40 => { send_payment(&nodes[0], &nodes[1], chan_a, 100_000, &mut payment_id, &mut payment_idx); },
1271 0x41 => { send_payment(&nodes[1], &nodes[0], chan_a, 100_000, &mut payment_id, &mut payment_idx); },
1272 0x42 => { send_payment(&nodes[1], &nodes[2], chan_b, 100_000, &mut payment_id, &mut payment_idx); },
1273 0x43 => { send_payment(&nodes[2], &nodes[1], chan_b, 100_000, &mut payment_id, &mut payment_idx); },
1274 0x44 => { send_hop_payment(&nodes[0], &nodes[1], chan_a, &nodes[2], chan_b, 100_000, &mut payment_id, &mut payment_idx); },
1275 0x45 => { send_hop_payment(&nodes[2], &nodes[1], chan_b, &nodes[0], chan_a, 100_000, &mut payment_id, &mut payment_idx); },
1277 0x48 => { send_payment(&nodes[0], &nodes[1], chan_a, 10_000, &mut payment_id, &mut payment_idx); },
1278 0x49 => { send_payment(&nodes[1], &nodes[0], chan_a, 10_000, &mut payment_id, &mut payment_idx); },
1279 0x4a => { send_payment(&nodes[1], &nodes[2], chan_b, 10_000, &mut payment_id, &mut payment_idx); },
1280 0x4b => { send_payment(&nodes[2], &nodes[1], chan_b, 10_000, &mut payment_id, &mut payment_idx); },
1281 0x4c => { send_hop_payment(&nodes[0], &nodes[1], chan_a, &nodes[2], chan_b, 10_000, &mut payment_id, &mut payment_idx); },
1282 0x4d => { send_hop_payment(&nodes[2], &nodes[1], chan_b, &nodes[0], chan_a, 10_000, &mut payment_id, &mut payment_idx); },
1284 0x50 => { send_payment(&nodes[0], &nodes[1], chan_a, 1_000, &mut payment_id, &mut payment_idx); },
1285 0x51 => { send_payment(&nodes[1], &nodes[0], chan_a, 1_000, &mut payment_id, &mut payment_idx); },
1286 0x52 => { send_payment(&nodes[1], &nodes[2], chan_b, 1_000, &mut payment_id, &mut payment_idx); },
1287 0x53 => { send_payment(&nodes[2], &nodes[1], chan_b, 1_000, &mut payment_id, &mut payment_idx); },
1288 0x54 => { send_hop_payment(&nodes[0], &nodes[1], chan_a, &nodes[2], chan_b, 1_000, &mut payment_id, &mut payment_idx); },
1289 0x55 => { send_hop_payment(&nodes[2], &nodes[1], chan_b, &nodes[0], chan_a, 1_000, &mut payment_id, &mut payment_idx); },
1291 0x58 => { send_payment(&nodes[0], &nodes[1], chan_a, 100, &mut payment_id, &mut payment_idx); },
1292 0x59 => { send_payment(&nodes[1], &nodes[0], chan_a, 100, &mut payment_id, &mut payment_idx); },
1293 0x5a => { send_payment(&nodes[1], &nodes[2], chan_b, 100, &mut payment_id, &mut payment_idx); },
1294 0x5b => { send_payment(&nodes[2], &nodes[1], chan_b, 100, &mut payment_id, &mut payment_idx); },
1295 0x5c => { send_hop_payment(&nodes[0], &nodes[1], chan_a, &nodes[2], chan_b, 100, &mut payment_id, &mut payment_idx); },
1296 0x5d => { send_hop_payment(&nodes[2], &nodes[1], chan_b, &nodes[0], chan_a, 100, &mut payment_id, &mut payment_idx); },
1298 0x60 => { send_payment(&nodes[0], &nodes[1], chan_a, 10, &mut payment_id, &mut payment_idx); },
1299 0x61 => { send_payment(&nodes[1], &nodes[0], chan_a, 10, &mut payment_id, &mut payment_idx); },
1300 0x62 => { send_payment(&nodes[1], &nodes[2], chan_b, 10, &mut payment_id, &mut payment_idx); },
1301 0x63 => { send_payment(&nodes[2], &nodes[1], chan_b, 10, &mut payment_id, &mut payment_idx); },
1302 0x64 => { send_hop_payment(&nodes[0], &nodes[1], chan_a, &nodes[2], chan_b, 10, &mut payment_id, &mut payment_idx); },
1303 0x65 => { send_hop_payment(&nodes[2], &nodes[1], chan_b, &nodes[0], chan_a, 10, &mut payment_id, &mut payment_idx); },
1305 0x68 => { send_payment(&nodes[0], &nodes[1], chan_a, 1, &mut payment_id, &mut payment_idx); },
1306 0x69 => { send_payment(&nodes[1], &nodes[0], chan_a, 1, &mut payment_id, &mut payment_idx); },
1307 0x6a => { send_payment(&nodes[1], &nodes[2], chan_b, 1, &mut payment_id, &mut payment_idx); },
1308 0x6b => { send_payment(&nodes[2], &nodes[1], chan_b, 1, &mut payment_id, &mut payment_idx); },
1309 0x6c => { send_hop_payment(&nodes[0], &nodes[1], chan_a, &nodes[2], chan_b, 1, &mut payment_id, &mut payment_idx); },
1310 0x6d => { send_hop_payment(&nodes[2], &nodes[1], chan_b, &nodes[0], chan_a, 1, &mut payment_id, &mut payment_idx); },
1313 let mut max_feerate = last_htlc_clear_fee_a;
1315 max_feerate *= FEE_SPIKE_BUFFER_FEE_INCREASE_MULTIPLE as u32;
1317 if fee_est_a.ret_val.fetch_add(250, atomic::Ordering::AcqRel) + 250 > max_feerate {
1318 fee_est_a.ret_val.store(max_feerate, atomic::Ordering::Release);
1320 nodes[0].maybe_update_chan_fees();
1322 0x81 => { fee_est_a.ret_val.store(253, atomic::Ordering::Release); nodes[0].maybe_update_chan_fees(); },
1325 let mut max_feerate = last_htlc_clear_fee_b;
1327 max_feerate *= FEE_SPIKE_BUFFER_FEE_INCREASE_MULTIPLE as u32;
1329 if fee_est_b.ret_val.fetch_add(250, atomic::Ordering::AcqRel) + 250 > max_feerate {
1330 fee_est_b.ret_val.store(max_feerate, atomic::Ordering::Release);
1332 nodes[1].maybe_update_chan_fees();
1334 0x85 => { fee_est_b.ret_val.store(253, atomic::Ordering::Release); nodes[1].maybe_update_chan_fees(); },
1337 let mut max_feerate = last_htlc_clear_fee_c;
1339 max_feerate *= FEE_SPIKE_BUFFER_FEE_INCREASE_MULTIPLE as u32;
1341 if fee_est_c.ret_val.fetch_add(250, atomic::Ordering::AcqRel) + 250 > max_feerate {
1342 fee_est_c.ret_val.store(max_feerate, atomic::Ordering::Release);
1344 nodes[2].maybe_update_chan_fees();
1346 0x89 => { fee_est_c.ret_val.store(253, atomic::Ordering::Release); nodes[2].maybe_update_chan_fees(); },
1348 0xf0 => complete_monitor_update(&monitor_a, &chan_1_funding, &complete_first),
1349 0xf1 => complete_monitor_update(&monitor_a, &chan_1_funding, &complete_second),
1350 0xf2 => complete_monitor_update(&monitor_a, &chan_1_funding, &Vec::pop),
1352 0xf4 => complete_monitor_update(&monitor_b, &chan_1_funding, &complete_first),
1353 0xf5 => complete_monitor_update(&monitor_b, &chan_1_funding, &complete_second),
1354 0xf6 => complete_monitor_update(&monitor_b, &chan_1_funding, &Vec::pop),
1356 0xf8 => complete_monitor_update(&monitor_b, &chan_2_funding, &complete_first),
1357 0xf9 => complete_monitor_update(&monitor_b, &chan_2_funding, &complete_second),
1358 0xfa => complete_monitor_update(&monitor_b, &chan_2_funding, &Vec::pop),
1360 0xfc => complete_monitor_update(&monitor_c, &chan_2_funding, &complete_first),
1361 0xfd => complete_monitor_update(&monitor_c, &chan_2_funding, &complete_second),
1362 0xfe => complete_monitor_update(&monitor_c, &chan_2_funding, &Vec::pop),
1365 // Test that no channel is in a stuck state where neither party can send funds even
1366 // after we resolve all pending events.
1367 // First make sure there are no pending monitor updates and further update
1368 // operations complete.
1369 *monitor_a.persister.update_ret.lock().unwrap() = ChannelMonitorUpdateStatus::Completed;
1370 *monitor_b.persister.update_ret.lock().unwrap() = ChannelMonitorUpdateStatus::Completed;
1371 *monitor_c.persister.update_ret.lock().unwrap() = ChannelMonitorUpdateStatus::Completed;
1373 complete_all_monitor_updates(&monitor_a, &chan_1_funding);
1374 complete_all_monitor_updates(&monitor_b, &chan_1_funding);
1375 complete_all_monitor_updates(&monitor_b, &chan_2_funding);
1376 complete_all_monitor_updates(&monitor_c, &chan_2_funding);
1378 // Next, make sure peers are all connected to each other
1379 if chan_a_disconnected {
1380 nodes[0].peer_connected(&nodes[1].get_our_node_id(), &Init {
1381 features: nodes[1].init_features(), networks: None, remote_network_address: None
1383 nodes[1].peer_connected(&nodes[0].get_our_node_id(), &Init {
1384 features: nodes[0].init_features(), networks: None, remote_network_address: None
1386 chan_a_disconnected = false;
1388 if chan_b_disconnected {
1389 nodes[1].peer_connected(&nodes[2].get_our_node_id(), &Init {
1390 features: nodes[2].init_features(), networks: None, remote_network_address: None
1392 nodes[2].peer_connected(&nodes[1].get_our_node_id(), &Init {
1393 features: nodes[1].init_features(), networks: None, remote_network_address: None
1395 chan_b_disconnected = false;
1398 for i in 0..std::usize::MAX {
1399 if i == 100 { panic!("It may take may iterations to settle the state, but it should not take forever"); }
1400 // Then, make sure any current forwards make their way to their destination
1401 if process_msg_events!(0, false, ProcessMessages::AllMessages) { continue; }
1402 if process_msg_events!(1, false, ProcessMessages::AllMessages) { continue; }
1403 if process_msg_events!(2, false, ProcessMessages::AllMessages) { continue; }
1404 // ...making sure any pending PendingHTLCsForwardable events are handled and
1405 // payments claimed.
1406 if process_events!(0, false) { continue; }
1407 if process_events!(1, false) { continue; }
1408 if process_events!(2, false) { continue; }
1412 // Finally, make sure that at least one end of each channel can make a substantial payment
1414 send_payment(&nodes[0], &nodes[1], chan_a, 10_000_000, &mut payment_id, &mut payment_idx) ||
1415 send_payment(&nodes[1], &nodes[0], chan_a, 10_000_000, &mut payment_id, &mut payment_idx));
1417 send_payment(&nodes[1], &nodes[2], chan_b, 10_000_000, &mut payment_id, &mut payment_idx) ||
1418 send_payment(&nodes[2], &nodes[1], chan_b, 10_000_000, &mut payment_id, &mut payment_idx));
1420 last_htlc_clear_fee_a = fee_est_a.ret_val.load(atomic::Ordering::Acquire);
1421 last_htlc_clear_fee_b = fee_est_b.ret_val.load(atomic::Ordering::Acquire);
1422 last_htlc_clear_fee_c = fee_est_c.ret_val.load(atomic::Ordering::Acquire);
1424 _ => test_return!(),
1427 if nodes[0].get_and_clear_needs_persistence() == true {
1428 node_a_ser.0.clear();
1429 nodes[0].write(&mut node_a_ser).unwrap();
1431 if nodes[1].get_and_clear_needs_persistence() == true {
1432 node_b_ser.0.clear();
1433 nodes[1].write(&mut node_b_ser).unwrap();
1435 if nodes[2].get_and_clear_needs_persistence() == true {
1436 node_c_ser.0.clear();
1437 nodes[2].write(&mut node_c_ser).unwrap();
1442 /// We actually have different behavior based on if a certain log string has been seen, so we have
1443 /// to do a bit more tracking.
1445 struct SearchingOutput<O: Output> {
1447 may_fail: Arc<atomic::AtomicBool>,
1449 impl<O: Output> Output for SearchingOutput<O> {
1450 fn locked_write(&self, data: &[u8]) {
1451 // We hit a design limitation of LN state machine (see CONCURRENT_INBOUND_HTLC_FEE_BUFFER)
1452 if std::str::from_utf8(data).unwrap().contains("Outbound update_fee HTLC buffer overflow - counterparty should force-close this channel") {
1453 self.may_fail.store(true, atomic::Ordering::Release);
1455 self.output.locked_write(data)
1458 impl<O: Output> SearchingOutput<O> {
1459 pub fn new(output: O) -> Self {
1460 Self { output, may_fail: Arc::new(atomic::AtomicBool::new(false)) }
1464 pub fn chanmon_consistency_test<Out: Output>(data: &[u8], out: Out) {
1465 do_test(data, out.clone(), false);
1466 do_test(data, out, true);
1470 pub extern "C" fn chanmon_consistency_run(data: *const u8, datalen: usize) {
1471 do_test(unsafe { std::slice::from_raw_parts(data, datalen) }, test_logger::DevNull{}, false);
1472 do_test(unsafe { std::slice::from_raw_parts(data, datalen) }, test_logger::DevNull{}, true);