Skip to main content

reth_eth_wire_types/snap/
account.rs

1//! Account data of the snap/2 protocol and its slim trie account encoding.
2
3use alloc::borrow::ToOwned;
4use alloy_primitives::{B256, KECCAK256_EMPTY, U256};
5use alloy_rlp::{BufMut, Decodable, Encodable, Header, RlpDecodable, RlpEncodable};
6use alloy_trie::{TrieAccount, EMPTY_ROOT_HASH};
7use reth_codecs_derive::add_arbitrary_tests;
8
9/// Account data in the response.
10#[derive(Debug, Clone, PartialEq, Eq, RlpEncodable, RlpDecodable)]
11#[cfg_attr(any(test, feature = "arbitrary"), derive(arbitrary::Arbitrary))]
12#[add_arbitrary_tests(rlp)]
13pub struct AccountData {
14    /// Hash of the account address (trie path)
15    pub hash: B256,
16    /// Account fields encoded as a nested RLP list with default hashes elided.
17    pub body: SlimAccountBody,
18}
19
20impl AccountData {
21    /// Converts `account` to snap/2's slim representation.
22    pub fn from_trie_account(hash: B256, account: &TrieAccount) -> Self {
23        Self { hash, body: account.into() }
24    }
25
26    /// Returns the account the trie leaf commits to.
27    ///
28    /// Default storage roots and code hashes are restored when decoding the slim body.
29    pub const fn trie_account(&self) -> &TrieAccount {
30        &self.body.0
31    }
32
33    /// Consumes the wire value and returns its hashed key with the decoded trie account.
34    pub fn into_trie_entry(self) -> (B256, TrieAccount) {
35        (self.hash, self.body.into())
36    }
37}
38
39/// A trie account encoded with default storage and code hashes replaced by empty byte strings.
40#[derive(Debug, Clone, PartialEq, Eq)]
41pub struct SlimAccountBody(TrieAccount);
42
43impl SlimAccountBody {
44    fn as_rlp(&self) -> SlimAccountBodyRef<'_> {
45        SlimAccountBodyRef {
46            nonce: self.0.nonce,
47            balance: self.0.balance,
48            storage_root: SlimAccountBodyRef::shorten(&self.0.storage_root, EMPTY_ROOT_HASH),
49            code_hash: SlimAccountBodyRef::shorten(&self.0.code_hash, KECCAK256_EMPTY),
50        }
51    }
52
53    /// Restores a dropped field to `empty`, rejecting any length the encoding never produces.
54    fn restore(value: &[u8], empty: B256) -> alloy_rlp::Result<B256> {
55        match value {
56            [] => Ok(empty),
57            _ => B256::try_from(value).map_err(|_| alloy_rlp::Error::UnexpectedLength),
58        }
59    }
60}
61
62impl From<&TrieAccount> for SlimAccountBody {
63    fn from(account: &TrieAccount) -> Self {
64        Self(account.to_owned())
65    }
66}
67
68impl From<SlimAccountBody> for TrieAccount {
69    fn from(body: SlimAccountBody) -> Self {
70        body.0
71    }
72}
73
74impl Encodable for SlimAccountBody {
75    fn encode(&self, out: &mut dyn BufMut) {
76        self.as_rlp().encode(out);
77    }
78
79    fn length(&self) -> usize {
80        self.as_rlp().length()
81    }
82}
83
84impl Decodable for SlimAccountBody {
85    fn decode(buf: &mut &[u8]) -> alloy_rlp::Result<Self> {
86        let mut payload = Header::decode_bytes(buf, true)?;
87        let nonce = u64::decode(&mut payload)?;
88        let balance = U256::decode(&mut payload)?;
89        let storage_root =
90            Self::restore(Header::decode_bytes(&mut payload, false)?, EMPTY_ROOT_HASH)?;
91        let code_hash = Self::restore(Header::decode_bytes(&mut payload, false)?, KECCAK256_EMPTY)?;
92        if !payload.is_empty() {
93            return Err(alloy_rlp::Error::UnexpectedLength)
94        }
95        Ok(Self(TrieAccount::new(nonce, balance, storage_root, code_hash)))
96    }
97}
98
99#[cfg(any(test, feature = "arbitrary"))]
100impl<'a> arbitrary::Arbitrary<'a> for SlimAccountBody {
101    fn arbitrary(u: &mut arbitrary::Unstructured<'a>) -> arbitrary::Result<Self> {
102        let storage_root = if u.arbitrary()? { u.arbitrary()? } else { EMPTY_ROOT_HASH };
103        let code_hash = if u.arbitrary()? { u.arbitrary()? } else { KECCAK256_EMPTY };
104        Ok(Self(TrieAccount::new(u.arbitrary()?, u.arbitrary()?, storage_root, code_hash)))
105    }
106}
107
108/// Borrowed encode twin of [`SlimAccountBody`].
109#[derive(RlpEncodable)]
110struct SlimAccountBodyRef<'a> {
111    /// The account's nonce.
112    nonce: u64,
113    /// The account's balance.
114    balance: U256,
115    /// Empty when the account has no storage.
116    storage_root: &'a [u8],
117    /// Empty when the account has no code.
118    code_hash: &'a [u8],
119}
120
121impl<'a> SlimAccountBodyRef<'a> {
122    /// Drops a field that holds its empty default, which is what makes the encoding slim.
123    fn shorten(value: &'a B256, empty: B256) -> &'a [u8] {
124        if *value == empty {
125            &[]
126        } else {
127            value.as_slice()
128        }
129    }
130}
131
132#[cfg(test)]
133mod tests {
134    use super::*;
135    use crate::snap::AccountRangeMessage;
136    use test_case::test_case;
137
138    fn trie_account(storage_root: B256, code_hash: B256) -> TrieAccount {
139        TrieAccount::new(7, U256::from(42), storage_root, code_hash)
140    }
141
142    #[test]
143    fn account_range_matches_nested_account_wire_encoding() {
144        // [request_id, [[hash, [nonce, balance, storage_root, code_hash]]], proof]
145        let wire = alloy_primitives::hex!(
146            "ea01e7e6a00101010101010101010101010101010101010101010101010101010101010101c4072a8080c0"
147        );
148        let message = AccountRangeMessage {
149            request_id: 1,
150            accounts: vec![AccountData::from_trie_account(
151                B256::repeat_byte(1),
152                &trie_account(EMPTY_ROOT_HASH, KECCAK256_EMPTY),
153            )],
154            proof: vec![],
155        };
156
157        assert_eq!(alloy_rlp::encode(&message), wire);
158        assert_eq!(alloy_rlp::decode_exact::<AccountRangeMessage>(&wire).unwrap(), message);
159    }
160
161    #[test]
162    fn account_data_rejects_byte_string_wrapped_body() {
163        let wire = alloy_primitives::hex!(
164            "e7a0010101010101010101010101010101010101010101010101010101010101010185c4072a8080"
165        );
166        assert!(alloy_rlp::decode_exact::<AccountData>(&wire).is_err());
167    }
168
169    #[test]
170    fn account_data_consumes_only_its_own_list() {
171        let account = AccountData::from_trie_account(
172            B256::repeat_byte(1),
173            &trie_account(B256::repeat_byte(2), B256::repeat_byte(3)),
174        );
175        let mut wire = alloy_rlp::encode(&account);
176        assert_eq!(wire.len(), account.length());
177        wire.push(0x80);
178        let mut input = wire.as_slice();
179        assert_eq!(AccountData::decode(&mut input).unwrap(), account);
180        assert_eq!(input, &[0x80]);
181    }
182
183    #[test]
184    fn account_data_rejects_missing_truncated_and_extra_body_items() {
185        for wire in [
186            "e1a00101010101010101010101010101010101010101010101010101010101010101",
187            "e4a00101010101010101010101010101010101010101010101010101010101010101c4072a",
188            "e7a00101010101010101010101010101010101010101010101010101010101010101c4072a808080",
189        ] {
190            let bytes = alloy_primitives::hex::decode(wire).unwrap();
191            assert!(alloy_rlp::decode_exact::<AccountData>(&bytes).is_err());
192        }
193    }
194
195    #[test]
196    fn slim_body_elides_empty_storage_and_code() {
197        let account = trie_account(EMPTY_ROOT_HASH, KECCAK256_EMPTY);
198        let hash = B256::repeat_byte(1);
199        let encoded = AccountData::from_trie_account(hash, &account);
200
201        let body = alloy_rlp::encode(&encoded.body);
202        assert_eq!(body, alloy_primitives::hex!("c4072a8080"));
203        assert_eq!(alloy_rlp::decode_exact::<SlimAccountBody>(&body).unwrap(), encoded.body);
204        assert_eq!(encoded.trie_account(), &account);
205        assert_eq!(encoded.into_trie_entry(), (hash, account));
206    }
207
208    #[test]
209    fn slim_body_keeps_non_default_storage_and_code() {
210        let account = trie_account(B256::repeat_byte(2), B256::repeat_byte(3));
211        let encoded = AccountData::from_trie_account(B256::repeat_byte(1), &account);
212
213        let body = alloy_rlp::encode(&encoded.body);
214        let mut expected = Vec::new();
215        account.encode(&mut expected);
216        assert_eq!(body, expected);
217        assert_eq!(alloy_rlp::decode_exact::<SlimAccountBody>(&body).unwrap(), encoded.body);
218        assert_eq!(encoded.trie_account(), &account);
219    }
220
221    #[test_case(1)]
222    #[test_case(16)]
223    #[test_case(31)]
224    #[test_case(33)]
225    fn slim_body_rejects_invalid_hash_lengths(len: usize) {
226        let invalid = vec![0xaa; len];
227        for (storage_root, code_hash) in
228            [(invalid.as_slice(), &[][..]), (&[][..], invalid.as_slice())]
229        {
230            let body = alloy_rlp::encode(SlimAccountBodyRef {
231                nonce: 7,
232                balance: U256::from(42),
233                storage_root,
234                code_hash,
235            });
236            assert_eq!(
237                alloy_rlp::decode_exact::<SlimAccountBody>(&body),
238                Err(alloy_rlp::Error::UnexpectedLength)
239            );
240        }
241    }
242
243    #[test_case("c0")]
244    #[test_case("c3072a80")]
245    #[test_case("c5072a808080")]
246    #[test_case("c4072a808000")]
247    fn slim_body_rejects_missing_and_extra_fields(wire: &str) {
248        let bytes = alloy_primitives::hex::decode(wire).unwrap();
249        assert!(alloy_rlp::decode_exact::<SlimAccountBody>(&bytes).is_err());
250    }
251}