gitlab.com/lightnet1/evrynet-node@v1.1.0/light/odr_test.go (about)

     1  // Copyright 2016 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 light
    18  
    19  import (
    20  	"bytes"
    21  	"context"
    22  	"errors"
    23  	"math/big"
    24  	"testing"
    25  	"time"
    26  
    27  	"gitlab.com/lightnet1/evrynet-node/common"
    28  	"gitlab.com/lightnet1/evrynet-node/common/math"
    29  	"gitlab.com/lightnet1/evrynet-node/consensus/ethash"
    30  	"gitlab.com/lightnet1/evrynet-node/core"
    31  	"gitlab.com/lightnet1/evrynet-node/core/rawdb"
    32  	"gitlab.com/lightnet1/evrynet-node/core/state"
    33  	"gitlab.com/lightnet1/evrynet-node/core/types"
    34  	"gitlab.com/lightnet1/evrynet-node/core/vm"
    35  	"gitlab.com/lightnet1/evrynet-node/crypto"
    36  	"gitlab.com/lightnet1/evrynet-node/evrdb"
    37  	"gitlab.com/lightnet1/evrynet-node/params"
    38  	"gitlab.com/lightnet1/evrynet-node/rlp"
    39  	"gitlab.com/lightnet1/evrynet-node/trie"
    40  )
    41  
    42  var (
    43  	testBankKey, _  = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291")
    44  	testBankAddress = crypto.PubkeyToAddress(testBankKey.PublicKey)
    45  	testBankFunds   = new(big.Int).Exp(big.NewInt(10), big.NewInt(18), nil)
    46  
    47  	acc1Key, _ = crypto.HexToECDSA("8a1f9a8f95be41cd7ccb6168179afb4504aefe388d1e14474d32c45c72ce7b7a")
    48  	acc2Key, _ = crypto.HexToECDSA("49a7b37aa6f6645917e7b807e9d1c00d4fa71f18343b0d4122a4d2df64dd6fee")
    49  	acc1Addr   = crypto.PubkeyToAddress(acc1Key.PublicKey)
    50  	acc2Addr   = crypto.PubkeyToAddress(acc2Key.PublicKey)
    51  
    52  	testContractCode = common.Hex2Bytes("606060405260cc8060106000396000f360606040526000357c01000000000000000000000000000000000000000000000000000000009004806360cd2685146041578063c16431b914606b57603f565b005b6055600480803590602001909190505060a9565b6040518082815260200191505060405180910390f35b60886004808035906020019091908035906020019091905050608a565b005b80600060005083606481101560025790900160005b50819055505b5050565b6000600060005082606481101560025790900160005b5054905060c7565b91905056")
    53  	testContractAddr common.Address
    54  )
    55  
    56  type testOdr struct {
    57  	OdrBackend
    58  	indexerConfig *IndexerConfig
    59  	sdb, ldb      evrdb.Database
    60  	disable       bool
    61  }
    62  
    63  func (odr *testOdr) Database() evrdb.Database {
    64  	return odr.ldb
    65  }
    66  
    67  var ErrOdrDisabled = errors.New("ODR disabled")
    68  
    69  func (odr *testOdr) Retrieve(ctx context.Context, req OdrRequest) error {
    70  	if odr.disable {
    71  		return ErrOdrDisabled
    72  	}
    73  	switch req := req.(type) {
    74  	case *BlockRequest:
    75  		number := rawdb.ReadHeaderNumber(odr.sdb, req.Hash)
    76  		if number != nil {
    77  			req.Rlp = rawdb.ReadBodyRLP(odr.sdb, req.Hash, *number)
    78  		}
    79  	case *ReceiptsRequest:
    80  		number := rawdb.ReadHeaderNumber(odr.sdb, req.Hash)
    81  		if number != nil {
    82  			req.Receipts = rawdb.ReadRawReceipts(odr.sdb, req.Hash, *number)
    83  		}
    84  	case *TrieRequest:
    85  		t, _ := trie.New(req.Id.Root, trie.NewDatabase(odr.sdb))
    86  		nodes := NewNodeSet()
    87  		t.Prove(req.Key, 0, nodes)
    88  		req.Proof = nodes
    89  	case *CodeRequest:
    90  		req.Data, _ = odr.sdb.Get(req.Hash[:])
    91  	}
    92  	req.StoreResult(odr.ldb)
    93  	return nil
    94  }
    95  
    96  func (odr *testOdr) IndexerConfig() *IndexerConfig {
    97  	return odr.indexerConfig
    98  }
    99  
   100  type odrTestFn func(ctx context.Context, db evrdb.Database, bc *core.BlockChain, lc *LightChain, bhash common.Hash) ([]byte, error)
   101  
   102  func TestOdrGetBlockLes2(t *testing.T) { testChainOdr(t, 1, odrGetBlock) }
   103  
   104  func odrGetBlock(ctx context.Context, db evrdb.Database, bc *core.BlockChain, lc *LightChain, bhash common.Hash) ([]byte, error) {
   105  	var block *types.Block
   106  	if bc != nil {
   107  		block = bc.GetBlockByHash(bhash)
   108  	} else {
   109  		block, _ = lc.GetBlockByHash(ctx, bhash)
   110  	}
   111  	if block == nil {
   112  		return nil, nil
   113  	}
   114  	rlp, _ := rlp.EncodeToBytes(block)
   115  	return rlp, nil
   116  }
   117  
   118  func TestOdrGetReceiptsLes2(t *testing.T) { testChainOdr(t, 1, odrGetReceipts) }
   119  
   120  func odrGetReceipts(ctx context.Context, db evrdb.Database, bc *core.BlockChain, lc *LightChain, bhash common.Hash) ([]byte, error) {
   121  	var receipts types.Receipts
   122  	if bc != nil {
   123  		number := rawdb.ReadHeaderNumber(db, bhash)
   124  		if number != nil {
   125  			receipts = rawdb.ReadReceipts(db, bhash, *number, bc.Config())
   126  		}
   127  	} else {
   128  		number := rawdb.ReadHeaderNumber(db, bhash)
   129  		if number != nil {
   130  			receipts, _ = GetBlockReceipts(ctx, lc.Odr(), bhash, *number)
   131  		}
   132  	}
   133  	if receipts == nil {
   134  		return nil, nil
   135  	}
   136  	rlp, _ := rlp.EncodeToBytes(receipts)
   137  	return rlp, nil
   138  }
   139  
   140  func TestOdrAccountsLes2(t *testing.T) { testChainOdr(t, 1, odrAccounts) }
   141  
   142  func odrAccounts(ctx context.Context, db evrdb.Database, bc *core.BlockChain, lc *LightChain, bhash common.Hash) ([]byte, error) {
   143  	dummyAddr := common.HexToAddress("1234567812345678123456781234567812345678")
   144  	acc := []common.Address{testBankAddress, acc1Addr, acc2Addr, dummyAddr}
   145  
   146  	var st *state.StateDB
   147  	if bc == nil {
   148  		header := lc.GetHeaderByHash(bhash)
   149  		st = NewState(ctx, header, lc.Odr())
   150  	} else {
   151  		header := bc.GetHeaderByHash(bhash)
   152  		st, _ = state.New(header.Root, state.NewDatabase(db))
   153  	}
   154  
   155  	var res []byte
   156  	for _, addr := range acc {
   157  		bal := st.GetBalance(addr)
   158  		rlp, _ := rlp.EncodeToBytes(bal)
   159  		res = append(res, rlp...)
   160  	}
   161  	return res, st.Error()
   162  }
   163  
   164  func TestOdrContractCallLes2(t *testing.T) { testChainOdr(t, 1, odrContractCall) }
   165  
   166  type callmsg struct {
   167  	types.Message
   168  }
   169  
   170  func (callmsg) CheckNonce() bool { return false }
   171  
   172  func odrContractCall(ctx context.Context, db evrdb.Database, bc *core.BlockChain, lc *LightChain, bhash common.Hash) ([]byte, error) {
   173  	data := common.Hex2Bytes("60CD26850000000000000000000000000000000000000000000000000000000000000000")
   174  	config := params.TestChainConfig
   175  
   176  	var res []byte
   177  	for i := 0; i < 3; i++ {
   178  		data[35] = byte(i)
   179  
   180  		var (
   181  			st     *state.StateDB
   182  			header *types.Header
   183  			chain  core.ChainContext
   184  		)
   185  		if bc == nil {
   186  			chain = lc
   187  			header = lc.GetHeaderByHash(bhash)
   188  			st = NewState(ctx, header, lc.Odr())
   189  		} else {
   190  			chain = bc
   191  			header = bc.GetHeaderByHash(bhash)
   192  			st, _ = state.New(header.Root, state.NewDatabase(db))
   193  		}
   194  
   195  		// Perform read-only call.
   196  		st.SetBalance(testBankAddress, math.MaxBig256)
   197  		msg := callmsg{types.NewMessage(testBankAddress, &testContractAddr, 0, new(big.Int), 1000000, new(big.Int), data, false)}
   198  		context := core.NewEVMContext(msg, header, chain, nil)
   199  		vmenv := vm.NewEVM(context, st, config, vm.Config{})
   200  		gp := new(core.GasPool).AddGas(math.MaxUint64)
   201  		ret, _, _, _ := core.ApplyMessage(vmenv, msg, gp)
   202  		res = append(res, ret...)
   203  		if st.Error() != nil {
   204  			return res, st.Error()
   205  		}
   206  	}
   207  	return res, nil
   208  }
   209  
   210  func testChainGen(i int, block *core.BlockGen) {
   211  	signer := types.HomesteadSigner{}
   212  	switch i {
   213  	case 0:
   214  		// In block 1, the test bank sends account #1 some ether.
   215  		txValue := new(big.Int).Mul(big.NewInt(1100000), big.NewInt(params.GasPriceConfig))
   216  		tx, _ := types.SignTx(
   217  			types.NewTransaction(block.TxNonce(testBankAddress), acc1Addr, txValue, params.TxGas, big.NewInt(params.GasPriceConfig), nil),
   218  			signer,
   219  			testBankKey,
   220  		)
   221  		block.AddTx(tx)
   222  	case 1:
   223  		// In block 2, the test bank sends some more ether to account #1.
   224  		// acc1Addr passes it on to account #2.
   225  		// acc1Addr creates a test contract.
   226  		tx1, _ := types.SignTx(
   227  			types.NewTransaction(block.TxNonce(testBankAddress), acc1Addr, big.NewInt(1000), params.TxGas, big.NewInt(params.GasPriceConfig), nil),
   228  			signer,
   229  			testBankKey,
   230  		)
   231  		nonce := block.TxNonce(acc1Addr)
   232  		tx2, _ := types.SignTx(
   233  			types.NewTransaction(nonce, acc2Addr, big.NewInt(1000), params.TxGas, big.NewInt(params.GasPriceConfig), nil),
   234  			signer,
   235  			acc1Key,
   236  		)
   237  		nonce++
   238  		tx3, _ := types.SignTx(
   239  			types.NewContractCreation(nonce, big.NewInt(0), 1000000, big.NewInt(params.GasPriceConfig), testContractCode),
   240  			signer,
   241  			acc1Key,
   242  		)
   243  		testContractAddr = crypto.CreateAddress(acc1Addr, nonce)
   244  		block.AddTx(tx1)
   245  		block.AddTx(tx2)
   246  		block.AddTx(tx3)
   247  	case 2:
   248  		// Block 3 is empty but was mined by account #2.
   249  		block.SetCoinbase(acc2Addr)
   250  		block.SetExtra([]byte("yeehaw"))
   251  		data := common.Hex2Bytes("C16431B900000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000001")
   252  		tx, _ := types.SignTx(
   253  			types.NewTransaction(block.TxNonce(testBankAddress), testContractAddr, big.NewInt(0), 100000, big.NewInt(params.GasPriceConfig), data),
   254  			signer,
   255  			testBankKey,
   256  		)
   257  		block.AddTx(tx)
   258  	case 3:
   259  		// Block 4 includes blocks 2 and 3 as uncle headers (with modified extra data).
   260  		b2 := block.PrevBlock(1).Header()
   261  		b2.Extra = []byte("foo")
   262  		block.AddUncle(b2)
   263  		b3 := block.PrevBlock(2).Header()
   264  		b3.Extra = []byte("foo")
   265  		block.AddUncle(b3)
   266  		data := common.Hex2Bytes("C16431B900000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000002")
   267  		tx, _ := types.SignTx(
   268  			types.NewTransaction(block.TxNonce(testBankAddress), testContractAddr, big.NewInt(0), 100000, big.NewInt(params.GasPriceConfig), data),
   269  			signer,
   270  			testBankKey,
   271  		)
   272  		block.AddTx(tx)
   273  	}
   274  }
   275  
   276  func testChainOdr(t *testing.T, protocol int, fn odrTestFn) {
   277  	var (
   278  		sdb     = rawdb.NewMemoryDatabase()
   279  		ldb     = rawdb.NewMemoryDatabase()
   280  		gspec   = core.Genesis{Alloc: core.GenesisAlloc{testBankAddress: {Balance: testBankFunds}}}
   281  		genesis = gspec.MustCommit(sdb)
   282  	)
   283  	gspec.MustCommit(ldb)
   284  	// Assemble the test environment
   285  	blockchain, _ := core.NewBlockChain(sdb, nil, params.TestChainConfig, ethash.NewFullFaker(), vm.Config{}, nil)
   286  	gchain, _ := core.GenerateChain(params.TestChainConfig, genesis, ethash.NewFaker(), sdb, 4, testChainGen)
   287  	if _, err := blockchain.InsertChain(gchain); err != nil {
   288  		t.Fatal(err)
   289  	}
   290  
   291  	odr := &testOdr{sdb: sdb, ldb: ldb, indexerConfig: TestClientIndexerConfig}
   292  	lightchain, err := NewLightChain(odr, params.TestChainConfig, ethash.NewFullFaker())
   293  	if err != nil {
   294  		t.Fatal(err)
   295  	}
   296  	headers := make([]*types.Header, len(gchain))
   297  	for i, block := range gchain {
   298  		headers[i] = block.Header()
   299  	}
   300  	if _, err := lightchain.InsertHeaderChain(headers, 1); err != nil {
   301  		t.Fatal(err)
   302  	}
   303  
   304  	test := func(expFail int) {
   305  		for i := uint64(0); i <= blockchain.CurrentHeader().Number.Uint64(); i++ {
   306  			bhash := rawdb.ReadCanonicalHash(sdb, i)
   307  			b1, err := fn(NoOdr, sdb, blockchain, nil, bhash)
   308  			if err != nil {
   309  				t.Fatalf("error in full-node test for block %d: %v", i, err)
   310  			}
   311  
   312  			ctx, cancel := context.WithTimeout(context.Background(), 200*time.Millisecond)
   313  			defer cancel()
   314  
   315  			exp := i < uint64(expFail)
   316  			b2, err := fn(ctx, ldb, nil, lightchain, bhash)
   317  			if err != nil && exp {
   318  				t.Errorf("error in ODR test for block %d: %v", i, err)
   319  			}
   320  
   321  			eq := bytes.Equal(b1, b2)
   322  			if exp && !eq {
   323  				t.Errorf("ODR test output for block %d doesn't match full node", i)
   324  			}
   325  		}
   326  	}
   327  
   328  	// expect retrievals to fail (except genesis block) without a les peer
   329  	t.Log("checking without ODR")
   330  	odr.disable = true
   331  	test(1)
   332  
   333  	// expect all retrievals to pass with ODR enabled
   334  	t.Log("checking with ODR")
   335  	odr.disable = false
   336  	test(len(gchain))
   337  
   338  	// still expect all retrievals to pass, now data should be cached locally
   339  	t.Log("checking without ODR, should be cached")
   340  	odr.disable = true
   341  	test(len(gchain))
   342  }