api_test.go 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229
  1. // Copyright 2020 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 catalyst
  17. import (
  18. "math/big"
  19. "testing"
  20. "github.com/ethereum/go-ethereum/common"
  21. "github.com/ethereum/go-ethereum/consensus/ethash"
  22. "github.com/ethereum/go-ethereum/core"
  23. "github.com/ethereum/go-ethereum/core/rawdb"
  24. "github.com/ethereum/go-ethereum/core/types"
  25. "github.com/ethereum/go-ethereum/crypto"
  26. "github.com/ethereum/go-ethereum/eth"
  27. "github.com/ethereum/go-ethereum/eth/ethconfig"
  28. "github.com/ethereum/go-ethereum/node"
  29. "github.com/ethereum/go-ethereum/params"
  30. )
  31. var (
  32. // testKey is a private key to use for funding a tester account.
  33. testKey, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291")
  34. // testAddr is the Ethereum address of the tester account.
  35. testAddr = crypto.PubkeyToAddress(testKey.PublicKey)
  36. testBalance = big.NewInt(2e10)
  37. )
  38. func generateTestChain() (*core.Genesis, []*types.Block) {
  39. db := rawdb.NewMemoryDatabase()
  40. config := params.AllEthashProtocolChanges
  41. genesis := &core.Genesis{
  42. Config: config,
  43. Alloc: core.GenesisAlloc{testAddr: {Balance: testBalance}},
  44. ExtraData: []byte("test genesis"),
  45. Timestamp: 9000,
  46. }
  47. generate := func(i int, g *core.BlockGen) {
  48. g.OffsetTime(5)
  49. g.SetExtra([]byte("test"))
  50. }
  51. gblock := genesis.ToBlock(db)
  52. engine := ethash.NewFaker()
  53. blocks, _ := core.GenerateChain(config, gblock, engine, db, 10, generate)
  54. blocks = append([]*types.Block{gblock}, blocks...)
  55. return genesis, blocks
  56. }
  57. func generateTestChainWithFork(n int, fork int) (*core.Genesis, []*types.Block, []*types.Block) {
  58. if fork >= n {
  59. fork = n - 1
  60. }
  61. db := rawdb.NewMemoryDatabase()
  62. //nolint:composites
  63. config := &params.ChainConfig{big.NewInt(1337), big.NewInt(0), nil, false, big.NewInt(0), common.Hash{}, big.NewInt(0), big.NewInt(0), big.NewInt(0), big.NewInt(0), big.NewInt(0), big.NewInt(0), big.NewInt(0), big.NewInt(0), nil, nil, big.NewInt(0), new(params.EthashConfig), nil}
  64. genesis := &core.Genesis{
  65. Config: config,
  66. Alloc: core.GenesisAlloc{testAddr: {Balance: testBalance}},
  67. ExtraData: []byte("test genesis"),
  68. Timestamp: 9000,
  69. }
  70. generate := func(i int, g *core.BlockGen) {
  71. g.OffsetTime(5)
  72. g.SetExtra([]byte("test"))
  73. }
  74. generateFork := func(i int, g *core.BlockGen) {
  75. g.OffsetTime(5)
  76. g.SetExtra([]byte("testF"))
  77. }
  78. gblock := genesis.ToBlock(db)
  79. engine := ethash.NewFaker()
  80. blocks, _ := core.GenerateChain(config, gblock, engine, db, n, generate)
  81. blocks = append([]*types.Block{gblock}, blocks...)
  82. forkedBlocks, _ := core.GenerateChain(config, blocks[fork], engine, db, n-fork, generateFork)
  83. return genesis, blocks, forkedBlocks
  84. }
  85. func TestEth2AssembleBlock(t *testing.T) {
  86. genesis, blocks := generateTestChain()
  87. n, ethservice := startEthService(t, genesis, blocks[1:9])
  88. defer n.Close()
  89. api := newConsensusAPI(ethservice)
  90. signer := types.NewEIP155Signer(ethservice.BlockChain().Config().ChainID)
  91. tx, err := types.SignTx(types.NewTransaction(0, blocks[8].Coinbase(), big.NewInt(1000), params.TxGas, nil, nil), signer, testKey)
  92. if err != nil {
  93. t.Fatalf("error signing transaction, err=%v", err)
  94. }
  95. ethservice.TxPool().AddLocal(tx)
  96. blockParams := assembleBlockParams{
  97. ParentHash: blocks[8].ParentHash(),
  98. Timestamp: blocks[8].Time(),
  99. }
  100. execData, err := api.AssembleBlock(blockParams)
  101. if err != nil {
  102. t.Fatalf("error producing block, err=%v", err)
  103. }
  104. if len(execData.Transactions) != 1 {
  105. t.Fatalf("invalid number of transactions %d != 1", len(execData.Transactions))
  106. }
  107. }
  108. func TestEth2AssembleBlockWithAnotherBlocksTxs(t *testing.T) {
  109. genesis, blocks := generateTestChain()
  110. n, ethservice := startEthService(t, genesis, blocks[1:9])
  111. defer n.Close()
  112. api := newConsensusAPI(ethservice)
  113. // Put the 10th block's tx in the pool and produce a new block
  114. api.addBlockTxs(blocks[9])
  115. blockParams := assembleBlockParams{
  116. ParentHash: blocks[9].ParentHash(),
  117. Timestamp: blocks[9].Time(),
  118. }
  119. execData, err := api.AssembleBlock(blockParams)
  120. if err != nil {
  121. t.Fatalf("error producing block, err=%v", err)
  122. }
  123. if len(execData.Transactions) != blocks[9].Transactions().Len() {
  124. t.Fatalf("invalid number of transactions %d != 1", len(execData.Transactions))
  125. }
  126. }
  127. func TestEth2NewBlock(t *testing.T) {
  128. genesis, blocks, forkedBlocks := generateTestChainWithFork(10, 4)
  129. n, ethservice := startEthService(t, genesis, blocks[1:5])
  130. defer n.Close()
  131. api := newConsensusAPI(ethservice)
  132. for i := 5; i < 10; i++ {
  133. p := executableData{
  134. ParentHash: ethservice.BlockChain().CurrentBlock().Hash(),
  135. Miner: blocks[i].Coinbase(),
  136. StateRoot: blocks[i].Root(),
  137. GasLimit: blocks[i].GasLimit(),
  138. GasUsed: blocks[i].GasUsed(),
  139. Transactions: encodeTransactions(blocks[i].Transactions()),
  140. ReceiptRoot: blocks[i].ReceiptHash(),
  141. LogsBloom: blocks[i].Bloom().Bytes(),
  142. BlockHash: blocks[i].Hash(),
  143. Timestamp: blocks[i].Time(),
  144. Number: uint64(i),
  145. }
  146. success, err := api.NewBlock(p)
  147. if err != nil || !success.Valid {
  148. t.Fatalf("Failed to insert block: %v", err)
  149. }
  150. }
  151. exp := ethservice.BlockChain().CurrentBlock().Hash()
  152. // Introduce the fork point.
  153. lastBlockNum := blocks[4].Number()
  154. lastBlock := blocks[4]
  155. for i := 0; i < 4; i++ {
  156. lastBlockNum.Add(lastBlockNum, big.NewInt(1))
  157. p := executableData{
  158. ParentHash: lastBlock.Hash(),
  159. Miner: forkedBlocks[i].Coinbase(),
  160. StateRoot: forkedBlocks[i].Root(),
  161. Number: lastBlockNum.Uint64(),
  162. GasLimit: forkedBlocks[i].GasLimit(),
  163. GasUsed: forkedBlocks[i].GasUsed(),
  164. Transactions: encodeTransactions(blocks[i].Transactions()),
  165. ReceiptRoot: forkedBlocks[i].ReceiptHash(),
  166. LogsBloom: forkedBlocks[i].Bloom().Bytes(),
  167. BlockHash: forkedBlocks[i].Hash(),
  168. Timestamp: forkedBlocks[i].Time(),
  169. }
  170. success, err := api.NewBlock(p)
  171. if err != nil || !success.Valid {
  172. t.Fatalf("Failed to insert forked block #%d: %v", i, err)
  173. }
  174. lastBlock, err = insertBlockParamsToBlock(p)
  175. if err != nil {
  176. t.Fatal(err)
  177. }
  178. }
  179. if ethservice.BlockChain().CurrentBlock().Hash() != exp {
  180. t.Fatalf("Wrong head after inserting fork %x != %x", exp, ethservice.BlockChain().CurrentBlock().Hash())
  181. }
  182. }
  183. // startEthService creates a full node instance for testing.
  184. func startEthService(t *testing.T, genesis *core.Genesis, blocks []*types.Block) (*node.Node, *eth.Ethereum) {
  185. t.Helper()
  186. n, err := node.New(&node.Config{})
  187. if err != nil {
  188. t.Fatal("can't create node:", err)
  189. }
  190. ethcfg := &ethconfig.Config{Genesis: genesis, Ethash: ethash.Config{PowMode: ethash.ModeFake}}
  191. ethservice, err := eth.New(n, ethcfg)
  192. if err != nil {
  193. t.Fatal("can't create eth service:", err)
  194. }
  195. if err := n.Start(); err != nil {
  196. t.Fatal("can't start node:", err)
  197. }
  198. if _, err := ethservice.BlockChain().InsertChain(blocks); err != nil {
  199. n.Close()
  200. t.Fatal("can't import test blocks:", err)
  201. }
  202. ethservice.SetEtherbase(testAddr)
  203. return n, ethservice
  204. }