odr_test.go 11.2 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
// Copyright 2016 The go-ethereum Authors
// This file is part of the go-ethereum library.
//
// The go-ethereum library is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// The go-ethereum library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.

17 18 19 20
package light

import (
	"bytes"
21
	"context"
22 23 24 25 26 27
	"errors"
	"math/big"
	"testing"
	"time"

	"github.com/ethereum/go-ethereum/common"
28
	"github.com/ethereum/go-ethereum/common/math"
29
	"github.com/ethereum/go-ethereum/consensus/ethash"
30
	"github.com/ethereum/go-ethereum/core"
31
	"github.com/ethereum/go-ethereum/core/rawdb"
32 33 34 35 36 37 38 39 40 41 42 43 44
	"github.com/ethereum/go-ethereum/core/state"
	"github.com/ethereum/go-ethereum/core/types"
	"github.com/ethereum/go-ethereum/core/vm"
	"github.com/ethereum/go-ethereum/crypto"
	"github.com/ethereum/go-ethereum/ethdb"
	"github.com/ethereum/go-ethereum/params"
	"github.com/ethereum/go-ethereum/rlp"
	"github.com/ethereum/go-ethereum/trie"
)

var (
	testBankKey, _  = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291")
	testBankAddress = crypto.PubkeyToAddress(testBankKey.PublicKey)
45
	testBankFunds   = big.NewInt(1_000_000_000_000_000_000)
46 47 48 49 50 51 52 53 54 55 56 57

	acc1Key, _ = crypto.HexToECDSA("8a1f9a8f95be41cd7ccb6168179afb4504aefe388d1e14474d32c45c72ce7b7a")
	acc2Key, _ = crypto.HexToECDSA("49a7b37aa6f6645917e7b807e9d1c00d4fa71f18343b0d4122a4d2df64dd6fee")
	acc1Addr   = crypto.PubkeyToAddress(acc1Key.PublicKey)
	acc2Addr   = crypto.PubkeyToAddress(acc2Key.PublicKey)

	testContractCode = common.Hex2Bytes("606060405260cc8060106000396000f360606040526000357c01000000000000000000000000000000000000000000000000000000009004806360cd2685146041578063c16431b914606b57603f565b005b6055600480803590602001909190505060a9565b6040518082815260200191505060405180910390f35b60886004808035906020019091908035906020019091905050608a565b005b80600060005083606481101560025790900160005b50819055505b5050565b6000600060005082606481101560025790900160005b5054905060c7565b91905056")
	testContractAddr common.Address
)

type testOdr struct {
	OdrBackend
58 59 60
	indexerConfig *IndexerConfig
	sdb, ldb      ethdb.Database
	disable       bool
61 62 63 64 65 66 67 68 69 70 71 72 73 74
}

func (odr *testOdr) Database() ethdb.Database {
	return odr.ldb
}

var ErrOdrDisabled = errors.New("ODR disabled")

func (odr *testOdr) Retrieve(ctx context.Context, req OdrRequest) error {
	if odr.disable {
		return ErrOdrDisabled
	}
	switch req := req.(type) {
	case *BlockRequest:
75 76 77 78
		number := rawdb.ReadHeaderNumber(odr.sdb, req.Hash)
		if number != nil {
			req.Rlp = rawdb.ReadBodyRLP(odr.sdb, req.Hash, *number)
		}
79
	case *ReceiptsRequest:
80 81
		number := rawdb.ReadHeaderNumber(odr.sdb, req.Hash)
		if number != nil {
82
			req.Receipts = rawdb.ReadRawReceipts(odr.sdb, req.Hash, *number)
83
		}
84
	case *TrieRequest:
85
		t, _ := trie.New(req.Id.Root, trie.NewDatabase(odr.sdb))
86 87 88
		nodes := NewNodeSet()
		t.Prove(req.Key, 0, nodes)
		req.Proof = nodes
89
	case *CodeRequest:
90
		req.Data = rawdb.ReadCode(odr.sdb, req.Hash)
91 92 93 94 95
	}
	req.StoreResult(odr.ldb)
	return nil
}

96 97 98 99
func (odr *testOdr) IndexerConfig() *IndexerConfig {
	return odr.indexerConfig
}

100
type odrTestFn func(ctx context.Context, db ethdb.Database, bc *core.BlockChain, lc *LightChain, bhash common.Hash) ([]byte, error)
101

102
func TestOdrGetBlockLes2(t *testing.T) { testChainOdr(t, 1, odrGetBlock) }
103

104
func odrGetBlock(ctx context.Context, db ethdb.Database, bc *core.BlockChain, lc *LightChain, bhash common.Hash) ([]byte, error) {
105 106 107 108 109 110 111
	var block *types.Block
	if bc != nil {
		block = bc.GetBlockByHash(bhash)
	} else {
		block, _ = lc.GetBlockByHash(ctx, bhash)
	}
	if block == nil {
112
		return nil, nil
113 114
	}
	rlp, _ := rlp.EncodeToBytes(block)
115
	return rlp, nil
116 117
}

