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