github.com/linapex/ethereum-go-chinese@v0.0.0-20190316121929-f8b7a73c3fa1/les/odr_test.go (about)

     1  
     2  //<developer>
     3  //    <name>linapex 曹一峰</name>
     4  //    <email>linapex@163.com</email>
     5  //    <wx>superexc</wx>
     6  //    <qqgroup>128148617</qqgroup>
     7  //    <url>https://jsq.ink</url>
     8  //    <role>pku engineer</role>
     9  //    <date>2019-03-16 19:16:39</date>
    10  //</624450095663812608>
    11  
    12  
    13  package les
    14  
    15  import (
    16  	"bytes"
    17  	"context"
    18  	"math/big"
    19  	"testing"
    20  	"time"
    21  
    22  	"github.com/ethereum/go-ethereum/common"
    23  	"github.com/ethereum/go-ethereum/common/math"
    24  	"github.com/ethereum/go-ethereum/core"
    25  	"github.com/ethereum/go-ethereum/core/rawdb"
    26  	"github.com/ethereum/go-ethereum/core/state"
    27  	"github.com/ethereum/go-ethereum/core/types"
    28  	"github.com/ethereum/go-ethereum/core/vm"
    29  	"github.com/ethereum/go-ethereum/ethdb"
    30  	"github.com/ethereum/go-ethereum/light"
    31  	"github.com/ethereum/go-ethereum/params"
    32  	"github.com/ethereum/go-ethereum/rlp"
    33  )
    34  
    35  type odrTestFn func(ctx context.Context, db ethdb.Database, config *params.ChainConfig, bc *core.BlockChain, lc *light.LightChain, bhash common.Hash) []byte
    36  
    37  func TestOdrGetBlockLes1(t *testing.T) { testOdr(t, 1, 1, odrGetBlock) }
    38  
    39  func TestOdrGetBlockLes2(t *testing.T) { testOdr(t, 2, 1, odrGetBlock) }
    40  
    41  func odrGetBlock(ctx context.Context, db ethdb.Database, config *params.ChainConfig, bc *core.BlockChain, lc *light.LightChain, bhash common.Hash) []byte {
    42  	var block *types.Block
    43  	if bc != nil {
    44  		block = bc.GetBlockByHash(bhash)
    45  	} else {
    46  		block, _ = lc.GetBlockByHash(ctx, bhash)
    47  	}
    48  	if block == nil {
    49  		return nil
    50  	}
    51  	rlp, _ := rlp.EncodeToBytes(block)
    52  	return rlp
    53  }
    54  
    55  func TestOdrGetReceiptsLes1(t *testing.T) { testOdr(t, 1, 1, odrGetReceipts) }
    56  
    57  func TestOdrGetReceiptsLes2(t *testing.T) { testOdr(t, 2, 1, odrGetReceipts) }
    58  
    59  func odrGetReceipts(ctx context.Context, db ethdb.Database, config *params.ChainConfig, bc *core.BlockChain, lc *light.LightChain, bhash common.Hash) []byte {
    60  	var receipts types.Receipts
    61  	if bc != nil {
    62  		if number := rawdb.ReadHeaderNumber(db, bhash); number != nil {
    63  			receipts = rawdb.ReadReceipts(db, bhash, *number)
    64  		}
    65  	} else {
    66  		if number := rawdb.ReadHeaderNumber(db, bhash); number != nil {
    67  			receipts, _ = light.GetBlockReceipts(ctx, lc.Odr(), bhash, *number)
    68  		}
    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  //testOdr tests odr requests whose validation guaranteed by block headers.
   159  func testOdr(t *testing.T, protocol int, expFail uint64, fn odrTestFn) {
   160  //组装测试环境
   161  	server, client, tearDown := newClientServerEnv(t, 4, protocol, nil, true)
   162  	defer tearDown()
   163  	client.pm.synchronise(client.rPeer)
   164  
   165  	test := func(expFail uint64) {
   166  		for i := uint64(0); i <= server.pm.blockchain.CurrentHeader().Number.Uint64(); i++ {
   167  			bhash := rawdb.ReadCanonicalHash(server.db, i)
   168  			b1 := fn(light.NoOdr, server.db, server.pm.chainConfig, server.pm.blockchain.(*core.BlockChain), nil, bhash)
   169  
   170  			ctx, cancel := context.WithTimeout(context.Background(), 200*time.Millisecond)
   171  			defer cancel()
   172  			b2 := fn(ctx, client.db, client.pm.chainConfig, nil, client.pm.blockchain.(*light.LightChain), bhash)
   173  
   174  			eq := bytes.Equal(b1, b2)
   175  			exp := i < expFail
   176  			if exp && !eq {
   177  				t.Errorf("odr mismatch")
   178  			}
   179  			if !exp && eq {
   180  				t.Errorf("unexpected odr match")
   181  			}
   182  		}
   183  	}
   184  //暂时删除对等测试ODR失败
   185  //预计在没有LES对等机的情况下检索失败(Genesis块除外)
   186  	client.peers.Unregister(client.rPeer.id)
   187  time.Sleep(time.Millisecond * 10) //ensure that all peerSetNotify callbacks are executed
   188  	test(expFail)
   189  //希望所有检索都通过
   190  	client.peers.Register(client.rPeer)
   191  time.Sleep(time.Millisecond * 10) //确保执行所有peersetnotify回调
   192  	client.peers.lock.Lock()
   193  	client.rPeer.hasBlock = func(common.Hash, uint64, bool) bool { return true }
   194  	client.peers.lock.Unlock()
   195  	test(5)
   196  //仍然希望通过所有检索,现在应该在本地缓存数据
   197  	client.peers.Unregister(client.rPeer.id)
   198  time.Sleep(time.Millisecond * 10) //确保执行所有peersetnotify回调
   199  	test(5)
   200  }
   201