Skip to content

Commit 2e52052

Browse files
committed
tmp
1 parent 0052b3b commit 2e52052

File tree

10 files changed

+165
-15
lines changed

10 files changed

+165
-15
lines changed

bus-mapping/src/circuit_input_builder.rs

+1
Original file line numberDiff line numberDiff line change
@@ -947,6 +947,7 @@ pub struct BuilderClient<P: JsonRpcClient> {
947947
}
948948

949949
/// Get State Accesses from TxExecTraces
950+
#[deprecated]
950951
pub fn get_state_accesses(
951952
eth_block: &EthBlock,
952953
geth_traces: &[eth_types::GethExecTrace],

bus-mapping/src/circuit_input_builder/access.rs

+26
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ use eth_types::{
55
use ethers_core::utils::get_contract_address;
66
use std::collections::{hash_map::Entry, HashMap, HashSet};
77

8+
use eth_types::geth_types::GethData;
89
use AccessValue::{Account, Code, Storage};
910
use RW::{READ, WRITE};
1011

@@ -119,6 +120,30 @@ impl AccessSet {
119120
self.state.extend(other.state.drain());
120121
self.code.extend(other.code.drain());
121122
}
123+
124+
pub(crate) fn from_l1_geth_data(geth_data: &GethData) -> Self {
125+
let mut access_set = AccessSet::default();
126+
access_set.add_account(geth_data.eth_block.author.unwrap());
127+
for trace in geth_data.geth_traces.iter() {
128+
access_set.extend_from_traces(trace.prestate.as_ref().unwrap());
129+
}
130+
access_set
131+
}
132+
133+
pub(crate) fn from_l2_geth_data(geth_data: &GethData) -> Self {
134+
let mut access_set = AccessSet::default();
135+
access_set.add_account(geth_data.eth_block.author.unwrap());
136+
for (addr, storage) in geth_data.block_trace.storage_trace.storage_proofs.iter() {
137+
log::info!("add addr {:?} to access_set", addr);
138+
access_set.add_account(*addr);
139+
access_set.add_code(*addr);
140+
for key in storage.keys() {
141+
log::info!("add addr {:?} key {:?} to access_set", addr, key);
142+
access_set.add_storage(*addr, *key);
143+
}
144+
}
145+
access_set
146+
}
122147
}
123148

124149
impl From<Vec<Access>> for AccessSet {
@@ -149,6 +174,7 @@ impl Default for CodeSource {
149174
/// Generate the State Access trace from the given trace. All state read/write
150175
/// accesses are reported, without distinguishing those that happen in revert
151176
/// sections.
177+
#[deprecated]
152178
pub fn gen_state_access_trace<TX>(
153179
_block: &eth_types::Block<TX>,
154180
tx: &eth_types::Transaction,

bus-mapping/src/circuit_input_builder/tracer_tests.rs

+1
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,7 @@ impl CircuitInputBuilderTx {
5252
return_value: "".to_owned(),
5353
struct_logs: vec![geth_step.clone()],
5454
account_after: vec![],
55+
prestate: None,
5556
},
5657
false,
5758
)

bus-mapping/src/mock.rs

+44-4
Original file line numberDiff line numberDiff line change
@@ -57,10 +57,50 @@ impl BlockData {
5757
let mut sdb = StateDB::new();
5858
let mut code_db = CodeDB::new();
5959

60-
let access_set: AccessSet =
61-
get_state_accesses(&geth_data.eth_block, &geth_data.geth_traces)
62-
.expect("state accesses")
63-
.into();
60+
let access_set = {
61+
// let old_access_set: AccessSet =
62+
// get_state_accesses(&geth_data.eth_block, &geth_data.geth_traces)
63+
// .expect("state accesses")
64+
// .into();
65+
let access_set = AccessSet::from_l2_geth_data(&geth_data);
66+
// for addr in old_access_set.code.iter() {
67+
// assert!(
68+
// access_set.code.contains(addr),
69+
// "code {:?} is not in access_set",
70+
// addr
71+
// );
72+
// }
73+
// for (addr, states) in old_access_set.state.iter() {
74+
// assert!(
75+
// access_set.state.contains_key(addr),
76+
// "state {:?} is not in access_set",
77+
// addr
78+
// );
79+
// for state in states {
80+
// assert!(
81+
// access_set.state.get(addr).unwrap().contains(state),
82+
// "state {:?} is not in access_set",
83+
// state
84+
// );
85+
// }
86+
// }
87+
// for addr in access_set.code.iter() {
88+
// if !old_access_set.code.contains(addr) {
89+
// log::error!("code {:?} is not in old_access_set", addr);
90+
// }
91+
// }
92+
// for (addr, states) in access_set.state.iter() {
93+
// if !old_access_set.state.contains_key(addr) {
94+
// log::error!("state {:?} is not in old_access_set", addr);
95+
// }
96+
// for state in states {
97+
// if !old_access_set.state.get(addr).unwrap().contains(state) {
98+
// log::error!("state {:?} is not in old_access_set", state);
99+
// }
100+
// }
101+
// }
102+
access_set
103+
};
64104
// Initialize all accesses accounts to zero
65105
for addr in access_set.state.keys() {
66106
sdb.set_account(addr, state_db::Account::zero());

eth-types/src/geth_types.rs

+4
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
//! Types needed for generating Ethereum traces
22
33
use crate::{
4+
l2_types::BlockTrace,
45
sign_types::{biguint_to_32bytes_le, ct_option_ok_or, recover_pk, SignData, SECP256K1_Q},
56
AccessList, Address, Block, Bytes, Error, GethExecTrace, Hash, ToBigEndian, ToLittleEndian,
67
Word, U64,
@@ -385,6 +386,9 @@ pub struct GethData {
385386
pub geth_traces: Vec<GethExecTrace>,
386387
/// Accounts
387388
pub accounts: Vec<Account>,
389+
/// block trace
390+
#[cfg(feature = "scroll")]
391+
pub block_trace: BlockTrace,
388392
}
389393
/*
390394
impl GethData {

eth-types/src/l2_types.rs

+1
Original file line numberDiff line numberDiff line change
@@ -209,6 +209,7 @@ impl From<ExecutionResult> for GethExecTrace {
209209
return_value: e.return_value,
210210
struct_logs,
211211
account_after: e.account_after,
212+
prestate: None,
212213
}
213214
}
214215
}

eth-types/src/lib.rs

+3
Original file line numberDiff line numberDiff line change
@@ -471,6 +471,7 @@ pub struct ResultGethExecTrace {
471471
/// the memory size before the expansion, so that it corresponds to the memory
472472
/// before the step is executed.
473473
#[derive(Deserialize, Serialize, Clone, Debug, Eq, PartialEq)]
474+
#[serde(deny_unknown_fields)]
474475
pub struct GethExecTrace {
475476
/// L1 fee
476477
#[serde(default)]
@@ -489,6 +490,8 @@ pub struct GethExecTrace {
489490
/// List of accounts' (coinbase etc) status AFTER execution
490491
/// Only viable for scroll mode
491492
pub account_after: Vec<crate::l2_types::AccountProofWrapper>,
493+
/// prestate trace
494+
pub prestate: Option<HashMap<Address, GethPrestateTrace>>,
492495
}
493496

494497
#[derive(Clone, Debug, Eq, PartialEq, Deserialize)]

geth-utils/l1geth/trace.go

+81-7
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,9 @@
11
package main
22

33
import (
4+
"encoding/json"
45
"fmt"
6+
"github.com/ethereum/go-ethereum/eth/tracers"
57
"math/big"
68

79
"github.com/ethereum/go-ethereum/common"
@@ -12,6 +14,7 @@ import (
1214
"github.com/ethereum/go-ethereum/core/types"
1315
"github.com/ethereum/go-ethereum/core/vm"
1416
"github.com/ethereum/go-ethereum/eth/tracers/logger"
17+
_ "github.com/ethereum/go-ethereum/eth/tracers/native"
1518
"github.com/ethereum/go-ethereum/params"
1619
"github.com/imdario/mergo"
1720
)
@@ -21,10 +24,11 @@ import (
2124
// while replaying a transaction in debug mode as well as transaction
2225
// execution status, the amount of gas used and the return value
2326
type ExecutionResult struct {
24-
Gas uint64 `json:"gas"`
25-
Failed bool `json:"failed"`
26-
ReturnValue string `json:"returnValue"`
27-
StructLogs []StructLogRes `json:"structLogs"`
27+
Gas uint64 `json:"gas"`
28+
Failed bool `json:"failed"`
29+
ReturnValue string `json:"returnValue"`
30+
StructLogs []StructLogRes `json:"structLogs"`
31+
Prestate json.RawMessage `json:"prestate"`
2832
}
2933

3034
// StructLogRes stores a structured log emitted by the EVM while replaying a
@@ -236,22 +240,92 @@ func Trace(config TraceConfig) ([]*ExecutionResult, error) {
236240
// Run the transactions with tracing enabled.
237241
executionResults := make([]*ExecutionResult, len(config.Transactions))
238242
for i, message := range messages {
239-
tracer := logger.NewStructLogger(config.LoggerConfig)
240-
evm := vm.NewEVM(blockCtx, core.NewEVMTxContext(&message), stateDB, &chainConfig, vm.Config{Debug: true, Tracer: tracer, NoBaseFee: true})
243+
txContext := core.NewEVMTxContext(&message)
244+
prestateTracer, err := tracers.DefaultDirectory.New("prestateTracer", new(tracers.Context), nil)
245+
if err != nil {
246+
return nil, fmt.Errorf("Failed to create prestateTracer: %w", err)
247+
}
248+
structLogger := logger.NewStructLogger(config.LoggerConfig)
249+
tracer := NewMuxTracer(
250+
structLogger,
251+
prestateTracer,
252+
)
253+
evm := vm.NewEVM(blockCtx, txContext, stateDB, &chainConfig, vm.Config{Debug: true, Tracer: tracer, NoBaseFee: true})
241254

242255
result, err := core.ApplyMessage(evm, &message, new(core.GasPool).AddGas(message.GasLimit))
243256
if err != nil {
244257
return nil, fmt.Errorf("Failed to apply config.Transactions[%d]: %w", i, err)
245258
}
246259
stateDB.Finalise(true)
247260

261+
prestate, err := prestateTracer.GetResult()
262+
if err != nil {
263+
return nil, fmt.Errorf("Failed to get prestateTracer result: %w", err)
264+
}
248265
executionResults[i] = &ExecutionResult{
249266
Gas: result.UsedGas,
250267
Failed: result.Failed(),
251268
ReturnValue: fmt.Sprintf("%x", result.ReturnData),
252-
StructLogs: FormatLogs(tracer.StructLogs()),
269+
StructLogs: FormatLogs(structLogger.StructLogs()),
270+
Prestate: prestate,
253271
}
254272
}
255273

256274
return executionResults, nil
257275
}
276+
277+
type MuxTracer struct {
278+
tracers []vm.EVMLogger
279+
}
280+
281+
func NewMuxTracer(tracers ...vm.EVMLogger) *MuxTracer {
282+
return &MuxTracer{tracers}
283+
}
284+
285+
func (t *MuxTracer) CaptureTxStart(gasLimit uint64) {
286+
for _, tracer := range t.tracers {
287+
tracer.CaptureTxStart(gasLimit)
288+
}
289+
}
290+
291+
func (t *MuxTracer) CaptureTxEnd(restGas uint64) {
292+
for _, tracer := range t.tracers {
293+
tracer.CaptureTxEnd(restGas)
294+
}
295+
}
296+
297+
func (t *MuxTracer) CaptureStart(env *vm.EVM, from common.Address, to common.Address, create bool, input []byte, gas uint64, value *big.Int) {
298+
for _, tracer := range t.tracers {
299+
tracer.CaptureStart(env, from, to, create, input, gas, value)
300+
}
301+
}
302+
303+
func (t *MuxTracer) CaptureEnd(output []byte, gasUsed uint64, err error) {
304+
for _, tracer := range t.tracers {
305+
tracer.CaptureEnd(output, gasUsed, err)
306+
}
307+
}
308+
309+
func (t *MuxTracer) CaptureEnter(typ vm.OpCode, from common.Address, to common.Address, input []byte, gas uint64, value *big.Int) {
310+
for _, tracer := range t.tracers {
311+
tracer.CaptureEnter(typ, from, to, input, gas, value)
312+
}
313+
}
314+
315+
func (t *MuxTracer) CaptureExit(output []byte, gasUsed uint64, err error) {
316+
for _, tracer := range t.tracers {
317+
tracer.CaptureExit(output, gasUsed, err)
318+
}
319+
}
320+
321+
func (t *MuxTracer) CaptureState(pc uint64, op vm.OpCode, gas, cost uint64, scope *vm.ScopeContext, rData []byte, depth int, err error) {
322+
for _, tracer := range t.tracers {
323+
tracer.CaptureState(pc, op, gas, cost, scope, rData, depth, err)
324+
}
325+
}
326+
327+
func (t *MuxTracer) CaptureFault(pc uint64, op vm.OpCode, gas, cost uint64, scope *vm.ScopeContext, depth int, err error) {
328+
for _, tracer := range t.tracers {
329+
tracer.CaptureFault(pc, op, gas, cost, scope, depth, err)
330+
}
331+
}

integration-tests/tests/circuit_input_builder.rs

+3-3
Original file line numberDiff line numberDiff line change
@@ -37,12 +37,12 @@ async fn test_circuit_input_builder_block(block_num: u64) {
3737
let (eth_block, geth_trace, history_hashes, prev_state_root) =
3838
cli.get_block(block_num).await.unwrap();
3939

40-
// 2. Get State Accesses from TxExecTraces
41-
let access_set = get_state_accesses(&eth_block, &geth_trace).unwrap();
40+
// 2. Query State Accesses
41+
let access_set = cli.get_state_accesses(&eth_block).await.unwrap();
4242
trace!("AccessSet: {:#?}", access_set);
4343

4444
// 3. Query geth for all accounts, storage keys, and codes from Accesses
45-
let (proofs, codes) = cli.get_state(block_num, access_set.into()).await.unwrap();
45+
let (proofs, codes) = cli.get_state(block_num, access_set).await.unwrap();
4646

4747
// 4. Build a partial StateDB from step 3
4848
let (state_db, code_db) = build_state_code_db(proofs, codes);

mock/src/test_ctx.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -95,7 +95,6 @@ pub struct TestContext<const NACC: usize, const NTX: usize> {
9595
pub eth_block: eth_types::Block<eth_types::Transaction>,
9696
/// Execution Trace from geth
9797
pub geth_traces: Vec<eth_types::GethExecTrace>,
98-
9998
#[cfg(feature = "scroll")]
10099
block_trace: BlockTrace,
101100
}
@@ -108,6 +107,7 @@ impl<const NACC: usize, const NTX: usize> From<TestContext<NACC, NTX>> for GethD
108107
eth_block: ctx.eth_block,
109108
geth_traces: ctx.geth_traces.to_vec(),
110109
accounts: ctx.accounts.into(),
110+
block_trace: ctx.block_trace,
111111
}
112112
}
113113
}

0 commit comments

Comments
 (0)