api_test.go 7.8 KB

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