github.com/ccm-chain/ccmchain@v1.0.0/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  	"errors"
    22  	"fmt"
    23  	"io"
    24  	"math/big"
    25  	"strings"
    26  	"time"
    27  
    28  	"github.com/ccm-chain/ccmchain/common"
    29  	"github.com/ccm-chain/ccmchain/common/hexutil"
    30  	"github.com/ccm-chain/ccmchain/common/math"
    31  	"github.com/ccm-chain/ccmchain/core/types"
    32  )
    33  
    34  var errTraceLimitReached = errors.New("the number of logs reached the specified limit")
    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  }
    57  
    58  //go:generate gencodec -type StructLog -field-override structLogMarshaling -out gen_structlog.go
    59  
    60  // StructLog is emitted to the EVM each cycle and lists information about the current internal state
    61  // prior to the execution of the statement.
    62  type StructLog struct {
    63  	Pc            uint64                      `json:"pc"`
    64  	Op            OpCode                      `json:"op"`
    65  	Gas           uint64                      `json:"gas"`
    66  	GasCost       uint64                      `json:"gasCost"`
    67  	Memory        []byte                      `json:"memory"`
    68  	MemorySize    int                         `json:"memSize"`
    69  	Stack         []*big.Int                  `json:"stack"`
    70  	ReturnStack   []uint32                    `json:"returnStack"`
    71  	ReturnData    []byte                      `json:"returnData"`
    72  	Storage       map[common.Hash]common.Hash `json:"-"`
    73  	Depth         int                         `json:"depth"`
    74  	RefundCounter uint64                      `json:"refund"`
    75  	Err           error                       `json:"-"`
    76  }
    77  
    78  // overrides for gencodec
    79  type structLogMarshaling struct {
    80  	Stack       []*math.HexOrDecimal256
    81  	ReturnStack []math.HexOrDecimal64
    82  	Gas         math.HexOrDecimal64
    83  	GasCost     math.HexOrDecimal64
    84  	Memory      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(from common.Address, to common.Address, create bool, input []byte, gas uint64, value *big.Int) error
   109  	CaptureState(env *EVM, pc uint64, op OpCode, gas, cost uint64, memory *Memory, stack *Stack, rStack *ReturnStack, rData []byte, contract *Contract, depth int, err error) error
   110  	CaptureFault(env *EVM, pc uint64, op OpCode, gas, cost uint64, memory *Memory, stack *Stack, rStack *ReturnStack, contract *Contract, depth int, err error) error
   111  	CaptureEnd(output []byte, gasUsed uint64, t time.Duration, err error) 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  // CaptureStart implements the Tracer interface to initialize the tracing operation.
   140  func (l *StructLogger) CaptureStart(from common.Address, to common.Address, create bool, input []byte, gas uint64, value *big.Int) error {
   141  	return nil
   142  }
   143  
   144  // CaptureState logs a new structured log message and pushes it out to the environment
   145  //
   146  // CaptureState also tracks SLOAD/SSTORE ops to track storage change.
   147  func (l *StructLogger) CaptureState(env *EVM, pc uint64, op OpCode, gas, cost uint64, memory *Memory, stack *Stack, rStack *ReturnStack, rData []byte, contract *Contract, depth int, err error) error {
   148  	// check if already accumulated the specified number of logs
   149  	if l.cfg.Limit != 0 && l.cfg.Limit <= len(l.logs) {
   150  		return errTraceLimitReached
   151  	}
   152  	// Copy a snapshot of the current memory state to a new buffer
   153  	var mem []byte
   154  	if !l.cfg.DisableMemory {
   155  		mem = make([]byte, len(memory.Data()))
   156  		copy(mem, memory.Data())
   157  	}
   158  	// Copy a snapshot of the current stack state to a new buffer
   159  	var stck []*big.Int
   160  	if !l.cfg.DisableStack {
   161  		stck = make([]*big.Int, len(stack.Data()))
   162  		for i, item := range stack.Data() {
   163  			stck[i] = new(big.Int).Set(item.ToBig())
   164  		}
   165  	}
   166  	var rstack []uint32
   167  	if !l.cfg.DisableStack && rStack != nil {
   168  		rstck := make([]uint32, len(rStack.data))
   169  		copy(rstck, rStack.data)
   170  	}
   171  	// Copy a snapshot of the current storage to a new container
   172  	var storage Storage
   173  	if !l.cfg.DisableStorage {
   174  		// initialise new changed values storage container for this contract
   175  		// if not present.
   176  		if l.storage[contract.Address()] == nil {
   177  			l.storage[contract.Address()] = make(Storage)
   178  		}
   179  		// capture SLOAD opcodes and record the read entry in the local storage
   180  		if op == SLOAD && stack.len() >= 1 {
   181  			var (
   182  				address = common.Hash(stack.data[stack.len()-1].Bytes32())
   183  				value   = env.StateDB.GetState(contract.Address(), address)
   184  			)
   185  			l.storage[contract.Address()][address] = value
   186  		}
   187  		// capture SSTORE opcodes and record the written entry in the local storage.
   188  		if op == SSTORE && stack.len() >= 2 {
   189  			var (
   190  				value   = common.Hash(stack.data[stack.len()-2].Bytes32())
   191  				address = common.Hash(stack.data[stack.len()-1].Bytes32())
   192  			)
   193  			l.storage[contract.Address()][address] = value
   194  		}
   195  		storage = l.storage[contract.Address()].Copy()
   196  	}
   197  	var rdata []byte
   198  	if !l.cfg.DisableReturnData {
   199  		rdata = make([]byte, len(rData))
   200  		copy(rdata, rData)
   201  	}
   202  	// create a new snapshot of the EVM.
   203  	log := StructLog{pc, op, gas, cost, mem, memory.Len(), stck, rstack, rdata, storage, depth, env.StateDB.GetRefund(), err}
   204  	l.logs = append(l.logs, log)
   205  	return nil
   206  }
   207  
   208  // CaptureFault implements the Tracer interface to trace an execution fault
   209  // while running an opcode.
   210  func (l *StructLogger) CaptureFault(env *EVM, pc uint64, op OpCode, gas, cost uint64, memory *Memory, stack *Stack, rStack *ReturnStack, contract *Contract, depth int, err error) error {
   211  	return nil
   212  }
   213  
   214  // CaptureEnd is called after the call finishes to finalize the tracing.
   215  func (l *StructLogger) CaptureEnd(output []byte, gasUsed uint64, t time.Duration, err error) error {
   216  	l.output = output
   217  	l.err = err
   218  	if l.cfg.Debug {
   219  		fmt.Printf("0x%x\n", output)
   220  		if err != nil {
   221  			fmt.Printf(" error: %v\n", err)
   222  		}
   223  	}
   224  	return nil
   225  }
   226  
   227  // StructLogs returns the captured log entries.
   228  func (l *StructLogger) StructLogs() []StructLog { return l.logs }
   229  
   230  // Error returns the VM error captured by the trace.
   231  func (l *StructLogger) Error() error { return l.err }
   232  
   233  // Output returns the VM return value captured by the trace.
   234  func (l *StructLogger) Output() []byte { return l.output }
   235  
   236  // WriteTrace writes a formatted trace to the given writer
   237  func WriteTrace(writer io.Writer, logs []StructLog) {
   238  	for _, log := range logs {
   239  		fmt.Fprintf(writer, "%-16spc=%08d gas=%v cost=%v", log.Op, log.Pc, log.Gas, log.GasCost)
   240  		if log.Err != nil {
   241  			fmt.Fprintf(writer, " ERROR: %v", log.Err)
   242  		}
   243  		fmt.Fprintln(writer)
   244  
   245  		if len(log.Stack) > 0 {
   246  			fmt.Fprintln(writer, "Stack:")
   247  			for i := len(log.Stack) - 1; i >= 0; i-- {
   248  				fmt.Fprintf(writer, "%08d  %x\n", len(log.Stack)-i-1, math.PaddedBigBytes(log.Stack[i], 32))
   249  			}
   250  		}
   251  		if len(log.ReturnStack) > 0 {
   252  			fmt.Fprintln(writer, "ReturnStack:")
   253  			for i := len(log.Stack) - 1; i >= 0; i-- {
   254  				fmt.Fprintf(writer, "%08d  0x%x (%d)\n", len(log.Stack)-i-1, log.ReturnStack[i], log.ReturnStack[i])
   255  			}
   256  		}
   257  		if len(log.Memory) > 0 {
   258  			fmt.Fprintln(writer, "Memory:")
   259  			fmt.Fprint(writer, hex.Dump(log.Memory))
   260  		}
   261  		if len(log.Storage) > 0 {
   262  			fmt.Fprintln(writer, "Storage:")
   263  			for h, item := range log.Storage {
   264  				fmt.Fprintf(writer, "%x: %x\n", h, item)
   265  			}
   266  		}
   267  		if len(log.ReturnData) > 0 {
   268  			fmt.Fprintln(writer, "ReturnData:")
   269  			fmt.Fprint(writer, hex.Dump(log.ReturnData))
   270  		}
   271  		fmt.Fprintln(writer)
   272  	}
   273  }
   274  
   275  // WriteLogs writes vm logs in a readable format to the given writer
   276  func WriteLogs(writer io.Writer, logs []*types.Log) {
   277  	for _, log := range logs {
   278  		fmt.Fprintf(writer, "LOG%d: %x bn=%d txi=%x\n", len(log.Topics), log.Address, log.BlockNumber, log.TxIndex)
   279  
   280  		for i, topic := range log.Topics {
   281  			fmt.Fprintf(writer, "%08d  %x\n", i, topic)
   282  		}
   283  
   284  		fmt.Fprint(writer, hex.Dump(log.Data))
   285  		fmt.Fprintln(writer)
   286  	}
   287  }
   288  
   289  type mdLogger struct {
   290  	out io.Writer
   291  	cfg *LogConfig
   292  }
   293  
   294  // NewMarkdownLogger creates a logger which outputs information in a format adapted
   295  // for human readability, and is also a valid markdown table
   296  func NewMarkdownLogger(cfg *LogConfig, writer io.Writer) *mdLogger {
   297  	l := &mdLogger{writer, cfg}
   298  	if l.cfg == nil {
   299  		l.cfg = &LogConfig{}
   300  	}
   301  	return l
   302  }
   303  
   304  func (t *mdLogger) CaptureStart(from common.Address, to common.Address, create bool, input []byte, gas uint64, value *big.Int) error {
   305  	if !create {
   306  		fmt.Fprintf(t.out, "From: `%v`\nTo: `%v`\nData: `0x%x`\nGas: `%d`\nValue `%v` wei\n",
   307  			from.String(), to.String(),
   308  			input, gas, value)
   309  	} else {
   310  		fmt.Fprintf(t.out, "From: `%v`\nCreate at: `%v`\nData: `0x%x`\nGas: `%d`\nValue `%v` wei\n",
   311  			from.String(), to.String(),
   312  			input, gas, value)
   313  	}
   314  
   315  	fmt.Fprintf(t.out, `
   316  |  Pc   |      Op     | Cost |   Stack   |   RStack  |
   317  |-------|-------------|------|-----------|-----------|
   318  `)
   319  	return nil
   320  }
   321  
   322  func (t *mdLogger) CaptureState(env *EVM, pc uint64, op OpCode, gas, cost uint64, memory *Memory, stack *Stack, rStack *ReturnStack, rData []byte, contract *Contract, depth int, err error) error {
   323  	fmt.Fprintf(t.out, "| %4d  | %10v  |  %3d |", pc, op, cost)
   324  
   325  	if !t.cfg.DisableStack { // format stack
   326  		var a []string
   327  		for _, elem := range stack.data {
   328  			a = append(a, fmt.Sprintf("%d", elem))
   329  		}
   330  		b := fmt.Sprintf("[%v]", strings.Join(a, ","))
   331  		fmt.Fprintf(t.out, "%10v |", b)
   332  	}
   333  	if !t.cfg.DisableStack { // format return stack
   334  		var a []string
   335  		for _, elem := range rStack.data {
   336  			a = append(a, fmt.Sprintf("%2d", elem))
   337  		}
   338  		b := fmt.Sprintf("[%v]", strings.Join(a, ","))
   339  		fmt.Fprintf(t.out, "%10v |", b)
   340  	}
   341  	fmt.Fprintln(t.out, "")
   342  	if err != nil {
   343  		fmt.Fprintf(t.out, "Error: %v\n", err)
   344  	}
   345  	return nil
   346  }
   347  
   348  func (t *mdLogger) CaptureFault(env *EVM, pc uint64, op OpCode, gas, cost uint64, memory *Memory, stack *Stack, rStack *ReturnStack, contract *Contract, depth int, err error) error {
   349  
   350  	fmt.Fprintf(t.out, "\nError: at pc=%d, op=%v: %v\n", pc, op, err)
   351  
   352  	return nil
   353  }
   354  
   355  func (t *mdLogger) CaptureEnd(output []byte, gasUsed uint64, tm time.Duration, err error) error {
   356  	fmt.Fprintf(t.out, `
   357  Output: 0x%x
   358  Consumed gas: %d
   359  Error: %v
   360  `,
   361  		output, gasUsed, err)
   362  	return nil
   363  }