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