github.com/bloxroute-labs/bor@v0.1.4/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/maticnetwork/bor/common"
    27  	"github.com/maticnetwork/bor/common/math"
    28  	"github.com/maticnetwork/bor/core"
    29  	"github.com/maticnetwork/bor/core/rawdb"
    30  	"github.com/maticnetwork/bor/core/state"
    31  	"github.com/maticnetwork/bor/core/types"
    32  	"github.com/maticnetwork/bor/core/vm"
    33  	"github.com/maticnetwork/bor/ethdb"
    34  	"github.com/maticnetwork/bor/light"
    35  	"github.com/maticnetwork/bor/params"
    36  	"github.com/maticnetwork/bor/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  
    43  func odrGetBlock(ctx context.Context, db ethdb.Database, config *params.ChainConfig, bc *core.BlockChain, lc *light.LightChain, bhash common.Hash) []byte {
    44  	var block *types.Block
    45  	if bc != nil {
    46  		block = bc.GetBlockByHash(bhash)
    47  	} else {
    48  		block, _ = lc.GetBlockByHash(ctx, bhash)
    49  	}
    50  	if block == nil {
    51  		return nil
    52  	}
    53  	rlp, _ := rlp.EncodeToBytes(block)
    54  	return rlp
    55  }
    56  
    57  func TestOdrGetReceiptsLes2(t *testing.T) { testOdr(t, 2, 1, true, 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, config)
    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 TestOdrAccountsLes2(t *testing.T) { testOdr(t, 2, 1, true, odrAccounts) }
    78  
    79  func odrAccounts(ctx context.Context, db ethdb.Database, config *params.ChainConfig, bc *core.BlockChain, lc *light.LightChain, bhash common.Hash) []byte {
    80  	dummyAddr := common.HexToAddress("1234567812345678123456781234567812345678")
    81  	acc := []common.Address{bankAddr, userAddr1, userAddr2, dummyAddr}
    82  
    83  	var (
    84  		res []byte
    85  		st  *state.StateDB
    86  		err error
    87  	)
    88  	for _, addr := range acc {
    89  		if bc != nil {
    90  			header := bc.GetHeaderByHash(bhash)
    91  			st, err = state.New(header.Root, state.NewDatabase(db))
    92  		} else {
    93  			header := lc.GetHeaderByHash(bhash)
    94  			st = light.NewState(ctx, header, lc.Odr())
    95  		}
    96  		if err == nil {
    97  			bal := st.GetBalance(addr)
    98  			rlp, _ := rlp.EncodeToBytes(bal)
    99  			res = append(res, rlp...)
   100  		}
   101  	}
   102  	return res
   103  }
   104  
   105  func TestOdrContractCallLes2(t *testing.T) { testOdr(t, 2, 2, true, odrContractCall) }
   106  
   107  type callmsg struct {
   108  	types.Message
   109  }
   110  
   111  func (callmsg) CheckNonce() bool { return false }
   112  
   113  func odrContractCall(ctx context.Context, db ethdb.Database, config *params.ChainConfig, bc *core.BlockChain, lc *light.LightChain, bhash common.Hash) []byte {
   114  	data := common.Hex2Bytes("60CD26850000000000000000000000000000000000000000000000000000000000000000")
   115  
   116  	var res []byte
   117  	for i := 0; i < 3; i++ {
   118  		data[35] = byte(i)
   119  		if bc != nil {
   120  			header := bc.GetHeaderByHash(bhash)
   121  			statedb, err := state.New(header.Root, state.NewDatabase(db))
   122  
   123  			if err == nil {
   124  				from := statedb.GetOrNewStateObject(bankAddr)
   125  				from.SetBalance(math.MaxBig256)
   126  
   127  				msg := callmsg{types.NewMessage(from.Address(), &testContractAddr, 0, new(big.Int), 100000, new(big.Int), data, false)}
   128  
   129  				context := core.NewEVMContext(msg, header, bc, nil)
   130  				vmenv := vm.NewEVM(context, statedb, config, vm.Config{})
   131  
   132  				//vmenv := core.NewEnv(statedb, config, bc, msg, header, vm.Config{})
   133  				gp := new(core.GasPool).AddGas(math.MaxUint64)
   134  				ret, _, _, _ := core.ApplyMessage(vmenv, msg, gp)
   135  				res = append(res, ret...)
   136  			}
   137  		} else {
   138  			header := lc.GetHeaderByHash(bhash)
   139  			state := light.NewState(ctx, header, lc.Odr())
   140  			state.SetBalance(bankAddr, math.MaxBig256)
   141  			msg := callmsg{types.NewMessage(bankAddr, &testContractAddr, 0, new(big.Int), 100000, new(big.Int), data, false)}
   142  			context := core.NewEVMContext(msg, header, lc, nil)
   143  			vmenv := vm.NewEVM(context, state, config, vm.Config{})
   144  			gp := new(core.GasPool).AddGas(math.MaxUint64)
   145  			ret, _, _, _ := core.ApplyMessage(vmenv, msg, gp)
   146  			if state.Error() == nil {
   147  				res = append(res, ret...)
   148  			}
   149  		}
   150  	}
   151  	return res
   152  }
   153  
   154  func TestOdrTxStatusLes2(t *testing.T) { testOdr(t, 2, 1, false, odrTxStatus) }
   155  
   156  func odrTxStatus(ctx context.Context, db ethdb.Database, config *params.ChainConfig, bc *core.BlockChain, lc *light.LightChain, bhash common.Hash) []byte {
   157  	var txs types.Transactions
   158  	if bc != nil {
   159  		block := bc.GetBlockByHash(bhash)
   160  		txs = block.Transactions()
   161  	} else {
   162  		if block, _ := lc.GetBlockByHash(ctx, bhash); block != nil {
   163  			btxs := block.Transactions()
   164  			txs = make(types.Transactions, len(btxs))
   165  			for i, tx := range btxs {
   166  				var err error
   167  				txs[i], _, _, _, err = light.GetTransaction(ctx, lc.Odr(), tx.Hash())
   168  				if err != nil {
   169  					return nil
   170  				}
   171  			}
   172  		}
   173  	}
   174  	rlp, _ := rlp.EncodeToBytes(txs)
   175  	return rlp
   176  }
   177  
   178  // testOdr tests odr requests whose validation guaranteed by block headers.
   179  func testOdr(t *testing.T, protocol int, expFail uint64, checkCached bool, fn odrTestFn) {
   180  	// Assemble the test environment
   181  	server, client, tearDown := newClientServerEnv(t, 4, protocol, nil, true)
   182  	defer tearDown()
   183  	client.pm.synchronise(client.rPeer)
   184  
   185  	test := func(expFail uint64) {
   186  		// Mark this as a helper to put the failures at the correct lines
   187  		t.Helper()
   188  
   189  		for i := uint64(0); i <= server.pm.blockchain.CurrentHeader().Number.Uint64(); i++ {
   190  			bhash := rawdb.ReadCanonicalHash(server.db, i)
   191  			b1 := fn(light.NoOdr, server.db, server.pm.chainConfig, server.pm.blockchain.(*core.BlockChain), nil, bhash)
   192  
   193  			ctx, cancel := context.WithTimeout(context.Background(), 200*time.Millisecond)
   194  			defer cancel()
   195  			b2 := fn(ctx, client.db, client.pm.chainConfig, nil, client.pm.blockchain.(*light.LightChain), bhash)
   196  
   197  			eq := bytes.Equal(b1, b2)
   198  			exp := i < expFail
   199  			if exp && !eq {
   200  				t.Fatalf("odr mismatch: have %x, want %x", b2, b1)
   201  			}
   202  			if !exp && eq {
   203  				t.Fatalf("unexpected odr match")
   204  			}
   205  		}
   206  	}
   207  	// temporarily remove peer to test odr fails
   208  	// expect retrievals to fail (except genesis block) without a les peer
   209  	client.peers.Unregister(client.rPeer.id)
   210  	time.Sleep(time.Millisecond * 10) // ensure that all peerSetNotify callbacks are executed
   211  	test(expFail)
   212  
   213  	// expect all retrievals to pass
   214  	client.peers.Register(client.rPeer)
   215  	time.Sleep(time.Millisecond * 10) // ensure that all peerSetNotify callbacks are executed
   216  	client.peers.lock.Lock()
   217  	client.rPeer.hasBlock = func(common.Hash, uint64, bool) bool { return true }
   218  	client.peers.lock.Unlock()
   219  	test(5)
   220  	if checkCached {
   221  		// still expect all retrievals to pass, now data should be cached locally
   222  		client.peers.Unregister(client.rPeer.id)
   223  		time.Sleep(time.Millisecond * 10) // ensure that all peerSetNotify callbacks are executed
   224  		test(5)
   225  	}
   226  }