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