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