Skip to main content

reth_eth_wire_types/
broadcast.rs

1//! Types for broadcasting new data.
2
3use crate::{EthMessage, EthVersion, NetworkPrimitives};
4use alloc::{sync::Arc, vec::Vec};
5use alloy_consensus::transaction::TxHashRef;
6use alloy_eips::eip2718::Typed2718;
7use alloy_primitives::{bytes::BufMut, Bytes, TxHash, B128, B256, U128};
8use alloy_rlp::{
9    decode_append, Decodable, Encodable, Header, RlpDecodable, RlpDecodableWrapper, RlpEncodable,
10    RlpEncodableWrapper,
11};
12use core::{fmt::Debug, mem};
13use derive_more::{Deref, DerefMut, IntoIterator};
14use reth_codecs_derive::{add_arbitrary_tests, generate_tests};
15use reth_ethereum_primitives::TransactionSigned;
16use reth_primitives_traits::{sync::OnceLock, Block, InMemorySize, SignedTransaction};
17
18/// Soft limit for the number of hashes in a
19/// [`NewPooledTransactionHashes`] broadcast message.
20///
21/// Spec'd at 4096 hashes.
22///
23/// <https://github.com/ethereum/devp2p/blob/master/caps/eth.md#newpooledtransactionhashes-0x08>
24pub const SOFT_LIMIT_COUNT_HASHES_IN_NEW_POOLED_TRANSACTIONS_BROADCAST_MESSAGE: usize = 4096;
25
26/// Twice the spec'd soft limit for `NewPooledTransactionHashes` announcements.
27///
28/// This caps the initial allocation for the size and hash lists, which grow past it only as their
29/// entries are decoded.
30const NEW_POOLED_TRANSACTION_HASHES_DECODE_CAP: usize =
31    2 * SOFT_LIMIT_COUNT_HASHES_IN_NEW_POOLED_TRANSACTIONS_BROADCAST_MESSAGE;
32
33/// Smallest encoding of one announcement after its type: a one-byte size and an RLP string
34/// holding its hash.
35const MIN_ENCODED_ANNOUNCEMENT_LEN: usize = 1 + 1 + B256::len_bytes();
36
37/// This informs peers of new blocks that have appeared on the network.
38#[derive(
39    Clone,
40    Debug,
41    PartialEq,
42    Eq,
43    RlpEncodableWrapper,
44    RlpDecodableWrapper,
45    Default,
46    Deref,
47    DerefMut,
48    IntoIterator,
49)]
50#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
51#[cfg_attr(any(test, feature = "arbitrary"), derive(arbitrary::Arbitrary))]
52#[add_arbitrary_tests(rlp)]
53pub struct NewBlockHashes(
54    /// New block hashes and the block number for each blockhash.
55    /// Clients should request blocks using a [`GetBlockBodies`](crate::GetBlockBodies) message.
56    pub Vec<BlockHashNumber>,
57);
58
59// === impl NewBlockHashes ===
60
61impl NewBlockHashes {
62    /// Returns the latest block in the list of blocks.
63    pub fn latest(&self) -> Option<&BlockHashNumber> {
64        self.iter().max_by_key(|b| b.number)
65    }
66}
67
68/// A block hash _and_ a block number.
69#[derive(Clone, Debug, PartialEq, Eq, RlpEncodable, RlpDecodable, Default)]
70#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
71#[cfg_attr(any(test, feature = "arbitrary"), derive(arbitrary::Arbitrary))]
72#[add_arbitrary_tests(rlp)]
73pub struct BlockHashNumber {
74    /// The block hash
75    pub hash: B256,
76    /// The block number
77    pub number: u64,
78}
79
80impl From<Vec<BlockHashNumber>> for NewBlockHashes {
81    fn from(v: Vec<BlockHashNumber>) -> Self {
82        Self(v)
83    }
84}
85
86impl From<NewBlockHashes> for Vec<BlockHashNumber> {
87    fn from(v: NewBlockHashes) -> Self {
88        v.0
89    }
90}
91
92/// A trait for block payloads transmitted through p2p.
93pub trait NewBlockPayload:
94    Encodable + Decodable + Clone + Eq + Debug + Send + Sync + Unpin + 'static
95{
96    /// The block type.
97    type Block: Block;
98
99    /// Returns a reference to the block.
100    fn block(&self) -> &Self::Block;
101}
102
103/// A new block with the current total difficulty, which includes the difficulty of the returned
104/// block.
105#[derive(Clone, Debug, PartialEq, Eq, RlpEncodable, RlpDecodable, Default)]
106#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
107#[cfg_attr(any(test, feature = "arbitrary"), derive(arbitrary::Arbitrary))]
108pub struct NewBlock<B = reth_ethereum_primitives::Block> {
109    /// A new block.
110    pub block: B,
111    /// The current total difficulty.
112    pub td: U128,
113}
114
115impl<B: Block + 'static> NewBlockPayload for NewBlock<B> {
116    type Block = B;
117
118    fn block(&self) -> &Self::Block {
119        &self.block
120    }
121}
122
123generate_tests!(#[rlp, 25] NewBlock<reth_ethereum_primitives::Block>, EthNewBlockTests);
124
125/// This informs peers of transactions that have appeared on the network and are not yet included
126/// in a block.
127#[derive(
128    Clone,
129    Debug,
130    PartialEq,
131    Eq,
132    RlpEncodableWrapper,
133    RlpDecodableWrapper,
134    Default,
135    Deref,
136    IntoIterator,
137)]
138#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
139#[cfg_attr(any(test, feature = "arbitrary"), derive(arbitrary::Arbitrary))]
140#[add_arbitrary_tests(rlp, 10)]
141pub struct Transactions<T = TransactionSigned>(
142    /// New transactions for the peer to include in its mempool.
143    pub Vec<T>,
144);
145
146impl<T: SignedTransaction> Transactions<T> {
147    /// Returns `true` if the list of transactions contains any blob transactions.
148    pub fn has_eip4844(&self) -> bool {
149        self.iter().any(|tx| tx.is_eip4844())
150    }
151}
152
153impl<T> From<Vec<T>> for Transactions<T> {
154    fn from(txs: Vec<T>) -> Self {
155        Self(txs)
156    }
157}
158
159impl<T> From<Transactions<T>> for Vec<T> {
160    fn from(txs: Transactions<T>) -> Self {
161        txs.0
162    }
163}
164
165impl<T: Decodable + InMemorySize> Transactions<T> {
166    /// Decodes the RLP list of transactions, stopping once the cumulative
167    /// [`InMemorySize`] of decoded transactions exceeds `memory_budget` bytes.
168    /// Any remaining transactions in the payload are skipped.
169    pub fn decode_with_memory_budget(
170        buf: &mut &[u8],
171        memory_budget: usize,
172    ) -> alloy_rlp::Result<Self> {
173        decode_list_with_memory_budget(buf, memory_budget).map(Self)
174    }
175}
176
177/// Decodes an RLP list, stopping once the cumulative [`InMemorySize`] of decoded items exceeds
178/// `memory_budget` bytes. Any remaining items in the payload are skipped.
179pub fn decode_list_with_memory_budget<T: Decodable + InMemorySize>(
180    buf: &mut &[u8],
181    memory_budget: usize,
182) -> alloy_rlp::Result<Vec<T>> {
183    decode_list_with_memory_budget_by(buf, memory_budget, T::decode)
184}
185
186/// Decodes each item with the version-specific decoder before charging its memory usage.
187pub(crate) fn decode_list_with_memory_budget_by<T: InMemorySize>(
188    buf: &mut &[u8],
189    memory_budget: usize,
190    mut decode: impl FnMut(&mut &[u8]) -> alloy_rlp::Result<T>,
191) -> alloy_rlp::Result<Vec<T>> {
192    let Header { list, payload_length } = Header::decode(buf)?;
193    if !list {
194        return Err(alloy_rlp::Error::UnexpectedString)
195    }
196    // Payload length checked by Header::decode.
197    let (mut payload, rest) = buf.split_at(payload_length);
198
199    let mut txs = Vec::with_capacity(estimated_transaction_list_capacity(payload_length));
200    let mut total_size = 0usize;
201
202    while !payload.is_empty() {
203        let item = decode(&mut payload)?;
204        total_size = total_size.saturating_add(item.size());
205
206        if total_size > memory_budget {
207            break;
208        }
209
210        txs.push(item);
211    }
212
213    *buf = rest;
214    Ok(txs)
215}
216
217// Keep this as a conservative hint: small lists stay allocation-free until the first push, while
218// large untrusted payloads cannot force an outsized preallocation.
219const MIN_TRANSACTION_RLP_SIZE_ESTIMATE: usize = 128;
220const MIN_PREALLOCATED_TRANSACTIONS: usize = 4;
221const MAX_PREALLOCATED_TRANSACTIONS: usize = 1024;
222
223const fn estimated_transaction_list_capacity(payload_length: usize) -> usize {
224    let estimate = payload_length / MIN_TRANSACTION_RLP_SIZE_ESTIMATE;
225    if estimate < MIN_PREALLOCATED_TRANSACTIONS {
226        0
227    } else if estimate > MAX_PREALLOCATED_TRANSACTIONS {
228        MAX_PREALLOCATED_TRANSACTIONS
229    } else {
230        estimate
231    }
232}
233
234/// Same as [`Transactions`] but this is intended as egress message send from local to _many_ peers.
235///
236/// The list of transactions is constructed on per-peers basis, but the underlying transaction
237/// objects are shared.
238#[derive(
239    Clone, Debug, PartialEq, Eq, RlpEncodableWrapper, RlpDecodableWrapper, Deref, IntoIterator,
240)]
241#[cfg_attr(any(test, feature = "arbitrary"), derive(arbitrary::Arbitrary))]
242#[add_arbitrary_tests(rlp, 20)]
243pub struct SharedTransactions<T = TransactionSigned>(
244    /// New transactions for the peer to include in its mempool.
245    pub Vec<Arc<T>>,
246);
247
248/// A transaction that can be lazily encoded for pool-backed outbound propagation.
249pub trait BroadcastPoolTransaction:
250    Encodable + TxHashRef + Typed2718 + Send + Sync + 'static
251{
252}
253
254impl<T> BroadcastPoolTransaction for T where
255    T: Encodable + TxHashRef + Typed2718 + Send + Sync + 'static
256{
257}
258
259/// Shared cached encoding for an outbound transaction.
260///
261/// This keeps the transaction object and its encoded bytes behind shared references so cloned
262/// per-peer messages reuse the same EIP-2718 encoding.
263pub struct LazyEncoded<T: ?Sized> {
264    value: Arc<T>,
265    encoded: Arc<OnceLock<Bytes>>,
266}
267
268impl<T: ?Sized> Clone for LazyEncoded<T> {
269    fn clone(&self) -> Self {
270        Self { value: Arc::clone(&self.value), encoded: Arc::clone(&self.encoded) }
271    }
272}
273
274impl LazyEncoded<dyn BroadcastPoolTransaction> {
275    /// Wraps a transaction-like value and lazily caches its encoded bytes.
276    pub fn new<T>(value: T) -> Self
277    where
278        T: BroadcastPoolTransaction,
279    {
280        let value: Arc<dyn BroadcastPoolTransaction> = Arc::new(value);
281        Self { value, encoded: Arc::new(OnceLock::new()) }
282    }
283}
284
285impl<T: Encodable + ?Sized> Encodable for LazyEncoded<T> {
286    fn encode(&self, out: &mut dyn BufMut) {
287        let encoded = self.encoded.get_or_init(|| self.encode_uncached());
288        out.put_slice(encoded);
289    }
290
291    fn length(&self) -> usize {
292        self.encoded.get_or_init(|| self.encode_uncached()).len()
293    }
294}
295
296impl<T: Encodable + ?Sized> LazyEncoded<T> {
297    fn encode_uncached(&self) -> Bytes {
298        alloy_rlp::encode(&self.value).into()
299    }
300}
301
302impl<T: TxHashRef + ?Sized> TxHashRef for LazyEncoded<T> {
303    fn tx_hash(&self) -> &TxHash {
304        self.value.tx_hash()
305    }
306}
307
308impl<T: Typed2718 + ?Sized> Typed2718 for LazyEncoded<T> {
309    fn ty(&self) -> u8 {
310        self.value.ty()
311    }
312}
313
314impl<T: ?Sized> Debug for LazyEncoded<T> {
315    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
316        f.debug_struct("LazyEncoded")
317            .field("is_cached", &self.encoded.get().is_some())
318            .finish_non_exhaustive()
319    }
320}
321
322/// A lazily encoded transaction used for pool-backed full transaction propagation.
323pub type LazyEncodedTransaction = LazyEncoded<dyn BroadcastPoolTransaction>;
324
325/// Outbound-only full transaction propagation message backed by pool transactions.
326///
327/// This encodes to the same `Transactions` wire payload as [`SharedTransactions`], but is used by
328/// the transaction manager when the source is the pool. Unlike [`SharedTransactions`], it can wrap
329/// pool transaction references directly and cache each transaction's encoded bytes across per-peer
330/// messages. Queued messages retain the pool-backed value and the shared cached bytes until they
331/// are sent.
332#[derive(Clone, Debug, Deref, RlpEncodableWrapper)]
333pub struct BroadcastPoolTransactions(pub Vec<LazyEncodedTransaction>);
334
335impl BroadcastPoolTransactions {
336    /// Returns an iterator over the transaction hashes.
337    pub fn iter_hashes(&self) -> impl Iterator<Item = &TxHash> + '_ {
338        self.0.iter().map(TxHashRef::tx_hash)
339    }
340}
341
342/// A wrapper type for all different new pooled transaction types
343#[derive(Clone, Debug, PartialEq, Eq)]
344#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
345pub enum NewPooledTransactionHashes {
346    /// A list of transaction hashes valid for [66-68)
347    Eth66(NewPooledTransactionHashes66),
348    /// A list of transaction hashes valid for [68-72)
349    ///
350    /// Note: it is assumed that the payload is valid (all vectors have the same length)
351    Eth68(NewPooledTransactionHashes68),
352    /// A list of transaction hashes valid from [72..]
353    ///
354    /// This extends the eth/68 announcement payload with the `cell_mask` field introduced by
355    /// [EIP-8070](https://eips.ethereum.org/EIPS/eip-8070).
356    ///
357    /// Note: it is assumed that the payload is valid (all vectors have the same length)
358    Eth72(NewPooledTransactionHashes72),
359}
360
361// === impl NewPooledTransactionHashes ===
362
363impl NewPooledTransactionHashes {
364    /// Returns the message [`EthVersion`].
365    pub const fn version(&self) -> EthVersion {
366        match self {
367            Self::Eth66(_) => EthVersion::Eth66,
368            Self::Eth68(_) => EthVersion::Eth68,
369            Self::Eth72(_) => EthVersion::Eth72,
370        }
371    }
372
373    /// Returns `true` if the payload is valid for the given version
374    pub const fn is_valid_for_version(&self, version: EthVersion) -> bool {
375        match self {
376            Self::Eth66(_) => {
377                matches!(version, EthVersion::Eth67 | EthVersion::Eth66)
378            }
379            Self::Eth68(_) => {
380                matches!(
381                    version,
382                    EthVersion::Eth68 | EthVersion::Eth69 | EthVersion::Eth70 | EthVersion::Eth71
383                )
384            }
385            Self::Eth72(_) => version.is_eth72_or_newer(),
386        }
387    }
388
389    /// Returns an iterator over all transaction hashes.
390    pub fn iter_hashes(&self) -> impl Iterator<Item = &B256> + '_ {
391        match self {
392            Self::Eth66(msg) => msg.iter(),
393            Self::Eth68(msg) => msg.hashes.iter(),
394            Self::Eth72(msg) => msg.hashes.iter(),
395        }
396    }
397
398    /// Returns an immutable reference to transaction hashes.
399    pub const fn hashes(&self) -> &Vec<B256> {
400        match self {
401            Self::Eth66(msg) => &msg.0,
402            Self::Eth68(msg) => &msg.hashes,
403            Self::Eth72(msg) => &msg.hashes,
404        }
405    }
406
407    /// Returns a mutable reference to transaction hashes.
408    pub const fn hashes_mut(&mut self) -> &mut Vec<B256> {
409        match self {
410            Self::Eth66(msg) => &mut msg.0,
411            Self::Eth68(msg) => &mut msg.hashes,
412            Self::Eth72(msg) => &mut msg.hashes,
413        }
414    }
415
416    /// Consumes the type and returns all hashes
417    pub fn into_hashes(self) -> Vec<B256> {
418        match self {
419            Self::Eth66(msg) => msg.0,
420            Self::Eth68(msg) => msg.hashes,
421            Self::Eth72(msg) => msg.hashes,
422        }
423    }
424
425    /// Returns an iterator over all transaction hashes.
426    pub fn into_iter_hashes(self) -> impl Iterator<Item = B256> {
427        match self {
428            Self::Eth66(msg) => msg.into_iter(),
429            Self::Eth68(msg) => msg.hashes.into_iter(),
430            Self::Eth72(msg) => msg.hashes.into_iter(),
431        }
432    }
433
434    /// Shortens the number of hashes in the message, keeping the first `len` hashes and dropping
435    /// the rest. If `len` is greater than the number of hashes, this has no effect.
436    pub fn truncate(&mut self, len: usize) {
437        match self {
438            Self::Eth66(msg) => msg.truncate(len),
439            Self::Eth68(msg) => {
440                msg.types.truncate(len);
441                msg.sizes.truncate(len);
442                msg.hashes.truncate(len);
443            }
444            Self::Eth72(msg) => {
445                msg.types.truncate(len);
446                msg.sizes.truncate(len);
447                msg.hashes.truncate(len);
448            }
449        }
450    }
451
452    /// Returns true if the message is empty
453    pub const fn is_empty(&self) -> bool {
454        match self {
455            Self::Eth66(msg) => msg.0.is_empty(),
456            Self::Eth68(msg) => msg.hashes.is_empty(),
457            Self::Eth72(msg) => msg.hashes.is_empty(),
458        }
459    }
460
461    /// Returns the number of hashes in the message
462    pub const fn len(&self) -> usize {
463        match self {
464            Self::Eth66(msg) => msg.0.len(),
465            Self::Eth68(msg) => msg.hashes.len(),
466            Self::Eth72(msg) => msg.hashes.len(),
467        }
468    }
469
470    /// Returns an immutable reference to the inner type if this is an eth68 announcement.
471    pub const fn as_eth72(&self) -> Option<&NewPooledTransactionHashes72> {
472        match self {
473            Self::Eth66(_) | Self::Eth68(_) => None,
474            Self::Eth72(msg) => Some(msg),
475        }
476    }
477
478    /// Returns a mutable reference to the inner type if this is an eth68 announcement.
479    pub const fn as_eth72_mut(&mut self) -> Option<&mut NewPooledTransactionHashes72> {
480        match self {
481            Self::Eth66(_) | Self::Eth68(_) => None,
482            Self::Eth72(msg) => Some(msg),
483        }
484    }
485
486    /// Returns an immutable reference to the inner type if this is an eth68 announcement.
487    pub const fn as_eth68(&self) -> Option<&NewPooledTransactionHashes68> {
488        match self {
489            Self::Eth66(_) | Self::Eth72(_) => None,
490            Self::Eth68(msg) => Some(msg),
491        }
492    }
493
494    /// Returns a mutable reference to the inner type if this is an eth68 announcement.
495    pub const fn as_eth68_mut(&mut self) -> Option<&mut NewPooledTransactionHashes68> {
496        match self {
497            Self::Eth66(_) | Self::Eth72(_) => None,
498            Self::Eth68(msg) => Some(msg),
499        }
500    }
501
502    /// Returns a mutable reference to the inner type if this is an eth66 announcement.
503    pub const fn as_eth66_mut(&mut self) -> Option<&mut NewPooledTransactionHashes66> {
504        match self {
505            Self::Eth66(msg) => Some(msg),
506            Self::Eth68(_) | Self::Eth72(_) => None,
507        }
508    }
509
510    /// Returns the inner type if this is an eth68 announcement.
511    pub fn take_eth68(&mut self) -> Option<NewPooledTransactionHashes68> {
512        match self {
513            Self::Eth66(_) | Self::Eth72(_) => None,
514            Self::Eth68(msg) => Some(mem::take(msg)),
515        }
516    }
517
518    /// Returns the inner type if this is an eth66 announcement.
519    pub fn take_eth66(&mut self) -> Option<NewPooledTransactionHashes66> {
520        match self {
521            Self::Eth66(msg) => Some(mem::take(msg)),
522            Self::Eth68(_) | Self::Eth72(_) => None,
523        }
524    }
525}
526
527impl<N: NetworkPrimitives> From<NewPooledTransactionHashes> for EthMessage<N> {
528    fn from(value: NewPooledTransactionHashes) -> Self {
529        match value {
530            NewPooledTransactionHashes::Eth66(msg) => Self::NewPooledTransactionHashes66(msg),
531            NewPooledTransactionHashes::Eth68(msg) => Self::NewPooledTransactionHashes68(msg),
532            NewPooledTransactionHashes::Eth72(msg) => Self::NewPooledTransactionHashes72(msg),
533        }
534    }
535}
536
537impl From<NewPooledTransactionHashes66> for NewPooledTransactionHashes {
538    fn from(hashes: NewPooledTransactionHashes66) -> Self {
539        Self::Eth66(hashes)
540    }
541}
542
543impl From<NewPooledTransactionHashes68> for NewPooledTransactionHashes {
544    fn from(hashes: NewPooledTransactionHashes68) -> Self {
545        Self::Eth68(hashes)
546    }
547}
548
549impl From<NewPooledTransactionHashes72> for NewPooledTransactionHashes {
550    fn from(hashes: NewPooledTransactionHashes72) -> Self {
551        Self::Eth72(hashes)
552    }
553}
554
555/// This informs peers of transaction hashes for transactions that have appeared on the network,
556/// but have not been included in a block.
557#[derive(
558    Clone,
559    Debug,
560    PartialEq,
561    Eq,
562    RlpEncodableWrapper,
563    RlpDecodableWrapper,
564    Default,
565    Deref,
566    DerefMut,
567    IntoIterator,
568)]
569#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
570#[cfg_attr(any(test, feature = "arbitrary"), derive(arbitrary::Arbitrary))]
571#[add_arbitrary_tests(rlp)]
572pub struct NewPooledTransactionHashes66(
573    /// Transaction hashes for new transactions that have appeared on the network.
574    /// Clients should request the transactions with the given hashes using a
575    /// [`GetPooledTransactions`](crate::GetPooledTransactions) message.
576    pub Vec<B256>,
577);
578
579impl NewPooledTransactionHashes66 {
580    /// Returns a new instance with capacity for `capacity` hashes.
581    pub fn with_capacity(capacity: usize) -> Self {
582        Self(Vec::with_capacity(capacity))
583    }
584}
585
586impl From<Vec<B256>> for NewPooledTransactionHashes66 {
587    fn from(v: Vec<B256>) -> Self {
588        Self(v)
589    }
590}
591
592/// Same as [`NewPooledTransactionHashes66`] but extends that beside the transaction hashes,
593/// the node sends the transaction types and their sizes (as defined in EIP-2718) as well.
594#[derive(Clone, Debug, PartialEq, Eq, Default)]
595#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
596pub struct NewPooledTransactionHashes68 {
597    /// Transaction types for new transactions that have appeared on the network.
598    ///
599    /// ## Note on RLP encoding and decoding
600    ///
601    /// In the [eth/68 spec](https://eips.ethereum.org/EIPS/eip-5793#specification) this is defined
602    /// the following way:
603    ///  * `[type_0: B_1, type_1: B_1, ...]`
604    ///
605    /// This would make it seem like the [`Encodable`] and
606    /// [`Decodable`] implementations should directly use a `Vec<u8>` for
607    /// encoding and decoding, because it looks like this field should be encoded as a _list_ of
608    /// bytes.
609    ///
610    /// However, [this is implemented in geth as a `[]byte`
611    /// type](https://github.com/ethereum/go-ethereum/blob/82d934b1dd80cdd8190803ea9f73ed2c345e2576/eth/protocols/eth/protocol.go#L308-L313),
612    /// which [ends up being encoded as a RLP
613    /// string](https://github.com/ethereum/go-ethereum/blob/82d934b1dd80cdd8190803ea9f73ed2c345e2576/rlp/encode_test.go#L171-L176),
614    /// **not** a RLP list.
615    ///
616    /// Because of this, we do not directly use the `Vec<u8>` when encoding and decoding, and
617    /// instead use the [`Encodable`] and [`Decodable`]
618    /// implementations for `&[u8]` instead, which encodes into a RLP string, and expects an RLP
619    /// string when decoding.
620    pub types: Vec<u8>,
621    /// Transaction sizes for new transactions that have appeared on the network.
622    pub sizes: Vec<usize>,
623    /// Transaction hashes for new transactions that have appeared on the network.
624    pub hashes: Vec<B256>,
625}
626
627#[cfg(feature = "arbitrary")]
628impl proptest::prelude::Arbitrary for NewPooledTransactionHashes68 {
629    type Parameters = ();
630    fn arbitrary_with(_args: ()) -> Self::Strategy {
631        use proptest::{collection::vec, prelude::*};
632        // Generate a single random length for all vectors
633        let vec_length = any::<usize>().prop_map(|x| x % 100 + 1); // Lengths between 1 and 100
634
635        vec_length
636            .prop_flat_map(|len| {
637                // Use the generated length to create vectors of TxType, usize, and B256
638                let types_vec = vec(
639                    proptest_arbitrary_interop::arb::<reth_ethereum_primitives::TxType>()
640                        .prop_map(|ty| ty as u8),
641                    len..=len,
642                );
643
644                // Map the usize values to the range 0..131072(0x20000)
645                let sizes_vec = vec(proptest::num::usize::ANY.prop_map(|x| x % 131072), len..=len);
646                let hashes_vec = vec(any::<B256>(), len..=len);
647
648                (types_vec, sizes_vec, hashes_vec)
649            })
650            .prop_map(|(types, sizes, hashes)| Self { types, sizes, hashes })
651            .boxed()
652    }
653
654    type Strategy = proptest::prelude::BoxedStrategy<Self>;
655}
656
657impl NewPooledTransactionHashes68 {
658    /// Returns the number of announced hashes.
659    pub const fn len(&self) -> usize {
660        self.hashes.len()
661    }
662
663    /// Returns whether there are no announced hashes.
664    pub const fn is_empty(&self) -> bool {
665        self.hashes.is_empty()
666    }
667
668    /// Returns a new instance with capacity for `capacity` entries.
669    pub fn with_capacity(capacity: usize) -> Self {
670        Self {
671            types: Vec::with_capacity(capacity),
672            sizes: Vec::with_capacity(capacity),
673            hashes: Vec::with_capacity(capacity),
674        }
675    }
676
677    /// Returns an iterator over tx hashes zipped with corresponding metadata.
678    pub fn metadata_iter(&self) -> impl Iterator<Item = (&B256, (u8, usize))> {
679        self.hashes.iter().zip(self.types.iter().copied().zip(self.sizes.iter().copied()))
680    }
681
682    /// Appends a transaction
683    pub fn push<T: SignedTransaction>(&mut self, tx: &T) {
684        self.hashes.push(*tx.tx_hash());
685        self.sizes.push(tx.encode_2718_len());
686        self.types.push(tx.ty());
687    }
688
689    /// Appends the provided transactions
690    pub fn extend<'a, T: SignedTransaction>(&mut self, txs: impl IntoIterator<Item = &'a T>) {
691        for tx in txs {
692            self.push(tx);
693        }
694    }
695
696    /// Shrinks the capacity of the message vectors as much as possible.
697    pub fn shrink_to_fit(&mut self) {
698        self.hashes.shrink_to_fit();
699        self.sizes.shrink_to_fit();
700        self.types.shrink_to_fit()
701    }
702
703    /// Consumes and appends a transaction
704    pub fn with_transaction<T: SignedTransaction>(mut self, tx: &T) -> Self {
705        self.push(tx);
706        self
707    }
708
709    /// Consumes and appends the provided transactions
710    pub fn with_transactions<'a, T: SignedTransaction>(
711        mut self,
712        txs: impl IntoIterator<Item = &'a T>,
713    ) -> Self {
714        self.extend(txs);
715        self
716    }
717}
718
719impl Encodable for NewPooledTransactionHashes68 {
720    fn encode(&self, out: &mut dyn bytes::BufMut) {
721        #[derive(RlpEncodable)]
722        struct EncodableNewPooledTransactionHashes68<'a> {
723            types: &'a [u8],
724            sizes: &'a Vec<usize>,
725            hashes: &'a Vec<B256>,
726        }
727
728        let encodable = EncodableNewPooledTransactionHashes68 {
729            types: &self.types[..],
730            sizes: &self.sizes,
731            hashes: &self.hashes,
732        };
733
734        encodable.encode(out);
735    }
736    fn length(&self) -> usize {
737        #[derive(RlpEncodable)]
738        struct EncodableNewPooledTransactionHashes68<'a> {
739            types: &'a [u8],
740            sizes: &'a Vec<usize>,
741            hashes: &'a Vec<B256>,
742        }
743
744        let encodable = EncodableNewPooledTransactionHashes68 {
745            types: &self.types[..],
746            sizes: &self.sizes,
747            hashes: &self.hashes,
748        };
749
750        encodable.length()
751    }
752}
753
754impl Decodable for NewPooledTransactionHashes68 {
755    fn decode(buf: &mut &[u8]) -> alloy_rlp::Result<Self> {
756        let Header { list, payload_length } = Header::decode(buf)?;
757        if !list {
758            return Err(alloy_rlp::Error::UnexpectedString)
759        }
760        // Payload length checked by Header::decode.
761        let (mut payload, rest) = buf.split_at(payload_length);
762        let (types, sizes, hashes) = decode_pooled_transaction_hashes_payload(&mut payload)?;
763
764        if !payload.is_empty() {
765            return Err(alloy_rlp::Error::ListLengthMismatch {
766                expected: payload_length,
767                got: payload_length - payload.len(),
768            })
769        }
770
771        ensure_pooled_transaction_hashes_lengths(hashes.len(), types.len(), sizes.len())?;
772
773        *buf = rest;
774        Ok(Self { types, sizes, hashes })
775    }
776}
777
778/// Same as [`NewPooledTransactionHashes68`] but adds the eth/72 `cell_mask` field from
779/// [EIP-8070](https://eips.ethereum.org/EIPS/eip-8070).
780#[derive(Clone, Debug, PartialEq, Eq, Default)]
781#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
782pub struct NewPooledTransactionHashes72 {
783    /// Transaction types for new transactions that have appeared on the network.
784    ///
785    /// ## Note on RLP encoding and decoding
786    ///
787    /// In the [eth/72 spec](https://eips.ethereum.org/EIPS/eip-8070#specification) this is defined
788    /// the following way:
789    ///  * `[types: B, [size_0: P, size_1: P, ...], [hash_0: B_32, hash_1: B_32, ...], cell_mask:
790    ///    B_16]`
791    pub types: Vec<u8>,
792    /// Transaction sizes for new transactions that have appeared on the network.
793    pub sizes: Vec<usize>,
794    /// Transaction hashes for new transactions that have appeared on the network.
795    pub hashes: Vec<B256>,
796    /// Cell availability mask for type 3 (blob) transactions announced by this message.
797    ///
798    /// Per [EIP-8070](https://eips.ethereum.org/EIPS/eip-8070), this is a `B_16`
799    /// bitarray over `CELLS_PER_EXT_BLOB`; bit `i` is set when the announcer has column
800    /// `i` available for every type 3 transaction in the message.
801    ///
802    /// On the wire this field is always encoded as a 16 byte string, zero-filled when no
803    /// type 3 transactions are announced: go-ethereum decodes the mask into a fixed
804    /// `[16]byte` and rejects the RLP `nil` encoding the EIP text describes, so the
805    /// always-present form is the de facto network format. `None` is equivalent to a zero
806    /// mask; decoding additionally accepts the spec's `nil` encoding for compatibility.
807    pub cell_mask: Option<B128>,
808}
809
810#[cfg(feature = "arbitrary")]
811impl proptest::prelude::Arbitrary for NewPooledTransactionHashes72 {
812    type Parameters = ();
813    fn arbitrary_with(_args: ()) -> Self::Strategy {
814        use proptest::{collection::vec, prelude::*};
815        // Generate a single random length for all vectors
816        let vec_length = any::<usize>().prop_map(|x| x % 100 + 1); // Lengths between 1 and 100
817
818        vec_length
819            .prop_flat_map(|len| {
820                // Use the generated length to create vectors of TxType, usize, and B256
821                let types_vec = vec(
822                    proptest_arbitrary_interop::arb::<reth_ethereum_primitives::TxType>()
823                        .prop_map(|ty| ty as u8),
824                    len..=len,
825                );
826
827                // Map the usize values to the range 0..131072(0x20000)
828                let sizes_vec = vec(proptest::num::usize::ANY.prop_map(|x| x % 131072), len..=len);
829                let hashes_vec = vec(any::<B256>(), len..=len);
830                // A zero mask is spelled `None`, so generating `Some(ZERO)` would produce a
831                // value that cannot survive its own encoding.
832                let cell_mask =
833                    any::<Option<B128>>().prop_map(|mask| mask.filter(|mask| !mask.is_zero()));
834
835                (types_vec, sizes_vec, hashes_vec, cell_mask)
836            })
837            .prop_map(|(types, sizes, hashes, cell_mask)| Self { types, sizes, hashes, cell_mask })
838            .boxed()
839    }
840
841    type Strategy = proptest::prelude::BoxedStrategy<Self>;
842}
843
844impl NewPooledTransactionHashes72 {
845    /// Returns the number of announced hashes.
846    pub const fn len(&self) -> usize {
847        self.hashes.len()
848    }
849
850    /// Returns whether there are no announced hashes.
851    pub const fn is_empty(&self) -> bool {
852        self.hashes.is_empty()
853    }
854
855    /// Cell mask advertising availability of every cell.
856    ///
857    /// Used when announcing blob transactions whose full sidecar is available locally, since
858    /// every cell can be computed from the complete blob data.
859    pub const ALL_CELLS_MASK: B128 = B128::repeat_byte(0xff);
860
861    /// Returns a new instance with capacity for `capacity` entries and no cell mask.
862    pub fn with_capacity(capacity: usize) -> Self {
863        Self {
864            types: Vec::with_capacity(capacity),
865            sizes: Vec::with_capacity(capacity),
866            hashes: Vec::with_capacity(capacity),
867            cell_mask: None,
868        }
869    }
870
871    /// Returns an iterator over tx hashes zipped with corresponding metadata.
872    pub fn metadata_iter(&self) -> impl Iterator<Item = (&B256, (u8, usize))> {
873        self.hashes.iter().zip(self.types.iter().copied().zip(self.sizes.iter().copied()))
874    }
875
876    /// Appends a transaction
877    pub fn push<T: SignedTransaction>(&mut self, tx: &T) {
878        self.hashes.push(*tx.tx_hash());
879        self.sizes.push(tx.encode_2718_len());
880        self.types.push(tx.ty());
881        if tx.is_eip4844() {
882            self.cell_mask = Some(Self::ALL_CELLS_MASK);
883        }
884    }
885
886    /// Appends the provided transactions
887    pub fn extend<'a, T: SignedTransaction>(&mut self, txs: impl IntoIterator<Item = &'a T>) {
888        for tx in txs {
889            self.push(tx);
890        }
891    }
892
893    /// Shrinks the capacity of the message vectors as much as possible.
894    pub fn shrink_to_fit(&mut self) {
895        self.hashes.shrink_to_fit();
896        self.sizes.shrink_to_fit();
897        self.types.shrink_to_fit()
898    }
899
900    /// Consumes and appends a transaction
901    pub fn with_transaction<T: SignedTransaction>(mut self, tx: &T) -> Self {
902        self.push(tx);
903        self
904    }
905
906    /// Consumes and appends the provided transactions
907    pub fn with_transactions<'a, T: SignedTransaction>(
908        mut self,
909        txs: impl IntoIterator<Item = &'a T>,
910    ) -> Self {
911        self.extend(txs);
912        self
913    }
914
915    fn payload_length(&self) -> usize {
916        self.types.as_slice().length() +
917            self.sizes.length() +
918            self.hashes.length() +
919            self.cell_mask.unwrap_or_default().length()
920    }
921}
922
923impl Encodable for NewPooledTransactionHashes72 {
924    fn encode(&self, out: &mut dyn bytes::BufMut) {
925        Header { list: true, payload_length: self.payload_length() }.encode(out);
926        self.types.as_slice().encode(out);
927        self.sizes.encode(out);
928        self.hashes.encode(out);
929        // A zero-filled mask when no cells are available, see the `cell_mask` field docs.
930        self.cell_mask.unwrap_or_default().encode(out);
931    }
932
933    fn length(&self) -> usize {
934        Header { list: true, payload_length: self.payload_length() }.length_with_payload()
935    }
936}
937
938impl Decodable for NewPooledTransactionHashes72 {
939    fn decode(buf: &mut &[u8]) -> alloy_rlp::Result<Self> {
940        let Header { list, payload_length } = Header::decode(buf)?;
941        if !list {
942            return Err(alloy_rlp::Error::UnexpectedString)
943        }
944        // Payload length checked by Header::decode.
945        let (mut payload, rest) = buf.split_at(payload_length);
946        let (types, sizes, hashes) = decode_pooled_transaction_hashes_payload(&mut payload)?;
947        let Some(first_byte) = payload.first().copied() else {
948            return Err(alloy_rlp::Error::InputTooShort)
949        };
950        let cell_mask = if first_byte == alloy_rlp::EMPTY_STRING_CODE {
951            // The EIP-8070 `nil` encoding, tolerated for compatibility.
952            payload = &payload[1..];
953            None
954        } else {
955            // A zero mask is the wire representation of "no cells available", see the
956            // `cell_mask` field docs.
957            Some(B128::decode(&mut payload)?).filter(|mask| !mask.is_zero())
958        };
959
960        if !payload.is_empty() {
961            return Err(alloy_rlp::Error::ListLengthMismatch {
962                expected: payload_length,
963                got: payload_length - payload.len(),
964            })
965        }
966
967        ensure_pooled_transaction_hashes_lengths(hashes.len(), types.len(), sizes.len())?;
968
969        *buf = rest;
970        Ok(Self { types, sizes, hashes, cell_mask })
971    }
972}
973
974/// Decodes the `types`, `sizes` and `hashes` fields of a `NewPooledTransactionHashes` payload.
975///
976/// Rejects a payload too short to hold one size and one hash per type, and stops decoding
977/// `sizes` at the first entry beyond the number of types.
978#[inline]
979fn decode_pooled_transaction_hashes_payload(
980    payload: &mut &[u8],
981) -> alloy_rlp::Result<(Vec<u8>, Vec<usize>, Vec<B256>)> {
982    let types = Header::decode_bytes(payload, false)?;
983    if types.len().saturating_mul(MIN_ENCODED_ANNOUNCEMENT_LEN) > payload.len() {
984        return Err(alloy_rlp::Error::InputTooShort)
985    }
986    let capacity = types.len().min(NEW_POOLED_TRANSACTION_HASHES_DECODE_CAP);
987
988    // Each size takes at least one byte on the wire but a `usize` in memory, so decoding stops at
989    // the first extra entry instead of reading a list longer than `types`.
990    let mut sizes = Vec::with_capacity(capacity);
991    let mut sizes_payload = Header::decode_bytes(payload, true)?;
992    while !sizes_payload.is_empty() {
993        if sizes.len() == types.len() {
994            return Err(alloy_rlp::Error::Custom("more sizes than transaction types"))
995        }
996        sizes.push(usize::decode(&mut sizes_payload)?);
997    }
998
999    let mut hashes = Vec::with_capacity(capacity);
1000    decode_append(payload, &mut hashes)?;
1001
1002    Ok((types.to_vec(), sizes, hashes))
1003}
1004
1005#[inline]
1006const fn ensure_pooled_transaction_hashes_lengths(
1007    hashes_len: usize,
1008    types_len: usize,
1009    sizes_len: usize,
1010) -> alloy_rlp::Result<()> {
1011    if hashes_len != types_len {
1012        return Err(alloy_rlp::Error::ListLengthMismatch { expected: hashes_len, got: types_len })
1013    }
1014    if hashes_len != sizes_len {
1015        return Err(alloy_rlp::Error::ListLengthMismatch { expected: hashes_len, got: sizes_len })
1016    }
1017
1018    Ok(())
1019}
1020
1021/// Interface for handling mempool message data. Used in various filters in pipelines in
1022/// `TransactionsManager` and in queries to `TransactionPool`.
1023pub trait HandleMempoolData {
1024    /// The announcement contains no entries.
1025    fn is_empty(&self) -> bool;
1026
1027    /// Returns the number of entries.
1028    fn len(&self) -> usize;
1029
1030    /// Retain only entries for which the hash in the entry satisfies a given predicate.
1031    fn retain_by_hash(&mut self, f: impl FnMut(&TxHash) -> bool);
1032}
1033
1034impl<T: SignedTransaction> HandleMempoolData for Vec<T> {
1035    fn is_empty(&self) -> bool {
1036        self.is_empty()
1037    }
1038
1039    fn len(&self) -> usize {
1040        self.len()
1041    }
1042
1043    fn retain_by_hash(&mut self, mut f: impl FnMut(&TxHash) -> bool) {
1044        self.retain(|tx| f(tx.tx_hash()))
1045    }
1046}
1047
1048/// The earliest block, the latest block and hash of the latest block which can be provided.
1049/// See [BlockRangeUpdate](https://github.com/ethereum/devp2p/blob/master/caps/eth.md#blockrangeupdate-0x11).
1050#[derive(Clone, Debug, PartialEq, Eq, Default, RlpEncodable, RlpDecodable)]
1051#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1052#[cfg_attr(feature = "serde", serde(rename_all = "camelCase"))]
1053pub struct BlockRangeUpdate {
1054    /// The earliest block which is available.
1055    pub earliest: u64,
1056    /// The latest block which is available.
1057    pub latest: u64,
1058    /// Latest available block's hash.
1059    pub latest_hash: B256,
1060}
1061
1062impl InMemorySize for NewPooledTransactionHashes {
1063    fn size(&self) -> usize {
1064        match self {
1065            Self::Eth66(msg) => msg.0.len() * core::mem::size_of::<B256>(),
1066            Self::Eth68(msg) => {
1067                msg.types.len() * core::mem::size_of::<u8>() +
1068                    msg.sizes.len() * core::mem::size_of::<usize>() +
1069                    msg.hashes.len() * core::mem::size_of::<B256>()
1070            }
1071            Self::Eth72(msg) => {
1072                msg.types.len() * core::mem::size_of::<u8>() +
1073                    msg.sizes.len() * core::mem::size_of::<usize>() +
1074                    msg.hashes.len() * core::mem::size_of::<B256>() +
1075                    core::mem::size_of::<B128>()
1076            }
1077        }
1078    }
1079}
1080
1081#[cfg(test)]
1082mod tests {
1083    use super::*;
1084    use alloy_consensus::{transaction::TxHashRef, Typed2718};
1085    use alloy_eips::eip2718::Encodable2718;
1086    use alloy_primitives::{b256, hex, Bytes, Signature, U256};
1087    use alloy_rlp::{RlpDecodable, RlpEncodable};
1088    use proptest::prelude::*;
1089    use reth_ethereum_primitives::{Transaction, TransactionSigned};
1090    use std::str::FromStr;
1091
1092    /// Takes as input a struct / encoded hex message pair, ensuring that we encode to the exact hex
1093    /// message, and decode to the exact struct.
1094    fn test_encoding_vector<T: Encodable + Decodable + PartialEq + core::fmt::Debug>(
1095        input: (T, &[u8]),
1096    ) {
1097        let (expected_decoded, expected_encoded) = input;
1098        let mut encoded = Vec::new();
1099        expected_decoded.encode(&mut encoded);
1100
1101        assert_eq!(hex::encode(&encoded), hex::encode(expected_encoded));
1102
1103        let decoded = T::decode(&mut encoded.as_ref()).unwrap();
1104        assert_eq!(expected_decoded, decoded);
1105    }
1106
1107    fn encoded<T: Encodable>(value: &T) -> Vec<u8> {
1108        let mut out = Vec::new();
1109        value.encode(&mut out);
1110        out
1111    }
1112
1113    #[derive(RlpEncodable, RlpDecodable)]
1114    struct EncodableNewPooledTransactionHashes68 {
1115        types: Bytes,
1116        sizes: Vec<usize>,
1117        hashes: Vec<B256>,
1118    }
1119
1120    type NewPooledTransactionHashes68Fields = (Vec<u8>, Vec<usize>, Vec<B256>);
1121
1122    fn decode_eth68_hashes_derived(
1123        buf: &mut &[u8],
1124    ) -> alloy_rlp::Result<NewPooledTransactionHashes68> {
1125        let encodable = EncodableNewPooledTransactionHashes68::decode(buf)?;
1126        let msg = NewPooledTransactionHashes68 {
1127            types: encodable.types.into(),
1128            sizes: encodable.sizes,
1129            hashes: encodable.hashes,
1130        };
1131
1132        ensure_pooled_transaction_hashes_lengths(
1133            msg.hashes.len(),
1134            msg.types.len(),
1135            msg.sizes.len(),
1136        )?;
1137
1138        Ok(msg)
1139    }
1140
1141    fn eth68_hash_fields_strategy() -> impl Strategy<Value = NewPooledTransactionHashes68Fields> {
1142        // Independent lengths almost never match, so half the cases share one length.
1143        prop_oneof![
1144            (0usize..128).prop_map(|len| (len, len, len)),
1145            (0usize..128, 0usize..128, 0usize..128),
1146        ]
1147        .prop_flat_map(|(types_len, sizes_len, hashes_len)| {
1148            (
1149                proptest::collection::vec(any::<u8>(), types_len),
1150                proptest::collection::vec(0usize..131_072, sizes_len),
1151                proptest::collection::vec(any::<B256>(), hashes_len),
1152            )
1153        })
1154    }
1155
1156    proptest! {
1157        #[test]
1158        fn broadcast_pool_transactions_match_shared_transactions_encoding(
1159            txs in proptest::collection::vec(
1160                proptest_arbitrary_interop::arb::<TransactionSigned>(),
1161                0..32,
1162            )
1163        ) {
1164            let shared = SharedTransactions::<TransactionSigned>(
1165                txs.iter().cloned().map(Arc::new).collect(),
1166            );
1167            let broadcast = BroadcastPoolTransactions(
1168                txs.iter().cloned().map(LazyEncoded::new).collect(),
1169            );
1170
1171            prop_assert_eq!(broadcast.length(), shared.length());
1172
1173            let shared_encoded = encoded(&shared);
1174            let broadcast_encoded = encoded(&broadcast);
1175            prop_assert_eq!(&broadcast_encoded, &shared_encoded);
1176
1177            let broadcast_encoded_cached = encoded(&broadcast);
1178            prop_assert_eq!(&broadcast_encoded_cached, &shared_encoded);
1179
1180            let mut shared_bytes = shared_encoded.as_slice();
1181            let decoded_shared = SharedTransactions::<TransactionSigned>::decode(&mut shared_bytes)
1182                .expect("shared transactions decode");
1183            prop_assert!(shared_bytes.is_empty());
1184
1185            let mut broadcast_bytes = broadcast_encoded.as_slice();
1186            let decoded_broadcast =
1187                SharedTransactions::<TransactionSigned>::decode(&mut broadcast_bytes)
1188                    .expect("broadcast pool transactions decode as shared transactions");
1189            prop_assert!(broadcast_bytes.is_empty());
1190
1191            prop_assert_eq!(decoded_broadcast, decoded_shared);
1192        }
1193
1194        #[test]
1195        fn eth_68_handrolled_decode_matches_derived_implementation(
1196            (types, sizes, hashes) in eth68_hash_fields_strategy()
1197        ) {
1198            let lengths_match = types.len() == sizes.len() && sizes.len() == hashes.len();
1199            let encodable = EncodableNewPooledTransactionHashes68 {
1200                types: Bytes::from(types),
1201                sizes,
1202                hashes,
1203            };
1204            let encoded = encoded(&encodable);
1205
1206            let mut derived_buf = encoded.as_slice();
1207            let derived = decode_eth68_hashes_derived(&mut derived_buf);
1208
1209            let mut handrolled_buf = encoded.as_slice();
1210            let handrolled = NewPooledTransactionHashes68::decode(&mut handrolled_buf);
1211
1212            // The hand-rolled decoder stops early on malformed lengths, so only success must match.
1213            prop_assert_eq!(handrolled.as_ref().ok(), derived.as_ref().ok());
1214            prop_assert_eq!(handrolled.is_ok(), lengths_match);
1215            if handrolled.is_ok() {
1216                prop_assert!(derived_buf.is_empty());
1217                prop_assert!(handrolled_buf.is_empty());
1218            }
1219        }
1220    }
1221
1222    #[test]
1223    fn can_return_latest_block() {
1224        let mut blocks = NewBlockHashes(vec![BlockHashNumber { hash: B256::random(), number: 0 }]);
1225        let latest = blocks.latest().unwrap();
1226        assert_eq!(latest.number, 0);
1227
1228        blocks.push(BlockHashNumber { hash: B256::random(), number: 100 });
1229        blocks.push(BlockHashNumber { hash: B256::random(), number: 2 });
1230        let latest = blocks.latest().unwrap();
1231        assert_eq!(latest.number, 100);
1232    }
1233
1234    #[test]
1235    fn eth_68_tx_hash_roundtrip() {
1236        let vectors = vec![
1237            (
1238                NewPooledTransactionHashes68 { types: vec![], sizes: vec![], hashes: vec![] },
1239                &hex!("c380c0c0")[..],
1240            ),
1241            (
1242                NewPooledTransactionHashes68 {
1243                    types: vec![0x00],
1244                    sizes: vec![0x00],
1245                    hashes: vec![
1246                        B256::ZERO,
1247                    ],
1248                },
1249                &hex!(
1250                    "e500c180e1a00000000000000000000000000000000000000000000000000000000000000000"
1251                )[..],
1252            ),
1253            (
1254                NewPooledTransactionHashes68 {
1255                    types: vec![0x00, 0x00],
1256                    sizes: vec![0x00, 0x00],
1257                    hashes: vec![
1258                        B256::ZERO,
1259                        B256::ZERO,
1260                    ],
1261                },
1262                &hex!(
1263                    "f84a820000c28080f842a00000000000000000000000000000000000000000000000000000000000000000a00000000000000000000000000000000000000000000000000000000000000000"
1264                )[..],
1265            ),
1266            (
1267                NewPooledTransactionHashes68 {
1268                    types: vec![0x02],
1269                    sizes: vec![0xb6],
1270                    hashes: vec![
1271                        b256!("0xfecbed04c7b88d8e7221a0a3f5dc33f220212347fc167459ea5cc9c3eb4c1124"),
1272                    ],
1273                },
1274                &hex!(
1275                    "e602c281b6e1a0fecbed04c7b88d8e7221a0a3f5dc33f220212347fc167459ea5cc9c3eb4c1124"
1276                )[..],
1277            ),
1278            (
1279                NewPooledTransactionHashes68 {
1280                    types: vec![0xff, 0xff],
1281                    sizes: vec![0xffffffff, 0xffffffff],
1282                    hashes: vec![
1283                        B256::repeat_byte(0xff),
1284                        B256::repeat_byte(0xff),
1285                    ],
1286                },
1287                &hex!(
1288                    "f85282ffffca84ffffffff84fffffffff842a0ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffa0ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"
1289                )[..],
1290            ),
1291            (
1292                NewPooledTransactionHashes68 {
1293                    types: vec![0xff, 0xff],
1294                    sizes: vec![0xffffffff, 0xffffffff],
1295                    hashes: vec![
1296                        b256!("0xbeefcafebeefcafebeefcafebeefcafebeefcafebeefcafebeefcafebeefcafe"),
1297                        b256!("0xbeefcafebeefcafebeefcafebeefcafebeefcafebeefcafebeefcafebeefcafe"),
1298                    ],
1299                },
1300                &hex!(
1301                    "f85282ffffca84ffffffff84fffffffff842a0beefcafebeefcafebeefcafebeefcafebeefcafebeefcafebeefcafebeefcafea0beefcafebeefcafebeefcafebeefcafebeefcafebeefcafebeefcafebeefcafe"
1302                )[..],
1303            ),
1304            (
1305                NewPooledTransactionHashes68 {
1306                    types: vec![0x10, 0x10],
1307                    sizes: vec![0xdeadc0de, 0xdeadc0de],
1308                    hashes: vec![
1309                        b256!("0x3b9aca00f0671c9a2a1b817a0a78d3fe0c0f776cccb2a8c3c1b412a4f4e4d4e2"),
1310                        b256!("0x3b9aca00f0671c9a2a1b817a0a78d3fe0c0f776cccb2a8c3c1b412a4f4e4d4e2"),
1311                    ],
1312                },
1313                &hex!(
1314                    "f852821010ca84deadc0de84deadc0def842a03b9aca00f0671c9a2a1b817a0a78d3fe0c0f776cccb2a8c3c1b412a4f4e4d4e2a03b9aca00f0671c9a2a1b817a0a78d3fe0c0f776cccb2a8c3c1b412a4f4e4d4e2"
1315                )[..],
1316            ),
1317            (
1318                NewPooledTransactionHashes68 {
1319                    types: vec![0x6f, 0x6f],
1320                    sizes: vec![0x7fffffff, 0x7fffffff],
1321                    hashes: vec![
1322                        B256::with_last_byte(2),
1323                        B256::with_last_byte(2),
1324                    ],
1325                },
1326                &hex!(
1327                    "f852826f6fca847fffffff847ffffffff842a00000000000000000000000000000000000000000000000000000000000000002a00000000000000000000000000000000000000000000000000000000000000002"
1328                )[..],
1329            ),
1330        ];
1331
1332        for vector in vectors {
1333            test_encoding_vector(vector);
1334        }
1335    }
1336
1337    #[test]
1338    fn eth_72_zero_cell_mask_decodes_as_none() {
1339        // The wire cannot tell a zero mask from an absent one, so `None` is the only
1340        // representation that survives a round trip.
1341        let zero = NewPooledTransactionHashes72 {
1342            types: vec![],
1343            sizes: vec![],
1344            hashes: vec![],
1345            cell_mask: Some(B128::ZERO),
1346        };
1347
1348        let mut encoded = Vec::new();
1349        zero.encode(&mut encoded);
1350
1351        let decoded = NewPooledTransactionHashes72::decode(&mut &encoded[..]).unwrap();
1352
1353        assert_eq!(decoded.cell_mask, None);
1354        assert_eq!(encoded, hex!("d480c0c09000000000000000000000000000000000"));
1355    }
1356
1357    #[test]
1358    fn eth_72_tx_hash_roundtrip() {
1359        let vectors = vec![
1360            // `None` is always encoded as a zero-filled 16 byte mask, matching go-ethereum's
1361            // non-optional `[16]byte` field.
1362            (
1363                NewPooledTransactionHashes72 {
1364                    types: vec![],
1365                    sizes: vec![],
1366                    hashes: vec![],
1367                    cell_mask: None,
1368                },
1369                &hex!("d480c0c09000000000000000000000000000000000")[..],
1370            ),
1371            (
1372                NewPooledTransactionHashes72 {
1373                    types: vec![],
1374                    sizes: vec![],
1375                    hashes: vec![],
1376                    cell_mask: Some(B128::repeat_byte(0x11)),
1377                },
1378                &hex!("d480c0c09011111111111111111111111111111111")[..],
1379            ),
1380        ];
1381
1382        for vector in vectors {
1383            test_encoding_vector(vector);
1384        }
1385    }
1386
1387    #[test]
1388    fn eth_72_decodes_spec_nil_cell_mask() {
1389        // The EIP-8070 text encodes an absent mask as the RLP empty string; decoding stays
1390        // lenient even though reth never produces this form.
1391        let encoded = hex!("c480c0c080");
1392
1393        let decoded = NewPooledTransactionHashes72::decode(&mut encoded.as_ref()).unwrap();
1394
1395        assert_eq!(decoded.cell_mask, None);
1396    }
1397
1398    #[test]
1399    fn eth_72_rejects_missing_cell_mask() {
1400        let encoded_eth68_payload = hex!("c380c0c0");
1401
1402        let result = NewPooledTransactionHashes72::decode(&mut encoded_eth68_payload.as_ref());
1403
1404        assert!(matches!(result, Err(alloy_rlp::Error::InputTooShort)));
1405    }
1406
1407    fn signed_transaction() -> impl SignedTransaction {
1408        TransactionSigned::new_unhashed(
1409            Transaction::Legacy(Default::default()),
1410            Signature::new(
1411                U256::from_str(
1412                    "0x64b1702d9298fee62dfeccc57d322a463ad55ca201256d01f62b45b2e1c21c12",
1413                )
1414                .unwrap(),
1415                U256::from_str(
1416                    "0x64b1702d9298fee62dfeccc57d322a463ad55ca201256d01f62b45b2e1c21c10",
1417                )
1418                .unwrap(),
1419                false,
1420            ),
1421        )
1422    }
1423
1424    #[test]
1425    fn test_pooled_tx_hashes_68_push() {
1426        let tx = signed_transaction();
1427        let mut tx_hashes =
1428            NewPooledTransactionHashes68 { types: vec![], sizes: vec![], hashes: vec![] };
1429        tx_hashes.push(&tx);
1430        assert_eq!(tx_hashes.types.len(), 1);
1431        assert_eq!(tx_hashes.sizes.len(), 1);
1432        assert_eq!(tx_hashes.hashes.len(), 1);
1433        assert_eq!(tx_hashes.types[0], tx.ty());
1434        assert_eq!(tx_hashes.sizes[0], tx.encode_2718_len());
1435        assert_eq!(tx_hashes.hashes[0], *tx.tx_hash());
1436    }
1437
1438    #[test]
1439    fn test_pooled_tx_hashes_68_extend() {
1440        let tx = signed_transaction();
1441        let txs = vec![tx.clone(), tx.clone()];
1442        let mut tx_hashes =
1443            NewPooledTransactionHashes68 { types: vec![], sizes: vec![], hashes: vec![] };
1444        tx_hashes.extend(&txs);
1445        assert_eq!(tx_hashes.types.len(), 2);
1446        assert_eq!(tx_hashes.sizes.len(), 2);
1447        assert_eq!(tx_hashes.hashes.len(), 2);
1448        assert_eq!(tx_hashes.types[0], tx.ty());
1449        assert_eq!(tx_hashes.sizes[0], tx.encode_2718_len());
1450        assert_eq!(tx_hashes.hashes[0], *tx.tx_hash());
1451        assert_eq!(tx_hashes.types[1], tx.ty());
1452        assert_eq!(tx_hashes.sizes[1], tx.encode_2718_len());
1453        assert_eq!(tx_hashes.hashes[1], *tx.tx_hash());
1454    }
1455
1456    #[test]
1457    fn test_pooled_tx_hashes_68_with_transaction() {
1458        let tx = signed_transaction();
1459        let tx_hashes =
1460            NewPooledTransactionHashes68 { types: vec![], sizes: vec![], hashes: vec![] }
1461                .with_transaction(&tx);
1462        assert_eq!(tx_hashes.types.len(), 1);
1463        assert_eq!(tx_hashes.sizes.len(), 1);
1464        assert_eq!(tx_hashes.hashes.len(), 1);
1465        assert_eq!(tx_hashes.types[0], tx.ty());
1466        assert_eq!(tx_hashes.sizes[0], tx.encode_2718_len());
1467        assert_eq!(tx_hashes.hashes[0], *tx.tx_hash());
1468    }
1469
1470    #[test]
1471    fn test_pooled_tx_hashes_68_with_transactions() {
1472        let tx = signed_transaction();
1473        let txs = vec![tx.clone(), tx.clone()];
1474        let tx_hashes =
1475            NewPooledTransactionHashes68 { types: vec![], sizes: vec![], hashes: vec![] }
1476                .with_transactions(&txs);
1477        assert_eq!(tx_hashes.types.len(), 2);
1478        assert_eq!(tx_hashes.sizes.len(), 2);
1479        assert_eq!(tx_hashes.hashes.len(), 2);
1480        assert_eq!(tx_hashes.types[0], tx.ty());
1481        assert_eq!(tx_hashes.sizes[0], tx.encode_2718_len());
1482        assert_eq!(tx_hashes.hashes[0], *tx.tx_hash());
1483        assert_eq!(tx_hashes.types[1], tx.ty());
1484        assert_eq!(tx_hashes.sizes[1], tx.encode_2718_len());
1485        assert_eq!(tx_hashes.hashes[1], *tx.tx_hash());
1486    }
1487
1488    #[test]
1489    fn eth_68_stops_decoding_sizes_beyond_types() {
1490        let encoded = encoded(&EncodableNewPooledTransactionHashes68 {
1491            types: Bytes::from_static(&[0x02]),
1492            sizes: vec![0; 1024],
1493            hashes: vec![B256::ZERO],
1494        });
1495
1496        let result = NewPooledTransactionHashes68::decode(&mut encoded.as_slice());
1497
1498        assert_eq!(result, Err(alloy_rlp::Error::Custom("more sizes than transaction types")));
1499    }
1500
1501    #[test]
1502    fn eth_68_types_need_room_for_sizes_and_hashes() {
1503        let too_short = encoded(&EncodableNewPooledTransactionHashes68 {
1504            types: Bytes::from_static(&[0x02; 4]),
1505            sizes: vec![],
1506            hashes: vec![],
1507        });
1508
1509        let result = NewPooledTransactionHashes68::decode(&mut too_short.as_slice());
1510
1511        assert_eq!(result, Err(alloy_rlp::Error::InputTooShort));
1512
1513        // One-byte sizes leave the smallest room per entry that a valid announcement can have.
1514        let eth68 = NewPooledTransactionHashes68 {
1515            types: vec![0x02; 8],
1516            sizes: vec![0; 8],
1517            hashes: vec![B256::ZERO; 8],
1518        };
1519        let decoded = NewPooledTransactionHashes68::decode(&mut encoded(&eth68).as_slice());
1520        assert_eq!(decoded, Ok(eth68.clone()));
1521
1522        let eth72 = NewPooledTransactionHashes72 {
1523            types: eth68.types,
1524            sizes: eth68.sizes,
1525            hashes: eth68.hashes,
1526            cell_mask: None,
1527        };
1528        let decoded = NewPooledTransactionHashes72::decode(&mut encoded(&eth72).as_slice());
1529        assert_eq!(decoded, Ok(eth72));
1530    }
1531}