github.1485827954.workers.dev/ethereum/go-ethereum@v1.14.3/eth/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 "slices" 28 "sync/atomic" 29 "testing" 30 "time" 31 32 "github.com/ethereum/go-ethereum/common" 33 "github.com/ethereum/go-ethereum/common/hexutil" 34 "github.com/ethereum/go-ethereum/consensus" 35 "github.com/ethereum/go-ethereum/consensus/ethash" 36 "github.com/ethereum/go-ethereum/core" 37 "github.com/ethereum/go-ethereum/core/rawdb" 38 "github.com/ethereum/go-ethereum/core/state" 39 "github.com/ethereum/go-ethereum/core/types" 40 "github.com/ethereum/go-ethereum/core/vm" 41 "github.com/ethereum/go-ethereum/crypto" 42 "github.com/ethereum/go-ethereum/eth/tracers/logger" 43 "github.com/ethereum/go-ethereum/ethdb" 44 "github.com/ethereum/go-ethereum/internal/ethapi" 45 "github.com/ethereum/go-ethereum/params" 46 "github.com/ethereum/go-ethereum/rpc" 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 ethdb.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 // newTestBackend 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) (bool, *types.Transaction, common.Hash, uint64, uint64, error) { 117 tx, hash, blockNumber, index := rawdb.ReadTransaction(b.chaindb, txHash) 118 return tx != nil, 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() ethdb.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) (*types.Transaction, 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 tx, 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: types.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 nonce := uint64(0) 204 backend := newTestBackend(t, genBlocks, genesis, func(i int, b *core.BlockGen) { 205 // Transfer from account[0] to account[1] 206 // value: 1000 wei 207 // fee: 0 wei 208 tx, _ := types.SignTx(types.NewTx(&types.LegacyTx{ 209 Nonce: nonce, 210 To: &accounts[1].addr, 211 Value: big.NewInt(1000), 212 Gas: params.TxGas, 213 GasPrice: b.BaseFee(), 214 Data: nil}), 215 signer, accounts[0].key) 216 b.AddTx(tx) 217 nonce++ 218 219 if i == genBlocks-2 { 220 // Transfer from account[0] to account[2] 221 tx, _ = types.SignTx(types.NewTx(&types.LegacyTx{ 222 Nonce: nonce, 223 To: &accounts[2].addr, 224 Value: big.NewInt(1000), 225 Gas: params.TxGas, 226 GasPrice: b.BaseFee(), 227 Data: nil}), 228 signer, accounts[0].key) 229 b.AddTx(tx) 230 nonce++ 231 232 // Transfer from account[0] to account[1] again 233 tx, _ = types.SignTx(types.NewTx(&types.LegacyTx{ 234 Nonce: nonce, 235 To: &accounts[1].addr, 236 Value: big.NewInt(1000), 237 Gas: params.TxGas, 238 GasPrice: b.BaseFee(), 239 Data: nil}), 240 signer, accounts[0].key) 241 b.AddTx(tx) 242 nonce++ 243 } 244 }) 245 246 uintPtr := func(i int) *hexutil.Uint { x := hexutil.Uint(i); return &x } 247 248 defer backend.teardown() 249 api := NewAPI(backend) 250 var testSuite = []struct { 251 blockNumber rpc.BlockNumber 252 call ethapi.TransactionArgs 253 config *TraceCallConfig 254 expectErr error 255 expect string 256 }{ 257 // Standard JSON trace upon the genesis, plain transfer. 258 { 259 blockNumber: rpc.BlockNumber(0), 260 call: ethapi.TransactionArgs{ 261 From: &accounts[0].addr, 262 To: &accounts[1].addr, 263 Value: (*hexutil.Big)(big.NewInt(1000)), 264 }, 265 config: nil, 266 expectErr: nil, 267 expect: `{"gas":21000,"failed":false,"returnValue":"","structLogs":[]}`, 268 }, 269 // Standard JSON trace upon the head, plain transfer. 270 { 271 blockNumber: rpc.BlockNumber(genBlocks), 272 call: ethapi.TransactionArgs{ 273 From: &accounts[0].addr, 274 To: &accounts[1].addr, 275 Value: (*hexutil.Big)(big.NewInt(1000)), 276 }, 277 config: nil, 278 expectErr: nil, 279 expect: `{"gas":21000,"failed":false,"returnValue":"","structLogs":[]}`, 280 }, 281 // Upon the last state, default to the post block's state 282 { 283 blockNumber: rpc.BlockNumber(genBlocks - 1), 284 call: ethapi.TransactionArgs{ 285 From: &accounts[2].addr, 286 To: &accounts[0].addr, 287 Value: (*hexutil.Big)(new(big.Int).Add(big.NewInt(params.Ether), big.NewInt(100))), 288 }, 289 config: nil, 290 expect: `{"gas":21000,"failed":false,"returnValue":"","structLogs":[]}`, 291 }, 292 // Before the first transaction, should be failed 293 { 294 blockNumber: rpc.BlockNumber(genBlocks - 1), 295 call: ethapi.TransactionArgs{ 296 From: &accounts[2].addr, 297 To: &accounts[0].addr, 298 Value: (*hexutil.Big)(new(big.Int).Add(big.NewInt(params.Ether), big.NewInt(100))), 299 }, 300 config: &TraceCallConfig{TxIndex: uintPtr(0)}, 301 expectErr: fmt.Errorf("tracing failed: insufficient funds for gas * price + value: address %s have 1000000000000000000 want 1000000000000000100", accounts[2].addr), 302 }, 303 // Before the target transaction, should be failed 304 { 305 blockNumber: rpc.BlockNumber(genBlocks - 1), 306 call: ethapi.TransactionArgs{ 307 From: &accounts[2].addr, 308 To: &accounts[0].addr, 309 Value: (*hexutil.Big)(new(big.Int).Add(big.NewInt(params.Ether), big.NewInt(100))), 310 }, 311 config: &TraceCallConfig{TxIndex: uintPtr(1)}, 312 expectErr: fmt.Errorf("tracing failed: insufficient funds for gas * price + value: address %s have 1000000000000000000 want 1000000000000000100", accounts[2].addr), 313 }, 314 // After the target transaction, should be succeed 315 { 316 blockNumber: rpc.BlockNumber(genBlocks - 1), 317 call: ethapi.TransactionArgs{ 318 From: &accounts[2].addr, 319 To: &accounts[0].addr, 320 Value: (*hexutil.Big)(new(big.Int).Add(big.NewInt(params.Ether), big.NewInt(100))), 321 }, 322 config: &TraceCallConfig{TxIndex: uintPtr(2)}, 323 expectErr: nil, 324 expect: `{"gas":21000,"failed":false,"returnValue":"","structLogs":[]}`, 325 }, 326 // Standard JSON trace upon the non-existent block, error expects 327 { 328 blockNumber: rpc.BlockNumber(genBlocks + 1), 329 call: ethapi.TransactionArgs{ 330 From: &accounts[0].addr, 331 To: &accounts[1].addr, 332 Value: (*hexutil.Big)(big.NewInt(1000)), 333 }, 334 config: nil, 335 expectErr: fmt.Errorf("block #%d not found", genBlocks+1), 336 //expect: nil, 337 }, 338 // Standard JSON trace upon the latest block 339 { 340 blockNumber: rpc.LatestBlockNumber, 341 call: ethapi.TransactionArgs{ 342 From: &accounts[0].addr, 343 To: &accounts[1].addr, 344 Value: (*hexutil.Big)(big.NewInt(1000)), 345 }, 346 config: nil, 347 expectErr: nil, 348 expect: `{"gas":21000,"failed":false,"returnValue":"","structLogs":[]}`, 349 }, 350 // Tracing on 'pending' should fail: 351 { 352 blockNumber: rpc.PendingBlockNumber, 353 call: ethapi.TransactionArgs{ 354 From: &accounts[0].addr, 355 To: &accounts[1].addr, 356 Value: (*hexutil.Big)(big.NewInt(1000)), 357 }, 358 config: nil, 359 expectErr: errors.New("tracing on top of pending is not supported"), 360 }, 361 { 362 blockNumber: rpc.LatestBlockNumber, 363 call: ethapi.TransactionArgs{ 364 From: &accounts[0].addr, 365 Input: &hexutil.Bytes{0x43}, // blocknumber 366 }, 367 config: &TraceCallConfig{ 368 BlockOverrides: ðapi.BlockOverrides{Number: (*hexutil.Big)(big.NewInt(0x1337))}, 369 }, 370 expectErr: nil, 371 expect: ` {"gas":53018,"failed":false,"returnValue":"","structLogs":[ 372 {"pc":0,"op":"NUMBER","gas":24946984,"gasCost":2,"depth":1,"stack":[]}, 373 {"pc":1,"op":"STOP","gas":24946982,"gasCost":0,"depth":1,"stack":["0x1337"]}]}`, 374 }, 375 } 376 for i, testspec := range testSuite { 377 result, err := api.TraceCall(context.Background(), testspec.call, rpc.BlockNumberOrHash{BlockNumber: &testspec.blockNumber}, testspec.config) 378 if testspec.expectErr != nil { 379 if err == nil { 380 t.Errorf("test %d: expect error %v, got nothing", i, testspec.expectErr) 381 continue 382 } 383 if !reflect.DeepEqual(err.Error(), testspec.expectErr.Error()) { 384 t.Errorf("test %d: error mismatch, want '%v', got '%v'", i, testspec.expectErr, err) 385 } 386 } else { 387 if err != nil { 388 t.Errorf("test %d: expect no error, got %v", i, err) 389 continue 390 } 391 var have *logger.ExecutionResult 392 if err := json.Unmarshal(result.(json.RawMessage), &have); err != nil { 393 t.Errorf("test %d: failed to unmarshal result %v", i, err) 394 } 395 var want *logger.ExecutionResult 396 if err := json.Unmarshal([]byte(testspec.expect), &want); err != nil { 397 t.Errorf("test %d: failed to unmarshal result %v", i, err) 398 } 399 if !reflect.DeepEqual(have, want) { 400 t.Errorf("test %d: result mismatch, want %v, got %v", i, testspec.expect, string(result.(json.RawMessage))) 401 } 402 } 403 } 404 } 405 406 func TestTraceTransaction(t *testing.T) { 407 t.Parallel() 408 409 // Initialize test accounts 410 accounts := newAccounts(2) 411 genesis := &core.Genesis{ 412 Config: params.TestChainConfig, 413 Alloc: types.GenesisAlloc{ 414 accounts[0].addr: {Balance: big.NewInt(params.Ether)}, 415 accounts[1].addr: {Balance: big.NewInt(params.Ether)}, 416 }, 417 } 418 target := common.Hash{} 419 signer := types.HomesteadSigner{} 420 backend := newTestBackend(t, 1, genesis, func(i int, b *core.BlockGen) { 421 // Transfer from account[0] to account[1] 422 // value: 1000 wei 423 // fee: 0 wei 424 tx, _ := types.SignTx(types.NewTx(&types.LegacyTx{ 425 Nonce: uint64(i), 426 To: &accounts[1].addr, 427 Value: big.NewInt(1000), 428 Gas: params.TxGas, 429 GasPrice: b.BaseFee(), 430 Data: nil}), 431 signer, accounts[0].key) 432 b.AddTx(tx) 433 target = tx.Hash() 434 }) 435 defer backend.chain.Stop() 436 api := NewAPI(backend) 437 result, err := api.TraceTransaction(context.Background(), target, nil) 438 if err != nil { 439 t.Errorf("Failed to trace transaction %v", err) 440 } 441 var have *logger.ExecutionResult 442 if err := json.Unmarshal(result.(json.RawMessage), &have); err != nil { 443 t.Errorf("failed to unmarshal result %v", err) 444 } 445 if !reflect.DeepEqual(have, &logger.ExecutionResult{ 446 Gas: params.TxGas, 447 Failed: false, 448 ReturnValue: "", 449 StructLogs: []logger.StructLogRes{}, 450 }) { 451 t.Error("Transaction tracing result is different") 452 } 453 454 // Test non-existent transaction 455 _, err = api.TraceTransaction(context.Background(), common.Hash{42}, nil) 456 if !errors.Is(err, errTxNotFound) { 457 t.Fatalf("want %v, have %v", errTxNotFound, err) 458 } 459 } 460 461 func TestTraceBlock(t *testing.T) { 462 t.Parallel() 463 464 // Initialize test accounts 465 accounts := newAccounts(3) 466 genesis := &core.Genesis{ 467 Config: params.TestChainConfig, 468 Alloc: types.GenesisAlloc{ 469 accounts[0].addr: {Balance: big.NewInt(params.Ether)}, 470 accounts[1].addr: {Balance: big.NewInt(params.Ether)}, 471 accounts[2].addr: {Balance: big.NewInt(params.Ether)}, 472 }, 473 } 474 genBlocks := 10 475 signer := types.HomesteadSigner{} 476 var txHash common.Hash 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.NewTx(&types.LegacyTx{ 482 Nonce: uint64(i), 483 To: &accounts[1].addr, 484 Value: big.NewInt(1000), 485 Gas: params.TxGas, 486 GasPrice: b.BaseFee(), 487 Data: nil}), 488 signer, accounts[0].key) 489 b.AddTx(tx) 490 txHash = tx.Hash() 491 }) 492 defer backend.chain.Stop() 493 api := NewAPI(backend) 494 495 var testSuite = []struct { 496 blockNumber rpc.BlockNumber 497 config *TraceConfig 498 want string 499 expectErr error 500 }{ 501 // Trace genesis block, expect error 502 { 503 blockNumber: rpc.BlockNumber(0), 504 expectErr: errors.New("genesis is not traceable"), 505 }, 506 // Trace head block 507 { 508 blockNumber: rpc.BlockNumber(genBlocks), 509 want: fmt.Sprintf(`[{"txHash":"%v","result":{"gas":21000,"failed":false,"returnValue":"","structLogs":[]}}]`, txHash), 510 }, 511 // Trace non-existent block 512 { 513 blockNumber: rpc.BlockNumber(genBlocks + 1), 514 expectErr: fmt.Errorf("block #%d not found", genBlocks+1), 515 }, 516 // Trace latest block 517 { 518 blockNumber: rpc.LatestBlockNumber, 519 want: fmt.Sprintf(`[{"txHash":"%v","result":{"gas":21000,"failed":false,"returnValue":"","structLogs":[]}}]`, txHash), 520 }, 521 // Trace pending block 522 { 523 blockNumber: rpc.PendingBlockNumber, 524 want: fmt.Sprintf(`[{"txHash":"%v","result":{"gas":21000,"failed":false,"returnValue":"","structLogs":[]}}]`, txHash), 525 }, 526 } 527 for i, tc := range testSuite { 528 result, err := api.TraceBlockByNumber(context.Background(), tc.blockNumber, tc.config) 529 if tc.expectErr != nil { 530 if err == nil { 531 t.Errorf("test %d, want error %v", i, tc.expectErr) 532 continue 533 } 534 if !reflect.DeepEqual(err, tc.expectErr) { 535 t.Errorf("test %d: error mismatch, want %v, get %v", i, tc.expectErr, err) 536 } 537 continue 538 } 539 if err != nil { 540 t.Errorf("test %d, want no error, have %v", i, err) 541 continue 542 } 543 have, _ := json.Marshal(result) 544 want := tc.want 545 if string(have) != want { 546 t.Errorf("test %d, result mismatch, have\n%v\n, want\n%v\n", i, string(have), want) 547 } 548 } 549 } 550 551 func TestTracingWithOverrides(t *testing.T) { 552 t.Parallel() 553 // Initialize test accounts 554 accounts := newAccounts(3) 555 storageAccount := common.Address{0x13, 37} 556 genesis := &core.Genesis{ 557 Config: params.TestChainConfig, 558 Alloc: types.GenesisAlloc{ 559 accounts[0].addr: {Balance: big.NewInt(params.Ether)}, 560 accounts[1].addr: {Balance: big.NewInt(params.Ether)}, 561 accounts[2].addr: {Balance: big.NewInt(params.Ether)}, 562 // An account with existing storage 563 storageAccount: { 564 Balance: new(big.Int), 565 Storage: map[common.Hash]common.Hash{ 566 common.HexToHash("0x03"): common.HexToHash("0x33"), 567 common.HexToHash("0x04"): common.HexToHash("0x44"), 568 }, 569 }, 570 }, 571 } 572 genBlocks := 10 573 signer := types.HomesteadSigner{} 574 backend := newTestBackend(t, genBlocks, genesis, func(i int, b *core.BlockGen) { 575 // Transfer from account[0] to account[1] 576 // value: 1000 wei 577 // fee: 0 wei 578 tx, _ := types.SignTx(types.NewTx(&types.LegacyTx{ 579 Nonce: uint64(i), 580 To: &accounts[1].addr, 581 Value: big.NewInt(1000), 582 Gas: params.TxGas, 583 GasPrice: b.BaseFee(), 584 Data: nil}), 585 signer, accounts[0].key) 586 b.AddTx(tx) 587 }) 588 defer backend.chain.Stop() 589 api := NewAPI(backend) 590 randomAccounts := newAccounts(3) 591 type res struct { 592 Gas int 593 Failed bool 594 ReturnValue string 595 } 596 var testSuite = []struct { 597 blockNumber rpc.BlockNumber 598 call ethapi.TransactionArgs 599 config *TraceCallConfig 600 expectErr error 601 want string 602 }{ 603 // Call which can only succeed if state is state overridden 604 { 605 blockNumber: rpc.LatestBlockNumber, 606 call: ethapi.TransactionArgs{ 607 From: &randomAccounts[0].addr, 608 To: &randomAccounts[1].addr, 609 Value: (*hexutil.Big)(big.NewInt(1000)), 610 }, 611 config: &TraceCallConfig{ 612 StateOverrides: ðapi.StateOverride{ 613 randomAccounts[0].addr: ethapi.OverrideAccount{Balance: newRPCBalance(new(big.Int).Mul(big.NewInt(1), big.NewInt(params.Ether)))}, 614 }, 615 }, 616 want: `{"gas":21000,"failed":false,"returnValue":""}`, 617 }, 618 // Invalid call without state overriding 619 { 620 blockNumber: rpc.LatestBlockNumber, 621 call: ethapi.TransactionArgs{ 622 From: &randomAccounts[0].addr, 623 To: &randomAccounts[1].addr, 624 Value: (*hexutil.Big)(big.NewInt(1000)), 625 }, 626 config: &TraceCallConfig{}, 627 expectErr: core.ErrInsufficientFunds, 628 }, 629 // Successful simple contract call 630 // 631 // // SPDX-License-Identifier: GPL-3.0 632 // 633 // pragma solidity >=0.7.0 <0.8.0; 634 // 635 // /** 636 // * @title Storage 637 // * @dev Store & retrieve value in a variable 638 // */ 639 // contract Storage { 640 // uint256 public number; 641 // constructor() { 642 // number = block.number; 643 // } 644 // } 645 { 646 blockNumber: rpc.LatestBlockNumber, 647 call: ethapi.TransactionArgs{ 648 From: &randomAccounts[0].addr, 649 To: &randomAccounts[2].addr, 650 Data: newRPCBytes(common.Hex2Bytes("8381f58a")), // call number() 651 }, 652 config: &TraceCallConfig{ 653 //Tracer: &tracer, 654 StateOverrides: ðapi.StateOverride{ 655 randomAccounts[2].addr: ethapi.OverrideAccount{ 656 Code: newRPCBytes(common.Hex2Bytes("6080604052348015600f57600080fd5b506004361060285760003560e01c80638381f58a14602d575b600080fd5b60336049565b6040518082815260200191505060405180910390f35b6000548156fea2646970667358221220eab35ffa6ab2adfe380772a48b8ba78e82a1b820a18fcb6f59aa4efb20a5f60064736f6c63430007040033")), 657 StateDiff: newStates([]common.Hash{{}}, []common.Hash{common.BigToHash(big.NewInt(123))}), 658 }, 659 }, 660 }, 661 want: `{"gas":23347,"failed":false,"returnValue":"000000000000000000000000000000000000000000000000000000000000007b"}`, 662 }, 663 { // Override blocknumber 664 blockNumber: rpc.LatestBlockNumber, 665 call: ethapi.TransactionArgs{ 666 From: &accounts[0].addr, 667 // BLOCKNUMBER PUSH1 MSTORE 668 Input: newRPCBytes(common.Hex2Bytes("4360005260206000f3")), 669 }, 670 config: &TraceCallConfig{ 671 BlockOverrides: ðapi.BlockOverrides{Number: (*hexutil.Big)(big.NewInt(0x1337))}, 672 }, 673 want: `{"gas":59537,"failed":false,"returnValue":"0000000000000000000000000000000000000000000000000000000000001337"}`, 674 }, 675 { // Override blocknumber, and query a blockhash 676 blockNumber: rpc.LatestBlockNumber, 677 call: ethapi.TransactionArgs{ 678 From: &accounts[0].addr, 679 Input: &hexutil.Bytes{ 680 0x60, 0x00, 0x40, // BLOCKHASH(0) 681 0x60, 0x00, 0x52, // STORE memory offset 0 682 0x61, 0x13, 0x36, 0x40, // BLOCKHASH(0x1336) 683 0x60, 0x20, 0x52, // STORE memory offset 32 684 0x61, 0x13, 0x37, 0x40, // BLOCKHASH(0x1337) 685 0x60, 0x40, 0x52, // STORE memory offset 64 686 0x60, 0x60, 0x60, 0x00, 0xf3, // RETURN (0-96) 687 688 }, // blocknumber 689 }, 690 config: &TraceCallConfig{ 691 BlockOverrides: ðapi.BlockOverrides{Number: (*hexutil.Big)(big.NewInt(0x1337))}, 692 }, 693 want: `{"gas":72666,"failed":false,"returnValue":"000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"}`, 694 }, 695 /* 696 pragma solidity =0.8.12; 697 698 contract Test { 699 uint private x; 700 701 function test2() external { 702 x = 1337; 703 revert(); 704 } 705 706 function test() external returns (uint) { 707 x = 1; 708 try this.test2() {} catch (bytes memory) {} 709 return x; 710 } 711 } 712 */ 713 { // First with only code override, not storage override 714 blockNumber: rpc.LatestBlockNumber, 715 call: ethapi.TransactionArgs{ 716 From: &randomAccounts[0].addr, 717 To: &randomAccounts[2].addr, 718 Data: newRPCBytes(common.Hex2Bytes("f8a8fd6d")), // 719 }, 720 config: &TraceCallConfig{ 721 StateOverrides: ðapi.StateOverride{ 722 randomAccounts[2].addr: ethapi.OverrideAccount{ 723 Code: newRPCBytes(common.Hex2Bytes("6080604052348015600f57600080fd5b506004361060325760003560e01c806366e41cb7146037578063f8a8fd6d14603f575b600080fd5b603d6057565b005b60456062565b60405190815260200160405180910390f35b610539600090815580fd5b60006001600081905550306001600160a01b03166366e41cb76040518163ffffffff1660e01b8152600401600060405180830381600087803b15801560a657600080fd5b505af192505050801560b6575060015b60e9573d80801560e1576040519150601f19603f3d011682016040523d82523d6000602084013e60e6565b606091505b50505b506000549056fea26469706673582212205ce45de745a5308f713cb2f448589177ba5a442d1a2eff945afaa8915961b4d064736f6c634300080c0033")), 724 }, 725 }, 726 }, 727 want: `{"gas":44100,"failed":false,"returnValue":"0000000000000000000000000000000000000000000000000000000000000001"}`, 728 }, 729 { // Same again, this time with storage override 730 blockNumber: rpc.LatestBlockNumber, 731 call: ethapi.TransactionArgs{ 732 From: &randomAccounts[0].addr, 733 To: &randomAccounts[2].addr, 734 Data: newRPCBytes(common.Hex2Bytes("f8a8fd6d")), // 735 }, 736 config: &TraceCallConfig{ 737 StateOverrides: ðapi.StateOverride{ 738 randomAccounts[2].addr: ethapi.OverrideAccount{ 739 Code: newRPCBytes(common.Hex2Bytes("6080604052348015600f57600080fd5b506004361060325760003560e01c806366e41cb7146037578063f8a8fd6d14603f575b600080fd5b603d6057565b005b60456062565b60405190815260200160405180910390f35b610539600090815580fd5b60006001600081905550306001600160a01b03166366e41cb76040518163ffffffff1660e01b8152600401600060405180830381600087803b15801560a657600080fd5b505af192505050801560b6575060015b60e9573d80801560e1576040519150601f19603f3d011682016040523d82523d6000602084013e60e6565b606091505b50505b506000549056fea26469706673582212205ce45de745a5308f713cb2f448589177ba5a442d1a2eff945afaa8915961b4d064736f6c634300080c0033")), 740 State: newStates([]common.Hash{{}}, []common.Hash{{}}), 741 }, 742 }, 743 }, 744 //want: `{"gas":46900,"failed":false,"returnValue":"0000000000000000000000000000000000000000000000000000000000000539"}`, 745 want: `{"gas":44100,"failed":false,"returnValue":"0000000000000000000000000000000000000000000000000000000000000001"}`, 746 }, 747 { // No state override 748 blockNumber: rpc.LatestBlockNumber, 749 call: ethapi.TransactionArgs{ 750 From: &randomAccounts[0].addr, 751 To: &storageAccount, 752 Data: newRPCBytes(common.Hex2Bytes("f8a8fd6d")), // 753 }, 754 config: &TraceCallConfig{ 755 StateOverrides: ðapi.StateOverride{ 756 storageAccount: ethapi.OverrideAccount{ 757 Code: newRPCBytes([]byte{ 758 // SLOAD(3) + SLOAD(4) (which is 0x77) 759 byte(vm.PUSH1), 0x04, 760 byte(vm.SLOAD), 761 byte(vm.PUSH1), 0x03, 762 byte(vm.SLOAD), 763 byte(vm.ADD), 764 // 0x77 -> MSTORE(0) 765 byte(vm.PUSH1), 0x00, 766 byte(vm.MSTORE), 767 // RETURN (0, 32) 768 byte(vm.PUSH1), 32, 769 byte(vm.PUSH1), 00, 770 byte(vm.RETURN), 771 }), 772 }, 773 }, 774 }, 775 want: `{"gas":25288,"failed":false,"returnValue":"0000000000000000000000000000000000000000000000000000000000000077"}`, 776 }, 777 { // Full state override 778 // The original storage is 779 // 3: 0x33 780 // 4: 0x44 781 // With a full override, where we set 3:0x11, the slot 4 should be 782 // removed. So SLOT(3)+SLOT(4) should be 0x11. 783 blockNumber: rpc.LatestBlockNumber, 784 call: ethapi.TransactionArgs{ 785 From: &randomAccounts[0].addr, 786 To: &storageAccount, 787 Data: newRPCBytes(common.Hex2Bytes("f8a8fd6d")), // 788 }, 789 config: &TraceCallConfig{ 790 StateOverrides: ðapi.StateOverride{ 791 storageAccount: ethapi.OverrideAccount{ 792 Code: newRPCBytes([]byte{ 793 // SLOAD(3) + SLOAD(4) (which is now 0x11 + 0x00) 794 byte(vm.PUSH1), 0x04, 795 byte(vm.SLOAD), 796 byte(vm.PUSH1), 0x03, 797 byte(vm.SLOAD), 798 byte(vm.ADD), 799 // 0x11 -> MSTORE(0) 800 byte(vm.PUSH1), 0x00, 801 byte(vm.MSTORE), 802 // RETURN (0, 32) 803 byte(vm.PUSH1), 32, 804 byte(vm.PUSH1), 00, 805 byte(vm.RETURN), 806 }), 807 State: newStates( 808 []common.Hash{common.HexToHash("0x03")}, 809 []common.Hash{common.HexToHash("0x11")}), 810 }, 811 }, 812 }, 813 want: `{"gas":25288,"failed":false,"returnValue":"0000000000000000000000000000000000000000000000000000000000000011"}`, 814 }, 815 { // Partial state override 816 // The original storage is 817 // 3: 0x33 818 // 4: 0x44 819 // With a partial override, where we set 3:0x11, the slot 4 as before. 820 // So SLOT(3)+SLOT(4) should be 0x55. 821 blockNumber: rpc.LatestBlockNumber, 822 call: ethapi.TransactionArgs{ 823 From: &randomAccounts[0].addr, 824 To: &storageAccount, 825 Data: newRPCBytes(common.Hex2Bytes("f8a8fd6d")), // 826 }, 827 config: &TraceCallConfig{ 828 StateOverrides: ðapi.StateOverride{ 829 storageAccount: ethapi.OverrideAccount{ 830 Code: newRPCBytes([]byte{ 831 // SLOAD(3) + SLOAD(4) (which is now 0x11 + 0x44) 832 byte(vm.PUSH1), 0x04, 833 byte(vm.SLOAD), 834 byte(vm.PUSH1), 0x03, 835 byte(vm.SLOAD), 836 byte(vm.ADD), 837 // 0x55 -> MSTORE(0) 838 byte(vm.PUSH1), 0x00, 839 byte(vm.MSTORE), 840 // RETURN (0, 32) 841 byte(vm.PUSH1), 32, 842 byte(vm.PUSH1), 00, 843 byte(vm.RETURN), 844 }), 845 StateDiff: &map[common.Hash]common.Hash{ 846 common.HexToHash("0x03"): common.HexToHash("0x11"), 847 }, 848 }, 849 }, 850 }, 851 want: `{"gas":25288,"failed":false,"returnValue":"0000000000000000000000000000000000000000000000000000000000000055"}`, 852 }, 853 } 854 for i, tc := range testSuite { 855 result, err := api.TraceCall(context.Background(), tc.call, rpc.BlockNumberOrHash{BlockNumber: &tc.blockNumber}, tc.config) 856 if tc.expectErr != nil { 857 if err == nil { 858 t.Errorf("test %d: want error %v, have nothing", i, tc.expectErr) 859 continue 860 } 861 if !errors.Is(err, tc.expectErr) { 862 t.Errorf("test %d: error mismatch, want %v, have %v", i, tc.expectErr, err) 863 } 864 continue 865 } 866 if err != nil { 867 t.Errorf("test %d: want no error, have %v", i, err) 868 continue 869 } 870 // Turn result into res-struct 871 var ( 872 have res 873 want res 874 ) 875 resBytes, _ := json.Marshal(result) 876 json.Unmarshal(resBytes, &have) 877 json.Unmarshal([]byte(tc.want), &want) 878 if !reflect.DeepEqual(have, want) { 879 t.Logf("result: %v\n", string(resBytes)) 880 t.Errorf("test %d, result mismatch, have\n%v\n, want\n%v\n", i, have, want) 881 } 882 } 883 } 884 885 type Account struct { 886 key *ecdsa.PrivateKey 887 addr common.Address 888 } 889 890 func newAccounts(n int) (accounts []Account) { 891 for i := 0; i < n; i++ { 892 key, _ := crypto.GenerateKey() 893 addr := crypto.PubkeyToAddress(key.PublicKey) 894 accounts = append(accounts, Account{key: key, addr: addr}) 895 } 896 slices.SortFunc(accounts, func(a, b Account) int { return a.addr.Cmp(b.addr) }) 897 return accounts 898 } 899 900 func newRPCBalance(balance *big.Int) **hexutil.Big { 901 rpcBalance := (*hexutil.Big)(balance) 902 return &rpcBalance 903 } 904 905 func newRPCBytes(bytes []byte) *hexutil.Bytes { 906 rpcBytes := hexutil.Bytes(bytes) 907 return &rpcBytes 908 } 909 910 func newStates(keys []common.Hash, vals []common.Hash) *map[common.Hash]common.Hash { 911 if len(keys) != len(vals) { 912 panic("invalid input") 913 } 914 m := make(map[common.Hash]common.Hash) 915 for i := 0; i < len(keys); i++ { 916 m[keys[i]] = vals[i] 917 } 918 return &m 919 } 920 921 func TestTraceChain(t *testing.T) { 922 // Initialize test accounts 923 accounts := newAccounts(3) 924 genesis := &core.Genesis{ 925 Config: params.TestChainConfig, 926 Alloc: types.GenesisAlloc{ 927 accounts[0].addr: {Balance: big.NewInt(params.Ether)}, 928 accounts[1].addr: {Balance: big.NewInt(params.Ether)}, 929 accounts[2].addr: {Balance: big.NewInt(params.Ether)}, 930 }, 931 } 932 genBlocks := 50 933 signer := types.HomesteadSigner{} 934 935 var ( 936 ref atomic.Uint32 // total refs has made 937 rel atomic.Uint32 // total rels has made 938 nonce uint64 939 ) 940 backend := newTestBackend(t, genBlocks, genesis, func(i int, b *core.BlockGen) { 941 // Transfer from account[0] to account[1] 942 // value: 1000 wei 943 // fee: 0 wei 944 for j := 0; j < i+1; j++ { 945 tx, _ := types.SignTx(types.NewTransaction(nonce, accounts[1].addr, big.NewInt(1000), params.TxGas, b.BaseFee(), nil), signer, accounts[0].key) 946 b.AddTx(tx) 947 nonce += 1 948 } 949 }) 950 backend.refHook = func() { ref.Add(1) } 951 backend.relHook = func() { rel.Add(1) } 952 api := NewAPI(backend) 953 954 single := `{"txHash":"0x0000000000000000000000000000000000000000000000000000000000000000","result":{"gas":21000,"failed":false,"returnValue":"","structLogs":[]}}` 955 var cases = []struct { 956 start uint64 957 end uint64 958 config *TraceConfig 959 }{ 960 {0, 50, nil}, // the entire chain range, blocks [1, 50] 961 {10, 20, nil}, // the middle chain range, blocks [11, 20] 962 } 963 for _, c := range cases { 964 ref.Store(0) 965 rel.Store(0) 966 967 from, _ := api.blockByNumber(context.Background(), rpc.BlockNumber(c.start)) 968 to, _ := api.blockByNumber(context.Background(), rpc.BlockNumber(c.end)) 969 resCh := api.traceChain(from, to, c.config, nil) 970 971 next := c.start + 1 972 for result := range resCh { 973 if have, want := uint64(result.Block), next; have != want { 974 t.Fatalf("unexpected tracing block, have %d want %d", have, want) 975 } 976 if have, want := len(result.Traces), int(next); have != want { 977 t.Fatalf("unexpected result length, have %d want %d", have, want) 978 } 979 for _, trace := range result.Traces { 980 trace.TxHash = common.Hash{} 981 blob, _ := json.Marshal(trace) 982 if have, want := string(blob), single; have != want { 983 t.Fatalf("unexpected tracing result, have\n%v\nwant:\n%v", have, want) 984 } 985 } 986 next += 1 987 } 988 if next != c.end+1 { 989 t.Error("Missing tracing block") 990 } 991 992 if nref, nrel := ref.Load(), rel.Load(); nref != nrel { 993 t.Errorf("Ref and deref actions are not equal, ref %d rel %d", nref, nrel) 994 } 995 } 996 }