Skip to main content

reth_eth_wire_types/
cells.rs

1//! Shared (EIP-8070) and indexed (EIP-8408) cell retrieval messages.
2//!
3//! Payload codecs are flattened: `RequestPair` supplies the outer RLP list and request id.
4
5use alloc::vec::Vec;
6use alloy_eips::eip7594::{BlobCellMask, Cell};
7use alloy_primitives::{map::B256Map, Bytes, B128, B256};
8use alloy_rlp::{BufMut, Decodable, Encodable, Error, Header};
9use reth_primitives_traits::InMemorySize;
10
11#[cfg(feature = "serde")]
12use core::fmt;
13#[cfg(feature = "serde")]
14use serde::{
15    de::{
16        value::{SeqAccessDeserializer, StrDeserializer},
17        SeqAccess, Visitor,
18    },
19    Deserialize, Deserializer, Serialize, Serializer,
20};
21
22/// Mandatory transaction count bound for indexed cell messages (EIP-8408).
23pub const MAX_INDEXED_CELL_HASHES: usize = 64;
24
25/// Mandatory mask table bound for indexed cell messages (EIP-8408).
26pub const MAX_INDEXED_CELL_MASKS: usize = 64;
27
28#[cfg(feature = "serde")]
29const MAX_SERIALIZED_CELL_MASK_BYTES: usize =
30    Header { list: true, payload_length: MAX_INDEXED_CELL_MASKS * (B128::len_bytes() + 1) }
31        .length_with_payload() +
32        Header { list: false, payload_length: MAX_INDEXED_CELL_HASHES }.length_with_payload();
33
34/// Cell indices shared by all transactions or selected through a canonical mask table.
35/// Serde preserves the `B128` representation for shared masks. Indexed masks serialize as
36/// their RLP field sequence in a hex string (or bytes for binary formats).
37#[derive(Clone, Debug, PartialEq, Eq)]
38pub enum CellMasks {
39    /// The eth/72 form, also accepted on eth/73 without indexed-form limits.
40    Shared(B128),
41    /// The eth/73 form. Masks must be unique, referenced, and ordered by first use.
42    Indexed {
43        /// At most 64 masks. Requests need at least two; empty responses use none.
44        masks: Vec<B128>,
45        /// One byte per transaction hash, indexing `masks`.
46        mask_ids: Bytes,
47    },
48}
49
50impl CellMasks {
51    /// Returns whether this uses the eth/73 indexed form.
52    pub const fn is_indexed(&self) -> bool {
53        matches!(self, Self::Indexed { .. })
54    }
55
56    /// Returns the shared mask or the mask at an indexed transaction position.
57    /// Returns `None` if an indexed identifier or table entry is missing.
58    pub fn mask_at(&self, index: usize) -> Option<B128> {
59        match self {
60            Self::Shared(mask) => Some(*mask),
61            Self::Indexed { masks, mask_ids } => masks.get(*mask_ids.get(index)? as usize).copied(),
62        }
63    }
64
65    /// Validates the indexed bounds, uniqueness, and first-reference ordering.
66    /// Shared forms retain eth/72 semantics. Only responses may use an empty indexed table
67    /// or an indexed table with a single mask.
68    pub fn validate(&self, hashes: &[B256], response: bool) -> alloy_rlp::Result<()> {
69        let Self::Indexed { masks, mask_ids } = self else { return Ok(()) };
70        if hashes.len() > MAX_INDEXED_CELL_HASHES ||
71            masks.len() > MAX_INDEXED_CELL_MASKS ||
72            mask_ids.len() != hashes.len() ||
73            (!response && hashes.is_empty()) ||
74            (hashes.is_empty() != masks.is_empty())
75        {
76            return Err(Error::Custom("invalid indexed cell counts"))
77        }
78        let mut next = 0;
79        for &id in mask_ids {
80            let id = usize::from(id);
81            if id >= masks.len() || id > next {
82                return Err(Error::Custom("invalid cell mask identifier order"))
83            }
84            if id == next {
85                next += 1;
86            }
87        }
88        if next != masks.len() {
89            return Err(Error::Custom("unreferenced cell mask"))
90        }
91        // Both collections are bounded by 64; no hash table allocation is needed.
92        for (index, mask) in masks.iter().enumerate() {
93            if masks[..index].contains(mask) {
94                return Err(Error::Custom("duplicate cell mask"))
95            }
96        }
97        for (index, hash) in hashes.iter().enumerate() {
98            if hashes[..index].contains(hash) {
99                return Err(Error::Custom("duplicate cell transaction hash"))
100            }
101        }
102        if !response && masks.len() == 1 {
103            return Err(Error::Custom("uniform cell requests must use the shared form"))
104        }
105        Ok(())
106    }
107}
108
109impl Default for CellMasks {
110    fn default() -> Self {
111        Self::Shared(B128::ZERO)
112    }
113}
114
115impl From<B128> for CellMasks {
116    fn from(mask: B128) -> Self {
117        Self::Shared(mask)
118    }
119}
120
121impl Encodable for CellMasks {
122    fn encode(&self, out: &mut dyn BufMut) {
123        match self {
124            Self::Shared(mask) => mask.encode(out),
125            Self::Indexed { masks, mask_ids } => {
126                masks.encode(out);
127                mask_ids.encode(out);
128            }
129        }
130    }
131
132    fn length(&self) -> usize {
133        match self {
134            Self::Shared(mask) => mask.length(),
135            Self::Indexed { masks, mask_ids } => masks.length() + mask_ids.length(),
136        }
137    }
138}
139
140impl Decodable for CellMasks {
141    fn decode(buf: &mut &[u8]) -> alloy_rlp::Result<Self> {
142        let mut header_buf = *buf;
143        if !Header::decode(&mut header_buf)?.list {
144            return B128::decode(buf).map(Self::Shared)
145        }
146        let masks = decode_bounded_list(buf, MAX_INDEXED_CELL_MASKS)?;
147        let ids = Header::decode_bytes(buf, false)?;
148        if ids.len() > MAX_INDEXED_CELL_HASHES {
149            return Err(Error::Custom("invalid indexed cell counts"))
150        }
151        Ok(Self::Indexed { masks, mask_ids: Bytes::copy_from_slice(ids) })
152    }
153}
154
155#[cfg(feature = "serde")]
156impl Serialize for CellMasks {
157    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
158        match self {
159            Self::Shared(mask) => mask.serialize(serializer),
160            Self::Indexed { masks, mask_ids } => {
161                if masks.len() > MAX_INDEXED_CELL_MASKS || mask_ids.len() > MAX_INDEXED_CELL_HASHES
162                {
163                    return Err(serde::ser::Error::custom("invalid indexed cell counts"))
164                }
165                let encoded = alloy_rlp::encode(self);
166                // Valid indexed forms are either two bytes (empty) or at least 19 bytes.
167                if encoded.len() == B128::len_bytes() {
168                    return Err(serde::ser::Error::custom("invalid indexed cell mask encoding"))
169                }
170                Bytes::from(encoded).serialize(serializer)
171            }
172        }
173    }
174}
175
176#[cfg(feature = "serde")]
177impl<'de> Deserialize<'de> for CellMasks {
178    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
179        struct CellMasksVisitor;
180
181        impl<'de> Visitor<'de> for CellMasksVisitor {
182            type Value = CellMasks;
183
184            fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
185                formatter.write_str("a 16-byte shared mask or bounded indexed cell mask bytes")
186            }
187
188            fn visit_bytes<E: serde::de::Error>(self, encoded: &[u8]) -> Result<Self::Value, E> {
189                if encoded.len() == B128::len_bytes() {
190                    return Ok(CellMasks::Shared(B128::from_slice(encoded)))
191                }
192                if encoded.len() > MAX_SERIALIZED_CELL_MASK_BYTES {
193                    return Err(E::custom("serialized cell masks exceed indexed bounds"))
194                }
195                let mut buf = encoded;
196                let masks = CellMasks::decode(&mut buf).map_err(E::custom)?;
197                if !masks.is_indexed() || !buf.is_empty() {
198                    return Err(E::custom("invalid indexed cell mask encoding"))
199                }
200                Ok(masks)
201            }
202
203            fn visit_str<E: serde::de::Error>(self, value: &str) -> Result<Self::Value, E> {
204                let shared_hex_len = B128::len_bytes() * 2;
205                if value.len() == shared_hex_len || value.len() == shared_hex_len + 2 {
206                    return B128::deserialize(StrDeserializer::<E>::new(value))
207                        .map(CellMasks::Shared)
208                }
209                // Bound the hex input before Bytes allocates its decoding buffer.
210                if value.len() > MAX_SERIALIZED_CELL_MASK_BYTES * 2 + 2 {
211                    return Err(E::custom("serialized cell masks exceed indexed bounds"))
212                }
213                let encoded = Bytes::deserialize(StrDeserializer::<E>::new(value))?;
214                self.visit_bytes(&encoded)
215            }
216
217            fn visit_seq<A: SeqAccess<'de>>(self, seq: A) -> Result<Self::Value, A::Error> {
218                B128::deserialize(SeqAccessDeserializer::new(seq)).map(CellMasks::Shared)
219            }
220        }
221
222        if deserializer.is_human_readable() {
223            deserializer.deserialize_any(CellMasksVisitor)
224        } else {
225            deserializer.deserialize_bytes(CellMasksVisitor)
226        }
227    }
228}
229
230/// Transaction hashes and the cell indices requested from every blob in each transaction.
231#[derive(Clone, Debug, Default, PartialEq, Eq)]
232#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
233pub struct GetCells {
234    /// Transaction hashes, unique and bounded to 64 in indexed requests.
235    pub hashes: Vec<B256>,
236    /// Shared or indexed little-endian cell bitvectors.
237    pub cell_mask: CellMasks,
238}
239
240impl GetCells {
241    /// Returns the requested indices at a transaction position, interpreting the wire bitvector.
242    pub fn cell_mask(&self, index: usize) -> Option<BlobCellMask> {
243        self.cell_mask.mask_at(index).map(BlobCellMask::new)
244    }
245
246    /// Builds an adaptive request from one mask per hash, choosing shared for uniform masks.
247    /// Rejects mismatched lengths, empty batches, or invalid indexed requests.
248    pub fn from_masks(hashes: Vec<B256>, masks: Vec<B128>) -> alloy_rlp::Result<Self> {
249        if hashes.is_empty() || hashes.len() != masks.len() {
250            return Err(Error::Custom("invalid indexed cell counts"))
251        }
252        let first = masks[0];
253        if masks.iter().all(|mask| *mask == first) {
254            return Ok(Self { hashes, cell_mask: first.into() })
255        }
256        if hashes.len() > MAX_INDEXED_CELL_HASHES {
257            return Err(Error::Custom("invalid indexed cell counts"))
258        }
259        let mut unique = Vec::new();
260        let mut ids = Vec::with_capacity(masks.len());
261        for mask in masks {
262            let id = unique.iter().position(|entry| *entry == mask).unwrap_or_else(|| {
263                unique.push(mask);
264                unique.len() - 1
265            });
266            // The hash count bounds the number of distinct masks to 64.
267            ids.push(id as u8);
268        }
269        let cell_mask = CellMasks::Indexed { masks: unique, mask_ids: ids.into() };
270        cell_mask.validate(&hashes, false)?;
271        Ok(Self { hashes, cell_mask })
272    }
273}
274
275impl InMemorySize for GetCells {
276    fn size(&self) -> usize {
277        self.hashes.len() * core::mem::size_of::<B256>() +
278            match &self.cell_mask {
279                CellMasks::Shared(_) => core::mem::size_of::<B128>(),
280                CellMasks::Indexed { masks, mask_ids } => {
281                    masks.len() * core::mem::size_of::<B128>() + mask_ids.len()
282                }
283            }
284    }
285}
286
287impl Encodable for GetCells {
288    fn encode(&self, out: &mut dyn BufMut) {
289        self.hashes.encode(out);
290        self.cell_mask.encode(out);
291    }
292
293    fn length(&self) -> usize {
294        self.hashes.length() + self.cell_mask.length()
295    }
296}
297
298impl Decodable for GetCells {
299    fn decode(buf: &mut &[u8]) -> alloy_rlp::Result<Self> {
300        // Inspect masks before allocating hashes so indexed counts are bounded during decoding.
301        let mut tail = *buf;
302        Header::decode_bytes(&mut tail, true)?;
303        let cell_mask = CellMasks::decode(&mut tail)?;
304        let hashes = if cell_mask.is_indexed() {
305            decode_bounded_list(buf, MAX_INDEXED_CELL_HASHES)?
306        } else {
307            Vec::<B256>::decode(buf)?
308        };
309        cell_mask.validate(&hashes, false)?;
310        *buf = tail;
311        Ok(Self { hashes, cell_mask })
312    }
313}
314
315/// Returned cells, grouped by transaction, then blob order, then increasing set bit index.
316/// Cells remain untrusted until checked against the transaction commitments and cell proofs.
317#[derive(Clone, Debug, Default, PartialEq, Eq)]
318#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
319pub struct Cells {
320    /// Hashes identifying the returned transactions.
321    pub hashes: Vec<B256>,
322    /// Cells in blob order and increasing cell-index order within each blob.
323    pub cells: Vec<Vec<Cell>>,
324    /// Returned cell indices for each transaction.
325    pub cell_mask: CellMasks,
326}
327
328impl Cells {
329    /// Checks form, requested hash multiplicities, mask subsets, and cell-list dimensions.
330    /// Cryptographic verification requires the transaction's commitments and proofs and is
331    /// performed by the caller before importing any data into the blobpool.
332    pub fn validate_response(&self, request: &GetCells) -> alloy_rlp::Result<()> {
333        self.cell_mask.validate(&self.hashes, true)?;
334        if self.cell_mask.is_indexed() != request.cell_mask.is_indexed() ||
335            self.hashes.len() != self.cells.len()
336        {
337            return Err(Error::Custom("invalid cell response form"))
338        }
339        // Indexed requests are bounded to 64 hashes. Large shared responses need a lookup
340        // table to prevent peer-controlled repeated hashes from causing quadratic work.
341        let mut shared_hashes = (matches!(request.cell_mask, CellMasks::Shared(_)) &&
342            request.hashes.len() > MAX_INDEXED_CELL_HASHES &&
343            self.hashes.len() > MAX_INDEXED_CELL_HASHES)
344            .then(|| {
345                let mut remaining = B256Map::<usize>::with_capacity_and_hasher(
346                    request.hashes.len(),
347                    Default::default(),
348                );
349                for hash in &request.hashes {
350                    *remaining.entry(*hash).or_default() += 1;
351                }
352                remaining
353            });
354        for (index, hash) in self.hashes.iter().enumerate() {
355            let request_index = if let Some(hashes) = &mut shared_hashes {
356                let remaining = hashes
357                    .get_mut(hash)
358                    .ok_or(Error::Custom("unrequested cell transaction hash"))?;
359                if *remaining == 0 {
360                    return Err(Error::Custom("duplicate cell transaction hash"))
361                }
362                *remaining -= 1;
363                // Shared masks do not depend on the transaction position.
364                0
365            } else {
366                let request_index = request
367                    .hashes
368                    .iter()
369                    .position(|requested| requested == hash)
370                    .ok_or(Error::Custom("unrequested cell transaction hash"))?;
371                if !self.cell_mask.is_indexed() && self.hashes[..index].contains(hash) {
372                    let returned =
373                        self.hashes[..index].iter().filter(|entry| *entry == hash).count();
374                    let requested = request.hashes.iter().filter(|entry| *entry == hash).count();
375                    if returned >= requested {
376                        return Err(Error::Custom("duplicate cell transaction hash"))
377                    }
378                }
379                request_index
380            };
381            let mask = self
382                .cell_mask
383                .mask_at(index)
384                .ok_or(Error::Custom("invalid cell mask identifier"))?;
385            let requested = request
386                .cell_mask
387                .mask_at(request_index)
388                .ok_or(Error::Custom("invalid cell mask identifier"))?;
389            let mask = BlobCellMask::new(mask);
390            if !mask.is_subset_of(BlobCellMask::new(requested)) {
391                return Err(Error::Custom("unrequested cell index"))
392            }
393            let count = mask.count();
394            if (count == 0 && !self.cells[index].is_empty()) ||
395                (count != 0 &&
396                    (self.cells[index].is_empty() ||
397                        !self.cells[index].len().is_multiple_of(count)))
398            {
399                return Err(Error::Custom("invalid cell response dimensions"))
400            }
401        }
402        Ok(())
403    }
404}
405
406impl Encodable for Cells {
407    fn encode(&self, out: &mut dyn BufMut) {
408        self.hashes.encode(out);
409        self.cells.encode(out);
410        self.cell_mask.encode(out);
411    }
412
413    fn length(&self) -> usize {
414        self.hashes.length() + self.cells.length() + self.cell_mask.length()
415    }
416}
417
418impl Decodable for Cells {
419    fn decode(buf: &mut &[u8]) -> alloy_rlp::Result<Self> {
420        let mut tail = *buf;
421        Header::decode_bytes(&mut tail, true)?;
422        let mut cell_lists = Header::decode_bytes(&mut tail, true)?;
423        let cell_mask = CellMasks::decode(&mut tail)?;
424        let hashes = if cell_mask.is_indexed() {
425            decode_bounded_list(buf, MAX_INDEXED_CELL_HASHES)?
426        } else {
427            Vec::<B256>::decode(buf)?
428        };
429        // EIP-8408 requires all mask metadata to be validated before cell-response allocation.
430        cell_mask.validate(&hashes, true)?;
431        let mut cells = Vec::new();
432        while !cell_lists.is_empty() {
433            if cells.len() == hashes.len() {
434                return Err(Error::Custom("invalid cell response dimensions"))
435            }
436            cells.push(Vec::<Cell>::decode(&mut cell_lists)?);
437        }
438        if cells.len() != hashes.len() {
439            return Err(Error::Custom("invalid cell response dimensions"))
440        }
441        *buf = tail;
442        Ok(Self { hashes, cells, cell_mask })
443    }
444}
445
446fn decode_bounded_list<T: Decodable>(buf: &mut &[u8], max: usize) -> alloy_rlp::Result<Vec<T>> {
447    let mut payload = Header::decode_bytes(buf, true)?;
448    let mut values = Vec::new();
449    while !payload.is_empty() {
450        if values.len() == max {
451            return Err(Error::Custom("invalid indexed cell counts"))
452        }
453        values.push(T::decode(&mut payload)?);
454    }
455    Ok(values)
456}
457
458#[cfg(test)]
459mod tests {
460    use super::*;
461    use crate::{
462        message::RequestPair, EthMessage, EthMessageID, EthNetworkPrimitives, EthVersion,
463        ProtocolMessage,
464    };
465    use alloy_primitives::{hex, U256};
466    use proptest::prelude::*;
467
468    fn indexed(hashes: Vec<B256>, masks: Vec<B128>, ids: &[u8]) -> GetCells {
469        GetCells {
470            hashes,
471            cell_mask: CellMasks::Indexed { masks, mask_ids: Bytes::copy_from_slice(ids) },
472        }
473    }
474
475    fn request() -> GetCells {
476        indexed(
477            vec![B256::ZERO, B256::repeat_byte(1)],
478            vec![B128::repeat_byte(1), B128::repeat_byte(2)],
479            &[0, 1],
480        )
481    }
482
483    #[test]
484    fn shared_wire_vector_is_flat() {
485        let pair = RequestPair { request_id: 1, message: GetCells::default() };
486        let expected = hex!("d301c09000000000000000000000000000000000");
487        assert_eq!(alloy_rlp::encode(&pair), expected);
488        assert_eq!(alloy_rlp::decode_exact::<RequestPair<GetCells>>(&expected).unwrap(), pair);
489        let response = RequestPair { request_id: 1, message: Cells::default() };
490        let expected = hex!("d401c0c09000000000000000000000000000000000");
491        assert_eq!(alloy_rlp::encode(&response), expected);
492        assert_eq!(alloy_rlp::decode_exact::<RequestPair<Cells>>(&expected).unwrap(), response);
493    }
494
495    #[test]
496    fn shared_cell_framing_by_version() {
497        let messages = [
498            EthMessage::<EthNetworkPrimitives>::GetCells(RequestPair {
499                request_id: 1,
500                message: GetCells::default(),
501            }),
502            EthMessage::Cells(RequestPair { request_id: 1, message: Cells::default() }),
503        ];
504        for message in messages {
505            let protocol = ProtocolMessage::from(message);
506            let canonical = alloy_rlp::encode(&protocol);
507            for version in [EthVersion::Eth72, EthVersion::Eth73] {
508                let mut buf = canonical.as_slice();
509                assert_eq!(ProtocolMessage::decode_message(version, &mut buf).unwrap(), protocol);
510                assert!(buf.is_empty());
511            }
512        }
513    }
514
515    #[test]
516    fn cell_payload_is_bounded() {
517        for (wire, extra_field) in [
518            (
519                hex!("14d301c09000000000000000000000000000000000").to_vec(),
520                hex!("14d401c0900000000000000000000000000000000080").to_vec(),
521            ),
522            (
523                hex!("15d401c0c09000000000000000000000000000000000").to_vec(),
524                hex!("15d501c0c0900000000000000000000000000000000080").to_vec(),
525            ),
526        ] {
527            for version in [EthVersion::Eth72, EthVersion::Eth73] {
528                let mut appended = wire.clone();
529                appended.push(0x80);
530                let mut buf = appended.as_slice();
531                ProtocolMessage::<EthNetworkPrimitives>::decode_message(version, &mut buf).unwrap();
532                assert_eq!(buf, &[0x80]);
533                assert!(matches!(
534                    ProtocolMessage::<EthNetworkPrimitives>::decode_message(
535                        version,
536                        &mut extra_field.as_slice()
537                    ),
538                    Err(crate::message::MessageError::RlpError(Error::UnexpectedLength))
539                ));
540            }
541        }
542    }
543
544    #[test]
545    fn indexed_packets_match_geth_rlp_vectors() {
546        let vectors: serde_json::Value =
547            serde_json::from_str(include_str!("../testdata/eip8408/vectors.json",)).unwrap();
548        let hashes = [0x11u64, 0x22, 0x33].map(|value| B256::from(U256::from(value))).to_vec();
549        let request = indexed(
550            hashes.clone(),
551            vec![
552                B128::from((1u128 | (1 << 8) | (1 << 127)).to_le_bytes()),
553                B128::from((2u128 | (1 << 9)).to_le_bytes()),
554            ],
555            &[0, 1, 0],
556        );
557        let mut first = Cell::ZERO;
558        first[0] = 1;
559        first[2047] = 2;
560        let mut second = Cell::ZERO;
561        second[0] = 3;
562        second[2047] = 4;
563        let response = Cells {
564            hashes: hashes[1..].to_vec(),
565            cells: vec![vec![first], vec![second]],
566            cell_mask: CellMasks::Indexed {
567                masks: vec![
568                    B128::from((1u128 << 9).to_le_bytes()),
569                    B128::from((1u128 << 127).to_le_bytes()),
570                ],
571                mask_ids: Bytes::from_static(&[0, 1]),
572            },
573        };
574        assert_eq!(response.validate_response(&request), Ok(()));
575        let empty = Cells {
576            cell_mask: CellMasks::Indexed { masks: vec![], mask_ids: Bytes::new() },
577            ..Default::default()
578        };
579        for (name, message) in [
580            (
581                "request",
582                EthMessage::<EthNetworkPrimitives>::GetCells(RequestPair {
583                    request_id: 42,
584                    message: request,
585                }),
586            ),
587            ("response", EthMessage::Cells(RequestPair { request_id: 42, message: response })),
588            ("empty_response", EthMessage::Cells(RequestPair { request_id: 42, message: empty })),
589        ] {
590            let expected = vectors[name].as_str().unwrap().parse::<Bytes>().unwrap();
591            let protocol = ProtocolMessage::from(message);
592            assert_eq!(alloy_rlp::encode(&protocol).as_slice(), expected.as_ref());
593            let mut buf = expected.as_ref();
594            assert_eq!(
595                ProtocolMessage::decode_message(EthVersion::Eth73, &mut buf).unwrap(),
596                protocol
597            );
598            assert!(buf.is_empty());
599        }
600    }
601
602    #[test]
603    fn indexed_wire_vector_is_flat() {
604        // Local schema fixture; independent geth RLP vectors are checked above.
605        let pair = RequestPair { request_id: 1, message: request() };
606        let expected = hex!("f86b01f842a00000000000000000000000000000000000000000000000000000000000000000a00101010101010101010101010101010101010101010101010101010101010101e290010101010101010101010101010101019002020202020202020202020202020202820001");
607        assert_eq!(alloy_rlp::encode(&pair), expected);
608        assert_eq!(alloy_rlp::decode_exact::<RequestPair<GetCells>>(&expected).unwrap(), pair);
609        assert_eq!(pair.length(), expected.len());
610    }
611
612    #[test]
613    fn empty_indexed_response_vector() {
614        let pair = RequestPair {
615            request_id: 1,
616            message: Cells {
617                cell_mask: CellMasks::Indexed { masks: vec![], mask_ids: Bytes::new() },
618                ..Default::default()
619            },
620        };
621        let expected = hex!("c501c0c0c080");
622        assert_eq!(alloy_rlp::encode(&pair), expected);
623        assert_eq!(alloy_rlp::decode_exact::<RequestPair<Cells>>(&expected).unwrap(), pair);
624        let empty = indexed(vec![], vec![], &[]);
625        assert_eq!(
626            GetCells::decode(&mut alloy_rlp::encode(empty).as_slice()),
627            Err(Error::Custom("invalid indexed cell counts"))
628        );
629    }
630
631    #[test]
632    fn rejects_noncanonical_tables() {
633        let hashes = request().hashes;
634        let a = B128::repeat_byte(1);
635        let b = B128::repeat_byte(2);
636        let cases = [
637            (indexed(hashes.clone(), vec![a, b], &[0]), "invalid indexed cell counts"),
638            (indexed(hashes.clone(), vec![], &[0, 0]), "invalid indexed cell counts"),
639            (indexed(hashes.clone(), vec![a, b], &[1, 0]), "invalid cell mask identifier order"),
640            (indexed(hashes.clone(), vec![a, b], &[0, 2]), "invalid cell mask identifier order"),
641            (indexed(hashes.clone(), vec![a, b], &[0, 255]), "invalid cell mask identifier order"),
642            (indexed(hashes.clone(), vec![a, b], &[0, 0]), "unreferenced cell mask"),
643            (indexed(hashes, vec![a, a], &[0, 1]), "duplicate cell mask"),
644            (indexed(vec![B256::ZERO; 2], vec![a, b], &[0, 1]), "duplicate cell transaction hash"),
645        ];
646        for (request, error) in cases {
647            assert_eq!(
648                GetCells::decode(&mut alloy_rlp::encode(request).as_slice()),
649                Err(Error::Custom(error))
650            );
651        }
652    }
653
654    #[test]
655    fn indexed_bounds_and_shared_compatibility() {
656        for count in [1, 2, 64, 65] {
657            let hashes = (0..count).map(|n| B256::repeat_byte(n as u8)).collect::<Vec<_>>();
658            let masks =
659                if count == 1 { vec![B128::ZERO] } else { vec![B128::ZERO, B128::repeat_byte(1)] };
660            let ids = (0..count).map(|index| (index % 2) as u8).collect::<Vec<_>>();
661            let req = indexed(hashes.clone(), masks, &ids);
662            let decoded = GetCells::decode(&mut alloy_rlp::encode(&req).as_slice());
663            if count == 1 {
664                assert_eq!(
665                    decoded,
666                    Err(Error::Custom("uniform cell requests must use the shared form"))
667                );
668            } else if count <= 64 {
669                assert_eq!(decoded, Ok(req));
670            } else {
671                assert_eq!(decoded, Err(Error::Custom("invalid indexed cell counts")));
672            }
673            let shared = GetCells { hashes, cell_mask: B128::ZERO.into() };
674            assert_eq!(GetCells::decode(&mut alloy_rlp::encode(&shared).as_slice()), Ok(shared));
675        }
676        let oversized = indexed(vec![B256::ZERO], vec![B128::ZERO; 65], &[0]);
677        assert_eq!(
678            GetCells::decode(&mut alloy_rlp::encode(oversized).as_slice()),
679            Err(Error::Custom("invalid indexed cell counts"))
680        );
681        let oversized_ids = indexed(vec![B256::ZERO], vec![B128::ZERO], &[0; 65]);
682        assert_eq!(
683            GetCells::decode(&mut alloy_rlp::encode(oversized_ids).as_slice()),
684            Err(Error::Custom("invalid indexed cell counts"))
685        );
686    }
687
688    #[test]
689    fn adaptive_encoding_keeps_uniform_requests_shared() {
690        let hashes = vec![B256::ZERO, B256::repeat_byte(1), B256::repeat_byte(2)];
691        let a = B128::repeat_byte(1);
692        let b = B128::repeat_byte(2);
693        assert_eq!(
694            GetCells::from_masks(hashes.clone(), vec![a; 3]).unwrap().cell_mask,
695            CellMasks::Shared(a)
696        );
697        assert_eq!(
698            GetCells::from_masks(hashes, vec![a, b, a]).unwrap().cell_mask,
699            CellMasks::Indexed { masks: vec![a, b], mask_ids: Bytes::from_static(&[0, 1, 0]) }
700        );
701        assert_eq!(
702            GetCells::from_masks(vec![], vec![]),
703            Err(Error::Custom("invalid indexed cell counts"))
704        );
705        assert_eq!(
706            GetCells::from_masks(vec![B256::ZERO], vec![]),
707            Err(Error::Custom("invalid indexed cell counts"))
708        );
709    }
710
711    #[test]
712    fn response_metadata_precedes_cell_decoding() {
713        let req = indexed(vec![B256::ZERO], vec![B128::ZERO], &[1]);
714        let mut wire = alloy_rlp::encode(&req.hashes);
715        // The cell is intentionally malformed. Invalid metadata must win before cell decoding.
716        wire.extend_from_slice(&[0xc1, 0x80]);
717        req.cell_mask.encode(&mut wire);
718        assert_eq!(
719            Cells::decode(&mut wire.as_slice()),
720            Err(Error::Custom("invalid cell mask identifier order"))
721        );
722    }
723
724    #[test]
725    fn decode_bounds_precede_element_decoding() {
726        // Each list holds one malformed element past its bound, which must not be decoded.
727        let mut payload = alloy_rlp::encode(B256::ZERO).repeat(MAX_INDEXED_CELL_HASHES);
728        payload.push(0x80);
729        let mut hashes = Vec::new();
730        Header { list: true, payload_length: payload.len() }.encode(&mut hashes);
731        hashes.extend_from_slice(&payload);
732        let masks = CellMasks::Indexed {
733            masks: vec![B128::ZERO, B128::repeat_byte(1)],
734            mask_ids: (0..MAX_INDEXED_CELL_HASHES).map(|index| (index % 2) as u8).collect(),
735        };
736        let mut request = hashes.clone();
737        masks.encode(&mut request);
738        assert_eq!(
739            GetCells::decode(&mut request.as_slice()),
740            Err(Error::Custom("invalid indexed cell counts"))
741        );
742        let mut response = hashes;
743        response.push(0xc0);
744        masks.encode(&mut response);
745        assert_eq!(
746            Cells::decode(&mut response.as_slice()),
747            Err(Error::Custom("invalid indexed cell counts"))
748        );
749        let mut response = alloy_rlp::encode(vec![B256::ZERO]);
750        response.extend_from_slice(&hex!("c3c0c180"));
751        B128::ZERO.encode(&mut response);
752        assert_eq!(
753            Cells::decode(&mut response.as_slice()),
754            Err(Error::Custom("invalid cell response dimensions"))
755        );
756    }
757
758    #[test]
759    fn response_correlation_and_subsets() {
760        let request = indexed(
761            vec![B256::ZERO, B256::repeat_byte(1)],
762            vec![B128::from(3u128.to_le_bytes()), B128::from(4u128.to_le_bytes())],
763            &[0, 1],
764        );
765        let mut response = Cells {
766            hashes: vec![B256::ZERO],
767            cells: vec![vec![Cell::ZERO]],
768            cell_mask: CellMasks::Indexed {
769                masks: vec![B128::from(1u128.to_le_bytes())],
770                mask_ids: Bytes::from_static(&[0]),
771            },
772        };
773        assert_eq!(response.validate_response(&request), Ok(()));
774        response.hashes[0] = B256::repeat_byte(2);
775        assert_eq!(
776            response.validate_response(&request),
777            Err(Error::Custom("unrequested cell transaction hash"))
778        );
779        response.hashes[0] = B256::ZERO;
780        response.cell_mask = CellMasks::Indexed {
781            masks: vec![B128::from(4u128.to_le_bytes())],
782            mask_ids: Bytes::from_static(&[0]),
783        };
784        assert_eq!(
785            response.validate_response(&request),
786            Err(Error::Custom("unrequested cell index"))
787        );
788        response.cell_mask = CellMasks::Shared(B128::ZERO);
789        assert_eq!(
790            response.validate_response(&request),
791            Err(Error::Custom("invalid cell response form"))
792        );
793        response.cell_mask = CellMasks::Indexed {
794            masks: vec![B128::from(3u128.to_le_bytes())],
795            mask_ids: Bytes::from_static(&[0]),
796        };
797        assert_eq!(
798            response.validate_response(&request),
799            Err(Error::Custom("invalid cell response dimensions"))
800        );
801        response.cell_mask =
802            CellMasks::Indexed { masks: vec![B128::ZERO], mask_ids: Bytes::from_static(&[0]) };
803        assert_eq!(
804            response.validate_response(&request),
805            Err(Error::Custom("invalid cell response dimensions"))
806        );
807        response.cells.clear();
808        assert_eq!(
809            response.validate_response(&request),
810            Err(Error::Custom("invalid cell response form"))
811        );
812    }
813
814    #[test]
815    fn shared_response_hash_lookup() {
816        for count in [1, MAX_INDEXED_CELL_HASHES, MAX_INDEXED_CELL_HASHES + 1, 4096] {
817            let request = GetCells {
818                hashes: (0..count).map(|index| B256::from(U256::from(index))).collect(),
819                cell_mask: B128::from(1u128.to_le_bytes()).into(),
820            };
821            let mut response = Cells {
822                hashes: request.hashes.clone(),
823                cells: vec![vec![]; count],
824                cell_mask: B128::ZERO.into(),
825            };
826            assert_eq!(response.validate_response(&request), Ok(()));
827            if count > 1 {
828                let mut repeated = response.clone();
829                repeated.hashes.fill(request.hashes[count - 1]);
830                assert_eq!(
831                    repeated.validate_response(&request),
832                    Err(Error::Custom("duplicate cell transaction hash"))
833                );
834            }
835            response.hashes[count - 1] = B256::repeat_byte(0xff);
836            assert_eq!(
837                response.validate_response(&request),
838                Err(Error::Custom("unrequested cell transaction hash"))
839            );
840            response.hashes[count - 1] = request.hashes[count - 1];
841            response.cell_mask = B128::from(2u128.to_le_bytes()).into();
842            assert_eq!(
843                response.validate_response(&request),
844                Err(Error::Custom("unrequested cell index"))
845            );
846        }
847    }
848
849    #[test]
850    fn small_shared_response_to_large_request() {
851        let request = GetCells {
852            hashes: (0..=MAX_INDEXED_CELL_HASHES)
853                .map(|index| B256::from(U256::from(index)))
854                .collect(),
855            cell_mask: B128::ZERO.into(),
856        };
857        for count in [0, 1, MAX_INDEXED_CELL_HASHES] {
858            let mut response = Cells {
859                hashes: request.hashes.iter().rev().take(count).copied().collect(),
860                cells: vec![vec![]; count],
861                cell_mask: B128::ZERO.into(),
862            };
863            assert_eq!(response.validate_response(&request), Ok(()));
864            if let Some(hash) = response.hashes.last_mut() {
865                *hash = B256::repeat_byte(0xff);
866                assert_eq!(
867                    response.validate_response(&request),
868                    Err(Error::Custom("unrequested cell transaction hash"))
869                );
870            }
871        }
872    }
873
874    #[test]
875    fn shared_response_respects_requested_hash_multiplicity() {
876        for count in [3, MAX_INDEXED_CELL_HASHES, MAX_INDEXED_CELL_HASHES + 1, 4096] {
877            let mut hashes =
878                (0..count).map(|index| B256::from(U256::from(index))).collect::<Vec<_>>();
879            hashes[count - 1] = hashes[0];
880            let request = GetCells { hashes: hashes.clone(), cell_mask: B128::ZERO.into() };
881            let mut response =
882                Cells { hashes, cells: vec![vec![]; count], cell_mask: B128::ZERO.into() };
883            assert_eq!(response.validate_response(&request), Ok(()));
884            response.hashes[1] = response.hashes[0];
885            assert_eq!(
886                response.validate_response(&request),
887                Err(Error::Custom("duplicate cell transaction hash"))
888            );
889        }
890    }
891
892    #[test]
893    fn uniform_indexed_requests_are_rejected_but_responses_are_valid() {
894        let hashes = vec![B256::ZERO, B256::repeat_byte(1)];
895        let a = B128::from(1u128.to_le_bytes());
896        let b = B128::from(2u128.to_le_bytes());
897        let uniform = indexed(hashes.clone(), vec![a], &[0, 0]);
898        assert_eq!(
899            GetCells::decode(&mut alloy_rlp::encode(uniform).as_slice()),
900            Err(Error::Custom("uniform cell requests must use the shared form"))
901        );
902        let request = GetCells::from_masks(hashes.clone(), vec![a, b]).unwrap();
903        let response = Cells {
904            hashes: vec![hashes[0]],
905            cells: vec![vec![Cell::ZERO]],
906            cell_mask: CellMasks::Indexed { masks: vec![a], mask_ids: Bytes::from_static(&[0]) },
907        };
908        assert_eq!(response.validate_response(&request), Ok(()));
909        assert_eq!(
910            alloy_rlp::decode_exact::<RequestPair<Cells>>(&alloy_rlp::encode(RequestPair {
911                request_id: 1,
912                message: response.clone(),
913            }))
914            .unwrap()
915            .message,
916            response
917        );
918    }
919
920    #[test]
921    fn decoding_is_bounded_by_request_pair() {
922        let pair = RequestPair { request_id: 1, message: request() };
923        let mut wire = alloy_rlp::encode(&pair);
924        wire.push(0x80);
925        let mut buf = wire.as_slice();
926        assert_eq!(RequestPair::<GetCells>::decode(&mut buf).unwrap(), pair);
927        assert_eq!(buf, &[0x80]);
928        assert_eq!(
929            RequestPair::<GetCells>::decode(
930                &mut &hex!("c101c09000000000000000000000000000000000")[..]
931            ),
932            Err(Error::InputTooShort)
933        );
934    }
935
936    #[test]
937    fn indexed_forms_require_eth73() {
938        let messages = [
939            EthMessage::<EthNetworkPrimitives>::GetCells(RequestPair {
940                request_id: 1,
941                message: request(),
942            }),
943            EthMessage::Cells(RequestPair {
944                request_id: 1,
945                message: Cells {
946                    cell_mask: CellMasks::Indexed { masks: vec![], mask_ids: Bytes::new() },
947                    ..Default::default()
948                },
949            }),
950        ];
951        for message in messages {
952            let message_type = message.message_id();
953            let protocol = ProtocolMessage { message_type, message };
954            let encoded = alloy_rlp::encode(&protocol);
955            assert_eq!(
956                ProtocolMessage::<EthNetworkPrimitives>::decode_message(
957                    EthVersion::Eth73,
958                    &mut encoded.as_slice()
959                )
960                .unwrap(),
961                protocol
962            );
963            assert!(
964                matches!(ProtocolMessage::<EthNetworkPrimitives>::decode_message(EthVersion::Eth72,&mut encoded.as_slice()),Err(crate::message::MessageError::Invalid(EthVersion::Eth72, id)) if id == message_type)
965            );
966        }
967        assert_eq!(
968            EthMessageID::message_count(EthVersion::Eth73),
969            EthMessageID::message_count(EthVersion::Eth72)
970        );
971    }
972
973    #[test]
974    fn indexed_response_roundtrip_and_dimensions() {
975        let request = request();
976        let response = Cells {
977            hashes: request.hashes.clone(),
978            cells: vec![vec![Cell::ZERO; 16], vec![Cell::repeat_byte(1); 16]],
979            cell_mask: request.cell_mask.clone(),
980        };
981        assert_eq!(response.validate_response(&request), Ok(()));
982        let pair = RequestPair { request_id: 9, message: response.clone() };
983        let wire = alloy_rlp::encode(&pair);
984        assert_eq!(pair.length(), wire.len());
985        assert_eq!(alloy_rlp::decode_exact::<RequestPair<Cells>>(&wire).unwrap(), pair);
986        let mut missing = response.clone();
987        missing.cells.pop();
988        assert_eq!(
989            Cells::decode(&mut alloy_rlp::encode(missing).as_slice()),
990            Err(Error::Custom("invalid cell response dimensions"))
991        );
992        let mut extra = response.clone();
993        extra.cells.push(vec![]);
994        assert_eq!(
995            Cells::decode(&mut alloy_rlp::encode(extra).as_slice()),
996            Err(Error::Custom("invalid cell response dimensions"))
997        );
998        let mut no_cells = response;
999        no_cells.cells[0].clear();
1000        assert_eq!(
1001            no_cells.validate_response(&request),
1002            Err(Error::Custom("invalid cell response dimensions"))
1003        );
1004    }
1005
1006    #[test]
1007    fn adaptive_rejects_invalid_heterogeneous_batches() {
1008        let hashes = (0..65).map(B256::repeat_byte).collect::<Vec<_>>();
1009        let masks = (0..65).map(B128::repeat_byte).collect::<Vec<_>>();
1010        assert_eq!(
1011            GetCells::from_masks(hashes, masks),
1012            Err(Error::Custom("invalid indexed cell counts"))
1013        );
1014        assert_eq!(
1015            GetCells::from_masks(vec![B256::ZERO; 2], vec![B128::ZERO, B128::repeat_byte(1)]),
1016            Err(Error::Custom("duplicate cell transaction hash"))
1017        );
1018        let hashes = (0..64).map(B256::repeat_byte).collect::<Vec<_>>();
1019        let masks = (0..64).map(B128::repeat_byte).collect::<Vec<_>>();
1020        let request = GetCells::from_masks(hashes, masks).unwrap();
1021        assert_eq!(request.cell_mask.validate(&request.hashes, false), Ok(()));
1022    }
1023
1024    proptest! {
1025        #[test]
1026        fn adaptive_roundtrip(mask_values in proptest::collection::vec(any::<u128>(),1..=64)) {
1027            let hashes = (0..mask_values.len()).map(|i| B256::repeat_byte(i as u8)).collect();
1028            let masks = mask_values.iter().map(|n| B128::from(n.to_le_bytes())).collect();
1029            let req = GetCells::from_masks(hashes,masks).unwrap();
1030            let pair = RequestPair { request_id: 1,message: req };
1031            let wire = alloy_rlp::encode(&pair);
1032            prop_assert_eq!(pair.length(),wire.len());
1033            prop_assert_eq!(alloy_rlp::decode_exact::<RequestPair<GetCells>>(&wire).unwrap(),pair);
1034        }
1035
1036        #[test]
1037        fn shared_versions_roundtrip(
1038            hashes in proptest::collection::vec(any::<[u8; 32]>(), 0..70),
1039            mask in any::<[u8; 16]>(),
1040            request_id in any::<u64>(),
1041        ) {
1042            let hashes = hashes.into_iter().map(B256::from).collect::<Vec<_>>();
1043            let messages = [
1044                EthMessage::<EthNetworkPrimitives>::GetCells(RequestPair {
1045                    request_id,
1046                    message: GetCells { hashes: hashes.clone(), cell_mask: B128::from(mask).into() },
1047                }),
1048                EthMessage::Cells(RequestPair {
1049                    request_id,
1050                    message: Cells {
1051                        cells: vec![vec![]; hashes.len()],
1052                        hashes,
1053                        cell_mask: B128::ZERO.into(),
1054                    },
1055                }),
1056            ];
1057            for message in messages {
1058                let protocol = ProtocolMessage::from(message);
1059                for version in [EthVersion::Eth72, EthVersion::Eth73] {
1060                    let wire = alloy_rlp::encode(&protocol);
1061                    let mut buf = wire.as_slice();
1062                    prop_assert_eq!(&ProtocolMessage::decode_message(version, &mut buf).unwrap(),
1063                        &protocol);
1064                    prop_assert!(buf.is_empty());
1065                }
1066            }
1067        }
1068
1069        #[test]
1070        fn arbitrary_input_does_not_panic(data in proptest::collection::vec(any::<u8>(),0..4096)) {
1071            let _request = RequestPair::<GetCells>::decode(&mut data.as_slice());
1072            let _response = RequestPair::<Cells>::decode(&mut data.as_slice());
1073            for version in [EthVersion::Eth72, EthVersion::Eth73] {
1074                let _message = ProtocolMessage::<EthNetworkPrimitives>::decode_message(
1075                    version, &mut data.as_slice());
1076            }
1077        }
1078    }
1079}
1080
1081#[cfg(all(test, feature = "serde"))]
1082mod serde_tests {
1083    use super::*;
1084
1085    #[derive(Debug, PartialEq, Eq, Serialize, Deserialize)]
1086    struct LegacyGetCells {
1087        hashes: Vec<B256>,
1088        cell_mask: B128,
1089    }
1090
1091    #[derive(Debug, PartialEq, Eq, Serialize, Deserialize)]
1092    struct LegacyCells {
1093        hashes: Vec<B256>,
1094        cells: Vec<Vec<Cell>>,
1095        cell_mask: B128,
1096    }
1097
1098    #[test]
1099    fn shared_requests_preserve_legacy_serde() {
1100        for mask in [B128::ZERO, B128::repeat_byte(0x81)] {
1101            let legacy = LegacyGetCells { hashes: vec![B256::ZERO], cell_mask: mask };
1102            let request = GetCells { hashes: legacy.hashes.clone(), cell_mask: mask.into() };
1103            let json = serde_json::to_string(&legacy).unwrap();
1104            assert_eq!(serde_json::to_string(&request).unwrap(), json);
1105            assert_eq!(serde_json::from_str::<GetCells>(&json).unwrap(), request);
1106            assert_eq!(serde_json::from_str::<LegacyGetCells>(&json).unwrap(), legacy);
1107            let bytes = bincode::serialize(&legacy).unwrap();
1108            assert_eq!(bincode::serialize(&request).unwrap(), bytes);
1109            assert_eq!(bincode::deserialize::<GetCells>(&bytes).unwrap(), request);
1110            assert_eq!(bincode::deserialize::<LegacyGetCells>(&bytes).unwrap(), legacy);
1111        }
1112    }
1113
1114    #[test]
1115    fn shared_responses_preserve_legacy_serde() {
1116        for mask in [B128::ZERO, B128::repeat_byte(0x81)] {
1117            let legacy = LegacyCells {
1118                hashes: vec![B256::ZERO],
1119                cells: vec![vec![
1120                    Cell::ZERO;
1121                    u128::from_le_bytes(mask.into()).count_ones() as usize
1122                ]],
1123                cell_mask: mask,
1124            };
1125            let response = Cells {
1126                hashes: legacy.hashes.clone(),
1127                cells: legacy.cells.clone(),
1128                cell_mask: mask.into(),
1129            };
1130            let json = serde_json::to_string(&legacy).unwrap();
1131            assert_eq!(serde_json::to_string(&response).unwrap(), json);
1132            assert_eq!(serde_json::from_str::<Cells>(&json).unwrap(), response);
1133            assert_eq!(serde_json::from_str::<LegacyCells>(&json).unwrap(), legacy);
1134            let bytes = bincode::serialize(&legacy).unwrap();
1135            assert_eq!(bincode::serialize(&response).unwrap(), bytes);
1136            assert_eq!(bincode::deserialize::<Cells>(&bytes).unwrap(), response);
1137            assert_eq!(bincode::deserialize::<LegacyCells>(&bytes).unwrap(), legacy);
1138        }
1139    }
1140
1141    #[test]
1142    fn indexed_masks_serde_roundtrip() {
1143        for count in [0, 1, MAX_INDEXED_CELL_MASKS] {
1144            let masks = CellMasks::Indexed {
1145                masks: (0..count).map(|index| B128::repeat_byte(index as u8)).collect(),
1146                mask_ids: (0..count).map(|index| index as u8).collect::<Vec<_>>().into(),
1147            };
1148            let json = serde_json::to_string(&masks).unwrap();
1149            assert_eq!(serde_json::from_str::<CellMasks>(&json).unwrap(), masks);
1150            let bytes = bincode::serialize(&masks).unwrap();
1151            assert_eq!(bincode::deserialize::<CellMasks>(&bytes).unwrap(), masks);
1152        }
1153        assert_eq!(
1154            serde_json::to_string(&CellMasks::Indexed { masks: vec![], mask_ids: Bytes::new() })
1155                .unwrap(),
1156            "\"0xc080\""
1157        );
1158    }
1159
1160    #[test]
1161    fn serde_rejects_ambiguous_and_trailing_encodings() {
1162        // This malformed indexed table would otherwise collide with a raw B128's length.
1163        let ambiguous = CellMasks::Indexed { masks: vec![], mask_ids: vec![0; 14].into() };
1164        assert_eq!(alloy_rlp::encode(&ambiguous).len(), B128::len_bytes());
1165        assert!(matches!(bincode::serialize(&ambiguous).unwrap_err().as_ref(),
1166            bincode::ErrorKind::Custom(message) if message == "invalid indexed cell mask encoding"));
1167        for masks in [
1168            CellMasks::Shared(B128::ZERO),
1169            CellMasks::Indexed { masks: vec![], mask_ids: Bytes::new() },
1170        ] {
1171            let mut encoded = alloy_rlp::encode(&masks);
1172            if masks.is_indexed() {
1173                encoded.push(0x80);
1174            }
1175            let bytes = bincode::serialize(&Bytes::from(encoded)).unwrap();
1176            assert!(matches!(bincode::deserialize::<CellMasks>(&bytes).unwrap_err().as_ref(),
1177                bincode::ErrorKind::Custom(message) if message == "invalid indexed cell mask encoding"));
1178        }
1179    }
1180
1181    #[test]
1182    fn serde_rejects_malformed_or_oversized_indexed_bytes() {
1183        for (encoded, expected) in [
1184            (Bytes::new(), Error::InputTooShort),
1185            (
1186                Bytes::from(alloy_rlp::encode(CellMasks::Indexed {
1187                    masks: vec![B128::ZERO; MAX_INDEXED_CELL_MASKS + 1],
1188                    mask_ids: Bytes::new(),
1189                })),
1190                Error::Custom("invalid indexed cell counts"),
1191            ),
1192            (
1193                Bytes::from(alloy_rlp::encode(CellMasks::Indexed {
1194                    masks: vec![],
1195                    mask_ids: vec![0; MAX_INDEXED_CELL_HASHES + 1].into(),
1196                })),
1197                Error::Custom("invalid indexed cell counts"),
1198            ),
1199        ] {
1200            let bytes = bincode::serialize(&encoded).unwrap();
1201            assert!(matches!(bincode::deserialize::<CellMasks>(&bytes).unwrap_err().as_ref(),
1202                bincode::ErrorKind::Custom(message) if *message == expected.to_string()));
1203        }
1204    }
1205
1206    #[test]
1207    fn serde_bounds_input_before_hex_decoding() {
1208        let encoded = Bytes::from(vec![0; MAX_SERIALIZED_CELL_MASK_BYTES + 1]);
1209        let value = serde_json::to_value(&encoded).unwrap();
1210        assert_eq!(
1211            serde_json::from_value::<CellMasks>(value).unwrap_err().to_string(),
1212            "serialized cell masks exceed indexed bounds"
1213        );
1214        let bytes = bincode::serialize(&encoded).unwrap();
1215        assert!(matches!(bincode::deserialize::<CellMasks>(&bytes).unwrap_err().as_ref(),
1216            bincode::ErrorKind::Custom(message) if message == "serialized cell masks exceed indexed bounds"));
1217        for masks in [
1218            CellMasks::Indexed {
1219                masks: vec![B128::ZERO; MAX_INDEXED_CELL_MASKS + 1],
1220                mask_ids: Bytes::new(),
1221            },
1222            CellMasks::Indexed {
1223                masks: vec![],
1224                mask_ids: vec![0; MAX_INDEXED_CELL_HASHES + 1].into(),
1225            },
1226        ] {
1227            assert!(matches!(bincode::serialize(&masks).unwrap_err().as_ref(),
1228                bincode::ErrorKind::Custom(message) if message == "invalid indexed cell counts"));
1229        }
1230    }
1231
1232    #[test]
1233    fn indexed_responses_serde_roundtrip() {
1234        for response in [
1235            Cells {
1236                cell_mask: CellMasks::Indexed { masks: vec![], mask_ids: Bytes::new() },
1237                ..Default::default()
1238            },
1239            Cells {
1240                hashes: vec![B256::ZERO],
1241                cells: vec![vec![Cell::ZERO]],
1242                cell_mask: CellMasks::Indexed {
1243                    masks: vec![B128::from(1u128.to_le_bytes())],
1244                    mask_ids: vec![0].into(),
1245                },
1246            },
1247        ] {
1248            let json = serde_json::to_string(&response).unwrap();
1249            assert_eq!(serde_json::from_str::<Cells>(&json).unwrap(), response);
1250            let bytes = bincode::serialize(&response).unwrap();
1251            assert_eq!(bincode::deserialize::<Cells>(&bytes).unwrap(), response);
1252        }
1253        assert_eq!(
1254            serde_json::from_str::<CellMasks>(&serde_json::to_string(&[0u8; 16]).unwrap()).unwrap(),
1255            CellMasks::Shared(B128::ZERO)
1256        );
1257    }
1258
1259    proptest::proptest! {
1260        #[test]
1261        fn adaptive_masks_serde_roundtrip(values in proptest::collection::vec(proptest::prelude::any::<u128>(), 1..=64)) {
1262            let hashes = (0..values.len()).map(|index| B256::repeat_byte(index as u8)).collect();
1263            let masks = values.into_iter().map(|bits| B128::from(bits.to_le_bytes())).collect();
1264            let request = GetCells::from_masks(hashes, masks).unwrap();
1265            let json = serde_json::to_string(&request).unwrap();
1266            proptest::prop_assert_eq!(&serde_json::from_str::<GetCells>(&json).unwrap(), &request);
1267            let bytes = bincode::serialize(&request).unwrap();
1268            proptest::prop_assert_eq!(bincode::deserialize::<GetCells>(&bytes).unwrap(), request);
1269        }
1270    }
1271}