github.com/aigarnetwork/aigar@v0.0.0-20191115204914-d59a6eb70f8e/core/vm/logger.go (about)

     1  //  Copyright 2018 The go-ethereum Authors
     2  //  Copyright 2019 The go-aigar Authors
     3  //  This file is part of the go-aigar library.
     4  //
     5  //  The go-aigar library is free software: you can redistribute it and/or modify
     6  //  it under the terms of the GNU Lesser General Public License as published by
     7  //  the Free Software Foundation, either version 3 of the License, or
     8  //  (at your option) any later version.
     9  //
    10  //  The go-aigar library is distributed in the hope that it will be useful,
    11  //  but WITHOUT ANY WARRANTY; without even the implied warranty of
    12  //  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    13  //  GNU Lesser General Public License for more details.
    14  //
    15  //  You should have received a copy of the GNU Lesser General Public License
    16  //  along with the go-aigar library. If not, see <http://www.gnu.org/licenses/>.
    17  
    18  package vm
    19  
    20  import (
    21  	"encoding/hex"
    22  	"fmt"
    23  	"io"
    24  	"math/big"
    25  	"time"
    26  
    27  	"github.com/AigarNetwork/aigar/common"
    28  	"github.com/AigarNetwork/aigar/common/hexutil"
    29  	"github.com/AigarNetwork/aigar/common/math"
    30  	"github.com/AigarNetwork/aigar/core/types"
    31  )
    32  
    33  // Storage represents a contract's storage.
    34  type Storage map[common.Hash]common.Hash
    35  
    36  // Copy duplicates the current storage.
    37  func (s Storage) Copy() Storage {
    38  	cpy := make(Storage)
    39  	for key, value := range s {
    40  		cpy[key] = value
    41  	}
    42  
    43  	return cpy
    44  }
    45  
    46  // LogConfig are the configuration options for structured logger the EVM
    47  type LogConfig struct {
    48  	DisableMemory  bool // disable memory capture
    49  	DisableStack   bool // disable stack capture
    50  	DisableStorage bool // disable storage capture
    51  	Debug          bool // print output during capture end
    52  	Limit          int  // maximum length of output, but zero means unlimited
    53  }
    54  
    55  //go:generate gencodec -type StructLog -field-override structLogMarshaling -out gen_structlog.go
    56  
    57  // StructLog is emitted to the EVM each cycle and lists information about the current internal state
    58  // prior to the execution of the statement.
    59  type StructLog struct {
    60  	Pc            uint64                      `json:"pc"`
    61  	Op            OpCode                      `json:"op"`
    62  	Gas           uint64                      `json:"gas"`
    63  	GasCost       uint64                      `json:"gasCost"`
    64  	Memory        []byte                      `json:"memory"`
    65  	MemorySize    int                         `json:"memSize"`
    66  	Stack         []*big.Int                  `json:"stack"`
    67  	Storage       map[common.Hash]common.Hash `json:"-"`
    68  	Depth         int                         `json:"depth"`
    69  	RefundCounter uint64                      `json:"refund"`
    70  	Err           error                       `json:"-"`
    71  }
    72  
    73  // overrides for gencodec
    74  type structLogMarshaling struct {
    75  	Stack       []*math.HexOrDecimal256
    76  	Gas         math.HexOrDecimal64
    77  	GasCost     math.HexOrDecimal64
    78  	Memory      hexutil.Bytes
    79  	OpName      string `json:"opName"` // adds call to OpName() in MarshalJSON
    80  	ErrorString string `json:"error"`  // adds call to ErrorString() in MarshalJSON
    81  }
    82  
    83  // OpName formats the operand name in a human-readable format.
    84  func (s *StructLog) OpName() string {
    85  	return s.Op.String()
    86  }
    87  
    88  // ErrorString formats the log's error as a string.
    89  func (s *StructLog) ErrorString() string {
    90  	if s.Err != nil {
    91  		return s.Err.Error()
    92  	}
    93  	return ""
    94  }
    95  
    96  // Tracer is used to collect execution traces from an EVM transaction
    97  // execution. CaptureState is called for each step of the VM with the
    98  // current VM state.
    99  // Note that reference types are actual VM data structures; make copies
   100  // if you need to retain them beyond the current call.
   101  type Tracer interface {
   102  	CaptureStart(from common.Address, to common.Address, create bool, input []byte, gas uint64, value *big.Int) error
   103  	CaptureState(env *EVM, pc uint64, op OpCode, gas, cost uint64, memory *Memory, stack *Stack, contract *Contract, depth int, err error) error
   104  	CaptureFault(env *EVM, pc uint64, op OpCode, gas, cost uint64, memory *Memory, stack *Stack, contract *Contract, depth int, err error) error
   105  	CaptureEnd(output []byte, gasUsed uint64, t time.Duration, err error) error
   106  }
   107  
   108  // StructLogger is an EVM state logger and implements Tracer.
   109  //
   110  // StructLogger can capture state based on the given Log configuration and also keeps
   111  // a track record of modified storage which is used in reporting snapshots of the
   112  // contract their storage.
   113  type StructLogger struct {
   114  	cfg LogConfig
   115  
   116  	logs          []StructLog
   117  	changedValues map[common.Address]Storage
   118  	output        []byte
   119  	err           error
   120  }
   121  
   122  // NewStructLogger returns a new logger
   123  func NewStructLogger(cfg *LogConfig) *StructLogger {
   124  	logger := &StructLogger{
   125  		changedValues: make(map[common.Address]Storage),
   126  	}
   127  	if cfg != nil {
   128  		logger.cfg = *cfg
   129  	}
   130  	return logger
   131  }
   132  
   133  // CaptureStart implements the Tracer interface to initialize the tracing operation.
   134  func (l *StructLogger) CaptureStart(from common.Address, to common.Address, create bool, input []byte, gas uint64, value *big.Int) error {
   135  	return nil
   136  }
   137  
   138  // CaptureState logs a new structured log message and pushes it out to the environment
   139  //
   140  // CaptureState also tracks SSTORE ops to track dirty values.
   141  func (l *StructLogger) CaptureState(env *EVM, pc uint64, op OpCode, gas, cost uint64, memory *Memory, stack *Stack, contract *Contract, depth int, err error) error {
   142  	// check if already accumulated the specified number of logs
   143  	if l.cfg.Limit != 0 && l.cfg.Limit <= len(l.logs) {
   144  		return ErrTraceLimitReached
   145  	}
   146  
   147  	// initialise new changed values storage container for this contract
   148  	// if not present.
   149  	if l.changedValues[contract.Address()] == nil {
   150  		l.changedValues[contract.Address()] = make(Storage)
   151  	}
   152  
   153  	// capture SSTORE opcodes and determine the changed value and store
   154  	// it in the local storage container.
   155  	if op == SSTORE && stack.len() >= 2 {
   156  		var (
   157  			value   = common.BigToHash(stack.data[stack.len()-2])
   158  			address = common.BigToHash(stack.data[stack.len()-1])
   159  		)
   160  		l.changedValues[contract.Address()][address] = value
   161  	}
   162  	// Copy a snapshot of the current memory state to a new buffer
   163  	var mem []byte
   164  	if !l.cfg.DisableMemory {
   165  		mem = make([]byte, len(memory.Data()))
   166  		copy(mem, memory.Data())
   167  	}
   168  	// Copy a snapshot of the current stack state to a new buffer
   169  	var stck []*big.Int
   170  	if !l.cfg.DisableStack {
   171  		stck = make([]*big.Int, len(stack.Data()))
   172  		for i, item := range stack.Data() {
   173  			stck[i] = new(big.Int).Set(item)
   174  		}
   175  	}
   176  	// Copy a snapshot of the current storage to a new container
   177  	var storage Storage
   178  	if !l.cfg.DisableStorage {
   179  		storage = l.changedValues[contract.Address()].Copy()
   180  	}
   181  	// create a new snapshot of the EVM.
   182  	log := StructLog{pc, op, gas, cost, mem, memory.Len(), stck, storage, depth, env.StateDB.GetRefund(), err}
   183  
   184  	l.logs = append(l.logs, log)
   185  	return nil
   186  }
   187  
   188  // CaptureFault implements the Tracer interface to trace an execution fault
   189  // while running an opcode.
   190  func (l *StructLogger) CaptureFault(env *EVM, pc uint64, op OpCode, gas, cost uint64, memory *Memory, stack *Stack, contract *Contract, depth int, err error) error {
   191  	return nil
   192  }
   193  
   194  // CaptureEnd is called after the call finishes to finalize the tracing.
   195  func (l *StructLogger) CaptureEnd(output []byte, gasUsed uint64, t time.Duration, err error) error {
   196  	l.output = output
   197  	l.err = err
   198  	if l.cfg.Debug {
   199  		fmt.Printf("0x%x\n", output)
   200  		if err != nil {
   201  			fmt.Printf(" error: %v\n", err)
   202  		}
   203  	}
   204  	return nil
   205  }
   206  
   207  // StructLogs returns the captured log entries.
   208  func (l *StructLogger) StructLogs() []StructLog { return l.logs }
   209  
   210  // Error returns the VM error captured by the trace.
   211  func (l *StructLogger) Error() error { return l.err }
   212  
   213  // Output returns the VM return value captured by the trace.
   214  func (l *StructLogger) Output() []byte { return l.output }
   215  
   216  // WriteTrace writes a formatted trace to the given writer
   217  func WriteTrace(writer io.Writer, logs []StructLog) {
   218  	for _, log := range logs {
   219  		fmt.Fprintf(writer, "%-16spc=%08d gas=%v cost=%v", log.Op, log.Pc, log.Gas, log.GasCost)
   220  		if log.Err != nil {
   221  			fmt.Fprintf(writer, " ERROR: %v", log.Err)
   222  		}
   223  		fmt.Fprintln(writer)
   224  
   225  		if len(log.Stack) > 0 {
   226  			fmt.Fprintln(writer, "Stack:")
   227  			for i := len(log.Stack) - 1; i >= 0; i-- {
   228  				fmt.Fprintf(writer, "%08d  %x\n", len(log.Stack)-i-1, math.PaddedBigBytes(log.Stack[i], 32))
   229  			}
   230  		}
   231  		if len(log.Memory) > 0 {
   232  			fmt.Fprintln(writer, "Memory:")
   233  			fmt.Fprint(writer, hex.Dump(log.Memory))
   234  		}
   235  		if len(log.Storage) > 0 {
   236  			fmt.Fprintln(writer, "Storage:")
   237  			for h, item := range log.Storage {
   238  				fmt.Fprintf(writer, "%x: %x\n", h, item)
   239  			}
   240  		}
   241  		fmt.Fprintln(writer)
   242  	}
   243  }
   244  
   245  // WriteLogs writes vm logs in a readable format to the given writer
   246  func WriteLogs(writer io.Writer, logs []*types.Log) {
   247  	for _, log := range logs {
   248  		fmt.Fprintf(writer, "LOG%d: %x bn=%d txi=%x\n", len(log.Topics), log.Address, log.BlockNumber, log.TxIndex)
   249  
   250  		for i, topic := range log.Topics {
   251  			fmt.Fprintf(writer, "%08d  %x\n", i, topic)
   252  		}
   253  
   254  		fmt.Fprint(writer, hex.Dump(log.Data))
   255  		fmt.Fprintln(writer)
   256  	}
   257  }