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