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