Merge pull request #3089 from TheBlueMatt/2024-06-channel_state-module
[rust-lightning] / fuzz / src / full_stack.rs
1 // This file is Copyright its original authors, visible in version control
2 // history.
3 //
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
8 // licenses.
9
10 //! Test that no series of bytes received over the wire/connections created/payments sent can
11 //! result in a crash. We do this by standing up a node and then reading bytes from input to denote
12 //! actions such as creating new inbound/outbound connections, bytes to be read from a connection,
13 //! or payments to send/ways to handle events generated.
14 //! This test has been very useful, though due to its complexity good starting inputs are critical.
15
16 use bitcoin::amount::Amount;
17 use bitcoin::blockdata::constants::genesis_block;
18 use bitcoin::blockdata::transaction::{Transaction, TxOut};
19 use bitcoin::blockdata::script::{Builder, ScriptBuf};
20 use bitcoin::blockdata::opcodes;
21 use bitcoin::blockdata::locktime::absolute::LockTime;
22 use bitcoin::consensus::encode::deserialize;
23 use bitcoin::network::Network;
24 use bitcoin::transaction::Version;
25
26 use bitcoin::WPubkeyHash;
27 use bitcoin::hashes::hex::FromHex;
28 use bitcoin::hashes::Hash as _;
29 use bitcoin::hashes::sha256::Hash as Sha256;
30 use bitcoin::hashes::sha256d::Hash as Sha256dHash;
31 use bitcoin::hash_types::{Txid, BlockHash};
32
33 use lightning::blinded_path::BlindedPath;
34 use lightning::blinded_path::message::ForwardNode;
35 use lightning::blinded_path::payment::ReceiveTlvs;
36 use lightning::chain;
37 use lightning::chain::{BestBlock, ChannelMonitorUpdateStatus, Confirm, Listen};
38 use lightning::chain::chaininterface::{BroadcasterInterface, ConfirmationTarget, FeeEstimator};
39 use lightning::chain::chainmonitor;
40 use lightning::chain::transaction::OutPoint;
41 use lightning::sign::{InMemorySigner, Recipient, KeyMaterial, EntropySource, NodeSigner, SignerProvider};
42 use lightning::events::Event;
43 use lightning::ln::{ChannelId, PaymentHash, PaymentPreimage, PaymentSecret};
44 use lightning::ln::channel_state::ChannelDetails;
45 use lightning::ln::channelmanager::{ChainParameters, ChannelManager, PaymentId, RecipientOnionFields, Retry, InterceptId};
46 use lightning::ln::peer_handler::{MessageHandler,PeerManager,SocketDescriptor,IgnoringMessageHandler};
47 use lightning::ln::msgs::{self, DecodeError};
48 use lightning::ln::script::ShutdownScript;
49 use lightning::ln::functional_test_utils::*;
50 use lightning::offers::invoice::{BlindedPayInfo, UnsignedBolt12Invoice};
51 use lightning::offers::invoice_request::UnsignedInvoiceRequest;
52 use lightning::onion_message::messenger::{Destination, MessageRouter, OnionMessagePath};
53 use lightning::routing::gossip::{P2PGossipSync, NetworkGraph};
54 use lightning::routing::utxo::UtxoLookup;
55 use lightning::routing::router::{InFlightHtlcs, PaymentParameters, Route, RouteParameters, Router};
56 use lightning::util::config::{ChannelConfig, UserConfig};
57 use lightning::util::hash_tables::*;
58 use lightning::util::errors::APIError;
59 use lightning::util::test_channel_signer::{TestChannelSigner, EnforcementState};
60 use lightning::util::logger::Logger;
61 use lightning::util::ser::{Readable, ReadableArgs, Writeable};
62
63 use crate::utils::test_logger;
64 use crate::utils::test_persister::TestPersister;
65
66 use bitcoin::secp256k1::{Message, PublicKey, SecretKey, Scalar, Secp256k1, self};
67 use bitcoin::secp256k1::ecdh::SharedSecret;
68 use bitcoin::secp256k1::ecdsa::{RecoverableSignature, Signature};
69 use bitcoin::secp256k1::schnorr;
70
71 use std::cell::RefCell;
72 use std::convert::TryInto;
73 use std::cmp;
74 use std::sync::{Arc, Mutex};
75 use std::sync::atomic::{AtomicU64,AtomicUsize,Ordering};
76 use bech32::u5;
77
78 #[inline]
79 pub fn slice_to_be16(v: &[u8]) -> u16 {
80         ((v[0] as u16) << 8*1) |
81         ((v[1] as u16) << 8*0)
82 }
83
84 #[inline]
85 pub fn be16_to_array(u: u16) -> [u8; 2] {
86         let mut v = [0; 2];
87         v[0] = ((u >> 8*1) & 0xff) as u8;
88         v[1] = ((u >> 8*0) & 0xff) as u8;
89         v
90 }
91
92 #[inline]
93 pub fn slice_to_be24(v: &[u8]) -> u32 {
94         ((v[0] as u32) << 8*2) |
95         ((v[1] as u32) << 8*1) |
96         ((v[2] as u32) << 8*0)
97 }
98
99 struct InputData {
100         data: Vec<u8>,
101         read_pos: AtomicUsize,
102 }
103 impl InputData {
104         fn get_slice(&self, len: usize) -> Option<&[u8]> {
105                 let old_pos = self.read_pos.fetch_add(len, Ordering::AcqRel);
106                 if self.data.len() < old_pos + len {
107                         return None;
108                 }
109                 Some(&self.data[old_pos..old_pos + len])
110         }
111 }
112 impl std::io::Read for &InputData {
113         fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
114                 if let Some(sl) = self.get_slice(buf.len()) {
115                         buf.copy_from_slice(sl);
116                         Ok(buf.len())
117                 } else {
118                         Ok(0)
119                 }
120         }
121 }
122
123 struct FuzzEstimator {
124         input: Arc<InputData>,
125 }
126 impl FeeEstimator for FuzzEstimator {
127         fn get_est_sat_per_1000_weight(&self, _: ConfirmationTarget) -> u32 {
128                 //TODO: We should actually be testing at least much more than 64k...
129                 match self.input.get_slice(2) {
130                         Some(slice) => cmp::max(slice_to_be16(slice) as u32, 253),
131                         None => 253
132                 }
133         }
134 }
135
136 struct FuzzRouter {}
137
138 impl Router for FuzzRouter {
139         fn find_route(
140                 &self, _payer: &PublicKey, _params: &RouteParameters, _first_hops: Option<&[&ChannelDetails]>,
141                 _inflight_htlcs: InFlightHtlcs
142         ) -> Result<Route, msgs::LightningError> {
143                 Err(msgs::LightningError {
144                         err: String::from("Not implemented"),
145                         action: msgs::ErrorAction::IgnoreError
146                 })
147         }
148
149         fn create_blinded_payment_paths<T: secp256k1::Signing + secp256k1::Verification>(
150                 &self, _recipient: PublicKey, _first_hops: Vec<ChannelDetails>, _tlvs: ReceiveTlvs,
151                 _amount_msats: u64, _secp_ctx: &Secp256k1<T>,
152         ) -> Result<Vec<(BlindedPayInfo, BlindedPath)>, ()> {
153                 unreachable!()
154         }
155 }
156
157 impl MessageRouter for FuzzRouter {
158         fn find_path(
159                 &self, _sender: PublicKey, _peers: Vec<PublicKey>, _destination: Destination
160         ) -> Result<OnionMessagePath, ()> {
161                 unreachable!()
162         }
163
164         fn create_blinded_paths<T: secp256k1::Signing + secp256k1::Verification>(
165                 &self, _recipient: PublicKey, _peers: Vec<ForwardNode>, _secp_ctx: &Secp256k1<T>,
166         ) -> Result<Vec<BlindedPath>, ()> {
167                 unreachable!()
168         }
169 }
170
171 struct TestBroadcaster {
172         txn_broadcasted: Mutex<Vec<Transaction>>,
173 }
174 impl BroadcasterInterface for TestBroadcaster {
175         fn broadcast_transactions(&self, txs: &[&Transaction]) {
176                 let owned_txs: Vec<Transaction> = txs.iter().map(|tx| (*tx).clone()).collect();
177                 self.txn_broadcasted.lock().unwrap().extend(owned_txs);
178         }
179 }
180
181 #[derive(Clone)]
182 struct Peer<'a> {
183         id: u8,
184         peers_connected: &'a RefCell<[bool; 256]>,
185 }
186 impl<'a> SocketDescriptor for Peer<'a> {
187         fn send_data(&mut self, data: &[u8], _resume_read: bool) -> usize {
188                 data.len()
189         }
190         fn disconnect_socket(&mut self) {
191                 assert!(self.peers_connected.borrow()[self.id as usize]);
192                 self.peers_connected.borrow_mut()[self.id as usize] = false;
193         }
194 }
195 impl<'a> PartialEq for Peer<'a> {
196         fn eq(&self, other: &Self) -> bool {
197                 self.id == other.id
198         }
199 }
200 impl<'a> Eq for Peer<'a> {}
201 impl<'a> std::hash::Hash for Peer<'a> {
202         fn hash<H : std::hash::Hasher>(&self, h: &mut H) {
203                 self.id.hash(h)
204         }
205 }
206
207 type ChannelMan<'a> = ChannelManager<
208         Arc<chainmonitor::ChainMonitor<TestChannelSigner, Arc<dyn chain::Filter>, Arc<TestBroadcaster>, Arc<FuzzEstimator>, Arc<dyn Logger>, Arc<TestPersister>>>,
209         Arc<TestBroadcaster>, Arc<KeyProvider>, Arc<KeyProvider>, Arc<KeyProvider>, Arc<FuzzEstimator>, &'a FuzzRouter, Arc<dyn Logger>>;
210 type PeerMan<'a> = PeerManager<Peer<'a>, Arc<ChannelMan<'a>>, Arc<P2PGossipSync<Arc<NetworkGraph<Arc<dyn Logger>>>, Arc<dyn UtxoLookup>, Arc<dyn Logger>>>, IgnoringMessageHandler, Arc<dyn Logger>, IgnoringMessageHandler, Arc<KeyProvider>>;
211
212 struct MoneyLossDetector<'a> {
213         manager: Arc<ChannelMan<'a>>,
214         monitor: Arc<chainmonitor::ChainMonitor<TestChannelSigner, Arc<dyn chain::Filter>, Arc<TestBroadcaster>, Arc<FuzzEstimator>, Arc<dyn Logger>, Arc<TestPersister>>>,
215         handler: PeerMan<'a>,
216
217         peers: &'a RefCell<[bool; 256]>,
218         funding_txn: Vec<Transaction>,
219         txids_confirmed: HashMap<Txid, usize>,
220         header_hashes: Vec<(BlockHash, u32)>,
221         height: usize,
222         max_height: usize,
223         blocks_connected: u32,
224         error_message: String,
225 }
226 impl<'a> MoneyLossDetector<'a> {
227         pub fn new(peers: &'a RefCell<[bool; 256]>,
228                    manager: Arc<ChannelMan<'a>>,
229                    monitor: Arc<chainmonitor::ChainMonitor<TestChannelSigner, Arc<dyn chain::Filter>, Arc<TestBroadcaster>, Arc<FuzzEstimator>, Arc<dyn Logger>, Arc<TestPersister>>>,
230                    handler: PeerMan<'a>) -> Self {
231                 MoneyLossDetector {
232                         manager,
233                         monitor,
234                         handler,
235
236                         peers,
237                         funding_txn: Vec::new(),
238                         txids_confirmed: new_hash_map(),
239                         header_hashes: vec![(genesis_block(Network::Bitcoin).block_hash(), 0)],
240                         height: 0,
241                         max_height: 0,
242                         blocks_connected: 0,
243                         error_message: "Channel force-closed".to_string(),
244                 }
245         }
246
247         fn connect_block(&mut self, all_txn: &[Transaction]) {
248                 let mut txdata = Vec::with_capacity(all_txn.len());
249                 for (idx, tx) in all_txn.iter().enumerate() {
250                         let txid = tx.txid();
251                         self.txids_confirmed.entry(txid).or_insert_with(|| {
252                                 txdata.push((idx + 1, tx));
253                                 self.height
254                         });
255                 }
256
257                 self.blocks_connected += 1;
258                 let header = create_dummy_header(self.header_hashes[self.height].0, self.blocks_connected);
259                 self.height += 1;
260                 self.manager.transactions_confirmed(&header, &txdata, self.height as u32);
261                 self.manager.best_block_updated(&header, self.height as u32);
262                 (*self.monitor).transactions_confirmed(&header, &txdata, self.height as u32);
263                 (*self.monitor).best_block_updated(&header, self.height as u32);
264                 if self.header_hashes.len() > self.height {
265                         self.header_hashes[self.height] = (header.block_hash(), self.blocks_connected);
266                 } else {
267                         assert_eq!(self.header_hashes.len(), self.height);
268                         self.header_hashes.push((header.block_hash(), self.blocks_connected));
269                 }
270                 self.max_height = cmp::max(self.height, self.max_height);
271         }
272
273         fn disconnect_block(&mut self) {
274                 if self.height > 0 && (self.max_height < 6 || self.height >= self.max_height - 6) {
275                         let header = create_dummy_header(self.header_hashes[self.height - 1].0, self.header_hashes[self.height].1);
276                         self.manager.block_disconnected(&header, self.height as u32);
277                         self.monitor.block_disconnected(&header, self.height as u32);
278                         self.height -= 1;
279                         let removal_height = self.height;
280                         self.txids_confirmed.retain(|_, height| {
281                                 removal_height != *height
282                         });
283                 }
284         }
285 }
286
287 impl<'a> Drop for MoneyLossDetector<'a> {
288         fn drop(&mut self) {
289                 if !::std::thread::panicking() {
290                         // Disconnect all peers
291                         for (idx, peer) in self.peers.borrow().iter().enumerate() {
292                                 if *peer {
293                                         self.handler.socket_disconnected(&Peer{id: idx as u8, peers_connected: &self.peers});
294                                 }
295                         }
296
297                         // Force all channels onto the chain (and time out claim txn)
298                         self.manager.force_close_all_channels_broadcasting_latest_txn(self.error_message.to_string());
299                 }
300         }
301 }
302
303 struct KeyProvider {
304         node_secret: SecretKey,
305         inbound_payment_key: KeyMaterial,
306         counter: AtomicU64,
307         signer_state: RefCell<HashMap<u8, (bool, Arc<Mutex<EnforcementState>>)>>
308 }
309
310 impl EntropySource for KeyProvider {
311         fn get_secure_random_bytes(&self) -> [u8; 32] {
312                 let ctr = self.counter.fetch_add(1, Ordering::Relaxed);
313                 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
314                         (ctr >> 8*7) as u8, (ctr >> 8*6) as u8, (ctr >> 8*5) as u8, (ctr >> 8*4) as u8, (ctr >> 8*3) as u8, (ctr >> 8*2) as u8, (ctr >> 8*1) as u8, 14, (ctr >> 8*0) as u8]
315         }
316 }
317
318 impl NodeSigner for KeyProvider {
319         fn get_node_id(&self, recipient: Recipient) -> Result<PublicKey, ()> {
320                 let node_secret = match recipient {
321                         Recipient::Node => Ok(&self.node_secret),
322                         Recipient::PhantomNode => Err(())
323                 }?;
324                 Ok(PublicKey::from_secret_key(&Secp256k1::signing_only(), node_secret))
325         }
326
327         fn ecdh(&self, recipient: Recipient, other_key: &PublicKey, tweak: Option<&Scalar>) -> Result<SharedSecret, ()> {
328                 let mut node_secret = match recipient {
329                         Recipient::Node => Ok(self.node_secret.clone()),
330                         Recipient::PhantomNode => Err(())
331                 }?;
332                 if let Some(tweak) = tweak {
333                         node_secret = node_secret.mul_tweak(tweak).map_err(|_| ())?;
334                 }
335                 Ok(SharedSecret::new(other_key, &node_secret))
336         }
337
338         fn get_inbound_payment_key_material(&self) -> KeyMaterial {
339                 self.inbound_payment_key.clone()
340         }
341
342         fn sign_invoice(&self, _hrp_bytes: &[u8], _invoice_data: &[u5], _recipient: Recipient) -> Result<RecoverableSignature, ()> {
343                 unreachable!()
344         }
345
346         fn sign_bolt12_invoice_request(
347                 &self, _invoice_request: &UnsignedInvoiceRequest
348         ) -> Result<schnorr::Signature, ()> {
349                 unreachable!()
350         }
351
352         fn sign_bolt12_invoice(
353                 &self, _invoice: &UnsignedBolt12Invoice,
354         ) -> Result<schnorr::Signature, ()> {
355                 unreachable!()
356         }
357
358         fn sign_gossip_message(&self, msg: lightning::ln::msgs::UnsignedGossipMessage) -> Result<Signature, ()> {
359                 let msg_hash = Message::from_digest(Sha256dHash::hash(&msg.encode()[..]).to_byte_array());
360                 let secp_ctx = Secp256k1::signing_only();
361                 Ok(secp_ctx.sign_ecdsa(&msg_hash, &self.node_secret))
362         }
363 }
364
365 impl SignerProvider for KeyProvider {
366         type EcdsaSigner = TestChannelSigner;
367         #[cfg(taproot)]
368         type TaprootSigner = TestChannelSigner;
369
370         fn generate_channel_keys_id(&self, inbound: bool, _channel_value_satoshis: u64, _user_channel_id: u128) -> [u8; 32] {
371                 let ctr = self.counter.fetch_add(1, Ordering::Relaxed) as u8;
372                 self.signer_state.borrow_mut().insert(ctr, (inbound, Arc::new(Mutex::new(EnforcementState::new()))));
373                 [ctr; 32]
374         }
375
376         fn derive_channel_signer(&self, channel_value_satoshis: u64, channel_keys_id: [u8; 32]) -> Self::EcdsaSigner {
377                 let secp_ctx = Secp256k1::signing_only();
378                 let ctr = channel_keys_id[0];
379                 let (inbound, state) = self.signer_state.borrow().get(&ctr).unwrap().clone();
380                 TestChannelSigner::new_with_revoked(if inbound {
381                         InMemorySigner::new(
382                                 &secp_ctx,
383                                 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, ctr]).unwrap(),
384                                 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, ctr]).unwrap(),
385                                 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, ctr]).unwrap(),
386                                 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, ctr]).unwrap(),
387                                 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, ctr]).unwrap(),
388                                 [0, 0, 0, 0, 0, 0, 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, ctr],
389                                 channel_value_satoshis,
390                                 channel_keys_id,
391                                 channel_keys_id,
392                         )
393                 } else {
394                         InMemorySigner::new(
395                                 &secp_ctx,
396                                 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, ctr]).unwrap(),
397                                 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, ctr]).unwrap(),
398                                 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, 9, ctr]).unwrap(),
399                                 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, 10, ctr]).unwrap(),
400                                 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, 11, ctr]).unwrap(),
401                                 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 12, ctr],
402                                 channel_value_satoshis,
403                                 channel_keys_id,
404                                 channel_keys_id,
405                         )
406                 }, state, false)
407         }
408
409         fn read_chan_signer(&self, mut data: &[u8]) -> Result<TestChannelSigner, DecodeError> {
410                 let inner: InMemorySigner = ReadableArgs::read(&mut data, self)?;
411                 let state = Arc::new(Mutex::new(EnforcementState::new()));
412
413                 Ok(TestChannelSigner::new_with_revoked(
414                         inner,
415                         state,
416                         false
417                 ))
418         }
419
420         fn get_destination_script(&self, _channel_keys_id: [u8; 32]) -> Result<ScriptBuf, ()> {
421                 let secp_ctx = Secp256k1::signing_only();
422                 let channel_monitor_claim_key = SecretKey::from_slice(&<Vec<u8>>::from_hex("0fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff").unwrap()[..]).unwrap();
423                 let our_channel_monitor_claim_key_hash = WPubkeyHash::hash(&PublicKey::from_secret_key(&secp_ctx, &channel_monitor_claim_key).serialize());
424                 Ok(Builder::new().push_opcode(opcodes::all::OP_PUSHBYTES_0).push_slice(our_channel_monitor_claim_key_hash).into_script())
425         }
426
427         fn get_shutdown_scriptpubkey(&self) -> Result<ShutdownScript, ()> {
428                 let secp_ctx = Secp256k1::signing_only();
429                 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, 0, 1]).unwrap();
430                 let pubkey_hash = WPubkeyHash::hash(&PublicKey::from_secret_key(&secp_ctx, &secret_key).serialize());
431                 Ok(ShutdownScript::new_p2wpkh(&pubkey_hash))
432         }
433 }
434
435 #[inline]
436 pub fn do_test(mut data: &[u8], logger: &Arc<dyn Logger>) {
437         if data.len() < 32 { return; }
438
439         let our_network_key = match SecretKey::from_slice(&data[..32]) {
440                 Ok(key) => key,
441                 Err(_) => return,
442         };
443         data = &data[32..];
444
445         let config: UserConfig = if let Ok(config) = Readable::read(&mut data) { config } else { return; };
446
447         let input = Arc::new(InputData {
448                 data: data.to_vec(),
449                 read_pos: AtomicUsize::new(0),
450         });
451         let fee_est = Arc::new(FuzzEstimator {
452                 input: input.clone(),
453         });
454         let router = FuzzRouter {};
455
456         macro_rules! get_slice {
457                 ($len: expr) => {
458                         match input.get_slice($len as usize) {
459                                 Some(slice) => slice,
460                                 None => return,
461                         }
462                 }
463         }
464
465         macro_rules! get_bytes {
466                 ($len: expr) => { {
467                         let mut res = [0; $len];
468                         match input.get_slice($len as usize) {
469                                 Some(slice) => res.copy_from_slice(slice),
470                                 None => return,
471                         }
472                         res
473                 } }
474         }
475
476         macro_rules! get_pubkey {
477                 () => {
478                         match PublicKey::from_slice(get_slice!(33)) {
479                                 Ok(key) => key,
480                                 Err(_) => return,
481                         }
482                 }
483         }
484
485
486         let inbound_payment_key = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 42];
487
488         let broadcast = Arc::new(TestBroadcaster{ txn_broadcasted: Mutex::new(Vec::new()) });
489         let monitor = Arc::new(chainmonitor::ChainMonitor::new(None, broadcast.clone(), Arc::clone(&logger), fee_est.clone(),
490                 Arc::new(TestPersister { update_ret: Mutex::new(ChannelMonitorUpdateStatus::Completed) })));
491
492         let keys_manager = Arc::new(KeyProvider {
493                 node_secret: our_network_key.clone(),
494                 inbound_payment_key: KeyMaterial(inbound_payment_key.try_into().unwrap()),
495                 counter: AtomicU64::new(0),
496                 signer_state: RefCell::new(new_hash_map())
497         });
498         let network = Network::Bitcoin;
499         let best_block_timestamp = genesis_block(network).header.time;
500         let params = ChainParameters {
501                 network,
502                 best_block: BestBlock::from_network(network),
503         };
504         let channelmanager = Arc::new(ChannelManager::new(fee_est.clone(), monitor.clone(), broadcast.clone(), &router, Arc::clone(&logger), keys_manager.clone(), keys_manager.clone(), keys_manager.clone(), config, params, best_block_timestamp));
505         // Adding new calls to `EntropySource::get_secure_random_bytes` during startup can change all the
506         // keys subsequently generated in this test. Rather than regenerating all the messages manually,
507         // it's easier to just increment the counter here so the keys don't change.
508         keys_manager.counter.fetch_sub(3, Ordering::AcqRel);
509         let network_graph = Arc::new(NetworkGraph::new(network, Arc::clone(&logger)));
510         let gossip_sync = Arc::new(P2PGossipSync::new(Arc::clone(&network_graph), None, Arc::clone(&logger)));
511
512         let peers = RefCell::new([false; 256]);
513         let mut loss_detector = MoneyLossDetector::new(&peers, channelmanager.clone(), monitor.clone(), PeerManager::new(MessageHandler {
514                 chan_handler: channelmanager.clone(),
515                 route_handler: gossip_sync.clone(),
516                 onion_message_handler: IgnoringMessageHandler {},
517                 custom_message_handler: IgnoringMessageHandler {},
518         }, 0, &[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 15, 0], Arc::clone(&logger), keys_manager.clone()));
519
520         let mut should_forward = false;
521         let mut payments_received: Vec<PaymentHash> = Vec::new();
522         let mut intercepted_htlcs: Vec<InterceptId> = Vec::new();
523         let mut payments_sent: u16 = 0;
524         let mut pending_funding_generation: Vec<(ChannelId, PublicKey, u64, ScriptBuf)> = Vec::new();
525         let mut pending_funding_signatures = new_hash_map();
526
527         loop {
528                 match get_slice!(1)[0] {
529                         0 => {
530                                 let mut new_id = 0;
531                                 for i in 1..256 {
532                                         if !peers.borrow()[i-1] {
533                                                 new_id = i;
534                                                 break;
535                                         }
536                                 }
537                                 if new_id == 0 { return; }
538                                 loss_detector.handler.new_outbound_connection(get_pubkey!(), Peer{id: (new_id - 1) as u8, peers_connected: &peers}, None).unwrap();
539                                 peers.borrow_mut()[new_id - 1] = true;
540                         },
541                         1 => {
542                                 let mut new_id = 0;
543                                 for i in 1..256 {
544                                         if !peers.borrow()[i-1] {
545                                                 new_id = i;
546                                                 break;
547                                         }
548                                 }
549                                 if new_id == 0 { return; }
550                                 loss_detector.handler.new_inbound_connection(Peer{id: (new_id - 1) as u8, peers_connected: &peers}, None).unwrap();
551                                 peers.borrow_mut()[new_id - 1] = true;
552                         },
553                         2 => {
554                                 let peer_id = get_slice!(1)[0];
555                                 if !peers.borrow()[peer_id as usize] { return; }
556                                 loss_detector.handler.socket_disconnected(&Peer{id: peer_id, peers_connected: &peers});
557                                 peers.borrow_mut()[peer_id as usize] = false;
558                         },
559                         3 => {
560                                 let peer_id = get_slice!(1)[0];
561                                 if !peers.borrow()[peer_id as usize] { return; }
562                                 match loss_detector.handler.read_event(&mut Peer{id: peer_id, peers_connected: &peers}, get_slice!(get_slice!(1)[0])) {
563                                         Ok(res) => assert!(!res),
564                                         Err(_) => { peers.borrow_mut()[peer_id as usize] = false; }
565                                 }
566                         },
567                         4 => {
568                                 let final_value_msat = slice_to_be24(get_slice!(3)) as u64;
569                                 let payment_params = PaymentParameters::from_node_id(get_pubkey!(), 42);
570                                 let params = RouteParameters::from_payment_params_and_value(
571                                         payment_params, final_value_msat);
572                                 let mut payment_hash = PaymentHash([0; 32]);
573                                 payment_hash.0[0..2].copy_from_slice(&be16_to_array(payments_sent));
574                                 payment_hash.0 = Sha256::hash(&payment_hash.0[..]).to_byte_array();
575                                 payments_sent += 1;
576                                 let _ = channelmanager.send_payment(
577                                         payment_hash, RecipientOnionFields::spontaneous_empty(),
578                                         PaymentId(payment_hash.0), params, Retry::Attempts(2)
579                                 );
580                         },
581                         15 => {
582                                 let final_value_msat = slice_to_be24(get_slice!(3)) as u64;
583                                 let payment_params = PaymentParameters::from_node_id(get_pubkey!(), 42);
584                                 let params = RouteParameters::from_payment_params_and_value(
585                                         payment_params, final_value_msat);
586                                 let mut payment_hash = PaymentHash([0; 32]);
587                                 payment_hash.0[0..2].copy_from_slice(&be16_to_array(payments_sent));
588                                 payment_hash.0 = Sha256::hash(&payment_hash.0[..]).to_byte_array();
589                                 payments_sent += 1;
590                                 let mut payment_secret = PaymentSecret([0; 32]);
591                                 payment_secret.0[0..2].copy_from_slice(&be16_to_array(payments_sent));
592                                 payments_sent += 1;
593                                 let _ = channelmanager.send_payment(
594                                         payment_hash, RecipientOnionFields::secret_only(payment_secret),
595                                         PaymentId(payment_hash.0), params, Retry::Attempts(2)
596                                 );
597                         },
598                         17 => {
599                                 let final_value_msat = slice_to_be24(get_slice!(3)) as u64;
600                                 let payment_params = PaymentParameters::from_node_id(get_pubkey!(), 42);
601                                 let params = RouteParameters::from_payment_params_and_value(
602                                         payment_params, final_value_msat);
603                                 let _ = channelmanager.send_preflight_probes(params, None);
604                         },
605                         18 => {
606                                 let idx = u16::from_be_bytes(get_bytes!(2)) % cmp::max(payments_sent, 1);
607                                 let mut payment_id = PaymentId([0; 32]);
608                                 payment_id.0[0..2].copy_from_slice(&idx.to_be_bytes());
609                                 channelmanager.abandon_payment(payment_id);
610                         },
611                         5 => {
612                                 let peer_id = get_slice!(1)[0];
613                                 if !peers.borrow()[peer_id as usize] { return; }
614                                 let their_key = get_pubkey!();
615                                 let chan_value = slice_to_be24(get_slice!(3)) as u64;
616                                 let push_msat_value = slice_to_be24(get_slice!(3)) as u64;
617                                 if channelmanager.create_channel(their_key, chan_value, push_msat_value, 0, None, None).is_err() { return; }
618                         },
619                         6 => {
620                                 let mut channels = channelmanager.list_channels();
621                                 let channel_id = get_slice!(1)[0] as usize;
622                                 if channel_id >= channels.len() { return; }
623                                 channels.sort_by(|a, b| { a.channel_id.cmp(&b.channel_id) });
624                                 if channelmanager.close_channel(&channels[channel_id].channel_id, &channels[channel_id].counterparty.node_id).is_err() { return; }
625                         },
626                         7 => {
627                                 if should_forward {
628                                         channelmanager.process_pending_htlc_forwards();
629                                         should_forward = false;
630                                 }
631                         },
632                         8 => {
633                                 for payment in payments_received.drain(..) {
634                                         // SHA256 is defined as XOR of all input bytes placed in the first byte, and 0s
635                                         // for the remaining bytes. Thus, if not all remaining bytes are 0s we cannot
636                                         // fulfill this HTLC, but if they are, we can just take the first byte and
637                                         // place that anywhere in our preimage.
638                                         if &payment.0[1..] != &[0; 31] {
639                                                 channelmanager.fail_htlc_backwards(&payment);
640                                         } else {
641                                                 let mut payment_preimage = PaymentPreimage([0; 32]);
642                                                 payment_preimage.0[0] = payment.0[0];
643                                                 channelmanager.claim_funds(payment_preimage);
644                                         }
645                                 }
646                         },
647                         16 => {
648                                 let payment_preimage = PaymentPreimage(keys_manager.get_secure_random_bytes());
649                                 let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0[..]).to_byte_array());
650                                 // Note that this may fail - our hashes may collide and we'll end up trying to
651                                 // double-register the same payment_hash.
652                                 let _ = channelmanager.create_inbound_payment_for_hash(payment_hash, None, 1, None);
653                         },
654                         9 => {
655                                 for payment in payments_received.drain(..) {
656                                         channelmanager.fail_htlc_backwards(&payment);
657                                 }
658                         },
659                         10 => {
660                                 let mut tx = Transaction { version: Version(0), lock_time: LockTime::ZERO, input: Vec::new(), output: Vec::new() };
661                                 let mut channels = Vec::new();
662                                 for funding_generation in pending_funding_generation.drain(..) {
663                                         let txout = TxOut {
664                                                 value: Amount::from_sat(funding_generation.2), script_pubkey: funding_generation.3,
665                                         };
666                                         if !tx.output.contains(&txout) {
667                                                 tx.output.push(txout);
668                                                 channels.push((funding_generation.0, funding_generation.1));
669                                         }
670                                 }
671                                 // Once we switch to V2 channel opens we should be able to drop this entirely as
672                                 // channel_ids no longer change when we set the funding tx.
673                                 'search_loop: loop {
674                                         if tx.version.0 > 0xff {
675                                                 break;
676                                         }
677                                         let funding_txid = tx.txid();
678                                         if loss_detector.txids_confirmed.get(&funding_txid).is_none() {
679                                                 let outpoint = OutPoint { txid: funding_txid, index: 0 };
680                                                 for chan in channelmanager.list_channels() {
681                                                         if chan.channel_id == ChannelId::v1_from_funding_outpoint(outpoint) {
682                                                                 tx.version = Version(tx.version.0 + 1);
683                                                                 continue 'search_loop;
684                                                         }
685                                                 }
686                                                 break;
687                                         }
688                                         tx.version = Version(tx.version.0 + 1);
689                                 }
690                                 if tx.version.0 <= 0xff && !channels.is_empty() {
691                                         let chans = channels.iter().map(|(a, b)| (a, b)).collect::<Vec<_>>();
692                                         if let Err(e) = channelmanager.batch_funding_transaction_generated(&chans, tx.clone()) {
693                                                 // It's possible the channel has been closed in the mean time, but any other
694                                                 // failure may be a bug.
695                                                 if let APIError::ChannelUnavailable { .. } = e { } else { panic!(); }
696                                         }
697                                         let funding_txid = tx.txid();
698                                         for idx in 0..tx.output.len() {
699                                                 let outpoint = OutPoint { txid: funding_txid, index: idx as u16 };
700                                                 pending_funding_signatures.insert(outpoint, tx.clone());
701                                         }
702                                 }
703                         },
704                         11 => {
705                                 let mut txn = broadcast.txn_broadcasted.lock().unwrap().split_off(0);
706                                 if !txn.is_empty() {
707                                         loss_detector.connect_block(&txn[..]);
708                                         for _ in 2..100 {
709                                                 loss_detector.connect_block(&[]);
710                                         }
711                                 }
712                                 for tx in txn.drain(..) {
713                                         loss_detector.funding_txn.push(tx);
714                                 }
715                         },
716                         12 => {
717                                 let txlen = u16::from_be_bytes(get_bytes!(2));
718                                 if txlen == 0 {
719                                         loss_detector.connect_block(&[]);
720                                 } else {
721                                         let txres: Result<Transaction, _> = deserialize(get_slice!(txlen));
722                                         if let Ok(tx) = txres {
723                                                 let mut output_val = Amount::ZERO;
724                                                 for out in tx.output.iter() {
725                                                         if out.value > Amount::MAX_MONEY { return; }
726                                                         output_val += out.value;
727                                                         if output_val > Amount::MAX_MONEY { return; }
728                                                 }
729                                                 loss_detector.connect_block(&[tx]);
730                                         } else {
731                                                 return;
732                                         }
733                                 }
734                         },
735                         13 => {
736                                 loss_detector.disconnect_block();
737                         },
738                         14 => {
739                                 let mut channels = channelmanager.list_channels();
740                                 let channel_id = get_slice!(1)[0] as usize;
741                                 let error_message = "Channel force-closed";
742                                 if channel_id >= channels.len() { return; }
743                                 channels.sort_by(|a, b| { a.channel_id.cmp(&b.channel_id) });
744                                 channelmanager.force_close_broadcasting_latest_txn(&channels[channel_id].channel_id, &channels[channel_id].counterparty.node_id, error_message.to_string()).unwrap();
745                         },
746                         // 15, 16, 17, 18 is above
747                         19 => {
748                                 let mut list = loss_detector.handler.list_peers();
749                                 list.sort_by_key(|v| v.counterparty_node_id);
750                                 if let Some(peer_details) = list.get(0) {
751                                         loss_detector.handler.disconnect_by_node_id(peer_details.counterparty_node_id);
752                                 }
753                         },
754                         20 => loss_detector.handler.disconnect_all_peers(),
755                         21 => loss_detector.handler.timer_tick_occurred(),
756                         22 =>
757                                 loss_detector.handler.broadcast_node_announcement([42; 3], [43; 32], Vec::new()),
758                         32 => channelmanager.timer_tick_occurred(),
759                         33 => {
760                                 for id in intercepted_htlcs.drain(..) {
761                                         channelmanager.fail_intercepted_htlc(id).unwrap();
762                                 }
763                         }
764                         34 => {
765                                 let amt = u64::from_be_bytes(get_bytes!(8));
766                                 let chans = channelmanager.list_channels();
767                                 for id in intercepted_htlcs.drain(..) {
768                                         if chans.is_empty() {
769                                                 channelmanager.fail_intercepted_htlc(id).unwrap();
770                                         } else {
771                                                 let chan = &chans[amt as usize % chans.len()];
772                                                 channelmanager.forward_intercepted_htlc(id, &chan.channel_id, chan.counterparty.node_id, amt).unwrap();
773                                         }
774                                 }
775                         }
776                         35 => {
777                                 let config: ChannelConfig =
778                                         if let Ok(c) = Readable::read(&mut &*input) { c } else { return; };
779                                 let chans = channelmanager.list_channels();
780                                 if let Some(chan) = chans.get(0) {
781                                         let _ = channelmanager.update_channel_config(
782                                                 &chan.counterparty.node_id, &[chan.channel_id], &config
783                                         );
784                                 }
785                         }
786                         _ => return,
787                 }
788                 loss_detector.handler.process_events();
789                 for event in loss_detector.manager.get_and_clear_pending_events() {
790                         match event {
791                                 Event::FundingGenerationReady { temporary_channel_id, counterparty_node_id, channel_value_satoshis, output_script, .. } => {
792                                         pending_funding_generation.push((temporary_channel_id, counterparty_node_id, channel_value_satoshis, output_script));
793                                 },
794                                 Event::PaymentClaimable { payment_hash, .. } => {
795                                         //TODO: enhance by fetching random amounts from fuzz input?
796                                         payments_received.push(payment_hash);
797                                 },
798                                 Event::PendingHTLCsForwardable {..} => {
799                                         should_forward = true;
800                                 },
801                                 Event::HTLCIntercepted { intercept_id, .. } => {
802                                         if !intercepted_htlcs.contains(&intercept_id) {
803                                                 intercepted_htlcs.push(intercept_id);
804                                         }
805                                 },
806                                 _ => {},
807                         }
808                 }
809         }
810 }
811
812 pub fn full_stack_test<Out: test_logger::Output>(data: &[u8], out: Out) {
813         let logger: Arc<dyn Logger> = Arc::new(test_logger::TestLogger::new("".to_owned(), out));
814         do_test(data, &logger);
815 }
816
817 #[no_mangle]
818 pub extern "C" fn full_stack_run(data: *const u8, datalen: usize) {
819         let logger: Arc<dyn Logger> = Arc::new(test_logger::TestLogger::new("".to_owned(), test_logger::DevNull {}));
820         do_test(unsafe { std::slice::from_raw_parts(data, datalen) }, &logger);
821 }
822
823 #[cfg(test)]
824 mod tests {
825         use bitcoin::hashes::hex::FromHex;
826         use lightning::util::logger::{Logger, Record};
827         use std::collections::HashMap;
828         use std::sync::{Arc, Mutex};
829
830         struct TrackingLogger {
831                 /// (module, message) -> count
832                 pub lines: Mutex<HashMap<(String, String), usize>>,
833         }
834         impl Logger for TrackingLogger {
835                 fn log(&self, record: Record) {
836                         *self.lines.lock().unwrap().entry((record.module_path.to_string(), format!("{}", record.args))).or_insert(0) += 1;
837                         println!("{:<5} [{} : {}, {}] {}", record.level.to_string(), record.module_path, record.file, record.line, record.args);
838                 }
839         }
840
841         fn ext_from_hex(hex_with_spaces: &str, out: &mut Vec<u8>) {
842                 for hex in hex_with_spaces.split(" ") {
843                         out.append(&mut <Vec<u8>>::from_hex(hex).unwrap());
844                 }
845         }
846
847         #[test]
848         fn test_no_existing_test_breakage() {
849                 // To avoid accidentally causing all existing fuzz test cases to be useless by making minor
850                 // changes (such as requesting feerate info in a new place), we run a pretty full
851                 // step-through with two peers and HTLC forwarding here. Obviously this is pretty finicky,
852                 // so this should be updated pretty liberally, but at least we'll know when changes occur.
853                 // If nothing else, this test serves as a pretty great initial full_stack_target seed.
854
855                 // Following BOLT 8, lightning message on the wire are: 2-byte encrypted message length +
856                 // 16-byte MAC of the encrypted message length + encrypted Lightning message + 16-byte MAC
857                 // of the Lightning message
858                 // I.e 2nd inbound read, len 18 : 0006 (encrypted message length) + 03000000000000000000000000000000 (MAC of the encrypted message length)
859                 // Len 22 : 0010 00000000 (encrypted lightning message) + 03000000000000000000000000000000 (MAC of the Lightning message)
860
861                 // Writing new code generating transactions and see a new failure ? Don't forget to add input for the FuzzEstimator !
862
863                 let mut test = Vec::new();
864                 // our network key
865                 ext_from_hex("0100000000000000000000000000000000000000000000000000000000000000", &mut test);
866                 // config
867                 ext_from_hex("0000000000900000000000000000640001000000000001ffff0000000000000000ffffffffffffffffffffffffffffffff0000000000000000ffffffffffffffff000000ffffffff00ffff1a000400010000020400000000040200000a08ffffffffffffffff0001000000", &mut test);
868
869                 // new outbound connection with id 0
870                 ext_from_hex("00", &mut test);
871                 // peer's pubkey
872                 ext_from_hex("030000000000000000000000000000000000000000000000000000000000000002", &mut test);
873                 // inbound read from peer id 0 of len 50
874                 ext_from_hex("030032", &mut test);
875                 // noise act two (0||pubkey||mac)
876                 ext_from_hex("00 030000000000000000000000000000000000000000000000000000000000000002 03000000000000000000000000000000", &mut test);
877
878                 // inbound read from peer id 0 of len 18
879                 ext_from_hex("030012", &mut test);
880                 // message header indicating message length 16
881                 ext_from_hex("0010 03000000000000000000000000000000", &mut test);
882                 // inbound read from peer id 0 of len 32
883                 ext_from_hex("030020", &mut test);
884                 // init message (type 16) with static_remotekey required, no channel_type/anchors/taproot, and other bits optional and mac
885                 ext_from_hex("0010 00021aaa 0008aaa20aaa2a0a9aaa 03000000000000000000000000000000", &mut test);
886
887                 // inbound read from peer id 0 of len 18
888                 ext_from_hex("030012", &mut test);
889                 // message header indicating message length 327
890                 ext_from_hex("0147 03000000000000000000000000000000", &mut test);
891                 // inbound read from peer id 0 of len 254
892                 ext_from_hex("0300fe", &mut test);
893                 // beginning of open_channel message
894                 ext_from_hex("0020 6fe28c0ab6f1b372c1a6a246ae63f74f931e8365e15a089c68d6190000000000 ff4f00f805273c1b203bb5ebf8436bfde57b3be8c2f5e95d9491dbb181909679 000000000000c350 0000000000000000 0000000000000162 ffffffffffffffff 0000000000000222 0000000000000000 000000fd 0006 01e3 030000000000000000000000000000000000000000000000000000000000000001 030000000000000000000000000000000000000000000000000000000000000002 030000000000000000000000000000000000000000000000000000000000000003 030000000000000000000000000000000000000000000000000000000000000004", &mut test);
895                 // inbound read from peer id 0 of len 89
896                 ext_from_hex("030059", &mut test);
897                 // rest of open_channel and mac
898                 ext_from_hex("030000000000000000000000000000000000000000000000000000000000000005 020900000000000000000000000000000000000000000000000000000000000000 01 0000 01021000 03000000000000000000000000000000", &mut test);
899
900                 // One feerate request returning min feerate, which our open_channel also uses (ingested by FuzzEstimator)
901                 ext_from_hex("00fd", &mut test);
902                 // client should now respond with accept_channel (CHECK 1: type 33 to peer 03000000)
903
904                 // inbound read from peer id 0 of len 18
905                 ext_from_hex("030012", &mut test);
906                 // message header indicating message length 132
907                 ext_from_hex("0084 03000000000000000000000000000000", &mut test);
908                 // inbound read from peer id 0 of len 148
909                 ext_from_hex("030094", &mut test);
910                 // funding_created and mac
911                 ext_from_hex("0022 ff4f00f805273c1b203bb5ebf8436bfde57b3be8c2f5e95d9491dbb181909679 3d00000000000000000000000000000000000000000000000000000000000000 0000 00000000000000000000000000000000000000000000000000000000000000210100000000000000000000000000000000000000000000000000000000000000 03000000000000000000000000000000", &mut test);
912                 // client should now respond with funding_signed (CHECK 2: type 35 to peer 03000000)
913
914                 // connect a block with one transaction of len 94
915                 ext_from_hex("0c005e", &mut test);
916                 // the funding transaction
917                 ext_from_hex("020000000100000000000000000000000000000000000000000000000000000000000000000000000000ffffffff0150c3000000000000220020ae0000000000000000000000000000000000000000000000000000000000000000000000", &mut test);
918                 // connect a block with no transactions, one per line
919                 ext_from_hex("0c0000", &mut test);
920                 ext_from_hex("0c0000", &mut test);
921                 ext_from_hex("0c0000", &mut test);
922                 ext_from_hex("0c0000", &mut test);
923                 ext_from_hex("0c0000", &mut test);
924                 ext_from_hex("0c0000", &mut test);
925                 ext_from_hex("0c0000", &mut test);
926                 ext_from_hex("0c0000", &mut test);
927                 ext_from_hex("0c0000", &mut test);
928                 ext_from_hex("0c0000", &mut test);
929                 ext_from_hex("0c0000", &mut test);
930                 ext_from_hex("0c0000", &mut test);
931                 // by now client should have sent a channel_ready (CHECK 3: SendChannelReady to 03000000 for chan 3d000000)
932
933                 // inbound read from peer id 0 of len 18
934                 ext_from_hex("030012", &mut test);
935                 // message header indicating message length 67
936                 ext_from_hex("0043 03000000000000000000000000000000", &mut test);
937                 // inbound read from peer id 0 of len 83
938                 ext_from_hex("030053", &mut test);
939                 // channel_ready and mac
940                 ext_from_hex("0024 3d00000000000000000000000000000000000000000000000000000000000000 020800000000000000000000000000000000000000000000000000000000000000 03000000000000000000000000000000", &mut test);
941
942                 // new inbound connection with id 1
943                 ext_from_hex("01", &mut test);
944                 // inbound read from peer id 1 of len 50
945                 ext_from_hex("030132", &mut test);
946                 // inbound noise act 1
947                 ext_from_hex("0003000000000000000000000000000000000000000000000000000000000000000703000000000000000000000000000000", &mut test);
948                 // inbound read from peer id 1 of len 66
949                 ext_from_hex("030142", &mut test);
950                 // inbound noise act 3
951                 ext_from_hex("000302000000000000000000000000000000000000000000000000000000000000000300000000000000000000000000000003000000000000000000000000000000", &mut test);
952
953                 // inbound read from peer id 1 of len 18
954                 ext_from_hex("030112", &mut test);
955                 // message header indicating message length 16
956                 ext_from_hex("0010 01000000000000000000000000000000", &mut test);
957                 // inbound read from peer id 1 of len 32
958                 ext_from_hex("030120", &mut test);
959                 // init message (type 16) with static_remotekey required, no channel_type/anchors/taproot, and other bits optional and mac
960                 ext_from_hex("0010 00021aaa 0008aaa20aaa2a0a9aaa 01000000000000000000000000000000", &mut test);
961
962                 // create outbound channel to peer 1 for 50k sat
963                 ext_from_hex("05 01 030200000000000000000000000000000000000000000000000000000000000000 00c350 0003e8", &mut test);
964                 // One feerate requests (all returning min feerate) (gonna be ingested by FuzzEstimator)
965                 ext_from_hex("00fd", &mut test);
966
967                 // inbound read from peer id 1 of len 18
968                 ext_from_hex("030112", &mut test);
969                 // message header indicating message length 274
970                 ext_from_hex("0112 01000000000000000000000000000000", &mut test);
971                 // inbound read from peer id 1 of len 255
972                 ext_from_hex("0301ff", &mut test);
973                 // beginning of accept_channel
974                 ext_from_hex("0021 0000000000000000000000000000000000000000000000000000000000000e05 0000000000000162 00000000004c4b40 00000000000003e8 00000000000003e8 00000002 03f0 0005 030000000000000000000000000000000000000000000000000000000000000100 030000000000000000000000000000000000000000000000000000000000000200 030000000000000000000000000000000000000000000000000000000000000300 030000000000000000000000000000000000000000000000000000000000000400 030000000000000000000000000000000000000000000000000000000000000500 02660000000000000000000000000000", &mut test);
975                 // inbound read from peer id 1 of len 35
976                 ext_from_hex("030123", &mut test);
977                 // rest of accept_channel and mac
978                 ext_from_hex("0000000000000000000000000000000000 0000 01000000000000000000000000000000", &mut test);
979
980                 // create the funding transaction (client should send funding_created now)
981                 ext_from_hex("0a", &mut test);
982                 // Two feerate requests to check the dust exposure on the initial commitment tx
983                 ext_from_hex("00fd00fd", &mut test);
984
985                 // inbound read from peer id 1 of len 18
986                 ext_from_hex("030112", &mut test);
987                 // message header indicating message length 98
988                 ext_from_hex("0062 01000000000000000000000000000000", &mut test);
989                 // inbound read from peer id 1 of len 114
990                 ext_from_hex("030172", &mut test);
991                 // funding_signed message and mac
992                 ext_from_hex("0023 3a00000000000000000000000000000000000000000000000000000000000000 000000000000000000000000000000000000000000000000000000000000007c0001000000000000000000000000000000000000000000000000000000000000 01000000000000000000000000000000", &mut test);
993
994                 // broadcast funding transaction
995                 ext_from_hex("0b", &mut test);
996                 // by now client should have sent a channel_ready (CHECK 4: SendChannelReady to 03020000 for chan 3f000000)
997
998                 // inbound read from peer id 1 of len 18
999                 ext_from_hex("030112", &mut test);
1000                 // message header indicating message length 67
1001                 ext_from_hex("0043 01000000000000000000000000000000", &mut test);
1002                 // inbound read from peer id 1 of len 83
1003                 ext_from_hex("030153", &mut test);
1004                 // channel_ready and mac
1005                 ext_from_hex("0024 3a00000000000000000000000000000000000000000000000000000000000000 026700000000000000000000000000000000000000000000000000000000000000 01000000000000000000000000000000", &mut test);
1006
1007                 // inbound read from peer id 0 of len 18
1008                 ext_from_hex("030012", &mut test);
1009                 // message header indicating message length 1452
1010                 ext_from_hex("05ac 03000000000000000000000000000000", &mut test);
1011                 // inbound read from peer id 0 of len 255
1012                 ext_from_hex("0300ff", &mut test);
1013                 // beginning of update_add_htlc from 0 to 1 via client
1014                 ext_from_hex("0080 3d00000000000000000000000000000000000000000000000000000000000000 0000000000000000 0000000000003e80 ff00000000000000000000000000000000000000000000000000000000000000 000003f0 00 030000000000000000000000000000000000000000000000000000000000000555 11 020203e8 0401a0 060800000e0000010000 0a00000000000000000000000000000000000000000000000000000000000000 ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", &mut test);
1015                 // inbound read from peer id 0 of len 255
1016                 ext_from_hex("0300ff", &mut test);
1017                 ext_from_hex("ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", &mut test);
1018                 // inbound read from peer id 0 of len 255
1019                 ext_from_hex("0300ff", &mut test);
1020                 ext_from_hex("ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", &mut test);
1021                 // inbound read from peer id 0 of len 255
1022                 ext_from_hex("0300ff", &mut test);
1023                 ext_from_hex("ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", &mut test);
1024                 // inbound read from peer id 0 of len 255
1025                 ext_from_hex("0300ff", &mut test);
1026                 ext_from_hex("ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", &mut test);
1027                 // inbound read from peer id 0 of len 193
1028                 ext_from_hex("0300c1", &mut test);
1029                 // end of update_add_htlc from 0 to 1 via client and mac
1030                 ext_from_hex("ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff ab00000000000000000000000000000000000000000000000000000000000000 03000000000000000000000000000000", &mut test);
1031
1032                 // Two feerate requests to check dust exposure
1033                 ext_from_hex("00fd00fd", &mut test);
1034
1035                 // inbound read from peer id 0 of len 18
1036                 ext_from_hex("030012", &mut test);
1037                 // message header indicating message length 100
1038                 ext_from_hex("0064 03000000000000000000000000000000", &mut test);
1039                 // inbound read from peer id 0 of len 116
1040                 ext_from_hex("030074", &mut test);
1041                 // commitment_signed and mac
1042                 ext_from_hex("0084 3d00000000000000000000000000000000000000000000000000000000000000 00000000000000000000000000000000000000000000000000000000000000300100000000000000000000000000000000000000000000000000000000000000 0000 03000000000000000000000000000000", &mut test);
1043                 // client should now respond with revoke_and_ack and commitment_signed (CHECK 5/6: types 133 and 132 to peer 03000000)
1044
1045                 // inbound read from peer id 0 of len 18
1046                 ext_from_hex("030012", &mut test);
1047                 // message header indicating message length 99
1048                 ext_from_hex("0063 03000000000000000000000000000000", &mut test);
1049                 // inbound read from peer id 0 of len 115
1050                 ext_from_hex("030073", &mut test);
1051                 // revoke_and_ack and mac
1052                 ext_from_hex("0085 3d00000000000000000000000000000000000000000000000000000000000000 0900000000000000000000000000000000000000000000000000000000000000 020b00000000000000000000000000000000000000000000000000000000000000 03000000000000000000000000000000", &mut test);
1053
1054                 // process the now-pending HTLC forward
1055                 ext_from_hex("07", &mut test);
1056                 // Two feerate requests to check dust exposure
1057                 ext_from_hex("00fd00fd", &mut test);
1058                 // client now sends id 1 update_add_htlc and commitment_signed (CHECK 7: UpdateHTLCs event for node 03020000 with 1 HTLCs for channel 3f000000)
1059
1060                 // we respond with commitment_signed then revoke_and_ack (a weird, but valid, order)
1061                 // inbound read from peer id 1 of len 18
1062                 ext_from_hex("030112", &mut test);
1063                 // message header indicating message length 100
1064                 ext_from_hex("0064 01000000000000000000000000000000", &mut test);
1065                 // inbound read from peer id 1 of len 116
1066                 ext_from_hex("030174", &mut test);
1067                 // commitment_signed and mac
1068                 ext_from_hex("0084 3a00000000000000000000000000000000000000000000000000000000000000 000000000000000000000000000000000000000000000000000000000000006a0001000000000000000000000000000000000000000000000000000000000000 0000 01000000000000000000000000000000", &mut test);
1069                 //
1070                 // inbound read from peer id 1 of len 18
1071                 ext_from_hex("030112", &mut test);
1072                 // message header indicating message length 99
1073                 ext_from_hex("0063 01000000000000000000000000000000", &mut test);
1074                 // inbound read from peer id 1 of len 115
1075                 ext_from_hex("030173", &mut test);
1076                 // revoke_and_ack and mac
1077                 ext_from_hex("0085 3a00000000000000000000000000000000000000000000000000000000000000 6600000000000000000000000000000000000000000000000000000000000000 026400000000000000000000000000000000000000000000000000000000000000 01000000000000000000000000000000", &mut test);
1078                 //
1079                 // inbound read from peer id 1 of len 18
1080                 ext_from_hex("030112", &mut test);
1081                 // message header indicating message length 74
1082                 ext_from_hex("004a 01000000000000000000000000000000", &mut test);
1083                 // inbound read from peer id 1 of len 90
1084                 ext_from_hex("03015a", &mut test);
1085                 // update_fulfill_htlc and mac
1086                 ext_from_hex("0082 3a00000000000000000000000000000000000000000000000000000000000000 0000000000000000 ff00888888888888888888888888888888888888888888888888888888888888 01000000000000000000000000000000", &mut test);
1087                 // client should immediately claim the pending HTLC from peer 0 (CHECK 8: SendFulfillHTLCs for node 03000000 with preimage ff00888888 for channel 3d000000)
1088
1089                 // inbound read from peer id 1 of len 18
1090                 ext_from_hex("030112", &mut test);
1091                 // message header indicating message length 100
1092                 ext_from_hex("0064 01000000000000000000000000000000", &mut test);
1093                 // inbound read from peer id 1 of len 116
1094                 ext_from_hex("030174", &mut test);
1095                 // commitment_signed and mac
1096                 ext_from_hex("0084 3a00000000000000000000000000000000000000000000000000000000000000 00000000000000000000000000000000000000000000000000000000000000100001000000000000000000000000000000000000000000000000000000000000 0000 01000000000000000000000000000000", &mut test);
1097
1098                 // inbound read from peer id 1 of len 18
1099                 ext_from_hex("030112", &mut test);
1100                 // message header indicating message length 99
1101                 ext_from_hex("0063 01000000000000000000000000000000", &mut test);
1102                 // inbound read from peer id 1 of len 115
1103                 ext_from_hex("030173", &mut test);
1104                 // revoke_and_ack and mac
1105                 ext_from_hex("0085 3a00000000000000000000000000000000000000000000000000000000000000 6700000000000000000000000000000000000000000000000000000000000000 026500000000000000000000000000000000000000000000000000000000000000 01000000000000000000000000000000", &mut test);
1106
1107                 // before responding to the commitment_signed generated above, send a new HTLC
1108                 // inbound read from peer id 0 of len 18
1109                 ext_from_hex("030012", &mut test);
1110                 // message header indicating message length 1452
1111                 ext_from_hex("05ac 03000000000000000000000000000000", &mut test);
1112                 // inbound read from peer id 0 of len 255
1113                 ext_from_hex("0300ff", &mut test);
1114                 // beginning of update_add_htlc from 0 to 1 via client
1115                 ext_from_hex("0080 3d00000000000000000000000000000000000000000000000000000000000000 0000000000000001 0000000000003e80 ff00000000000000000000000000000000000000000000000000000000000000 000003f0 00 030000000000000000000000000000000000000000000000000000000000000555 11 020203e8 0401a0 060800000e0000010000 0a00000000000000000000000000000000000000000000000000000000000000 ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", &mut test);
1116                 // inbound read from peer id 0 of len 255
1117                 ext_from_hex("0300ff", &mut test);
1118                 ext_from_hex("ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", &mut test);
1119                 // inbound read from peer id 0 of len 255
1120                 ext_from_hex("0300ff", &mut test);
1121                 ext_from_hex("ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", &mut test);
1122                 // inbound read from peer id 0 of len 255
1123                 ext_from_hex("0300ff", &mut test);
1124                 ext_from_hex("ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", &mut test);
1125                 // inbound read from peer id 0 of len 255
1126                 ext_from_hex("0300ff", &mut test);
1127                 ext_from_hex("ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", &mut test);
1128                 // inbound read from peer id 0 of len 193
1129                 ext_from_hex("0300c1", &mut test);
1130                 // end of update_add_htlc from 0 to 1 via client and mac
1131                 ext_from_hex("ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff ab00000000000000000000000000000000000000000000000000000000000000 03000000000000000000000000000000", &mut test);
1132
1133                 // Two feerate requests to check dust exposure
1134                 ext_from_hex("00fd00fd", &mut test);
1135
1136                 // now respond to the update_fulfill_htlc+commitment_signed messages the client sent to peer 0
1137                 // inbound read from peer id 0 of len 18
1138                 ext_from_hex("030012", &mut test);
1139                 // message header indicating message length 99
1140                 ext_from_hex("0063 03000000000000000000000000000000", &mut test);
1141                 // inbound read from peer id 0 of len 115
1142                 ext_from_hex("030073", &mut test);
1143                 // revoke_and_ack and mac
1144                 ext_from_hex("0085 3d00000000000000000000000000000000000000000000000000000000000000 0800000000000000000000000000000000000000000000000000000000000000 020a00000000000000000000000000000000000000000000000000000000000000 03000000000000000000000000000000", &mut test);
1145                 // client should now respond with revoke_and_ack and commitment_signed (CHECK 5/6 duplicates)
1146
1147                 // inbound read from peer id 0 of len 18
1148                 ext_from_hex("030012", &mut test);
1149                 // message header indicating message length 100
1150                 ext_from_hex("0064 03000000000000000000000000000000", &mut test);
1151                 // inbound read from peer id 0 of len 116
1152                 ext_from_hex("030074", &mut test);
1153                 // commitment_signed and mac
1154                 ext_from_hex("0084 3d00000000000000000000000000000000000000000000000000000000000000 00000000000000000000000000000000000000000000000000000000000000c30100000000000000000000000000000000000000000000000000000000000000 0000 03000000000000000000000000000000", &mut test);
1155
1156                 // inbound read from peer id 0 of len 18
1157                 ext_from_hex("030012", &mut test);
1158                 // message header indicating message length 99
1159                 ext_from_hex("0063 03000000000000000000000000000000", &mut test);
1160                 // inbound read from peer id 0 of len 115
1161                 ext_from_hex("030073", &mut test);
1162                 // revoke_and_ack and mac
1163                 ext_from_hex("0085 3d00000000000000000000000000000000000000000000000000000000000000 0b00000000000000000000000000000000000000000000000000000000000000 020d00000000000000000000000000000000000000000000000000000000000000 03000000000000000000000000000000", &mut test);
1164
1165                 // process the now-pending HTLC forward
1166                 ext_from_hex("07", &mut test);
1167
1168                 // Two feerate requests to check dust exposure
1169                 ext_from_hex("00fd00fd", &mut test);
1170
1171                 // client now sends id 1 update_add_htlc and commitment_signed (CHECK 7 duplicate)
1172                 // we respond with revoke_and_ack, then commitment_signed, then update_fail_htlc
1173
1174                 // inbound read from peer id 1 of len 18
1175                 ext_from_hex("030112", &mut test);
1176                 // message header indicating message length 100
1177                 ext_from_hex("0064 01000000000000000000000000000000", &mut test);
1178                 // inbound read from peer id 1 of len 116
1179                 ext_from_hex("030174", &mut test);
1180                 // commitment_signed and mac
1181                 ext_from_hex("0084 3a00000000000000000000000000000000000000000000000000000000000000 00000000000000000000000000000000000000000000000000000000000000390001000000000000000000000000000000000000000000000000000000000000 0000 01000000000000000000000000000000", &mut test);
1182
1183                 // inbound read from peer id 1 of len 18
1184                 ext_from_hex("030112", &mut test);
1185                 // message header indicating message length 99
1186                 ext_from_hex("0063 01000000000000000000000000000000", &mut test);
1187                 // inbound read from peer id 1 of len 115
1188                 ext_from_hex("030173", &mut test);
1189                 // revoke_and_ack and mac
1190                 ext_from_hex("0085 3a00000000000000000000000000000000000000000000000000000000000000 6400000000000000000000000000000000000000000000000000000000000000 027000000000000000000000000000000000000000000000000000000000000000 01000000000000000000000000000000", &mut test);
1191
1192                 // inbound read from peer id 1 of len 18
1193                 ext_from_hex("030112", &mut test);
1194                 // message header indicating message length 44
1195                 ext_from_hex("002c 01000000000000000000000000000000", &mut test);
1196                 // inbound read from peer id 1 of len 60
1197                 ext_from_hex("03013c", &mut test);
1198                 // update_fail_htlc and mac
1199                 ext_from_hex("0083 3a00000000000000000000000000000000000000000000000000000000000000 0000000000000001 0000 01000000000000000000000000000000", &mut test);
1200
1201                 // inbound read from peer id 1 of len 18
1202                 ext_from_hex("030112", &mut test);
1203                 // message header indicating message length 100
1204                 ext_from_hex("0064 01000000000000000000000000000000", &mut test);
1205                 // inbound read from peer id 1 of len 116
1206                 ext_from_hex("030174", &mut test);
1207                 // commitment_signed and mac
1208                 ext_from_hex("0084 3a00000000000000000000000000000000000000000000000000000000000000 00000000000000000000000000000000000000000000000000000000000000390001000000000000000000000000000000000000000000000000000000000000 0000 01000000000000000000000000000000", &mut test);
1209
1210                 // inbound read from peer id 1 of len 18
1211                 ext_from_hex("030112", &mut test);
1212                 // message header indicating message length 99
1213                 ext_from_hex("0063 01000000000000000000000000000000", &mut test);
1214                 // inbound read from peer id 1 of len 115
1215                 ext_from_hex("030173", &mut test);
1216                 // revoke_and_ack and mac
1217                 ext_from_hex("0085 3a00000000000000000000000000000000000000000000000000000000000000 6500000000000000000000000000000000000000000000000000000000000000 027100000000000000000000000000000000000000000000000000000000000000 01000000000000000000000000000000", &mut test);
1218
1219                 // process the now-pending HTLC forward
1220                 ext_from_hex("07", &mut test);
1221                 // client now sends id 0 update_fail_htlc and commitment_signed (CHECK 9)
1222                 // now respond to the update_fail_htlc+commitment_signed messages the client sent to peer 0
1223
1224                 // inbound read from peer id 0 of len 18
1225                 ext_from_hex("030012", &mut test);
1226                 // message header indicating message length 99
1227                 ext_from_hex("0063 03000000000000000000000000000000", &mut test);
1228                 // inbound read from peer id 0 of len 115
1229                 ext_from_hex("030073", &mut test);
1230                 // revoke_and_ack and mac
1231                 ext_from_hex("0085 3d00000000000000000000000000000000000000000000000000000000000000 0a00000000000000000000000000000000000000000000000000000000000000 020c00000000000000000000000000000000000000000000000000000000000000 03000000000000000000000000000000", &mut test);
1232
1233                 // inbound read from peer id 0 of len 18
1234                 ext_from_hex("030012", &mut test);
1235                 // message header indicating message length 100
1236                 ext_from_hex("0064 03000000000000000000000000000000", &mut test);
1237                 // inbound read from peer id 0 of len 116
1238                 ext_from_hex("030074", &mut test);
1239                 // commitment_signed and mac
1240                 ext_from_hex("0084 3d00000000000000000000000000000000000000000000000000000000000000 00000000000000000000000000000000000000000000000000000000000000320100000000000000000000000000000000000000000000000000000000000000 0000 03000000000000000000000000000000", &mut test);
1241                 // client should now respond with revoke_and_ack (CHECK 5 duplicate)
1242
1243                 // inbound read from peer id 0 of len 18
1244                 ext_from_hex("030012", &mut test);
1245                 // message header indicating message length 1452
1246                 ext_from_hex("05ac 03000000000000000000000000000000", &mut test);
1247                 // inbound read from peer id 0 of len 255
1248                 ext_from_hex("0300ff", &mut test);
1249                 // beginning of update_add_htlc from 0 to 1 via client
1250                 ext_from_hex("0080 3d00000000000000000000000000000000000000000000000000000000000000 0000000000000002 00000000000b0838 ff00000000000000000000000000000000000000000000000000000000000000 000003f0 00 030000000000000000000000000000000000000000000000000000000000000555 12 02030927c0 0401a0 060800000e0000010000 0a00000000000000000000000000000000000000000000000000000000000000 ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", &mut test);
1251                 // inbound read from peer id 0 of len 255
1252                 ext_from_hex("0300ff", &mut test);
1253                 ext_from_hex("ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", &mut test);
1254                 // inbound read from peer id 0 of len 255
1255                 ext_from_hex("0300ff", &mut test);
1256                 ext_from_hex("ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", &mut test);
1257                 // inbound read from peer id 0 of len 255
1258                 ext_from_hex("0300ff", &mut test);
1259                 ext_from_hex("ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", &mut test);
1260                 // inbound read from peer id 0 of len 255
1261                 ext_from_hex("0300ff", &mut test);
1262                 ext_from_hex("ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", &mut test);
1263                 // inbound read from peer id 0 of len 193
1264                 ext_from_hex("0300c1", &mut test);
1265                 // end of update_add_htlc from 0 to 1 via client and mac
1266                 ext_from_hex("ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff 5300000000000000000000000000000000000000000000000000000000000000 03000000000000000000000000000000", &mut test);
1267
1268                 // Two feerate requests to check dust exposure
1269                 ext_from_hex("00fd00fd", &mut test);
1270
1271                 // inbound read from peer id 0 of len 18
1272                 ext_from_hex("030012", &mut test);
1273                 // message header indicating message length 164
1274                 ext_from_hex("00a4 03000000000000000000000000000000", &mut test);
1275                 // inbound read from peer id 0 of len 180
1276                 ext_from_hex("0300b4", &mut test);
1277                 // commitment_signed and mac
1278                 ext_from_hex("0084 3d00000000000000000000000000000000000000000000000000000000000000 00000000000000000000000000000000000000000000000000000000000000750100000000000000000000000000000000000000000000000000000000000000 0001 00000000000000000000000000000000000000000000000000000000000000670500000000000000000000000000000000000000000000000000000000000006 03000000000000000000000000000000", &mut test);
1279                 // client should now respond with revoke_and_ack and commitment_signed (CHECK 5/6 duplicates)
1280
1281                 // inbound read from peer id 0 of len 18
1282                 ext_from_hex("030012", &mut test);
1283                 // message header indicating message length 99
1284                 ext_from_hex("0063 03000000000000000000000000000000", &mut test);
1285                 // inbound read from peer id 0 of len 115
1286                 ext_from_hex("030073", &mut test);
1287                 // revoke_and_ack and mac
1288                 ext_from_hex("0085 3d00000000000000000000000000000000000000000000000000000000000000 0d00000000000000000000000000000000000000000000000000000000000000 020f00000000000000000000000000000000000000000000000000000000000000 03000000000000000000000000000000", &mut test);
1289
1290                 // process the now-pending HTLC forward
1291                 ext_from_hex("07", &mut test);
1292                 // Two feerate requests to check dust exposure
1293                 ext_from_hex("00fd00fd", &mut test);
1294                 // client now sends id 1 update_add_htlc and commitment_signed (CHECK 7 duplicate)
1295
1296                 // connect a block with one transaction of len 125
1297                 ext_from_hex("0c007d", &mut test);
1298                 // the commitment transaction for channel 3f00000000000000000000000000000000000000000000000000000000000000
1299                 ext_from_hex("02000000013a000000000000000000000000000000000000000000000000000000000000000000000000000000800258020000000000002200204b0000000000000000000000000000000000000000000000000000000000000014c0000000000000160014280000000000000000000000000000000000000005000020", &mut test);
1300                 //
1301                 // connect a block with one transaction of len 94
1302                 ext_from_hex("0c005e", &mut test);
1303                 // the HTLC timeout transaction
1304                 ext_from_hex("0200000001730000000000000000000000000000000000000000000000000000000000000000000000000000000001a701000000000000220020b20000000000000000000000000000000000000000000000000000000000000000000000", &mut test);
1305                 // connect a block with no transactions
1306                 ext_from_hex("0c0000", &mut test);
1307                 // connect a block with no transactions
1308                 ext_from_hex("0c0000", &mut test);
1309                 // connect a block with no transactions
1310                 ext_from_hex("0c0000", &mut test);
1311                 // connect a block with no transactions
1312                 ext_from_hex("0c0000", &mut test);
1313                 // connect a block with no transactions
1314                 ext_from_hex("0c0000", &mut test);
1315
1316                 // process the now-pending HTLC forward
1317                 ext_from_hex("07", &mut test);
1318                 // client now fails the HTLC backwards as it was unable to extract the payment preimage (CHECK 9 duplicate and CHECK 10)
1319
1320                 let logger = Arc::new(TrackingLogger { lines: Mutex::new(HashMap::new()) });
1321                 super::do_test(&test, &(Arc::clone(&logger) as Arc<dyn Logger>));
1322
1323                 let log_entries = logger.lines.lock().unwrap();
1324                 assert_eq!(log_entries.get(&("lightning::ln::peer_handler".to_string(), "Handling SendAcceptChannel event in peer_handler for node 030000000000000000000000000000000000000000000000000000000000000002 for channel ff4f00f805273c1b203bb5ebf8436bfde57b3be8c2f5e95d9491dbb181909679".to_string())), Some(&1)); // 1
1325                 assert_eq!(log_entries.get(&("lightning::ln::peer_handler".to_string(), "Handling SendFundingSigned event in peer_handler for node 030000000000000000000000000000000000000000000000000000000000000002 for channel 3d00000000000000000000000000000000000000000000000000000000000000".to_string())), Some(&1)); // 2
1326                 assert_eq!(log_entries.get(&("lightning::ln::peer_handler".to_string(), "Handling SendChannelReady event in peer_handler for node 030000000000000000000000000000000000000000000000000000000000000002 for channel 3d00000000000000000000000000000000000000000000000000000000000000".to_string())), Some(&1)); // 3
1327                 assert_eq!(log_entries.get(&("lightning::ln::peer_handler".to_string(), "Handling SendChannelReady event in peer_handler for node 030200000000000000000000000000000000000000000000000000000000000000 for channel 3a00000000000000000000000000000000000000000000000000000000000000".to_string())), Some(&1)); // 4
1328                 assert_eq!(log_entries.get(&("lightning::ln::peer_handler".to_string(), "Handling SendRevokeAndACK event in peer_handler for node 030000000000000000000000000000000000000000000000000000000000000002 for channel 3d00000000000000000000000000000000000000000000000000000000000000".to_string())), Some(&4)); // 5
1329                 assert_eq!(log_entries.get(&("lightning::ln::peer_handler".to_string(), "Handling UpdateHTLCs event in peer_handler for node 030000000000000000000000000000000000000000000000000000000000000002 with 0 adds, 0 fulfills, 0 fails for channel 3d00000000000000000000000000000000000000000000000000000000000000".to_string())), Some(&3)); // 6
1330                 assert_eq!(log_entries.get(&("lightning::ln::peer_handler".to_string(), "Handling UpdateHTLCs event in peer_handler for node 030200000000000000000000000000000000000000000000000000000000000000 with 1 adds, 0 fulfills, 0 fails for channel 3a00000000000000000000000000000000000000000000000000000000000000".to_string())), Some(&3)); // 7
1331                 assert_eq!(log_entries.get(&("lightning::ln::peer_handler".to_string(), "Handling UpdateHTLCs event in peer_handler for node 030000000000000000000000000000000000000000000000000000000000000002 with 0 adds, 1 fulfills, 0 fails for channel 3d00000000000000000000000000000000000000000000000000000000000000".to_string())), Some(&1)); // 8
1332                 assert_eq!(log_entries.get(&("lightning::ln::peer_handler".to_string(), "Handling UpdateHTLCs event in peer_handler for node 030000000000000000000000000000000000000000000000000000000000000002 with 0 adds, 0 fulfills, 1 fails for channel 3d00000000000000000000000000000000000000000000000000000000000000".to_string())), Some(&2)); // 9
1333                 assert_eq!(log_entries.get(&("lightning::chain::channelmonitor".to_string(), "Input spending counterparty commitment tx (0000000000000000000000000000000000000000000000000000000000000073:0) in 0000000000000000000000000000000000000000000000000000000000000067 resolves outbound HTLC with payment hash ff00000000000000000000000000000000000000000000000000000000000000 with timeout".to_string())), Some(&1)); // 10
1334         }
1335
1336         #[test]
1337         fn test_gossip_exchange_breakage() {
1338                 // To avoid accidentally causing all existing fuzz test cases to be useless by making minor
1339                 // changes (such as requesting feerate info in a new place), we exchange some gossip
1340                 // messages. Obviously this is pretty finicky, so this should be updated pretty liberally,
1341                 // but at least we'll know when changes occur.
1342                 // This test serves as a pretty good full_stack_target seed.
1343
1344                 // What each byte represents is broken down below, and then everything is concatenated into
1345                 // one large test at the end (you want %s/ -.*//g %s/\n\| \|\t\|\///g).
1346
1347                 // Following BOLT 8, lightning message on the wire are: 2-byte encrypted message length +
1348                 // 16-byte MAC of the encrypted message length + encrypted Lightning message + 16-byte MAC
1349                 // of the Lightning message
1350                 // I.e 2nd inbound read, len 18 : 0006 (encrypted message length) + 03000000000000000000000000000000 (MAC of the encrypted message length)
1351                 // Len 22 : 0010 00000000 (encrypted lightning message) + 03000000000000000000000000000000 (MAC of the Lightning message)
1352
1353                 // Writing new code generating transactions and see a new failure ? Don't forget to add input for the FuzzEstimator !
1354
1355                 let mut test = Vec::new();
1356
1357                 // our network key
1358                 ext_from_hex("0100000000000000000000000000000000000000000000000000000000000000", &mut test);
1359                 // config
1360                 ext_from_hex("0000000000900000000000000000640001000000000001ffff0000000000000000ffffffffffffffffffffffffffffffff0000000000000000ffffffffffffffff000000ffffffff00ffff1a000400010000020400000000040200000a08ffffffffffffffff0001000000", &mut test);
1361
1362                 // new outbound connection with id 0
1363                 ext_from_hex("00", &mut test);
1364                 // peer's pubkey
1365                 ext_from_hex("030000000000000000000000000000000000000000000000000000000000000002", &mut test);
1366                 // inbound read from peer id 0 of len 50
1367                 ext_from_hex("030032", &mut test);
1368                 // noise act two (0||pubkey||mac)
1369                 ext_from_hex("00 030000000000000000000000000000000000000000000000000000000000000002 03000000000000000000000000000000", &mut test);
1370
1371                 // inbound read from peer id 0 of len 18
1372                 ext_from_hex("030012", &mut test);
1373                 // message header indicating message length 16
1374                 ext_from_hex("0010 03000000000000000000000000000000", &mut test);
1375                 // inbound read from peer id 0 of len 32
1376                 ext_from_hex("030020", &mut test);
1377                 // init message (type 16) with static_remotekey required, no channel_type/anchors/taproot, and other bits optional and mac
1378                 ext_from_hex("0010 00021aaa 0008aaa20aaa2a0a9aaa 03000000000000000000000000000000", &mut test);
1379
1380                 // new inbound connection with id 1
1381                 ext_from_hex("01", &mut test);
1382                 // inbound read from peer id 1 of len 50
1383                 ext_from_hex("030132", &mut test);
1384                 // inbound noise act 1
1385                 ext_from_hex("0003000000000000000000000000000000000000000000000000000000000000000703000000000000000000000000000000", &mut test);
1386                 // inbound read from peer id 1 of len 66
1387                 ext_from_hex("030142", &mut test);
1388                 // inbound noise act 3
1389                 ext_from_hex("000302000000000000000000000000000000000000000000000000000000000000000300000000000000000000000000000003000000000000000000000000000000", &mut test);
1390
1391                 // inbound read from peer id 1 of len 18
1392                 ext_from_hex("030112", &mut test);
1393                 // message header indicating message length 16
1394                 ext_from_hex("0010 01000000000000000000000000000000", &mut test);
1395                 // inbound read from peer id 1 of len 32
1396                 ext_from_hex("030120", &mut test);
1397                 // init message (type 16) with static_remotekey required, no channel_type/anchors/taproot, and other bits optional and mac
1398                 ext_from_hex("0010 00021aaa 0008aaa20aaa2a0a9aaa 01000000000000000000000000000000", &mut test);
1399
1400                 // inbound read from peer id 0 of len 18
1401                 ext_from_hex("030012", &mut test);
1402                 // message header indicating message length 432
1403                 ext_from_hex("01b0 03000000000000000000000000000000", &mut test);
1404                 // inbound read from peer id 0 of len 255
1405                 ext_from_hex("0300ff", &mut test);
1406                 // First part of channel_announcement (type 256)
1407                 ext_from_hex("0100 00000000000000000000000000000000000000000000000000000000000000b20303030303030303030303030303030303030303030303030303030303030303 00000000000000000000000000000000000000000000000000000000000000b20202020202020202020202020202020202020202020202020202020202020202 00000000000000000000000000000000000000000000000000000000000000b20303030303030303030303030303030303030303030303030303030303030303 00000000000000000000000000000000000000000000000000000000000000b20202020202020202020202020202020202020202020202020202020202", &mut test);
1408                 // inbound read from peer id 0 of len 193
1409                 ext_from_hex("0300c1", &mut test);
1410                 // Last part of channel_announcement and mac
1411                 ext_from_hex("020202 00006fe28c0ab6f1b372c1a6a246ae63f74f931e8365e15a089c68d6190000000000000000000000002a030303030303030303030303030303030303030303030303030303030303030303020202020202020202020202020202020202020202020202020202020202020202030303030303030303030303030303030303030303030303030303030303030303020202020202020202020202020202020202020202020202020202020202020202 03000000000000000000000000000000", &mut test);
1412
1413                 // inbound read from peer id 0 of len 18
1414                 ext_from_hex("030012", &mut test);
1415                 // message header indicating message length 138
1416                 ext_from_hex("008a 03000000000000000000000000000000", &mut test);
1417                 // inbound read from peer id 0 of len 154
1418                 ext_from_hex("03009a", &mut test);
1419                 // channel_update (type 258) and mac
1420                 ext_from_hex("0102 00000000000000000000000000000000000000000000000000000000000000a60303030303030303030303030303030303030303030303030303030303030303 6fe28c0ab6f1b372c1a6a246ae63f74f931e8365e15a089c68d6190000000000 000000000000002a0000002c01000028000000000000000000000000000000000000000005f5e100 03000000000000000000000000000000", &mut test);
1421
1422                 // inbound read from peer id 0 of len 18
1423                 ext_from_hex("030012", &mut test);
1424                 // message header indicating message length 142
1425                 ext_from_hex("008e 03000000000000000000000000000000", &mut test);
1426                 // inbound read from peer id 0 of len 158
1427                 ext_from_hex("03009e", &mut test);
1428                 // node_announcement (type 257) and mac
1429                 ext_from_hex("0101 00000000000000000000000000000000000000000000000000000000000000280303030303030303030303030303030303030303030303030303030303030303 00000000002b03030303030303030303030303030303030303030303030303030303030303030300000000000000000000000000000000000000000000000000000000000000000000000000 03000000000000000000000000000000", &mut test);
1430
1431                 let logger = Arc::new(TrackingLogger { lines: Mutex::new(HashMap::new()) });
1432                 super::do_test(&test, &(Arc::clone(&logger) as Arc<dyn Logger>));
1433
1434                 let log_entries = logger.lines.lock().unwrap();
1435                 assert_eq!(log_entries.get(&("lightning::ln::peer_handler".to_string(), "Sending message to all peers except Some(PublicKey(0000000000000000000000000000000000000000000000000000000000000002ff00000000000000000000000000000000000000000000000000000000000002)) or the announced channel's counterparties: ChannelAnnouncement { node_signature_1: 3026020200b202200303030303030303030303030303030303030303030303030303030303030303, node_signature_2: 3026020200b202200202020202020202020202020202020202020202020202020202020202020202, bitcoin_signature_1: 3026020200b202200303030303030303030303030303030303030303030303030303030303030303, bitcoin_signature_2: 3026020200b202200202020202020202020202020202020202020202020202020202020202020202, contents: UnsignedChannelAnnouncement { features: [], chain_hash: 6fe28c0ab6f1b372c1a6a246ae63f74f931e8365e15a089c68d6190000000000, short_channel_id: 42, node_id_1: NodeId(030303030303030303030303030303030303030303030303030303030303030303), node_id_2: NodeId(020202020202020202020202020202020202020202020202020202020202020202), bitcoin_key_1: NodeId(030303030303030303030303030303030303030303030303030303030303030303), bitcoin_key_2: NodeId(020202020202020202020202020202020202020202020202020202020202020202), excess_data: [] } }".to_string())), Some(&1));
1436                 assert_eq!(log_entries.get(&("lightning::ln::peer_handler".to_string(), "Sending message to all peers except Some(PublicKey(0000000000000000000000000000000000000000000000000000000000000002ff00000000000000000000000000000000000000000000000000000000000002)): ChannelUpdate { signature: 3026020200a602200303030303030303030303030303030303030303030303030303030303030303, contents: UnsignedChannelUpdate { chain_hash: 6fe28c0ab6f1b372c1a6a246ae63f74f931e8365e15a089c68d6190000000000, short_channel_id: 42, timestamp: 44, flags: 0, cltv_expiry_delta: 40, htlc_minimum_msat: 0, htlc_maximum_msat: 100000000, fee_base_msat: 0, fee_proportional_millionths: 0, excess_data: [] } }".to_string())), Some(&1));
1437                 assert_eq!(log_entries.get(&("lightning::ln::peer_handler".to_string(), "Sending message to all peers except Some(PublicKey(0000000000000000000000000000000000000000000000000000000000000002ff00000000000000000000000000000000000000000000000000000000000002)) or the announced node: NodeAnnouncement { signature: 302502012802200303030303030303030303030303030303030303030303030303030303030303, contents: UnsignedNodeAnnouncement { features: [], timestamp: 43, node_id: NodeId(030303030303030303030303030303030303030303030303030303030303030303), rgb: [0, 0, 0], alias: NodeAlias([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]), addresses: [], excess_address_data: [], excess_data: [] } }".to_string())), Some(&1));
1438         }
1439 }