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