odr_test.go 11 KB

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