json_logger.go 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. // Copyright 2017 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 main
  17. import (
  18. "encoding/json"
  19. "io"
  20. "time"
  21. "github.com/ethereum/go-ethereum/common"
  22. "github.com/ethereum/go-ethereum/common/math"
  23. "github.com/ethereum/go-ethereum/core/vm"
  24. )
  25. type JSONLogger struct {
  26. encoder *json.Encoder
  27. cfg *vm.LogConfig
  28. }
  29. func NewJSONLogger(cfg *vm.LogConfig, writer io.Writer) *JSONLogger {
  30. return &JSONLogger{json.NewEncoder(writer), cfg}
  31. }
  32. // CaptureState outputs state information on the logger.
  33. func (l *JSONLogger) CaptureState(env *vm.EVM, pc uint64, op vm.OpCode, gas, cost uint64, memory *vm.Memory, stack *vm.Stack, contract *vm.Contract, depth int, err error) error {
  34. log := vm.StructLog{
  35. Pc: pc,
  36. Op: op,
  37. Gas: gas + cost,
  38. GasCost: cost,
  39. MemorySize: memory.Len(),
  40. Storage: nil,
  41. Depth: depth,
  42. Err: err,
  43. }
  44. if !l.cfg.DisableMemory {
  45. log.Memory = memory.Data()
  46. }
  47. if !l.cfg.DisableStack {
  48. log.Stack = stack.Data()
  49. }
  50. return l.encoder.Encode(log)
  51. }
  52. // CaptureEnd is triggered at end of execution.
  53. func (l *JSONLogger) CaptureEnd(output []byte, gasUsed uint64, t time.Duration) error {
  54. type endLog struct {
  55. Output string `json:"output"`
  56. GasUsed math.HexOrDecimal64 `json:"gasUsed"`
  57. Time time.Duration `json:"time"`
  58. }
  59. return l.encoder.Encode(endLog{common.Bytes2Hex(output), math.HexOrDecimal64(gasUsed), t})
  60. }