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