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