Unverified Commit 1876cb44 authored by Sina Mahmoodi's avatar Sina Mahmoodi Committed by GitHub

all: move loggers to eth/tracers (#23892)

* all: mv loggers to eth/tracers

* core/vm: minor

* eth/tracers: tmp comment out testStoreCapture

* eth/tracers: uncomment and fix logger test

* eth/tracers: simplify test

* core/vm: re-add license

* core/vm: minor

* rename LogConfig to Config
parent 9055cc14
...@@ -34,6 +34,7 @@ import ( ...@@ -34,6 +34,7 @@ import (
"github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/core/vm" "github.com/ethereum/go-ethereum/core/vm"
"github.com/ethereum/go-ethereum/crypto" "github.com/ethereum/go-ethereum/crypto"
"github.com/ethereum/go-ethereum/eth/tracers/logger"
"github.com/ethereum/go-ethereum/log" "github.com/ethereum/go-ethereum/log"
"github.com/ethereum/go-ethereum/params" "github.com/ethereum/go-ethereum/params"
"github.com/ethereum/go-ethereum/rlp" "github.com/ethereum/go-ethereum/rlp"
...@@ -112,7 +113,7 @@ func Transition(ctx *cli.Context) error { ...@@ -112,7 +113,7 @@ func Transition(ctx *cli.Context) error {
log.Warn(fmt.Sprintf("--%s has been deprecated in favour of --%s", TraceDisableReturnDataFlag.Name, TraceEnableReturnDataFlag.Name)) log.Warn(fmt.Sprintf("--%s has been deprecated in favour of --%s", TraceDisableReturnDataFlag.Name, TraceEnableReturnDataFlag.Name))
} }
// Configure the EVM logger // Configure the EVM logger
logConfig := &vm.LogConfig{ logConfig := &logger.Config{
DisableStack: ctx.Bool(TraceDisableStackFlag.Name), DisableStack: ctx.Bool(TraceDisableStackFlag.Name),
EnableMemory: !ctx.Bool(TraceDisableMemoryFlag.Name) || ctx.Bool(TraceEnableMemoryFlag.Name), EnableMemory: !ctx.Bool(TraceDisableMemoryFlag.Name) || ctx.Bool(TraceEnableMemoryFlag.Name),
EnableReturnData: !ctx.Bool(TraceDisableReturnDataFlag.Name) || ctx.Bool(TraceEnableReturnDataFlag.Name), EnableReturnData: !ctx.Bool(TraceDisableReturnDataFlag.Name) || ctx.Bool(TraceEnableReturnDataFlag.Name),
...@@ -134,7 +135,7 @@ func Transition(ctx *cli.Context) error { ...@@ -134,7 +135,7 @@ func Transition(ctx *cli.Context) error {
return nil, NewError(ErrorIO, fmt.Errorf("failed creating trace-file: %v", err)) return nil, NewError(ErrorIO, fmt.Errorf("failed creating trace-file: %v", err))
} }
prevFile = traceFile prevFile = traceFile
return vm.NewJSONLogger(logConfig, traceFile), nil return logger.NewJSONLogger(logConfig, traceFile), nil
} }
} else { } else {
getTracer = func(txIndex int, txHash common.Hash) (tracer vm.EVMLogger, err error) { getTracer = func(txIndex int, txHash common.Hash) (tracer vm.EVMLogger, err error) {
......
...@@ -36,6 +36,7 @@ import ( ...@@ -36,6 +36,7 @@ import (
"github.com/ethereum/go-ethereum/core/state" "github.com/ethereum/go-ethereum/core/state"
"github.com/ethereum/go-ethereum/core/vm" "github.com/ethereum/go-ethereum/core/vm"
"github.com/ethereum/go-ethereum/core/vm/runtime" "github.com/ethereum/go-ethereum/core/vm/runtime"
"github.com/ethereum/go-ethereum/eth/tracers/logger"
"github.com/ethereum/go-ethereum/log" "github.com/ethereum/go-ethereum/log"
"github.com/ethereum/go-ethereum/params" "github.com/ethereum/go-ethereum/params"
"gopkg.in/urfave/cli.v1" "gopkg.in/urfave/cli.v1"
...@@ -107,7 +108,7 @@ func runCmd(ctx *cli.Context) error { ...@@ -107,7 +108,7 @@ func runCmd(ctx *cli.Context) error {
glogger := log.NewGlogHandler(log.StreamHandler(os.Stderr, log.TerminalFormat(false))) glogger := log.NewGlogHandler(log.StreamHandler(os.Stderr, log.TerminalFormat(false)))
glogger.Verbosity(log.Lvl(ctx.GlobalInt(VerbosityFlag.Name))) glogger.Verbosity(log.Lvl(ctx.GlobalInt(VerbosityFlag.Name)))
log.Root().SetHandler(glogger) log.Root().SetHandler(glogger)
logconfig := &vm.LogConfig{ logconfig := &logger.Config{
EnableMemory: !ctx.GlobalBool(DisableMemoryFlag.Name), EnableMemory: !ctx.GlobalBool(DisableMemoryFlag.Name),
DisableStack: ctx.GlobalBool(DisableStackFlag.Name), DisableStack: ctx.GlobalBool(DisableStackFlag.Name),
DisableStorage: ctx.GlobalBool(DisableStorageFlag.Name), DisableStorage: ctx.GlobalBool(DisableStorageFlag.Name),
...@@ -117,7 +118,7 @@ func runCmd(ctx *cli.Context) error { ...@@ -117,7 +118,7 @@ func runCmd(ctx *cli.Context) error {
var ( var (
tracer vm.EVMLogger tracer vm.EVMLogger
debugLogger *vm.StructLogger debugLogger *logger.StructLogger
statedb *state.StateDB statedb *state.StateDB
chainConfig *params.ChainConfig chainConfig *params.ChainConfig
sender = common.BytesToAddress([]byte("sender")) sender = common.BytesToAddress([]byte("sender"))
...@@ -125,12 +126,12 @@ func runCmd(ctx *cli.Context) error { ...@@ -125,12 +126,12 @@ func runCmd(ctx *cli.Context) error {
genesisConfig *core.Genesis genesisConfig *core.Genesis
) )
if ctx.GlobalBool(MachineFlag.Name) { if ctx.GlobalBool(MachineFlag.Name) {
tracer = vm.NewJSONLogger(logconfig, os.Stdout) tracer = logger.NewJSONLogger(logconfig, os.Stdout)
} else if ctx.GlobalBool(DebugFlag.Name) { } else if ctx.GlobalBool(DebugFlag.Name) {
debugLogger = vm.NewStructLogger(logconfig) debugLogger = logger.NewStructLogger(logconfig)
tracer = debugLogger tracer = debugLogger
} else { } else {
debugLogger = vm.NewStructLogger(logconfig) debugLogger = logger.NewStructLogger(logconfig)
} }
if ctx.GlobalString(GenesisFlag.Name) != "" { if ctx.GlobalString(GenesisFlag.Name) != "" {
gen := readGenesis(ctx.GlobalString(GenesisFlag.Name)) gen := readGenesis(ctx.GlobalString(GenesisFlag.Name))
...@@ -288,10 +289,10 @@ func runCmd(ctx *cli.Context) error { ...@@ -288,10 +289,10 @@ func runCmd(ctx *cli.Context) error {
if ctx.GlobalBool(DebugFlag.Name) { if ctx.GlobalBool(DebugFlag.Name) {
if debugLogger != nil { if debugLogger != nil {
fmt.Fprintln(os.Stderr, "#### TRACE ####") fmt.Fprintln(os.Stderr, "#### TRACE ####")
vm.WriteTrace(os.Stderr, debugLogger.StructLogs()) logger.WriteTrace(os.Stderr, debugLogger.StructLogs())
} }
fmt.Fprintln(os.Stderr, "#### LOGS ####") fmt.Fprintln(os.Stderr, "#### LOGS ####")
vm.WriteLogs(os.Stderr, statedb.Logs()) logger.WriteLogs(os.Stderr, statedb.Logs())
} }
if bench || ctx.GlobalBool(StatDumpFlag.Name) { if bench || ctx.GlobalBool(StatDumpFlag.Name) {
......
...@@ -25,6 +25,7 @@ import ( ...@@ -25,6 +25,7 @@ import (
"github.com/ethereum/go-ethereum/core/state" "github.com/ethereum/go-ethereum/core/state"
"github.com/ethereum/go-ethereum/core/vm" "github.com/ethereum/go-ethereum/core/vm"
"github.com/ethereum/go-ethereum/eth/tracers/logger"
"github.com/ethereum/go-ethereum/log" "github.com/ethereum/go-ethereum/log"
"github.com/ethereum/go-ethereum/tests" "github.com/ethereum/go-ethereum/tests"
...@@ -58,7 +59,7 @@ func stateTestCmd(ctx *cli.Context) error { ...@@ -58,7 +59,7 @@ func stateTestCmd(ctx *cli.Context) error {
log.Root().SetHandler(glogger) log.Root().SetHandler(glogger)
// Configure the EVM logger // Configure the EVM logger
config := &vm.LogConfig{ config := &logger.Config{
EnableMemory: !ctx.GlobalBool(DisableMemoryFlag.Name), EnableMemory: !ctx.GlobalBool(DisableMemoryFlag.Name),
DisableStack: ctx.GlobalBool(DisableStackFlag.Name), DisableStack: ctx.GlobalBool(DisableStackFlag.Name),
DisableStorage: ctx.GlobalBool(DisableStorageFlag.Name), DisableStorage: ctx.GlobalBool(DisableStorageFlag.Name),
...@@ -66,18 +67,18 @@ func stateTestCmd(ctx *cli.Context) error { ...@@ -66,18 +67,18 @@ func stateTestCmd(ctx *cli.Context) error {
} }
var ( var (
tracer vm.EVMLogger tracer vm.EVMLogger
debugger *vm.StructLogger debugger *logger.StructLogger
) )
switch { switch {
case ctx.GlobalBool(MachineFlag.Name): case ctx.GlobalBool(MachineFlag.Name):
tracer = vm.NewJSONLogger(config, os.Stderr) tracer = logger.NewJSONLogger(config, os.Stderr)
case ctx.GlobalBool(DebugFlag.Name): case ctx.GlobalBool(DebugFlag.Name):
debugger = vm.NewStructLogger(config) debugger = logger.NewStructLogger(config)
tracer = debugger tracer = debugger
default: default:
debugger = vm.NewStructLogger(config) debugger = logger.NewStructLogger(config)
} }
// Load the test content from the input file // Load the test content from the input file
src, err := ioutil.ReadFile(ctx.Args().First()) src, err := ioutil.ReadFile(ctx.Args().First())
...@@ -118,7 +119,7 @@ func stateTestCmd(ctx *cli.Context) error { ...@@ -118,7 +119,7 @@ func stateTestCmd(ctx *cli.Context) error {
if ctx.GlobalBool(DebugFlag.Name) { if ctx.GlobalBool(DebugFlag.Name) {
if debugger != nil { if debugger != nil {
fmt.Fprintln(os.Stderr, "#### TRACE ####") fmt.Fprintln(os.Stderr, "#### TRACE ####")
vm.WriteTrace(os.Stderr, debugger.StructLogs()) logger.WriteTrace(os.Stderr, debugger.StructLogs())
} }
} }
} }
......
...@@ -35,6 +35,7 @@ import ( ...@@ -35,6 +35,7 @@ import (
"github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/core/vm" "github.com/ethereum/go-ethereum/core/vm"
"github.com/ethereum/go-ethereum/crypto" "github.com/ethereum/go-ethereum/crypto"
"github.com/ethereum/go-ethereum/eth/tracers/logger"
"github.com/ethereum/go-ethereum/ethdb" "github.com/ethereum/go-ethereum/ethdb"
"github.com/ethereum/go-ethereum/params" "github.com/ethereum/go-ethereum/params"
"github.com/ethereum/go-ethereum/trie" "github.com/ethereum/go-ethereum/trie"
...@@ -2690,7 +2691,7 @@ func TestDeleteRecreateSlots(t *testing.T) { ...@@ -2690,7 +2691,7 @@ func TestDeleteRecreateSlots(t *testing.T) {
gspec.MustCommit(diskdb) gspec.MustCommit(diskdb)
chain, err := NewBlockChain(diskdb, nil, params.TestChainConfig, engine, vm.Config{ chain, err := NewBlockChain(diskdb, nil, params.TestChainConfig, engine, vm.Config{
Debug: true, Debug: true,
Tracer: vm.NewJSONLogger(nil, os.Stdout), Tracer: logger.NewJSONLogger(nil, os.Stdout),
}, nil, nil) }, nil, nil)
if err != nil { if err != nil {
t.Fatalf("failed to create tester chain: %v", err) t.Fatalf("failed to create tester chain: %v", err)
...@@ -2770,7 +2771,7 @@ func TestDeleteRecreateAccount(t *testing.T) { ...@@ -2770,7 +2771,7 @@ func TestDeleteRecreateAccount(t *testing.T) {
gspec.MustCommit(diskdb) gspec.MustCommit(diskdb)
chain, err := NewBlockChain(diskdb, nil, params.TestChainConfig, engine, vm.Config{ chain, err := NewBlockChain(diskdb, nil, params.TestChainConfig, engine, vm.Config{
Debug: true, Debug: true,
Tracer: vm.NewJSONLogger(nil, os.Stdout), Tracer: logger.NewJSONLogger(nil, os.Stdout),
}, nil, nil) }, nil, nil)
if err != nil { if err != nil {
t.Fatalf("failed to create tester chain: %v", err) t.Fatalf("failed to create tester chain: %v", err)
......
This diff is collapsed.
...@@ -34,6 +34,7 @@ import ( ...@@ -34,6 +34,7 @@ import (
"github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/core/vm" "github.com/ethereum/go-ethereum/core/vm"
"github.com/ethereum/go-ethereum/eth/tracers" "github.com/ethereum/go-ethereum/eth/tracers"
"github.com/ethereum/go-ethereum/eth/tracers/logger"
"github.com/ethereum/go-ethereum/params" "github.com/ethereum/go-ethereum/params"
// force-load js tracers to trigger registration // force-load js tracers to trigger registration
...@@ -326,7 +327,7 @@ func TestBlockhash(t *testing.T) { ...@@ -326,7 +327,7 @@ func TestBlockhash(t *testing.T) {
} }
type stepCounter struct { type stepCounter struct {
inner *vm.JSONLogger inner *logger.JSONLogger
steps int steps int
} }
...@@ -493,7 +494,7 @@ func BenchmarkSimpleLoop(b *testing.B) { ...@@ -493,7 +494,7 @@ func BenchmarkSimpleLoop(b *testing.B) {
byte(vm.JUMP), byte(vm.JUMP),
} }
//tracer := vm.NewJSONLogger(nil, os.Stdout) //tracer := logger.NewJSONLogger(nil, os.Stdout)
//Execute(loopingCode, nil, &Config{ //Execute(loopingCode, nil, &Config{
// EVMConfig: vm.Config{ // EVMConfig: vm.Config{
// Debug: true, // Debug: true,
...@@ -536,7 +537,7 @@ func TestEip2929Cases(t *testing.T) { ...@@ -536,7 +537,7 @@ func TestEip2929Cases(t *testing.T) {
Execute(code, nil, &Config{ Execute(code, nil, &Config{
EVMConfig: vm.Config{ EVMConfig: vm.Config{
Debug: true, Debug: true,
Tracer: vm.NewMarkdownLogger(nil, os.Stdout), Tracer: logger.NewMarkdownLogger(nil, os.Stdout),
ExtraEips: []int{2929}, ExtraEips: []int{2929},
}, },
}) })
...@@ -686,7 +687,7 @@ func TestColdAccountAccessCost(t *testing.T) { ...@@ -686,7 +687,7 @@ func TestColdAccountAccessCost(t *testing.T) {
want: 7600, want: 7600,
}, },
} { } {
tracer := vm.NewStructLogger(nil) tracer := logger.NewStructLogger(nil)
Execute(tc.code, nil, &Config{ Execute(tc.code, nil, &Config{
EVMConfig: vm.Config{ EVMConfig: vm.Config{
Debug: true, Debug: true,
......
...@@ -36,6 +36,7 @@ import ( ...@@ -36,6 +36,7 @@ import (
"github.com/ethereum/go-ethereum/core/state" "github.com/ethereum/go-ethereum/core/state"
"github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/core/vm" "github.com/ethereum/go-ethereum/core/vm"
"github.com/ethereum/go-ethereum/eth/tracers/logger"
"github.com/ethereum/go-ethereum/ethdb" "github.com/ethereum/go-ethereum/ethdb"
"github.com/ethereum/go-ethereum/internal/ethapi" "github.com/ethereum/go-ethereum/internal/ethapi"
"github.com/ethereum/go-ethereum/log" "github.com/ethereum/go-ethereum/log"
...@@ -165,7 +166,7 @@ func (api *API) blockByNumberAndHash(ctx context.Context, number rpc.BlockNumber ...@@ -165,7 +166,7 @@ func (api *API) blockByNumberAndHash(ctx context.Context, number rpc.BlockNumber
// TraceConfig holds extra parameters to trace functions. // TraceConfig holds extra parameters to trace functions.
type TraceConfig struct { type TraceConfig struct {
*vm.LogConfig *logger.Config
Tracer *string Tracer *string
Timeout *string Timeout *string
Reexec *uint64 Reexec *uint64
...@@ -174,7 +175,7 @@ type TraceConfig struct { ...@@ -174,7 +175,7 @@ type TraceConfig struct {
// TraceCallConfig is the config for traceCall API. It holds one more // TraceCallConfig is the config for traceCall API. It holds one more
// field to override the state for tracing. // field to override the state for tracing.
type TraceCallConfig struct { type TraceCallConfig struct {
*vm.LogConfig *logger.Config
Tracer *string Tracer *string
Timeout *string Timeout *string
Reexec *uint64 Reexec *uint64
...@@ -183,7 +184,7 @@ type TraceCallConfig struct { ...@@ -183,7 +184,7 @@ type TraceCallConfig struct {
// StdTraceConfig holds extra parameters to standard-json trace functions. // StdTraceConfig holds extra parameters to standard-json trace functions.
type StdTraceConfig struct { type StdTraceConfig struct {
vm.LogConfig logger.Config
Reexec *uint64 Reexec *uint64
TxHash common.Hash TxHash common.Hash
} }
...@@ -669,11 +670,11 @@ func (api *API) standardTraceBlockToFile(ctx context.Context, block *types.Block ...@@ -669,11 +670,11 @@ func (api *API) standardTraceBlockToFile(ctx context.Context, block *types.Block
} }
// Retrieve the tracing configurations, or use default values // Retrieve the tracing configurations, or use default values
var ( var (
logConfig vm.LogConfig logConfig logger.Config
txHash common.Hash txHash common.Hash
) )
if config != nil { if config != nil {
logConfig = config.LogConfig logConfig = config.Config
txHash = config.TxHash txHash = config.TxHash
} }
logConfig.Debug = true logConfig.Debug = true
...@@ -698,7 +699,7 @@ func (api *API) standardTraceBlockToFile(ctx context.Context, block *types.Block ...@@ -698,7 +699,7 @@ func (api *API) standardTraceBlockToFile(ctx context.Context, block *types.Block
chainConfigCopy := new(params.ChainConfig) chainConfigCopy := new(params.ChainConfig)
*chainConfigCopy = *chainConfig *chainConfigCopy = *chainConfig
chainConfig = chainConfigCopy chainConfig = chainConfigCopy
if berlin := config.LogConfig.Overrides.BerlinBlock; berlin != nil { if berlin := config.Config.Overrides.BerlinBlock; berlin != nil {
chainConfig.BerlinBlock = berlin chainConfig.BerlinBlock = berlin
canon = false canon = false
} }
...@@ -730,7 +731,7 @@ func (api *API) standardTraceBlockToFile(ctx context.Context, block *types.Block ...@@ -730,7 +731,7 @@ func (api *API) standardTraceBlockToFile(ctx context.Context, block *types.Block
writer = bufio.NewWriter(dump) writer = bufio.NewWriter(dump)
vmConf = vm.Config{ vmConf = vm.Config{
Debug: true, Debug: true,
Tracer: vm.NewJSONLogger(&logConfig, writer), Tracer: logger.NewJSONLogger(&logConfig, writer),
EnablePreimageRecording: true, EnablePreimageRecording: true,
} }
} }
...@@ -847,7 +848,7 @@ func (api *API) TraceCall(ctx context.Context, args ethapi.TransactionArgs, bloc ...@@ -847,7 +848,7 @@ func (api *API) TraceCall(ctx context.Context, args ethapi.TransactionArgs, bloc
var traceConfig *TraceConfig var traceConfig *TraceConfig
if config != nil { if config != nil {
traceConfig = &TraceConfig{ traceConfig = &TraceConfig{
LogConfig: config.LogConfig, Config: config.Config,
Tracer: config.Tracer, Tracer: config.Tracer,
Timeout: config.Timeout, Timeout: config.Timeout,
Reexec: config.Reexec, Reexec: config.Reexec,
...@@ -868,7 +869,7 @@ func (api *API) traceTx(ctx context.Context, message core.Message, txctx *Contex ...@@ -868,7 +869,7 @@ func (api *API) traceTx(ctx context.Context, message core.Message, txctx *Contex
) )
switch { switch {
case config == nil: case config == nil:
tracer = vm.NewStructLogger(nil) tracer = logger.NewStructLogger(nil)
case config.Tracer != nil: case config.Tracer != nil:
// Define a meaningful timeout of a single transaction trace // Define a meaningful timeout of a single transaction trace
timeout := defaultTraceTimeout timeout := defaultTraceTimeout
...@@ -891,7 +892,7 @@ func (api *API) traceTx(ctx context.Context, message core.Message, txctx *Contex ...@@ -891,7 +892,7 @@ func (api *API) traceTx(ctx context.Context, message core.Message, txctx *Contex
tracer = t tracer = t
} }
default: default:
tracer = vm.NewStructLogger(config.LogConfig) tracer = logger.NewStructLogger(config.Config)
} }
// Run the transaction with tracing enabled. // Run the transaction with tracing enabled.
vmenv := vm.NewEVM(vmctx, txContext, statedb, api.backend.ChainConfig(), vm.Config{Debug: true, Tracer: tracer, NoBaseFee: true}) vmenv := vm.NewEVM(vmctx, txContext, statedb, api.backend.ChainConfig(), vm.Config{Debug: true, Tracer: tracer, NoBaseFee: true})
...@@ -906,7 +907,7 @@ func (api *API) traceTx(ctx context.Context, message core.Message, txctx *Contex ...@@ -906,7 +907,7 @@ func (api *API) traceTx(ctx context.Context, message core.Message, txctx *Contex
// Depending on the tracer type, format and return the output. // Depending on the tracer type, format and return the output.
switch tracer := tracer.(type) { switch tracer := tracer.(type) {
case *vm.StructLogger: case *logger.StructLogger:
// If the result contains a revert reason, return it. // If the result contains a revert reason, return it.
returnVal := fmt.Sprintf("%x", result.Return()) returnVal := fmt.Sprintf("%x", result.Return())
if len(result.Revert()) > 0 { if len(result.Revert()) > 0 {
......
...@@ -14,7 +14,7 @@ ...@@ -14,7 +14,7 @@
// You should have received a copy of the GNU Lesser General Public License // You should have received a copy of the GNU Lesser General Public License
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>. // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
package vm package logger
import ( import (
"math/big" "math/big"
...@@ -22,6 +22,7 @@ import ( ...@@ -22,6 +22,7 @@ import (
"github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/core/vm"
) )
// accessList is an accumulator for the set of accounts and storage slots an EVM // accessList is an accumulator for the set of accounts and storage slots an EVM
...@@ -137,36 +138,38 @@ func NewAccessListTracer(acl types.AccessList, from, to common.Address, precompi ...@@ -137,36 +138,38 @@ func NewAccessListTracer(acl types.AccessList, from, to common.Address, precompi
} }
} }
func (a *AccessListTracer) CaptureStart(env *EVM, from common.Address, to common.Address, create bool, input []byte, gas uint64, value *big.Int) { func (a *AccessListTracer) CaptureStart(env *vm.EVM, from common.Address, to common.Address, create bool, input []byte, gas uint64, value *big.Int) {
} }
// CaptureState captures all opcodes that touch storage or addresses and adds them to the accesslist. // CaptureState captures all opcodes that touch storage or addresses and adds them to the accesslist.
func (a *AccessListTracer) CaptureState(pc uint64, op OpCode, gas, cost uint64, scope *ScopeContext, rData []byte, depth int, err error) { func (a *AccessListTracer) CaptureState(pc uint64, op vm.OpCode, gas, cost uint64, scope *vm.ScopeContext, rData []byte, depth int, err error) {
stack := scope.Stack stack := scope.Stack
if (op == SLOAD || op == SSTORE) && stack.len() >= 1 { stackData := stack.Data()
slot := common.Hash(stack.data[stack.len()-1].Bytes32()) stackLen := len(stackData)
if (op == vm.SLOAD || op == vm.SSTORE) && stackLen >= 1 {
slot := common.Hash(stackData[stackLen-1].Bytes32())
a.list.addSlot(scope.Contract.Address(), slot) a.list.addSlot(scope.Contract.Address(), slot)
} }
if (op == EXTCODECOPY || op == EXTCODEHASH || op == EXTCODESIZE || op == BALANCE || op == SELFDESTRUCT) && stack.len() >= 1 { if (op == vm.EXTCODECOPY || op == vm.EXTCODEHASH || op == vm.EXTCODESIZE || op == vm.BALANCE || op == vm.SELFDESTRUCT) && stackLen >= 1 {
addr := common.Address(stack.data[stack.len()-1].Bytes20()) addr := common.Address(stackData[stackLen-1].Bytes20())
if _, ok := a.excl[addr]; !ok { if _, ok := a.excl[addr]; !ok {
a.list.addAddress(addr) a.list.addAddress(addr)
} }
} }
if (op == DELEGATECALL || op == CALL || op == STATICCALL || op == CALLCODE) && stack.len() >= 5 { if (op == vm.DELEGATECALL || op == vm.CALL || op == vm.STATICCALL || op == vm.CALLCODE) && stackLen >= 5 {
addr := common.Address(stack.data[stack.len()-2].Bytes20()) addr := common.Address(stackData[stackLen-2].Bytes20())
if _, ok := a.excl[addr]; !ok { if _, ok := a.excl[addr]; !ok {
a.list.addAddress(addr) a.list.addAddress(addr)
} }
} }
} }
func (*AccessListTracer) CaptureFault(pc uint64, op OpCode, gas, cost uint64, scope *ScopeContext, depth int, err error) { func (*AccessListTracer) CaptureFault(pc uint64, op vm.OpCode, gas, cost uint64, scope *vm.ScopeContext, depth int, err error) {
} }
func (*AccessListTracer) CaptureEnd(output []byte, gasUsed uint64, t time.Duration, err error) {} func (*AccessListTracer) CaptureEnd(output []byte, gasUsed uint64, t time.Duration, err error) {}
func (*AccessListTracer) CaptureEnter(typ OpCode, from common.Address, to common.Address, input []byte, gas uint64, value *big.Int) { func (*AccessListTracer) CaptureEnter(typ vm.OpCode, from common.Address, to common.Address, input []byte, gas uint64, value *big.Int) {
} }
func (*AccessListTracer) CaptureExit(output []byte, gasUsed uint64, err error) {} func (*AccessListTracer) CaptureExit(output []byte, gasUsed uint64, err error) {}
......
// Code generated by github.com/fjl/gencodec. DO NOT EDIT. // Code generated by github.com/fjl/gencodec. DO NOT EDIT.
package vm package logger
import ( import (
"encoding/json" "encoding/json"
...@@ -8,6 +8,7 @@ import ( ...@@ -8,6 +8,7 @@ import (
"github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/common/hexutil" "github.com/ethereum/go-ethereum/common/hexutil"
"github.com/ethereum/go-ethereum/common/math" "github.com/ethereum/go-ethereum/common/math"
"github.com/ethereum/go-ethereum/core/vm"
"github.com/holiman/uint256" "github.com/holiman/uint256"
) )
...@@ -17,7 +18,7 @@ var _ = (*structLogMarshaling)(nil) ...@@ -17,7 +18,7 @@ var _ = (*structLogMarshaling)(nil)
func (s StructLog) MarshalJSON() ([]byte, error) { func (s StructLog) MarshalJSON() ([]byte, error) {
type StructLog struct { type StructLog struct {
Pc uint64 `json:"pc"` Pc uint64 `json:"pc"`
Op OpCode `json:"op"` Op vm.OpCode `json:"op"`
Gas math.HexOrDecimal64 `json:"gas"` Gas math.HexOrDecimal64 `json:"gas"`
GasCost math.HexOrDecimal64 `json:"gasCost"` GasCost math.HexOrDecimal64 `json:"gasCost"`
Memory hexutil.Bytes `json:"memory"` Memory hexutil.Bytes `json:"memory"`
...@@ -53,7 +54,7 @@ func (s StructLog) MarshalJSON() ([]byte, error) { ...@@ -53,7 +54,7 @@ func (s StructLog) MarshalJSON() ([]byte, error) {
func (s *StructLog) UnmarshalJSON(input []byte) error { func (s *StructLog) UnmarshalJSON(input []byte) error {
type StructLog struct { type StructLog struct {
Pc *uint64 `json:"pc"` Pc *uint64 `json:"pc"`
Op *OpCode `json:"op"` Op *vm.OpCode `json:"op"`
Gas *math.HexOrDecimal64 `json:"gas"` Gas *math.HexOrDecimal64 `json:"gas"`
GasCost *math.HexOrDecimal64 `json:"gasCost"` GasCost *math.HexOrDecimal64 `json:"gasCost"`
Memory *hexutil.Bytes `json:"memory"` Memory *hexutil.Bytes `json:"memory"`
......
This diff is collapsed.
...@@ -14,7 +14,7 @@ ...@@ -14,7 +14,7 @@
// You should have received a copy of the GNU Lesser General Public License // You should have received a copy of the GNU Lesser General Public License
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>. // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
package vm package logger
import ( import (
"encoding/json" "encoding/json"
...@@ -24,32 +24,33 @@ import ( ...@@ -24,32 +24,33 @@ import (
"github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/common/math" "github.com/ethereum/go-ethereum/common/math"
"github.com/ethereum/go-ethereum/core/vm"
) )
type JSONLogger struct { type JSONLogger struct {
encoder *json.Encoder encoder *json.Encoder
cfg *LogConfig cfg *Config
env *EVM env *vm.EVM
} }
// NewJSONLogger creates a new EVM tracer that prints execution steps as JSON objects // NewJSONLogger creates a new EVM tracer that prints execution steps as JSON objects
// into the provided stream. // into the provided stream.
func NewJSONLogger(cfg *LogConfig, writer io.Writer) *JSONLogger { func NewJSONLogger(cfg *Config, writer io.Writer) *JSONLogger {
l := &JSONLogger{encoder: json.NewEncoder(writer), cfg: cfg} l := &JSONLogger{encoder: json.NewEncoder(writer), cfg: cfg}
if l.cfg == nil { if l.cfg == nil {
l.cfg = &LogConfig{} l.cfg = &Config{}
} }
return l return l
} }
func (l *JSONLogger) CaptureStart(env *EVM, from, to common.Address, create bool, input []byte, gas uint64, value *big.Int) { func (l *JSONLogger) CaptureStart(env *vm.EVM, from, to common.Address, create bool, input []byte, gas uint64, value *big.Int) {
l.env = env l.env = env
} }
func (l *JSONLogger) CaptureFault(uint64, OpCode, uint64, uint64, *ScopeContext, int, error) {} func (l *JSONLogger) CaptureFault(uint64, vm.OpCode, uint64, uint64, *vm.ScopeContext, int, error) {}
// CaptureState outputs state information on the logger. // CaptureState outputs state information on the logger.
func (l *JSONLogger) CaptureState(pc uint64, op OpCode, gas, cost uint64, scope *ScopeContext, rData []byte, depth int, err error) { func (l *JSONLogger) CaptureState(pc uint64, op vm.OpCode, gas, cost uint64, scope *vm.ScopeContext, rData []byte, depth int, err error) {
memory := scope.Memory memory := scope.Memory
stack := scope.Stack stack := scope.Stack
...@@ -67,7 +68,7 @@ func (l *JSONLogger) CaptureState(pc uint64, op OpCode, gas, cost uint64, scope ...@@ -67,7 +68,7 @@ func (l *JSONLogger) CaptureState(pc uint64, op OpCode, gas, cost uint64, scope
log.Memory = memory.Data() log.Memory = memory.Data()
} }
if !l.cfg.DisableStack { if !l.cfg.DisableStack {
log.Stack = stack.data log.Stack = stack.Data()
} }
if l.cfg.EnableReturnData { if l.cfg.EnableReturnData {
log.ReturnData = rData log.ReturnData = rData
...@@ -90,7 +91,7 @@ func (l *JSONLogger) CaptureEnd(output []byte, gasUsed uint64, t time.Duration, ...@@ -90,7 +91,7 @@ func (l *JSONLogger) CaptureEnd(output []byte, gasUsed uint64, t time.Duration,
l.encoder.Encode(endLog{common.Bytes2Hex(output), math.HexOrDecimal64(gasUsed), t, errMsg}) l.encoder.Encode(endLog{common.Bytes2Hex(output), math.HexOrDecimal64(gasUsed), t, errMsg})
} }
func (l *JSONLogger) CaptureEnter(typ OpCode, from common.Address, to common.Address, input []byte, gas uint64, value *big.Int) { func (l *JSONLogger) CaptureEnter(typ vm.OpCode, from common.Address, to common.Address, input []byte, gas uint64, value *big.Int) {
} }
func (l *JSONLogger) CaptureExit(output []byte, gasUsed uint64, err error) {} func (l *JSONLogger) CaptureExit(output []byte, gasUsed uint64, err error) {}
...@@ -14,7 +14,7 @@ ...@@ -14,7 +14,7 @@
// You should have received a copy of the GNU Lesser General Public License // You should have received a copy of the GNU Lesser General Public License
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>. // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
package vm package logger
import ( import (
"math/big" "math/big"
...@@ -22,8 +22,8 @@ import ( ...@@ -22,8 +22,8 @@ import (
"github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core/state" "github.com/ethereum/go-ethereum/core/state"
"github.com/ethereum/go-ethereum/core/vm"
"github.com/ethereum/go-ethereum/params" "github.com/ethereum/go-ethereum/params"
"github.com/holiman/uint256"
) )
type dummyContractRef struct { type dummyContractRef struct {
...@@ -47,23 +47,22 @@ type dummyStatedb struct { ...@@ -47,23 +47,22 @@ type dummyStatedb struct {
} }
func (*dummyStatedb) GetRefund() uint64 { return 1337 } func (*dummyStatedb) GetRefund() uint64 { return 1337 }
func (*dummyStatedb) GetState(_ common.Address, _ common.Hash) common.Hash { return common.Hash{} }
func (*dummyStatedb) SetState(_ common.Address, _ common.Hash, _ common.Hash) {}
func TestStoreCapture(t *testing.T) { func TestStoreCapture(t *testing.T) {
var ( var (
env = NewEVM(BlockContext{}, TxContext{}, &dummyStatedb{}, params.TestChainConfig, Config{})
logger = NewStructLogger(nil) logger = NewStructLogger(nil)
contract = NewContract(&dummyContractRef{}, &dummyContractRef{}, new(big.Int), 0) env = vm.NewEVM(vm.BlockContext{}, vm.TxContext{}, &dummyStatedb{}, params.TestChainConfig, vm.Config{Debug: true, Tracer: logger})
scope = &ScopeContext{ contract = vm.NewContract(&dummyContractRef{}, &dummyContractRef{}, new(big.Int), 100000)
Memory: NewMemory(),
Stack: newstack(),
Contract: contract,
}
) )
scope.Stack.push(uint256.NewInt(1)) contract.Code = []byte{byte(vm.PUSH1), 0x1, byte(vm.PUSH1), 0x0, byte(vm.SSTORE)}
scope.Stack.push(new(uint256.Int))
var index common.Hash var index common.Hash
logger.CaptureStart(env, common.Address{}, contract.Address(), false, nil, 0, nil) logger.CaptureStart(env, common.Address{}, contract.Address(), false, nil, 0, nil)
logger.CaptureState(0, SSTORE, 0, 0, scope, nil, 0, nil) _, err := env.Interpreter().Run(contract, []byte{}, false)
if err != nil {
t.Fatal(err)
}
if len(logger.storage[contract.Address()]) == 0 { if len(logger.storage[contract.Address()]) == 0 {
t.Fatalf("expected exactly 1 changed value on address %x, got %d", contract.Address(), t.Fatalf("expected exactly 1 changed value on address %x, got %d", contract.Address(),
len(logger.storage[contract.Address()])) len(logger.storage[contract.Address()]))
......
...@@ -27,6 +27,7 @@ import ( ...@@ -27,6 +27,7 @@ import (
"github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/core/vm" "github.com/ethereum/go-ethereum/core/vm"
"github.com/ethereum/go-ethereum/crypto" "github.com/ethereum/go-ethereum/crypto"
"github.com/ethereum/go-ethereum/eth/tracers/logger"
"github.com/ethereum/go-ethereum/params" "github.com/ethereum/go-ethereum/params"
"github.com/ethereum/go-ethereum/tests" "github.com/ethereum/go-ethereum/tests"
) )
...@@ -95,7 +96,7 @@ func BenchmarkTransactionTrace(b *testing.B) { ...@@ -95,7 +96,7 @@ func BenchmarkTransactionTrace(b *testing.B) {
} }
_, statedb := tests.MakePreState(rawdb.NewMemoryDatabase(), alloc, false) _, statedb := tests.MakePreState(rawdb.NewMemoryDatabase(), alloc, false)
// Create the tracer, the EVM environment and run it // Create the tracer, the EVM environment and run it
tracer := vm.NewStructLogger(&vm.LogConfig{ tracer := logger.NewStructLogger(&logger.Config{
Debug: false, Debug: false,
//DisableStorage: true, //DisableStorage: true,
//EnableMemory: false, //EnableMemory: false,
......
...@@ -40,6 +40,7 @@ import ( ...@@ -40,6 +40,7 @@ import (
"github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/core/vm" "github.com/ethereum/go-ethereum/core/vm"
"github.com/ethereum/go-ethereum/crypto" "github.com/ethereum/go-ethereum/crypto"
"github.com/ethereum/go-ethereum/eth/tracers/logger"
"github.com/ethereum/go-ethereum/log" "github.com/ethereum/go-ethereum/log"
"github.com/ethereum/go-ethereum/p2p" "github.com/ethereum/go-ethereum/p2p"
"github.com/ethereum/go-ethereum/params" "github.com/ethereum/go-ethereum/params"
...@@ -1138,7 +1139,7 @@ type StructLogRes struct { ...@@ -1138,7 +1139,7 @@ type StructLogRes struct {
} }
// FormatLogs formats EVM returned structured logs for json output // FormatLogs formats EVM returned structured logs for json output
func FormatLogs(logs []vm.StructLog) []StructLogRes { func FormatLogs(logs []logger.StructLog) []StructLogRes {
formatted := make([]StructLogRes, len(logs)) formatted := make([]StructLogRes, len(logs))
for index, trace := range logs { for index, trace := range logs {
formatted[index] = StructLogRes{ formatted[index] = StructLogRes{
...@@ -1425,9 +1426,9 @@ func AccessList(ctx context.Context, b Backend, blockNrOrHash rpc.BlockNumberOrH ...@@ -1425,9 +1426,9 @@ func AccessList(ctx context.Context, b Backend, blockNrOrHash rpc.BlockNumberOrH
precompiles := vm.ActivePrecompiles(b.ChainConfig().Rules(header.Number)) precompiles := vm.ActivePrecompiles(b.ChainConfig().Rules(header.Number))
// Create an initial tracer // Create an initial tracer
prevTracer := vm.NewAccessListTracer(nil, args.from(), to, precompiles) prevTracer := logger.NewAccessListTracer(nil, args.from(), to, precompiles)
if args.AccessList != nil { if args.AccessList != nil {
prevTracer = vm.NewAccessListTracer(*args.AccessList, args.from(), to, precompiles) prevTracer = logger.NewAccessListTracer(*args.AccessList, args.from(), to, precompiles)
} }
for { for {
// Retrieve the current access list to expand // Retrieve the current access list to expand
...@@ -1453,7 +1454,7 @@ func AccessList(ctx context.Context, b Backend, blockNrOrHash rpc.BlockNumberOrH ...@@ -1453,7 +1454,7 @@ func AccessList(ctx context.Context, b Backend, blockNrOrHash rpc.BlockNumberOrH
} }
// Apply the transaction with the access list tracer // Apply the transaction with the access list tracer
tracer := vm.NewAccessListTracer(accessList, args.from(), to, precompiles) tracer := logger.NewAccessListTracer(accessList, args.from(), to, precompiles)
config := vm.Config{Tracer: tracer, Debug: true, NoBaseFee: true} config := vm.Config{Tracer: tracer, Debug: true, NoBaseFee: true}
vmenv, _, err := b.GetEVM(ctx, msg, statedb, header, &config) vmenv, _, err := b.GetEVM(ctx, msg, statedb, header, &config)
if err != nil { if err != nil {
......
...@@ -24,6 +24,7 @@ import ( ...@@ -24,6 +24,7 @@ import (
"testing" "testing"
"github.com/ethereum/go-ethereum/core/vm" "github.com/ethereum/go-ethereum/core/vm"
"github.com/ethereum/go-ethereum/eth/tracers/logger"
) )
func TestState(t *testing.T) { func TestState(t *testing.T) {
...@@ -115,7 +116,7 @@ func withTrace(t *testing.T, gasLimit uint64, test func(vm.Config) error) { ...@@ -115,7 +116,7 @@ func withTrace(t *testing.T, gasLimit uint64, test func(vm.Config) error) {
} }
buf := new(bytes.Buffer) buf := new(bytes.Buffer)
w := bufio.NewWriter(buf) w := bufio.NewWriter(buf)
tracer := vm.NewJSONLogger(&vm.LogConfig{}, w) tracer := logger.NewJSONLogger(&logger.Config{}, w)
config.Debug, config.Tracer = true, tracer config.Debug, config.Tracer = true, tracer
err2 := test(config) err2 := test(config)
if !reflect.DeepEqual(err, err2) { if !reflect.DeepEqual(err, err2) {
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment