github.com/electroneum/electroneum-sc@v0.0.0-20230105223411-3bc1d078281e/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/electroneum/electroneum-sc/common" 33 "github.com/electroneum/electroneum-sc/common/hexutil" 34 "github.com/electroneum/electroneum-sc/consensus" 35 "github.com/electroneum/electroneum-sc/consensus/ethash" 36 "github.com/electroneum/electroneum-sc/core" 37 "github.com/electroneum/electroneum-sc/core/rawdb" 38 "github.com/electroneum/electroneum-sc/core/state" 39 "github.com/electroneum/electroneum-sc/core/types" 40 "github.com/electroneum/electroneum-sc/core/vm" 41 "github.com/electroneum/electroneum-sc/crypto" 42 "github.com/electroneum/electroneum-sc/eth/tracers/logger" 43 "github.com/electroneum/electroneum-sc/ethdb" 44 "github.com/electroneum/electroneum-sc/internal/ethapi" 45 "github.com/electroneum/electroneum-sc/params" 46 "github.com/electroneum/electroneum-sc/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 } 450 var testSuite = []struct { 451 blockNumber rpc.BlockNumber 452 call ethapi.TransactionArgs 453 config *TraceCallConfig 454 expectErr error 455 want string 456 }{ 457 // Call which can only succeed if state is state overridden 458 { 459 blockNumber: rpc.PendingBlockNumber, 460 call: ethapi.TransactionArgs{ 461 From: &randomAccounts[0].addr, 462 To: &randomAccounts[1].addr, 463 Value: (*hexutil.Big)(big.NewInt(1000)), 464 }, 465 config: &TraceCallConfig{ 466 StateOverrides: ðapi.StateOverride{ 467 randomAccounts[0].addr: ethapi.OverrideAccount{Balance: newRPCBalance(new(big.Int).Mul(big.NewInt(1), big.NewInt(params.Ether)))}, 468 }, 469 }, 470 want: `{"gas":21000,"failed":false,"returnValue":""}`, 471 }, 472 // Invalid call without state overriding 473 { 474 blockNumber: rpc.PendingBlockNumber, 475 call: ethapi.TransactionArgs{ 476 From: &randomAccounts[0].addr, 477 To: &randomAccounts[1].addr, 478 Value: (*hexutil.Big)(big.NewInt(1000)), 479 }, 480 config: &TraceCallConfig{}, 481 expectErr: core.ErrInsufficientFunds, 482 }, 483 // Successful simple contract call 484 // 485 // // SPDX-License-Identifier: GPL-3.0 486 // 487 // pragma solidity >=0.7.0 <0.8.0; 488 // 489 // /** 490 // * @title Storage 491 // * @dev Store & retrieve value in a variable 492 // */ 493 // contract Storage { 494 // uint256 public number; 495 // constructor() { 496 // number = block.number; 497 // } 498 // } 499 { 500 blockNumber: rpc.PendingBlockNumber, 501 call: ethapi.TransactionArgs{ 502 From: &randomAccounts[0].addr, 503 To: &randomAccounts[2].addr, 504 Data: newRPCBytes(common.Hex2Bytes("8381f58a")), // call number() 505 }, 506 config: &TraceCallConfig{ 507 //Tracer: &tracer, 508 StateOverrides: ðapi.StateOverride{ 509 randomAccounts[2].addr: ethapi.OverrideAccount{ 510 Code: newRPCBytes(common.Hex2Bytes("6080604052348015600f57600080fd5b506004361060285760003560e01c80638381f58a14602d575b600080fd5b60336049565b6040518082815260200191505060405180910390f35b6000548156fea2646970667358221220eab35ffa6ab2adfe380772a48b8ba78e82a1b820a18fcb6f59aa4efb20a5f60064736f6c63430007040033")), 511 StateDiff: newStates([]common.Hash{{}}, []common.Hash{common.BigToHash(big.NewInt(123))}), 512 }, 513 }, 514 }, 515 want: `{"gas":23347,"failed":false,"returnValue":"000000000000000000000000000000000000000000000000000000000000007b"}`, 516 }, 517 } 518 for i, tc := range testSuite { 519 result, err := api.TraceCall(context.Background(), tc.call, rpc.BlockNumberOrHash{BlockNumber: &tc.blockNumber}, tc.config) 520 if tc.expectErr != nil { 521 if err == nil { 522 t.Errorf("test %d: want error %v, have nothing", i, tc.expectErr) 523 continue 524 } 525 if !errors.Is(err, tc.expectErr) { 526 t.Errorf("test %d: error mismatch, want %v, have %v", i, tc.expectErr, err) 527 } 528 continue 529 } 530 if err != nil { 531 t.Errorf("test %d: want no error, have %v", i, err) 532 continue 533 } 534 // Turn result into res-struct 535 var ( 536 have res 537 want res 538 ) 539 resBytes, _ := json.Marshal(result) 540 json.Unmarshal(resBytes, &have) 541 json.Unmarshal([]byte(tc.want), &want) 542 if !reflect.DeepEqual(have, want) { 543 t.Errorf("test %d, result mismatch, have\n%v\n, want\n%v\n", i, string(resBytes), want) 544 } 545 } 546 } 547 548 type Account struct { 549 key *ecdsa.PrivateKey 550 addr common.Address 551 } 552 553 type Accounts []Account 554 555 func (a Accounts) Len() int { return len(a) } 556 func (a Accounts) Swap(i, j int) { a[i], a[j] = a[j], a[i] } 557 func (a Accounts) Less(i, j int) bool { return bytes.Compare(a[i].addr.Bytes(), a[j].addr.Bytes()) < 0 } 558 559 func newAccounts(n int) (accounts Accounts) { 560 for i := 0; i < n; i++ { 561 key, _ := crypto.GenerateKey() 562 addr := crypto.PubkeyToAddress(key.PublicKey) 563 accounts = append(accounts, Account{key: key, addr: addr}) 564 } 565 sort.Sort(accounts) 566 return accounts 567 } 568 569 func newRPCBalance(balance *big.Int) **hexutil.Big { 570 rpcBalance := (*hexutil.Big)(balance) 571 return &rpcBalance 572 } 573 574 func newRPCBytes(bytes []byte) *hexutil.Bytes { 575 rpcBytes := hexutil.Bytes(bytes) 576 return &rpcBytes 577 } 578 579 func newStates(keys []common.Hash, vals []common.Hash) *map[common.Hash]common.Hash { 580 if len(keys) != len(vals) { 581 panic("invalid input") 582 } 583 m := make(map[common.Hash]common.Hash) 584 for i := 0; i < len(keys); i++ { 585 m[keys[i]] = vals[i] 586 } 587 return &m 588 }