logger.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361
  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/holiman/uint256"
  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. // 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. EnableMemory bool // enable memory capture
  44. DisableStack bool // disable stack capture
  45. DisableStorage bool // disable storage capture
  46. EnableReturnData bool // enable return data capture
  47. Debug bool // print output during capture end
  48. Limit int // maximum length of output, but zero means unlimited
  49. // Chain overrides, can be used to execute a trace using future fork rules
  50. Overrides *params.ChainConfig `json:"overrides,omitempty"`
  51. }
  52. //go:generate gencodec -type StructLog -field-override structLogMarshaling -out gen_structlog.go
  53. // StructLog is emitted to the EVM each cycle and lists information about the current internal state
  54. // prior to the execution of the statement.
  55. type StructLog struct {
  56. Pc uint64 `json:"pc"`
  57. Op OpCode `json:"op"`
  58. Gas uint64 `json:"gas"`
  59. GasCost uint64 `json:"gasCost"`
  60. Memory []byte `json:"memory"`
  61. MemorySize int `json:"memSize"`
  62. Stack []uint256.Int `json:"stack"`
  63. ReturnData []byte `json:"returnData"`
  64. Storage map[common.Hash]common.Hash `json:"-"`
  65. Depth int `json:"depth"`
  66. RefundCounter uint64 `json:"refund"`
  67. Err error `json:"-"`
  68. }
  69. // overrides for gencodec
  70. type structLogMarshaling struct {
  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. // EVMLogger 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 EVMLogger interface {
  95. CaptureStart(env *EVM, from common.Address, to common.Address, create bool, input []byte, gas uint64, value *big.Int)
  96. CaptureState(pc uint64, op OpCode, gas, cost uint64, scope *ScopeContext, rData []byte, depth int, err error)
  97. CaptureEnter(typ OpCode, from common.Address, to common.Address, input []byte, gas uint64, value *big.Int)
  98. CaptureExit(output []byte, gasUsed uint64, err error)
  99. CaptureFault(pc uint64, op OpCode, gas, cost uint64, scope *ScopeContext, depth int, err error)
  100. CaptureEnd(output []byte, gasUsed uint64, t time.Duration, err error)
  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.
  107. type StructLogger struct {
  108. cfg LogConfig
  109. env *EVM
  110. storage map[common.Address]Storage
  111. logs []StructLog
  112. output []byte
  113. err error
  114. }
  115. // NewStructLogger returns a new logger
  116. func NewStructLogger(cfg *LogConfig) *StructLogger {
  117. logger := &StructLogger{
  118. storage: make(map[common.Address]Storage),
  119. }
  120. if cfg != nil {
  121. logger.cfg = *cfg
  122. }
  123. return logger
  124. }
  125. // Reset clears the data held by the logger.
  126. func (l *StructLogger) Reset() {
  127. l.storage = make(map[common.Address]Storage)
  128. l.output = make([]byte, 0)
  129. l.logs = l.logs[:0]
  130. l.err = nil
  131. }
  132. // CaptureStart implements the EVMLogger interface to initialize the tracing operation.
  133. func (l *StructLogger) CaptureStart(env *EVM, from common.Address, to common.Address, create bool, input []byte, gas uint64, value *big.Int) {
  134. l.env = env
  135. }
  136. // CaptureState logs a new structured log message and pushes it out to the environment
  137. //
  138. // CaptureState also tracks SLOAD/SSTORE ops to track storage change.
  139. func (l *StructLogger) CaptureState(pc uint64, op OpCode, gas, cost uint64, scope *ScopeContext, rData []byte, depth int, err error) {
  140. memory := scope.Memory
  141. stack := scope.Stack
  142. contract := scope.Contract
  143. // check if already accumulated the specified number of logs
  144. if l.cfg.Limit != 0 && l.cfg.Limit <= len(l.logs) {
  145. return
  146. }
  147. // Copy a snapshot of the current memory state to a new buffer
  148. var mem []byte
  149. if l.cfg.EnableMemory {
  150. mem = make([]byte, len(memory.Data()))
  151. copy(mem, memory.Data())
  152. }
  153. // Copy a snapshot of the current stack state to a new buffer
  154. var stck []uint256.Int
  155. if !l.cfg.DisableStack {
  156. stck = make([]uint256.Int, len(stack.Data()))
  157. for i, item := range stack.Data() {
  158. stck[i] = item
  159. }
  160. }
  161. // Copy a snapshot of the current storage to a new container
  162. var storage Storage
  163. if !l.cfg.DisableStorage && (op == SLOAD || op == SSTORE) {
  164. // initialise new changed values storage container for this contract
  165. // if not present.
  166. if l.storage[contract.Address()] == nil {
  167. l.storage[contract.Address()] = make(Storage)
  168. }
  169. // capture SLOAD opcodes and record the read entry in the local storage
  170. if op == SLOAD && stack.len() >= 1 {
  171. var (
  172. address = common.Hash(stack.data[stack.len()-1].Bytes32())
  173. value = l.env.StateDB.GetState(contract.Address(), address)
  174. )
  175. l.storage[contract.Address()][address] = value
  176. storage = l.storage[contract.Address()].Copy()
  177. } else if op == SSTORE && stack.len() >= 2 {
  178. // capture SSTORE opcodes and record the written entry in the local storage.
  179. var (
  180. value = common.Hash(stack.data[stack.len()-2].Bytes32())
  181. address = common.Hash(stack.data[stack.len()-1].Bytes32())
  182. )
  183. l.storage[contract.Address()][address] = value
  184. storage = l.storage[contract.Address()].Copy()
  185. }
  186. }
  187. var rdata []byte
  188. if l.cfg.EnableReturnData {
  189. rdata = make([]byte, len(rData))
  190. copy(rdata, rData)
  191. }
  192. // create a new snapshot of the EVM.
  193. log := StructLog{pc, op, gas, cost, mem, memory.Len(), stck, rdata, storage, depth, l.env.StateDB.GetRefund(), err}
  194. l.logs = append(l.logs, log)
  195. }
  196. // CaptureFault implements the EVMLogger interface to trace an execution fault
  197. // while running an opcode.
  198. func (l *StructLogger) CaptureFault(pc uint64, op OpCode, gas, cost uint64, scope *ScopeContext, depth int, err error) {
  199. }
  200. // CaptureEnd is called after the call finishes to finalize the tracing.
  201. func (l *StructLogger) CaptureEnd(output []byte, gasUsed uint64, t time.Duration, err error) {
  202. l.output = output
  203. l.err = err
  204. if l.cfg.Debug {
  205. fmt.Printf("0x%x\n", output)
  206. if err != nil {
  207. fmt.Printf(" error: %v\n", err)
  208. }
  209. }
  210. }
  211. func (l *StructLogger) CaptureEnter(typ OpCode, from common.Address, to common.Address, input []byte, gas uint64, value *big.Int) {
  212. }
  213. func (l *StructLogger) CaptureExit(output []byte, gasUsed uint64, err error) {}
  214. // StructLogs returns the captured log entries.
  215. func (l *StructLogger) StructLogs() []StructLog { return l.logs }
  216. // Error returns the VM error captured by the trace.
  217. func (l *StructLogger) Error() error { return l.err }
  218. // Output returns the VM return value captured by the trace.
  219. func (l *StructLogger) Output() []byte { return l.output }
  220. // WriteTrace writes a formatted trace to the given writer
  221. func WriteTrace(writer io.Writer, logs []StructLog) {
  222. for _, log := range logs {
  223. fmt.Fprintf(writer, "%-16spc=%08d gas=%v cost=%v", log.Op, log.Pc, log.Gas, log.GasCost)
  224. if log.Err != nil {
  225. fmt.Fprintf(writer, " ERROR: %v", log.Err)
  226. }
  227. fmt.Fprintln(writer)
  228. if len(log.Stack) > 0 {
  229. fmt.Fprintln(writer, "Stack:")
  230. for i := len(log.Stack) - 1; i >= 0; i-- {
  231. fmt.Fprintf(writer, "%08d %s\n", len(log.Stack)-i-1, log.Stack[i].Hex())
  232. }
  233. }
  234. if len(log.Memory) > 0 {
  235. fmt.Fprintln(writer, "Memory:")
  236. fmt.Fprint(writer, hex.Dump(log.Memory))
  237. }
  238. if len(log.Storage) > 0 {
  239. fmt.Fprintln(writer, "Storage:")
  240. for h, item := range log.Storage {
  241. fmt.Fprintf(writer, "%x: %x\n", h, item)
  242. }
  243. }
  244. if len(log.ReturnData) > 0 {
  245. fmt.Fprintln(writer, "ReturnData:")
  246. fmt.Fprint(writer, hex.Dump(log.ReturnData))
  247. }
  248. fmt.Fprintln(writer)
  249. }
  250. }
  251. // WriteLogs writes vm logs in a readable format to the given writer
  252. func WriteLogs(writer io.Writer, logs []*types.Log) {
  253. for _, log := range logs {
  254. fmt.Fprintf(writer, "LOG%d: %x bn=%d txi=%x\n", len(log.Topics), log.Address, log.BlockNumber, log.TxIndex)
  255. for i, topic := range log.Topics {
  256. fmt.Fprintf(writer, "%08d %x\n", i, topic)
  257. }
  258. fmt.Fprint(writer, hex.Dump(log.Data))
  259. fmt.Fprintln(writer)
  260. }
  261. }
  262. type mdLogger struct {
  263. out io.Writer
  264. cfg *LogConfig
  265. env *EVM
  266. }
  267. // NewMarkdownLogger creates a logger which outputs information in a format adapted
  268. // for human readability, and is also a valid markdown table
  269. func NewMarkdownLogger(cfg *LogConfig, writer io.Writer) *mdLogger {
  270. l := &mdLogger{out: writer, cfg: cfg}
  271. if l.cfg == nil {
  272. l.cfg = &LogConfig{}
  273. }
  274. return l
  275. }
  276. func (t *mdLogger) CaptureStart(env *EVM, from common.Address, to common.Address, create bool, input []byte, gas uint64, value *big.Int) {
  277. t.env = env
  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. }
  292. // CaptureState also tracks SLOAD/SSTORE ops to track storage change.
  293. func (t *mdLogger) CaptureState(pc uint64, op OpCode, gas, cost uint64, scope *ScopeContext, rData []byte, depth int, err error) {
  294. stack := scope.Stack
  295. fmt.Fprintf(t.out, "| %4d | %10v | %3d |", pc, op, cost)
  296. if !t.cfg.DisableStack {
  297. // format stack
  298. var a []string
  299. for _, elem := range stack.data {
  300. a = append(a, elem.Hex())
  301. }
  302. b := fmt.Sprintf("[%v]", strings.Join(a, ","))
  303. fmt.Fprintf(t.out, "%10v |", b)
  304. }
  305. fmt.Fprintf(t.out, "%10v |", t.env.StateDB.GetRefund())
  306. fmt.Fprintln(t.out, "")
  307. if err != nil {
  308. fmt.Fprintf(t.out, "Error: %v\n", err)
  309. }
  310. }
  311. func (t *mdLogger) CaptureFault(pc uint64, op OpCode, gas, cost uint64, scope *ScopeContext, depth int, err error) {
  312. fmt.Fprintf(t.out, "\nError: at pc=%d, op=%v: %v\n", pc, op, err)
  313. }
  314. func (t *mdLogger) CaptureEnd(output []byte, gasUsed uint64, tm time.Duration, err error) {
  315. fmt.Fprintf(t.out, "\nOutput: `0x%x`\nConsumed gas: `%d`\nError: `%v`\n",
  316. output, gasUsed, err)
  317. }
  318. func (t *mdLogger) CaptureEnter(typ OpCode, from common.Address, to common.Address, input []byte, gas uint64, value *big.Int) {
  319. }
  320. func (t *mdLogger) CaptureExit(output []byte, gasUsed uint64, err error) {}