github.com/truechain/go-ethereum@v1.8.11/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  	"time"
    25  
    26  	"github.com/ethereum/go-ethereum/common"
    27  	"github.com/ethereum/go-ethereum/common/hexutil"
    28  	"github.com/ethereum/go-ethereum/common/math"
    29  	"github.com/ethereum/go-ethereum/core/types"
    30  )
    31  
    32  type Storage map[common.Hash]common.Hash
    33  
    34  func (s Storage) Copy() Storage {
    35  	cpy := make(Storage)
    36  	for key, value := range s {
    37  		cpy[key] = value
    38  	}
    39  
    40  	return cpy
    41  }
    42  
    43  // LogConfig are the configuration options for structured logger the EVM
    44  type LogConfig struct {
    45  	DisableMemory  bool // disable memory capture
    46  	DisableStack   bool // disable stack capture
    47  	DisableStorage bool // disable storage capture
    48  	Debug          bool // print output during capture end
    49  	Limit          int  // maximum length of output, but zero means unlimited
    50  }
    51  
    52  //go:generate gencodec -type StructLog -field-override structLogMarshaling -out gen_structlog.go
    53  
    54  // StructLog is emitted to the EVM each cycle and lists information about the current internal state
    55  // prior to the execution of the statement.
    56  type StructLog struct {
    57  	Pc         uint64                      `json:"pc"`
    58  	Op         OpCode                      `json:"op"`
    59  	Gas        uint64                      `json:"gas"`
    60  	GasCost    uint64                      `json:"gasCost"`
    61  	Memory     []byte                      `json:"memory"`
    62  	MemorySize int                         `json:"memSize"`
    63  	Stack      []*big.Int                  `json:"stack"`
    64  	Storage    map[common.Hash]common.Hash `json:"-"`
    65  	Depth      int                         `json:"depth"`
    66  	Err        error                       `json:"-"`
    67  }
    68  
    69  // overrides for gencodec
    70  type structLogMarshaling struct {
    71  	Stack       []*math.HexOrDecimal256
    72  	Gas         math.HexOrDecimal64
    73  	GasCost     math.HexOrDecimal64
    74  	Memory      hexutil.Bytes
    75  	OpName      string `json:"opName"` // adds call to OpName() in MarshalJSON
    76  	ErrorString string `json:"error"`  // adds call to ErrorString() in MarshalJSON
    77  }
    78  
    79  func (s *StructLog) OpName() string {
    80  	return s.Op.String()
    81  }
    82  
    83  func (s *StructLog) ErrorString() string {
    84  	if s.Err != nil {
    85  		return s.Err.Error()
    86  	}
    87  	return ""
    88  }
    89  
    90  // Tracer is used to collect execution traces from an EVM transaction
    91  // execution. CaptureState is called for each step of the VM with the
    92  // current VM state.
    93  // Note that reference types are actual VM data structures; make copies
    94  // if you need to retain them beyond the current call.
    95  type Tracer interface {
    96  	CaptureStart(from common.Address, to common.Address, call bool, input []byte, gas uint64, value *big.Int) error
    97  	CaptureState(env *EVM, pc uint64, op OpCode, gas, cost uint64, memory *Memory, stack *Stack, contract *Contract, depth int, err error) error
    98  	CaptureFault(env *EVM, pc uint64, op OpCode, gas, cost uint64, memory *Memory, stack *Stack, contract *Contract, depth int, err error) error
    99  	CaptureEnd(output []byte, gasUsed uint64, t time.Duration, err error) error
   100  }
   101  
   102  // StructLogger is an EVM state logger and implements Tracer.
   103  //
   104  // StructLogger can capture state based on the given Log configuration and also keeps
   105  // a track record of modified storage which is used in reporting snapshots of the
   106  // contract their storage.
   107  type StructLogger struct {
   108  	cfg LogConfig
   109  
   110  	logs          []StructLog
   111  	changedValues map[common.Address]Storage
   112  	output        []byte
   113  	err           error
   114  }
   115  
   116  // NewStructLogger returns a new logger
   117  func NewStructLogger(cfg *LogConfig) *StructLogger {
   118  	logger := &StructLogger{
   119  		changedValues: make(map[common.Address]Storage),
   120  	}
   121  	if cfg != nil {
   122  		logger.cfg = *cfg
   123  	}
   124  	return logger
   125  }
   126  
   127  func (l *StructLogger) CaptureStart(from common.Address, to common.Address, create bool, input []byte, gas uint64, value *big.Int) error {
   128  	return nil
   129  }
   130  
   131  // CaptureState logs a new structured log message and pushes it out to the environment
   132  //
   133  // CaptureState also tracks SSTORE ops to track dirty values.
   134  func (l *StructLogger) CaptureState(env *EVM, pc uint64, op OpCode, gas, cost uint64, memory *Memory, stack *Stack, contract *Contract, depth int, err error) error {
   135  	// check if already accumulated the specified number of logs
   136  	if l.cfg.Limit != 0 && l.cfg.Limit <= len(l.logs) {
   137  		return ErrTraceLimitReached
   138  	}
   139  
   140  	// initialise new changed values storage container for this contract
   141  	// if not present.
   142  	if l.changedValues[contract.Address()] == nil {
   143  		l.changedValues[contract.Address()] = make(Storage)
   144  	}
   145  
   146  	// capture SSTORE opcodes and determine the changed value and store
   147  	// it in the local storage container.
   148  	if op == SSTORE && stack.len() >= 2 {
   149  		var (
   150  			value   = common.BigToHash(stack.data[stack.len()-2])
   151  			address = common.BigToHash(stack.data[stack.len()-1])
   152  		)
   153  		l.changedValues[contract.Address()][address] = value
   154  	}
   155  	// Copy a snapstot of the current memory state to a new buffer
   156  	var mem []byte
   157  	if !l.cfg.DisableMemory {
   158  		mem = make([]byte, len(memory.Data()))
   159  		copy(mem, memory.Data())
   160  	}
   161  	// Copy a snapshot of the current stack state to a new buffer
   162  	var stck []*big.Int
   163  	if !l.cfg.DisableStack {
   164  		stck = make([]*big.Int, len(stack.Data()))
   165  		for i, item := range stack.Data() {
   166  			stck[i] = new(big.Int).Set(item)
   167  		}
   168  	}
   169  	// Copy a snapshot of the current storage to a new container
   170  	var storage Storage
   171  	if !l.cfg.DisableStorage {
   172  		storage = l.changedValues[contract.Address()].Copy()
   173  	}
   174  	// create a new snaptshot of the EVM.
   175  	log := StructLog{pc, op, gas, cost, mem, memory.Len(), stck, storage, depth, err}
   176  
   177  	l.logs = append(l.logs, log)
   178  	return nil
   179  }
   180  
   181  func (l *StructLogger) CaptureFault(env *EVM, pc uint64, op OpCode, gas, cost uint64, memory *Memory, stack *Stack, contract *Contract, depth int, err error) error {
   182  	return nil
   183  }
   184  
   185  func (l *StructLogger) CaptureEnd(output []byte, gasUsed uint64, t time.Duration, err error) error {
   186  	l.output = output
   187  	l.err = err
   188  	if l.cfg.Debug {
   189  		fmt.Printf("0x%x\n", output)
   190  		if err != nil {
   191  			fmt.Printf(" error: %v\n", err)
   192  		}
   193  	}
   194  	return nil
   195  }
   196  
   197  // StructLogs returns the captured log entries.
   198  func (l *StructLogger) StructLogs() []StructLog { return l.logs }
   199  
   200  // Error returns the VM error captured by the trace.
   201  func (l *StructLogger) Error() error { return l.err }
   202  
   203  // Output returns the VM return value captured by the trace.
   204  func (l *StructLogger) Output() []byte { return l.output }
   205  
   206  // WriteTrace writes a formatted trace to the given writer
   207  func WriteTrace(writer io.Writer, logs []StructLog) {
   208  	for _, log := range logs {
   209  		fmt.Fprintf(writer, "%-16spc=%08d gas=%v cost=%v", log.Op, log.Pc, log.Gas, log.GasCost)
   210  		if log.Err != nil {
   211  			fmt.Fprintf(writer, " ERROR: %v", log.Err)
   212  		}
   213  		fmt.Fprintln(writer)
   214  
   215  		if len(log.Stack) > 0 {
   216  			fmt.Fprintln(writer, "Stack:")
   217  			for i := len(log.Stack) - 1; i >= 0; i-- {
   218  				fmt.Fprintf(writer, "%08d  %x\n", len(log.Stack)-i-1, math.PaddedBigBytes(log.Stack[i], 32))
   219  			}
   220  		}
   221  		if len(log.Memory) > 0 {
   222  			fmt.Fprintln(writer, "Memory:")
   223  			fmt.Fprint(writer, hex.Dump(log.Memory))
   224  		}
   225  		if len(log.Storage) > 0 {
   226  			fmt.Fprintln(writer, "Storage:")
   227  			for h, item := range log.Storage {
   228  				fmt.Fprintf(writer, "%x: %x\n", h, item)
   229  			}
   230  		}
   231  		fmt.Fprintln(writer)
   232  	}
   233  }
   234  
   235  // WriteLogs writes vm logs in a readable format to the given writer
   236  func WriteLogs(writer io.Writer, logs []*types.Log) {
   237  	for _, log := range logs {
   238  		fmt.Fprintf(writer, "LOG%d: %x bn=%d txi=%x\n", len(log.Topics), log.Address, log.BlockNumber, log.TxIndex)
   239  
   240  		for i, topic := range log.Topics {
   241  			fmt.Fprintf(writer, "%08d  %x\n", i, topic)
   242  		}
   243  
   244  		fmt.Fprint(writer, hex.Dump(log.Data))
   245  		fmt.Fprintln(writer)
   246  	}
   247  }