Skip to main content

reth_primitives_traits/
account.rs

1use crate::InMemorySize;
2use alloy_consensus::constants::KECCAK_EMPTY;
3use alloy_genesis::GenesisAccount;
4use alloy_primitives::{keccak256, Bytes, B256, U256};
5use alloy_trie::TrieAccount;
6use derive_more::Deref;
7use revm_bytecode::{Bytecode as RevmBytecode, BytecodeDecodeError};
8use revm_state::AccountInfo;
9
10#[cfg(any(test, feature = "reth-codec"))]
11/// Identifiers used in [`Compact`](reth_codecs::Compact) encoding of [`Bytecode`].
12pub mod compact_ids {
13    /// Identifier for legacy raw bytecode.
14    pub const LEGACY_RAW_BYTECODE_ID: u8 = 0;
15
16    /// Identifier for removed bytecode variant.
17    pub const REMOVED_BYTECODE_ID: u8 = 1;
18
19    /// Identifier for legacy analyzed bytecode.
20    pub const LEGACY_ANALYZED_BYTECODE_ID: u8 = 2;
21
22    /// Identifier for EIP-7702 bytecode.
23    pub const EIP7702_BYTECODE_ID: u8 = 4;
24}
25
26/// An Ethereum account.
27#[cfg_attr(any(test, feature = "serde"), derive(serde::Serialize, serde::Deserialize))]
28#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
29#[cfg_attr(any(test, feature = "arbitrary"), derive(arbitrary::Arbitrary))]
30#[cfg_attr(any(test, feature = "reth-codec"), derive(reth_codecs::Compact))]
31#[cfg_attr(any(test, feature = "reth-codec"), reth_codecs::add_arbitrary_tests(compact))]
32pub struct Account {
33    /// Account nonce.
34    pub nonce: u64,
35    /// Account balance.
36    pub balance: U256,
37    /// Hash of the account's bytecode.
38    pub bytecode_hash: Option<B256>,
39}
40
41impl Account {
42    /// Whether the account has bytecode.
43    pub const fn has_bytecode(&self) -> bool {
44        self.bytecode_hash.is_some()
45    }
46
47    /// After `SpuriousDragon` empty account is defined as account with nonce == 0 && balance == 0
48    /// && bytecode = None (or hash is [`KECCAK_EMPTY`]).
49    pub fn is_empty(&self) -> bool {
50        self.nonce == 0 &&
51            self.balance.is_zero() &&
52            self.bytecode_hash.is_none_or(|hash| hash == KECCAK_EMPTY)
53    }
54
55    /// Returns an account bytecode's hash.
56    /// In case of no bytecode, returns [`KECCAK_EMPTY`].
57    pub fn get_bytecode_hash(&self) -> B256 {
58        self.bytecode_hash.unwrap_or(KECCAK_EMPTY)
59    }
60
61    /// Converts the account into a trie account with the given storage root.
62    pub fn into_trie_account(self, storage_root: B256) -> TrieAccount {
63        let Self { nonce, balance, bytecode_hash } = self;
64        TrieAccount {
65            nonce,
66            balance,
67            storage_root,
68            code_hash: bytecode_hash.unwrap_or(KECCAK_EMPTY),
69        }
70    }
71
72    /// Extracts the account information from a [`revm_state::Account`]
73    pub fn from_revm_account(revm_account: &revm_state::Account) -> Self {
74        Self {
75            balance: revm_account.info.balance,
76            nonce: revm_account.info.nonce,
77            bytecode_hash: if revm_account.info.code_hash == revm_primitives::KECCAK_EMPTY {
78                None
79            } else {
80                Some(revm_account.info.code_hash)
81            },
82        }
83    }
84}
85
86impl From<revm_state::Account> for Account {
87    fn from(value: revm_state::Account) -> Self {
88        Self::from_revm_account(&value)
89    }
90}
91
92impl From<TrieAccount> for Account {
93    fn from(value: TrieAccount) -> Self {
94        Self {
95            balance: value.balance,
96            nonce: value.nonce,
97            bytecode_hash: (value.code_hash != KECCAK_EMPTY).then_some(value.code_hash),
98        }
99    }
100}
101
102impl InMemorySize for Account {
103    fn size(&self) -> usize {
104        size_of::<Self>()
105    }
106}
107
108/// Bytecode for an account.
109///
110/// A wrapper around [`revm::primitives::Bytecode`][RevmBytecode] with encoding/decoding support.
111#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
112#[derive(Debug, Clone, Default, PartialEq, Eq, Deref)]
113pub struct Bytecode(pub RevmBytecode);
114
115impl Bytecode {
116    /// Create new bytecode from raw bytes.
117    ///
118    /// No analysis will be performed.
119    ///
120    /// # Panics
121    ///
122    /// Panics if bytecode is EOF and has incorrect format.
123    pub fn new_raw(bytes: Bytes) -> Self {
124        Self(RevmBytecode::new_raw(bytes))
125    }
126
127    /// Creates a new raw [`revm_bytecode::Bytecode`].
128    ///
129    /// Returns an error on incorrect Bytecode format.
130    #[inline]
131    pub fn new_raw_checked(bytecode: Bytes) -> Result<Self, BytecodeDecodeError> {
132        RevmBytecode::new_raw_checked(bytecode).map(Self)
133    }
134}
135
136#[cfg(any(test, feature = "reth-codec"))]
137impl reth_codecs::Compact for Bytecode {
138    fn to_compact<B>(&self, buf: &mut B) -> usize
139    where
140        B: bytes::BufMut + AsMut<[u8]>,
141    {
142        use compact_ids::{EIP7702_BYTECODE_ID, LEGACY_ANALYZED_BYTECODE_ID};
143
144        let bytecode = self.0.bytes_ref();
145        buf.put_u32(bytecode.len() as u32);
146        buf.put_slice(bytecode.as_ref());
147        let len = if self.0.is_legacy() {
148            // [`REMOVED_BYTECODE_ID`] has been removed.
149            if let Some(jump_table) = self.0.legacy_jump_table() {
150                buf.put_u8(LEGACY_ANALYZED_BYTECODE_ID);
151                buf.put_u64(self.0.len() as u64);
152                let map = jump_table.as_slice();
153                buf.put_slice(map);
154                1 + 8 + map.len()
155            } else {
156                unreachable!("legacy bytecode must contain a jump table")
157            }
158        } else {
159            buf.put_u8(EIP7702_BYTECODE_ID);
160            1
161        };
162        len + bytecode.len() + 4
163    }
164
165    // # Panics
166    //
167    // A panic will be triggered if a bytecode variant of 1 or greater than 2 is passed from the
168    // database.
169    fn from_compact(mut buf: &[u8], _: usize) -> (Self, &[u8]) {
170        use byteorder::ReadBytesExt;
171        use bytes::Buf;
172
173        use compact_ids::*;
174
175        let len = buf.read_u32::<byteorder::BigEndian>().expect("could not read bytecode length")
176            as usize;
177        let bytes = Bytes::from(buf.copy_to_bytes(len));
178        let variant = buf.read_u8().expect("could not read bytecode variant");
179        let decoded = match variant {
180            LEGACY_RAW_BYTECODE_ID => Self(RevmBytecode::new_raw(bytes)),
181            REMOVED_BYTECODE_ID => {
182                unreachable!("Junk data in database: checked Bytecode variant was removed")
183            }
184            LEGACY_ANALYZED_BYTECODE_ID => {
185                let original_len = buf.read_u64::<byteorder::BigEndian>().unwrap() as usize;
186                // When saving jumptable, its length is getting aligned to u8 boundary. Thus, we
187                // need to re-calculate the internal length of bitvec and truncate it when loading
188                // jumptables to avoid inconsistencies during `Compact` roundtrip.
189                let jump_table_len = if buf.len() * 8 >= bytes.len() {
190                    // Use length of padded bytecode if we can fit it
191                    bytes.len()
192                } else {
193                    // Otherwise, use original_len
194                    original_len
195                };
196                Self(RevmBytecode::new_analyzed(
197                    bytes,
198                    original_len,
199                    revm_bytecode::JumpTable::from_slice(buf, jump_table_len),
200                ))
201            }
202            EIP7702_BYTECODE_ID => {
203                // EIP-7702 bytecode objects will be decoded from the raw bytecode
204                Self(RevmBytecode::new_raw(bytes))
205            }
206            _ => unreachable!("Junk data in database: unknown Bytecode variant"),
207        };
208        (decoded, &[])
209    }
210}
211
212impl From<&GenesisAccount> for Account {
213    fn from(value: &GenesisAccount) -> Self {
214        Self {
215            nonce: value.nonce.unwrap_or_default(),
216            balance: value.balance,
217            bytecode_hash: value.code.as_ref().map(keccak256),
218        }
219    }
220}
221
222impl From<AccountInfo> for Account {
223    fn from(revm_acc: AccountInfo) -> Self {
224        Self {
225            balance: revm_acc.balance,
226            nonce: revm_acc.nonce,
227            bytecode_hash: (!revm_acc.is_empty_code_hash()).then_some(revm_acc.code_hash),
228        }
229    }
230}
231
232impl From<&AccountInfo> for Account {
233    fn from(revm_acc: &AccountInfo) -> Self {
234        Self {
235            balance: revm_acc.balance,
236            nonce: revm_acc.nonce,
237            bytecode_hash: (!revm_acc.is_empty_code_hash()).then_some(revm_acc.code_hash),
238        }
239    }
240}
241
242impl From<Account> for AccountInfo {
243    fn from(reth_acc: Account) -> Self {
244        Self {
245            balance: reth_acc.balance,
246            nonce: reth_acc.nonce,
247            code_hash: reth_acc.bytecode_hash.unwrap_or(KECCAK_EMPTY),
248            code: None,
249            account_id: None,
250        }
251    }
252}
253
254#[cfg(test)]
255mod tests {
256    use super::*;
257    use alloy_primitives::{hex_literal::hex, B256, U256};
258    use reth_codecs::Compact;
259    use revm_bytecode::JumpTable;
260
261    #[test]
262    fn test_account() {
263        let mut buf = vec![];
264        let mut acc = Account::default();
265        let len = acc.to_compact(&mut buf);
266        assert_eq!(len, 2);
267
268        acc.balance = U256::from(2);
269        let len = acc.to_compact(&mut buf);
270        assert_eq!(len, 3);
271
272        acc.nonce = 2;
273        let len = acc.to_compact(&mut buf);
274        assert_eq!(len, 4);
275    }
276
277    #[test]
278    fn test_empty_account() {
279        let mut acc = Account { nonce: 0, balance: U256::ZERO, bytecode_hash: None };
280        // Nonce 0, balance 0, and bytecode hash set to None is considered empty.
281        assert!(acc.is_empty());
282
283        acc.bytecode_hash = Some(KECCAK_EMPTY);
284        // Nonce 0, balance 0, and bytecode hash set to KECCAK_EMPTY is considered empty.
285        assert!(acc.is_empty());
286
287        acc.balance = U256::from(2);
288        // Non-zero balance makes it non-empty.
289        assert!(!acc.is_empty());
290
291        acc.balance = U256::ZERO;
292        acc.nonce = 10;
293        // Non-zero nonce makes it non-empty.
294        assert!(!acc.is_empty());
295
296        acc.nonce = 0;
297        acc.bytecode_hash = Some(B256::from(U256::ZERO));
298        // Non-empty bytecode hash makes it non-empty.
299        assert!(!acc.is_empty());
300    }
301
302    #[test]
303    #[ignore]
304    fn test_bytecode() {
305        let mut buf = vec![];
306        let bytecode = Bytecode::new_raw(Bytes::default());
307        let len = bytecode.to_compact(&mut buf);
308        assert_eq!(len, 14);
309
310        let mut buf = vec![];
311        let bytecode = Bytecode::new_raw(Bytes::from(&hex!("ffff")));
312        let len = bytecode.to_compact(&mut buf);
313        assert_eq!(len, 17);
314
315        let mut buf = vec![];
316        let bytecode = Bytecode(RevmBytecode::new_analyzed(
317            Bytes::from(&hex!("ff00")),
318            2,
319            JumpTable::from_slice(&[0], 2),
320        ));
321        let len = bytecode.to_compact(&mut buf);
322        assert_eq!(len, 16);
323
324        let (decoded, remainder) = Bytecode::from_compact(&buf, len);
325        assert_eq!(decoded, bytecode);
326        assert!(remainder.is_empty());
327    }
328
329    #[test]
330    fn test_account_has_bytecode() {
331        // Account with no bytecode (None)
332        let acc_no_bytecode = Account { nonce: 1, balance: U256::from(1000), bytecode_hash: None };
333        assert!(!acc_no_bytecode.has_bytecode(), "Account should not have bytecode");
334
335        // Account with bytecode hash set to KECCAK_EMPTY (should have bytecode)
336        let acc_empty_bytecode =
337            Account { nonce: 1, balance: U256::from(1000), bytecode_hash: Some(KECCAK_EMPTY) };
338        assert!(acc_empty_bytecode.has_bytecode(), "Account should have bytecode");
339
340        // Account with a non-empty bytecode hash
341        let acc_with_bytecode = Account {
342            nonce: 1,
343            balance: U256::from(1000),
344            bytecode_hash: Some(B256::from_slice(&[0x11u8; 32])),
345        };
346        assert!(acc_with_bytecode.has_bytecode(), "Account should have bytecode");
347    }
348
349    #[test]
350    fn test_account_get_bytecode_hash() {
351        // Account with no bytecode (should return KECCAK_EMPTY)
352        let acc_no_bytecode = Account { nonce: 0, balance: U256::ZERO, bytecode_hash: None };
353        assert_eq!(acc_no_bytecode.get_bytecode_hash(), KECCAK_EMPTY, "Should return KECCAK_EMPTY");
354
355        // Account with bytecode hash set to KECCAK_EMPTY
356        let acc_empty_bytecode =
357            Account { nonce: 1, balance: U256::from(1000), bytecode_hash: Some(KECCAK_EMPTY) };
358        assert_eq!(
359            acc_empty_bytecode.get_bytecode_hash(),
360            KECCAK_EMPTY,
361            "Should return KECCAK_EMPTY"
362        );
363
364        // Account with a valid bytecode hash
365        let bytecode_hash = B256::from_slice(&[0x11u8; 32]);
366        let acc_with_bytecode =
367            Account { nonce: 1, balance: U256::from(1000), bytecode_hash: Some(bytecode_hash) };
368        assert_eq!(
369            acc_with_bytecode.get_bytecode_hash(),
370            bytecode_hash,
371            "Should return the bytecode hash"
372        );
373    }
374}