github.com/phillinzzz/newBsc@v1.1.6/eth/tracers/tracers_test.go (about)

     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  
    17  package tracers
    18  
    19  import (
    20  	"crypto/ecdsa"
    21  	"crypto/rand"
    22  	"encoding/json"
    23  	"io/ioutil"
    24  	"math/big"
    25  	"path/filepath"
    26  	"reflect"
    27  	"strings"
    28  	"testing"
    29  
    30  	"github.com/phillinzzz/newBsc/common"
    31  	"github.com/phillinzzz/newBsc/common/hexutil"
    32  	"github.com/phillinzzz/newBsc/common/math"
    33  	"github.com/phillinzzz/newBsc/core"
    34  	"github.com/phillinzzz/newBsc/core/rawdb"
    35  	"github.com/phillinzzz/newBsc/core/types"
    36  	"github.com/phillinzzz/newBsc/core/vm"
    37  	"github.com/phillinzzz/newBsc/crypto"
    38  	"github.com/phillinzzz/newBsc/params"
    39  	"github.com/phillinzzz/newBsc/rlp"
    40  	"github.com/phillinzzz/newBsc/tests"
    41  )
    42  
    43  // To generate a new callTracer test, copy paste the makeTest method below into
    44  // a Geth console and call it with a transaction hash you which to export.
    45  
    46  /*
    47  // makeTest generates a callTracer test by running a prestate reassembled and a
    48  // call trace run, assembling all the gathered information into a test case.
    49  var makeTest = function(tx, rewind) {
    50    // Generate the genesis block from the block, transaction and prestate data
    51    var block   = eth.getBlock(eth.getTransaction(tx).blockHash);
    52    var genesis = eth.getBlock(block.parentHash);
    53  
    54    delete genesis.gasUsed;
    55    delete genesis.logsBloom;
    56    delete genesis.parentHash;
    57    delete genesis.receiptsRoot;
    58    delete genesis.sha3Uncles;
    59    delete genesis.size;
    60    delete genesis.transactions;
    61    delete genesis.transactionsRoot;
    62    delete genesis.uncles;
    63  
    64    genesis.gasLimit  = genesis.gasLimit.toString();
    65    genesis.number    = genesis.number.toString();
    66    genesis.timestamp = genesis.timestamp.toString();
    67  
    68    genesis.alloc = debug.traceTransaction(tx, {tracer: "prestateTracer", rewind: rewind});
    69    for (var key in genesis.alloc) {
    70      genesis.alloc[key].nonce = genesis.alloc[key].nonce.toString();
    71    }
    72    genesis.config = admin.nodeInfo.protocols.eth.config;
    73  
    74    // Generate the call trace and produce the test input
    75    var result = debug.traceTransaction(tx, {tracer: "callTracer", rewind: rewind});
    76    delete result.time;
    77  
    78    console.log(JSON.stringify({
    79      genesis: genesis,
    80      context: {
    81        number:     block.number.toString(),
    82        difficulty: block.difficulty,
    83        timestamp:  block.timestamp.toString(),
    84        gasLimit:   block.gasLimit.toString(),
    85        miner:      block.miner,
    86      },
    87      input:  eth.getRawTransaction(tx),
    88      result: result,
    89    }, null, 2));
    90  }
    91  */
    92  
    93  // callTrace is the result of a callTracer run.
    94  type callTrace struct {
    95  	Type    string          `json:"type"`
    96  	From    common.Address  `json:"from"`
    97  	To      common.Address  `json:"to"`
    98  	Input   hexutil.Bytes   `json:"input"`
    99  	Output  hexutil.Bytes   `json:"output"`
   100  	Gas     *hexutil.Uint64 `json:"gas,omitempty"`
   101  	GasUsed *hexutil.Uint64 `json:"gasUsed,omitempty"`
   102  	Value   *hexutil.Big    `json:"value,omitempty"`
   103  	Error   string          `json:"error,omitempty"`
   104  	Calls   []callTrace     `json:"calls,omitempty"`
   105  }
   106  
   107  type callContext struct {
   108  	Number     math.HexOrDecimal64   `json:"number"`
   109  	Difficulty *math.HexOrDecimal256 `json:"difficulty"`
   110  	Time       math.HexOrDecimal64   `json:"timestamp"`
   111  	GasLimit   math.HexOrDecimal64   `json:"gasLimit"`
   112  	Miner      common.Address        `json:"miner"`
   113  }
   114  
   115  // callTracerTest defines a single test to check the call tracer against.
   116  type callTracerTest struct {
   117  	Genesis *core.Genesis `json:"genesis"`
   118  	Context *callContext  `json:"context"`
   119  	Input   string        `json:"input"`
   120  	Result  *callTrace    `json:"result"`
   121  }
   122  
   123  func TestPrestateTracerCreate2(t *testing.T) {
   124  	unsignedTx := types.NewTransaction(1, common.HexToAddress("0x00000000000000000000000000000000deadbeef"),
   125  		new(big.Int), 5000000, big.NewInt(1), []byte{})
   126  
   127  	privateKeyECDSA, err := ecdsa.GenerateKey(crypto.S256(), rand.Reader)
   128  	if err != nil {
   129  		t.Fatalf("err %v", err)
   130  	}
   131  	signer := types.NewEIP155Signer(big.NewInt(1))
   132  	tx, err := types.SignTx(unsignedTx, signer, privateKeyECDSA)
   133  	if err != nil {
   134  		t.Fatalf("err %v", err)
   135  	}
   136  	/**
   137  		This comes from one of the test-vectors on the Skinny Create2 - EIP
   138  
   139  	    address 0x00000000000000000000000000000000deadbeef
   140  	    salt 0x00000000000000000000000000000000000000000000000000000000cafebabe
   141  	    init_code 0xdeadbeef
   142  	    gas (assuming no mem expansion): 32006
   143  	    result: 0x60f3f640a8508fC6a86d45DF051962668E1e8AC7
   144  	*/
   145  	origin, _ := signer.Sender(tx)
   146  	txContext := vm.TxContext{
   147  		Origin:   origin,
   148  		GasPrice: big.NewInt(1),
   149  	}
   150  	context := vm.BlockContext{
   151  		CanTransfer: core.CanTransfer,
   152  		Transfer:    core.Transfer,
   153  		Coinbase:    common.Address{},
   154  		BlockNumber: new(big.Int).SetUint64(8000000),
   155  		Time:        new(big.Int).SetUint64(5),
   156  		Difficulty:  big.NewInt(0x30000),
   157  		GasLimit:    uint64(6000000),
   158  	}
   159  	alloc := core.GenesisAlloc{}
   160  
   161  	// The code pushes 'deadbeef' into memory, then the other params, and calls CREATE2, then returns
   162  	// the address
   163  	alloc[common.HexToAddress("0x00000000000000000000000000000000deadbeef")] = core.GenesisAccount{
   164  		Nonce:   1,
   165  		Code:    hexutil.MustDecode("0x63deadbeef60005263cafebabe6004601c6000F560005260206000F3"),
   166  		Balance: big.NewInt(1),
   167  	}
   168  	alloc[origin] = core.GenesisAccount{
   169  		Nonce:   1,
   170  		Code:    []byte{},
   171  		Balance: big.NewInt(500000000000000),
   172  	}
   173  	_, statedb := tests.MakePreState(rawdb.NewMemoryDatabase(), alloc, false)
   174  
   175  	// Create the tracer, the EVM environment and run it
   176  	tracer, err := New("prestateTracer", txContext)
   177  	if err != nil {
   178  		t.Fatalf("failed to create call tracer: %v", err)
   179  	}
   180  	evm := vm.NewEVM(context, txContext, statedb, params.MainnetChainConfig, vm.Config{Debug: true, Tracer: tracer})
   181  
   182  	msg, err := tx.AsMessage(signer)
   183  	if err != nil {
   184  		t.Fatalf("failed to prepare transaction for tracing: %v", err)
   185  	}
   186  	st := core.NewStateTransition(evm, msg, new(core.GasPool).AddGas(tx.Gas()))
   187  	if _, err = st.TransitionDb(); err != nil {
   188  		t.Fatalf("failed to execute transaction: %v", err)
   189  	}
   190  	// Retrieve the trace result and compare against the etalon
   191  	res, err := tracer.GetResult()
   192  	if err != nil {
   193  		t.Fatalf("failed to retrieve trace result: %v", err)
   194  	}
   195  	ret := make(map[string]interface{})
   196  	if err := json.Unmarshal(res, &ret); err != nil {
   197  		t.Fatalf("failed to unmarshal trace result: %v", err)
   198  	}
   199  	if _, has := ret["0x60f3f640a8508fc6a86d45df051962668e1e8ac7"]; !has {
   200  		t.Fatalf("Expected 0x60f3f640a8508fc6a86d45df051962668e1e8ac7 in result")
   201  	}
   202  }
   203  
   204  // Iterates over all the input-output datasets in the tracer test harness and
   205  // runs the JavaScript tracers against them.
   206  func TestCallTracer(t *testing.T) {
   207  	files, err := ioutil.ReadDir("testdata")
   208  	if err != nil {
   209  		t.Fatalf("failed to retrieve tracer test suite: %v", err)
   210  	}
   211  	for _, file := range files {
   212  		if !strings.HasPrefix(file.Name(), "call_tracer_") {
   213  			continue
   214  		}
   215  		file := file // capture range variable
   216  		t.Run(camel(strings.TrimSuffix(strings.TrimPrefix(file.Name(), "call_tracer_"), ".json")), func(t *testing.T) {
   217  			t.Parallel()
   218  
   219  			// Call tracer test found, read if from disk
   220  			blob, err := ioutil.ReadFile(filepath.Join("testdata", file.Name()))
   221  			if err != nil {
   222  				t.Fatalf("failed to read testcase: %v", err)
   223  			}
   224  			test := new(callTracerTest)
   225  			if err := json.Unmarshal(blob, test); err != nil {
   226  				t.Fatalf("failed to parse testcase: %v", err)
   227  			}
   228  			// Configure a blockchain with the given prestate
   229  			tx := new(types.Transaction)
   230  			if err := rlp.DecodeBytes(common.FromHex(test.Input), tx); err != nil {
   231  				t.Fatalf("failed to parse testcase input: %v", err)
   232  			}
   233  			signer := types.MakeSigner(test.Genesis.Config, new(big.Int).SetUint64(uint64(test.Context.Number)))
   234  			origin, _ := signer.Sender(tx)
   235  			txContext := vm.TxContext{
   236  				Origin:   origin,
   237  				GasPrice: tx.GasPrice(),
   238  			}
   239  			context := vm.BlockContext{
   240  				CanTransfer: core.CanTransfer,
   241  				Transfer:    core.Transfer,
   242  				Coinbase:    test.Context.Miner,
   243  				BlockNumber: new(big.Int).SetUint64(uint64(test.Context.Number)),
   244  				Time:        new(big.Int).SetUint64(uint64(test.Context.Time)),
   245  				Difficulty:  (*big.Int)(test.Context.Difficulty),
   246  				GasLimit:    uint64(test.Context.GasLimit),
   247  			}
   248  			_, statedb := tests.MakePreState(rawdb.NewMemoryDatabase(), test.Genesis.Alloc, false)
   249  
   250  			// Create the tracer, the EVM environment and run it
   251  			tracer, err := New("callTracer", txContext)
   252  			if err != nil {
   253  				t.Fatalf("failed to create call tracer: %v", err)
   254  			}
   255  			evm := vm.NewEVM(context, txContext, statedb, test.Genesis.Config, vm.Config{Debug: true, Tracer: tracer})
   256  
   257  			msg, err := tx.AsMessage(signer)
   258  			if err != nil {
   259  				t.Fatalf("failed to prepare transaction for tracing: %v", err)
   260  			}
   261  			st := core.NewStateTransition(evm, msg, new(core.GasPool).AddGas(tx.Gas()))
   262  			if _, err = st.TransitionDb(); err != nil {
   263  				t.Fatalf("failed to execute transaction: %v", err)
   264  			}
   265  			// Retrieve the trace result and compare against the etalon
   266  			res, err := tracer.GetResult()
   267  			if err != nil {
   268  				t.Fatalf("failed to retrieve trace result: %v", err)
   269  			}
   270  			ret := new(callTrace)
   271  			if err := json.Unmarshal(res, ret); err != nil {
   272  				t.Fatalf("failed to unmarshal trace result: %v", err)
   273  			}
   274  
   275  			if !jsonEqual(ret, test.Result) {
   276  				// uncomment this for easier debugging
   277  				//have, _ := json.MarshalIndent(ret, "", " ")
   278  				//want, _ := json.MarshalIndent(test.Result, "", " ")
   279  				//t.Fatalf("trace mismatch: \nhave %+v\nwant %+v", string(have), string(want))
   280  				t.Fatalf("trace mismatch: \nhave %+v\nwant %+v", ret, test.Result)
   281  			}
   282  		})
   283  	}
   284  }
   285  
   286  // jsonEqual is similar to reflect.DeepEqual, but does a 'bounce' via json prior to
   287  // comparison
   288  func jsonEqual(x, y interface{}) bool {
   289  	xTrace := new(callTrace)
   290  	yTrace := new(callTrace)
   291  	if xj, err := json.Marshal(x); err == nil {
   292  		json.Unmarshal(xj, xTrace)
   293  	} else {
   294  		return false
   295  	}
   296  	if yj, err := json.Marshal(y); err == nil {
   297  		json.Unmarshal(yj, yTrace)
   298  	} else {
   299  		return false
   300  	}
   301  	return reflect.DeepEqual(xTrace, yTrace)
   302  }
   303  
   304  func BenchmarkTransactionTrace(b *testing.B) {
   305  	key, _ := crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291")
   306  	from := crypto.PubkeyToAddress(key.PublicKey)
   307  	gas := uint64(1000000) // 1M gas
   308  	to := common.HexToAddress("0x00000000000000000000000000000000deadbeef")
   309  	signer := types.LatestSignerForChainID(big.NewInt(1337))
   310  	tx, err := types.SignNewTx(key, signer,
   311  		&types.LegacyTx{
   312  			Nonce:    1,
   313  			GasPrice: big.NewInt(500),
   314  			Gas:      gas,
   315  			To:       &to,
   316  		})
   317  	if err != nil {
   318  		b.Fatal(err)
   319  	}
   320  	txContext := vm.TxContext{
   321  		Origin:   from,
   322  		GasPrice: tx.GasPrice(),
   323  	}
   324  	context := vm.BlockContext{
   325  		CanTransfer: core.CanTransfer,
   326  		Transfer:    core.Transfer,
   327  		Coinbase:    common.Address{},
   328  		BlockNumber: new(big.Int).SetUint64(uint64(5)),
   329  		Time:        new(big.Int).SetUint64(uint64(5)),
   330  		Difficulty:  big.NewInt(0xffffffff),
   331  		GasLimit:    gas,
   332  	}
   333  	alloc := core.GenesisAlloc{}
   334  	// The code pushes 'deadbeef' into memory, then the other params, and calls CREATE2, then returns
   335  	// the address
   336  	loop := []byte{
   337  		byte(vm.JUMPDEST), //  [ count ]
   338  		byte(vm.PUSH1), 0, // jumpdestination
   339  		byte(vm.JUMP),
   340  	}
   341  	alloc[common.HexToAddress("0x00000000000000000000000000000000deadbeef")] = core.GenesisAccount{
   342  		Nonce:   1,
   343  		Code:    loop,
   344  		Balance: big.NewInt(1),
   345  	}
   346  	alloc[from] = core.GenesisAccount{
   347  		Nonce:   1,
   348  		Code:    []byte{},
   349  		Balance: big.NewInt(500000000000000),
   350  	}
   351  	_, statedb := tests.MakePreState(rawdb.NewMemoryDatabase(), alloc, false)
   352  	// Create the tracer, the EVM environment and run it
   353  	tracer := vm.NewStructLogger(&vm.LogConfig{
   354  		Debug: false,
   355  		//DisableStorage: true,
   356  		//DisableMemory: true,
   357  		//DisableReturnData: true,
   358  	})
   359  	evm := vm.NewEVM(context, txContext, statedb, params.AllEthashProtocolChanges, vm.Config{Debug: true, Tracer: tracer})
   360  	msg, err := tx.AsMessage(signer)
   361  	if err != nil {
   362  		b.Fatalf("failed to prepare transaction for tracing: %v", err)
   363  	}
   364  	b.ResetTimer()
   365  	b.ReportAllocs()
   366  
   367  	for i := 0; i < b.N; i++ {
   368  		snap := statedb.Snapshot()
   369  		st := core.NewStateTransition(evm, msg, new(core.GasPool).AddGas(tx.Gas()))
   370  		_, err = st.TransitionDb()
   371  		if err != nil {
   372  			b.Fatal(err)
   373  		}
   374  		statedb.RevertToSnapshot(snap)
   375  		if have, want := len(tracer.StructLogs()), 244752; have != want {
   376  			b.Fatalf("trace wrong, want %d steps, have %d", want, have)
   377  		}
   378  		tracer.Reset()
   379  	}
   380  }