github.1485827954.workers.dev/ethereum/go-ethereum@v1.14.3/eth/tracers/internal/tracetest/prestate_test.go (about)

     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  
    17  package tracetest
    18  
    19  import (
    20  	"encoding/json"
    21  	"math/big"
    22  	"os"
    23  	"path/filepath"
    24  	"strings"
    25  	"testing"
    26  
    27  	"github.com/ethereum/go-ethereum/common"
    28  	"github.com/ethereum/go-ethereum/core"
    29  	"github.com/ethereum/go-ethereum/core/rawdb"
    30  	"github.com/ethereum/go-ethereum/core/types"
    31  	"github.com/ethereum/go-ethereum/core/vm"
    32  	"github.com/ethereum/go-ethereum/eth/tracers"
    33  	"github.com/ethereum/go-ethereum/tests"
    34  )
    35  
    36  // prestateTrace is the result of a prestateTrace run.
    37  type prestateTrace = map[common.Address]*account
    38  
    39  type account struct {
    40  	Balance string                      `json:"balance"`
    41  	Code    string                      `json:"code"`
    42  	Nonce   uint64                      `json:"nonce"`
    43  	Storage map[common.Hash]common.Hash `json:"storage"`
    44  }
    45  
    46  // testcase defines a single test to check the stateDiff tracer against.
    47  type testcase struct {
    48  	Genesis      *core.Genesis   `json:"genesis"`
    49  	Context      *callContext    `json:"context"`
    50  	Input        string          `json:"input"`
    51  	TracerConfig json.RawMessage `json:"tracerConfig"`
    52  	Result       interface{}     `json:"result"`
    53  }
    54  
    55  func TestPrestateTracerLegacy(t *testing.T) {
    56  	testPrestateDiffTracer("prestateTracerLegacy", "prestate_tracer_legacy", t)
    57  }
    58  
    59  func TestPrestateTracer(t *testing.T) {
    60  	testPrestateDiffTracer("prestateTracer", "prestate_tracer", t)
    61  }
    62  
    63  func TestPrestateWithDiffModeTracer(t *testing.T) {
    64  	testPrestateDiffTracer("prestateTracer", "prestate_tracer_with_diff_mode", t)
    65  }
    66  
    67  func testPrestateDiffTracer(tracerName string, dirPath string, t *testing.T) {
    68  	files, err := os.ReadDir(filepath.Join("testdata", dirPath))
    69  	if err != nil {
    70  		t.Fatalf("failed to retrieve tracer test suite: %v", err)
    71  	}
    72  	for _, file := range files {
    73  		if !strings.HasSuffix(file.Name(), ".json") {
    74  			continue
    75  		}
    76  		file := file // capture range variable
    77  		t.Run(camel(strings.TrimSuffix(file.Name(), ".json")), func(t *testing.T) {
    78  			t.Parallel()
    79  
    80  			var (
    81  				test = new(testcase)
    82  				tx   = new(types.Transaction)
    83  			)
    84  			// Call tracer test found, read if from disk
    85  			if blob, err := os.ReadFile(filepath.Join("testdata", dirPath, file.Name())); err != nil {
    86  				t.Fatalf("failed to read testcase: %v", err)
    87  			} else if err := json.Unmarshal(blob, test); err != nil {
    88  				t.Fatalf("failed to parse testcase: %v", err)
    89  			}
    90  			if err := tx.UnmarshalBinary(common.FromHex(test.Input)); err != nil {
    91  				t.Fatalf("failed to parse testcase input: %v", err)
    92  			}
    93  			// Configure a blockchain with the given prestate
    94  			var (
    95  				signer  = types.MakeSigner(test.Genesis.Config, new(big.Int).SetUint64(uint64(test.Context.Number)), uint64(test.Context.Time))
    96  				context = test.Context.toBlockContext(test.Genesis)
    97  				state   = tests.MakePreState(rawdb.NewMemoryDatabase(), test.Genesis.Alloc, false, rawdb.HashScheme)
    98  			)
    99  			defer state.Close()
   100  
   101  			tracer, err := tracers.DefaultDirectory.New(tracerName, new(tracers.Context), test.TracerConfig)
   102  			if err != nil {
   103  				t.Fatalf("failed to create call tracer: %v", err)
   104  			}
   105  
   106  			state.StateDB.SetLogger(tracer.Hooks)
   107  			msg, err := core.TransactionToMessage(tx, signer, context.BaseFee)
   108  			if err != nil {
   109  				t.Fatalf("failed to prepare transaction for tracing: %v", err)
   110  			}
   111  			evm := vm.NewEVM(context, core.NewEVMTxContext(msg), state.StateDB, test.Genesis.Config, vm.Config{Tracer: tracer.Hooks})
   112  			tracer.OnTxStart(evm.GetVMContext(), tx, msg.From)
   113  			vmRet, err := core.ApplyMessage(evm, msg, new(core.GasPool).AddGas(tx.Gas()))
   114  			if err != nil {
   115  				t.Fatalf("failed to execute transaction: %v", err)
   116  			}
   117  			tracer.OnTxEnd(&types.Receipt{GasUsed: vmRet.UsedGas}, nil)
   118  			// Retrieve the trace result and compare against the expected
   119  			res, err := tracer.GetResult()
   120  			if err != nil {
   121  				t.Fatalf("failed to retrieve trace result: %v", err)
   122  			}
   123  			// The legacy javascript calltracer marshals json in js, which
   124  			// is not deterministic (as opposed to the golang json encoder).
   125  			if strings.HasSuffix(dirPath, "_legacy") {
   126  				// This is a tweak to make it deterministic. Can be removed when
   127  				// we remove the legacy tracer.
   128  				var x prestateTrace
   129  				json.Unmarshal(res, &x)
   130  				res, _ = json.Marshal(x)
   131  			}
   132  			want, err := json.Marshal(test.Result)
   133  			if err != nil {
   134  				t.Fatalf("failed to marshal test: %v", err)
   135  			}
   136  			if string(want) != string(res) {
   137  				t.Fatalf("trace mismatch\n have: %v\n want: %v\n", string(res), string(want))
   138  			}
   139  		})
   140  	}
   141  }