github.com/aquanetwork/aquachain@v1.7.8/core/vm/logger.go (about)

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