1// Copyright 2015 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 logger
18
19import (
20	"encoding/hex"
21	"fmt"
22	"io"
23	"math/big"
24	"strings"
25	"time"
26
27	"github.com/ethereum/go-ethereum/common"
28	"github.com/ethereum/go-ethereum/common/hexutil"
29	"github.com/ethereum/go-ethereum/common/math"
30	"github.com/ethereum/go-ethereum/core/types"
31	"github.com/ethereum/go-ethereum/core/vm"
32	"github.com/ethereum/go-ethereum/params"
33	"github.com/holiman/uint256"
34)
35
36// Storage represents a contract's storage.
37type Storage map[common.Hash]common.Hash
38
39// Copy duplicates the current storage.
40func (s Storage) Copy() Storage {
41	cpy := make(Storage)
42	for key, value := range s {
43		cpy[key] = value
44	}
45	return cpy
46}
47
48// Config are the configuration options for structured logger the EVM
49type Config struct {
50	EnableMemory     bool // enable memory capture
51	DisableStack     bool // disable stack capture
52	DisableStorage   bool // disable storage capture
53	EnableReturnData bool // enable return data capture
54	Debug            bool // print output during capture end
55	Limit            int  // maximum length of output, but zero means unlimited
56	// Chain overrides, can be used to execute a trace using future fork rules
57	Overrides *params.ChainConfig `json:"overrides,omitempty"`
58}
59
60//go:generate gencodec -type StructLog -field-override structLogMarshaling -out gen_structlog.go
61
62// StructLog is emitted to the EVM each cycle and lists information about the current internal state
63// prior to the execution of the statement.
64type StructLog struct {
65	Pc            uint64                      `json:"pc"`
66	Op            vm.OpCode                   `json:"op"`
67	Gas           uint64                      `json:"gas"`
68	GasCost       uint64                      `json:"gasCost"`
69	Memory        []byte                      `json:"memory"`
70	MemorySize    int                         `json:"memSize"`
71	Stack         []uint256.Int               `json:"stack"`
72	ReturnData    []byte                      `json:"returnData"`
73	Storage       map[common.Hash]common.Hash `json:"-"`
74	Depth         int                         `json:"depth"`
75	RefundCounter uint64                      `json:"refund"`
76	Err           error                       `json:"-"`
77}
78
79// overrides for gencodec
80type structLogMarshaling struct {
81	Gas         math.HexOrDecimal64
82	GasCost     math.HexOrDecimal64
83	Memory      hexutil.Bytes
84	ReturnData  hexutil.Bytes
85	OpName      string `json:"opName"` // adds call to OpName() in MarshalJSON
86	ErrorString string `json:"error"`  // adds call to ErrorString() in MarshalJSON
87}
88
89// OpName formats the operand name in a human-readable format.
90func (s *StructLog) OpName() string {
91	return s.Op.String()
92}
93
94// ErrorString formats the log's error as a string.
95func (s *StructLog) ErrorString() string {
96	if s.Err != nil {
97		return s.Err.Error()
98	}
99	return ""
100}
101
102// StructLogger is an EVM state logger and implements EVMLogger.
103//
104// StructLogger can capture state based on the given Log configuration and also keeps
105// a track record of modified storage which is used in reporting snapshots of the
106// contract their storage.
107type StructLogger struct {
108	cfg Config
109	env *vm.EVM
110
111	storage map[common.Address]Storage
112	logs    []StructLog
113	output  []byte
114	err     error
115}
116
117// NewStructLogger returns a new logger
118func NewStructLogger(cfg *Config) *StructLogger {
119	logger := &StructLogger{
120		storage: make(map[common.Address]Storage),
121	}
122	if cfg != nil {
123		logger.cfg = *cfg
124	}
125	return logger
126}
127
128// Reset clears the data held by the logger.
129func (l *StructLogger) Reset() {
130	l.storage = make(map[common.Address]Storage)
131	l.output = make([]byte, 0)
132	l.logs = l.logs[:0]
133	l.err = nil
134}
135
136// CaptureStart implements the EVMLogger interface to initialize the tracing operation.
137func (l *StructLogger) CaptureStart(env *vm.EVM, from common.Address, to common.Address, create bool, input []byte, gas uint64, value *big.Int) {
138	l.env = env
139}
140
141// CaptureState logs a new structured log message and pushes it out to the environment
142//
143// CaptureState also tracks SLOAD/SSTORE ops to track storage change.
144func (l *StructLogger) CaptureState(pc uint64, op vm.OpCode, gas, cost uint64, scope *vm.ScopeContext, rData []byte, depth int, err error) {
145	memory := scope.Memory
146	stack := scope.Stack
147	contract := scope.Contract
148	// check if already accumulated the specified number of logs
149	if l.cfg.Limit != 0 && l.cfg.Limit <= len(l.logs) {
150		return
151	}
152	// Copy a snapshot of the current memory state to a new buffer
153	var mem []byte
154	if l.cfg.EnableMemory {
155		mem = make([]byte, len(memory.Data()))
156		copy(mem, memory.Data())
157	}
158	// Copy a snapshot of the current stack state to a new buffer
159	var stck []uint256.Int
160	if !l.cfg.DisableStack {
161		stck = make([]uint256.Int, len(stack.Data()))
162		for i, item := range stack.Data() {
163			stck[i] = item
164		}
165	}
166	stackData := stack.Data()
167	stackLen := len(stackData)
168	// Copy a snapshot of the current storage to a new container
169	var storage Storage
170	if !l.cfg.DisableStorage && (op == vm.SLOAD || op == vm.SSTORE) {
171		// initialise new changed values storage container for this contract
172		// if not present.
173		if l.storage[contract.Address()] == nil {
174			l.storage[contract.Address()] = make(Storage)
175		}
176		// capture SLOAD opcodes and record the read entry in the local storage
177		if op == vm.SLOAD && stackLen >= 1 {
178			var (
179				address = common.Hash(stackData[stackLen-1].Bytes32())
180				value   = l.env.StateDB.GetState(contract.Address(), address)
181			)
182			l.storage[contract.Address()][address] = value
183			storage = l.storage[contract.Address()].Copy()
184		} else if op == vm.SSTORE && stackLen >= 2 {
185			// capture SSTORE opcodes and record the written entry in the local storage.
186			var (
187				value   = common.Hash(stackData[stackLen-2].Bytes32())
188				address = common.Hash(stackData[stackLen-1].Bytes32())
189			)
190			l.storage[contract.Address()][address] = value
191			storage = l.storage[contract.Address()].Copy()
192		}
193	}
194	var rdata []byte
195	if l.cfg.EnableReturnData {
196		rdata = make([]byte, len(rData))
197		copy(rdata, rData)
198	}
199	// create a new snapshot of the EVM.
200	log := StructLog{pc, op, gas, cost, mem, memory.Len(), stck, rdata, storage, depth, l.env.StateDB.GetRefund(), err}
201	l.logs = append(l.logs, log)
202}
203
204// CaptureFault implements the EVMLogger interface to trace an execution fault
205// while running an opcode.
206func (l *StructLogger) CaptureFault(pc uint64, op vm.OpCode, gas, cost uint64, scope *vm.ScopeContext, depth int, err error) {
207}
208
209// CaptureEnd is called after the call finishes to finalize the tracing.
210func (l *StructLogger) CaptureEnd(output []byte, gasUsed uint64, t time.Duration, err error) {
211	l.output = output
212	l.err = err
213	if l.cfg.Debug {
214		fmt.Printf("0x%x\n", output)
215		if err != nil {
216			fmt.Printf(" error: %v\n", err)
217		}
218	}
219}
220
221func (l *StructLogger) CaptureEnter(typ vm.OpCode, from common.Address, to common.Address, input []byte, gas uint64, value *big.Int) {
222}
223
224func (l *StructLogger) CaptureExit(output []byte, gasUsed uint64, err error) {}
225
226// StructLogs returns the captured log entries.
227func (l *StructLogger) StructLogs() []StructLog { return l.logs }
228
229// Error returns the VM error captured by the trace.
230func (l *StructLogger) Error() error { return l.err }
231
232// Output returns the VM return value captured by the trace.
233func (l *StructLogger) Output() []byte { return l.output }
234
235// WriteTrace writes a formatted trace to the given writer
236func WriteTrace(writer io.Writer, logs []StructLog) {
237	for _, log := range logs {
238		fmt.Fprintf(writer, "%-16spc=%08d gas=%v cost=%v", log.Op, log.Pc, log.Gas, log.GasCost)
239		if log.Err != nil {
240			fmt.Fprintf(writer, " ERROR: %v", log.Err)
241		}
242		fmt.Fprintln(writer)
243
244		if len(log.Stack) > 0 {
245			fmt.Fprintln(writer, "Stack:")
246			for i := len(log.Stack) - 1; i >= 0; i-- {
247				fmt.Fprintf(writer, "%08d  %s\n", len(log.Stack)-i-1, log.Stack[i].Hex())
248			}
249		}
250		if len(log.Memory) > 0 {
251			fmt.Fprintln(writer, "Memory:")
252			fmt.Fprint(writer, hex.Dump(log.Memory))
253		}
254		if len(log.Storage) > 0 {
255			fmt.Fprintln(writer, "Storage:")
256			for h, item := range log.Storage {
257				fmt.Fprintf(writer, "%x: %x\n", h, item)
258			}
259		}
260		if len(log.ReturnData) > 0 {
261			fmt.Fprintln(writer, "ReturnData:")
262			fmt.Fprint(writer, hex.Dump(log.ReturnData))
263		}
264		fmt.Fprintln(writer)
265	}
266}
267
268// WriteLogs writes vm logs in a readable format to the given writer
269func WriteLogs(writer io.Writer, logs []*types.Log) {
270	for _, log := range logs {
271		fmt.Fprintf(writer, "LOG%d: %x bn=%d txi=%x\n", len(log.Topics), log.Address, log.BlockNumber, log.TxIndex)
272
273		for i, topic := range log.Topics {
274			fmt.Fprintf(writer, "%08d  %x\n", i, topic)
275		}
276
277		fmt.Fprint(writer, hex.Dump(log.Data))
278		fmt.Fprintln(writer)
279	}
280}
281
282type mdLogger struct {
283	out io.Writer
284	cfg *Config
285	env *vm.EVM
286}
287
288// NewMarkdownLogger creates a logger which outputs information in a format adapted
289// for human readability, and is also a valid markdown table
290func NewMarkdownLogger(cfg *Config, writer io.Writer) *mdLogger {
291	l := &mdLogger{out: writer, cfg: cfg}
292	if l.cfg == nil {
293		l.cfg = &Config{}
294	}
295	return l
296}
297
298func (t *mdLogger) CaptureStart(env *vm.EVM, from common.Address, to common.Address, create bool, input []byte, gas uint64, value *big.Int) {
299	t.env = env
300	if !create {
301		fmt.Fprintf(t.out, "From: `%v`\nTo: `%v`\nData: `0x%x`\nGas: `%d`\nValue `%v` wei\n",
302			from.String(), to.String(),
303			input, gas, value)
304	} else {
305		fmt.Fprintf(t.out, "From: `%v`\nCreate at: `%v`\nData: `0x%x`\nGas: `%d`\nValue `%v` wei\n",
306			from.String(), to.String(),
307			input, gas, value)
308	}
309
310	fmt.Fprintf(t.out, `
311|  Pc   |      Op     | Cost |   Stack   |   RStack  |  Refund |
312|-------|-------------|------|-----------|-----------|---------|
313`)
314}
315
316// CaptureState also tracks SLOAD/SSTORE ops to track storage change.
317func (t *mdLogger) CaptureState(pc uint64, op vm.OpCode, gas, cost uint64, scope *vm.ScopeContext, rData []byte, depth int, err error) {
318	stack := scope.Stack
319	fmt.Fprintf(t.out, "| %4d  | %10v  |  %3d |", pc, op, cost)
320
321	if !t.cfg.DisableStack {
322		// format stack
323		var a []string
324		for _, elem := range stack.Data() {
325			a = append(a, elem.Hex())
326		}
327		b := fmt.Sprintf("[%v]", strings.Join(a, ","))
328		fmt.Fprintf(t.out, "%10v |", b)
329	}
330	fmt.Fprintf(t.out, "%10v |", t.env.StateDB.GetRefund())
331	fmt.Fprintln(t.out, "")
332	if err != nil {
333		fmt.Fprintf(t.out, "Error: %v\n", err)
334	}
335}
336
337func (t *mdLogger) CaptureFault(pc uint64, op vm.OpCode, gas, cost uint64, scope *vm.ScopeContext, depth int, err error) {
338	fmt.Fprintf(t.out, "\nError: at pc=%d, op=%v: %v\n", pc, op, err)
339}
340
341func (t *mdLogger) CaptureEnd(output []byte, gasUsed uint64, tm time.Duration, err error) {
342	fmt.Fprintf(t.out, "\nOutput: `0x%x`\nConsumed gas: `%d`\nError: `%v`\n",
343		output, gasUsed, err)
344}
345
346func (t *mdLogger) CaptureEnter(typ vm.OpCode, from common.Address, to common.Address, input []byte, gas uint64, value *big.Int) {
347}
348
349func (t *mdLogger) CaptureExit(output []byte, gasUsed uint64, err error) {}
350