api_test.go 7.8 KB

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