-
Notifications
You must be signed in to change notification settings - Fork 207
Expand file tree
/
Copy pathaccount.rs
More file actions
399 lines (358 loc) · 11.9 KB
/
Copy pathaccount.rs
File metadata and controls
399 lines (358 loc) · 11.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
use std::collections::BTreeMap;
use bytes::{BufMut, Bytes};
use ethereum_types::{H256, U256};
use ethrex_crypto::keccak::keccak_hash;
use ethrex_trie::Trie;
use rustc_hash::FxHashMap;
use serde::{Deserialize, Serialize};
use ethrex_rlp::{
decode::RLPDecode,
encode::RLPEncode,
error::RLPDecodeError,
structs::{Decoder, Encoder},
};
use super::GenesisAccount;
use crate::{
constants::{EMPTY_KECCACK_HASH, EMPTY_TRIE_HASH},
utils::keccak,
};
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Hash)]
pub struct Code {
// hash is only used for bytecodes stored in the DB, either for reading it from the DB
// or with the CODEHASH opcode, which needs an account address as argument and
// thus only accessed persisted bytecodes.
// We use a bogus H256::zero() value for initcodes as there is no way for the VM or
// endpoints to access that hash, saving one expensive Keccak hash.
pub hash: H256,
pub bytecode: Bytes,
// TODO: Consider using Arc<[u32]> (needs to enable serde rc feature)
// The valid addresses are 32-bit because, despite EIP-3860 restricting initcode size,
// this does not apply to previous forks. This is tested in the EEST tests, which would
// panic in debug mode.
pub jump_targets: Vec<u32>,
}
impl Code {
// SAFETY: hash will be stored as-is, so it either needs to match
// the real code hash (i.e. it was precomputed and we're reusing)
// or never be read (e.g. for initcode).
pub fn from_bytecode_unchecked(code: Bytes, hash: H256) -> Self {
let jump_targets = Self::compute_jump_targets(&code);
Self {
hash,
bytecode: code,
jump_targets,
}
}
pub fn from_bytecode(code: Bytes) -> Self {
let jump_targets = Self::compute_jump_targets(&code);
Self {
hash: keccak(code.as_ref()),
bytecode: code,
jump_targets,
}
}
fn compute_jump_targets(code: &[u8]) -> Vec<u32> {
debug_assert!(code.len() <= u32::MAX as usize);
let mut targets = Vec::new();
let mut i = 0;
while i < code.len() {
// TODO: we don't use the constants from the vm module to avoid a circular dependency
match code[i] {
// OP_JUMPDEST
0x5B => {
targets.push(i as u32);
}
// OP_PUSH1..32
c @ 0x60..0x80 => {
// OP_PUSH0
i += (c - 0x5F) as usize;
}
_ => (),
}
i += 1;
}
targets
}
/// Estimates the size of the Code struct in bytes
/// (including stack size and heap allocation).
///
/// Note: This is an estimation and may not be exact.
///
/// # Returns
///
/// usize - Estimated size in bytes
pub fn size(&self) -> usize {
let hash_size = size_of::<H256>();
let bytes_size = size_of::<Bytes>();
let vec_size = size_of::<Vec<u32>>() + self.jump_targets.len() * size_of::<u32>();
hash_size + bytes_size + vec_size
}
}
impl AsRef<Bytes> for Code {
fn as_ref(&self) -> &Bytes {
&self.bytecode
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct CodeMetadata {
pub length: u64,
}
#[derive(Clone, Default, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Account {
pub info: AccountInfo,
pub code: Code,
pub storage: FxHashMap<H256, U256>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Eq, Hash)]
pub struct AccountInfo {
pub code_hash: H256,
pub balance: U256,
pub nonce: u64,
}
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
pub struct AccountState {
pub nonce: u64,
pub balance: U256,
pub storage_root: H256,
pub code_hash: H256,
}
/// A slim codec for an [`AccountState`].
///
/// The slim codec will optimize both the [storage root](AccountState::storage_root) and the
/// [code hash](AccountState::code_hash)'s encoding so that it does not take space when empty.
///
/// The correct way to use it is to wrap the [`AccountState`] and encode it using this codec, and
/// not to store the codec as a field in a struct.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct AccountStateSlimCodec(pub AccountState);
impl Default for AccountInfo {
fn default() -> Self {
Self {
code_hash: *EMPTY_KECCACK_HASH,
balance: Default::default(),
nonce: Default::default(),
}
}
}
impl Default for AccountState {
fn default() -> Self {
Self {
nonce: Default::default(),
balance: Default::default(),
storage_root: *EMPTY_TRIE_HASH,
code_hash: *EMPTY_KECCACK_HASH,
}
}
}
impl Default for Code {
fn default() -> Self {
Self {
bytecode: Bytes::new(),
hash: *EMPTY_KECCACK_HASH,
jump_targets: Vec::new(),
}
}
}
impl From<GenesisAccount> for Account {
fn from(genesis: GenesisAccount) -> Self {
let code = Code::from_bytecode(genesis.code);
Self {
info: AccountInfo {
code_hash: code.hash,
balance: genesis.balance,
nonce: genesis.nonce,
},
code,
storage: genesis
.storage
.iter()
.map(|(k, v)| (H256(k.to_big_endian()), *v))
.collect(),
}
}
}
pub fn code_hash(code: &Bytes) -> H256 {
keccak(code.as_ref())
}
impl RLPEncode for AccountInfo {
fn encode(&self, buf: &mut dyn bytes::BufMut) {
Encoder::new(buf)
.encode_field(&self.code_hash)
.encode_field(&self.balance)
.encode_field(&self.nonce)
.finish();
}
}
impl RLPDecode for AccountInfo {
fn decode_unfinished(rlp: &[u8]) -> Result<(AccountInfo, &[u8]), RLPDecodeError> {
let decoder = Decoder::new(rlp)?;
let (code_hash, decoder) = decoder.decode_field("code_hash")?;
let (balance, decoder) = decoder.decode_field("balance")?;
let (nonce, decoder) = decoder.decode_field("nonce")?;
let account_info = AccountInfo {
code_hash,
balance,
nonce,
};
Ok((account_info, decoder.finish()?))
}
}
impl RLPEncode for AccountState {
fn encode(&self, buf: &mut dyn bytes::BufMut) {
Encoder::new(buf)
.encode_field(&self.nonce)
.encode_field(&self.balance)
.encode_field(&self.storage_root)
.encode_field(&self.code_hash)
.finish();
}
}
impl RLPDecode for AccountState {
fn decode_unfinished(rlp: &[u8]) -> Result<(AccountState, &[u8]), RLPDecodeError> {
let decoder = Decoder::new(rlp)?;
let (nonce, decoder) = decoder.decode_field("nonce")?;
let (balance, decoder) = decoder.decode_field("balance")?;
let (storage_root, decoder) = decoder.decode_field("storage_root")?;
let (code_hash, decoder) = decoder.decode_field("code_hash")?;
let state = AccountState {
nonce,
balance,
storage_root,
code_hash,
};
Ok((state, decoder.finish()?))
}
}
impl RLPEncode for AccountStateSlimCodec {
fn encode(&self, buf: &mut dyn BufMut) {
struct StorageRootCodec<'a>(&'a H256);
impl RLPEncode for StorageRootCodec<'_> {
fn encode(&self, buf: &mut dyn BufMut) {
let data = if *self.0 != *EMPTY_TRIE_HASH {
self.0.as_bytes()
} else {
&[]
};
data.encode(buf);
}
}
struct CodeHashCodec<'a>(&'a H256);
impl RLPEncode for CodeHashCodec<'_> {
fn encode(&self, buf: &mut dyn BufMut) {
let data = if *self.0 != *EMPTY_KECCACK_HASH {
self.0.as_bytes()
} else {
&[]
};
data.encode(buf);
}
}
Encoder::new(buf)
.encode_field(&self.0.nonce)
.encode_field(&self.0.balance)
.encode_field(&StorageRootCodec(&self.0.storage_root))
.encode_field(&CodeHashCodec(&self.0.code_hash))
.finish();
}
}
impl RLPDecode for AccountStateSlimCodec {
fn decode_unfinished(rlp: &[u8]) -> Result<(Self, &[u8]), RLPDecodeError> {
struct StorageRootCodec(H256);
impl RLPDecode for StorageRootCodec {
fn decode_unfinished(mut rlp: &[u8]) -> Result<(Self, &[u8]), RLPDecodeError> {
let value = match rlp.split_off_first() {
Some(0x80) => *EMPTY_TRIE_HASH,
Some(0xA0) => {
let data;
(data, rlp) = rlp
.split_first_chunk::<32>()
.ok_or(RLPDecodeError::invalid_length())?;
H256(*data)
}
_ => return Err(RLPDecodeError::invalid_length()),
};
Ok((Self(value), rlp))
}
}
struct CodeHashCodec(H256);
impl RLPDecode for CodeHashCodec {
fn decode_unfinished(mut rlp: &[u8]) -> Result<(Self, &[u8]), RLPDecodeError> {
let value = match rlp.split_off_first() {
Some(0x80) => *EMPTY_KECCACK_HASH,
Some(0xA0) => {
let data;
(data, rlp) = rlp
.split_first_chunk::<32>()
.ok_or(RLPDecodeError::invalid_length())?;
H256(*data)
}
_ => return Err(RLPDecodeError::invalid_length()),
};
Ok((Self(value), rlp))
}
}
let decoder = Decoder::new(rlp)?;
let (nonce, decoder) = decoder.decode_field("nonce")?;
let (balance, decoder) = decoder.decode_field("balance")?;
let (StorageRootCodec(storage_root), decoder) = decoder.decode_field("storage_root")?;
let (CodeHashCodec(code_hash), decoder) = decoder.decode_field("code_hash")?;
Ok((
Self(AccountState {
nonce,
balance,
storage_root,
code_hash,
}),
decoder.finish()?,
))
}
}
pub fn compute_storage_root(storage: &BTreeMap<U256, U256>) -> H256 {
let iter = storage.iter().filter_map(|(k, v)| {
(!v.is_zero()).then_some((keccak_hash(k.to_big_endian()).to_vec(), v.encode_to_vec()))
});
Trie::compute_hash_from_unsorted_iter(iter)
}
impl From<&GenesisAccount> for AccountState {
fn from(value: &GenesisAccount) -> Self {
AccountState {
nonce: value.nonce,
balance: value.balance,
storage_root: compute_storage_root(&value.storage),
code_hash: code_hash(&value.code),
}
}
}
impl Account {
pub fn new(balance: U256, code: Code, nonce: u64, storage: FxHashMap<H256, U256>) -> Self {
Self {
info: AccountInfo {
balance,
code_hash: code.hash,
nonce,
},
code,
storage,
}
}
}
impl AccountInfo {
pub fn is_empty(&self) -> bool {
self.balance.is_zero() && self.nonce == 0 && self.code_hash == *EMPTY_KECCACK_HASH
}
}
#[cfg(test)]
mod test {
use std::str::FromStr;
use super::*;
#[test]
fn test_code_hash() {
let empty_code = Bytes::new();
let hash = code_hash(&empty_code);
assert_eq!(
hash,
H256::from_str("c5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470")
.unwrap()
)
}
}