github.com/ylsGit/go-ethereum@v1.6.5/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
    90  
    91  func TestOdrGetBlockLes1(t *testing.T) { testChainOdr(t, 1, 1, odrGetBlock) }
    92  
    93  func odrGetBlock(ctx context.Context, db ethdb.Database, bc *core.BlockChain, lc *LightChain, bhash common.Hash) []byte {
    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
   102  	}
   103  	rlp, _ := rlp.EncodeToBytes(block)
   104  	return rlp
   105  }
   106  
   107  func TestOdrGetReceiptsLes1(t *testing.T) { testChainOdr(t, 1, 1, odrGetReceipts) }
   108  
   109  func odrGetReceipts(ctx context.Context, db ethdb.Database, bc *core.BlockChain, lc *LightChain, bhash common.Hash) []byte {
   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
   118  	}
   119  	rlp, _ := rlp.EncodeToBytes(receipts)
   120  	return rlp
   121  }
   122  
   123  func TestOdrAccountsLes1(t *testing.T) { testChainOdr(t, 1, 1, odrAccounts) }
   124  
   125  func odrAccounts(ctx context.Context, db ethdb.Database, bc *core.BlockChain, lc *LightChain, bhash common.Hash) []byte {
   126  	dummyAddr := common.HexToAddress("1234567812345678123456781234567812345678")
   127  	acc := []common.Address{testBankAddress, acc1Addr, acc2Addr, dummyAddr}
   128  
   129  	var res []byte
   130  	for _, addr := range acc {
   131  		if bc != nil {
   132  			header := bc.GetHeaderByHash(bhash)
   133  			st, err := state.New(header.Root, db)
   134  			if err == nil {
   135  				bal := st.GetBalance(addr)
   136  				rlp, _ := rlp.EncodeToBytes(bal)
   137  				res = append(res, rlp...)
   138  			}
   139  		} else {
   140  			header := lc.GetHeaderByHash(bhash)
   141  			st := NewLightState(StateTrieID(header), lc.Odr())
   142  			bal, err := st.GetBalance(ctx, addr)
   143  			if err == nil {
   144  				rlp, _ := rlp.EncodeToBytes(bal)
   145  				res = append(res, rlp...)
   146  			}
   147  		}
   148  	}
   149  
   150  	return res
   151  }
   152  
   153  func TestOdrContractCallLes1(t *testing.T) { testChainOdr(t, 1, 2, odrContractCall) }
   154  
   155  type callmsg struct {
   156  	types.Message
   157  }
   158  
   159  func (callmsg) CheckNonce() bool { return false }
   160  
   161  func odrContractCall(ctx context.Context, db ethdb.Database, bc *core.BlockChain, lc *LightChain, bhash common.Hash) []byte {
   162  	data := common.Hex2Bytes("60CD26850000000000000000000000000000000000000000000000000000000000000000")
   163  
   164  	config := params.TestChainConfig
   165  
   166  	var res []byte
   167  	for i := 0; i < 3; i++ {
   168  		data[35] = byte(i)
   169  		if bc != nil {
   170  			header := bc.GetHeaderByHash(bhash)
   171  			statedb, err := state.New(header.Root, db)
   172  			if err == nil {
   173  				from := statedb.GetOrNewStateObject(testBankAddress)
   174  				from.SetBalance(math.MaxBig256)
   175  
   176  				msg := callmsg{types.NewMessage(from.Address(), &testContractAddr, 0, new(big.Int), big.NewInt(1000000), new(big.Int), data, false)}
   177  
   178  				context := core.NewEVMContext(msg, header, bc, nil)
   179  				vmenv := vm.NewEVM(context, statedb, config, vm.Config{})
   180  
   181  				gp := new(core.GasPool).AddGas(math.MaxBig256)
   182  				ret, _, _ := core.ApplyMessage(vmenv, msg, gp)
   183  				res = append(res, ret...)
   184  			}
   185  		} else {
   186  			header := lc.GetHeaderByHash(bhash)
   187  			state := NewLightState(StateTrieID(header), lc.Odr())
   188  			vmstate := NewVMState(ctx, state)
   189  			from, err := state.GetOrNewStateObject(ctx, testBankAddress)
   190  			if err == nil {
   191  				from.SetBalance(math.MaxBig256)
   192  
   193  				msg := callmsg{types.NewMessage(from.Address(), &testContractAddr, 0, new(big.Int), big.NewInt(1000000), new(big.Int), data, false)}
   194  				context := core.NewEVMContext(msg, header, lc, nil)
   195  				vmenv := vm.NewEVM(context, vmstate, config, vm.Config{})
   196  				gp := new(core.GasPool).AddGas(math.MaxBig256)
   197  				ret, _, _ := core.ApplyMessage(vmenv, msg, gp)
   198  				if vmstate.Error() == nil {
   199  					res = append(res, ret...)
   200  				}
   201  			}
   202  		}
   203  	}
   204  	return res
   205  }
   206  
   207  func testChainGen(i int, block *core.BlockGen) {
   208  	signer := types.HomesteadSigner{}
   209  	switch i {
   210  	case 0:
   211  		// In block 1, the test bank sends account #1 some ether.
   212  		tx, _ := types.SignTx(types.NewTransaction(block.TxNonce(testBankAddress), acc1Addr, big.NewInt(10000), bigTxGas, nil, nil), signer, testBankKey)
   213  		block.AddTx(tx)
   214  	case 1:
   215  		// In block 2, the test bank sends some more ether to account #1.
   216  		// acc1Addr passes it on to account #2.
   217  		// acc1Addr creates a test contract.
   218  		tx1, _ := types.SignTx(types.NewTransaction(block.TxNonce(testBankAddress), acc1Addr, big.NewInt(1000), bigTxGas, nil, nil), signer, testBankKey)
   219  		nonce := block.TxNonce(acc1Addr)
   220  		tx2, _ := types.SignTx(types.NewTransaction(nonce, acc2Addr, big.NewInt(1000), bigTxGas, nil, nil), signer, acc1Key)
   221  		nonce++
   222  		tx3, _ := types.SignTx(types.NewContractCreation(nonce, big.NewInt(0), big.NewInt(1000000), big.NewInt(0), testContractCode), signer, acc1Key)
   223  		testContractAddr = crypto.CreateAddress(acc1Addr, nonce)
   224  		block.AddTx(tx1)
   225  		block.AddTx(tx2)
   226  		block.AddTx(tx3)
   227  	case 2:
   228  		// Block 3 is empty but was mined by account #2.
   229  		block.SetCoinbase(acc2Addr)
   230  		block.SetExtra([]byte("yeehaw"))
   231  		data := common.Hex2Bytes("C16431B900000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000001")
   232  		tx, _ := types.SignTx(types.NewTransaction(block.TxNonce(testBankAddress), testContractAddr, big.NewInt(0), big.NewInt(100000), nil, data), signer, testBankKey)
   233  		block.AddTx(tx)
   234  	case 3:
   235  		// Block 4 includes blocks 2 and 3 as uncle headers (with modified extra data).
   236  		b2 := block.PrevBlock(1).Header()
   237  		b2.Extra = []byte("foo")
   238  		block.AddUncle(b2)
   239  		b3 := block.PrevBlock(2).Header()
   240  		b3.Extra = []byte("foo")
   241  		block.AddUncle(b3)
   242  		data := common.Hex2Bytes("C16431B900000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000002")
   243  		tx, _ := types.SignTx(types.NewTransaction(block.TxNonce(testBankAddress), testContractAddr, big.NewInt(0), big.NewInt(100000), nil, data), signer, testBankKey)
   244  		block.AddTx(tx)
   245  	}
   246  }
   247  
   248  func testChainOdr(t *testing.T, protocol int, expFail uint64, fn odrTestFn) {
   249  	var (
   250  		evmux   = new(event.TypeMux)
   251  		sdb, _  = ethdb.NewMemDatabase()
   252  		ldb, _  = ethdb.NewMemDatabase()
   253  		gspec   = core.Genesis{Alloc: core.GenesisAlloc{testBankAddress: {Balance: testBankFunds}}}
   254  		genesis = gspec.MustCommit(sdb)
   255  	)
   256  	gspec.MustCommit(ldb)
   257  	// Assemble the test environment
   258  	blockchain, _ := core.NewBlockChain(sdb, params.TestChainConfig, ethash.NewFullFaker(), evmux, vm.Config{})
   259  	gchain, _ := core.GenerateChain(params.TestChainConfig, genesis, sdb, 4, testChainGen)
   260  	if _, err := blockchain.InsertChain(gchain); err != nil {
   261  		panic(err)
   262  	}
   263  
   264  	odr := &testOdr{sdb: sdb, ldb: ldb}
   265  	lightchain, _ := NewLightChain(odr, params.TestChainConfig, ethash.NewFullFaker(), evmux)
   266  	headers := make([]*types.Header, len(gchain))
   267  	for i, block := range gchain {
   268  		headers[i] = block.Header()
   269  	}
   270  	if _, err := lightchain.InsertHeaderChain(headers, 1); err != nil {
   271  		panic(err)
   272  	}
   273  
   274  	test := func(expFail uint64) {
   275  		for i := uint64(0); i <= blockchain.CurrentHeader().Number.Uint64(); i++ {
   276  			bhash := core.GetCanonicalHash(sdb, i)
   277  			b1 := fn(NoOdr, sdb, blockchain, nil, bhash)
   278  
   279  			ctx, cancel := context.WithTimeout(context.Background(), 200*time.Millisecond)
   280  			defer cancel()
   281  			b2 := fn(ctx, ldb, nil, lightchain, bhash)
   282  
   283  			eq := bytes.Equal(b1, b2)
   284  			exp := i < expFail
   285  			if exp && !eq {
   286  				t.Errorf("odr mismatch")
   287  			}
   288  			if !exp && eq {
   289  				t.Errorf("unexpected odr match")
   290  			}
   291  		}
   292  	}
   293  
   294  	odr.disable = true
   295  	// expect retrievals to fail (except genesis block) without a les peer
   296  	test(expFail)
   297  	odr.disable = false
   298  	// expect all retrievals to pass
   299  	test(5)
   300  	odr.disable = true
   301  	// still expect all retrievals to pass, now data should be cached locally
   302  	test(5)
   303  }