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