logger.go 15 KB

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