github.com/cryptogateway/go-paymex@v0.0.0-20210204174735-96277fb1e602/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/cryptogateway/go-paymex/common"
    27  	"github.com/cryptogateway/go-paymex/common/math"
    28  	"github.com/cryptogateway/go-paymex/core"
    29  	"github.com/cryptogateway/go-paymex/core/rawdb"
    30  	"github.com/cryptogateway/go-paymex/core/state"
    31  	"github.com/cryptogateway/go-paymex/core/types"
    32  	"github.com/cryptogateway/go-paymex/core/vm"
    33  	"github.com/cryptogateway/go-paymex/ethdb"
    34  	"github.com/cryptogateway/go-paymex/light"
    35  	"github.com/cryptogateway/go-paymex/params"
    36  	"github.com/cryptogateway/go-paymex/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), nil)
    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), nil)
   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.NewEVMBlockContext(header, bc, nil)
   134  				txContext := core.NewEVMTxContext(msg)
   135  				vmenv := vm.NewEVM(context, txContext, statedb, config, vm.Config{})
   136  
   137  				//vmenv := core.NewEnv(statedb, config, bc, msg, header, vm.Config{})
   138  				gp := new(core.GasPool).AddGas(math.MaxUint64)
   139  				result, _ := core.ApplyMessage(vmenv, msg, gp)
   140  				res = append(res, result.Return()...)
   141  			}
   142  		} else {
   143  			header := lc.GetHeaderByHash(bhash)
   144  			state := light.NewState(ctx, header, lc.Odr())
   145  			state.SetBalance(bankAddr, math.MaxBig256)
   146  			msg := callmsg{types.NewMessage(bankAddr, &testContractAddr, 0, new(big.Int), 100000, new(big.Int), data, false)}
   147  			context := core.NewEVMBlockContext(header, lc, nil)
   148  			txContext := core.NewEVMTxContext(msg)
   149  			vmenv := vm.NewEVM(context, txContext, state, config, vm.Config{})
   150  			gp := new(core.GasPool).AddGas(math.MaxUint64)
   151  			result, _ := core.ApplyMessage(vmenv, msg, gp)
   152  			if state.Error() == nil {
   153  				res = append(res, result.Return()...)
   154  			}
   155  		}
   156  	}
   157  	return res
   158  }
   159  
   160  func TestOdrTxStatusLes2(t *testing.T) { testOdr(t, 2, 1, false, odrTxStatus) }
   161  func TestOdrTxStatusLes3(t *testing.T) { testOdr(t, 3, 1, false, odrTxStatus) }
   162  
   163  func odrTxStatus(ctx context.Context, db ethdb.Database, config *params.ChainConfig, bc *core.BlockChain, lc *light.LightChain, bhash common.Hash) []byte {
   164  	var txs types.Transactions
   165  	if bc != nil {
   166  		block := bc.GetBlockByHash(bhash)
   167  		txs = block.Transactions()
   168  	} else {
   169  		if block, _ := lc.GetBlockByHash(ctx, bhash); block != nil {
   170  			btxs := block.Transactions()
   171  			txs = make(types.Transactions, len(btxs))
   172  			for i, tx := range btxs {
   173  				var err error
   174  				txs[i], _, _, _, err = light.GetTransaction(ctx, lc.Odr(), tx.Hash())
   175  				if err != nil {
   176  					return nil
   177  				}
   178  			}
   179  		}
   180  	}
   181  	rlp, _ := rlp.EncodeToBytes(txs)
   182  	return rlp
   183  }
   184  
   185  // testOdr tests odr requests whose validation guaranteed by block headers.
   186  func testOdr(t *testing.T, protocol int, expFail uint64, checkCached bool, fn odrTestFn) {
   187  	// Assemble the test environment
   188  	server, client, tearDown := newClientServerEnv(t, 4, protocol, nil, nil, 0, false, true, true)
   189  	defer tearDown()
   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.speer.hasBlockHook = 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.speer.hasBlockHook = 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.speer.id)
   240  		time.Sleep(time.Millisecond * 10) // ensure that all peerSetNotify callbacks are executed
   241  		test(5)
   242  	}
   243  }