github.com/ethereum-optimism/optimism/l2geth@v0.0.0-20230612200230-50b04ade19e3/core/vm/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 vm
    18  
    19  import (
    20  	"encoding/hex"
    21  	"fmt"
    22  	"io"
    23  	"math/big"
    24  	"strings"
    25  	"time"
    26  
    27  	"github.com/ethereum-optimism/optimism/l2geth/common"
    28  	"github.com/ethereum-optimism/optimism/l2geth/common/hexutil"
    29  	"github.com/ethereum-optimism/optimism/l2geth/common/math"
    30  	"github.com/ethereum-optimism/optimism/l2geth/core/types"
    31  	"github.com/ethereum-optimism/optimism/l2geth/params"
    32  )
    33  
    34  // Storage represents a contract's storage.
    35  type Storage map[common.Hash]common.Hash
    36  
    37  // Copy duplicates the current storage.
    38  func (s Storage) Copy() Storage {
    39  	cpy := make(Storage)
    40  	for key, value := range s {
    41  		cpy[key] = value
    42  	}
    43  
    44  	return cpy
    45  }
    46  
    47  // LogConfig are the configuration options for structured logger the EVM
    48  type LogConfig struct {
    49  	DisableMemory  bool // disable memory capture
    50  	DisableStack   bool // disable stack capture
    51  	DisableStorage bool // disable storage capture
    52  	Debug          bool // print output during capture end
    53  	Limit          int  // maximum length of output, but zero means unlimited
    54  	// Chain overrides, can be used to execute a trace using future fork rules
    55  	Overrides *params.ChainConfig `json:"overrides,omitempty"`
    56  }
    57  
    58  //go:generate gencodec -type StructLog -field-override structLogMarshaling -out gen_structlog.go
    59  
    60  // StructLog is emitted to the EVM each cycle and lists information about the current internal state
    61  // prior to the execution of the statement.
    62  type StructLog struct {
    63  	Pc            uint64                      `json:"pc"`
    64  	Op            OpCode                      `json:"op"`
    65  	Gas           uint64                      `json:"gas"`
    66  	GasCost       uint64                      `json:"gasCost"`
    67  	Memory        []byte                      `json:"memory"`
    68  	MemorySize    int                         `json:"memSize"`
    69  	Stack         []*big.Int                  `json:"stack"`
    70  	Storage       map[common.Hash]common.Hash `json:"-"`
    71  	Depth         int                         `json:"depth"`
    72  	RefundCounter uint64                      `json:"refund"`
    73  	Err           error                       `json:"-"`
    74  }
    75  
    76  // overrides for gencodec
    77  type structLogMarshaling struct {
    78  	Stack       []*math.HexOrDecimal256
    79  	Gas         math.HexOrDecimal64
    80  	GasCost     math.HexOrDecimal64
    81  	Memory      hexutil.Bytes
    82  	OpName      string `json:"opName"` // adds call to OpName() in MarshalJSON
    83  	ErrorString string `json:"error"`  // adds call to ErrorString() in MarshalJSON
    84  }
    85  
    86  // OpName formats the operand name in a human-readable format.
    87  func (s *StructLog) OpName() string {
    88  	return s.Op.String()
    89  }
    90  
    91  // ErrorString formats the log's error as a string.
    92  func (s *StructLog) ErrorString() string {
    93  	if s.Err != nil {
    94  		return s.Err.Error()
    95  	}
    96  	return ""
    97  }
    98  
    99  // Tracer is used to collect execution traces from an EVM transaction
   100  // execution. CaptureState is called for each step of the VM with the
   101  // current VM state.
   102  // Note that reference types are actual VM data structures; make copies
   103  // if you need to retain them beyond the current call.
   104  type Tracer interface {
   105  	CaptureStart(from common.Address, to common.Address, create bool, input []byte, gas uint64, value *big.Int) error
   106  	CaptureState(env *EVM, pc uint64, op OpCode, gas, cost uint64, memory *Memory, stack *Stack, contract *Contract, depth int, err error) error
   107  	CaptureFault(env *EVM, pc uint64, op OpCode, gas, cost uint64, memory *Memory, stack *Stack, contract *Contract, depth int, err error) error
   108  	CaptureEnd(output []byte, gasUsed uint64, t time.Duration, err error) error
   109  }
   110  
   111  // StructLogger is an EVM state logger and implements Tracer.
   112  //
   113  // StructLogger can capture state based on the given Log configuration and also keeps
   114  // a track record of modified storage which is used in reporting snapshots of the
   115  // contract their storage.
   116  type StructLogger struct {
   117  	cfg LogConfig
   118  
   119  	logs          []StructLog
   120  	changedValues map[common.Address]Storage
   121  	output        []byte
   122  	err           error
   123  }
   124  
   125  // NewStructLogger returns a new logger
   126  func NewStructLogger(cfg *LogConfig) *StructLogger {
   127  	logger := &StructLogger{
   128  		changedValues: make(map[common.Address]Storage),
   129  	}
   130  	if cfg != nil {
   131  		logger.cfg = *cfg
   132  	}
   133  	return logger
   134  }
   135  
   136  // CaptureStart implements the Tracer interface to initialize the tracing operation.
   137  func (l *StructLogger) CaptureStart(from common.Address, to common.Address, create bool, input []byte, gas uint64, value *big.Int) error {
   138  	return nil
   139  }
   140  
   141  // CaptureState logs a new structured log message and pushes it out to the environment
   142  //
   143  // CaptureState also tracks SSTORE ops to track dirty values.
   144  func (l *StructLogger) CaptureState(env *EVM, pc uint64, op OpCode, gas, cost uint64, memory *Memory, stack *Stack, contract *Contract, depth int, err error) error {
   145  	// check if already accumulated the specified number of logs
   146  	if l.cfg.Limit != 0 && l.cfg.Limit <= len(l.logs) {
   147  		return ErrTraceLimitReached
   148  	}
   149  
   150  	// initialise new changed values storage container for this contract
   151  	// if not present.
   152  	if l.changedValues[contract.Address()] == nil {
   153  		l.changedValues[contract.Address()] = make(Storage)
   154  	}
   155  
   156  	// capture SSTORE opcodes and determine the changed value and store
   157  	// it in the local storage container.
   158  	if op == SSTORE && stack.len() >= 2 {
   159  		var (
   160  			value   = common.BigToHash(stack.data[stack.len()-2])
   161  			address = common.BigToHash(stack.data[stack.len()-1])
   162  		)
   163  		l.changedValues[contract.Address()][address] = value
   164  	}
   165  	// Copy a snapshot of the current memory state to a new buffer
   166  	var mem []byte
   167  	if !l.cfg.DisableMemory {
   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 []*big.Int
   173  	if !l.cfg.DisableStack {
   174  		stck = make([]*big.Int, len(stack.Data()))
   175  		for i, item := range stack.Data() {
   176  			stck[i] = new(big.Int).Set(item)
   177  		}
   178  	}
   179  	// Copy a snapshot of the current storage to a new container
   180  	var storage Storage
   181  	if !l.cfg.DisableStorage {
   182  		storage = l.changedValues[contract.Address()].Copy()
   183  	}
   184  	// create a new snapshot of the EVM.
   185  	log := StructLog{pc, op, gas, cost, mem, memory.Len(), stck, storage, depth, env.StateDB.GetRefund(), err}
   186  
   187  	l.logs = append(l.logs, log)
   188  	return nil
   189  }
   190  
   191  // CaptureFault implements the Tracer interface to trace an execution fault
   192  // while running an opcode.
   193  func (l *StructLogger) CaptureFault(env *EVM, pc uint64, op OpCode, gas, cost uint64, memory *Memory, stack *Stack, contract *Contract, depth int, err error) error {
   194  	return nil
   195  }
   196  
   197  // CaptureEnd is called after the call finishes to finalize the tracing.
   198  func (l *StructLogger) CaptureEnd(output []byte, gasUsed uint64, t time.Duration, err error) error {
   199  	l.output = output
   200  	l.err = err
   201  	if l.cfg.Debug {
   202  		fmt.Printf("0x%x\n", output)
   203  		if err != nil {
   204  			fmt.Printf(" error: %v\n", err)
   205  		}
   206  	}
   207  	return nil
   208  }
   209  
   210  // StructLogs returns the captured log entries.
   211  func (l *StructLogger) StructLogs() []StructLog { return l.logs }
   212  
   213  // Error returns the VM error captured by the trace.
   214  func (l *StructLogger) Error() error { return l.err }
   215  
   216  // Output returns the VM return value captured by the trace.
   217  func (l *StructLogger) Output() []byte { return l.output }
   218  
   219  // WriteTrace writes a formatted trace to the given writer
   220  func WriteTrace(writer io.Writer, logs []StructLog) {
   221  	for _, log := range logs {
   222  		fmt.Fprintf(writer, "%-16spc=%08d gas=%v cost=%v", log.Op, log.Pc, log.Gas, log.GasCost)
   223  		if log.Err != nil {
   224  			fmt.Fprintf(writer, " ERROR: %v", log.Err)
   225  		}
   226  		fmt.Fprintln(writer)
   227  
   228  		if len(log.Stack) > 0 {
   229  			fmt.Fprintln(writer, "Stack:")
   230  			for i := len(log.Stack) - 1; i >= 0; i-- {
   231  				fmt.Fprintf(writer, "%08d  %x\n", len(log.Stack)-i-1, math.PaddedBigBytes(log.Stack[i], 32))
   232  			}
   233  		}
   234  		if len(log.Memory) > 0 {
   235  			fmt.Fprintln(writer, "Memory:")
   236  			fmt.Fprint(writer, hex.Dump(log.Memory))
   237  		}
   238  		if len(log.Storage) > 0 {
   239  			fmt.Fprintln(writer, "Storage:")
   240  			for h, item := range log.Storage {
   241  				fmt.Fprintf(writer, "%x: %x\n", h, item)
   242  			}
   243  		}
   244  		fmt.Fprintln(writer)
   245  	}
   246  }
   247  
   248  // WriteLogs writes vm logs in a readable format to the given writer
   249  func WriteLogs(writer io.Writer, logs []*types.Log) {
   250  	for _, log := range logs {
   251  		fmt.Fprintf(writer, "LOG%d: %x bn=%d txi=%x\n", len(log.Topics), log.Address, log.BlockNumber, log.TxIndex)
   252  
   253  		for i, topic := range log.Topics {
   254  			fmt.Fprintf(writer, "%08d  %x\n", i, topic)
   255  		}
   256  
   257  		fmt.Fprint(writer, hex.Dump(log.Data))
   258  		fmt.Fprintln(writer)
   259  	}
   260  }
   261  
   262  type mdLogger struct {
   263  	out io.Writer
   264  	cfg *LogConfig
   265  }
   266  
   267  // NewMarkdownLogger creates a logger which outputs information in a format adapted
   268  // for human readability, and is also a valid markdown table
   269  func NewMarkdownLogger(cfg *LogConfig, writer io.Writer) *mdLogger {
   270  	l := &mdLogger{writer, cfg}
   271  	if l.cfg == nil {
   272  		l.cfg = &LogConfig{}
   273  	}
   274  	return l
   275  }
   276  
   277  func (t *mdLogger) CaptureStart(from common.Address, to common.Address, create bool, input []byte, gas uint64, value *big.Int) error {
   278  	if !create {
   279  		fmt.Fprintf(t.out, "From: `%v`\nTo: `%v`\nData: `0x%x`\nGas: `%d`\nValue `%v` wei\n",
   280  			from.String(), to.String(),
   281  			input, gas, value)
   282  	} else {
   283  		fmt.Fprintf(t.out, "From: `%v`\nCreate at: `%v`\nData: `0x%x`\nGas: `%d`\nValue `%v` wei\n",
   284  			from.String(), to.String(),
   285  			input, gas, value)
   286  	}
   287  
   288  	fmt.Fprintf(t.out, `
   289  |  Pc   |      Op     | Cost |   Stack   |   RStack  |  Refund |
   290  |-------|-------------|------|-----------|-----------|---------|
   291  `)
   292  	return nil
   293  }
   294  
   295  func (t *mdLogger) CaptureState(env *EVM, pc uint64, op OpCode, gas, cost uint64, memory *Memory, stack *Stack, contract *Contract, depth int, err error) error {
   296  	fmt.Fprintf(t.out, "| %4d  | %10v  |  %3d |", pc, op, cost)
   297  
   298  	if !t.cfg.DisableStack {
   299  		// format stack
   300  		var a []string
   301  		for _, elem := range stack.data {
   302  			a = append(a, fmt.Sprintf("%v", elem.String()))
   303  		}
   304  		b := fmt.Sprintf("[%v]", strings.Join(a, ","))
   305  		fmt.Fprintf(t.out, "%10v |", b)
   306  
   307  		// format return stack
   308  		a = a[:0]
   309  		b = fmt.Sprintf("[%v]", strings.Join(a, ","))
   310  		fmt.Fprintf(t.out, "%10v |", b)
   311  	}
   312  	fmt.Fprintf(t.out, "%10v |", env.StateDB.GetRefund())
   313  	fmt.Fprintln(t.out, "")
   314  	if err != nil {
   315  		fmt.Fprintf(t.out, "Error: %v\n", err)
   316  	}
   317  	return nil
   318  }
   319  
   320  func (t *mdLogger) CaptureFault(env *EVM, pc uint64, op OpCode, gas, cost uint64, memory *Memory, stack *Stack, contract *Contract, depth int, err error) error {
   321  
   322  	fmt.Fprintf(t.out, "\nError: at pc=%d, op=%v: %v\n", pc, op, err)
   323  
   324  	return nil
   325  }
   326  
   327  func (t *mdLogger) CaptureEnd(output []byte, gasUsed uint64, tm time.Duration, err error) error {
   328  	fmt.Fprintf(t.out, "\nOutput: `0x%x`\nConsumed gas: `%d`\nError: `%v`\n",
   329  		output, gasUsed, err)
   330  	return nil
   331  }