Skip to main content

reth_eth_wire_types/snap/
messages.rs

1//! Request and response messages of the snap/2 protocol.
2
3use crate::{snap::AccountData, BlockAccessLists};
4use alloc::vec::Vec;
5use alloy_primitives::{Bytes, B256, U256};
6use alloy_rlp::{BufMut, Decodable, Encodable, RlpDecodable, RlpEncodable};
7use reth_codecs_derive::add_arbitrary_tests;
8
9/// Request for a range of accounts from the state trie.
10// https://github.com/ethereum/devp2p/blob/master/caps/snap.md#getaccountrange-0x00
11#[derive(Debug, Clone, PartialEq, Eq, RlpEncodable, RlpDecodable)]
12#[cfg_attr(any(test, feature = "arbitrary"), derive(arbitrary::Arbitrary))]
13#[add_arbitrary_tests(rlp)]
14pub struct GetAccountRangeMessage {
15    /// Request ID to match up responses with
16    pub request_id: u64,
17    /// Root hash of the account trie to serve
18    pub root_hash: B256,
19    /// Account hash of the first to retrieve
20    pub starting_hash: B256,
21    /// Account hash after which to stop serving data
22    pub limit_hash: B256,
23    /// Soft limit at which to stop returning data
24    pub response_bytes: u64,
25}
26
27/// Response containing a number of consecutive accounts and the Merkle proofs for the entire range.
28// http://github.com/ethereum/devp2p/blob/master/caps/snap.md#accountrange-0x01
29#[derive(Debug, Clone, PartialEq, Eq, RlpEncodable, RlpDecodable)]
30#[cfg_attr(any(test, feature = "arbitrary"), derive(arbitrary::Arbitrary))]
31#[add_arbitrary_tests(rlp)]
32pub struct AccountRangeMessage {
33    /// ID of the request this is a response for
34    pub request_id: u64,
35    /// List of consecutive accounts from the trie
36    pub accounts: Vec<AccountData>,
37    /// List of trie nodes proving the account range
38    pub proof: Vec<Bytes>,
39}
40
41/// Request for the storage slots of multiple accounts' storage tries.
42// https://github.com/ethereum/devp2p/blob/master/caps/snap.md#getstorageranges-0x02
43#[derive(Debug, Clone, PartialEq, Eq, RlpEncodable, RlpDecodable)]
44#[cfg_attr(any(test, feature = "arbitrary"), derive(arbitrary::Arbitrary))]
45#[add_arbitrary_tests(rlp)]
46pub struct GetStorageRangesMessage {
47    /// Request ID to match up responses with
48    pub request_id: u64,
49    /// Root hash of the account trie to serve
50    pub root_hash: B256,
51    /// Account hashes of the storage tries to serve
52    pub account_hashes: Vec<B256>,
53    /// Storage slot hash of the first to retrieve; unbounded (served as `B256::ZERO`) when the
54    /// wire encoding is an empty byte string.
55    pub starting_hash: RangeBound,
56    /// Storage slot hash after which to stop serving; unbounded (served as
57    /// `B256::repeat_byte(0xff)`) when the wire encoding is an empty byte string.
58    pub limit_hash: RangeBound,
59    /// Soft limit at which to stop returning data
60    pub response_bytes: u64,
61}
62
63/// A `snap/2` storage-range bound (`origin`/`limit` on [`GetStorageRangesMessage`]).
64///
65/// Encoded as either an empty byte string (unbounded) or a 32-byte hash.
66#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
67#[cfg_attr(any(test, feature = "arbitrary"), derive(arbitrary::Arbitrary))]
68pub struct RangeBound(Option<B256>);
69
70impl RangeBound {
71    /// Returns the bound's hash, or `default` if it was encoded as an empty byte string.
72    pub const fn unwrap_or(self, default: B256) -> B256 {
73        match self.0 {
74            Some(hash) => hash,
75            None => default,
76        }
77    }
78}
79
80impl From<B256> for RangeBound {
81    fn from(hash: B256) -> Self {
82        Self(Some(hash))
83    }
84}
85
86impl Encodable for RangeBound {
87    fn encode(&self, out: &mut dyn BufMut) {
88        match self.0 {
89            Some(hash) => hash.encode(out),
90            None => Bytes::new().encode(out),
91        }
92    }
93
94    fn length(&self) -> usize {
95        match self.0 {
96            Some(hash) => hash.length(),
97            None => Bytes::new().length(),
98        }
99    }
100}
101
102impl Decodable for RangeBound {
103    fn decode(buf: &mut &[u8]) -> alloy_rlp::Result<Self> {
104        let bytes = Bytes::decode(buf)?;
105        match bytes.len() {
106            0 => Ok(Self(None)),
107            32 => Ok(Self(Some(B256::from_slice(&bytes)))),
108            _ => Err(alloy_rlp::Error::UnexpectedLength),
109        }
110    }
111}
112
113/// Storage slot data in the response.
114#[derive(Debug, Clone, PartialEq, Eq, RlpEncodable, RlpDecodable)]
115#[cfg_attr(any(test, feature = "arbitrary"), derive(arbitrary::Arbitrary))]
116#[add_arbitrary_tests(rlp)]
117pub struct StorageData {
118    /// Hash of the storage slot key (trie path)
119    pub hash: B256,
120    /// Data content of the slot
121    pub data: Bytes,
122}
123
124impl StorageData {
125    /// Encodes a slot value as the storage trie leaf commits to it.
126    pub fn from_value(hash: B256, value: U256) -> Self {
127        Self { hash, data: alloy_rlp::encode(value).into() }
128    }
129
130    /// Decodes the slot value.
131    pub fn value(&self) -> alloy_rlp::Result<U256> {
132        alloy_rlp::decode_exact(&self.data)
133    }
134}
135
136/// Response containing a number of consecutive storage slots for the requested account
137/// and optionally the merkle proofs for the last range (boundary proofs) if it only partially
138/// covers the storage trie.
139// https://github.com/ethereum/devp2p/blob/master/caps/snap.md#storageranges-0x03
140#[derive(Debug, Clone, PartialEq, Eq, RlpEncodable, RlpDecodable)]
141#[cfg_attr(any(test, feature = "arbitrary"), derive(arbitrary::Arbitrary))]
142#[add_arbitrary_tests(rlp)]
143pub struct StorageRangesMessage {
144    /// ID of the request this is a response for
145    pub request_id: u64,
146    /// List of list of consecutive slots from the trie (one list per account)
147    pub slots: Vec<Vec<StorageData>>,
148    /// List of trie nodes proving the slot range (if partial)
149    pub proof: Vec<Bytes>,
150}
151
152/// Request to get a number of requested contract codes.
153// https://github.com/ethereum/devp2p/blob/master/caps/snap.md#getbytecodes-0x04
154#[derive(Debug, Clone, PartialEq, Eq, RlpEncodable, RlpDecodable)]
155#[cfg_attr(any(test, feature = "arbitrary"), derive(arbitrary::Arbitrary))]
156#[add_arbitrary_tests(rlp)]
157pub struct GetByteCodesMessage {
158    /// Request ID to match up responses with
159    pub request_id: u64,
160    /// Code hashes to retrieve the code for
161    pub hashes: Vec<B256>,
162    /// Soft limit at which to stop returning data (in bytes)
163    pub response_bytes: u64,
164}
165
166/// Response containing a number of requested contract codes.
167// https://github.com/ethereum/devp2p/blob/master/caps/snap.md#bytecodes-0x05
168#[derive(Debug, Clone, PartialEq, Eq, RlpEncodable, RlpDecodable)]
169#[cfg_attr(any(test, feature = "arbitrary"), derive(arbitrary::Arbitrary))]
170#[add_arbitrary_tests(rlp)]
171pub struct ByteCodesMessage {
172    /// ID of the request this is a response for
173    pub request_id: u64,
174    /// The requested bytecodes in order
175    pub codes: Vec<Bytes>,
176}
177
178/// Request BALs for the given block hashes.
179#[derive(Debug, Clone, PartialEq, Eq, RlpEncodable, RlpDecodable)]
180#[cfg_attr(any(test, feature = "arbitrary"), derive(arbitrary::Arbitrary))]
181#[add_arbitrary_tests(rlp)]
182pub struct GetBlockAccessListsMessage {
183    /// Request ID to match up responses with.
184    pub request_id: u64,
185    /// Block hashes to retrieve BALs for.
186    pub block_hashes: Vec<B256>,
187    /// Soft limit at which to stop returning data (in bytes).
188    pub response_bytes: u64,
189}
190
191/// Response containing one BAL per requested block hash.
192#[derive(Debug, Clone, PartialEq, Eq, RlpEncodable, RlpDecodable)]
193#[cfg_attr(any(test, feature = "arbitrary"), derive(arbitrary::Arbitrary))]
194#[add_arbitrary_tests(rlp)]
195pub struct BlockAccessListsMessage {
196    /// ID of the request this is a response for.
197    pub request_id: u64,
198    /// Raw BAL payloads in request order.
199    pub block_access_lists: BlockAccessLists,
200}
201
202#[cfg(test)]
203mod tests {
204    use super::*;
205
206    #[test]
207    fn storage_data_rejects_trailing_bytes() {
208        let mut slot = StorageData::from_value(B256::repeat_byte(4), U256::ONE);
209        slot.data = [slot.data.as_ref(), &[0x00]].concat().into();
210
211        assert!(slot.value().is_err());
212    }
213}