github.com/shrimpyuk/bor@v0.2.15-0.20220224151350-fb4ec6020bae/eth/catalyst/api_test.go (about)

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