-
Notifications
You must be signed in to change notification settings - Fork 20
Expand file tree
/
Copy pathexecutor.rs
More file actions
411 lines (358 loc) · 14.3 KB
/
executor.rs
File metadata and controls
411 lines (358 loc) · 14.3 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
400
401
402
403
404
405
406
407
408
409
410
411
use crate::{
chainspec::BerachainChainSpec,
engine::validate_proposer_pubkey_prague1,
evm::BerachainEvmFactory,
hardforks::BerachainHardforks,
node::evm::{
block_context::BerachainBlockExecutionCtx, config::BerachainEvmConfig,
error::BerachainExecutionError, receipt::BerachainReceiptBuilder,
},
transaction::{BerachainTxEnvelope, BerachainTxType, pol::create_pol_transaction},
};
use alloy_consensus::Transaction;
use alloy_eips::{Encodable2718, eip7685::Requests};
use alloy_evm::{
RecoveredTx,
block::state_changes::{balance_increment_state, post_block_balance_increments},
};
use alloy_primitives::Bytes;
use reth::{
chainspec::{EthereumHardfork, EthereumHardforks},
providers::BlockExecutionResult,
revm::{
DatabaseCommit, Inspector, State,
context::{
Block as _,
result::{ExecutionResult, Output, ResultAndState, SuccessReason},
},
database_interface::DatabaseCommitExt,
},
};
use reth_evm::{
Database, Evm, EvmFactory, FromRecoveredTx, FromTxWithEncoded, OnStateHook,
block::{
BlockExecutionError, BlockExecutor, BlockExecutorFactory, BlockExecutorFor,
BlockValidationError, ExecutableTx, StateChangePostBlockSource, StateChangeSource,
SystemCaller, TxResult,
},
eth::{
dao_fork, eip6110,
receipt_builder::{ReceiptBuilder, ReceiptBuilderCtx},
spec::EthExecutorSpec,
},
};
use std::{borrow::Cow, collections::HashMap, sync::Arc};
#[derive(Debug)]
pub struct BerachainTxResult<H> {
pub result: ResultAndState<H>,
pub blob_gas_used: u64,
pub tx_type: BerachainTxType,
}
impl<H> TxResult for BerachainTxResult<H> {
type HaltReason = H;
fn result(&self) -> &ResultAndState<H> {
&self.result
}
}
#[derive(Debug)]
pub struct BerachainBlockExecutor<'a, Evm> {
/// Berachain chain specification.
spec: Arc<BerachainChainSpec>,
/// Context for block execution.
pub ctx: BerachainBlockExecutionCtx<'a>,
/// Inner EVM.
evm: Evm,
/// Utility to call system smart contracts.
system_caller: SystemCaller<Arc<BerachainChainSpec>>,
/// Receipt builder.
receipt_builder: BerachainReceiptBuilder,
/// Receipts of executed transactions.
receipts: Vec<<BerachainReceiptBuilder as ReceiptBuilder>::Receipt>,
/// Total gas used by transactions in this block.
gas_used: u64,
/// Total blob gas used by blob transactions in this block.
blob_gas_used: u64,
}
impl<'a, Evm> BerachainBlockExecutor<'a, Evm> {
pub fn new(
evm: Evm,
ctx: BerachainBlockExecutionCtx<'a>,
spec: Arc<BerachainChainSpec>,
receipt_builder: BerachainReceiptBuilder,
) -> Self {
Self {
spec: spec.clone(),
evm,
ctx,
receipts: Vec::new(),
gas_used: 0,
blob_gas_used: 0,
system_caller: SystemCaller::new(spec.clone()),
receipt_builder,
}
}
/// Execute POL transaction as system call and manually capture receipt
fn execute_pol_transaction_with_receipt(&mut self) -> Result<(), BlockExecutionError>
where
Evm: reth_evm::Evm,
<Evm as reth_evm::Evm>::DB: DatabaseCommit,
{
let timestamp = self.evm.block().timestamp().saturating_to();
// Validate proposer pubkey presence for Prague1
validate_proposer_pubkey_prague1(&*self.spec, timestamp, self.ctx.prev_proposer_pubkey)?;
// Check if Prague1 hardfork is active (after validation)
if !self.spec.is_prague1_active_at_timestamp(timestamp) {
return Ok(());
}
// This panic should never occur due to the above validation
let prev_proposer_pubkey = self.ctx.prev_proposer_pubkey.unwrap();
// Use shared POL transaction creation logic
let base_fee = self.evm.block().basefee();
let pol_envelope = create_pol_transaction(
self.spec.clone(),
prev_proposer_pubkey,
self.evm.block().number(),
base_fee,
)?;
let (caller_address, calldata, pol_distributor_address) =
if let BerachainTxEnvelope::Berachain(pol_tx) = &pol_envelope {
(pol_tx.from, pol_tx.input.clone(), pol_tx.to)
} else {
return Err(BerachainExecutionError::InvalidPolTransactionType.into());
};
// Execute as system call (maintains zero gas cost and unlimited gas)
match self.evm.transact_system_call(
caller_address,
pol_distributor_address,
calldata.clone(),
) {
Ok(result_and_state) => {
tracing::debug!(target: "executor", ?result_and_state, "POL transaction executed successfully");
// Build receipt manually for the system call
let receipt = self.receipt_builder.build_receipt(ReceiptBuilderCtx {
tx_type: BerachainTxType::Berachain,
evm: &self.evm,
result: result_and_state.result,
state: &result_and_state.state,
cumulative_gas_used: self.gas_used, // No gas consumed by system call
});
// Add receipt to block
self.receipts.push(receipt);
// Notify system caller of state changes from system call
self.system_caller.on_state(
StateChangeSource::Transaction(0), /* POL is always the first transaction
* (index 0) */
&result_and_state.state,
);
// Commit the POL transaction state changes to the database
self.evm.db_mut().commit(result_and_state.state);
tracing::debug!(target: "executor", "POL transaction state changes committed to database");
Ok(())
}
Err(e) => {
tracing::error!(target: "executor", %e, "POL system call execution failed");
Err(BlockExecutionError::other(e))
}
}
}
}
impl<'db, DB, E> BlockExecutor for BerachainBlockExecutor<'_, E>
where
DB: Database + 'db,
E: Evm<
DB = &'db mut State<DB>,
Tx: FromRecoveredTx<BerachainTxEnvelope> + FromTxWithEncoded<BerachainTxEnvelope>,
>,
{
type Transaction = BerachainTxEnvelope;
type Receipt = reth_ethereum_primitives::Receipt<BerachainTxType>;
type Evm = E;
type Result = BerachainTxResult<E::HaltReason>;
fn apply_pre_execution_changes(&mut self) -> Result<(), BlockExecutionError> {
// Set state clear flag if the block is after the Spurious Dragon hardfork.
let state_clear_flag =
self.spec.is_spurious_dragon_active_at_block(self.evm.block().number().saturating_to());
self.evm.db_mut().set_state_clear_flag(state_clear_flag);
self.system_caller.apply_blockhashes_contract_call(self.ctx.parent_hash, &mut self.evm)?;
self.system_caller
.apply_beacon_root_contract_call(self.ctx.parent_beacon_block_root, &mut self.evm)?;
// Execute POL transaction and capture receipt
self.execute_pol_transaction_with_receipt()?;
Ok(())
}
fn execute_transaction_without_commit(
&mut self,
tx: impl ExecutableTx<Self>,
) -> Result<Self::Result, BlockExecutionError> {
let (tx_env, recovered) = tx.into_parts();
let consensus_tx = recovered.tx();
// For PoL txs, we simply populate a dummy result and state as it is ultimately ignored
// during commit_transaction.
if let BerachainTxEnvelope::Berachain(_) = consensus_tx {
return Ok(BerachainTxResult {
result: ResultAndState {
result: ExecutionResult::Success {
reason: SuccessReason::Stop,
gas_used: 0,
gas_refunded: 0,
logs: Vec::new(),
output: Output::Call(Bytes::default()),
},
state: HashMap::default(),
},
blob_gas_used: 0,
tx_type: BerachainTxType::Berachain,
});
}
// The sum of the transaction's gas limit, Tg, and the gas utilized in this block prior,
// must be no greater than the block's gasLimit.
let block_available_gas = self.evm.block().gas_limit() - self.gas_used;
if consensus_tx.gas_limit() > block_available_gas {
return Err(BlockValidationError::TransactionGasLimitMoreThanAvailableBlockGas {
transaction_gas_limit: consensus_tx.gas_limit(),
block_available_gas,
}
.into());
}
let blob_gas_used = consensus_tx.blob_gas_used().unwrap_or_default();
let tx_type = consensus_tx.tx_type();
let tx_hash = consensus_tx.trie_hash();
// Execute transaction and return the result
let result =
self.evm.transact_raw(tx_env).map_err(|err| BlockExecutionError::evm(err, tx_hash))?;
Ok(BerachainTxResult { result, blob_gas_used, tx_type })
}
fn commit_transaction(&mut self, output: Self::Result) -> Result<u64, BlockExecutionError> {
// Skip commit for POL transactions as it's already been applied in
// apply_pre_execution_changes
if output.tx_type == BerachainTxType::Berachain {
return Ok(0);
}
let BerachainTxResult { result: ResultAndState { result, state }, blob_gas_used, tx_type } =
output;
self.system_caller.on_state(StateChangeSource::Transaction(self.receipts.len()), &state);
let gas_used = result.gas_used();
// append gas used
self.gas_used += gas_used;
// only determine cancun fields when active
if self.spec.is_cancun_active_at_timestamp(self.evm.block().timestamp().saturating_to()) {
self.blob_gas_used = self.blob_gas_used.saturating_add(blob_gas_used);
}
// Push transaction changeset and calculate header bloom filter for receipt.
self.receipts.push(self.receipt_builder.build_receipt(ReceiptBuilderCtx {
tx_type,
evm: &self.evm,
result,
state: &state,
cumulative_gas_used: self.gas_used,
}));
// Commit the state changes.
self.evm.db_mut().commit(state);
Ok(gas_used)
}
fn finish(
mut self,
) -> Result<
(Self::Evm, BlockExecutionResult<<BerachainReceiptBuilder as ReceiptBuilder>::Receipt>),
BlockExecutionError,
> {
let requests = if self
.spec
.is_prague_active_at_timestamp(self.evm.block().timestamp().saturating_to())
{
let deposit_contract = self
.spec
.deposit_contract_address()
.unwrap_or(eip6110::MAINNET_DEPOSIT_CONTRACT_ADDRESS);
let deposit_requests =
crate::deposits::parse_deposits_from_receipts(deposit_contract, &self.receipts)?;
let mut requests = Requests::default();
if !deposit_requests.is_empty() {
requests.push_request_with_type(eip6110::DEPOSIT_REQUEST_TYPE, deposit_requests);
}
requests.extend(self.system_caller.apply_post_execution_changes(&mut self.evm)?);
requests
} else {
Requests::default()
};
let mut balance_increments = post_block_balance_increments(
&self.spec,
self.evm.block(),
self.ctx.ommers,
self.ctx.withdrawals.as_deref(),
);
// Irregular state change at Ethereum DAO hardfork
if self
.spec
.ethereum_fork_activation(EthereumHardfork::Dao)
.transitions_at_block(self.evm.block().number().saturating_to())
{
// drain balances from hardcoded addresses.
let drained_balance: u128 = self
.evm
.db_mut()
.drain_balances(dao_fork::DAO_HARDFORK_ACCOUNTS)
.map_err(|_| BlockValidationError::IncrementBalanceFailed)?
.into_iter()
.sum();
// return balance to DAO beneficiary.
*balance_increments.entry(dao_fork::DAO_HARDFORK_BENEFICIARY).or_default() +=
drained_balance;
}
// increment balances
self.evm
.db_mut()
.increment_balances(balance_increments.clone())
.map_err(|_| BlockValidationError::IncrementBalanceFailed)?;
// call state hook with changes due to balance increments.
self.system_caller.try_on_state_with(|| {
balance_increment_state(&balance_increments, self.evm.db_mut()).map(|state| {
(
StateChangeSource::PostBlock(StateChangePostBlockSource::BalanceIncrements),
Cow::Owned(state),
)
})
})?;
Ok((
self.evm,
BlockExecutionResult {
receipts: self.receipts,
requests,
gas_used: self.gas_used,
blob_gas_used: self.blob_gas_used,
},
))
}
fn set_state_hook(&mut self, hook: Option<Box<dyn OnStateHook>>) {
self.system_caller.with_state_hook(hook);
}
fn evm_mut(&mut self) -> &mut Self::Evm {
&mut self.evm
}
fn evm(&self) -> &Self::Evm {
&self.evm
}
fn receipts(&self) -> &[Self::Receipt] {
&self.receipts
}
}
impl BlockExecutorFactory for BerachainEvmConfig {
type EvmFactory = BerachainEvmFactory;
type ExecutionCtx<'a> = BerachainBlockExecutionCtx<'a>;
type Transaction = BerachainTxEnvelope;
type Receipt = reth_ethereum_primitives::Receipt<BerachainTxType>;
fn evm_factory(&self) -> &Self::EvmFactory {
&self.evm_factory
}
fn create_executor<'a, DB, I>(
&'a self,
evm: <Self::EvmFactory as EvmFactory>::Evm<&'a mut State<DB>, I>,
ctx: Self::ExecutionCtx<'a>,
) -> impl BlockExecutorFor<'a, Self, DB, I>
where
DB: Database + 'a,
I: Inspector<<Self::EvmFactory as EvmFactory>::Context<&'a mut State<DB>>> + 'a,
{
BerachainBlockExecutor::new(evm, ctx, self.spec.clone(), self.receipt_builder)
}
}