github.com/reapchain/go-reapchain@v0.2.15-0.20210609012950-9735c110c705/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 (self Storage) Copy() Storage {
    35  	cpy := make(Storage)
    36  	for key, value := range self {
    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  	FullStorage    bool // show full storage (slow)
    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  	Stack   []*big.Int                  `json:"stack"`
    63  	Storage map[common.Hash]common.Hash `json:"-"`
    64  	Depth   int                         `json:"depth"`
    65  	Err     error                       `json:"error"`
    66  }
    67  
    68  // overrides for gencodec
    69  type structLogMarshaling struct {
    70  	Stack      []*math.HexOrDecimal256
    71  	Gas        math.HexOrDecimal64
    72  	GasCost    math.HexOrDecimal64
    73  	Memory     hexutil.Bytes
    74  	OpName     string `json:"opName"`
    75  	MemorySize int    `json:"memSize"`
    76  }
    77  
    78  func (s *StructLog) OpName() string {
    79  	return s.Op.String()
    80  }
    81  
    82  func (s *StructLog) MemorySize() int {
    83  	return len(s.Memory)
    84  }
    85  
    86  // Tracer is used to collect execution traces from an EVM transaction
    87  // execution. CaptureState is called for each step of the VM with the
    88  // current VM state.
    89  // Note that reference types are actual VM data structures; make copies
    90  // if you need to retain them beyond the current call.
    91  type Tracer interface {
    92  	CaptureState(env *EVM, pc uint64, op OpCode, gas, cost uint64, memory *Memory, stack *Stack, contract *Contract, depth int, err error) error
    93  	CaptureEnd(output []byte, gasUsed uint64, t time.Duration) error
    94  }
    95  
    96  // StructLogger is an EVM state logger and implements Tracer.
    97  //
    98  // StructLogger can capture state based on the given Log configuration and also keeps
    99  // a track record of modified storage which is used in reporting snapshots of the
   100  // contract their storage.
   101  type StructLogger struct {
   102  	cfg LogConfig
   103  
   104  	logs          []StructLog
   105  	changedValues map[common.Address]Storage
   106  }
   107  
   108  // NewStructLogger returns a new logger
   109  func NewStructLogger(cfg *LogConfig) *StructLogger {
   110  	logger := &StructLogger{
   111  		changedValues: make(map[common.Address]Storage),
   112  	}
   113  	if cfg != nil {
   114  		logger.cfg = *cfg
   115  	}
   116  	return logger
   117  }
   118  
   119  // CaptureState logs a new structured log message and pushes it out to the environment
   120  //
   121  // CaptureState also tracks SSTORE ops to track dirty values.
   122  func (l *StructLogger) CaptureState(env *EVM, pc uint64, op OpCode, gas, cost uint64, memory *Memory, stack *Stack, contract *Contract, depth int, err error) error {
   123  	// check if already accumulated the specified number of logs
   124  	if l.cfg.Limit != 0 && l.cfg.Limit <= len(l.logs) {
   125  		return ErrTraceLimitReached
   126  	}
   127  
   128  	// initialise new changed values storage container for this contract
   129  	// if not present.
   130  	if l.changedValues[contract.Address()] == nil {
   131  		l.changedValues[contract.Address()] = make(Storage)
   132  	}
   133  
   134  	// capture SSTORE opcodes and determine the changed value and store
   135  	// it in the local storage container. NOTE: we do not need to do any
   136  	// range checks here because that's already handler prior to calling
   137  	// this function.
   138  	switch op {
   139  	case SSTORE:
   140  		var (
   141  			value   = common.BigToHash(stack.data[stack.len()-2])
   142  			address = common.BigToHash(stack.data[stack.len()-1])
   143  		)
   144  		l.changedValues[contract.Address()][address] = value
   145  	}
   146  
   147  	// copy a snapstot of the current memory state to a new buffer
   148  	var mem []byte
   149  	if !l.cfg.DisableMemory {
   150  		mem = make([]byte, len(memory.Data()))
   151  		copy(mem, memory.Data())
   152  	}
   153  
   154  	// copy a snapshot of the current stack state to a new buffer
   155  	var stck []*big.Int
   156  	if !l.cfg.DisableStack {
   157  		stck = make([]*big.Int, len(stack.Data()))
   158  		for i, item := range stack.Data() {
   159  			stck[i] = new(big.Int).Set(item)
   160  		}
   161  	}
   162  
   163  	// Copy the storage based on the settings specified in the log config. If full storage
   164  	// is disabled (default) we can use the simple Storage.Copy method, otherwise we use
   165  	// the state object to query for all values (slow process).
   166  	var storage Storage
   167  	if !l.cfg.DisableStorage {
   168  		if l.cfg.FullStorage {
   169  			storage = make(Storage)
   170  			// Get the contract account and loop over each storage entry. This may involve looping over
   171  			// the trie and is a very expensive process.
   172  
   173  			env.StateDB.ForEachStorage(contract.Address(), func(key, value common.Hash) bool {
   174  				storage[key] = value
   175  				// Return true, indicating we'd like to continue.
   176  				return true
   177  			})
   178  		} else {
   179  			// copy a snapshot of the current storage to a new container.
   180  			storage = l.changedValues[contract.Address()].Copy()
   181  		}
   182  	}
   183  	// create a new snaptshot of the EVM.
   184  	log := StructLog{pc, op, gas, cost, mem, stck, storage, env.depth, err}
   185  
   186  	l.logs = append(l.logs, log)
   187  	return nil
   188  }
   189  
   190  func (l *StructLogger) CaptureEnd(output []byte, gasUsed uint64, t time.Duration) error {
   191  	fmt.Printf("0x%x", output)
   192  	return nil
   193  }
   194  
   195  // StructLogs returns a list of captured log entries
   196  func (l *StructLogger) StructLogs() []StructLog {
   197  	return l.logs
   198  }
   199  
   200  // WriteTrace writes a formatted trace to the given writer
   201  func WriteTrace(writer io.Writer, logs []StructLog) {
   202  	for _, log := range logs {
   203  		fmt.Fprintf(writer, "%-10spc=%08d gas=%v cost=%v", log.Op, log.Pc, log.Gas, log.GasCost)
   204  		if log.Err != nil {
   205  			fmt.Fprintf(writer, " ERROR: %v", log.Err)
   206  		}
   207  		fmt.Fprintf(writer, "\n")
   208  
   209  		for i := len(log.Stack) - 1; i >= 0; i-- {
   210  			fmt.Fprintf(writer, "%08d  %x\n", len(log.Stack)-i-1, math.PaddedBigBytes(log.Stack[i], 32))
   211  		}
   212  
   213  		fmt.Fprint(writer, hex.Dump(log.Memory))
   214  
   215  		for h, item := range log.Storage {
   216  			fmt.Fprintf(writer, "%x: %x\n", h, item)
   217  		}
   218  		fmt.Fprintln(writer)
   219  	}
   220  }
   221  
   222  // WriteLogs writes vm logs in a readable format to the given writer
   223  func WriteLogs(writer io.Writer, logs []*types.Log) {
   224  	for _, log := range logs {
   225  		fmt.Fprintf(writer, "LOG%d: %x bn=%d txi=%x\n", len(log.Topics), log.Address, log.BlockNumber, log.TxIndex)
   226  
   227  		for i, topic := range log.Topics {
   228  			fmt.Fprintf(writer, "%08d  %x\n", i, topic)
   229  		}
   230  
   231  		fmt.Fprint(writer, hex.Dump(log.Data))
   232  		fmt.Fprintln(writer)
   233  	}
   234  }