github.com/phillinzzz/newBsc@v1.1.6/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  	"strings"
    25  	"time"
    26  
    27  	"github.com/holiman/uint256"
    28  
    29  	"github.com/phillinzzz/newBsc/common"
    30  	"github.com/phillinzzz/newBsc/common/hexutil"
    31  	"github.com/phillinzzz/newBsc/common/math"
    32  	"github.com/phillinzzz/newBsc/core/types"
    33  	"github.com/phillinzzz/newBsc/params"
    34  )
    35  
    36  // Storage represents a contract's storage.
    37  type Storage map[common.Hash]common.Hash
    38  
    39  // Copy duplicates the current storage.
    40  func (s Storage) Copy() Storage {
    41  	cpy := make(Storage)
    42  	for key, value := range s {
    43  		cpy[key] = value
    44  	}
    45  	return cpy
    46  }
    47  
    48  // LogConfig are the configuration options for structured logger the EVM
    49  type LogConfig struct {
    50  	DisableMemory     bool // disable memory capture
    51  	DisableStack      bool // disable stack capture
    52  	DisableStorage    bool // disable storage capture
    53  	DisableReturnData bool // disable return data capture
    54  	Debug             bool // print output during capture end
    55  	Limit             int  // maximum length of output, but zero means unlimited
    56  	// Chain overrides, can be used to execute a trace using future fork rules
    57  	Overrides *params.ChainConfig `json:"overrides,omitempty"`
    58  }
    59  
    60  //go:generate gencodec -type StructLog -field-override structLogMarshaling -out gen_structlog.go
    61  
    62  // StructLog is emitted to the EVM each cycle and lists information about the current internal state
    63  // prior to the execution of the statement.
    64  type StructLog struct {
    65  	Pc            uint64                      `json:"pc"`
    66  	Op            OpCode                      `json:"op"`
    67  	Gas           uint64                      `json:"gas"`
    68  	GasCost       uint64                      `json:"gasCost"`
    69  	Memory        []byte                      `json:"memory"`
    70  	MemorySize    int                         `json:"memSize"`
    71  	Stack         []uint256.Int               `json:"stack"`
    72  	ReturnData    []byte                      `json:"returnData"`
    73  	Storage       map[common.Hash]common.Hash `json:"-"`
    74  	Depth         int                         `json:"depth"`
    75  	RefundCounter uint64                      `json:"refund"`
    76  	Err           error                       `json:"-"`
    77  }
    78  
    79  // overrides for gencodec
    80  type structLogMarshaling struct {
    81  	Gas         math.HexOrDecimal64
    82  	GasCost     math.HexOrDecimal64
    83  	Memory      hexutil.Bytes
    84  	ReturnData  hexutil.Bytes
    85  	OpName      string `json:"opName"` // adds call to OpName() in MarshalJSON
    86  	ErrorString string `json:"error"`  // adds call to ErrorString() in MarshalJSON
    87  }
    88  
    89  // OpName formats the operand name in a human-readable format.
    90  func (s *StructLog) OpName() string {
    91  	return s.Op.String()
    92  }
    93  
    94  // ErrorString formats the log's error as a string.
    95  func (s *StructLog) ErrorString() string {
    96  	if s.Err != nil {
    97  		return s.Err.Error()
    98  	}
    99  	return ""
   100  }
   101  
   102  // Tracer is used to collect execution traces from an EVM transaction
   103  // execution. CaptureState is called for each step of the VM with the
   104  // current VM state.
   105  // Note that reference types are actual VM data structures; make copies
   106  // if you need to retain them beyond the current call.
   107  type Tracer interface {
   108  	CaptureStart(env *EVM, from common.Address, to common.Address, create bool, input []byte, gas uint64, value *big.Int)
   109  	CaptureState(env *EVM, pc uint64, op OpCode, gas, cost uint64, scope *ScopeContext, rData []byte, depth int, err error)
   110  	CaptureFault(env *EVM, pc uint64, op OpCode, gas, cost uint64, scope *ScopeContext, depth int, err error)
   111  	CaptureEnd(output []byte, gasUsed uint64, t time.Duration, err error)
   112  }
   113  
   114  // StructLogger is an EVM state logger and implements Tracer.
   115  //
   116  // StructLogger can capture state based on the given Log configuration and also keeps
   117  // a track record of modified storage which is used in reporting snapshots of the
   118  // contract their storage.
   119  type StructLogger struct {
   120  	cfg LogConfig
   121  
   122  	storage map[common.Address]Storage
   123  	logs    []StructLog
   124  	output  []byte
   125  	err     error
   126  }
   127  
   128  // NewStructLogger returns a new logger
   129  func NewStructLogger(cfg *LogConfig) *StructLogger {
   130  	logger := &StructLogger{
   131  		storage: make(map[common.Address]Storage),
   132  	}
   133  	if cfg != nil {
   134  		logger.cfg = *cfg
   135  	}
   136  	return logger
   137  }
   138  
   139  // Reset clears the data held by the logger.
   140  func (l *StructLogger) Reset() {
   141  	l.storage = make(map[common.Address]Storage)
   142  	l.output = make([]byte, 0)
   143  	l.logs = l.logs[:0]
   144  	l.err = nil
   145  }
   146  
   147  // CaptureStart implements the Tracer interface to initialize the tracing operation.
   148  func (l *StructLogger) CaptureStart(env *EVM, from common.Address, to common.Address, create bool, input []byte, gas uint64, value *big.Int) {
   149  }
   150  
   151  // CaptureState logs a new structured log message and pushes it out to the environment
   152  //
   153  // CaptureState also tracks SLOAD/SSTORE ops to track storage change.
   154  func (l *StructLogger) CaptureState(env *EVM, pc uint64, op OpCode, gas, cost uint64, scope *ScopeContext, rData []byte, depth int, err error) {
   155  	memory := scope.Memory
   156  	stack := scope.Stack
   157  	contract := scope.Contract
   158  	// check if already accumulated the specified number of logs
   159  	if l.cfg.Limit != 0 && l.cfg.Limit <= len(l.logs) {
   160  		return
   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 []uint256.Int
   170  	if !l.cfg.DisableStack {
   171  		stck = make([]uint256.Int, len(stack.Data()))
   172  		for i, item := range stack.Data() {
   173  			stck[i] = item
   174  		}
   175  	}
   176  	// Copy a snapshot of the current storage to a new container
   177  	var storage Storage
   178  	if !l.cfg.DisableStorage && (op == SLOAD || op == SSTORE) {
   179  		// initialise new changed values storage container for this contract
   180  		// if not present.
   181  		if l.storage[contract.Address()] == nil {
   182  			l.storage[contract.Address()] = make(Storage)
   183  		}
   184  		// capture SLOAD opcodes and record the read entry in the local storage
   185  		if op == SLOAD && stack.len() >= 1 {
   186  			var (
   187  				address = common.Hash(stack.data[stack.len()-1].Bytes32())
   188  				value   = env.StateDB.GetState(contract.Address(), address)
   189  			)
   190  			l.storage[contract.Address()][address] = value
   191  			storage = l.storage[contract.Address()].Copy()
   192  		} else if op == SSTORE && stack.len() >= 2 {
   193  			// capture SSTORE opcodes and record the written entry in the local storage.
   194  			var (
   195  				value   = common.Hash(stack.data[stack.len()-2].Bytes32())
   196  				address = common.Hash(stack.data[stack.len()-1].Bytes32())
   197  			)
   198  			l.storage[contract.Address()][address] = value
   199  			storage = l.storage[contract.Address()].Copy()
   200  		}
   201  	}
   202  	var rdata []byte
   203  	if !l.cfg.DisableReturnData {
   204  		rdata = make([]byte, len(rData))
   205  		copy(rdata, rData)
   206  	}
   207  	// create a new snapshot of the EVM.
   208  	log := StructLog{pc, op, gas, cost, mem, memory.Len(), stck, rdata, storage, depth, env.StateDB.GetRefund(), err}
   209  	l.logs = append(l.logs, log)
   210  }
   211  
   212  // CaptureFault implements the Tracer interface to trace an execution fault
   213  // while running an opcode.
   214  func (l *StructLogger) CaptureFault(env *EVM, pc uint64, op OpCode, gas, cost uint64, scope *ScopeContext, depth int, err error) {
   215  }
   216  
   217  // CaptureEnd is called after the call finishes to finalize the tracing.
   218  func (l *StructLogger) CaptureEnd(output []byte, gasUsed uint64, t time.Duration, err error) {
   219  	l.output = output
   220  	l.err = err
   221  	if l.cfg.Debug {
   222  		fmt.Printf("0x%x\n", output)
   223  		if err != nil {
   224  			fmt.Printf(" error: %v\n", err)
   225  		}
   226  	}
   227  }
   228  
   229  // StructLogs returns the captured log entries.
   230  func (l *StructLogger) StructLogs() []StructLog { return l.logs }
   231  
   232  // Error returns the VM error captured by the trace.
   233  func (l *StructLogger) Error() error { return l.err }
   234  
   235  // Output returns the VM return value captured by the trace.
   236  func (l *StructLogger) Output() []byte { return l.output }
   237  
   238  // WriteTrace writes a formatted trace to the given writer
   239  func WriteTrace(writer io.Writer, logs []StructLog) {
   240  	for _, log := range logs {
   241  		fmt.Fprintf(writer, "%-16spc=%08d gas=%v cost=%v", log.Op, log.Pc, log.Gas, log.GasCost)
   242  		if log.Err != nil {
   243  			fmt.Fprintf(writer, " ERROR: %v", log.Err)
   244  		}
   245  		fmt.Fprintln(writer)
   246  
   247  		if len(log.Stack) > 0 {
   248  			fmt.Fprintln(writer, "Stack:")
   249  			for i := len(log.Stack) - 1; i >= 0; i-- {
   250  				fmt.Fprintf(writer, "%08d  %s\n", len(log.Stack)-i-1, log.Stack[i].Hex())
   251  			}
   252  		}
   253  		if len(log.Memory) > 0 {
   254  			fmt.Fprintln(writer, "Memory:")
   255  			fmt.Fprint(writer, hex.Dump(log.Memory))
   256  		}
   257  		if len(log.Storage) > 0 {
   258  			fmt.Fprintln(writer, "Storage:")
   259  			for h, item := range log.Storage {
   260  				fmt.Fprintf(writer, "%x: %x\n", h, item)
   261  			}
   262  		}
   263  		if len(log.ReturnData) > 0 {
   264  			fmt.Fprintln(writer, "ReturnData:")
   265  			fmt.Fprint(writer, hex.Dump(log.ReturnData))
   266  		}
   267  		fmt.Fprintln(writer)
   268  	}
   269  }
   270  
   271  // WriteLogs writes vm logs in a readable format to the given writer
   272  func WriteLogs(writer io.Writer, logs []*types.Log) {
   273  	for _, log := range logs {
   274  		fmt.Fprintf(writer, "LOG%d: %x bn=%d txi=%x\n", len(log.Topics), log.Address, log.BlockNumber, log.TxIndex)
   275  
   276  		for i, topic := range log.Topics {
   277  			fmt.Fprintf(writer, "%08d  %x\n", i, topic)
   278  		}
   279  
   280  		fmt.Fprint(writer, hex.Dump(log.Data))
   281  		fmt.Fprintln(writer)
   282  	}
   283  }
   284  
   285  type mdLogger struct {
   286  	out io.Writer
   287  	cfg *LogConfig
   288  }
   289  
   290  // NewMarkdownLogger creates a logger which outputs information in a format adapted
   291  // for human readability, and is also a valid markdown table
   292  func NewMarkdownLogger(cfg *LogConfig, writer io.Writer) *mdLogger {
   293  	l := &mdLogger{writer, cfg}
   294  	if l.cfg == nil {
   295  		l.cfg = &LogConfig{}
   296  	}
   297  	return l
   298  }
   299  
   300  func (t *mdLogger) CaptureStart(env *EVM, from common.Address, to common.Address, create bool, input []byte, gas uint64, value *big.Int) {
   301  	if !create {
   302  		fmt.Fprintf(t.out, "From: `%v`\nTo: `%v`\nData: `0x%x`\nGas: `%d`\nValue `%v` wei\n",
   303  			from.String(), to.String(),
   304  			input, gas, value)
   305  	} else {
   306  		fmt.Fprintf(t.out, "From: `%v`\nCreate at: `%v`\nData: `0x%x`\nGas: `%d`\nValue `%v` wei\n",
   307  			from.String(), to.String(),
   308  			input, gas, value)
   309  	}
   310  
   311  	fmt.Fprintf(t.out, `
   312  |  Pc   |      Op     | Cost |   Stack   |   RStack  |  Refund |
   313  |-------|-------------|------|-----------|-----------|---------|
   314  `)
   315  }
   316  
   317  // CaptureState also tracks SLOAD/SSTORE ops to track storage change.
   318  func (t *mdLogger) CaptureState(env *EVM, pc uint64, op OpCode, gas, cost uint64, scope *ScopeContext, rData []byte, depth int, err error) {
   319  	stack := scope.Stack
   320  	fmt.Fprintf(t.out, "| %4d  | %10v  |  %3d |", pc, op, cost)
   321  
   322  	if !t.cfg.DisableStack {
   323  		// format stack
   324  		var a []string
   325  		for _, elem := range stack.data {
   326  			a = append(a, elem.Hex())
   327  		}
   328  		b := fmt.Sprintf("[%v]", strings.Join(a, ","))
   329  		fmt.Fprintf(t.out, "%10v |", b)
   330  	}
   331  	fmt.Fprintf(t.out, "%10v |", env.StateDB.GetRefund())
   332  	fmt.Fprintln(t.out, "")
   333  	if err != nil {
   334  		fmt.Fprintf(t.out, "Error: %v\n", err)
   335  	}
   336  }
   337  
   338  func (t *mdLogger) CaptureFault(env *EVM, pc uint64, op OpCode, gas, cost uint64, scope *ScopeContext, depth int, err error) {
   339  	fmt.Fprintf(t.out, "\nError: at pc=%d, op=%v: %v\n", pc, op, err)
   340  }
   341  
   342  func (t *mdLogger) CaptureEnd(output []byte, gasUsed uint64, tm time.Duration, err error) {
   343  	fmt.Fprintf(t.out, "\nOutput: `0x%x`\nConsumed gas: `%d`\nError: `%v`\n",
   344  		output, gasUsed, err)
   345  }