logger.go 12 KB

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