github.com/neatlab/neatio@v1.7.3-0.20220425043230-d903e92fcc75/chain/core/vm/logger.go (about)

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