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