github.com/codysnider/go-ethereum@v1.10.18-0.20220420071915-14f4ae99222a/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 "bytes" 21 "context" 22 "crypto/ecdsa" 23 "encoding/json" 24 "errors" 25 "fmt" 26 "math/big" 27 "reflect" 28 "sort" 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 errTransactionNotFound = errors.New("transaction not found") 53 ) 54 55 type testBackend struct { 56 chainConfig *params.ChainConfig 57 engine consensus.Engine 58 chaindb ethdb.Database 59 chain *core.BlockChain 60 } 61 62 func newTestBackend(t *testing.T, n int, gspec *core.Genesis, generator func(i int, b *core.BlockGen)) *testBackend { 63 backend := &testBackend{ 64 chainConfig: params.TestChainConfig, 65 engine: ethash.NewFaker(), 66 chaindb: rawdb.NewMemoryDatabase(), 67 } 68 // Generate blocks for testing 69 gspec.Config = backend.chainConfig 70 var ( 71 gendb = rawdb.NewMemoryDatabase() 72 genesis = gspec.MustCommit(gendb) 73 ) 74 blocks, _ := core.GenerateChain(backend.chainConfig, genesis, backend.engine, gendb, n, generator) 75 76 // Import the canonical chain 77 gspec.MustCommit(backend.chaindb) 78 cacheConfig := &core.CacheConfig{ 79 TrieCleanLimit: 256, 80 TrieDirtyLimit: 256, 81 TrieTimeLimit: 5 * time.Minute, 82 SnapshotLimit: 0, 83 TrieDirtyDisabled: true, // Archive mode 84 } 85 chain, err := core.NewBlockChain(backend.chaindb, cacheConfig, backend.chainConfig, backend.engine, vm.Config{}, nil, nil) 86 if err != nil { 87 t.Fatalf("failed to create tester chain: %v", err) 88 } 89 if n, err := chain.InsertChain(blocks); err != nil { 90 t.Fatalf("block %d: failed to insert into chain: %v", n, err) 91 } 92 backend.chain = chain 93 return backend 94 } 95 96 func (b *testBackend) HeaderByHash(ctx context.Context, hash common.Hash) (*types.Header, error) { 97 return b.chain.GetHeaderByHash(hash), nil 98 } 99 100 func (b *testBackend) HeaderByNumber(ctx context.Context, number rpc.BlockNumber) (*types.Header, error) { 101 if number == rpc.PendingBlockNumber || number == rpc.LatestBlockNumber { 102 return b.chain.CurrentHeader(), nil 103 } 104 return b.chain.GetHeaderByNumber(uint64(number)), nil 105 } 106 107 func (b *testBackend) BlockByHash(ctx context.Context, hash common.Hash) (*types.Block, error) { 108 return b.chain.GetBlockByHash(hash), nil 109 } 110 111 func (b *testBackend) BlockByNumber(ctx context.Context, number rpc.BlockNumber) (*types.Block, error) { 112 if number == rpc.PendingBlockNumber || number == rpc.LatestBlockNumber { 113 return b.chain.CurrentBlock(), nil 114 } 115 return b.chain.GetBlockByNumber(uint64(number)), nil 116 } 117 118 func (b *testBackend) GetTransaction(ctx context.Context, txHash common.Hash) (*types.Transaction, common.Hash, uint64, uint64, error) { 119 tx, hash, blockNumber, index := rawdb.ReadTransaction(b.chaindb, txHash) 120 if tx == nil { 121 return nil, common.Hash{}, 0, 0, errTransactionNotFound 122 } 123 return tx, hash, blockNumber, index, nil 124 } 125 126 func (b *testBackend) RPCGasCap() uint64 { 127 return 25000000 128 } 129 130 func (b *testBackend) ChainConfig() *params.ChainConfig { 131 return b.chainConfig 132 } 133 134 func (b *testBackend) Engine() consensus.Engine { 135 return b.engine 136 } 137 138 func (b *testBackend) ChainDb() ethdb.Database { 139 return b.chaindb 140 } 141 142 func (b *testBackend) StateAtBlock(ctx context.Context, block *types.Block, reexec uint64, base *state.StateDB, checkLive bool, preferDisk bool) (*state.StateDB, error) { 143 statedb, err := b.chain.StateAt(block.Root()) 144 if err != nil { 145 return nil, errStateNotFound 146 } 147 return statedb, nil 148 } 149 150 func (b *testBackend) StateAtTransaction(ctx context.Context, block *types.Block, txIndex int, reexec uint64) (core.Message, vm.BlockContext, *state.StateDB, error) { 151 parent := b.chain.GetBlock(block.ParentHash(), block.NumberU64()-1) 152 if parent == nil { 153 return nil, vm.BlockContext{}, nil, errBlockNotFound 154 } 155 statedb, err := b.chain.StateAt(parent.Root()) 156 if err != nil { 157 return nil, vm.BlockContext{}, nil, errStateNotFound 158 } 159 if txIndex == 0 && len(block.Transactions()) == 0 { 160 return nil, vm.BlockContext{}, statedb, nil 161 } 162 // Recompute transactions up to the target index. 163 signer := types.MakeSigner(b.chainConfig, block.Number()) 164 for idx, tx := range block.Transactions() { 165 msg, _ := tx.AsMessage(signer, block.BaseFee()) 166 txContext := core.NewEVMTxContext(msg) 167 context := core.NewEVMBlockContext(block.Header(), b.chain, nil) 168 if idx == txIndex { 169 return msg, context, statedb, nil 170 } 171 vmenv := vm.NewEVM(context, txContext, statedb, b.chainConfig, vm.Config{}) 172 if _, err := core.ApplyMessage(vmenv, msg, new(core.GasPool).AddGas(tx.Gas())); err != nil { 173 return nil, vm.BlockContext{}, nil, fmt.Errorf("transaction %#x failed: %v", tx.Hash(), err) 174 } 175 statedb.Finalise(vmenv.ChainConfig().IsEIP158(block.Number())) 176 } 177 return nil, vm.BlockContext{}, nil, fmt.Errorf("transaction index %d out of range for block %#x", txIndex, block.Hash()) 178 } 179 180 func TestTraceCall(t *testing.T) { 181 t.Parallel() 182 183 // Initialize test accounts 184 accounts := newAccounts(3) 185 genesis := &core.Genesis{Alloc: core.GenesisAlloc{ 186 accounts[0].addr: {Balance: big.NewInt(params.Ether)}, 187 accounts[1].addr: {Balance: big.NewInt(params.Ether)}, 188 accounts[2].addr: {Balance: big.NewInt(params.Ether)}, 189 }} 190 genBlocks := 10 191 signer := types.HomesteadSigner{} 192 api := NewAPI(newTestBackend(t, genBlocks, genesis, func(i int, b *core.BlockGen) { 193 // Transfer from account[0] to account[1] 194 // value: 1000 wei 195 // fee: 0 wei 196 tx, _ := types.SignTx(types.NewTransaction(uint64(i), accounts[1].addr, big.NewInt(1000), params.TxGas, b.BaseFee(), nil), signer, accounts[0].key) 197 b.AddTx(tx) 198 })) 199 200 var testSuite = []struct { 201 blockNumber rpc.BlockNumber 202 call ethapi.TransactionArgs 203 config *TraceCallConfig 204 expectErr error 205 expect interface{} 206 }{ 207 // Standard JSON trace upon the genesis, plain transfer. 208 { 209 blockNumber: rpc.BlockNumber(0), 210 call: ethapi.TransactionArgs{ 211 From: &accounts[0].addr, 212 To: &accounts[1].addr, 213 Value: (*hexutil.Big)(big.NewInt(1000)), 214 }, 215 config: nil, 216 expectErr: nil, 217 expect: &logger.ExecutionResult{ 218 Gas: params.TxGas, 219 Failed: false, 220 ReturnValue: "", 221 StructLogs: []logger.StructLogRes{}, 222 }, 223 }, 224 // Standard JSON trace upon the head, plain transfer. 225 { 226 blockNumber: rpc.BlockNumber(genBlocks), 227 call: ethapi.TransactionArgs{ 228 From: &accounts[0].addr, 229 To: &accounts[1].addr, 230 Value: (*hexutil.Big)(big.NewInt(1000)), 231 }, 232 config: nil, 233 expectErr: nil, 234 expect: &logger.ExecutionResult{ 235 Gas: params.TxGas, 236 Failed: false, 237 ReturnValue: "", 238 StructLogs: []logger.StructLogRes{}, 239 }, 240 }, 241 // Standard JSON trace upon the non-existent block, error expects 242 { 243 blockNumber: rpc.BlockNumber(genBlocks + 1), 244 call: ethapi.TransactionArgs{ 245 From: &accounts[0].addr, 246 To: &accounts[1].addr, 247 Value: (*hexutil.Big)(big.NewInt(1000)), 248 }, 249 config: nil, 250 expectErr: fmt.Errorf("block #%d not found", genBlocks+1), 251 expect: nil, 252 }, 253 // Standard JSON trace upon the latest block 254 { 255 blockNumber: rpc.LatestBlockNumber, 256 call: ethapi.TransactionArgs{ 257 From: &accounts[0].addr, 258 To: &accounts[1].addr, 259 Value: (*hexutil.Big)(big.NewInt(1000)), 260 }, 261 config: nil, 262 expectErr: nil, 263 expect: &logger.ExecutionResult{ 264 Gas: params.TxGas, 265 Failed: false, 266 ReturnValue: "", 267 StructLogs: []logger.StructLogRes{}, 268 }, 269 }, 270 // Standard JSON trace upon the pending block 271 { 272 blockNumber: rpc.PendingBlockNumber, 273 call: ethapi.TransactionArgs{ 274 From: &accounts[0].addr, 275 To: &accounts[1].addr, 276 Value: (*hexutil.Big)(big.NewInt(1000)), 277 }, 278 config: nil, 279 expectErr: nil, 280 expect: &logger.ExecutionResult{ 281 Gas: params.TxGas, 282 Failed: false, 283 ReturnValue: "", 284 StructLogs: []logger.StructLogRes{}, 285 }, 286 }, 287 } 288 for _, testspec := range testSuite { 289 result, err := api.TraceCall(context.Background(), testspec.call, rpc.BlockNumberOrHash{BlockNumber: &testspec.blockNumber}, testspec.config) 290 if testspec.expectErr != nil { 291 if err == nil { 292 t.Errorf("Expect error %v, get nothing", testspec.expectErr) 293 continue 294 } 295 if !reflect.DeepEqual(err, testspec.expectErr) { 296 t.Errorf("Error mismatch, want %v, get %v", testspec.expectErr, err) 297 } 298 } else { 299 if err != nil { 300 t.Errorf("Expect no error, get %v", err) 301 continue 302 } 303 var have *logger.ExecutionResult 304 if err := json.Unmarshal(result.(json.RawMessage), &have); err != nil { 305 t.Errorf("failed to unmarshal result %v", err) 306 } 307 if !reflect.DeepEqual(have, testspec.expect) { 308 t.Errorf("Result mismatch, want %v, get %v", testspec.expect, have) 309 } 310 } 311 } 312 } 313 314 func TestTraceTransaction(t *testing.T) { 315 t.Parallel() 316 317 // Initialize test accounts 318 accounts := newAccounts(2) 319 genesis := &core.Genesis{Alloc: core.GenesisAlloc{ 320 accounts[0].addr: {Balance: big.NewInt(params.Ether)}, 321 accounts[1].addr: {Balance: big.NewInt(params.Ether)}, 322 }} 323 target := common.Hash{} 324 signer := types.HomesteadSigner{} 325 api := NewAPI(newTestBackend(t, 1, genesis, func(i int, b *core.BlockGen) { 326 // Transfer from account[0] to account[1] 327 // value: 1000 wei 328 // fee: 0 wei 329 tx, _ := types.SignTx(types.NewTransaction(uint64(i), accounts[1].addr, big.NewInt(1000), params.TxGas, b.BaseFee(), nil), signer, accounts[0].key) 330 b.AddTx(tx) 331 target = tx.Hash() 332 })) 333 result, err := api.TraceTransaction(context.Background(), target, nil) 334 if err != nil { 335 t.Errorf("Failed to trace transaction %v", err) 336 } 337 var have *logger.ExecutionResult 338 if err := json.Unmarshal(result.(json.RawMessage), &have); err != nil { 339 t.Errorf("failed to unmarshal result %v", err) 340 } 341 if !reflect.DeepEqual(have, &logger.ExecutionResult{ 342 Gas: params.TxGas, 343 Failed: false, 344 ReturnValue: "", 345 StructLogs: []logger.StructLogRes{}, 346 }) { 347 t.Error("Transaction tracing result is different") 348 } 349 } 350 351 func TestTraceBlock(t *testing.T) { 352 t.Parallel() 353 354 // Initialize test accounts 355 accounts := newAccounts(3) 356 genesis := &core.Genesis{Alloc: core.GenesisAlloc{ 357 accounts[0].addr: {Balance: big.NewInt(params.Ether)}, 358 accounts[1].addr: {Balance: big.NewInt(params.Ether)}, 359 accounts[2].addr: {Balance: big.NewInt(params.Ether)}, 360 }} 361 genBlocks := 10 362 signer := types.HomesteadSigner{} 363 api := NewAPI(newTestBackend(t, genBlocks, genesis, func(i int, b *core.BlockGen) { 364 // Transfer from account[0] to account[1] 365 // value: 1000 wei 366 // fee: 0 wei 367 tx, _ := types.SignTx(types.NewTransaction(uint64(i), accounts[1].addr, big.NewInt(1000), params.TxGas, b.BaseFee(), nil), signer, accounts[0].key) 368 b.AddTx(tx) 369 })) 370 371 var testSuite = []struct { 372 blockNumber rpc.BlockNumber 373 config *TraceConfig 374 want string 375 expectErr error 376 }{ 377 // Trace genesis block, expect error 378 { 379 blockNumber: rpc.BlockNumber(0), 380 expectErr: errors.New("genesis is not traceable"), 381 }, 382 // Trace head block 383 { 384 blockNumber: rpc.BlockNumber(genBlocks), 385 want: `[{"result":{"gas":21000,"failed":false,"returnValue":"","structLogs":[]}}]`, 386 }, 387 // Trace non-existent block 388 { 389 blockNumber: rpc.BlockNumber(genBlocks + 1), 390 expectErr: fmt.Errorf("block #%d not found", genBlocks+1), 391 }, 392 // Trace latest block 393 { 394 blockNumber: rpc.LatestBlockNumber, 395 want: `[{"result":{"gas":21000,"failed":false,"returnValue":"","structLogs":[]}}]`, 396 }, 397 // Trace pending block 398 { 399 blockNumber: rpc.PendingBlockNumber, 400 want: `[{"result":{"gas":21000,"failed":false,"returnValue":"","structLogs":[]}}]`, 401 }, 402 } 403 for i, tc := range testSuite { 404 result, err := api.TraceBlockByNumber(context.Background(), tc.blockNumber, tc.config) 405 if tc.expectErr != nil { 406 if err == nil { 407 t.Errorf("test %d, want error %v", i, tc.expectErr) 408 continue 409 } 410 if !reflect.DeepEqual(err, tc.expectErr) { 411 t.Errorf("test %d: error mismatch, want %v, get %v", i, tc.expectErr, err) 412 } 413 continue 414 } 415 if err != nil { 416 t.Errorf("test %d, want no error, have %v", i, err) 417 continue 418 } 419 have, _ := json.Marshal(result) 420 want := tc.want 421 if string(have) != want { 422 t.Errorf("test %d, result mismatch, have\n%v\n, want\n%v\n", i, string(have), want) 423 } 424 } 425 } 426 427 func TestTracingWithOverrides(t *testing.T) { 428 t.Parallel() 429 // Initialize test accounts 430 accounts := newAccounts(3) 431 genesis := &core.Genesis{Alloc: core.GenesisAlloc{ 432 accounts[0].addr: {Balance: big.NewInt(params.Ether)}, 433 accounts[1].addr: {Balance: big.NewInt(params.Ether)}, 434 accounts[2].addr: {Balance: big.NewInt(params.Ether)}, 435 }} 436 genBlocks := 10 437 signer := types.HomesteadSigner{} 438 api := NewAPI(newTestBackend(t, genBlocks, genesis, func(i int, b *core.BlockGen) { 439 // Transfer from account[0] to account[1] 440 // value: 1000 wei 441 // fee: 0 wei 442 tx, _ := types.SignTx(types.NewTransaction(uint64(i), accounts[1].addr, big.NewInt(1000), params.TxGas, b.BaseFee(), nil), signer, accounts[0].key) 443 b.AddTx(tx) 444 })) 445 randomAccounts := newAccounts(3) 446 type res struct { 447 Gas int 448 Failed bool 449 returnValue string 450 } 451 var testSuite = []struct { 452 blockNumber rpc.BlockNumber 453 call ethapi.TransactionArgs 454 config *TraceCallConfig 455 expectErr error 456 want string 457 }{ 458 // Call which can only succeed if state is state overridden 459 { 460 blockNumber: rpc.PendingBlockNumber, 461 call: ethapi.TransactionArgs{ 462 From: &randomAccounts[0].addr, 463 To: &randomAccounts[1].addr, 464 Value: (*hexutil.Big)(big.NewInt(1000)), 465 }, 466 config: &TraceCallConfig{ 467 StateOverrides: ðapi.StateOverride{ 468 randomAccounts[0].addr: ethapi.OverrideAccount{Balance: newRPCBalance(new(big.Int).Mul(big.NewInt(1), big.NewInt(params.Ether)))}, 469 }, 470 }, 471 want: `{"gas":21000,"failed":false,"returnValue":""}`, 472 }, 473 // Invalid call without state overriding 474 { 475 blockNumber: rpc.PendingBlockNumber, 476 call: ethapi.TransactionArgs{ 477 From: &randomAccounts[0].addr, 478 To: &randomAccounts[1].addr, 479 Value: (*hexutil.Big)(big.NewInt(1000)), 480 }, 481 config: &TraceCallConfig{}, 482 expectErr: core.ErrInsufficientFunds, 483 }, 484 // Successful simple contract call 485 // 486 // // SPDX-License-Identifier: GPL-3.0 487 // 488 // pragma solidity >=0.7.0 <0.8.0; 489 // 490 // /** 491 // * @title Storage 492 // * @dev Store & retrieve value in a variable 493 // */ 494 // contract Storage { 495 // uint256 public number; 496 // constructor() { 497 // number = block.number; 498 // } 499 // } 500 { 501 blockNumber: rpc.PendingBlockNumber, 502 call: ethapi.TransactionArgs{ 503 From: &randomAccounts[0].addr, 504 To: &randomAccounts[2].addr, 505 Data: newRPCBytes(common.Hex2Bytes("8381f58a")), // call number() 506 }, 507 config: &TraceCallConfig{ 508 //Tracer: &tracer, 509 StateOverrides: ðapi.StateOverride{ 510 randomAccounts[2].addr: ethapi.OverrideAccount{ 511 Code: newRPCBytes(common.Hex2Bytes("6080604052348015600f57600080fd5b506004361060285760003560e01c80638381f58a14602d575b600080fd5b60336049565b6040518082815260200191505060405180910390f35b6000548156fea2646970667358221220eab35ffa6ab2adfe380772a48b8ba78e82a1b820a18fcb6f59aa4efb20a5f60064736f6c63430007040033")), 512 StateDiff: newStates([]common.Hash{{}}, []common.Hash{common.BigToHash(big.NewInt(123))}), 513 }, 514 }, 515 }, 516 want: `{"gas":23347,"failed":false,"returnValue":"000000000000000000000000000000000000000000000000000000000000007b"}`, 517 }, 518 } 519 for i, tc := range testSuite { 520 result, err := api.TraceCall(context.Background(), tc.call, rpc.BlockNumberOrHash{BlockNumber: &tc.blockNumber}, tc.config) 521 if tc.expectErr != nil { 522 if err == nil { 523 t.Errorf("test %d: want error %v, have nothing", i, tc.expectErr) 524 continue 525 } 526 if !errors.Is(err, tc.expectErr) { 527 t.Errorf("test %d: error mismatch, want %v, have %v", i, tc.expectErr, err) 528 } 529 continue 530 } 531 if err != nil { 532 t.Errorf("test %d: want no error, have %v", i, err) 533 continue 534 } 535 // Turn result into res-struct 536 var ( 537 have res 538 want res 539 ) 540 resBytes, _ := json.Marshal(result) 541 json.Unmarshal(resBytes, &have) 542 json.Unmarshal([]byte(tc.want), &want) 543 if !reflect.DeepEqual(have, want) { 544 t.Errorf("test %d, result mismatch, have\n%v\n, want\n%v\n", i, string(resBytes), want) 545 } 546 } 547 } 548 549 type Account struct { 550 key *ecdsa.PrivateKey 551 addr common.Address 552 } 553 554 type Accounts []Account 555 556 func (a Accounts) Len() int { return len(a) } 557 func (a Accounts) Swap(i, j int) { a[i], a[j] = a[j], a[i] } 558 func (a Accounts) Less(i, j int) bool { return bytes.Compare(a[i].addr.Bytes(), a[j].addr.Bytes()) < 0 } 559 560 func newAccounts(n int) (accounts Accounts) { 561 for i := 0; i < n; i++ { 562 key, _ := crypto.GenerateKey() 563 addr := crypto.PubkeyToAddress(key.PublicKey) 564 accounts = append(accounts, Account{key: key, addr: addr}) 565 } 566 sort.Sort(accounts) 567 return accounts 568 } 569 570 func newRPCBalance(balance *big.Int) **hexutil.Big { 571 rpcBalance := (*hexutil.Big)(balance) 572 return &rpcBalance 573 } 574 575 func newRPCBytes(bytes []byte) *hexutil.Bytes { 576 rpcBytes := hexutil.Bytes(bytes) 577 return &rpcBytes 578 } 579 580 func newStates(keys []common.Hash, vals []common.Hash) *map[common.Hash]common.Hash { 581 if len(keys) != len(vals) { 582 panic("invalid input") 583 } 584 m := make(map[common.Hash]common.Hash) 585 for i := 0; i < len(keys); i++ { 586 m[keys[i]] = vals[i] 587 } 588 return &m 589 }