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