github.com/waltonchain/waltonchain_gwtc_src@v1.1.4-0.20201225072101-8a298c95a819/cmd/evm/json_logger.go (about)

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