github.com/cheng762/platon-go@v1.8.17-0.20190529111256-7deff2d7be26/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  	"github.com/PlatONnetwork/PlatON-Go/log"
    21  	"bytes"
    22  	"encoding/hex"
    23  	"fmt"
    24  	"io"
    25  	"math/big"
    26  	"time"
    27  
    28  	"github.com/PlatONnetwork/PlatON-Go/common"
    29  	"github.com/PlatONnetwork/PlatON-Go/common/hexutil"
    30  	"github.com/PlatONnetwork/PlatON-Go/common/math"
    31  	"github.com/PlatONnetwork/PlatON-Go/core/types"
    32  )
    33  
    34  // Storage represents a contract's storage.
    35  type Storage map[common.Hash]common.Hash
    36  
    37  // Copy duplicates the current storage.
    38  func (s Storage) Copy() Storage {
    39  	cpy := make(Storage)
    40  	for key, value := range s {
    41  		cpy[key] = value
    42  	}
    43  
    44  	return cpy
    45  }
    46  
    47  // LogConfig are the configuration options for structured logger the EVM
    48  type LogConfig struct {
    49  	DisableMemory  bool // disable memory capture
    50  	DisableStack   bool // disable stack capture
    51  	DisableStorage bool // disable storage capture
    52  	Debug          bool // print output during capture end
    53  	Limit          int  // maximum length of output, but zero means unlimited
    54  }
    55  
    56  //go:generate gencodec -type StructLog -field-override structLogMarshaling -out gen_structlog.go
    57  
    58  // StructLog is emitted to the EVM each cycle and lists information about the current internal state
    59  // prior to the execution of the statement.
    60  type StructLog struct {
    61  	Pc         uint64                      `json:"pc"`
    62  	Op         OpCode                      `json:"op"`
    63  	Gas        uint64                      `json:"gas"`
    64  	GasCost    uint64                      `json:"gasCost"`
    65  	Memory     []byte                      `json:"memory"`
    66  	MemorySize int                         `json:"memSize"`
    67  	Stack      []*big.Int                  `json:"stack"`
    68  	Storage    map[common.Hash]common.Hash `json:"-"`
    69  	Depth      int                         `json:"depth"`
    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, call 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 snapstot 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 snaptshot of the EVM.
   182  	log := StructLog{pc, op, gas, cost, mem, memory.Len(), stck, storage, depth, 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  }
   258  
   259  
   260  type WasmLogger struct {
   261  	log.Logger
   262  	root log.Logger
   263  	buf *bytes.Buffer
   264  	logger log.Logger
   265  }
   266  
   267  func NewWasmLogger(cfg Config, root log.Logger) *WasmLogger {
   268  	l := &WasmLogger{
   269  		root:root,
   270  		logger:root.New(),
   271  	}
   272  
   273  	l.buf = new(bytes.Buffer)
   274  
   275  	level := log.LvlInfo
   276  
   277  	if cfg.Debug || log.GetWasmLogLevel() >= log.LvlDebug{
   278  		level = log.LvlDebug
   279  	}
   280  
   281  
   282  	l.logger.SetHandler(log.LvlFilterHandler(level, log.StreamHandler(l.buf, log.FormatFunc(func(r *log.Record) []byte {
   283  		return []byte(r.Msg)
   284  	}))))
   285  
   286  
   287  	return l
   288  }
   289  
   290  
   291  func (wl *WasmLogger) Flush()  {
   292  	if wl.buf.Len() != 0 {
   293  		wl.root.Debug(wl.buf.String())
   294  	}
   295  	wl.buf.Reset()
   296  }
   297  
   298  func (wl *WasmLogger) New(ctx ...interface{}) log.Logger {
   299  	return nil
   300  }
   301  
   302  // GetHandler gets the handler associated with the logger.
   303  func (wl *WasmLogger) GetHandler() log.Handler {
   304  	return nil
   305  }
   306  
   307  // SetHandler updates the logger to write records to the specified handler.
   308  func (wl *WasmLogger) SetHandler(h log.Handler) {
   309  }
   310  
   311  
   312  // Log a message at the given level with context key/value pairs
   313  func (wl *WasmLogger) Trace(msg string, ctx ...interface{}) {
   314  	wl.logger.Trace(msg, ctx...)
   315  }
   316  func (wl *WasmLogger) Debug(msg string, ctx ...interface{}) {
   317  	wl.logger.Debug(msg, ctx...)
   318  }
   319  func (wl *WasmLogger) Info(msg string, ctx ...interface{}) {
   320  	wl.logger.Info(msg, ctx...)
   321  }
   322  func (wl *WasmLogger) Warn(msg string, ctx ...interface{}) {
   323  	wl.logger.Warn(msg, ctx...)
   324  }
   325  func (wl *WasmLogger) Error(msg string, ctx ...interface{}) {
   326  	wl.logger.Error(msg, ctx...)
   327  }
   328  func (wl *WasmLogger) Crit(msg string, ctx ...interface{}) {
   329  	wl.logger.Crit(msg, ctx...)
   330  }
   331  
   332  
   333  
   334