118
func TestOdrGetReceiptsLes2(t *testing.T) { testChainOdr(t, 1, odrGetReceipts) }
119

120
func odrGetReceipts(ctx context.Context, db ethdb.Database, bc *core.BlockChain, lc *LightChain, bhash common.Hash) ([]byte, error) {
121 122
	var receipts types.Receipts
	if bc != nil {
123 124
		number := rawdb.ReadHeaderNumber(db, bhash)
		if number != nil {
125
			receipts = rawdb.ReadReceipts(db, bhash, *number, bc.Config())
126
		}
127
	} else {
128 129 130 131
		number := rawdb.ReadHeaderNumber(db, bhash)
		if number != nil {
			receipts, _ = GetBlockReceipts(ctx, lc.Odr(), bhash, *number)
		}
132 133
	}
	if receipts == nil {
134
		return nil, nil
135 136
	}
	rlp, _ := rlp.EncodeToBytes(receipts)
137
	return rlp, nil
138 139
}

140
func TestOdrAccountsLes2(t *testing.T) { testChainOdr(t, 1, odrAccounts) }
141

142
func odrAccounts(ctx context.Context, db ethdb.Database, bc *core.BlockChain, lc *LightChain, bhash common.Hash) ([]byte, error) {
143 144 145
	dummyAddr := common.HexToAddress("1234567812345678123456781234567812345678")
	acc := []common.Address{testBankAddress, acc1Addr, acc2Addr, dummyAddr}

146 147 148 149 150 151
	var st *state.StateDB
	if bc == nil {
		header := lc.GetHeaderByHash(bhash)
		st = NewState(ctx, header, lc.Odr())
	} else {
		header := bc.GetHeaderByHash(bhash)
152
		st, _ = state.New(header.Root, state.NewDatabase(db), nil)
153 154
	}

155 156
	var res []byte
	for _, addr := range acc {
157 158 159
		bal := st.GetBalance(addr)
		rlp, _ := rlp.EncodeToBytes(bal)
		res = append(res, rlp...)
160
	}
161
	return res, st.Error()
162 163
}

164
func TestOdrContractCallLes2(t *testing.T) { testChainOdr(t, 1, odrContractCall) }
165

166 167
type callmsg struct {
	types.Message
168 169
}

170
func (callmsg) CheckNonce() bool { return false }
171

172
func odrContractCall(ctx context.Context, db ethdb.Database, bc *core.BlockChain, lc *LightChain, bhash common.Hash) ([]byte, error) {
173
	data := common.Hex2Bytes("60CD26850000000000000000000000000000000000000000000000000000000000000000")
174 175
	config := params.TestChainConfig

176 177 178
	var res []byte
	for i := 0; i < 3; i++ {
		data[35] = byte(i)
179

180 181 182 183 184 185 186 187 188
		var (
			st     *state.StateDB
			header *types.Header
			chain  core.ChainContext
		)
		if bc == nil {
			chain = lc
			header = lc.GetHeaderByHash(bhash)
			st = NewState(ctx, header, lc.Odr())
189
		} else {
190 191
			chain = bc
			header = bc.GetHeaderByHash(bhash)
192
			st, _ = state.New(header.Root, state.NewDatabase(db), nil)
193 194 195 196
		}

		// Perform read-only call.
		st.SetBalance(testBankAddress, math.MaxBig256)
197
		msg := callmsg{types.NewMessage(testBankAddress, &testContractAddr, 0, new(big.Int), 1000000, big.NewInt(params.InitialBaseFee), big.NewInt(params.InitialBaseFee), new(big.Int), data, nil, true)}
198 199
		txContext := core.NewEVMTxContext(msg)
		context := core.NewEVMBlockContext(header, chain, nil)
200
		vmenv := vm.NewEVM(context, txContext, st, config, vm.Config{NoBaseFee: true})
201
		gp := new(core.GasPool).AddGas(math.MaxUint64)
202 203
		result, _ := core.ApplyMessage(vmenv, msg, gp)
		res = append(res, result.Return()...)
204 205
		if st.Error() != nil {
			return res, st.Error()
206 207
		}
	}
208
	return res, nil
209 210 211
}

