github.com/amazechain/amc@v0.1.3/internal/tracers/logger/logger.go (about)

     1  // Copyright 2023 The AmazeChain Authors
     2  // This file is part of the AmazeChain library.
     3  //
     4  // The AmazeChain 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 AmazeChain 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 AmazeChain library. If not, see <http://www.gnu.org/licenses/>.
    16  
    17  package logger
    18  
    19  import (
    20  	"encoding/hex"
    21  	"encoding/json"
    22  	"fmt"
    23  	"io"
    24  	"strings"
    25  	"sync/atomic"
    26  
    27  	types "github.com/amazechain/amc/common/block"
    28  	"github.com/amazechain/amc/common/hexutil"
    29  	"github.com/amazechain/amc/common/math"
    30  	common "github.com/amazechain/amc/common/types"
    31  	"github.com/amazechain/amc/internal/vm"
    32  	"github.com/amazechain/amc/params"
    33  	"github.com/holiman/uint256"
    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, len(s))
    42  	for key, value := range s {
    43  		cpy[key] = value
    44  	}
    45  	return cpy
    46  }
    47  
    48  // Config are the configuration options for structured logger the EVM
    49  type Config struct {
    50  	EnableMemory     bool // enable memory capture
    51  	DisableStack     bool // disable stack capture
    52  	DisableStorage   bool // disable storage capture
    53  	EnableReturnData bool // enable 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 go run github.com/fjl/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            vm.OpCode                   `json:"op"`
    67  	Gas           uint64                      `json:"gas"`
    68  	GasCost       uint64                      `json:"gasCost"`
    69  	Memory        []byte                      `json:"memory,omitempty"`
    70  	MemorySize    int                         `json:"memSize"`
    71  	Stack         []uint256.Int               `json:"stack"`
    72  	ReturnData    []byte                      `json:"returnData,omitempty"`
    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,omitempty"` // 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  // StructLogger is an EVM state logger and implements EVMLogger.
   103  //
   104  // StructLogger can capture state based on the given Log configuration and also keeps
   105  // a track record of modified storage which is used in reporting snapshots of the
   106  // contract their storage.
   107  type StructLogger struct {
   108  	cfg Config
   109  	env *vm.EVM
   110  
   111  	storage  map[common.Address]Storage
   112  	logs     []StructLog
   113  	output   []byte
   114  	err      error
   115  	gasLimit uint64
   116  	usedGas  uint64
   117  
   118  	interrupt uint32 // Atomic flag to signal execution interruption
   119  	reason    error  // Textual reason for the interruption
   120  }
   121  
   122  // NewStructLogger returns a new logger
   123  func NewStructLogger(cfg *Config) *StructLogger {
   124  	logger := &StructLogger{
   125  		storage: make(map[common.Address]Storage),
   126  	}
   127  	if cfg != nil {
   128  		logger.cfg = *cfg
   129  	}
   130  	return logger
   131  }
   132  
   133  // Reset clears the data held by the logger.
   134  func (l *StructLogger) Reset() {
   135  	l.storage = make(map[common.Address]Storage)
   136  	l.output = make([]byte, 0)
   137  	l.logs = l.logs[:0]
   138  	l.err = nil
   139  }
   140  
   141  // CaptureStart implements the EVMLogger interface to initialize the tracing operation.
   142  func (l *StructLogger) CaptureStart(env vm.VMInterface, from common.Address, to common.Address, create bool, input []byte, gas uint64, value *uint256.Int) {
   143  	l.env = env.(*vm.EVM)
   144  }
   145  
   146  // CaptureState logs a new structured log message and pushes it out to the environment
   147  //
   148  // CaptureState also tracks SLOAD/SSTORE ops to track storage change.
   149  func (l *StructLogger) CaptureState(pc uint64, op vm.OpCode, gas, cost uint64, scope *vm.ScopeContext, rData []byte, depth int, err error) {
   150  	// If tracing was interrupted, set the error and stop
   151  	if atomic.LoadUint32(&l.interrupt) > 0 {
   152  		return
   153  	}
   154  	// check if already accumulated the specified number of logs
   155  	if l.cfg.Limit != 0 && l.cfg.Limit <= len(l.logs) {
   156  		return
   157  	}
   158  
   159  	memory := scope.Memory
   160  	stack := scope.Stack
   161  	contract := scope.Contract
   162  	// Copy a snapshot of the current memory state to a new buffer
   163  	var mem []byte
   164  	if l.cfg.EnableMemory {
   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  	stackData := stack.Data
   177  	stackLen := len(stackData)
   178  	// Copy a snapshot of the current storage to a new container
   179  	var storage Storage
   180  	if !l.cfg.DisableStorage && (op == vm.SLOAD || op == vm.SSTORE) {
   181  		// initialise new changed values storage container for this contract
   182  		// if not present.
   183  		if l.storage[contract.Address()] == nil {
   184  			l.storage[contract.Address()] = make(Storage)
   185  		}
   186  		// capture SLOAD opcodes and record the read entry in the local storage
   187  		if op == vm.SLOAD && stackLen >= 1 {
   188  			var (
   189  				address = common.Hash(stackData[stackLen-1].Bytes32())
   190  				value   uint256.Int
   191  			)
   192  			l.env.IntraBlockState().GetState(contract.Address(), &address, &value)
   193  			l.storage[contract.Address()][address] = value.Bytes32()
   194  			storage = l.storage[contract.Address()].Copy()
   195  		} else if op == vm.SSTORE && stackLen >= 2 {
   196  			// capture SSTORE opcodes and record the written entry in the local storage.
   197  			var (
   198  				value   = common.Hash(stackData[stackLen-2].Bytes32())
   199  				address = common.Hash(stackData[stackLen-1].Bytes32())
   200  			)
   201  			l.storage[contract.Address()][address] = value
   202  			storage = l.storage[contract.Address()].Copy()
   203  		}
   204  	}
   205  	var rdata []byte
   206  	if l.cfg.EnableReturnData {
   207  		rdata = make([]byte, len(rData))
   208  		copy(rdata, rData)
   209  	}
   210  	// create a new snapshot of the EVM.
   211  	log := StructLog{pc, op, gas, cost, mem, memory.Len(), stck, rdata, storage, depth, l.env.IntraBlockState().GetRefund(), err}
   212  	l.logs = append(l.logs, log)
   213  }
   214  
   215  // CaptureFault implements the EVMLogger interface to trace an execution fault
   216  // while running an opcode.
   217  func (l *StructLogger) CaptureFault(pc uint64, op vm.OpCode, gas, cost uint64, scope *vm.ScopeContext, depth int, err error) {
   218  }
   219  
   220  // CaptureEnd is called after the call finishes to finalize the tracing.
   221  func (l *StructLogger) CaptureEnd(output []byte, gasUsed uint64, err error) {
   222  	l.output = output
   223  	l.err = err
   224  	if l.cfg.Debug {
   225  		fmt.Printf("%#x\n", output)
   226  		if err != nil {
   227  			fmt.Printf(" error: %v\n", err)
   228  		}
   229  	}
   230  }
   231  
   232  func (l *StructLogger) CaptureEnter(typ vm.OpCode, from common.Address, to common.Address, input []byte, gas uint64, value *uint256.Int) {
   233  }
   234  
   235  func (l *StructLogger) CaptureExit(output []byte, gasUsed uint64, err error) {
   236  }
   237  
   238  func (l *StructLogger) GetResult() (json.RawMessage, error) {
   239  	// Tracing aborted
   240  	if l.reason != nil {
   241  		return nil, l.reason
   242  	}
   243  	failed := l.err != nil
   244  	returnData := common.CopyBytes(l.output)
   245  	// Return data when successful and revert reason when reverted, otherwise empty.
   246  	returnVal := fmt.Sprintf("%x", returnData)
   247  	if failed && l.err != vm.ErrExecutionReverted {
   248  		returnVal = ""
   249  	}
   250  	return json.Marshal(&ExecutionResult{
   251  		Gas:         l.usedGas,
   252  		Failed:      failed,
   253  		ReturnValue: returnVal,
   254  		StructLogs:  formatLogs(l.StructLogs()),
   255  	})
   256  }
   257  
   258  // Stop terminates execution of the tracer at the first opportune moment.
   259  func (l *StructLogger) Stop(err error) {
   260  	l.reason = err
   261  	atomic.StoreUint32(&l.interrupt, 1)
   262  }
   263  
   264  func (l *StructLogger) CaptureTxStart(gasLimit uint64) {
   265  	l.gasLimit = gasLimit
   266  }
   267  
   268  func (l *StructLogger) CaptureTxEnd(restGas uint64) {
   269  	l.usedGas = l.gasLimit - restGas
   270  }
   271  
   272  // StructLogs returns the captured log entries.
   273  func (l *StructLogger) StructLogs() []StructLog { return l.logs }
   274  
   275  // Error returns the VM error captured by the trace.
   276  func (l *StructLogger) Error() error { return l.err }
   277  
   278  // Output returns the VM return value captured by the trace.
   279  func (l *StructLogger) Output() []byte { return l.output }
   280  
   281  // WriteTrace writes a formatted trace to the given writer
   282  func WriteTrace(writer io.Writer, logs []StructLog) {
   283  	for _, log := range logs {
   284  		fmt.Fprintf(writer, "%-16spc=%08d gas=%v cost=%v", log.Op, log.Pc, log.Gas, log.GasCost)
   285  		if log.Err != nil {
   286  			fmt.Fprintf(writer, " ERROR: %v", log.Err)
   287  		}
   288  		fmt.Fprintln(writer)
   289  
   290  		if len(log.Stack) > 0 {
   291  			fmt.Fprintln(writer, "Stack:")
   292  			for i := len(log.Stack) - 1; i >= 0; i-- {
   293  				fmt.Fprintf(writer, "%08d  %s\n", len(log.Stack)-i-1, log.Stack[i].Hex())
   294  			}
   295  		}
   296  		if len(log.Memory) > 0 {
   297  			fmt.Fprintln(writer, "Memory:")
   298  			fmt.Fprint(writer, hex.Dump(log.Memory))
   299  		}
   300  		if len(log.Storage) > 0 {
   301  			fmt.Fprintln(writer, "Storage:")
   302  			for h, item := range log.Storage {
   303  				fmt.Fprintf(writer, "%x: %x\n", h, item)
   304  			}
   305  		}
   306  		if len(log.ReturnData) > 0 {
   307  			fmt.Fprintln(writer, "ReturnData:")
   308  			fmt.Fprint(writer, hex.Dump(log.ReturnData))
   309  		}
   310  		fmt.Fprintln(writer)
   311  	}
   312  }
   313  
   314  // WriteLogs writes vm logs in a readable format to the given writer
   315  func WriteLogs(writer io.Writer, logs []*types.Log) {
   316  	for _, log := range logs {
   317  		fmt.Fprintf(writer, "LOG%d: %x bn=%d txi=%x\n", len(log.Topics), log.Address, log.BlockNumber, log.TxIndex)
   318  
   319  		for i, topic := range log.Topics {
   320  			fmt.Fprintf(writer, "%08d  %x\n", i, topic)
   321  		}
   322  
   323  		fmt.Fprint(writer, hex.Dump(log.Data))
   324  		fmt.Fprintln(writer)
   325  	}
   326  }
   327  
   328  type mdLogger struct {
   329  	out io.Writer
   330  	cfg *Config
   331  	env vm.VMInterface
   332  }
   333  
   334  // NewMarkdownLogger creates a logger which outputs information in a format adapted
   335  // for human readability, and is also a valid markdown table
   336  func NewMarkdownLogger(cfg *Config, writer io.Writer) *mdLogger {
   337  	l := &mdLogger{writer, cfg, nil}
   338  	if l.cfg == nil {
   339  		l.cfg = &Config{}
   340  	}
   341  	return l
   342  }
   343  
   344  func (t *mdLogger) CaptureTxStart(gasLimit uint64) {}
   345  
   346  func (t *mdLogger) CaptureTxEnd(restGas uint64) {}
   347  
   348  func (t *mdLogger) captureStartOrEnter(from, to common.Address, create bool, input []byte, gas uint64, value *uint256.Int) {
   349  	if !create {
   350  		fmt.Fprintf(t.out, "From: `%v`\nTo: `%v`\nData: `0x%x`\nGas: `%d`\nValue `%v` wei\n",
   351  			from.String(), to.String(),
   352  			input, gas, value)
   353  	} else {
   354  		fmt.Fprintf(t.out, "From: `%v`\nCreate at: `%v`\nData: `0x%x`\nGas: `%d`\nValue `%v` wei\n",
   355  			from.String(), to.String(),
   356  			input, gas, value)
   357  	}
   358  
   359  	fmt.Fprintf(t.out, `
   360  |  Pc   |      Op     | Cost |   Stack   |   RStack  |  Refund |
   361  |-------|-------------|------|-----------|-----------|---------|
   362  `)
   363  }
   364  
   365  func (t *mdLogger) CaptureStart(env vm.VMInterface, from common.Address, to common.Address, create bool, input []byte, gas uint64, value *uint256.Int) { //nolint:interfacer
   366  	t.env = env
   367  	t.captureStartOrEnter(from, to, create, input, gas, value)
   368  }
   369  
   370  func (t *mdLogger) CaptureEnter(typ vm.OpCode, from common.Address, to common.Address, input []byte, gas uint64, value *uint256.Int) { //nolint:interfacer
   371  	t.captureStartOrEnter(from, to, false, input, gas, value)
   372  }
   373  
   374  func (t *mdLogger) CaptureState(pc uint64, op vm.OpCode, gas, cost uint64, scope *vm.ScopeContext, rData []byte, depth int, err error) {
   375  	stack := scope.Stack
   376  
   377  	fmt.Fprintf(t.out, "| %4d  | %10v  |  %3d |", pc, op, cost)
   378  
   379  	if !t.cfg.DisableStack {
   380  		// format stack
   381  		var a []string
   382  		for _, elem := range stack.Data {
   383  			a = append(a, fmt.Sprintf("%v", elem.String()))
   384  		}
   385  		b := fmt.Sprintf("[%v]", strings.Join(a, ","))
   386  		fmt.Fprintf(t.out, "%10v |", b)
   387  	}
   388  	fmt.Fprintf(t.out, "%10v |", t.env.IntraBlockState().GetRefund())
   389  	fmt.Fprintln(t.out, "")
   390  	if err != nil {
   391  		fmt.Fprintf(t.out, "Error: %v\n", err)
   392  	}
   393  }
   394  
   395  func (t *mdLogger) CaptureFault(pc uint64, op vm.OpCode, gas, cost uint64, scope *vm.ScopeContext, depth int, err error) {
   396  	fmt.Fprintf(t.out, "\nError: at pc=%d, op=%v: %v\n", pc, op, err)
   397  }
   398  
   399  func (t *mdLogger) captureEndOrExit(output []byte, usedGas uint64, err error) {
   400  	fmt.Fprintf(t.out, "\nOutput: `0x%x`\nConsumed gas: `%d`\nError: `%v`\n",
   401  		output, usedGas, err)
   402  }
   403  
   404  func (t *mdLogger) CaptureEnd(output []byte, usedGas uint64, err error) {
   405  	t.captureEndOrExit(output, usedGas, err)
   406  }
   407  
   408  func (t *mdLogger) CaptureExit(output []byte, usedGas uint64, err error) {
   409  	t.captureEndOrExit(output, usedGas, err)
   410  }
   411  
   412  // ExecutionResult groups all structured logs emitted by the EVM
   413  // while replaying a transaction in debug mode as well as transaction
   414  // execution status, the amount of gas used and the return value
   415  type ExecutionResult struct {
   416  	Gas         uint64         `json:"gas"`
   417  	Failed      bool           `json:"failed"`
   418  	ReturnValue string         `json:"returnValue"`
   419  	StructLogs  []StructLogRes `json:"structLogs"`
   420  }
   421  
   422  // StructLogRes stores a structured log emitted by the EVM while replaying a
   423  // transaction in debug mode
   424  type StructLogRes struct {
   425  	Pc            uint64             `json:"pc"`
   426  	Op            string             `json:"op"`
   427  	Gas           uint64             `json:"gas"`
   428  	GasCost       uint64             `json:"gasCost"`
   429  	Depth         int                `json:"depth"`
   430  	Error         string             `json:"error,omitempty"`
   431  	Stack         *[]string          `json:"stack,omitempty"`
   432  	Memory        *[]string          `json:"memory,omitempty"`
   433  	Storage       *map[string]string `json:"storage,omitempty"`
   434  	RefundCounter uint64             `json:"refund,omitempty"`
   435  }
   436  
   437  // formatLogs formats EVM returned structured logs for json output
   438  func formatLogs(logs []StructLog) []StructLogRes {
   439  	formatted := make([]StructLogRes, len(logs))
   440  	for index, trace := range logs {
   441  		formatted[index] = StructLogRes{
   442  			Pc:            trace.Pc,
   443  			Op:            trace.Op.String(),
   444  			Gas:           trace.Gas,
   445  			GasCost:       trace.GasCost,
   446  			Depth:         trace.Depth,
   447  			Error:         trace.ErrorString(),
   448  			RefundCounter: trace.RefundCounter,
   449  		}
   450  		if trace.Stack != nil {
   451  			stack := make([]string, len(trace.Stack))
   452  			for i, stackValue := range trace.Stack {
   453  				stack[i] = stackValue.Hex()
   454  			}
   455  			formatted[index].Stack = &stack
   456  		}
   457  		if trace.Memory != nil {
   458  			memory := make([]string, 0, (len(trace.Memory)+31)/32)
   459  			for i := 0; i+32 <= len(trace.Memory); i += 32 {
   460  				memory = append(memory, fmt.Sprintf("%x", trace.Memory[i:i+32]))
   461  			}
   462  			formatted[index].Memory = &memory
   463  		}
   464  		if trace.Storage != nil {
   465  			storage := make(map[string]string)
   466  			for i, storageValue := range trace.Storage {
   467  				storage[fmt.Sprintf("%x", i)] = fmt.Sprintf("%x", storageValue)
   468  			}
   469  			formatted[index].Storage = &storage
   470  		}
   471  	}
   472  	return formatted
   473  }