Skip to content

Commit 42a914a

Browse files
holimankaralabe
authored andcommitted
cmd/evm, core/vm, eth: implement api methods to do stdjson dump to local filesystem
1 parent 09d588e commit 42a914a

File tree

5 files changed

+148
-20
lines changed

5 files changed

+148
-20
lines changed

cmd/evm/runner.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -89,7 +89,7 @@ func runCmd(ctx *cli.Context) error {
8989
genesisConfig *core.Genesis
9090
)
9191
if ctx.GlobalBool(MachineFlag.Name) {
92-
tracer = NewJSONLogger(logconfig, os.Stdout)
92+
tracer = vm.NewJSONLogger(logconfig, os.Stdout)
9393
} else if ctx.GlobalBool(DebugFlag.Name) {
9494
debugLogger = vm.NewStructLogger(logconfig)
9595
tracer = debugLogger

cmd/evm/staterunner.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -68,7 +68,7 @@ func stateTestCmd(ctx *cli.Context) error {
6868
)
6969
switch {
7070
case ctx.GlobalBool(MachineFlag.Name):
71-
tracer = NewJSONLogger(config, os.Stderr)
71+
tracer = vm.NewJSONLogger(config, os.Stderr)
7272

7373
case ctx.GlobalBool(DebugFlag.Name):
7474
debugger = vm.NewStructLogger(config)

cmd/evm/json_logger.go renamed to core/vm/logger_json.go

Lines changed: 6 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@
1414
// You should have received a copy of the GNU General Public License
1515
// along with go-ethereum. If not, see <http://www.gnu.org/licenses/>.
1616

17-
package main
17+
package vm
1818

1919
import (
2020
"encoding/json"
@@ -24,17 +24,16 @@ import (
2424

2525
"github.com/ethereum/go-ethereum/common"
2626
"github.com/ethereum/go-ethereum/common/math"
27-
"github.com/ethereum/go-ethereum/core/vm"
2827
)
2928

3029
type JSONLogger struct {
3130
encoder *json.Encoder
32-
cfg *vm.LogConfig
31+
cfg *LogConfig
3332
}
3433

3534
// NewJSONLogger creates a new EVM tracer that prints execution steps as JSON objects
3635
// into the provided stream.
37-
func NewJSONLogger(cfg *vm.LogConfig, writer io.Writer) *JSONLogger {
36+
func NewJSONLogger(cfg *LogConfig, writer io.Writer) *JSONLogger {
3837
return &JSONLogger{json.NewEncoder(writer), cfg}
3938
}
4039

@@ -43,8 +42,8 @@ func (l *JSONLogger) CaptureStart(from common.Address, to common.Address, create
4342
}
4443

4544
// CaptureState outputs state information on the logger.
46-
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 {
47-
log := vm.StructLog{
45+
func (l *JSONLogger) CaptureState(env *EVM, pc uint64, op OpCode, gas, cost uint64, memory *Memory, stack *Stack, contract *Contract, depth int, err error) error {
46+
log := StructLog{
4847
Pc: pc,
4948
Op: op,
5049
Gas: gas,
@@ -65,7 +64,7 @@ func (l *JSONLogger) CaptureState(env *vm.EVM, pc uint64, op vm.OpCode, gas, cos
6564
}
6665

6766
// CaptureFault outputs state information on the logger.
68-
func (l *JSONLogger) CaptureFault(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 {
67+
func (l *JSONLogger) CaptureFault(env *EVM, pc uint64, op OpCode, gas, cost uint64, memory *Memory, stack *Stack, contract *Contract, depth int, err error) error {
6968
return nil
7069
}
7170

eth/api_tracer.go

Lines changed: 130 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -17,11 +17,13 @@
1717
package eth
1818

1919
import (
20+
"bufio"
2021
"bytes"
2122
"context"
2223
"errors"
2324
"fmt"
2425
"io/ioutil"
26+
"os"
2527
"runtime"
2628
"sync"
2729
"time"
@@ -60,6 +62,13 @@ type TraceConfig struct {
6062
Reexec *uint64
6163
}
6264

65+
// StdTraceConfig holds extra parameters to standard-json trace functions.
66+
type StdTraceConfig struct {
67+
*vm.LogConfig
68+
Reexec *uint64
69+
TxHash *common.Hash
70+
}
71+
6372
// txTraceResult is the result of a single transaction trace.
6473
type txTraceResult struct {
6574
Result interface{} `json:"result,omitempty"` // Trace results produced by the tracer
@@ -391,13 +400,37 @@ func (api *PrivateDebugAPI) TraceBlockFromFile(ctx context.Context, file string,
391400
return api.TraceBlock(ctx, blob, config)
392401
}
393402

394-
// TraceBadBlock returns the structured logs created during the execution of a block
395-
// within the blockchain 'badblocks' cache
396-
func (api *PrivateDebugAPI) TraceBadBlock(ctx context.Context, index int, config *TraceConfig) ([]*txTraceResult, error) {
397-
if blocks := api.eth.blockchain.BadBlocks(); index < len(blocks) {
398-
return api.traceBlock(ctx, blocks[index], config)
403+
// TraceBadBlockByHash returns the structured logs created during the execution of a block
404+
func (api *PrivateDebugAPI) TraceBadBlock(ctx context.Context, blockHash common.Hash, config *TraceConfig) ([]*txTraceResult, error) {
405+
blocks := api.eth.blockchain.BadBlocks()
406+
for _, block := range blocks {
407+
if block.Hash() == blockHash {
408+
return api.traceBlock(ctx, block, config)
409+
}
410+
}
411+
return nil, fmt.Errorf("hash not found among bad blocks")
412+
}
413+
414+
// StandardTraceBadBlockToFile dumps the standard-json logs to files on the local filesystem,
415+
// and returns a list of files to the caller.
416+
func (api *PrivateDebugAPI) StandardTraceBadBlockToFile(ctx context.Context, blockHash common.Hash, stdConfig *StdTraceConfig) ([]string, error) {
417+
blocks := api.eth.blockchain.BadBlocks()
418+
for _, block := range blocks {
419+
if block.Hash() == blockHash {
420+
return api.standardTraceBlockToFile(ctx, block, stdConfig)
421+
}
399422
}
400-
return nil, fmt.Errorf("index out of range")
423+
return nil, fmt.Errorf("hash not found among bad blocks")
424+
}
425+
426+
// StandardTraceBlockToFile dumps the standard-json logs to files on the local filesystem,
427+
// and returns a list of files to the caller.
428+
func (api *PrivateDebugAPI) StandardTraceBlockToFile(ctx context.Context, blockHash common.Hash, stdConfig *StdTraceConfig) ([]string, error) {
429+
block := api.eth.blockchain.GetBlockByHash(blockHash)
430+
if block == nil {
431+
return nil, fmt.Errorf("block #%x not found", blockHash)
432+
}
433+
return api.standardTraceBlockToFile(ctx, block, stdConfig)
401434
}
402435

403436
// traceBlock configures a new tracer according to the provided configuration, and
@@ -481,6 +514,92 @@ func (api *PrivateDebugAPI) traceBlock(ctx context.Context, block *types.Block,
481514
return results, nil
482515
}
483516

517+
// standardTraceBlockToFile configures a new tracer which uses standard-json output, and
518+
// traces either a full block or an individual transaction. The return value will be one filename
519+
// per transaction traced.
520+
func (api *PrivateDebugAPI) standardTraceBlockToFile(ctx context.Context, block *types.Block, stdConfig *StdTraceConfig) ([]string, error) {
521+
// Create the parent state database
522+
if err := api.eth.engine.VerifyHeader(api.eth.blockchain, block.Header(), true); err != nil {
523+
return nil, err
524+
}
525+
parent := api.eth.blockchain.GetBlock(block.ParentHash(), block.NumberU64()-1)
526+
if parent == nil {
527+
return nil, fmt.Errorf("parent %x not found", block.ParentHash())
528+
}
529+
var (
530+
signer = types.MakeSigner(api.config, block.Number())
531+
done = false
532+
blockPrefix = fmt.Sprintf("block_0x%x", block.Hash().Bytes()[:4])
533+
usedLogConfig = &vm.LogConfig{Debug: true}
534+
files []string
535+
reExec_val = defaultTraceReexec
536+
txHash *common.Hash
537+
)
538+
if stdConfig != nil {
539+
if stdConfig.Reexec != nil {
540+
reExec_val = *stdConfig.Reexec
541+
}
542+
if stdConfig.LogConfig != nil {
543+
usedLogConfig.DisableMemory = stdConfig.LogConfig.DisableMemory
544+
usedLogConfig.DisableStack = stdConfig.LogConfig.DisableStack
545+
usedLogConfig.DisableStorage = stdConfig.LogConfig.DisableStorage
546+
usedLogConfig.Limit = stdConfig.LogConfig.Limit
547+
}
548+
txHash = stdConfig.TxHash
549+
}
550+
statedb, err := api.computeStateDB(parent, reExec_val)
551+
if err != nil {
552+
return nil, err
553+
}
554+
555+
for i, tx := range block.Transactions() {
556+
var (
557+
outfile *os.File
558+
err error
559+
)
560+
msg, _ := tx.AsMessage(signer)
561+
vmctx := core.NewEVMContext(msg, block.Header(), api.eth.blockchain, nil)
562+
vmConf := vm.Config{}
563+
if txHash == nil || bytes.Equal(txHash.Bytes(), tx.Hash().Bytes()) {
564+
prefix := fmt.Sprintf("%v-%d-0x%x-", blockPrefix, i, tx.Hash().Bytes()[:4])
565+
// Open a file to dump trace into
566+
outfile, err = ioutil.TempFile(os.TempDir(), prefix)
567+
if err != nil {
568+
return nil, err
569+
}
570+
files = append(files, outfile.Name())
571+
vmConf = vm.Config{
572+
Debug: true,
573+
Tracer: vm.NewJSONLogger(usedLogConfig, bufio.NewWriter(outfile)),
574+
EnablePreimageRecording: true,
575+
}
576+
if txHash != nil { // Only one tx to trace
577+
done = true
578+
}
579+
}
580+
vmenv := vm.NewEVM(vmctx, statedb, api.config, vmConf)
581+
_, _, _, err = core.ApplyMessage(vmenv, msg, new(core.GasPool).AddGas(msg.Gas()))
582+
583+
if outfile != nil {
584+
outfile.Close()
585+
log.Info("Wrote trace", "file", outfile.Name())
586+
}
587+
if err != nil {
588+
return files, err
589+
}
590+
// Finalize the state so any modifications are written to the trie
591+
statedb.Finalise(true)
592+
593+
if done {
594+
break
595+
}
596+
}
597+
if txHash != nil && !done {
598+
return nil, fmt.Errorf("transaction hash not found in block")
599+
}
600+
return files, nil
601+
}
602+
484603
// computeStateDB retrieves the state database associated with a certain block.
485604
// If no state is locally available for the given block, a number of blocks are
486605
// attempted to be reexecuted to generate the desired state.
@@ -506,7 +625,7 @@ func (api *PrivateDebugAPI) computeStateDB(block *types.Block, reexec uint64) (*
506625
if err != nil {
507626
switch err.(type) {
508627
case *trie.MissingNodeError:
509-
return nil, errors.New("required historical state unavailable")
628+
return nil, fmt.Errorf("required historical state unavailable (reexec=%d)", reexec)
510629
default:
511630
return nil, err
512631
}
@@ -520,7 +639,7 @@ func (api *PrivateDebugAPI) computeStateDB(block *types.Block, reexec uint64) (*
520639
for block.NumberU64() < origin {
521640
// Print progress logs if long enough time elapsed
522641
if time.Since(logged) > 8*time.Second {
523-
log.Info("Regenerating historical state", "block", block.NumberU64()+1, "target", origin, "elapsed", time.Since(start))
642+
log.Info("Regenerating historical state", "block", block.NumberU64()+1, "target", origin, "remaining", origin-block.NumberU64()-1, "elapsed", time.Since(start))
524643
logged = time.Now()
525644
}
526645
// Retrieve the next block to regenerate and process it
@@ -529,15 +648,15 @@ func (api *PrivateDebugAPI) computeStateDB(block *types.Block, reexec uint64) (*
529648
}
530649
_, _, _, err := api.eth.blockchain.Processor().Process(block, statedb, vm.Config{})
531650
if err != nil {
532-
return nil, err
651+
return nil, fmt.Errorf("processing block %d failed: %v", block.NumberU64(), err)
533652
}
534653
// Finalize the state so any modifications are written to the trie
535-
root, err := statedb.Commit(true)
654+
root, err := statedb.Commit(api.eth.blockchain.Config().IsEIP158(block.Number()))
536655
if err != nil {
537656
return nil, err
538657
}
539658
if err := statedb.Reset(root); err != nil {
540-
return nil, err
659+
return nil, fmt.Errorf("state reset after block %d failed: %v", block.NumberU64(), err)
541660
}
542661
database.TrieDB().Reference(root, common.Hash{})
543662
if proot != (common.Hash{}) {

internal/web3ext/web3ext.go

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -384,6 +384,16 @@ web3._extend({
384384
params: 1,
385385
inputFormatter: [null]
386386
}),
387+
new web3._extend.Method({
388+
name: 'standardTraceBadBlockToFile',
389+
call: 'debug_standardTraceBadBlockToFile',
390+
params: 2,
391+
}),
392+
new web3._extend.Method({
393+
name: 'standardTraceBlockToFile',
394+
call: 'debug_standardTraceBlockToFile',
395+
params: 2,
396+
}),
387397
new web3._extend.Method({
388398
name: 'traceBlockByNumber',
389399
call: 'debug_traceBlockByNumber',

0 commit comments

Comments
 (0)