github.com/MikyChow/arbitrum-go-ethereum@v0.0.0-20230306102812-078da49636de/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  	"strconv"
    24  	"strings"
    25  	"sync/atomic"
    26  	"time"
    27  
    28  	"github.com/MikyChow/arbitrum-go-ethereum/common"
    29  	"github.com/MikyChow/arbitrum-go-ethereum/core/vm"
    30  	"github.com/MikyChow/arbitrum-go-ethereum/eth/tracers"
    31  )
    32  
    33  func init() {
    34  	register("callTracer", newCallTracer)
    35  }
    36  
    37  type callFrame struct {
    38  	// Arbitrum: we add these here due to the tracer returning the top frame
    39  	BeforeEVMTransfers *[]arbitrumTransfer `json:"beforeEVMTransfers,omitempty"`
    40  	AfterEVMTransfers  *[]arbitrumTransfer `json:"afterEVMTransfers,omitempty"`
    41  
    42  	Type    string      `json:"type"`
    43  	From    string      `json:"from"`
    44  	To      string      `json:"to,omitempty"`
    45  	Value   string      `json:"value,omitempty"`
    46  	Gas     string      `json:"gas"`
    47  	GasUsed string      `json:"gasUsed"`
    48  	Input   string      `json:"input"`
    49  	Output  string      `json:"output,omitempty"`
    50  	Error   string      `json:"error,omitempty"`
    51  	Calls   []callFrame `json:"calls,omitempty"`
    52  }
    53  
    54  type callTracer struct {
    55  	// Arbitrum: capture transfers occuring outside of evm execution
    56  	beforeEVMTransfers []arbitrumTransfer
    57  	afterEVMTransfers  []arbitrumTransfer
    58  
    59  	env       *vm.EVM
    60  	callstack []callFrame
    61  	config    callTracerConfig
    62  	interrupt uint32 // Atomic flag to signal execution interruption
    63  	reason    error  // Textual reason for the interruption
    64  }
    65  
    66  type callTracerConfig struct {
    67  	OnlyTopCall bool `json:"onlyTopCall"` // If true, call tracer won't collect any subcalls
    68  }
    69  
    70  // newCallTracer returns a native go tracer which tracks
    71  // call frames of a tx, and implements vm.EVMLogger.
    72  func newCallTracer(ctx *tracers.Context, cfg json.RawMessage) (tracers.Tracer, error) {
    73  	var config callTracerConfig
    74  	if cfg != nil {
    75  		if err := json.Unmarshal(cfg, &config); err != nil {
    76  			return nil, err
    77  		}
    78  	}
    79  	// First callframe contains tx context info
    80  	// and is populated on start and end.
    81  	return &callTracer{
    82  		callstack:          make([]callFrame, 1),
    83  		beforeEVMTransfers: []arbitrumTransfer{},
    84  		afterEVMTransfers:  []arbitrumTransfer{},
    85  	}, nil
    86  }
    87  
    88  // CaptureStart implements the EVMLogger interface to initialize the tracing operation.
    89  func (t *callTracer) CaptureStart(env *vm.EVM, from common.Address, to common.Address, create bool, input []byte, gas uint64, value *big.Int) {
    90  	t.env = env
    91  	t.callstack[0] = callFrame{
    92  		Type:  "CALL",
    93  		From:  addrToHex(from),
    94  		To:    addrToHex(to),
    95  		Input: bytesToHex(input),
    96  		Gas:   uintToHex(gas),
    97  		Value: bigToHex(value),
    98  	}
    99  	if create {
   100  		t.callstack[0].Type = "CREATE"
   101  	}
   102  }
   103  
   104  // CaptureEnd is called after the call finishes to finalize the tracing.
   105  func (t *callTracer) CaptureEnd(output []byte, gasUsed uint64, _ time.Duration, err error) {
   106  	t.callstack[0].GasUsed = uintToHex(gasUsed)
   107  	if err != nil {
   108  		t.callstack[0].Error = err.Error()
   109  		if err.Error() == "execution reverted" && len(output) > 0 {
   110  			t.callstack[0].Output = bytesToHex(output)
   111  		}
   112  	} else {
   113  		t.callstack[0].Output = bytesToHex(output)
   114  	}
   115  }
   116  
   117  // CaptureState implements the EVMLogger interface to trace a single step of VM execution.
   118  func (t *callTracer) CaptureState(pc uint64, op vm.OpCode, gas, cost uint64, scope *vm.ScopeContext, rData []byte, depth int, err error) {
   119  }
   120  
   121  // CaptureFault implements the EVMLogger interface to trace an execution fault.
   122  func (t *callTracer) CaptureFault(pc uint64, op vm.OpCode, gas, cost uint64, _ *vm.ScopeContext, depth int, err error) {
   123  }
   124  
   125  // CaptureEnter is called when EVM enters a new scope (via call, create or selfdestruct).
   126  func (t *callTracer) CaptureEnter(typ vm.OpCode, from common.Address, to common.Address, input []byte, gas uint64, value *big.Int) {
   127  	if t.config.OnlyTopCall {
   128  		return
   129  	}
   130  	// Skip if tracing was interrupted
   131  	if atomic.LoadUint32(&t.interrupt) > 0 {
   132  		t.env.Cancel()
   133  		return
   134  	}
   135  
   136  	call := callFrame{
   137  		Type:  typ.String(),
   138  		From:  addrToHex(from),
   139  		To:    addrToHex(to),
   140  		Input: bytesToHex(input),
   141  		Gas:   uintToHex(gas),
   142  		Value: bigToHex(value),
   143  	}
   144  	t.callstack = append(t.callstack, call)
   145  }
   146  
   147  // CaptureExit is called when EVM exits a scope, even if the scope didn't
   148  // execute any code.
   149  func (t *callTracer) CaptureExit(output []byte, gasUsed uint64, err error) {
   150  	if t.config.OnlyTopCall {
   151  		return
   152  	}
   153  	size := len(t.callstack)
   154  	if size <= 1 {
   155  		return
   156  	}
   157  	// pop call
   158  	call := t.callstack[size-1]
   159  	t.callstack = t.callstack[:size-1]
   160  	size -= 1
   161  
   162  	call.GasUsed = uintToHex(gasUsed)
   163  	if err == nil {
   164  		call.Output = bytesToHex(output)
   165  	} else {
   166  		call.Error = err.Error()
   167  		if call.Type == "CREATE" || call.Type == "CREATE2" {
   168  			call.To = ""
   169  		}
   170  	}
   171  	t.callstack[size-1].Calls = append(t.callstack[size-1].Calls, call)
   172  }
   173  
   174  func (*callTracer) CaptureTxStart(gasLimit uint64) {}
   175  
   176  func (*callTracer) CaptureTxEnd(restGas uint64) {}
   177  
   178  // GetResult returns the json-encoded nested list of call traces, and any
   179  // error arising from the encoding or forceful termination (via `Stop`).
   180  func (t *callTracer) GetResult() (json.RawMessage, error) {
   181  	if len(t.callstack) != 1 {
   182  		return nil, errors.New("incorrect number of top-level calls")
   183  	}
   184  
   185  	// Arbitrum: populate the top-level call with additional info
   186  	call := t.callstack[0]
   187  	call.BeforeEVMTransfers = &t.beforeEVMTransfers
   188  	call.AfterEVMTransfers = &t.afterEVMTransfers
   189  
   190  	res, err := json.Marshal(call)
   191  	if err != nil {
   192  		return nil, err
   193  	}
   194  	return json.RawMessage(res), t.reason
   195  }
   196  
   197  // Stop terminates execution of the tracer at the first opportune moment.
   198  func (t *callTracer) Stop(err error) {
   199  	t.reason = err
   200  	atomic.StoreUint32(&t.interrupt, 1)
   201  }
   202  
   203  func bytesToHex(s []byte) string {
   204  	return "0x" + common.Bytes2Hex(s)
   205  }
   206  
   207  func bigToHex(n *big.Int) string {
   208  	if n == nil {
   209  		return ""
   210  	}
   211  	return "0x" + n.Text(16)
   212  }
   213  
   214  func uintToHex(n uint64) string {
   215  	return "0x" + strconv.FormatUint(n, 16)
   216  }
   217  
   218  func addrToHex(a common.Address) string {
   219  	return strings.ToLower(a.Hex())
   220  }