logger.go 11 KB

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