github.com/core-coin/go-core@v1.1.7/core/vm/logger.go (about)

     1  // Copyright 2015 by the Authors
     2  // This file is part of the go-core library.
     3  //
     4  // The go-core 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-core 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-core 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/core-coin/go-core/common"
    29  	"github.com/core-coin/go-core/common/hexutil"
    30  	"github.com/core-coin/go-core/common/math"
    31  	"github.com/core-coin/go-core/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  
    46  	return cpy
    47  }
    48  
    49  // LogConfig are the configuration options for structured logger the CVM
    50  type LogConfig struct {
    51  	DisableMemory     bool // disable memory capture
    52  	DisableStack      bool // disable stack capture
    53  	DisableStorage    bool // disable storage capture
    54  	DisableReturnData bool // disable return data capture
    55  	Debug             bool // print output during capture end
    56  	Limit             int  // maximum length of output, but zero means unlimited
    57  }
    58  
    59  //go:generate gencodec -type StructLog -field-override structLogMarshaling -out gen_structlog.go
    60  
    61  // StructLog is emitted to the CVM each cycle and lists information about the current internal state
    62  // prior to the execution of the statement.
    63  type StructLog struct {
    64  	Pc            uint64                      `json:"pc"`
    65  	Op            OpCode                      `json:"op"`
    66  	Energy        uint64                      `json:"energy"`
    67  	EnergyCost    uint64                      `json:"energyCost"`
    68  	Memory        []byte                      `json:"memory"`
    69  	MemorySize    int                         `json:"memSize"`
    70  	Stack         []*big.Int                  `json:"stack"`
    71  	ReturnStack   []uint32                    `json:"returnStack"`
    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  	Stack       []*math.HexOrDecimal256
    82  	ReturnStack []math.HexOrDecimal64
    83  	Energy      math.HexOrDecimal64
    84  	EnergyCost  math.HexOrDecimal64
    85  	Memory      hexutil.Bytes
    86  	OpName      string `json:"opName"` // adds call to OpName() in MarshalJSON
    87  	ErrorString string `json:"error"`  // adds call to ErrorString() in MarshalJSON
    88  }
    89  
    90  // OpName formats the operand name in a human-readable format.
    91  func (s *StructLog) OpName() string {
    92  	return s.Op.String()
    93  }
    94  
    95  // ErrorString formats the log's error as a string.
    96  func (s *StructLog) ErrorString() string {
    97  	if s.Err != nil {
    98  		return s.Err.Error()
    99  	}
   100  	return ""
   101  }
   102  
   103  // Tracer is used to collect execution traces from an CVM transaction
   104  // execution. CaptureState is called for each step of the VM with the
   105  // current VM state.
   106  // Note that reference types are actual VM data structures; make copies
   107  // if you need to retain them beyond the current call.
   108  type Tracer interface {
   109  	CaptureStart(from common.Address, to common.Address, create bool, input []byte, energy uint64, value *big.Int) error
   110  	CaptureState(env *CVM, pc uint64, op OpCode, energy, cost uint64, memory *Memory, stack *Stack, rStack *ReturnStack, rData []byte, contract *Contract, depth int, err error) error
   111  	CaptureFault(env *CVM, pc uint64, op OpCode, energy, cost uint64, memory *Memory, stack *Stack, rStack *ReturnStack, contract *Contract, depth int, err error) error
   112  	CaptureEnd(output []byte, energyUsed uint64, t time.Duration, err error) error
   113  }
   114  
   115  // StructLogger is an CVM state logger and implements Tracer.
   116  //
   117  // StructLogger can capture state based on the given Log configuration and also keeps
   118  // a track record of modified storage which is used in reporting snapshots of the
   119  // contract their storage.
   120  type StructLogger struct {
   121  	cfg LogConfig
   122  
   123  	logs          []StructLog
   124  	changedValues map[common.Address]Storage
   125  	output        []byte
   126  	err           error
   127  }
   128  
   129  // NewStructLogger returns a new logger
   130  func NewStructLogger(cfg *LogConfig) *StructLogger {
   131  	logger := &StructLogger{
   132  		changedValues: make(map[common.Address]Storage),
   133  	}
   134  	if cfg != nil {
   135  		logger.cfg = *cfg
   136  	}
   137  	return logger
   138  }
   139  
   140  // CaptureStart implements the Tracer interface to initialize the tracing operation.
   141  func (l *StructLogger) CaptureStart(from common.Address, to common.Address, create bool, input []byte, energy uint64, value *big.Int) error {
   142  	return nil
   143  }
   144  
   145  // CaptureState logs a new structured log message and pushes it out to the environment
   146  //
   147  // CaptureState also tracks SSTORE ops to track dirty values.
   148  func (l *StructLogger) CaptureState(env *CVM, pc uint64, op OpCode, energy, cost uint64, memory *Memory, stack *Stack, rStack *ReturnStack, rData []byte, contract *Contract, depth int, err error) error {
   149  	// check if already accumulated the specified number of logs
   150  	if l.cfg.Limit != 0 && l.cfg.Limit <= len(l.logs) {
   151  		return errTraceLimitReached
   152  	}
   153  
   154  	// initialise new changed values storage container for this contract
   155  	// if not present.
   156  	if l.changedValues[contract.Address()] == nil {
   157  		l.changedValues[contract.Address()] = make(Storage)
   158  	}
   159  
   160  	// capture SSTORE opcodes and determine the changed value and store
   161  	// it in the local storage container.
   162  	if op == SSTORE && stack.len() >= 2 {
   163  		var (
   164  			value   = common.Hash(stack.data[stack.len()-2].Bytes32())
   165  			address = common.Hash(stack.data[stack.len()-1].Bytes32())
   166  		)
   167  		l.changedValues[contract.Address()][address] = value
   168  	}
   169  	// Copy a snapshot of the current memory state to a new buffer
   170  	var mem []byte
   171  	if !l.cfg.DisableMemory {
   172  		mem = make([]byte, len(memory.Data()))
   173  		copy(mem, memory.Data())
   174  	}
   175  	// Copy a snapshot of the current stack state to a new buffer
   176  	var stck []*big.Int
   177  	if !l.cfg.DisableStack {
   178  		stck = make([]*big.Int, len(stack.Data()))
   179  		for i, item := range stack.Data() {
   180  			stck[i] = new(big.Int).Set(item.ToBig())
   181  		}
   182  	}
   183  	// Copy a snapshot of the current storage to a new container
   184  	var storage Storage
   185  	if !l.cfg.DisableStorage {
   186  		storage = l.changedValues[contract.Address()].Copy()
   187  	}
   188  	var rstack []uint32
   189  	if !l.cfg.DisableStack && rStack != nil {
   190  		rstck := make([]uint32, len(rStack.data))
   191  		copy(rstck, rStack.data)
   192  	}
   193  	var rdata []byte
   194  	if !l.cfg.DisableReturnData {
   195  		rdata = make([]byte, len(rData))
   196  		copy(rdata, rData)
   197  	}
   198  	// create a new snapshot of the EVM.
   199  	log := StructLog{pc, op, energy, cost, mem, memory.Len(), stck, rstack, rdata, storage, depth, env.StateDB.GetRefund(), err}
   200  	l.logs = append(l.logs, log)
   201  	return nil
   202  }
   203  
   204  // CaptureFault implements the Tracer interface to trace an execution fault
   205  // while running an opcode.
   206  func (l *StructLogger) CaptureFault(env *CVM, pc uint64, op OpCode, energy, cost uint64, memory *Memory, stack *Stack, rStack *ReturnStack, contract *Contract, depth int, err error) error {
   207  	return nil
   208  }
   209  
   210  // CaptureEnd is called after the call finishes to finalize the tracing.
   211  func (l *StructLogger) CaptureEnd(output []byte, energyUsed uint64, t time.Duration, err error) error {
   212  	l.output = output
   213  	l.err = err
   214  	if l.cfg.Debug {
   215  		fmt.Printf("0x%x\n", output)
   216  		if err != nil {
   217  			fmt.Printf(" error: %v\n", err)
   218  		}
   219  	}
   220  	return nil
   221  }
   222  
   223  // StructLogs returns the captured log entries.
   224  func (l *StructLogger) StructLogs() []StructLog { return l.logs }
   225  
   226  // Error returns the VM error captured by the trace.
   227  func (l *StructLogger) Error() error { return l.err }
   228  
   229  // Output returns the VM return value captured by the trace.
   230  func (l *StructLogger) Output() []byte { return l.output }
   231  
   232  // WriteTrace writes a formatted trace to the given writer
   233  func WriteTrace(writer io.Writer, logs []StructLog) {
   234  	for _, log := range logs {
   235  		fmt.Fprintf(writer, "%-16spc=%08d energy=%v cost=%v", log.Op, log.Pc, log.Energy, log.EnergyCost)
   236  		if log.Err != nil {
   237  			fmt.Fprintf(writer, " ERROR: %v", log.Err)
   238  		}
   239  		fmt.Fprintln(writer)
   240  
   241  		if len(log.Stack) > 0 {
   242  			fmt.Fprintln(writer, "Stack:")
   243  			for i := len(log.Stack) - 1; i >= 0; i-- {
   244  				fmt.Fprintf(writer, "%08d  %x\n", len(log.Stack)-i-1, math.PaddedBigBytes(log.Stack[i], 32))
   245  			}
   246  		}
   247  		if len(log.ReturnStack) > 0 {
   248  			fmt.Fprintln(writer, "ReturnStack:")
   249  			for i := len(log.Stack) - 1; i >= 0; i-- {
   250  				fmt.Fprintf(writer, "%08d  0x%x (%d)\n", len(log.Stack)-i-1, log.ReturnStack[i], log.ReturnStack[i])
   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(from common.Address, to common.Address, create bool, input []byte, gas uint64, value *big.Int) error {
   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  |
   313  |-------|-------------|------|-----------|-----------|
   314  `)
   315  	return nil
   316  }
   317  
   318  func (t *mdLogger) CaptureState(env *CVM, pc uint64, op OpCode, gas, cost uint64, memory *Memory, stack *Stack, rStack *ReturnStack, rData []byte, contract *Contract, depth int, err error) error {
   319  	fmt.Fprintf(t.out, "| %4d  | %10v  |  %3d |", pc, op, cost)
   320  
   321  	if !t.cfg.DisableStack { // format stack
   322  		var a []string
   323  		for _, elem := range stack.data {
   324  			a = append(a, fmt.Sprintf("%d", elem))
   325  		}
   326  		b := fmt.Sprintf("[%v]", strings.Join(a, ","))
   327  		fmt.Fprintf(t.out, "%10v |", b)
   328  	}
   329  	if !t.cfg.DisableStack { // format return stack
   330  		var a []string
   331  		for _, elem := range rStack.data {
   332  			a = append(a, fmt.Sprintf("%2d", elem))
   333  		}
   334  		b := fmt.Sprintf("[%v]", strings.Join(a, ","))
   335  		fmt.Fprintf(t.out, "%10v |", b)
   336  	}
   337  	fmt.Fprintln(t.out, "")
   338  	if err != nil {
   339  		fmt.Fprintf(t.out, "Error: %v\n", err)
   340  	}
   341  	return nil
   342  }
   343  
   344  func (t *mdLogger) CaptureFault(env *CVM, pc uint64, op OpCode, gas, cost uint64, memory *Memory, stack *Stack, rStack *ReturnStack, contract *Contract, depth int, err error) error {
   345  
   346  	fmt.Fprintf(t.out, "\nError: at pc=%d, op=%v: %v\n", pc, op, err)
   347  
   348  	return nil
   349  }
   350  
   351  func (t *mdLogger) CaptureEnd(output []byte, gasUsed uint64, tm time.Duration, err error) error {
   352  	fmt.Fprintf(t.out, `
   353  Output: 0x%x
   354  Consumed gas: %d
   355  Error: %v
   356  `,
   357  		output, gasUsed, err)
   358  	return nil
   359  }