api_test.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487
  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. package tracers
  17. import (
  18. "bytes"
  19. "context"
  20. "crypto/ecdsa"
  21. "errors"
  22. "fmt"
  23. "math/big"
  24. "reflect"
  25. "sort"
  26. "testing"
  27. "time"
  28. "github.com/ethereum/go-ethereum/common"
  29. "github.com/ethereum/go-ethereum/common/hexutil"
  30. "github.com/ethereum/go-ethereum/consensus"
  31. "github.com/ethereum/go-ethereum/consensus/ethash"
  32. "github.com/ethereum/go-ethereum/core"
  33. "github.com/ethereum/go-ethereum/core/rawdb"
  34. "github.com/ethereum/go-ethereum/core/state"
  35. "github.com/ethereum/go-ethereum/core/types"
  36. "github.com/ethereum/go-ethereum/core/vm"
  37. "github.com/ethereum/go-ethereum/crypto"
  38. "github.com/ethereum/go-ethereum/ethdb"
  39. "github.com/ethereum/go-ethereum/internal/ethapi"
  40. "github.com/ethereum/go-ethereum/params"
  41. "github.com/ethereum/go-ethereum/rpc"
  42. )
  43. var (
  44. errStateNotFound = errors.New("state not found")
  45. errBlockNotFound = errors.New("block not found")
  46. errTransactionNotFound = errors.New("transaction not found")
  47. )
  48. type testBackend struct {
  49. chainConfig *params.ChainConfig
  50. engine consensus.Engine
  51. chaindb ethdb.Database
  52. chain *core.BlockChain
  53. }
  54. func newTestBackend(t *testing.T, n int, gspec *core.Genesis, generator func(i int, b *core.BlockGen)) *testBackend {
  55. backend := &testBackend{
  56. chainConfig: params.TestChainConfig,
  57. engine: ethash.NewFaker(),
  58. chaindb: rawdb.NewMemoryDatabase(),
  59. }
  60. // Generate blocks for testing
  61. gspec.Config = backend.chainConfig
  62. var (
  63. gendb = rawdb.NewMemoryDatabase()
  64. genesis = gspec.MustCommit(gendb)
  65. )
  66. blocks, _ := core.GenerateChain(backend.chainConfig, genesis, backend.engine, gendb, n, generator)
  67. // Import the canonical chain
  68. gspec.MustCommit(backend.chaindb)
  69. cacheConfig := &core.CacheConfig{
  70. TrieCleanLimit: 256,
  71. TrieDirtyLimit: 256,
  72. TrieTimeLimit: 5 * time.Minute,
  73. SnapshotLimit: 0,
  74. TrieDirtyDisabled: true, // Archive mode
  75. }
  76. chain, err := core.NewBlockChain(backend.chaindb, cacheConfig, backend.chainConfig, backend.engine, vm.Config{}, nil, nil)
  77. if err != nil {
  78. t.Fatalf("failed to create tester chain: %v", err)
  79. }
  80. if n, err := chain.InsertChain(blocks); err != nil {
  81. t.Fatalf("block %d: failed to insert into chain: %v", n, err)
  82. }
  83. backend.chain = chain
  84. return backend
  85. }
  86. func (b *testBackend) HeaderByHash(ctx context.Context, hash common.Hash) (*types.Header, error) {
  87. return b.chain.GetHeaderByHash(hash), nil
  88. }
  89. func (b *testBackend) HeaderByNumber(ctx context.Context, number rpc.BlockNumber) (*types.Header, error) {
  90. if number == rpc.PendingBlockNumber || number == rpc.LatestBlockNumber {
  91. return b.chain.CurrentHeader(), nil
  92. }
  93. return b.chain.GetHeaderByNumber(uint64(number)), nil
  94. }
  95. func (b *testBackend) BlockByHash(ctx context.Context, hash common.Hash) (*types.Block, error) {
  96. return b.chain.GetBlockByHash(hash), nil
  97. }
  98. func (b *testBackend) BlockByNumber(ctx context.Context, number rpc.BlockNumber) (*types.Block, error) {
  99. if number == rpc.PendingBlockNumber || number == rpc.LatestBlockNumber {
  100. return b.chain.CurrentBlock(), nil
  101. }
  102. return b.chain.GetBlockByNumber(uint64(number)), nil
  103. }
  104. func (b *testBackend) GetTransaction(ctx context.Context, txHash common.Hash) (*types.Transaction, common.Hash, uint64, uint64, error) {
  105. tx, hash, blockNumber, index := rawdb.ReadTransaction(b.chaindb, txHash)
  106. if tx == nil {
  107. return nil, common.Hash{}, 0, 0, errTransactionNotFound
  108. }
  109. return tx, hash, blockNumber, index, nil
  110. }
  111. func (b *testBackend) RPCGasCap() uint64 {
  112. return 25000000
  113. }
  114. func (b *testBackend) ChainConfig() *params.ChainConfig {
  115. return b.chainConfig
  116. }
  117. func (b *testBackend) Engine() consensus.Engine {
  118. return b.engine
  119. }
  120. func (b *testBackend) ChainDb() ethdb.Database {
  121. return b.chaindb
  122. }
  123. func (b *testBackend) StateAtBlock(ctx context.Context, block *types.Block, reexec uint64) (*state.StateDB, func(), error) {
  124. statedb, err := b.chain.StateAt(block.Root())
  125. if err != nil {
  126. return nil, nil, errStateNotFound
  127. }
  128. return statedb, func() {}, nil
  129. }
  130. func (b *testBackend) StateAtTransaction(ctx context.Context, block *types.Block, txIndex int, reexec uint64) (core.Message, vm.BlockContext, *state.StateDB, func(), error) {
  131. parent := b.chain.GetBlock(block.ParentHash(), block.NumberU64()-1)
  132. if parent == nil {
  133. return nil, vm.BlockContext{}, nil, nil, errBlockNotFound
  134. }
  135. statedb, err := b.chain.StateAt(parent.Root())
  136. if err != nil {
  137. return nil, vm.BlockContext{}, nil, nil, errStateNotFound
  138. }
  139. if txIndex == 0 && len(block.Transactions()) == 0 {
  140. return nil, vm.BlockContext{}, statedb, func() {}, nil
  141. }
  142. // Recompute transactions up to the target index.
  143. signer := types.MakeSigner(b.chainConfig, block.Number())
  144. for idx, tx := range block.Transactions() {
  145. msg, _ := tx.AsMessage(signer)
  146. txContext := core.NewEVMTxContext(msg)
  147. context := core.NewEVMBlockContext(block.Header(), b.chain, nil)
  148. if idx == txIndex {
  149. return msg, context, statedb, func() {}, nil
  150. }
  151. vmenv := vm.NewEVM(context, txContext, statedb, b.chainConfig, vm.Config{})
  152. if _, err := core.ApplyMessage(vmenv, msg, new(core.GasPool).AddGas(tx.Gas())); err != nil {
  153. return nil, vm.BlockContext{}, nil, nil, fmt.Errorf("transaction %#x failed: %v", tx.Hash(), err)
  154. }
  155. statedb.Finalise(vmenv.ChainConfig().IsEIP158(block.Number()))
  156. }
  157. return nil, vm.BlockContext{}, nil, nil, fmt.Errorf("transaction index %d out of range for block %#x", txIndex, block.Hash())
  158. }
  159. func (b *testBackend) StatesInRange(ctx context.Context, fromBlock *types.Block, toBlock *types.Block, reexec uint64) ([]*state.StateDB, func(), error) {
  160. var result []*state.StateDB
  161. for number := fromBlock.NumberU64(); number <= toBlock.NumberU64(); number += 1 {
  162. block := b.chain.GetBlockByNumber(number)
  163. if block == nil {
  164. return nil, nil, errBlockNotFound
  165. }
  166. statedb, err := b.chain.StateAt(block.Root())
  167. if err != nil {
  168. return nil, nil, errStateNotFound
  169. }
  170. result = append(result, statedb)
  171. }
  172. return result, func() {}, nil
  173. }
  174. func TestTraceCall(t *testing.T) {
  175. t.Parallel()
  176. // Initialize test accounts
  177. accounts := newAccounts(3)
  178. genesis := &core.Genesis{Alloc: core.GenesisAlloc{
  179. accounts[0].addr: {Balance: big.NewInt(params.Ether)},
  180. accounts[1].addr: {Balance: big.NewInt(params.Ether)},
  181. accounts[2].addr: {Balance: big.NewInt(params.Ether)},
  182. }}
  183. genBlocks := 10
  184. signer := types.HomesteadSigner{}
  185. api := NewAPI(newTestBackend(t, genBlocks, genesis, func(i int, b *core.BlockGen) {
  186. // Transfer from account[0] to account[1]
  187. // value: 1000 wei
  188. // fee: 0 wei
  189. tx, _ := types.SignTx(types.NewTransaction(uint64(i), accounts[1].addr, big.NewInt(1000), params.TxGas, big.NewInt(0), nil), signer, accounts[0].key)
  190. b.AddTx(tx)
  191. }))
  192. var testSuite = []struct {
  193. blockNumber rpc.BlockNumber
  194. call ethapi.CallArgs
  195. config *TraceConfig
  196. expectErr error
  197. expect interface{}
  198. }{
  199. // Standard JSON trace upon the genesis, plain transfer.
  200. {
  201. blockNumber: rpc.BlockNumber(0),
  202. call: ethapi.CallArgs{
  203. From: &accounts[0].addr,
  204. To: &accounts[1].addr,
  205. Value: (*hexutil.Big)(big.NewInt(1000)),
  206. },
  207. config: nil,
  208. expectErr: nil,
  209. expect: &ethapi.ExecutionResult{
  210. Gas: params.TxGas,
  211. Failed: false,
  212. ReturnValue: "",
  213. StructLogs: []ethapi.StructLogRes{},
  214. },
  215. },
  216. // Standard JSON trace upon the head, plain transfer.
  217. {
  218. blockNumber: rpc.BlockNumber(genBlocks),
  219. call: ethapi.CallArgs{
  220. From: &accounts[0].addr,
  221. To: &accounts[1].addr,
  222. Value: (*hexutil.Big)(big.NewInt(1000)),
  223. },
  224. config: nil,
  225. expectErr: nil,
  226. expect: &ethapi.ExecutionResult{
  227. Gas: params.TxGas,
  228. Failed: false,
  229. ReturnValue: "",
  230. StructLogs: []ethapi.StructLogRes{},
  231. },
  232. },
  233. // Standard JSON trace upon the non-existent block, error expects
  234. {
  235. blockNumber: rpc.BlockNumber(genBlocks + 1),
  236. call: ethapi.CallArgs{
  237. From: &accounts[0].addr,
  238. To: &accounts[1].addr,
  239. Value: (*hexutil.Big)(big.NewInt(1000)),
  240. },
  241. config: nil,
  242. expectErr: fmt.Errorf("block #%d not found", genBlocks+1),
  243. expect: nil,
  244. },
  245. // Standard JSON trace upon the latest block
  246. {
  247. blockNumber: rpc.LatestBlockNumber,
  248. call: ethapi.CallArgs{
  249. From: &accounts[0].addr,
  250. To: &accounts[1].addr,
  251. Value: (*hexutil.Big)(big.NewInt(1000)),
  252. },
  253. config: nil,
  254. expectErr: nil,
  255. expect: &ethapi.ExecutionResult{
  256. Gas: params.TxGas,
  257. Failed: false,
  258. ReturnValue: "",
  259. StructLogs: []ethapi.StructLogRes{},
  260. },
  261. },
  262. // Standard JSON trace upon the pending block
  263. {
  264. blockNumber: rpc.PendingBlockNumber,
  265. call: ethapi.CallArgs{
  266. From: &accounts[0].addr,
  267. To: &accounts[1].addr,
  268. Value: (*hexutil.Big)(big.NewInt(1000)),
  269. },
  270. config: nil,
  271. expectErr: nil,
  272. expect: &ethapi.ExecutionResult{
  273. Gas: params.TxGas,
  274. Failed: false,
  275. ReturnValue: "",
  276. StructLogs: []ethapi.StructLogRes{},
  277. },
  278. },
  279. }
  280. for _, testspec := range testSuite {
  281. result, err := api.TraceCall(context.Background(), testspec.call, rpc.BlockNumberOrHash{BlockNumber: &testspec.blockNumber}, testspec.config)
  282. if testspec.expectErr != nil {
  283. if err == nil {
  284. t.Errorf("Expect error %v, get nothing", testspec.expectErr)
  285. continue
  286. }
  287. if !reflect.DeepEqual(err, testspec.expectErr) {
  288. t.Errorf("Error mismatch, want %v, get %v", testspec.expectErr, err)
  289. }
  290. } else {
  291. if err != nil {
  292. t.Errorf("Expect no error, get %v", err)
  293. continue
  294. }
  295. if !reflect.DeepEqual(result, testspec.expect) {
  296. t.Errorf("Result mismatch, want %v, get %v", testspec.expect, result)
  297. }
  298. }
  299. }
  300. }
  301. func TestTraceTransaction(t *testing.T) {
  302. t.Parallel()
  303. // Initialize test accounts
  304. accounts := newAccounts(2)
  305. genesis := &core.Genesis{Alloc: core.GenesisAlloc{
  306. accounts[0].addr: {Balance: big.NewInt(params.Ether)},
  307. accounts[1].addr: {Balance: big.NewInt(params.Ether)},
  308. }}
  309. target := common.Hash{}
  310. signer := types.HomesteadSigner{}
  311. api := NewAPI(newTestBackend(t, 1, genesis, func(i int, b *core.BlockGen) {
  312. // Transfer from account[0] to account[1]
  313. // value: 1000 wei
  314. // fee: 0 wei
  315. tx, _ := types.SignTx(types.NewTransaction(uint64(i), accounts[1].addr, big.NewInt(1000), params.TxGas, big.NewInt(0), nil), signer, accounts[0].key)
  316. b.AddTx(tx)
  317. target = tx.Hash()
  318. }))
  319. result, err := api.TraceTransaction(context.Background(), target, nil)
  320. if err != nil {
  321. t.Errorf("Failed to trace transaction %v", err)
  322. }
  323. if !reflect.DeepEqual(result, &ethapi.ExecutionResult{
  324. Gas: params.TxGas,
  325. Failed: false,
  326. ReturnValue: "",
  327. StructLogs: []ethapi.StructLogRes{},
  328. }) {
  329. t.Error("Transaction tracing result is different")
  330. }
  331. }
  332. func TestTraceBlock(t *testing.T) {
  333. t.Parallel()
  334. // Initialize test accounts
  335. accounts := newAccounts(3)
  336. genesis := &core.Genesis{Alloc: core.GenesisAlloc{
  337. accounts[0].addr: {Balance: big.NewInt(params.Ether)},
  338. accounts[1].addr: {Balance: big.NewInt(params.Ether)},
  339. accounts[2].addr: {Balance: big.NewInt(params.Ether)},
  340. }}
  341. genBlocks := 10
  342. signer := types.HomesteadSigner{}
  343. api := NewAPI(newTestBackend(t, genBlocks, genesis, func(i int, b *core.BlockGen) {
  344. // Transfer from account[0] to account[1]
  345. // value: 1000 wei
  346. // fee: 0 wei
  347. tx, _ := types.SignTx(types.NewTransaction(uint64(i), accounts[1].addr, big.NewInt(1000), params.TxGas, big.NewInt(0), nil), signer, accounts[0].key)
  348. b.AddTx(tx)
  349. }))
  350. var testSuite = []struct {
  351. blockNumber rpc.BlockNumber
  352. config *TraceConfig
  353. expect interface{}
  354. expectErr error
  355. }{
  356. // Trace genesis block, expect error
  357. {
  358. blockNumber: rpc.BlockNumber(0),
  359. config: nil,
  360. expect: nil,
  361. expectErr: errors.New("genesis is not traceable"),
  362. },
  363. // Trace head block
  364. {
  365. blockNumber: rpc.BlockNumber(genBlocks),
  366. config: nil,
  367. expectErr: nil,
  368. expect: []*txTraceResult{
  369. {
  370. Result: &ethapi.ExecutionResult{
  371. Gas: params.TxGas,
  372. Failed: false,
  373. ReturnValue: "",
  374. StructLogs: []ethapi.StructLogRes{},
  375. },
  376. },
  377. },
  378. },
  379. // Trace non-existent block
  380. {
  381. blockNumber: rpc.BlockNumber(genBlocks + 1),
  382. config: nil,
  383. expectErr: fmt.Errorf("block #%d not found", genBlocks+1),
  384. expect: nil,
  385. },
  386. // Trace latest block
  387. {
  388. blockNumber: rpc.LatestBlockNumber,
  389. config: nil,
  390. expectErr: nil,
  391. expect: []*txTraceResult{
  392. {
  393. Result: &ethapi.ExecutionResult{
  394. Gas: params.TxGas,
  395. Failed: false,
  396. ReturnValue: "",
  397. StructLogs: []ethapi.StructLogRes{},
  398. },
  399. },
  400. },
  401. },
  402. // Trace pending block
  403. {
  404. blockNumber: rpc.PendingBlockNumber,
  405. config: nil,
  406. expectErr: nil,
  407. expect: []*txTraceResult{
  408. {
  409. Result: &ethapi.ExecutionResult{
  410. Gas: params.TxGas,
  411. Failed: false,
  412. ReturnValue: "",
  413. StructLogs: []ethapi.StructLogRes{},
  414. },
  415. },
  416. },
  417. },
  418. }
  419. for _, testspec := range testSuite {
  420. result, err := api.TraceBlockByNumber(context.Background(), testspec.blockNumber, testspec.config)
  421. if testspec.expectErr != nil {
  422. if err == nil {
  423. t.Errorf("Expect error %v, get nothing", testspec.expectErr)
  424. continue
  425. }
  426. if !reflect.DeepEqual(err, testspec.expectErr) {
  427. t.Errorf("Error mismatch, want %v, get %v", testspec.expectErr, err)
  428. }
  429. } else {
  430. if err != nil {
  431. t.Errorf("Expect no error, get %v", err)
  432. continue
  433. }
  434. if !reflect.DeepEqual(result, testspec.expect) {
  435. t.Errorf("Result mismatch, want %v, get %v", testspec.expect, result)
  436. }
  437. }
  438. }
  439. }
  440. type Account struct {
  441. key *ecdsa.PrivateKey
  442. addr common.Address
  443. }
  444. type Accounts []Account
  445. func (a Accounts) Len() int { return len(a) }
  446. func (a Accounts) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
  447. func (a Accounts) Less(i, j int) bool { return bytes.Compare(a[i].addr.Bytes(), a[j].addr.Bytes()) < 0 }
  448. func newAccounts(n int) (accounts Accounts) {
  449. for i := 0; i < n; i++ {
  450. key, _ := crypto.GenerateKey()
  451. addr := crypto.PubkeyToAddress(key.PublicKey)
  452. accounts = append(accounts, Account{key: key, addr: addr})
  453. }
  454. sort.Sort(accounts)
  455. return accounts
  456. }