github.com/codysnider/go-ethereum@v1.10.18-0.20220420071915-14f4ae99222a/eth/tracers/logger/logger.go (about)

     1  // Copyright 2015 The go-ethereum Authors
     2  // This file is part of the go-ethereum library.
     3  //
     4  // The go-ethereum library is free software: you can redistribute it and/or modify
     5  // it under the terms of the GNU Lesser General Public License as published by
     6  // the Free Software Foundation, either version 3 of the License, or
     7  // (at your option) any later version.
     8  //
     9  // The go-ethereum library is distributed in the hope that it will be useful,
    10  // but WITHOUT ANY WARRANTY; without even the implied warranty of
    11  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    12  // GNU Lesser General Public License for more details.
    13  //
    14  // You should have received a copy of the GNU Lesser General Public License
    15  // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
    16  
    17  package logger
    18  
    19  import (
    20  	"encoding/hex"
    21  	"encoding/json"
    22  	"fmt"
    23  	"io"
    24  	"math/big"
    25  	"strings"
    26  	"sync/atomic"
    27  	"time"
    28  
    29  	"github.com/ethereum/go-ethereum/common"
    30  	"github.com/ethereum/go-ethereum/common/hexutil"
    31  	"github.com/ethereum/go-ethereum/common/math"
    32  	"github.com/ethereum/go-ethereum/core/types"
    33  	"github.com/ethereum/go-ethereum/core/vm"
    34  	"github.com/ethereum/go-ethereum/params"
    35  	"github.com/holiman/uint256"
    36  )
    37  
    38  // Storage represents a contract's storage.
    39  type Storage map[common.Hash]common.Hash
    40  
    41  // Copy duplicates the current storage.
    42  func (s Storage) Copy() Storage {
    43  	cpy := make(Storage)
    44  	for key, value := range s {
    45  		cpy[key] = value
    46  	}
    47  	return cpy
    48  }
    49  
    50  // Config are the configuration options for structured logger the EVM
    51  type Config struct {
    52  	EnableMemory     bool // enable memory capture
    53  	DisableStack     bool // disable stack capture
    54  	DisableStorage   bool // disable storage capture
    55  	EnableReturnData bool // enable return data capture
    56  	Debug            bool // print output during capture end
    57  	Limit            int  // maximum length of output, but zero means unlimited
    58  	// Chain overrides, can be used to execute a trace using future fork rules
    59  	Overrides *params.ChainConfig `json:"overrides,omitempty"`
    60  }
    61  
    62  //go:generate go run github.com/fjl/gencodec -type StructLog -field-override structLogMarshaling -out gen_structlog.go
    63  
    64  // StructLog is emitted to the EVM each cycle and lists information about the current internal state
    65  // prior to the execution of the statement.
    66  type StructLog struct {
    67  	Pc            uint64                      `json:"pc"`
    68  	Op            vm.OpCode                   `json:"op"`
    69  	Gas           uint64                      `json:"gas"`
    70  	GasCost       uint64                      `json:"gasCost"`
    71  	Memory        []byte                      `json:"memory,omitempty"`
    72  	MemorySize    int                         `json:"memSize"`
    73  	Stack         []uint256.Int               `json:"stack"`
    74  	ReturnData    []byte                      `json:"returnData,omitempty"`
    75  	Storage       map[common.Hash]common.Hash `json:"-"`
    76  	Depth         int                         `json:"depth"`
    77  	RefundCounter uint64                      `json:"refund"`
    78  	Err           error                       `json:"-"`
    79  }
    80  
    81  // overrides for gencodec
    82  type structLogMarshaling struct {
    83  	Gas         math.HexOrDecimal64
    84  	GasCost     math.HexOrDecimal64
    85  	Memory      hexutil.Bytes
    86  	ReturnData  hexutil.Bytes
    87  	OpName      string `json:"opName"`          // adds call to OpName() in MarshalJSON
    88  	ErrorString string `json:"error,omitempty"` // adds call to ErrorString() in MarshalJSON
    89  }
    90  
    91  // OpName formats the operand name in a human-readable format.
    92  func (s *StructLog) OpName() string {
    93  	return s.Op.String()
    94  }
    95  
    96  // ErrorString formats the log's error as a string.
    97  func (s *StructLog) ErrorString() string {
    98  	if s.Err != nil {
    99  		return s.Err.Error()
   100  	}
   101  	return ""
   102  }
   103  
   104  // StructLogger is an EVM state logger and implements EVMLogger.
   105  //
   106  // StructLogger can capture state based on the given Log configuration and also keeps
   107  // a track record of modified storage which is used in reporting snapshots of the
   108  // contract their storage.
   109  type StructLogger struct {
   110  	cfg Config
   111  	env *vm.EVM
   112  
   113  	storage  map[common.Address]Storage
   114  	logs     []StructLog
   115  	output   []byte
   116  	err      error
   117  	gasLimit uint64
   118  	usedGas  uint64
   119  
   120  	interrupt uint32 // Atomic flag to signal execution interruption
   121  	reason    error  // Textual reason for the interruption
   122  }
   123  
   124  // NewStructLogger returns a new logger
   125  func NewStructLogger(cfg *Config) *StructLogger {
   126  	logger := &StructLogger{
   127  		storage: make(map[common.Address]Storage),
   128  	}
   129  	if cfg != nil {
   130  		logger.cfg = *cfg
   131  	}
   132  	return logger
   133  }
   134  
   135  // Reset clears the data held by the logger.
   136  func (l *StructLogger) Reset() {
   137  	l.storage = make(map[common.Address]Storage)
   138  	l.output = make([]byte, 0)
   139  	l.logs = l.logs[:0]
   140  	l.err = nil
   141  }
   142  
   143  // CaptureStart implements the EVMLogger interface to initialize the tracing operation.
   144  func (l *StructLogger) CaptureStart(env *vm.EVM, from common.Address, to common.Address, create bool, input []byte, gas uint64, value *big.Int) {
   145  	l.env = env
   146  }
   147  
   148  // CaptureState logs a new structured log message and pushes it out to the environment
   149  //
   150  // CaptureState also tracks SLOAD/SSTORE ops to track storage change.
   151  func (l *StructLogger) CaptureState(pc uint64, op vm.OpCode, gas, cost uint64, scope *vm.ScopeContext, rData []byte, depth int, err error) {
   152  	// If tracing was interrupted, set the error and stop
   153  	if atomic.LoadUint32(&l.interrupt) > 0 {
   154  		l.env.Cancel()
   155  		return
   156  	}
   157  	// check if already accumulated the specified number of logs
   158  	if l.cfg.Limit != 0 && l.cfg.Limit <= len(l.logs) {
   159  		return
   160  	}
   161  
   162  	memory := scope.Memory
   163  	stack := scope.Stack
   164  	contract := scope.Contract
   165  	// Copy a snapshot of the current memory state to a new buffer
   166  	var mem []byte
   167  	if l.cfg.EnableMemory {
   168  		mem = make([]byte, len(memory.Data()))
   169  		copy(mem, memory.Data())
   170  	}
   171  	// Copy a snapshot of the current stack state to a new buffer
   172  	var stck []uint256.Int
   173  	if !l.cfg.DisableStack {
   174  		stck = make([]uint256.Int, len(stack.Data()))
   175  		for i, item := range stack.Data() {
   176  			stck[i] = item
   177  		}
   178  	}
   179  	stackData := stack.Data()
   180  	stackLen := len(stackData)
   181  	// Copy a snapshot of the current storage to a new container
   182  	var storage Storage
   183  	if !l.cfg.DisableStorage && (op == vm.SLOAD || op == vm.SSTORE) {
   184  		// initialise new changed values storage container for this contract
   185  		// if not present.
   186  		if l.storage[contract.Address()] == nil {
   187  			l.storage[contract.Address()] = make(Storage)
   188  		}
   189  		// capture SLOAD opcodes and record the read entry in the local storage
   190  		if op == vm.SLOAD && stackLen >= 1 {
   191  			var (
   192  				address = common.Hash(stackData[stackLen-1].Bytes32())
   193  				value   = l.env.StateDB.GetState(contract.Address(), address)
   194  			)
   195  			l.storage[contract.Address()][address] = value
   196  			storage = l.storage[contract.Address()].Copy()
   197  		} else if op == vm.SSTORE && stackLen >= 2 {
   198  			// capture SSTORE opcodes and record the written entry in the local storage.
   199  			var (
   200  				value   = common.Hash(stackData[stackLen-2].Bytes32())
   201  				address = common.Hash(stackData[stackLen-1].Bytes32())
   202  			)
   203  			l.storage[contract.Address()][address] = value
   204  			storage = l.storage[contract.Address()].Copy()
   205  		}
   206  	}
   207  	var rdata []byte
   208  	if l.cfg.EnableReturnData {
   209  		rdata = make([]byte, len(rData))
   210  		copy(rdata, rData)
   211  	}
   212  	// create a new snapshot of the EVM.
   213  	log := StructLog{pc, op, gas, cost, mem, memory.Len(), stck, rdata, storage, depth, l.env.StateDB.GetRefund(), err}
   214  	l.logs = append(l.logs, log)
   215  }
   216  
   217  // CaptureFault implements the EVMLogger interface to trace an execution fault
   218  // while running an opcode.
   219  func (l *StructLogger) CaptureFault(pc uint64, op vm.OpCode, gas, cost uint64, scope *vm.ScopeContext, depth int, err error) {
   220  }
   221  
   222  // CaptureEnd is called after the call finishes to finalize the tracing.
   223  func (l *StructLogger) CaptureEnd(output []byte, gasUsed uint64, t time.Duration, err error) {
   224  	l.output = output
   225  	l.err = err
   226  	if l.cfg.Debug {
   227  		fmt.Printf("0x%x\n", output)
   228  		if err != nil {
   229  			fmt.Printf(" error: %v\n", err)
   230  		}
   231  	}
   232  }
   233  
   234  func (l *StructLogger) CaptureEnter(typ vm.OpCode, from common.Address, to common.Address, input []byte, gas uint64, value *big.Int) {
   235  }
   236  
   237  func (l *StructLogger) CaptureExit(output []byte, gasUsed uint64, err error) {
   238  }
   239  
   240  func (l *StructLogger) GetResult() (json.RawMessage, error) {
   241  	// Tracing aborted
   242  	if l.reason != nil {
   243  		return nil, l.reason
   244  	}
   245  	failed := l.err != nil
   246  	returnData := common.CopyBytes(l.output)
   247  	// Return data when successful and revert reason when reverted, otherwise empty.
   248  	returnVal := fmt.Sprintf("%x", returnData)
   249  	if failed && l.err != vm.ErrExecutionReverted {
   250  		returnVal = ""
   251  	}
   252  	return json.Marshal(&ExecutionResult{
   253  		Gas:         l.usedGas,
   254  		Failed:      failed,
   255  		ReturnValue: returnVal,
   256  		StructLogs:  formatLogs(l.StructLogs()),
   257  	})
   258  }
   259  
   260  // Stop terminates execution of the tracer at the first opportune moment.
   261  func (l *StructLogger) Stop(err error) {
   262  	l.reason = err
   263  	atomic.StoreUint32(&l.interrupt, 1)
   264  }
   265  
   266  func (l *StructLogger) CaptureTxStart(gasLimit uint64) {
   267  	l.gasLimit = gasLimit
   268  }
   269  
   270  func (l *StructLogger) CaptureTxEnd(restGas uint64) {
   271  	l.usedGas = l.gasLimit - restGas
   272  }
   273  
   274  // StructLogs returns the captured log entries.
   275  func (l *StructLogger) StructLogs() []StructLog { return l.logs }
   276  
   277  // Error returns the VM error captured by the trace.
   278  func (l *StructLogger) Error() error { return l.err }
   279  
   280  // Output returns the VM return value captured by the trace.
   281  func (l *StructLogger) Output() []byte { return l.output }
   282  
   283  // WriteTrace writes a formatted trace to the given writer
   284  func WriteTrace(writer io.Writer, logs []StructLog) {
   285  	for _, log := range logs {
   286  		fmt.Fprintf(writer, "%-16spc=%08d gas=%v cost=%v", log.Op, log.Pc, log.Gas, log.GasCost)
   287  		if log.Err != nil {
   288  			fmt.Fprintf(writer, " ERROR: %v", log.Err)
   289  		}
   290  		fmt.Fprintln(writer)
   291  
   292  		if len(log.Stack) > 0 {
   293  			fmt.Fprintln(writer, "Stack:")
   294  			for i := len(log.Stack) - 1; i >= 0; i-- {
   295  				fmt.Fprintf(writer, "%08d  %s\n", len(log.Stack)-i-1, log.Stack[i].Hex())
   296  			}
   297  		}
   298  		if len(log.Memory) > 0 {
   299  			fmt.Fprintln(writer, "Memory:")
   300  			fmt.Fprint(writer, hex.Dump(log.Memory))
   301  		}
   302  		if len(log.Storage) > 0 {
   303  			fmt.Fprintln(writer, "Storage:")
   304  			for h, item := range log.Storage {
   305  				fmt.Fprintf(writer, "%x: %x\n", h, item)
   306  			}
   307  		}
   308  		if len(log.ReturnData) > 0 {
   309  			fmt.Fprintln(writer, "ReturnData:")
   310  			fmt.Fprint(writer, hex.Dump(log.ReturnData))
   311  		}
   312  		fmt.Fprintln(writer)
   313  	}
   314  }
   315  
   316  // WriteLogs writes vm logs in a readable format to the given writer
   317  func WriteLogs(writer io.Writer, logs []*types.Log) {
   318  	for _, log := range logs {
   319  		fmt.Fprintf(writer, "LOG%d: %x bn=%d txi=%x\n", len(log.Topics), log.Address, log.BlockNumber, log.TxIndex)
   320  
   321  		for i, topic := range log.Topics {
   322  			fmt.Fprintf(writer, "%08d  %x\n", i, topic)
   323  		}
   324  
   325  		fmt.Fprint(writer, hex.Dump(log.Data))
   326  		fmt.Fprintln(writer)
   327  	}
   328  }
   329  
   330  type mdLogger struct {
   331  	out io.Writer
   332  	cfg *Config
   333  	env *vm.EVM
   334  }
   335  
   336  // NewMarkdownLogger creates a logger which outputs information in a format adapted
   337  // for human readability, and is also a valid markdown table
   338  func NewMarkdownLogger(cfg *Config, writer io.Writer) *mdLogger {
   339  	l := &mdLogger{out: writer, cfg: cfg}
   340  	if l.cfg == nil {
   341  		l.cfg = &Config{}
   342  	}
   343  	return l
   344  }
   345  
   346  func (t *mdLogger) CaptureStart(env *vm.EVM, from common.Address, to common.Address, create bool, input []byte, gas uint64, value *big.Int) {
   347  	t.env = env
   348  	if !create {
   349  		fmt.Fprintf(t.out, "From: `%v`\nTo: `%v`\nData: `0x%x`\nGas: `%d`\nValue `%v` wei\n",
   350  			from.String(), to.String(),
   351  			input, gas, value)
   352  	} else {
   353  		fmt.Fprintf(t.out, "From: `%v`\nCreate at: `%v`\nData: `0x%x`\nGas: `%d`\nValue `%v` wei\n",
   354  			from.String(), to.String(),
   355  			input, gas, value)
   356  	}
   357  
   358  	fmt.Fprintf(t.out, `
   359  |  Pc   |      Op     | Cost |   Stack   |   RStack  |  Refund |
   360  |-------|-------------|------|-----------|-----------|---------|
   361  `)
   362  }
   363  
   364  // CaptureState also tracks SLOAD/SSTORE ops to track storage change.
   365  func (t *mdLogger) CaptureState(pc uint64, op vm.OpCode, gas, cost uint64, scope *vm.ScopeContext, rData []byte, depth int, err error) {
   366  	stack := scope.Stack
   367  	fmt.Fprintf(t.out, "| %4d  | %10v  |  %3d |", pc, op, cost)
   368  
   369  	if !t.cfg.DisableStack {
   370  		// format stack
   371  		var a []string
   372  		for _, elem := range stack.Data() {
   373  			a = append(a, elem.Hex())
   374  		}
   375  		b := fmt.Sprintf("[%v]", strings.Join(a, ","))
   376  		fmt.Fprintf(t.out, "%10v |", b)
   377  	}
   378  	fmt.Fprintf(t.out, "%10v |", t.env.StateDB.GetRefund())
   379  	fmt.Fprintln(t.out, "")
   380  	if err != nil {
   381  		fmt.Fprintf(t.out, "Error: %v\n", err)
   382  	}
   383  }
   384  
   385  func (t *mdLogger) CaptureFault(pc uint64, op vm.OpCode, gas, cost uint64, scope *vm.ScopeContext, depth int, err error) {
   386  	fmt.Fprintf(t.out, "\nError: at pc=%d, op=%v: %v\n", pc, op, err)
   387  }
   388  
   389  func (t *mdLogger) CaptureEnd(output []byte, gasUsed uint64, tm time.Duration, err error) {
   390  	fmt.Fprintf(t.out, "\nOutput: `0x%x`\nConsumed gas: `%d`\nError: `%v`\n",
   391  		output, gasUsed, err)
   392  }
   393  
   394  func (t *mdLogger) CaptureEnter(typ vm.OpCode, from common.Address, to common.Address, input []byte, gas uint64, value *big.Int) {
   395  }
   396  
   397  func (t *mdLogger) CaptureExit(output []byte, gasUsed uint64, err error) {}
   398  
   399  func (*mdLogger) CaptureTxStart(gasLimit uint64) {}
   400  
   401  func (*mdLogger) CaptureTxEnd(restGas uint64) {}
   402  
   403  // ExecutionResult groups all structured logs emitted by the EVM
   404  // while replaying a transaction in debug mode as well as transaction
   405  // execution status, the amount of gas used and the return value
   406  type ExecutionResult struct {
   407  	Gas         uint64         `json:"gas"`
   408  	Failed      bool           `json:"failed"`
   409  	ReturnValue string         `json:"returnValue"`
   410  	StructLogs  []StructLogRes `json:"structLogs"`
   411  }
   412  
   413  // StructLogRes stores a structured log emitted by the EVM while replaying a
   414  // transaction in debug mode
   415  type StructLogRes struct {
   416  	Pc            uint64             `json:"pc"`
   417  	Op            string             `json:"op"`
   418  	Gas           uint64             `json:"gas"`
   419  	GasCost       uint64             `json:"gasCost"`
   420  	Depth         int                `json:"depth"`
   421  	Error         string             `json:"error,omitempty"`
   422  	Stack         *[]string          `json:"stack,omitempty"`
   423  	Memory        *[]string          `json:"memory,omitempty"`
   424  	Storage       *map[string]string `json:"storage,omitempty"`
   425  	RefundCounter uint64             `json:"refund,omitempty"`
   426  }
   427  
   428  // formatLogs formats EVM returned structured logs for json output
   429  func formatLogs(logs []StructLog) []StructLogRes {
   430  	formatted := make([]StructLogRes, len(logs))
   431  	for index, trace := range logs {
   432  		formatted[index] = StructLogRes{
   433  			Pc:            trace.Pc,
   434  			Op:            trace.Op.String(),
   435  			Gas:           trace.Gas,
   436  			GasCost:       trace.GasCost,
   437  			Depth:         trace.Depth,
   438  			Error:         trace.ErrorString(),
   439  			RefundCounter: trace.RefundCounter,
   440  		}
   441  		if trace.Stack != nil {
   442  			stack := make([]string, len(trace.Stack))
   443  			for i, stackValue := range trace.Stack {
   444  				stack[i] = stackValue.Hex()
   445  			}
   446  			formatted[index].Stack = &stack
   447  		}
   448  		if trace.Memory != nil {
   449  			memory := make([]string, 0, (len(trace.Memory)+31)/32)
   450  			for i := 0; i+32 <= len(trace.Memory); i += 32 {
   451  				memory = append(memory, fmt.Sprintf("%x", trace.Memory[i:i+32]))
   452  			}
   453  			formatted[index].Memory = &memory
   454  		}
   455  		if trace.Storage != nil {
   456  			storage := make(map[string]string)
   457  			for i, storageValue := range trace.Storage {
   458  				storage[fmt.Sprintf("%x", i)] = fmt.Sprintf("%x", storageValue)
   459  			}
   460  			formatted[index].Storage = &storage
   461  		}
   462  	}
   463  	return formatted
   464  }