github.com/theQRL/go-zond@v0.1.1/zond/tracers/api_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 tracers 18 19 import ( 20 "context" 21 "crypto/ecdsa" 22 "encoding/json" 23 "errors" 24 "fmt" 25 "math/big" 26 "reflect" 27 "sync/atomic" 28 "testing" 29 "time" 30 31 "github.com/theQRL/go-zond/common" 32 "github.com/theQRL/go-zond/common/hexutil" 33 "github.com/theQRL/go-zond/consensus" 34 "github.com/theQRL/go-zond/consensus/ethash" 35 "github.com/theQRL/go-zond/core" 36 "github.com/theQRL/go-zond/core/rawdb" 37 "github.com/theQRL/go-zond/core/state" 38 "github.com/theQRL/go-zond/core/types" 39 "github.com/theQRL/go-zond/core/vm" 40 "github.com/theQRL/go-zond/crypto" 41 "github.com/theQRL/go-zond/internal/ethapi" 42 "github.com/theQRL/go-zond/params" 43 "github.com/theQRL/go-zond/rpc" 44 "github.com/theQRL/go-zond/zond/tracers/logger" 45 "github.com/theQRL/go-zond/zonddb" 46 "golang.org/x/exp/slices" 47 ) 48 49 var ( 50 errStateNotFound = errors.New("state not found") 51 errBlockNotFound = errors.New("block not found") 52 ) 53 54 type testBackend struct { 55 chainConfig *params.ChainConfig 56 engine consensus.Engine 57 chaindb zonddb.Database 58 chain *core.BlockChain 59 60 refHook func() // Hook is invoked when the requested state is referenced 61 relHook func() // Hook is invoked when the requested state is released 62 } 63 64 // testBackend creates a new test backend. OBS: After test is done, teardown must be 65 // invoked in order to release associated resources. 66 func newTestBackend(t *testing.T, n int, gspec *core.Genesis, generator func(i int, b *core.BlockGen)) *testBackend { 67 backend := &testBackend{ 68 chainConfig: gspec.Config, 69 engine: ethash.NewFaker(), 70 chaindb: rawdb.NewMemoryDatabase(), 71 } 72 // Generate blocks for testing 73 _, blocks, _ := core.GenerateChainWithGenesis(gspec, backend.engine, n, generator) 74 75 // Import the canonical chain 76 cacheConfig := &core.CacheConfig{ 77 TrieCleanLimit: 256, 78 TrieDirtyLimit: 256, 79 TrieTimeLimit: 5 * time.Minute, 80 SnapshotLimit: 0, 81 TrieDirtyDisabled: true, // Archive mode 82 } 83 chain, err := core.NewBlockChain(backend.chaindb, cacheConfig, gspec, nil, backend.engine, vm.Config{}, nil, nil) 84 if err != nil { 85 t.Fatalf("failed to create tester chain: %v", err) 86 } 87 if n, err := chain.InsertChain(blocks); err != nil { 88 t.Fatalf("block %d: failed to insert into chain: %v", n, err) 89 } 90 backend.chain = chain 91 return backend 92 } 93 94 func (b *testBackend) HeaderByHash(ctx context.Context, hash common.Hash) (*types.Header, error) { 95 return b.chain.GetHeaderByHash(hash), nil 96 } 97 98 func (b *testBackend) HeaderByNumber(ctx context.Context, number rpc.BlockNumber) (*types.Header, error) { 99 if number == rpc.PendingBlockNumber || number == rpc.LatestBlockNumber { 100 return b.chain.CurrentHeader(), nil 101 } 102 return b.chain.GetHeaderByNumber(uint64(number)), nil 103 } 104 105 func (b *testBackend) BlockByHash(ctx context.Context, hash common.Hash) (*types.Block, error) { 106 return b.chain.GetBlockByHash(hash), nil 107 } 108 109 func (b *testBackend) BlockByNumber(ctx context.Context, number rpc.BlockNumber) (*types.Block, error) { 110 if number == rpc.PendingBlockNumber || number == rpc.LatestBlockNumber { 111 return b.chain.GetBlockByNumber(b.chain.CurrentBlock().Number.Uint64()), nil 112 } 113 return b.chain.GetBlockByNumber(uint64(number)), nil 114 } 115 116 func (b *testBackend) GetTransaction(ctx context.Context, txHash common.Hash) (*types.Transaction, common.Hash, uint64, uint64, error) { 117 tx, hash, blockNumber, index := rawdb.ReadTransaction(b.chaindb, txHash) 118 return tx, hash, blockNumber, index, nil 119 } 120 121 func (b *testBackend) RPCGasCap() uint64 { 122 return 25000000 123 } 124 125 func (b *testBackend) ChainConfig() *params.ChainConfig { 126 return b.chainConfig 127 } 128 129 func (b *testBackend) Engine() consensus.Engine { 130 return b.engine 131 } 132 133 func (b *testBackend) ChainDb() zonddb.Database { 134 return b.chaindb 135 } 136 137 // teardown releases the associated resources. 138 func (b *testBackend) teardown() { 139 b.chain.Stop() 140 } 141 142 func (b *testBackend) StateAtBlock(ctx context.Context, block *types.Block, reexec uint64, base *state.StateDB, readOnly bool, preferDisk bool) (*state.StateDB, StateReleaseFunc, error) { 143 statedb, err := b.chain.StateAt(block.Root()) 144 if err != nil { 145 return nil, nil, errStateNotFound 146 } 147 if b.refHook != nil { 148 b.refHook() 149 } 150 release := func() { 151 if b.relHook != nil { 152 b.relHook() 153 } 154 } 155 return statedb, release, nil 156 } 157 158 func (b *testBackend) StateAtTransaction(ctx context.Context, block *types.Block, txIndex int, reexec uint64) (*core.Message, vm.BlockContext, *state.StateDB, StateReleaseFunc, error) { 159 parent := b.chain.GetBlock(block.ParentHash(), block.NumberU64()-1) 160 if parent == nil { 161 return nil, vm.BlockContext{}, nil, nil, errBlockNotFound 162 } 163 statedb, release, err := b.StateAtBlock(ctx, parent, reexec, nil, true, false) 164 if err != nil { 165 return nil, vm.BlockContext{}, nil, nil, errStateNotFound 166 } 167 if txIndex == 0 && len(block.Transactions()) == 0 { 168 return nil, vm.BlockContext{}, statedb, release, nil 169 } 170 // Recompute transactions up to the target index. 171 signer := types.MakeSigner(b.chainConfig, block.Number(), block.Time()) 172 for idx, tx := range block.Transactions() { 173 msg, _ := core.TransactionToMessage(tx, signer, block.BaseFee()) 174 txContext := core.NewEVMTxContext(msg) 175 context := core.NewEVMBlockContext(block.Header(), b.chain, nil) 176 if idx == txIndex { 177 return msg, context, statedb, release, nil 178 } 179 vmenv := vm.NewEVM(context, txContext, statedb, b.chainConfig, vm.Config{}) 180 if _, err := core.ApplyMessage(vmenv, msg, new(core.GasPool).AddGas(tx.Gas())); err != nil { 181 return nil, vm.BlockContext{}, nil, nil, fmt.Errorf("transaction %#x failed: %v", tx.Hash(), err) 182 } 183 statedb.Finalise(vmenv.ChainConfig().IsEIP158(block.Number())) 184 } 185 return nil, vm.BlockContext{}, nil, nil, fmt.Errorf("transaction index %d out of range for block %#x", txIndex, block.Hash()) 186 } 187 188 func TestTraceCall(t *testing.T) { 189 t.Parallel() 190 191 // Initialize test accounts 192 accounts := newAccounts(3) 193 genesis := &core.Genesis{ 194 Config: params.TestChainConfig, 195 Alloc: core.GenesisAlloc{ 196 accounts[0].addr: {Balance: big.NewInt(params.Ether)}, 197 accounts[1].addr: {Balance: big.NewInt(params.Ether)}, 198 accounts[2].addr: {Balance: big.NewInt(params.Ether)}, 199 }, 200 } 201 genBlocks := 10 202 signer := types.HomesteadSigner{} 203 backend := newTestBackend(t, genBlocks, genesis, func(i int, b *core.BlockGen) { 204 // Transfer from account[0] to account[1] 205 // value: 1000 wei 206 // fee: 0 wei 207 tx, _ := types.SignTx(types.NewTransaction(uint64(i), accounts[1].addr, big.NewInt(1000), params.TxGas, b.BaseFee(), nil), signer, accounts[0].key) 208 b.AddTx(tx) 209 }) 210 defer backend.teardown() 211 api := NewAPI(backend) 212 var testSuite = []struct { 213 blockNumber rpc.BlockNumber 214 call ethapi.TransactionArgs 215 config *TraceCallConfig 216 expectErr error 217 expect string 218 }{ 219 // Standard JSON trace upon the genesis, plain transfer. 220 { 221 blockNumber: rpc.BlockNumber(0), 222 call: ethapi.TransactionArgs{ 223 From: &accounts[0].addr, 224 To: &accounts[1].addr, 225 Value: (*hexutil.Big)(big.NewInt(1000)), 226 }, 227 config: nil, 228 expectErr: nil, 229 expect: `{"gas":21000,"failed":false,"returnValue":"","structLogs":[]}`, 230 }, 231 // Standard JSON trace upon the head, plain transfer. 232 { 233 blockNumber: rpc.BlockNumber(genBlocks), 234 call: ethapi.TransactionArgs{ 235 From: &accounts[0].addr, 236 To: &accounts[1].addr, 237 Value: (*hexutil.Big)(big.NewInt(1000)), 238 }, 239 config: nil, 240 expectErr: nil, 241 expect: `{"gas":21000,"failed":false,"returnValue":"","structLogs":[]}`, 242 }, 243 // Standard JSON trace upon the non-existent block, error expects 244 { 245 blockNumber: rpc.BlockNumber(genBlocks + 1), 246 call: ethapi.TransactionArgs{ 247 From: &accounts[0].addr, 248 To: &accounts[1].addr, 249 Value: (*hexutil.Big)(big.NewInt(1000)), 250 }, 251 config: nil, 252 expectErr: fmt.Errorf("block #%d not found", genBlocks+1), 253 //expect: nil, 254 }, 255 // Standard JSON trace upon the latest block 256 { 257 blockNumber: rpc.LatestBlockNumber, 258 call: ethapi.TransactionArgs{ 259 From: &accounts[0].addr, 260 To: &accounts[1].addr, 261 Value: (*hexutil.Big)(big.NewInt(1000)), 262 }, 263 config: nil, 264 expectErr: nil, 265 expect: `{"gas":21000,"failed":false,"returnValue":"","structLogs":[]}`, 266 }, 267 // Tracing on 'pending' should fail: 268 { 269 blockNumber: rpc.PendingBlockNumber, 270 call: ethapi.TransactionArgs{ 271 From: &accounts[0].addr, 272 To: &accounts[1].addr, 273 Value: (*hexutil.Big)(big.NewInt(1000)), 274 }, 275 config: nil, 276 expectErr: errors.New("tracing on top of pending is not supported"), 277 }, 278 { 279 blockNumber: rpc.LatestBlockNumber, 280 call: ethapi.TransactionArgs{ 281 From: &accounts[0].addr, 282 Input: &hexutil.Bytes{0x43}, // blocknumber 283 }, 284 config: &TraceCallConfig{ 285 BlockOverrides: ðapi.BlockOverrides{Number: (*hexutil.Big)(big.NewInt(0x1337))}, 286 }, 287 expectErr: nil, 288 expect: ` {"gas":53018,"failed":false,"returnValue":"","structLogs":[ 289 {"pc":0,"op":"NUMBER","gas":24946984,"gasCost":2,"depth":1,"stack":[]}, 290 {"pc":1,"op":"STOP","gas":24946982,"gasCost":0,"depth":1,"stack":["0x1337"]}]}`, 291 }, 292 } 293 for i, testspec := range testSuite { 294 result, err := api.TraceCall(context.Background(), testspec.call, rpc.BlockNumberOrHash{BlockNumber: &testspec.blockNumber}, testspec.config) 295 if testspec.expectErr != nil { 296 if err == nil { 297 t.Errorf("test %d: expect error %v, got nothing", i, testspec.expectErr) 298 continue 299 } 300 if !reflect.DeepEqual(err, testspec.expectErr) { 301 t.Errorf("test %d: error mismatch, want %v, git %v", i, testspec.expectErr, err) 302 } 303 } else { 304 if err != nil { 305 t.Errorf("test %d: expect no error, got %v", i, err) 306 continue 307 } 308 var have *logger.ExecutionResult 309 if err := json.Unmarshal(result.(json.RawMessage), &have); err != nil { 310 t.Errorf("test %d: failed to unmarshal result %v", i, err) 311 } 312 var want *logger.ExecutionResult 313 if err := json.Unmarshal([]byte(testspec.expect), &want); err != nil { 314 t.Errorf("test %d: failed to unmarshal result %v", i, err) 315 } 316 if !reflect.DeepEqual(have, want) { 317 t.Errorf("test %d: result mismatch, want %v, got %v", i, testspec.expect, string(result.(json.RawMessage))) 318 } 319 } 320 } 321 } 322 323 func TestTraceTransaction(t *testing.T) { 324 t.Parallel() 325 326 // Initialize test accounts 327 accounts := newAccounts(2) 328 genesis := &core.Genesis{ 329 Config: params.TestChainConfig, 330 Alloc: core.GenesisAlloc{ 331 accounts[0].addr: {Balance: big.NewInt(params.Ether)}, 332 accounts[1].addr: {Balance: big.NewInt(params.Ether)}, 333 }, 334 } 335 target := common.Hash{} 336 signer := types.HomesteadSigner{} 337 backend := newTestBackend(t, 1, genesis, func(i int, b *core.BlockGen) { 338 // Transfer from account[0] to account[1] 339 // value: 1000 wei 340 // fee: 0 wei 341 tx, _ := types.SignTx(types.NewTransaction(uint64(i), accounts[1].addr, big.NewInt(1000), params.TxGas, b.BaseFee(), nil), signer, accounts[0].key) 342 b.AddTx(tx) 343 target = tx.Hash() 344 }) 345 defer backend.chain.Stop() 346 api := NewAPI(backend) 347 result, err := api.TraceTransaction(context.Background(), target, nil) 348 if err != nil { 349 t.Errorf("Failed to trace transaction %v", err) 350 } 351 var have *logger.ExecutionResult 352 if err := json.Unmarshal(result.(json.RawMessage), &have); err != nil { 353 t.Errorf("failed to unmarshal result %v", err) 354 } 355 if !reflect.DeepEqual(have, &logger.ExecutionResult{ 356 Gas: params.TxGas, 357 Failed: false, 358 ReturnValue: "", 359 StructLogs: []logger.StructLogRes{}, 360 }) { 361 t.Error("Transaction tracing result is different") 362 } 363 364 // Test non-existent transaction 365 _, err = api.TraceTransaction(context.Background(), common.Hash{42}, nil) 366 if !errors.Is(err, errTxNotFound) { 367 t.Fatalf("want %v, have %v", errTxNotFound, err) 368 } 369 } 370 371 func TestTraceBlock(t *testing.T) { 372 t.Parallel() 373 374 // Initialize test accounts 375 accounts := newAccounts(3) 376 genesis := &core.Genesis{ 377 Config: params.TestChainConfig, 378 Alloc: core.GenesisAlloc{ 379 accounts[0].addr: {Balance: big.NewInt(params.Ether)}, 380 accounts[1].addr: {Balance: big.NewInt(params.Ether)}, 381 accounts[2].addr: {Balance: big.NewInt(params.Ether)}, 382 }, 383 } 384 genBlocks := 10 385 signer := types.HomesteadSigner{} 386 var txHash common.Hash 387 backend := newTestBackend(t, genBlocks, genesis, func(i int, b *core.BlockGen) { 388 // Transfer from account[0] to account[1] 389 // value: 1000 wei 390 // fee: 0 wei 391 tx, _ := types.SignTx(types.NewTransaction(uint64(i), accounts[1].addr, big.NewInt(1000), params.TxGas, b.BaseFee(), nil), signer, accounts[0].key) 392 b.AddTx(tx) 393 txHash = tx.Hash() 394 }) 395 defer backend.chain.Stop() 396 api := NewAPI(backend) 397 398 var testSuite = []struct { 399 blockNumber rpc.BlockNumber 400 config *TraceConfig 401 want string 402 expectErr error 403 }{ 404 // Trace genesis block, expect error 405 { 406 blockNumber: rpc.BlockNumber(0), 407 expectErr: errors.New("genesis is not traceable"), 408 }, 409 // Trace head block 410 { 411 blockNumber: rpc.BlockNumber(genBlocks), 412 want: fmt.Sprintf(`[{"txHash":"%v","result":{"gas":21000,"failed":false,"returnValue":"","structLogs":[]}}]`, txHash), 413 }, 414 // Trace non-existent block 415 { 416 blockNumber: rpc.BlockNumber(genBlocks + 1), 417 expectErr: fmt.Errorf("block #%d not found", genBlocks+1), 418 }, 419 // Trace latest block 420 { 421 blockNumber: rpc.LatestBlockNumber, 422 want: fmt.Sprintf(`[{"txHash":"%v","result":{"gas":21000,"failed":false,"returnValue":"","structLogs":[]}}]`, txHash), 423 }, 424 // Trace pending block 425 { 426 blockNumber: rpc.PendingBlockNumber, 427 want: fmt.Sprintf(`[{"txHash":"%v","result":{"gas":21000,"failed":false,"returnValue":"","structLogs":[]}}]`, txHash), 428 }, 429 } 430 for i, tc := range testSuite { 431 result, err := api.TraceBlockByNumber(context.Background(), tc.blockNumber, tc.config) 432 if tc.expectErr != nil { 433 if err == nil { 434 t.Errorf("test %d, want error %v", i, tc.expectErr) 435 continue 436 } 437 if !reflect.DeepEqual(err, tc.expectErr) { 438 t.Errorf("test %d: error mismatch, want %v, get %v", i, tc.expectErr, err) 439 } 440 continue 441 } 442 if err != nil { 443 t.Errorf("test %d, want no error, have %v", i, err) 444 continue 445 } 446 have, _ := json.Marshal(result) 447 want := tc.want 448 if string(have) != want { 449 t.Errorf("test %d, result mismatch, have\n%v\n, want\n%v\n", i, string(have), want) 450 } 451 } 452 } 453 454 func TestTracingWithOverrides(t *testing.T) { 455 t.Parallel() 456 // Initialize test accounts 457 accounts := newAccounts(3) 458 storageAccount := common.Address{0x13, 37} 459 genesis := &core.Genesis{ 460 Config: params.TestChainConfig, 461 Alloc: core.GenesisAlloc{ 462 accounts[0].addr: {Balance: big.NewInt(params.Ether)}, 463 accounts[1].addr: {Balance: big.NewInt(params.Ether)}, 464 accounts[2].addr: {Balance: big.NewInt(params.Ether)}, 465 // An account with existing storage 466 storageAccount: { 467 Balance: new(big.Int), 468 Storage: map[common.Hash]common.Hash{ 469 common.HexToHash("0x03"): common.HexToHash("0x33"), 470 common.HexToHash("0x04"): common.HexToHash("0x44"), 471 }, 472 }, 473 }, 474 } 475 genBlocks := 10 476 signer := types.HomesteadSigner{} 477 backend := newTestBackend(t, genBlocks, genesis, func(i int, b *core.BlockGen) { 478 // Transfer from account[0] to account[1] 479 // value: 1000 wei 480 // fee: 0 wei 481 tx, _ := types.SignTx(types.NewTransaction(uint64(i), accounts[1].addr, big.NewInt(1000), params.TxGas, b.BaseFee(), nil), signer, accounts[0].key) 482 b.AddTx(tx) 483 }) 484 defer backend.chain.Stop() 485 api := NewAPI(backend) 486 randomAccounts := newAccounts(3) 487 type res struct { 488 Gas int 489 Failed bool 490 ReturnValue string 491 } 492 var testSuite = []struct { 493 blockNumber rpc.BlockNumber 494 call ethapi.TransactionArgs 495 config *TraceCallConfig 496 expectErr error 497 want string 498 }{ 499 // Call which can only succeed if state is state overridden 500 { 501 blockNumber: rpc.LatestBlockNumber, 502 call: ethapi.TransactionArgs{ 503 From: &randomAccounts[0].addr, 504 To: &randomAccounts[1].addr, 505 Value: (*hexutil.Big)(big.NewInt(1000)), 506 }, 507 config: &TraceCallConfig{ 508 StateOverrides: ðapi.StateOverride{ 509 randomAccounts[0].addr: ethapi.OverrideAccount{Balance: newRPCBalance(new(big.Int).Mul(big.NewInt(1), big.NewInt(params.Ether)))}, 510 }, 511 }, 512 want: `{"gas":21000,"failed":false,"returnValue":""}`, 513 }, 514 // Invalid call without state overriding 515 { 516 blockNumber: rpc.LatestBlockNumber, 517 call: ethapi.TransactionArgs{ 518 From: &randomAccounts[0].addr, 519 To: &randomAccounts[1].addr, 520 Value: (*hexutil.Big)(big.NewInt(1000)), 521 }, 522 config: &TraceCallConfig{}, 523 expectErr: core.ErrInsufficientFunds, 524 }, 525 // Successful simple contract call 526 // 527 // // SPDX-License-Identifier: GPL-3.0 528 // 529 // pragma solidity >=0.7.0 <0.8.0; 530 // 531 // /** 532 // * @title Storage 533 // * @dev Store & retrieve value in a variable 534 // */ 535 // contract Storage { 536 // uint256 public number; 537 // constructor() { 538 // number = block.number; 539 // } 540 // } 541 { 542 blockNumber: rpc.LatestBlockNumber, 543 call: ethapi.TransactionArgs{ 544 From: &randomAccounts[0].addr, 545 To: &randomAccounts[2].addr, 546 Data: newRPCBytes(common.Hex2Bytes("8381f58a")), // call number() 547 }, 548 config: &TraceCallConfig{ 549 //Tracer: &tracer, 550 StateOverrides: ðapi.StateOverride{ 551 randomAccounts[2].addr: ethapi.OverrideAccount{ 552 Code: newRPCBytes(common.Hex2Bytes("6080604052348015600f57600080fd5b506004361060285760003560e01c80638381f58a14602d575b600080fd5b60336049565b6040518082815260200191505060405180910390f35b6000548156fea2646970667358221220eab35ffa6ab2adfe380772a48b8ba78e82a1b820a18fcb6f59aa4efb20a5f60064736f6c63430007040033")), 553 StateDiff: newStates([]common.Hash{{}}, []common.Hash{common.BigToHash(big.NewInt(123))}), 554 }, 555 }, 556 }, 557 want: `{"gas":23347,"failed":false,"returnValue":"000000000000000000000000000000000000000000000000000000000000007b"}`, 558 }, 559 { // Override blocknumber 560 blockNumber: rpc.LatestBlockNumber, 561 call: ethapi.TransactionArgs{ 562 From: &accounts[0].addr, 563 // BLOCKNUMBER PUSH1 MSTORE 564 Input: newRPCBytes(common.Hex2Bytes("4360005260206000f3")), 565 //&hexutil.Bytes{0x43}, // blocknumber 566 }, 567 config: &TraceCallConfig{ 568 BlockOverrides: ðapi.BlockOverrides{Number: (*hexutil.Big)(big.NewInt(0x1337))}, 569 }, 570 want: `{"gas":59537,"failed":false,"returnValue":"0000000000000000000000000000000000000000000000000000000000001337"}`, 571 }, 572 { // Override blocknumber, and query a blockhash 573 blockNumber: rpc.LatestBlockNumber, 574 call: ethapi.TransactionArgs{ 575 From: &accounts[0].addr, 576 Input: &hexutil.Bytes{ 577 0x60, 0x00, 0x40, // BLOCKHASH(0) 578 0x60, 0x00, 0x52, // STORE memory offset 0 579 0x61, 0x13, 0x36, 0x40, // BLOCKHASH(0x1336) 580 0x60, 0x20, 0x52, // STORE memory offset 32 581 0x61, 0x13, 0x37, 0x40, // BLOCKHASH(0x1337) 582 0x60, 0x40, 0x52, // STORE memory offset 64 583 0x60, 0x60, 0x60, 0x00, 0xf3, // RETURN (0-96) 584 585 }, // blocknumber 586 }, 587 config: &TraceCallConfig{ 588 BlockOverrides: ðapi.BlockOverrides{Number: (*hexutil.Big)(big.NewInt(0x1337))}, 589 }, 590 want: `{"gas":72666,"failed":false,"returnValue":"000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"}`, 591 }, 592 /* 593 pragma solidity =0.8.12; 594 595 contract Test { 596 uint private x; 597 598 function test2() external { 599 x = 1337; 600 revert(); 601 } 602 603 function test() external returns (uint) { 604 x = 1; 605 try this.test2() {} catch (bytes memory) {} 606 return x; 607 } 608 } 609 */ 610 { // First with only code override, not storage override 611 blockNumber: rpc.LatestBlockNumber, 612 call: ethapi.TransactionArgs{ 613 From: &randomAccounts[0].addr, 614 To: &randomAccounts[2].addr, 615 Data: newRPCBytes(common.Hex2Bytes("f8a8fd6d")), // 616 }, 617 config: &TraceCallConfig{ 618 StateOverrides: ðapi.StateOverride{ 619 randomAccounts[2].addr: ethapi.OverrideAccount{ 620 Code: newRPCBytes(common.Hex2Bytes("6080604052348015600f57600080fd5b506004361060325760003560e01c806366e41cb7146037578063f8a8fd6d14603f575b600080fd5b603d6057565b005b60456062565b60405190815260200160405180910390f35b610539600090815580fd5b60006001600081905550306001600160a01b03166366e41cb76040518163ffffffff1660e01b8152600401600060405180830381600087803b15801560a657600080fd5b505af192505050801560b6575060015b60e9573d80801560e1576040519150601f19603f3d011682016040523d82523d6000602084013e60e6565b606091505b50505b506000549056fea26469706673582212205ce45de745a5308f713cb2f448589177ba5a442d1a2eff945afaa8915961b4d064736f6c634300080c0033")), 621 }, 622 }, 623 }, 624 want: `{"gas":44100,"failed":false,"returnValue":"0000000000000000000000000000000000000000000000000000000000000001"}`, 625 }, 626 { // Same again, this time with storage override 627 blockNumber: rpc.LatestBlockNumber, 628 call: ethapi.TransactionArgs{ 629 From: &randomAccounts[0].addr, 630 To: &randomAccounts[2].addr, 631 Data: newRPCBytes(common.Hex2Bytes("f8a8fd6d")), // 632 }, 633 config: &TraceCallConfig{ 634 StateOverrides: ðapi.StateOverride{ 635 randomAccounts[2].addr: ethapi.OverrideAccount{ 636 Code: newRPCBytes(common.Hex2Bytes("6080604052348015600f57600080fd5b506004361060325760003560e01c806366e41cb7146037578063f8a8fd6d14603f575b600080fd5b603d6057565b005b60456062565b60405190815260200160405180910390f35b610539600090815580fd5b60006001600081905550306001600160a01b03166366e41cb76040518163ffffffff1660e01b8152600401600060405180830381600087803b15801560a657600080fd5b505af192505050801560b6575060015b60e9573d80801560e1576040519150601f19603f3d011682016040523d82523d6000602084013e60e6565b606091505b50505b506000549056fea26469706673582212205ce45de745a5308f713cb2f448589177ba5a442d1a2eff945afaa8915961b4d064736f6c634300080c0033")), 637 State: newStates([]common.Hash{{}}, []common.Hash{{}}), 638 }, 639 }, 640 }, 641 //want: `{"gas":46900,"failed":false,"returnValue":"0000000000000000000000000000000000000000000000000000000000000539"}`, 642 want: `{"gas":44100,"failed":false,"returnValue":"0000000000000000000000000000000000000000000000000000000000000001"}`, 643 }, 644 { // No state override 645 blockNumber: rpc.LatestBlockNumber, 646 call: ethapi.TransactionArgs{ 647 From: &randomAccounts[0].addr, 648 To: &storageAccount, 649 Data: newRPCBytes(common.Hex2Bytes("f8a8fd6d")), // 650 }, 651 config: &TraceCallConfig{ 652 StateOverrides: ðapi.StateOverride{ 653 storageAccount: ethapi.OverrideAccount{ 654 Code: newRPCBytes([]byte{ 655 // SLOAD(3) + SLOAD(4) (which is 0x77) 656 byte(vm.PUSH1), 0x04, 657 byte(vm.SLOAD), 658 byte(vm.PUSH1), 0x03, 659 byte(vm.SLOAD), 660 byte(vm.ADD), 661 // 0x77 -> MSTORE(0) 662 byte(vm.PUSH1), 0x00, 663 byte(vm.MSTORE), 664 // RETURN (0, 32) 665 byte(vm.PUSH1), 32, 666 byte(vm.PUSH1), 00, 667 byte(vm.RETURN), 668 }), 669 }, 670 }, 671 }, 672 want: `{"gas":25288,"failed":false,"returnValue":"0000000000000000000000000000000000000000000000000000000000000077"}`, 673 }, 674 { // Full state override 675 // The original storage is 676 // 3: 0x33 677 // 4: 0x44 678 // With a full override, where we set 3:0x11, the slot 4 should be 679 // removed. So SLOT(3)+SLOT(4) should be 0x11. 680 blockNumber: rpc.LatestBlockNumber, 681 call: ethapi.TransactionArgs{ 682 From: &randomAccounts[0].addr, 683 To: &storageAccount, 684 Data: newRPCBytes(common.Hex2Bytes("f8a8fd6d")), // 685 }, 686 config: &TraceCallConfig{ 687 StateOverrides: ðapi.StateOverride{ 688 storageAccount: ethapi.OverrideAccount{ 689 Code: newRPCBytes([]byte{ 690 // SLOAD(3) + SLOAD(4) (which is now 0x11 + 0x00) 691 byte(vm.PUSH1), 0x04, 692 byte(vm.SLOAD), 693 byte(vm.PUSH1), 0x03, 694 byte(vm.SLOAD), 695 byte(vm.ADD), 696 // 0x11 -> MSTORE(0) 697 byte(vm.PUSH1), 0x00, 698 byte(vm.MSTORE), 699 // RETURN (0, 32) 700 byte(vm.PUSH1), 32, 701 byte(vm.PUSH1), 00, 702 byte(vm.RETURN), 703 }), 704 State: newStates( 705 []common.Hash{common.HexToHash("0x03")}, 706 []common.Hash{common.HexToHash("0x11")}), 707 }, 708 }, 709 }, 710 want: `{"gas":25288,"failed":false,"returnValue":"0000000000000000000000000000000000000000000000000000000000000011"}`, 711 }, 712 { // Partial state override 713 // The original storage is 714 // 3: 0x33 715 // 4: 0x44 716 // With a partial override, where we set 3:0x11, the slot 4 as before. 717 // So SLOT(3)+SLOT(4) should be 0x55. 718 blockNumber: rpc.LatestBlockNumber, 719 call: ethapi.TransactionArgs{ 720 From: &randomAccounts[0].addr, 721 To: &storageAccount, 722 Data: newRPCBytes(common.Hex2Bytes("f8a8fd6d")), // 723 }, 724 config: &TraceCallConfig{ 725 StateOverrides: ðapi.StateOverride{ 726 storageAccount: ethapi.OverrideAccount{ 727 Code: newRPCBytes([]byte{ 728 // SLOAD(3) + SLOAD(4) (which is now 0x11 + 0x44) 729 byte(vm.PUSH1), 0x04, 730 byte(vm.SLOAD), 731 byte(vm.PUSH1), 0x03, 732 byte(vm.SLOAD), 733 byte(vm.ADD), 734 // 0x55 -> MSTORE(0) 735 byte(vm.PUSH1), 0x00, 736 byte(vm.MSTORE), 737 // RETURN (0, 32) 738 byte(vm.PUSH1), 32, 739 byte(vm.PUSH1), 00, 740 byte(vm.RETURN), 741 }), 742 StateDiff: &map[common.Hash]common.Hash{ 743 common.HexToHash("0x03"): common.HexToHash("0x11"), 744 }, 745 }, 746 }, 747 }, 748 want: `{"gas":25288,"failed":false,"returnValue":"0000000000000000000000000000000000000000000000000000000000000055"}`, 749 }, 750 } 751 for i, tc := range testSuite { 752 result, err := api.TraceCall(context.Background(), tc.call, rpc.BlockNumberOrHash{BlockNumber: &tc.blockNumber}, tc.config) 753 if tc.expectErr != nil { 754 if err == nil { 755 t.Errorf("test %d: want error %v, have nothing", i, tc.expectErr) 756 continue 757 } 758 if !errors.Is(err, tc.expectErr) { 759 t.Errorf("test %d: error mismatch, want %v, have %v", i, tc.expectErr, err) 760 } 761 continue 762 } 763 if err != nil { 764 t.Errorf("test %d: want no error, have %v", i, err) 765 continue 766 } 767 // Turn result into res-struct 768 var ( 769 have res 770 want res 771 ) 772 resBytes, _ := json.Marshal(result) 773 json.Unmarshal(resBytes, &have) 774 json.Unmarshal([]byte(tc.want), &want) 775 if !reflect.DeepEqual(have, want) { 776 t.Logf("result: %v\n", string(resBytes)) 777 t.Errorf("test %d, result mismatch, have\n%v\n, want\n%v\n", i, have, want) 778 } 779 } 780 } 781 782 type Account struct { 783 key *ecdsa.PrivateKey 784 addr common.Address 785 } 786 787 func newAccounts(n int) (accounts []Account) { 788 for i := 0; i < n; i++ { 789 key, _ := crypto.GenerateKey() 790 addr := crypto.PubkeyToAddress(key.PublicKey) 791 accounts = append(accounts, Account{key: key, addr: addr}) 792 } 793 slices.SortFunc(accounts, func(a, b Account) int { return a.addr.Cmp(b.addr) }) 794 return accounts 795 } 796 797 func newRPCBalance(balance *big.Int) **hexutil.Big { 798 rpcBalance := (*hexutil.Big)(balance) 799 return &rpcBalance 800 } 801 802 func newRPCBytes(bytes []byte) *hexutil.Bytes { 803 rpcBytes := hexutil.Bytes(bytes) 804 return &rpcBytes 805 } 806 807 func newStates(keys []common.Hash, vals []common.Hash) *map[common.Hash]common.Hash { 808 if len(keys) != len(vals) { 809 panic("invalid input") 810 } 811 m := make(map[common.Hash]common.Hash) 812 for i := 0; i < len(keys); i++ { 813 m[keys[i]] = vals[i] 814 } 815 return &m 816 } 817 818 func TestTraceChain(t *testing.T) { 819 // Initialize test accounts 820 accounts := newAccounts(3) 821 genesis := &core.Genesis{ 822 Config: params.TestChainConfig, 823 Alloc: core.GenesisAlloc{ 824 accounts[0].addr: {Balance: big.NewInt(params.Ether)}, 825 accounts[1].addr: {Balance: big.NewInt(params.Ether)}, 826 accounts[2].addr: {Balance: big.NewInt(params.Ether)}, 827 }, 828 } 829 genBlocks := 50 830 signer := types.HomesteadSigner{} 831 832 var ( 833 ref atomic.Uint32 // total refs has made 834 rel atomic.Uint32 // total rels has made 835 nonce uint64 836 ) 837 backend := newTestBackend(t, genBlocks, genesis, func(i int, b *core.BlockGen) { 838 // Transfer from account[0] to account[1] 839 // value: 1000 wei 840 // fee: 0 wei 841 for j := 0; j < i+1; j++ { 842 tx, _ := types.SignTx(types.NewTransaction(nonce, accounts[1].addr, big.NewInt(1000), params.TxGas, b.BaseFee(), nil), signer, accounts[0].key) 843 b.AddTx(tx) 844 nonce += 1 845 } 846 }) 847 backend.refHook = func() { ref.Add(1) } 848 backend.relHook = func() { rel.Add(1) } 849 api := NewAPI(backend) 850 851 single := `{"txHash":"0x0000000000000000000000000000000000000000000000000000000000000000","result":{"gas":21000,"failed":false,"returnValue":"","structLogs":[]}}` 852 var cases = []struct { 853 start uint64 854 end uint64 855 config *TraceConfig 856 }{ 857 {0, 50, nil}, // the entire chain range, blocks [1, 50] 858 {10, 20, nil}, // the middle chain range, blocks [11, 20] 859 } 860 for _, c := range cases { 861 ref.Store(0) 862 rel.Store(0) 863 864 from, _ := api.blockByNumber(context.Background(), rpc.BlockNumber(c.start)) 865 to, _ := api.blockByNumber(context.Background(), rpc.BlockNumber(c.end)) 866 resCh := api.traceChain(from, to, c.config, nil) 867 868 next := c.start + 1 869 for result := range resCh { 870 if have, want := uint64(result.Block), next; have != want { 871 t.Fatalf("unexpected tracing block, have %d want %d", have, want) 872 } 873 if have, want := len(result.Traces), int(next); have != want { 874 t.Fatalf("unexpected result length, have %d want %d", have, want) 875 } 876 for _, trace := range result.Traces { 877 trace.TxHash = common.Hash{} 878 blob, _ := json.Marshal(trace) 879 if have, want := string(blob), single; have != want { 880 t.Fatalf("unexpected tracing result, have\n%v\nwant:\n%v", have, want) 881 } 882 } 883 next += 1 884 } 885 if next != c.end+1 { 886 t.Error("Missing tracing block") 887 } 888 889 if nref, nrel := ref.Load(), rel.Load(); nref != nrel { 890 t.Errorf("Ref and deref actions are not equal, ref %d rel %d", nref, nrel) 891 } 892 } 893 }