logger.go 12 KB

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