api_test.go 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241
  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. Ethash: new(params.EthashConfig),
  75. }
  76. genesis := &core.Genesis{
  77. Config: config,
  78. Alloc: core.GenesisAlloc{testAddr: {Balance: testBalance}},
  79. ExtraData: []byte("test genesis"),
  80. Timestamp: 9000,
  81. }
  82. generate := func(i int, g *core.BlockGen) {
  83. g.OffsetTime(5)
  84. g.SetExtra([]byte("test"))
  85. }
  86. generateFork := func(i int, g *core.BlockGen) {
  87. g.OffsetTime(5)
  88. g.SetExtra([]byte("testF"))
  89. }
  90. gblock := genesis.ToBlock(db)
  91. engine := ethash.NewFaker()
  92. blocks, _ := core.GenerateChain(config, gblock, engine, db, n, generate)
  93. blocks = append([]*types.Block{gblock}, blocks...)
  94. forkedBlocks, _ := core.GenerateChain(config, blocks[fork], engine, db, n-fork, generateFork)
  95. return genesis, blocks, forkedBlocks
  96. }
  97. func TestEth2AssembleBlock(t *testing.T) {
  98. genesis, blocks := generateTestChain()
  99. n, ethservice := startEthService(t, genesis, blocks[1:9])
  100. defer n.Close()
  101. api := newConsensusAPI(ethservice)
  102. signer := types.NewEIP155Signer(ethservice.BlockChain().Config().ChainID)
  103. tx, err := types.SignTx(types.NewTransaction(0, blocks[8].Coinbase(), big.NewInt(1000), params.TxGas, nil, nil), signer, testKey)
  104. if err != nil {
  105. t.Fatalf("error signing transaction, err=%v", err)
  106. }
  107. ethservice.TxPool().AddLocal(tx)
  108. blockParams := assembleBlockParams{
  109. ParentHash: blocks[8].ParentHash(),
  110. Timestamp: blocks[8].Time(),
  111. }
  112. execData, err := api.AssembleBlock(blockParams)
  113. if err != nil {
  114. t.Fatalf("error producing block, err=%v", err)
  115. }
  116. if len(execData.Transactions) != 1 {
  117. t.Fatalf("invalid number of transactions %d != 1", len(execData.Transactions))
  118. }
  119. }
  120. func TestEth2AssembleBlockWithAnotherBlocksTxs(t *testing.T) {
  121. genesis, blocks := generateTestChain()
  122. n, ethservice := startEthService(t, genesis, blocks[1:9])
  123. defer n.Close()
  124. api := newConsensusAPI(ethservice)
  125. // Put the 10th block's tx in the pool and produce a new block
  126. api.addBlockTxs(blocks[9])
  127. blockParams := assembleBlockParams{
  128. ParentHash: blocks[9].ParentHash(),
  129. Timestamp: blocks[9].Time(),
  130. }
  131. execData, err := api.AssembleBlock(blockParams)
  132. if err != nil {
  133. t.Fatalf("error producing block, err=%v", err)
  134. }
  135. if len(execData.Transactions) != blocks[9].Transactions().Len() {
  136. t.Fatalf("invalid number of transactions %d != 1", len(execData.Transactions))
  137. }
  138. }
  139. func TestEth2NewBlock(t *testing.T) {
  140. genesis, blocks, forkedBlocks := generateTestChainWithFork(10, 4)
  141. n, ethservice := startEthService(t, genesis, blocks[1:5])
  142. defer n.Close()
  143. api := newConsensusAPI(ethservice)
  144. for i := 5; i < 10; i++ {
  145. p := executableData{
  146. ParentHash: ethservice.BlockChain().CurrentBlock().Hash(),
  147. Miner: blocks[i].Coinbase(),
  148. StateRoot: blocks[i].Root(),
  149. GasLimit: blocks[i].GasLimit(),
  150. GasUsed: blocks[i].GasUsed(),
  151. Transactions: encodeTransactions(blocks[i].Transactions()),
  152. ReceiptRoot: blocks[i].ReceiptHash(),
  153. LogsBloom: blocks[i].Bloom().Bytes(),
  154. BlockHash: blocks[i].Hash(),
  155. Timestamp: blocks[i].Time(),
  156. Number: uint64(i),
  157. }
  158. success, err := api.NewBlock(p)
  159. if err != nil || !success.Valid {
  160. t.Fatalf("Failed to insert block: %v", err)
  161. }
  162. }
  163. exp := ethservice.BlockChain().CurrentBlock().Hash()
  164. // Introduce the fork point.
  165. lastBlockNum := blocks[4].Number()
  166. lastBlock := blocks[4]
  167. for i := 0; i < 4; i++ {
  168. lastBlockNum.Add(lastBlockNum, big.NewInt(1))
  169. p := executableData{
  170. ParentHash: lastBlock.Hash(),
  171. Miner: forkedBlocks[i].Coinbase(),
  172. StateRoot: forkedBlocks[i].Root(),
  173. Number: lastBlockNum.Uint64(),
  174. GasLimit: forkedBlocks[i].GasLimit(),
  175. GasUsed: forkedBlocks[i].GasUsed(),
  176. Transactions: encodeTransactions(blocks[i].Transactions()),
  177. ReceiptRoot: forkedBlocks[i].ReceiptHash(),
  178. LogsBloom: forkedBlocks[i].Bloom().Bytes(),
  179. BlockHash: forkedBlocks[i].Hash(),
  180. Timestamp: forkedBlocks[i].Time(),
  181. }
  182. success, err := api.NewBlock(p)
  183. if err != nil || !success.Valid {
  184. t.Fatalf("Failed to insert forked block #%d: %v", i, err)
  185. }
  186. lastBlock, err = insertBlockParamsToBlock(p)
  187. if err != nil {
  188. t.Fatal(err)
  189. }
  190. }
  191. if ethservice.BlockChain().CurrentBlock().Hash() != exp {
  192. t.Fatalf("Wrong head after inserting fork %x != %x", exp, ethservice.BlockChain().CurrentBlock().Hash())
  193. }
  194. }
  195. // startEthService creates a full node instance for testing.
  196. func startEthService(t *testing.T, genesis *core.Genesis, blocks []*types.Block) (*node.Node, *eth.Ethereum) {
  197. t.Helper()
  198. n, err := node.New(&node.Config{})
  199. if err != nil {
  200. t.Fatal("can't create node:", err)
  201. }
  202. ethcfg := &ethconfig.Config{Genesis: genesis, Ethash: ethash.Config{PowMode: ethash.ModeFake}}
  203. ethservice, err := eth.New(n, ethcfg)
  204. if err != nil {
  205. t.Fatal("can't create eth service:", err)
  206. }
  207. if err := n.Start(); err != nil {
  208. t.Fatal("can't start node:", err)
  209. }
  210. if _, err := ethservice.BlockChain().InsertChain(blocks); err != nil {
  211. n.Close()
  212. t.Fatal("can't import test blocks:", err)
  213. }
  214. ethservice.SetEtherbase(testAddr)
  215. return n, ethservice
  216. }