-
Notifications
You must be signed in to change notification settings - Fork 648
/
Copy pathenv.rs
562 lines (510 loc) · 19.6 KB
/
env.rs
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
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
use crate::{
alloc::vec::Vec, calc_blob_fee, Account, EVMError, InvalidTransaction, Spec, SpecId, B160,
B256, GAS_PER_BLOB, KECCAK_EMPTY, MAX_INITCODE_SIZE, U256,
};
use bytes::Bytes;
use core::cmp::{min, Ordering};
#[derive(Clone, Debug, Default, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Env {
pub cfg: CfgEnv,
pub block: BlockEnv,
pub tx: TxEnv,
}
/// The block environment.
#[derive(Clone, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct BlockEnv {
/// The number of ancestor blocks of this block (block height).
pub number: U256,
/// Coinbase or miner or address that created and signed the block.
///
/// This is the receiver address of all the gas spent in the block.
pub coinbase: B160,
/// The timestamp of the block in seconds since the UNIX epoch.
pub timestamp: U256,
/// The gas limit of the block.
pub gas_limit: U256,
/// The base fee per gas, added in the London upgrade with [EIP-1559].
///
/// [EIP-1559]: https://eips.ethereum.org/EIPS/eip-1559
pub basefee: U256,
/// The difficulty of the block.
///
/// Unused after the Paris (AKA the merge) upgrade, and replaced by `prevrandao`.
pub difficulty: U256,
/// The output of the randomness beacon provided by the beacon chain.
///
/// Replaces `difficulty` after the Paris (AKA the merge) upgrade with [EIP-4399].
///
/// NOTE: `prevrandao` can be found in a block in place of `mix_hash`.
///
/// [EIP-4399]: https://eips.ethereum.org/EIPS/eip-4399
pub prevrandao: Option<B256>,
/// Excess blob gas and blob fee.
/// See also [`calc_excess_blob_gas`](crate::calc_excess_blob_gas)
///
/// Incorporated as part of the Cancun upgrade via [EIP-4844].
///
/// [EIP-4844]: https://eips.ethereum.org/EIPS/eip-4844
pub blob_gas_and_fee: Option<BlobGasAndFee>,
}
/// Structure holding block blob excess gas and it calculates blob fee.
///
/// Incorporated as part of the Cancun upgrade via [EIP-4844].
///
/// [EIP-4844]: https://eips.ethereum.org/EIPS/eip-4844
#[derive(Clone, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct BlobGasAndFee {
pub excess_blob_gas: u64,
pub blob_fee: u64,
}
impl BlobGasAndFee {
/// Takes excess blob gas and calculated blob fee with [`calc_blob_fee`]
pub fn new(excess_blob_gas: u64) -> Self {
let blob_fee = calc_blob_fee(excess_blob_gas);
Self {
excess_blob_gas,
blob_fee,
}
}
}
impl BlockEnv {
/// Takes `blob_excess_gas` saves it inside env
/// and calculates `blob_fee` with [`BlobGasAndFee`].
pub fn set_blob_gas_and_fee(&mut self, excess_blob_gas: u64) {
self.blob_gas_and_fee = Some(BlobGasAndFee::new(excess_blob_gas));
}
/// See [EIP-4844] and [`Env::calc_data_fee`].
///
/// Returns `None` if `Cancun` is not enabled. This is enforced in [`Env::validate_block_env`].
///
/// [EIP-4844]: https://eips.ethereum.org/EIPS/eip-4844
#[inline]
pub fn get_blob_fee(&self) -> Option<u64> {
self.blob_gas_and_fee.as_ref().map(|a| a.blob_fee)
}
/// Return `blob_excess_gas` header field. See [EIP-4844].
///
/// Returns `None` if `Cancun` is not enabled. This is enforced in [`Env::validate_block_env`].
///
/// [EIP-4844]: https://eips.ethereum.org/EIPS/eip-4844
#[inline]
pub fn get_blob_excess_gas(&self) -> Option<u64> {
self.blob_gas_and_fee.as_ref().map(|a| a.excess_blob_gas)
}
}
/// The transaction environment.
#[derive(Clone, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct TxEnv {
/// The caller, author or signer of the transaction.
pub caller: B160,
/// The gas limit of the transaction.
pub gas_limit: u64,
/// The gas price of the transaction.
pub gas_price: U256,
/// The destination of the transaction.
pub transact_to: TransactTo,
/// The value sent to `transact_to`.
pub value: U256,
/// The data of the transaction.
#[cfg_attr(feature = "serde", serde(with = "crate::utilities::serde_hex_bytes"))]
pub data: Bytes,
/// The nonce of the transaction. If set to `None`, no checks are performed.
pub nonce: Option<u64>,
/// The chain ID of the transaction. If set to `None`, no checks are performed.
///
/// Incorporated as part of the Spurious Dragon upgrade via [EIP-155].
///
/// [EIP-155]: https://eips.ethereum.org/EIPS/eip-155
pub chain_id: Option<u64>,
/// A list of addresses and storage keys that the transaction plans to access.
///
/// Added in [EIP-2930].
///
/// [EIP-2930]: https://eips.ethereum.org/EIPS/eip-2930
pub access_list: Vec<(B160, Vec<U256>)>,
/// The priority fee per gas.
///
/// Incorporated as part of the London upgrade via [EIP-1559].
///
/// [EIP-1559]: https://eips.ethereum.org/EIPS/eip-1559
pub gas_priority_fee: Option<U256>,
/// The list of blob versioned hashes.
///
/// Incorporated as part of the Cancun upgrade via [EIP-4844].
///
/// [EIP-4844]: https://eips.ethereum.org/EIPS/eip-4844
pub blob_hashes: Vec<B256>,
/// The max fee per blob gas.
///
/// Incorporated as part of the Cancun upgrade via [EIP-4844].
///
/// [EIP-4844]: https://eips.ethereum.org/EIPS/eip-4844
pub max_fee_per_blob_gas: Option<U256>,
}
impl TxEnv {
/// See [EIP-4844] and [`Env::calc_data_fee`].
///
/// [EIP-4844]: https://eips.ethereum.org/EIPS/eip-4844
#[inline]
pub fn get_total_blob_gas(&self) -> u64 {
GAS_PER_BLOB * self.blob_hashes.len() as u64
}
}
/// Transaction destination.
#[derive(Clone, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum TransactTo {
/// Simple call to an address.
Call(B160),
/// Contract creation.
Create(CreateScheme),
}
impl TransactTo {
/// Calls the given address.
#[inline]
pub fn call(address: B160) -> Self {
Self::Call(address)
}
/// Creates a contract.
#[inline]
pub fn create() -> Self {
Self::Create(CreateScheme::Create)
}
/// Creates a contract with the given salt using `CREATE2`.
#[inline]
pub fn create2(salt: U256) -> Self {
Self::Create(CreateScheme::Create2 { salt })
}
/// Returns `true` if the transaction is `Call`.
#[inline]
pub fn is_call(&self) -> bool {
matches!(self, Self::Call(_))
}
/// Returns `true` if the transaction is `Create` or `Create2`.
#[inline]
pub fn is_create(&self) -> bool {
matches!(self, Self::Create(_))
}
}
/// Create scheme.
#[derive(Clone, Copy, Eq, PartialEq, Debug)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum CreateScheme {
/// Legacy create scheme of `CREATE`.
Create,
/// Create scheme of `CREATE2`.
Create2 {
/// Salt.
salt: U256,
},
}
/// EVM configuration.
#[derive(Clone, Debug, Eq, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[non_exhaustive]
pub struct CfgEnv {
pub chain_id: u64,
pub spec_id: SpecId,
/// KZG Settings for point evaluation precompile. By default, this is loaded from the ethereum mainnet trusted setup.
#[cfg_attr(feature = "serde", serde(skip))]
#[cfg(feature = "std")]
pub kzg_settings: crate::kzg::EnvKzgSettings,
/// Bytecode that is created with CREATE/CREATE2 is by default analysed and jumptable is created.
/// This is very beneficial for testing and speeds up execution of that bytecode if called multiple times.
///
/// Default: Analyse
pub perf_analyse_created_bytecodes: AnalysisKind,
/// If some it will effects EIP-170: Contract code size limit. Useful to increase this because of tests.
/// By default it is 0x6000 (~25kb).
pub limit_contract_code_size: Option<usize>,
/// Disables the coinbase tip during the finalization of the transaction. This is useful for
/// rollups that redirect the tip to the sequencer.
pub disable_coinbase_tip: bool,
/// A hard memory limit in bytes beyond which [Memory] cannot be resized.
///
/// In cases where the gas limit may be extraordinarily high, it is recommended to set this to
/// a sane value to prevent memory allocation panics. Defaults to `2^32 - 1` bytes per
/// EIP-1985.
#[cfg(feature = "memory_limit")]
pub memory_limit: u64,
/// Skip balance checks if true. Adds transaction cost to balance to ensure execution doesn't fail.
#[cfg(feature = "optional_balance_check")]
pub disable_balance_check: bool,
/// There are use cases where it's allowed to provide a gas limit that's higher than a block's gas limit. To that
/// end, you can disable the block gas limit validation.
/// By default, it is set to `false`.
#[cfg(feature = "optional_block_gas_limit")]
pub disable_block_gas_limit: bool,
/// EIP-3607 rejects transactions from senders with deployed code. In development, it can be desirable to simulate
/// calls from contracts, which this setting allows.
/// By default, it is set to `false`.
#[cfg(feature = "optional_eip3607")]
pub disable_eip3607: bool,
/// Disables all gas refunds. This is useful when using chains that have gas refunds disabled e.g. Avalanche.
/// Reasoning behind removing gas refunds can be found in EIP-3298.
/// By default, it is set to `false`.
#[cfg(feature = "optional_gas_refund")]
pub disable_gas_refund: bool,
/// Disables base fee checks for EIP-1559 transactions.
/// This is useful for testing method calls with zero gas price.
#[cfg(feature = "optional_no_base_fee")]
pub disable_base_fee: bool,
}
impl CfgEnv {
#[cfg(feature = "optional_eip3607")]
pub fn is_eip3607_disabled(&self) -> bool {
self.disable_eip3607
}
#[cfg(not(feature = "optional_eip3607"))]
pub fn is_eip3607_disabled(&self) -> bool {
false
}
#[cfg(feature = "optional_balance_check")]
pub fn is_balance_check_disabled(&self) -> bool {
self.disable_balance_check
}
#[cfg(not(feature = "optional_balance_check"))]
pub fn is_balance_check_disabled(&self) -> bool {
false
}
#[cfg(feature = "optional_gas_refund")]
pub fn is_gas_refund_disabled(&self) -> bool {
self.disable_gas_refund
}
#[cfg(not(feature = "optional_gas_refund"))]
pub fn is_gas_refund_disabled(&self) -> bool {
false
}
#[cfg(feature = "optional_no_base_fee")]
pub fn is_base_fee_check_disabled(&self) -> bool {
self.disable_base_fee
}
#[cfg(not(feature = "optional_no_base_fee"))]
pub fn is_base_fee_check_disabled(&self) -> bool {
false
}
#[cfg(feature = "optional_block_gas_limit")]
pub fn is_block_gas_limit_disabled(&self) -> bool {
self.disable_block_gas_limit
}
#[cfg(not(feature = "optional_block_gas_limit"))]
pub fn is_block_gas_limit_disabled(&self) -> bool {
false
}
}
/// What bytecode analysis to perform.
#[derive(Clone, Default, Debug, Eq, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum AnalysisKind {
/// Do not perform bytecode analysis.
Raw,
/// Check the bytecode for validity.
Check,
/// Perform bytecode analysis.
#[default]
Analyse,
}
impl Default for CfgEnv {
fn default() -> Self {
Self {
chain_id: 1,
spec_id: SpecId::LATEST,
perf_analyse_created_bytecodes: AnalysisKind::default(),
limit_contract_code_size: None,
disable_coinbase_tip: false,
#[cfg(feature = "std")]
kzg_settings: crate::kzg::EnvKzgSettings::Default,
#[cfg(feature = "memory_limit")]
memory_limit: (1 << 32) - 1,
#[cfg(feature = "optional_balance_check")]
disable_balance_check: false,
#[cfg(feature = "optional_block_gas_limit")]
disable_block_gas_limit: false,
#[cfg(feature = "optional_eip3607")]
disable_eip3607: false,
#[cfg(feature = "optional_gas_refund")]
disable_gas_refund: false,
#[cfg(feature = "optional_no_base_fee")]
disable_base_fee: false,
}
}
}
impl Default for BlockEnv {
fn default() -> Self {
Self {
number: U256::ZERO,
coinbase: B160::zero(),
timestamp: U256::from(1),
gas_limit: U256::MAX,
basefee: U256::ZERO,
difficulty: U256::ZERO,
prevrandao: Some(B256::zero()),
blob_gas_and_fee: Some(BlobGasAndFee::new(0)),
}
}
}
impl Default for TxEnv {
fn default() -> Self {
Self {
caller: B160::zero(),
gas_limit: u64::MAX,
gas_price: U256::ZERO,
gas_priority_fee: None,
transact_to: TransactTo::Call(B160::zero()), // will do nothing
value: U256::ZERO,
data: Bytes::new(),
chain_id: None,
nonce: None,
access_list: Vec::new(),
blob_hashes: Vec::new(),
max_fee_per_blob_gas: None,
}
}
}
impl Env {
/// Calculates the effective gas price of the transaction.
#[inline]
pub fn effective_gas_price(&self) -> U256 {
if let Some(priority_fee) = self.tx.gas_priority_fee {
min(self.tx.gas_price, self.block.basefee + priority_fee)
} else {
self.tx.gas_price
}
}
/// Calculates the [EIP-4844] `data_fee` of the transaction.
///
/// Returns `None` if `Cancun` is not enabled. This is enforced in [`Env::validate_block_env`].
///
/// [EIP-4844]: https://eips.ethereum.org/EIPS/eip-4844
#[inline]
pub fn calc_data_fee(&self) -> Option<u64> {
self.block
.get_blob_fee()
.map(|blob_gas_price| blob_gas_price * self.tx.get_total_blob_gas())
}
/// Validate the block environment.
#[inline]
pub fn validate_block_env<SPEC: Spec, T>(&self) -> Result<(), EVMError<T>> {
// `prevrandao` is required for the merge
if SPEC::enabled(SpecId::MERGE) && self.block.prevrandao.is_none() {
return Err(EVMError::PrevrandaoNotSet);
}
// `excess_blob_gas` is required for Cancun
if SPEC::enabled(SpecId::CANCUN) && self.block.blob_gas_and_fee.is_none() {
return Err(EVMError::ExcessBlobGasNotSet);
}
Ok(())
}
/// Validate transaction data that is set inside ENV and return error if something is wrong.
///
/// Return initial spend gas (Gas needed to execute transaction).
#[inline]
pub fn validate_tx<SPEC: Spec>(&self) -> Result<(), InvalidTransaction> {
let gas_limit = self.tx.gas_limit;
let effective_gas_price = self.effective_gas_price();
let is_create = self.tx.transact_to.is_create();
// BASEFEE tx check
if SPEC::enabled(SpecId::LONDON) {
if let Some(priority_fee) = self.tx.gas_priority_fee {
if priority_fee > self.tx.gas_price {
// or gas_max_fee for eip1559
return Err(InvalidTransaction::GasMaxFeeGreaterThanPriorityFee);
}
}
let basefee = self.block.basefee;
// check minimal cost against basefee
if !self.cfg.is_base_fee_check_disabled() && effective_gas_price < basefee {
return Err(InvalidTransaction::GasPriceLessThanBasefee);
}
}
// Check if gas_limit is more than block_gas_limit
if !self.cfg.is_block_gas_limit_disabled() && U256::from(gas_limit) > self.block.gas_limit {
return Err(InvalidTransaction::CallerGasLimitMoreThanBlock);
}
// EIP-3860: Limit and meter initcode
if SPEC::enabled(SpecId::SHANGHAI) && is_create {
let max_initcode_size = self
.cfg
.limit_contract_code_size
.map(|limit| limit.saturating_mul(2))
.unwrap_or(MAX_INITCODE_SIZE);
if self.tx.data.len() > max_initcode_size {
return Err(InvalidTransaction::CreateInitcodeSizeLimit);
}
}
// Check if the transaction's chain id is correct
if let Some(tx_chain_id) = self.tx.chain_id {
if tx_chain_id != self.cfg.chain_id {
return Err(InvalidTransaction::InvalidChainId);
}
}
// Check that access list is empty for transactions before BERLIN
if !SPEC::enabled(SpecId::BERLIN) && !self.tx.access_list.is_empty() {
return Err(InvalidTransaction::AccessListNotSupported);
}
// - For CANCUN and later, check that the gas price is not more than the tx max
// - For before CANCUN, check that `blob_hashes` and `max_fee_per_blob_gas` are empty / not set
if SPEC::enabled(SpecId::CANCUN) {
if let Some(max) = self.tx.max_fee_per_blob_gas {
let price = self.block.get_blob_fee().expect("already checked");
if U256::from(price) > max {
return Err(InvalidTransaction::BlobGasPriceGreaterThanMax);
}
}
} else {
if !self.tx.blob_hashes.is_empty() {
return Err(InvalidTransaction::BlobVersionedHashesNotSupported);
}
if self.tx.max_fee_per_blob_gas.is_some() {
return Err(InvalidTransaction::MaxFeePerBlobGasNotSupported);
}
}
Ok(())
}
/// Validate transaction against state.
#[inline]
pub fn validate_tx_against_state(&self, account: &Account) -> Result<(), InvalidTransaction> {
// EIP-3607: Reject transactions from senders with deployed code
// This EIP is introduced after london but there was no collision in past
// so we can leave it enabled always
if !self.cfg.is_eip3607_disabled() && account.info.code_hash != KECCAK_EMPTY {
return Err(InvalidTransaction::RejectCallerWithCode);
}
// Check that the transaction's nonce is correct
if let Some(tx) = self.tx.nonce {
let state = account.info.nonce;
match tx.cmp(&state) {
Ordering::Greater => {
return Err(InvalidTransaction::NonceTooHigh { tx, state });
}
Ordering::Less => {
return Err(InvalidTransaction::NonceTooLow { tx, state });
}
_ => {}
}
}
let mut balance_check = U256::from(self.tx.gas_limit)
.checked_mul(self.tx.gas_price)
.and_then(|gas_cost| gas_cost.checked_add(self.tx.value))
.ok_or(InvalidTransaction::OverflowPaymentInTransaction)?;
if SpecId::enabled(self.cfg.spec_id, SpecId::CANCUN) {
let data_fee = self.calc_data_fee().expect("already checked");
balance_check = balance_check
.checked_add(U256::from(data_fee))
.ok_or(InvalidTransaction::OverflowPaymentInTransaction)?;
}
// Check if account has enough balance for gas_limit*gas_price and value transfer.
// Transfer will be done inside `*_inner` functions.
if !self.cfg.is_balance_check_disabled() && balance_check > account.info.balance {
return Err(InvalidTransaction::LackOfFundForMaxFee {
fee: self.tx.gas_limit,
balance: account.info.balance,
});
}
Ok(())
}
}