-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathhost_executor.rs
More file actions
241 lines (211 loc) · 8.89 KB
/
host_executor.rs
File metadata and controls
241 lines (211 loc) · 8.89 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
use std::sync::Arc;
use crate::HostError;
use alloy_consensus::{BlockHeader, Header, TxReceipt};
use alloy_network::BlockResponse;
use alloy_primitives::{Bloom, Sealable};
use alloy_provider::{Network, Provider};
use guest_executor::{
custom::CustomEvmFactory, io::ClientExecutorInput, BlockValidator, IntoInput, IntoPrimitives,
};
use primitives::{genesis::Genesis, is_goat_testnet};
use reth_chainspec::ChainSpec;
use reth_evm::{
execute::{BasicBlockExecutor, Executor},
ConfigureEvm,
};
use reth_evm_ethereum::EthEvmConfig;
use reth_optimism_chainspec::OpChainSpec;
use reth_optimism_evm::OpEvmConfig;
use reth_primitives_traits::{Block, BlockBody, SealedHeader};
use reth_trie::{HashedPostState, KeccakKeyHasher};
use revm::database::CacheDB;
use revm_primitives::Address;
use rpc_db::RpcDb;
pub type EthHostExecutor = HostExecutor<EthEvmConfig<ChainSpec, CustomEvmFactory>, ChainSpec>;
pub type OpHostExecutor = HostExecutor<OpEvmConfig, OpChainSpec>;
/// An executor that fetches data from a [Provider] to execute blocks in the [ClientExecutor].
#[derive(Debug, Clone)]
pub struct HostExecutor<C: ConfigureEvm, CS> {
evm_config: C,
chain_spec: Arc<CS>,
}
impl EthHostExecutor {
pub fn eth(chain_spec: Arc<ChainSpec>, custom_beneficiary: Option<Address>) -> Self {
Self {
evm_config: EthEvmConfig::new_with_evm_factory(
chain_spec.clone(),
CustomEvmFactory::new(custom_beneficiary),
),
chain_spec,
}
}
}
impl OpHostExecutor {
pub fn optimism(chain_spec: Arc<OpChainSpec>) -> Self {
Self { evm_config: OpEvmConfig::optimism(chain_spec.clone()), chain_spec }
}
}
impl<C: ConfigureEvm, CS> HostExecutor<C, CS> {
/// Creates a new [HostExecutor].
pub fn new(evm_config: C, chain_spec: Arc<CS>) -> Self {
Self { evm_config, chain_spec }
}
/// Executes the block with the given block number.
pub async fn execute<P, N>(
&self,
block_number: u64,
provider: &P,
debug_provider: &P,
genesis: Genesis,
custom_beneficiary: Option<Address>,
opcode_tracking: bool,
) -> Result<ClientExecutorInput<C::Primitives>, HostError>
where
C::Primitives: IntoPrimitives<N> + IntoInput + BlockValidator<CS>,
P: Provider<N> + Clone + std::fmt::Debug,
N: Network,
{
let chain_id: u64 = (&genesis).try_into().unwrap();
tracing::debug!("chain id: {}", chain_id);
let is_goat_testnet = is_goat_testnet(chain_id);
// Fetch the current block and the previous block from the provider.
tracing::info!("[{}] fetching the current block and the previous block", block_number);
let rpc_block = provider
.get_block_by_number(block_number.into())
.full()
.await?
.ok_or(HostError::ExpectedBlock(block_number))?;
let current_block = C::Primitives::into_primitive_block(rpc_block.clone());
let previous_block = provider
.get_block_by_number((block_number - 1).into())
.full()
.await?
.ok_or(HostError::ExpectedBlock(block_number))
.map(C::Primitives::into_primitive_block)?;
tracing::info!("[{}] create rpc db", block_number);
#[cfg(not(feature = "execution-witness"))]
let rpc_db = rpc_db::BasicRpcDb::new(
debug_provider,
block_number - 1,
previous_block.header().state_root(),
);
#[cfg(feature = "execution-witness")]
let rpc_db = rpc_db::ExecutionWitnessRpcDb::new(
debug_provider,
block_number - 1,
previous_block.header().state_root(),
is_goat_testnet,
)
.await
.map_err(HostError::RpcDbError)?;
tracing::info!("[{}] create rpc db done", block_number);
let cache_db = CacheDB::new(&rpc_db);
let block_executor =
BasicBlockExecutor::new(self.evm_config.clone(), cache_db, Some(chain_id));
tracing::info!(
"executing the block with rpc db: block_number={}, transaction_count={}",
block_number,
current_block.body().transactions().len()
);
let block = current_block
.clone()
.try_into_recovered()
.map_err(|_| HostError::FailedToRecoverSenders)?;
tracing::info!("[{}] validate block", block_number);
C::Primitives::validate_block(&block, self.chain_spec.clone())?;
// Validate the block header.
tracing::info!("[{}] validate header", block_number);
C::Primitives::validate_header(
&SealedHeader::seal_slow(C::Primitives::into_consensus_header(
rpc_block.header().clone(),
)),
self.chain_spec.clone(),
)?;
tracing::info!("[{}] execute block", block_number);
let now = std::time::Instant::now();
let execution_output = block_executor.execute(&block)?;
tracing::info!("[{}] block execution took {:?}", block_number, now.elapsed());
// Validate the block post execution.
tracing::info!("[{}] validating the block post execution", block_number);
C::Primitives::validate_block_post_execution(
&block,
self.chain_spec.clone(),
&execution_output,
is_goat_testnet,
)?;
// Accumulate the logs bloom.
tracing::info!("[{}] accumulating the logs bloom", block_number);
let mut logs_bloom = Bloom::default();
execution_output.result.receipts.iter().for_each(|r| {
logs_bloom.accrue_bloom(&r.bloom());
});
let state = rpc_db.state(&execution_output.state).await.map_err(HostError::RpcDbError)?;
// Verify the state root.
tracing::info!("[{}] verifying the state root", block_number);
let state_root = {
let mut mutated_state = state.clone();
mutated_state.update(&HashedPostState::from_bundle_state::<KeccakKeyHasher>(
&execution_output.state.state,
));
mutated_state.state_root()
};
if state_root != current_block.header().state_root() {
return Err(HostError::StateRootMismatch(
state_root,
current_block.header().state_root(),
));
}
// Derive the block header.
//
// Note: the receipts root and gas used are verified by `validate_block_post_execution`.
let header = Header {
parent_hash: current_block.header().parent_hash(),
ommers_hash: current_block.header().ommers_hash(),
beneficiary: current_block.header().beneficiary(),
state_root,
transactions_root: current_block.header().transactions_root(),
receipts_root: current_block.header().receipts_root(),
logs_bloom,
difficulty: current_block.header().difficulty(),
number: current_block.header().number(),
gas_limit: current_block.header().gas_limit(),
gas_used: current_block.header().gas_used(),
timestamp: current_block.header().timestamp(),
extra_data: current_block.header().extra_data().clone(),
mix_hash: current_block.header().mix_hash().unwrap(),
nonce: current_block.header().nonce().unwrap(),
base_fee_per_gas: current_block.header().base_fee_per_gas(),
withdrawals_root: current_block.header().withdrawals_root(),
blob_gas_used: current_block.header().blob_gas_used(),
excess_blob_gas: current_block.header().excess_blob_gas(),
parent_beacon_block_root: current_block.header().parent_beacon_block_root(),
requests_hash: current_block.header().requests_hash(),
};
let ancestor_headers = rpc_db.ancestor_headers().await.map_err(HostError::RpcDbError)?;
// Assert the derived header is correct.
let constructed_header_hash = header.hash_slow();
let target_hash = current_block.header().hash_slow();
if constructed_header_hash != target_hash {
return Err(HostError::HeaderMismatch(constructed_header_hash, target_hash));
}
// Log the result.
tracing::info!(
"successfully executed block: block_number={}, block_hash={}, state_root={}",
current_block.header().number(),
constructed_header_hash,
state_root
);
// Create the client input.
let client_input = ClientExecutorInput {
current_block: C::Primitives::into_input_block(current_block),
ancestor_headers,
parent_state: state,
bytecodes: rpc_db.bytecodes(),
genesis,
custom_beneficiary,
opcode_tracking,
};
tracing::info!("[{}] successfully generated client input", block_number);
Ok(client_input)
}
}