github.com/calmw/ethereum@v0.1.1/eth/tracers/native/call.go (about)

     1  // Copyright 2021 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 native
    18  
    19  import (
    20  	"encoding/json"
    21  	"errors"
    22  	"math/big"
    23  	"sync/atomic"
    24  
    25  	"github.com/calmw/ethereum/accounts/abi"
    26  	"github.com/calmw/ethereum/common"
    27  	"github.com/calmw/ethereum/common/hexutil"
    28  	"github.com/calmw/ethereum/core/vm"
    29  	"github.com/calmw/ethereum/eth/tracers"
    30  )
    31  
    32  //go:generate go run github.com/fjl/gencodec -type callFrame -field-override callFrameMarshaling -out gen_callframe_json.go
    33  
    34  func init() {
    35  	tracers.DefaultDirectory.Register("callTracer", newCallTracer, false)
    36  }
    37  
    38  type callLog struct {
    39  	Address common.Address `json:"address"`
    40  	Topics  []common.Hash  `json:"topics"`
    41  	Data    hexutil.Bytes  `json:"data"`
    42  }
    43  
    44  type callFrame struct {
    45  	Type         vm.OpCode       `json:"-"`
    46  	From         common.Address  `json:"from"`
    47  	Gas          uint64          `json:"gas"`
    48  	GasUsed      uint64          `json:"gasUsed"`
    49  	To           *common.Address `json:"to,omitempty" rlp:"optional"`
    50  	Input        []byte          `json:"input" rlp:"optional"`
    51  	Output       []byte          `json:"output,omitempty" rlp:"optional"`
    52  	Error        string          `json:"error,omitempty" rlp:"optional"`
    53  	RevertReason string          `json:"revertReason,omitempty"`
    54  	Calls        []callFrame     `json:"calls,omitempty" rlp:"optional"`
    55  	Logs         []callLog       `json:"logs,omitempty" rlp:"optional"`
    56  	// Placed at end on purpose. The RLP will be decoded to 0 instead of
    57  	// nil if there are non-empty elements after in the struct.
    58  	Value *big.Int `json:"value,omitempty" rlp:"optional"`
    59  }
    60  
    61  func (f callFrame) TypeString() string {
    62  	return f.Type.String()
    63  }
    64  
    65  func (f callFrame) failed() bool {
    66  	return len(f.Error) > 0
    67  }
    68  
    69  func (f *callFrame) processOutput(output []byte, err error) {
    70  	output = common.CopyBytes(output)
    71  	if err == nil {
    72  		f.Output = output
    73  		return
    74  	}
    75  	f.Error = err.Error()
    76  	if f.Type == vm.CREATE || f.Type == vm.CREATE2 {
    77  		f.To = nil
    78  	}
    79  	if !errors.Is(err, vm.ErrExecutionReverted) || len(output) == 0 {
    80  		return
    81  	}
    82  	f.Output = output
    83  	if len(output) < 4 {
    84  		return
    85  	}
    86  	if unpacked, err := abi.UnpackRevert(output); err == nil {
    87  		f.RevertReason = unpacked
    88  	}
    89  }
    90  
    91  type callFrameMarshaling struct {
    92  	TypeString string `json:"type"`
    93  	Gas        hexutil.Uint64
    94  	GasUsed    hexutil.Uint64
    95  	Value      *hexutil.Big
    96  	Input      hexutil.Bytes
    97  	Output     hexutil.Bytes
    98  }
    99  
   100  type callTracer struct {
   101  	noopTracer
   102  	callstack []callFrame
   103  	config    callTracerConfig
   104  	gasLimit  uint64
   105  	interrupt atomic.Bool // Atomic flag to signal execution interruption
   106  	reason    error       // Textual reason for the interruption
   107  }
   108  
   109  type callTracerConfig struct {
   110  	OnlyTopCall bool `json:"onlyTopCall"` // If true, call tracer won't collect any subcalls
   111  	WithLog     bool `json:"withLog"`     // If true, call tracer will collect event logs
   112  }
   113  
   114  // newCallTracer returns a native go tracer which tracks
   115  // call frames of a tx, and implements vm.EVMLogger.
   116  func newCallTracer(ctx *tracers.Context, cfg json.RawMessage) (tracers.Tracer, error) {
   117  	var config callTracerConfig
   118  	if cfg != nil {
   119  		if err := json.Unmarshal(cfg, &config); err != nil {
   120  			return nil, err
   121  		}
   122  	}
   123  	// First callframe contains tx context info
   124  	// and is populated on start and end.
   125  	return &callTracer{callstack: make([]callFrame, 1), config: config}, nil
   126  }
   127  
   128  // CaptureStart implements the EVMLogger interface to initialize the tracing operation.
   129  func (t *callTracer) CaptureStart(env *vm.EVM, from common.Address, to common.Address, create bool, input []byte, gas uint64, value *big.Int) {
   130  	toCopy := to
   131  	t.callstack[0] = callFrame{
   132  		Type:  vm.CALL,
   133  		From:  from,
   134  		To:    &toCopy,
   135  		Input: common.CopyBytes(input),
   136  		Gas:   t.gasLimit,
   137  		Value: value,
   138  	}
   139  	if create {
   140  		t.callstack[0].Type = vm.CREATE
   141  	}
   142  }
   143  
   144  // CaptureEnd is called after the call finishes to finalize the tracing.
   145  func (t *callTracer) CaptureEnd(output []byte, gasUsed uint64, err error) {
   146  	t.callstack[0].processOutput(output, err)
   147  }
   148  
   149  // CaptureState implements the EVMLogger interface to trace a single step of VM execution.
   150  func (t *callTracer) CaptureState(pc uint64, op vm.OpCode, gas, cost uint64, scope *vm.ScopeContext, rData []byte, depth int, err error) {
   151  	// skip if the previous op caused an error
   152  	if err != nil {
   153  		return
   154  	}
   155  	// Only logs need to be captured via opcode processing
   156  	if !t.config.WithLog {
   157  		return
   158  	}
   159  	// Avoid processing nested calls when only caring about top call
   160  	if t.config.OnlyTopCall && depth > 0 {
   161  		return
   162  	}
   163  	// Skip if tracing was interrupted
   164  	if t.interrupt.Load() {
   165  		return
   166  	}
   167  	switch op {
   168  	case vm.LOG0, vm.LOG1, vm.LOG2, vm.LOG3, vm.LOG4:
   169  		size := int(op - vm.LOG0)
   170  
   171  		stack := scope.Stack
   172  		stackData := stack.Data()
   173  
   174  		// Don't modify the stack
   175  		mStart := stackData[len(stackData)-1]
   176  		mSize := stackData[len(stackData)-2]
   177  		topics := make([]common.Hash, size)
   178  		for i := 0; i < size; i++ {
   179  			topic := stackData[len(stackData)-2-(i+1)]
   180  			topics[i] = common.Hash(topic.Bytes32())
   181  		}
   182  
   183  		data, err := tracers.GetMemoryCopyPadded(scope.Memory, int64(mStart.Uint64()), int64(mSize.Uint64()))
   184  		if err != nil {
   185  			// mSize was unrealistically large
   186  			return
   187  		}
   188  
   189  		log := callLog{Address: scope.Contract.Address(), Topics: topics, Data: hexutil.Bytes(data)}
   190  		t.callstack[len(t.callstack)-1].Logs = append(t.callstack[len(t.callstack)-1].Logs, log)
   191  	}
   192  }
   193  
   194  // CaptureEnter is called when EVM enters a new scope (via call, create or selfdestruct).
   195  func (t *callTracer) CaptureEnter(typ vm.OpCode, from common.Address, to common.Address, input []byte, gas uint64, value *big.Int) {
   196  	if t.config.OnlyTopCall {
   197  		return
   198  	}
   199  	// Skip if tracing was interrupted
   200  	if t.interrupt.Load() {
   201  		return
   202  	}
   203  
   204  	toCopy := to
   205  	call := callFrame{
   206  		Type:  typ,
   207  		From:  from,
   208  		To:    &toCopy,
   209  		Input: common.CopyBytes(input),
   210  		Gas:   gas,
   211  		Value: value,
   212  	}
   213  	t.callstack = append(t.callstack, call)
   214  }
   215  
   216  // CaptureExit is called when EVM exits a scope, even if the scope didn't
   217  // execute any code.
   218  func (t *callTracer) CaptureExit(output []byte, gasUsed uint64, err error) {
   219  	if t.config.OnlyTopCall {
   220  		return
   221  	}
   222  	size := len(t.callstack)
   223  	if size <= 1 {
   224  		return
   225  	}
   226  	// pop call
   227  	call := t.callstack[size-1]
   228  	t.callstack = t.callstack[:size-1]
   229  	size -= 1
   230  
   231  	call.GasUsed = gasUsed
   232  	call.processOutput(output, err)
   233  	t.callstack[size-1].Calls = append(t.callstack[size-1].Calls, call)
   234  }
   235  
   236  func (t *callTracer) CaptureTxStart(gasLimit uint64) {
   237  	t.gasLimit = gasLimit
   238  }
   239  
   240  func (t *callTracer) CaptureTxEnd(restGas uint64) {
   241  	t.callstack[0].GasUsed = t.gasLimit - restGas
   242  	if t.config.WithLog {
   243  		// Logs are not emitted when the call fails
   244  		clearFailedLogs(&t.callstack[0], false)
   245  	}
   246  }
   247  
   248  // GetResult returns the json-encoded nested list of call traces, and any
   249  // error arising from the encoding or forceful termination (via `Stop`).
   250  func (t *callTracer) GetResult() (json.RawMessage, error) {
   251  	if len(t.callstack) != 1 {
   252  		return nil, errors.New("incorrect number of top-level calls")
   253  	}
   254  
   255  	res, err := json.Marshal(t.callstack[0])
   256  	if err != nil {
   257  		return nil, err
   258  	}
   259  	return json.RawMessage(res), t.reason
   260  }
   261  
   262  // Stop terminates execution of the tracer at the first opportune moment.
   263  func (t *callTracer) Stop(err error) {
   264  	t.reason = err
   265  	t.interrupt.Store(true)
   266  }
   267  
   268  // clearFailedLogs clears the logs of a callframe and all its children
   269  // in case of execution failure.
   270  func clearFailedLogs(cf *callFrame, parentFailed bool) {
   271  	failed := cf.failed() || parentFailed
   272  	// Clear own logs
   273  	if failed {
   274  		cf.Logs = nil
   275  	}
   276  	for i := range cf.Calls {
   277  		clearFailedLogs(&cf.Calls[i], failed)
   278  	}
   279  }