github.com/guiltylotus/go-ethereum@v1.9.7/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/rawdb"
    30  	"github.com/ethereum/go-ethereum/core/state"
    31  	"github.com/ethereum/go-ethereum/core/types"
    32  	"github.com/ethereum/go-ethereum/core/vm"
    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 TestOdrGetBlockLes2(t *testing.T) { testOdr(t, 2, 1, true, odrGetBlock) }
    42  func TestOdrGetBlockLes3(t *testing.T) { testOdr(t, 3, 1, true, odrGetBlock) }
    43  
    44  func odrGetBlock(ctx context.Context, db ethdb.Database, config *params.ChainConfig, bc *core.BlockChain, lc *light.LightChain, bhash common.Hash) []byte {
    45  	var block *types.Block
    46  	if bc != nil {
    47  		block = bc.GetBlockByHash(bhash)
    48  	} else {
    49  		block, _ = lc.GetBlockByHash(ctx, bhash)
    50  	}
    51  	if block == nil {
    52  		return nil
    53  	}
    54  	rlp, _ := rlp.EncodeToBytes(block)
    55  	return rlp
    56  }
    57  
    58  func TestOdrGetReceiptsLes2(t *testing.T) { testOdr(t, 2, 1, true, odrGetReceipts) }
    59  func TestOdrGetReceiptsLes3(t *testing.T) { testOdr(t, 3, 1, true, odrGetReceipts) }
    60  
    61  func odrGetReceipts(ctx context.Context, db ethdb.Database, config *params.ChainConfig, bc *core.BlockChain, lc *light.LightChain, bhash common.Hash) []byte {
    62  	var receipts types.Receipts
    63  	if bc != nil {
    64  		if number := rawdb.ReadHeaderNumber(db, bhash); number != nil {
    65  			receipts = rawdb.ReadReceipts(db, bhash, *number, config)
    66  		}
    67  	} else {
    68  		if number := rawdb.ReadHeaderNumber(db, bhash); number != nil {
    69  			receipts, _ = light.GetBlockReceipts(ctx, lc.Odr(), bhash, *number)
    70  		}
    71  	}
    72  	if receipts == nil {
    73  		return nil
    74  	}
    75  	rlp, _ := rlp.EncodeToBytes(receipts)
    76  	return rlp
    77  }
    78  
    79  func TestOdrAccountsLes2(t *testing.T) { testOdr(t, 2, 1, true, odrAccounts) }
    80  func TestOdrAccountsLes3(t *testing.T) { testOdr(t, 3, 1, true, odrAccounts) }
    81  
    82  func odrAccounts(ctx context.Context, db ethdb.Database, config *params.ChainConfig, bc *core.BlockChain, lc *light.LightChain, bhash common.Hash) []byte {
    83  	dummyAddr := common.HexToAddress("1234567812345678123456781234567812345678")
    84  	acc := []common.Address{bankAddr, userAddr1, userAddr2, dummyAddr}
    85  
    86  	var (
    87  		res []byte
    88  		st  *state.StateDB
    89  		err error
    90  	)
    91  	for _, addr := range acc {
    92  		if bc != nil {
    93  			header := bc.GetHeaderByHash(bhash)
    94  			st, err = state.New(header.Root, state.NewDatabase(db))
    95  		} else {
    96  			header := lc.GetHeaderByHash(bhash)
    97  			st = light.NewState(ctx, header, lc.Odr())
    98  		}
    99  		if err == nil {
   100  			bal := st.GetBalance(addr)
   101  			rlp, _ := rlp.EncodeToBytes(bal)
   102  			res = append(res, rlp...)
   103  		}
   104  	}
   105  	return res
   106  }
   107  
   108  func TestOdrContractCallLes2(t *testing.T) { testOdr(t, 2, 2, true, odrContractCall) }
   109  func TestOdrContractCallLes3(t *testing.T) { testOdr(t, 3, 2, true, 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(bankAddr)
   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(bankAddr, math.MaxBig256)
   145  			msg := callmsg{types.NewMessage(bankAddr, &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 TestOdrTxStatusLes2(t *testing.T) { testOdr(t, 2, 1, false, odrTxStatus) }
   159  func TestOdrTxStatusLes3(t *testing.T) { testOdr(t, 3, 1, false, odrTxStatus) }
   160  
   161  func odrTxStatus(ctx context.Context, db ethdb.Database, config *params.ChainConfig, bc *core.BlockChain, lc *light.LightChain, bhash common.Hash) []byte {
   162  	var txs types.Transactions
   163  	if bc != nil {
   164  		block := bc.GetBlockByHash(bhash)
   165  		txs = block.Transactions()
   166  	} else {
   167  		if block, _ := lc.GetBlockByHash(ctx, bhash); block != nil {
   168  			btxs := block.Transactions()
   169  			txs = make(types.Transactions, len(btxs))
   170  			for i, tx := range btxs {
   171  				var err error
   172  				txs[i], _, _, _, err = light.GetTransaction(ctx, lc.Odr(), tx.Hash())
   173  				if err != nil {
   174  					return nil
   175  				}
   176  			}
   177  		}
   178  	}
   179  	rlp, _ := rlp.EncodeToBytes(txs)
   180  	return rlp
   181  }
   182  
   183  // testOdr tests odr requests whose validation guaranteed by block headers.
   184  func testOdr(t *testing.T, protocol int, expFail uint64, checkCached bool, fn odrTestFn) {
   185  	// Assemble the test environment
   186  	server, client, tearDown := newClientServerEnv(t, 4, protocol, nil, nil, 0, false, true)
   187  	defer tearDown()
   188  
   189  	client.handler.synchronise(client.peer.peer)
   190  
   191  	// Ensure the client has synced all necessary data.
   192  	clientHead := client.handler.backend.blockchain.CurrentHeader()
   193  	if clientHead.Number.Uint64() != 4 {
   194  		t.Fatalf("Failed to sync the chain with server, head: %v", clientHead.Number.Uint64())
   195  	}
   196  	// Disable the mechanism that we will wait a few time for request
   197  	// even there is no suitable peer to send right now.
   198  	waitForPeers = 0
   199  
   200  	test := func(expFail uint64) {
   201  		// Mark this as a helper to put the failures at the correct lines
   202  		t.Helper()
   203  
   204  		for i := uint64(0); i <= server.handler.blockchain.CurrentHeader().Number.Uint64(); i++ {
   205  			bhash := rawdb.ReadCanonicalHash(server.db, i)
   206  			b1 := fn(light.NoOdr, server.db, server.handler.server.chainConfig, server.handler.blockchain, nil, bhash)
   207  
   208  			// Set the timeout as 1 second here, ensure there is enough time
   209  			// for travis to make the action.
   210  			ctx, cancel := context.WithTimeout(context.Background(), time.Second)
   211  			b2 := fn(ctx, client.db, client.handler.backend.chainConfig, nil, client.handler.backend.blockchain, bhash)
   212  			cancel()
   213  
   214  			eq := bytes.Equal(b1, b2)
   215  			exp := i < expFail
   216  			if exp && !eq {
   217  				t.Fatalf("odr mismatch: have %x, want %x", b2, b1)
   218  			}
   219  			if !exp && eq {
   220  				t.Fatalf("unexpected odr match")
   221  			}
   222  		}
   223  	}
   224  
   225  	// expect retrievals to fail (except genesis block) without a les peer
   226  	client.handler.backend.peers.lock.Lock()
   227  	client.peer.peer.hasBlock = func(common.Hash, uint64, bool) bool { return false }
   228  	client.handler.backend.peers.lock.Unlock()
   229  	test(expFail)
   230  
   231  	// expect all retrievals to pass
   232  	client.handler.backend.peers.lock.Lock()
   233  	client.peer.peer.hasBlock = func(common.Hash, uint64, bool) bool { return true }
   234  	client.handler.backend.peers.lock.Unlock()
   235  	test(5)
   236  
   237  	// still expect all retrievals to pass, now data should be cached locally
   238  	if checkCached {
   239  		client.handler.backend.peers.Unregister(client.peer.peer.id)
   240  		time.Sleep(time.Millisecond * 10) // ensure that all peerSetNotify callbacks are executed
   241  		test(5)
   242  	}
   243  }