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