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