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