func testChainGen(i int, block *core.BlockGen) {
212
	signer := types.HomesteadSigner{}
213 214 215
	switch i {
	case 0:
		// In block 1, the test bank sends account #1 some ether.
216
		tx, _ := types.SignTx(types.NewTransaction(block.TxNonce(testBankAddress), acc1Addr, big.NewInt(10_000_000_000_000_000), params.TxGas, block.BaseFee(), nil), signer, testBankKey)
217 218 219 220 221
		block.AddTx(tx)
	case 1:
		// In block 2, the test bank sends some more ether to account #1.
		// acc1Addr passes it on to account #2.
		// acc1Addr creates a test contract.
222
		tx1, _ := types.SignTx(types.NewTransaction(block.TxNonce(testBankAddress), acc1Addr, big.NewInt(1_000_000_000_000_000), params.TxGas, block.BaseFee(), nil), signer, testBankKey)
223
		nonce := block.TxNonce(acc1Addr)
224
		tx2, _ := types.SignTx(types.NewTransaction(nonce, acc2Addr, big.NewInt(1_000_000_000_000_000), params.TxGas, block.BaseFee(), nil), signer, acc1Key)
225
		nonce++
226
		tx3, _ := types.SignTx(types.NewContractCreation(nonce, big.NewInt(0), 1000000, block.BaseFee(), testContractCode), signer, acc1Key)
227 228 229 230 231 232 233 234 235
		testContractAddr = crypto.CreateAddress(acc1Addr, nonce)
		block.AddTx(tx1)
		block.AddTx(tx2)
		block.AddTx(tx3)
	case 2:
		// Block 3 is empty but was mined by account #2.
		block.SetCoinbase(acc2Addr)
		block.SetExtra([]byte("yeehaw"))
		data := common.Hex2Bytes("C16431B900000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000001")
236
		tx, _ := types.SignTx(types.NewTransaction(block.TxNonce(testBankAddress), testContractAddr, big.NewInt(0), 100000, block.BaseFee(), data), signer, testBankKey)
237 238 239 240 241 242 243 244 245 246
		block.AddTx(tx)
	case 3:
		// Block 4 includes blocks 2 and 3 as uncle headers (with modified extra data).
		b2 := block.PrevBlock(1).Header()
		b2.Extra = []byte("foo")
		block.AddUncle(b2)
		b3 := block.PrevBlock(2).Header()
		b3.Extra = []byte("foo")
		block.AddUncle(b3)
		data := common.Hex2Bytes("C16431B900000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000002")
247
		tx, _ := types.SignTx(types.NewTransaction(block.TxNonce(testBankAddress), testContractAddr, big.NewInt(0), 100000, block.BaseFee(), data), signer, testBankKey)
248 249 250 251
		block.AddTx(tx)
	}
}

252
func testChainOdr(t *testing.T, protocol int, fn odrTestFn) {
253
	var (
254 255 256 257 258 259
		sdb   = rawdb.NewMemoryDatabase()
		ldb   = rawdb.NewMemoryDatabase()
		gspec = core.Genesis{
			Alloc:   core.GenesisAlloc{testBankAddress: {Balance: testBankFunds}},
			BaseFee: big.NewInt(params.InitialBaseFee),
		}
260
		genesis = gspec.MustCommit(sdb)
261
	)
262
	gspec.MustCommit(ldb)
263
	// Assemble the test environment
264
	blockchain, _ := core.NewBlockChain(sdb, nil, params.TestChainConfig, ethash.NewFullFaker(), vm.Config{}, nil, nil)
265
	gchain, _ := core.GenerateChain(params.TestChainConfig, genesis, ethash.NewFaker(), sdb, 4, testChainGen)
266
	if _, err := blockchain.InsertChain(gchain); err != nil {
267
		t.Fatal(err)
268 269
	}

270
	odr := &testOdr{sdb: sdb, ldb: ldb, indexerConfig: TestClientIndexerConfig}
271
	lightchain, err := NewLightChain(odr, params.TestChainConfig, ethash.NewFullFaker(), nil)
272 273 274
	if err != nil {
		t.Fatal(err)
	}
275 276 277 278 279
	headers := make([]*types.Header, len(gchain))
	for i, block := range gchain {
		headers[i] = block.Header()
	}
	if _, err := lightchain.InsertHeaderChain(headers, 1); err != nil {
280
		t.Fatal(err)
281 282
	}

283
	test := func(expFail int) {
284
		for i := uint64(0); i <= blockchain.CurrentHeader().Number.Uint64(); i++ {
285
			bhash := rawdb.ReadCanonicalHash(sdb, i)
286 287 288 289
			b1, err := fn(NoOdr, sdb, blockchain, nil, bhash)
			if err != nil {
				t.Fatalf("error in full-node test for block %d: %v", i, err)
			}
290 291 292

			ctx, cancel := context.WithTimeout(context.Background(), 200*time.Millisecond)
			defer cancel()
293 294 295 296 297 298

			exp := i < uint64(expFail)
			b2, err := fn(ctx, ldb, nil, lightchain, bhash)
			if err != nil && exp {
				t.Errorf("error in ODR test for block %d: %v", i, err)
			}
299

300 301
			eq := bytes.Equal(b1, b2)
			if exp && !eq {
302
				t.Errorf("ODR test output for block %d doesn't match full node", i)
303 304 305 306 307
			}
		}
	}

	// expect retrievals to fail (except genesis block) without a les peer
308
	t.Log("checking without ODR")
309
	odr.disable = true
310 311 312 313 314 315 316
	test(1)

	// expect all retrievals to pass with ODR enabled
	t.Log("checking with ODR")
	odr.disable = false
	test(len(gchain))

317
	// still expect all retrievals to pass, now data should be cached locally
318 319 320
	t.Log("checking without ODR, should be cached")
	odr.disable = true
	test(len(gchain))
321
}