github.com/fxsjy/go-ethereum@v1.8.4-0.20180410143526-2e247705cd27/les/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 les
    18  
    19  import (
    20  	"bytes"
    21  	"context"
    22  	"math/big"
    23  	"testing"
    24  	"time"
    25  
    26  	"github.com/ethereum/go-ethereum/common"
    27  	"github.com/ethereum/go-ethereum/common/math"
    28  	"github.com/ethereum/go-ethereum/core"
    29  	"github.com/ethereum/go-ethereum/core/state"
    30  	"github.com/ethereum/go-ethereum/core/types"
    31  	"github.com/ethereum/go-ethereum/core/vm"
    32  	"github.com/ethereum/go-ethereum/eth"
    33  	"github.com/ethereum/go-ethereum/ethdb"
    34  	"github.com/ethereum/go-ethereum/light"
    35  	"github.com/ethereum/go-ethereum/params"
    36  	"github.com/ethereum/go-ethereum/rlp"
    37  )
    38  
    39  type odrTestFn func(ctx context.Context, db ethdb.Database, config *params.ChainConfig, bc *core.BlockChain, lc *light.LightChain, bhash common.Hash) []byte
    40  
    41  func TestOdrGetBlockLes1(t *testing.T) { testOdr(t, 1, 1, odrGetBlock) }
    42  
    43  func TestOdrGetBlockLes2(t *testing.T) { testOdr(t, 2, 1, odrGetBlock) }
    44  
    45  func odrGetBlock(ctx context.Context, db ethdb.Database, config *params.ChainConfig, bc *core.BlockChain, lc *light.LightChain, bhash common.Hash) []byte {
    46  	var block *types.Block
    47  	if bc != nil {
    48  		block = bc.GetBlockByHash(bhash)
    49  	} else {
    50  		block, _ = lc.GetBlockByHash(ctx, bhash)
    51  	}
    52  	if block == nil {
    53  		return nil
    54  	}
    55  	rlp, _ := rlp.EncodeToBytes(block)
    56  	return rlp
    57  }
    58  
    59  func TestOdrGetReceiptsLes1(t *testing.T) { testOdr(t, 1, 1, odrGetReceipts) }
    60  
    61  func TestOdrGetReceiptsLes2(t *testing.T) { testOdr(t, 2, 1, odrGetReceipts) }
    62  
    63  func odrGetReceipts(ctx context.Context, db ethdb.Database, config *params.ChainConfig, bc *core.BlockChain, lc *light.LightChain, bhash common.Hash) []byte {
    64  	var receipts types.Receipts
    65  	if bc != nil {
    66  		receipts = core.GetBlockReceipts(db, bhash, core.GetBlockNumber(db, bhash))
    67  	} else {
    68  		receipts, _ = light.GetBlockReceipts(ctx, lc.Odr(), bhash, core.GetBlockNumber(db, bhash))
    69  	}
    70  	if receipts == nil {
    71  		return nil
    72  	}
    73  	rlp, _ := rlp.EncodeToBytes(receipts)
    74  	return rlp
    75  }
    76  
    77  func TestOdrAccountsLes1(t *testing.T) { testOdr(t, 1, 1, odrAccounts) }
    78  
    79  func TestOdrAccountsLes2(t *testing.T) { testOdr(t, 2, 1, odrAccounts) }
    80  
    81  func odrAccounts(ctx context.Context, db ethdb.Database, config *params.ChainConfig, bc *core.BlockChain, lc *light.LightChain, bhash common.Hash) []byte {
    82  	dummyAddr := common.HexToAddress("1234567812345678123456781234567812345678")
    83  	acc := []common.Address{testBankAddress, acc1Addr, acc2Addr, dummyAddr}
    84  
    85  	var (
    86  		res []byte
    87  		st  *state.StateDB
    88  		err error
    89  	)
    90  	for _, addr := range acc {
    91  		if bc != nil {
    92  			header := bc.GetHeaderByHash(bhash)
    93  			st, err = state.New(header.Root, state.NewDatabase(db))
    94  		} else {
    95  			header := lc.GetHeaderByHash(bhash)
    96  			st = light.NewState(ctx, header, lc.Odr())
    97  		}
    98  		if err == nil {
    99  			bal := st.GetBalance(addr)
   100  			rlp, _ := rlp.EncodeToBytes(bal)
   101  			res = append(res, rlp...)
   102  		}
   103  	}
   104  	return res
   105  }
   106  
   107  func TestOdrContractCallLes1(t *testing.T) { testOdr(t, 1, 2, odrContractCall) }
   108  
   109  func TestOdrContractCallLes2(t *testing.T) { testOdr(t, 2, 2, odrContractCall) }
   110  
   111  type callmsg struct {
   112  	types.Message
   113  }
   114  
   115  func (callmsg) CheckNonce() bool { return false }
   116  
   117  func odrContractCall(ctx context.Context, db ethdb.Database, config *params.ChainConfig, bc *core.BlockChain, lc *light.LightChain, bhash common.Hash) []byte {
   118  	data := common.Hex2Bytes("60CD26850000000000000000000000000000000000000000000000000000000000000000")
   119  
   120  	var res []byte
   121  	for i := 0; i < 3; i++ {
   122  		data[35] = byte(i)
   123  		if bc != nil {
   124  			header := bc.GetHeaderByHash(bhash)
   125  			statedb, err := state.New(header.Root, state.NewDatabase(db))
   126  
   127  			if err == nil {
   128  				from := statedb.GetOrNewStateObject(testBankAddress)
   129  				from.SetBalance(math.MaxBig256)
   130  
   131  				msg := callmsg{types.NewMessage(from.Address(), &testContractAddr, 0, new(big.Int), 100000, new(big.Int), data, false)}
   132  
   133  				context := core.NewEVMContext(msg, header, bc, nil)
   134  				vmenv := vm.NewEVM(context, statedb, config, vm.Config{})
   135  
   136  				//vmenv := core.NewEnv(statedb, config, bc, msg, header, vm.Config{})
   137  				gp := new(core.GasPool).AddGas(math.MaxUint64)
   138  				ret, _, _, _ := core.ApplyMessage(vmenv, msg, gp)
   139  				res = append(res, ret...)
   140  			}
   141  		} else {
   142  			header := lc.GetHeaderByHash(bhash)
   143  			state := light.NewState(ctx, header, lc.Odr())
   144  			state.SetBalance(testBankAddress, math.MaxBig256)
   145  			msg := callmsg{types.NewMessage(testBankAddress, &testContractAddr, 0, new(big.Int), 100000, new(big.Int), data, false)}
   146  			context := core.NewEVMContext(msg, header, lc, nil)
   147  			vmenv := vm.NewEVM(context, state, config, vm.Config{})
   148  			gp := new(core.GasPool).AddGas(math.MaxUint64)
   149  			ret, _, _, _ := core.ApplyMessage(vmenv, msg, gp)
   150  			if state.Error() == nil {
   151  				res = append(res, ret...)
   152  			}
   153  		}
   154  	}
   155  	return res
   156  }
   157  
   158  func testOdr(t *testing.T, protocol int, expFail uint64, fn odrTestFn) {
   159  	// Assemble the test environment
   160  	peers := newPeerSet()
   161  	dist := newRequestDistributor(peers, make(chan struct{}))
   162  	rm := newRetrieveManager(peers, dist, nil)
   163  	db, _ := ethdb.NewMemDatabase()
   164  	ldb, _ := ethdb.NewMemDatabase()
   165  	odr := NewLesOdr(ldb, light.NewChtIndexer(db, true), light.NewBloomTrieIndexer(db, true), eth.NewBloomIndexer(db, light.BloomTrieFrequency), rm)
   166  	pm := newTestProtocolManagerMust(t, false, 4, testChainGen, nil, nil, db)
   167  	lpm := newTestProtocolManagerMust(t, true, 0, nil, peers, odr, ldb)
   168  	_, err1, lpeer, err2 := newTestPeerPair("peer", protocol, pm, lpm)
   169  	select {
   170  	case <-time.After(time.Millisecond * 100):
   171  	case err := <-err1:
   172  		t.Fatalf("peer 1 handshake error: %v", err)
   173  	case err := <-err2:
   174  		t.Fatalf("peer 1 handshake error: %v", err)
   175  	}
   176  
   177  	lpm.synchronise(lpeer)
   178  
   179  	test := func(expFail uint64) {
   180  		for i := uint64(0); i <= pm.blockchain.CurrentHeader().Number.Uint64(); i++ {
   181  			bhash := core.GetCanonicalHash(db, i)
   182  			b1 := fn(light.NoOdr, db, pm.chainConfig, pm.blockchain.(*core.BlockChain), nil, bhash)
   183  
   184  			ctx, cancel := context.WithTimeout(context.Background(), 200*time.Millisecond)
   185  			defer cancel()
   186  			b2 := fn(ctx, ldb, lpm.chainConfig, nil, lpm.blockchain.(*light.LightChain), bhash)
   187  
   188  			eq := bytes.Equal(b1, b2)
   189  			exp := i < expFail
   190  			if exp && !eq {
   191  				t.Errorf("odr mismatch")
   192  			}
   193  			if !exp && eq {
   194  				t.Errorf("unexpected odr match")
   195  			}
   196  		}
   197  	}
   198  
   199  	// temporarily remove peer to test odr fails
   200  	// expect retrievals to fail (except genesis block) without a les peer
   201  	peers.Unregister(lpeer.id)
   202  	time.Sleep(time.Millisecond * 10) // ensure that all peerSetNotify callbacks are executed
   203  	test(expFail)
   204  	// expect all retrievals to pass
   205  	peers.Register(lpeer)
   206  	time.Sleep(time.Millisecond * 10) // ensure that all peerSetNotify callbacks are executed
   207  	lpeer.lock.Lock()
   208  	lpeer.hasBlock = func(common.Hash, uint64) bool { return true }
   209  	lpeer.lock.Unlock()
   210  	test(5)
   211  	// still expect all retrievals to pass, now data should be cached locally
   212  	peers.Unregister(lpeer.id)
   213  	time.Sleep(time.Millisecond * 10) // ensure that all peerSetNotify callbacks are executed
   214  	test(5)
   215  }