github.com/n1ghtfa1l/go-vnt@v0.6.4-alpha.6/light/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 light
    18  
    19  import (
    20  	"bytes"
    21  	"context"
    22  	"errors"
    23  	"math/big"
    24  	"testing"
    25  	"time"
    26  
    27  	"github.com/vntchain/go-vnt/common"
    28  	"github.com/vntchain/go-vnt/common/math"
    29  	"github.com/vntchain/go-vnt/consensus/mock"
    30  	"github.com/vntchain/go-vnt/core"
    31  	"github.com/vntchain/go-vnt/core/rawdb"
    32  	"github.com/vntchain/go-vnt/core/state"
    33  	"github.com/vntchain/go-vnt/core/types"
    34  	"github.com/vntchain/go-vnt/core/vm"
    35  	"github.com/vntchain/go-vnt/core/wavm"
    36  	"github.com/vntchain/go-vnt/crypto"
    37  	"github.com/vntchain/go-vnt/params"
    38  	"github.com/vntchain/go-vnt/rlp"
    39  	"github.com/vntchain/go-vnt/trie"
    40  	"github.com/vntchain/go-vnt/vntdb"
    41  )
    42  
    43  var (
    44  	testBankKey, _  = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291")
    45  	testBankAddress = crypto.PubkeyToAddress(testBankKey.PublicKey)
    46  	testBankFunds   = big.NewInt(0).Mul(big.NewInt(1e9), big.NewInt(1e18))
    47  
    48  	acc1Key, _ = crypto.HexToECDSA("8a1f9a8f95be41cd7ccb6168179afb4504aefe388d1e14474d32c45c72ce7b7a")
    49  	acc2Key, _ = crypto.HexToECDSA("49a7b37aa6f6645917e7b807e9d1c00d4fa71f18343b0d4122a4d2df64dd6fee")
    50  	acc1Addr   = crypto.PubkeyToAddress(acc1Key.PublicKey)
    51  	acc2Addr   = crypto.PubkeyToAddress(acc2Key.PublicKey)
    52  
    53  	testContractCode = common.Hex2Bytes("606060405260cc8060106000396000f360606040526000357c01000000000000000000000000000000000000000000000000000000009004806360cd2685146041578063c16431b914606b57603f565b005b6055600480803590602001909190505060a9565b6040518082815260200191505060405180910390f35b60886004808035906020019091908035906020019091905050608a565b005b80600060005083606481101560025790900160005b50819055505b5050565b6000600060005082606481101560025790900160005b5054905060c7565b91905056")
    54  	testContractAddr common.Address
    55  )
    56  
    57  type testOdr struct {
    58  	OdrBackend
    59  	sdb, ldb vntdb.Database
    60  	disable  bool
    61  }
    62  
    63  func (odr *testOdr) Database() vntdb.Database {
    64  	return odr.ldb
    65  }
    66  
    67  var ErrOdrDisabled = errors.New("ODR disabled")
    68  
    69  func (odr *testOdr) Retrieve(ctx context.Context, req OdrRequest) error {
    70  	if odr.disable {
    71  		return ErrOdrDisabled
    72  	}
    73  	switch req := req.(type) {
    74  	case *BlockRequest:
    75  		number := rawdb.ReadHeaderNumber(odr.sdb, req.Hash)
    76  		if number != nil {
    77  			req.Rlp = rawdb.ReadBodyRLP(odr.sdb, req.Hash, *number)
    78  		}
    79  	case *ReceiptsRequest:
    80  		number := rawdb.ReadHeaderNumber(odr.sdb, req.Hash)
    81  		if number != nil {
    82  			req.Receipts = rawdb.ReadReceipts(odr.sdb, req.Hash, *number)
    83  		}
    84  	case *TrieRequest:
    85  		t, _ := trie.New(req.Id.Root, trie.NewDatabase(odr.sdb))
    86  		nodes := NewNodeSet()
    87  		t.Prove(req.Key, 0, nodes)
    88  		req.Proof = nodes
    89  	case *CodeRequest:
    90  		req.Data, _ = odr.sdb.Get(req.Hash[:])
    91  	}
    92  	req.StoreResult(odr.ldb)
    93  	return nil
    94  }
    95  
    96  type odrTestFn func(ctx context.Context, db vntdb.Database, bc *core.BlockChain, lc *LightChain, bhash common.Hash) ([]byte, error)
    97  
    98  func TestOdrGetBlockLes1(t *testing.T) { testChainOdr(t, 1, odrGetBlock) }
    99  
   100  func odrGetBlock(ctx context.Context, db vntdb.Database, bc *core.BlockChain, lc *LightChain, bhash common.Hash) ([]byte, error) {
   101  	var block *types.Block
   102  	if bc != nil {
   103  		block = bc.GetBlockByHash(bhash)
   104  	} else {
   105  		block, _ = lc.GetBlockByHash(ctx, bhash)
   106  	}
   107  	if block == nil {
   108  		return nil, nil
   109  	}
   110  	rlp, _ := rlp.EncodeToBytes(block)
   111  	return rlp, nil
   112  }
   113  
   114  func TestOdrGetReceiptsLes1(t *testing.T) { testChainOdr(t, 1, odrGetReceipts) }
   115  
   116  func odrGetReceipts(ctx context.Context, db vntdb.Database, bc *core.BlockChain, lc *LightChain, bhash common.Hash) ([]byte, error) {
   117  	var receipts types.Receipts
   118  	if bc != nil {
   119  		number := rawdb.ReadHeaderNumber(db, bhash)
   120  		if number != nil {
   121  			receipts = rawdb.ReadReceipts(db, bhash, *number)
   122  		}
   123  	} else {
   124  		number := rawdb.ReadHeaderNumber(db, bhash)
   125  		if number != nil {
   126  			receipts, _ = GetBlockReceipts(ctx, lc.Odr(), bhash, *number)
   127  		}
   128  	}
   129  	if receipts == nil {
   130  		return nil, nil
   131  	}
   132  	rlp, _ := rlp.EncodeToBytes(receipts)
   133  	return rlp, nil
   134  }
   135  
   136  func TestOdrAccountsLes1(t *testing.T) { testChainOdr(t, 1, odrAccounts) }
   137  
   138  func odrAccounts(ctx context.Context, db vntdb.Database, bc *core.BlockChain, lc *LightChain, bhash common.Hash) ([]byte, error) {
   139  	dummyAddr := common.HexToAddress("1234567812345678123456781234567812345678")
   140  	acc := []common.Address{testBankAddress, acc1Addr, acc2Addr, dummyAddr}
   141  
   142  	var st *state.StateDB
   143  	if bc == nil {
   144  		header := lc.GetHeaderByHash(bhash)
   145  		st = NewState(ctx, header, lc.Odr())
   146  	} else {
   147  		header := bc.GetHeaderByHash(bhash)
   148  		st, _ = state.New(header.Root, state.NewDatabase(db))
   149  	}
   150  
   151  	var res []byte
   152  	for _, addr := range acc {
   153  		bal := st.GetBalance(addr)
   154  		rlp, _ := rlp.EncodeToBytes(bal)
   155  		res = append(res, rlp...)
   156  	}
   157  	return res, st.Error()
   158  }
   159  
   160  func TestOdrContractCallLes1(t *testing.T) { testChainOdr(t, 1, odrContractCall) }
   161  
   162  type callmsg struct {
   163  	types.Message
   164  }
   165  
   166  func (callmsg) CheckNonce() bool { return false }
   167  
   168  func odrContractCall(ctx context.Context, db vntdb.Database, bc *core.BlockChain, lc *LightChain, bhash common.Hash) ([]byte, error) {
   169  	data := common.Hex2Bytes("60CD26850000000000000000000000000000000000000000000000000000000000000000")
   170  	config := params.TestChainConfig
   171  
   172  	var res []byte
   173  	for i := 0; i < 3; i++ {
   174  		data[35] = byte(i)
   175  
   176  		var (
   177  			st     *state.StateDB
   178  			header *types.Header
   179  			chain  core.ChainContext
   180  		)
   181  		if bc == nil {
   182  			chain = lc
   183  			header = lc.GetHeaderByHash(bhash)
   184  			st = NewState(ctx, header, lc.Odr())
   185  		} else {
   186  			chain = bc
   187  			header = bc.GetHeaderByHash(bhash)
   188  			st, _ = state.New(header.Root, state.NewDatabase(db))
   189  		}
   190  
   191  		// Perform read-only call.
   192  		st.SetBalance(testBankAddress, math.MaxBig256)
   193  		msg := callmsg{types.NewMessage(testBankAddress, &testContractAddr, 0, new(big.Int), 1000000, new(big.Int), data, false)}
   194  		context := core.NewVMContext(msg, header, chain, nil)
   195  		vmenv := wavm.NewWAVM(context, st, config, vm.Config{})
   196  		gp := new(core.GasPool).AddGas(math.MaxUint64)
   197  		ret, _, _, _ := core.ApplyMessage(vmenv, msg, gp)
   198  		res = append(res, ret...)
   199  		if st.Error() != nil {
   200  			return res, st.Error()
   201  		}
   202  	}
   203  	return res, nil
   204  }
   205  
   206  func testChainGen(i int, block *core.BlockGen) {
   207  	signer := types.NewHubbleSigner(big.NewInt(1))
   208  	switch i {
   209  	case 0:
   210  		// In block 1, the test bank sends account #1 some vnt.
   211  		tx, _ := types.SignTx(types.NewTransaction(block.TxNonce(testBankAddress), acc1Addr, big.NewInt(10000), params.TxGas, nil, nil), signer, testBankKey)
   212  		block.AddTx(tx)
   213  	case 1:
   214  		// In block 2, the test bank sends some more vnt to account #1.
   215  		// acc1Addr passes it on to account #2.
   216  		// acc1Addr creates a test contract.
   217  		tx1, _ := types.SignTx(types.NewTransaction(block.TxNonce(testBankAddress), acc1Addr, big.NewInt(1000), params.TxGas, nil, nil), signer, testBankKey)
   218  		nonce := block.TxNonce(acc1Addr)
   219  		tx2, _ := types.SignTx(types.NewTransaction(nonce, acc2Addr, big.NewInt(1000), params.TxGas, nil, nil), signer, acc1Key)
   220  		nonce++
   221  		tx3, _ := types.SignTx(types.NewContractCreation(nonce, big.NewInt(0), 1000000, big.NewInt(0), testContractCode), signer, acc1Key)
   222  		testContractAddr = crypto.CreateAddress(acc1Addr, nonce)
   223  		block.AddTx(tx1)
   224  		block.AddTx(tx2)
   225  		block.AddTx(tx3)
   226  	case 2:
   227  		// Block 3 is empty but was produced by account #2.
   228  		block.SetCoinbase(acc2Addr)
   229  		block.SetExtra([]byte("yeehaw"))
   230  		data := common.Hex2Bytes("C16431B900000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000001")
   231  		tx, _ := types.SignTx(types.NewTransaction(block.TxNonce(testBankAddress), testContractAddr, big.NewInt(0), 100000, nil, data), signer, testBankKey)
   232  		block.AddTx(tx)
   233  	}
   234  }
   235  
   236  func testChainOdr(t *testing.T, protocol int, fn odrTestFn) {
   237  	var (
   238  		sdb     = vntdb.NewMemDatabase()
   239  		ldb     = vntdb.NewMemDatabase()
   240  		gspec   = core.Genesis{Alloc: core.GenesisAlloc{testBankAddress: {Balance: testBankFunds}}}
   241  		genesis = gspec.MustCommit(sdb)
   242  	)
   243  	gspec.MustCommit(ldb)
   244  	// Assemble the test environment
   245  	blockchain, _ := core.NewBlockChain(sdb, nil, params.TestChainConfig, mock.NewMock(), vm.Config{})
   246  	gchain, _ := core.GenerateChain(params.TestChainConfig, genesis, mock.NewMock(), sdb, 4, testChainGen)
   247  	if _, err := blockchain.InsertChain(gchain); err != nil {
   248  		t.Fatal(err)
   249  	}
   250  
   251  	odr := &testOdr{sdb: sdb, ldb: ldb}
   252  	lightchain, err := NewLightChain(odr, params.TestChainConfig, mock.NewMock())
   253  	if err != nil {
   254  		t.Fatal(err)
   255  	}
   256  	headers := make([]*types.Header, len(gchain))
   257  	for i, block := range gchain {
   258  		headers[i] = block.Header()
   259  	}
   260  	if _, err := lightchain.InsertHeaderChain(headers, 1); err != nil {
   261  		t.Fatal(err)
   262  	}
   263  
   264  	test := func(expFail int) {
   265  		for i := uint64(0); i <= blockchain.CurrentHeader().Number.Uint64(); i++ {
   266  			bhash := rawdb.ReadCanonicalHash(sdb, i)
   267  			b1, err := fn(NoOdr, sdb, blockchain, nil, bhash)
   268  			if err != nil {
   269  				t.Fatalf("error in full-node test for block %d: %v", i, err)
   270  			}
   271  
   272  			ctx, cancel := context.WithTimeout(context.Background(), 200*time.Millisecond)
   273  			defer cancel()
   274  
   275  			exp := i < uint64(expFail)
   276  			b2, err := fn(ctx, ldb, nil, lightchain, bhash)
   277  			if err != nil && exp {
   278  				t.Errorf("error in ODR test for block %d: %v", i, err)
   279  			}
   280  
   281  			eq := bytes.Equal(b1, b2)
   282  			if exp && !eq {
   283  				t.Errorf("ODR test output for block %d doesn't match full node", i)
   284  			}
   285  		}
   286  	}
   287  
   288  	// expect retrievals to fail (except genesis block) without a les peer
   289  	t.Log("checking without ODR")
   290  	odr.disable = true
   291  	test(1)
   292  
   293  	// expect all retrievals to pass with ODR enabled
   294  	t.Log("checking with ODR")
   295  	odr.disable = false
   296  	test(len(gchain))
   297  
   298  	// still expect all retrievals to pass, now data should be cached locally
   299  	t.Log("checking without ODR, should be cached")
   300  	odr.disable = true
   301  	test(len(gchain))
   302  }