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