odr_test.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318
  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/rawdb"
  29. "github.com/ethereum/go-ethereum/core/state"
  30. "github.com/ethereum/go-ethereum/core/types"
  31. "github.com/ethereum/go-ethereum/core/vm"
  32. "github.com/ethereum/go-ethereum/crypto"
  33. "github.com/ethereum/go-ethereum/ethdb"
  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. )
  49. type testOdr struct {
  50. OdrBackend
  51. indexerConfig *IndexerConfig
  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. number := rawdb.ReadHeaderNumber(odr.sdb, req.Hash)
  66. if number != nil {
  67. req.Rlp = rawdb.ReadBodyRLP(odr.sdb, req.Hash, *number)
  68. }
  69. case *ReceiptsRequest:
  70. number := rawdb.ReadHeaderNumber(odr.sdb, req.Hash)
  71. if number != nil {
  72. req.Receipts = rawdb.ReadRawReceipts(odr.sdb, req.Hash, *number)
  73. }
  74. case *TrieRequest:
  75. t, _ := trie.New(req.Id.Root, trie.NewDatabase(odr.sdb))
  76. nodes := NewNodeSet()
  77. t.Prove(req.Key, 0, nodes)
  78. req.Proof = nodes
  79. case *CodeRequest:
  80. req.Data = rawdb.ReadCode(odr.sdb, req.Hash)
  81. }
  82. req.StoreResult(odr.ldb)
  83. return nil
  84. }
  85. func (odr *testOdr) IndexerConfig() *IndexerConfig {
  86. return odr.indexerConfig
  87. }
  88. type odrTestFn func(ctx context.Context, db ethdb.Database, bc *core.BlockChain, lc *LightChain, bhash common.Hash) ([]byte, error)
  89. func TestOdrGetBlockLes2(t *testing.T) { testChainOdr(t, 1, odrGetBlock) }
  90. func odrGetBlock(ctx context.Context, db ethdb.Database, bc *core.BlockChain, lc *LightChain, bhash common.Hash) ([]byte, error) {
  91. var block *types.Block
  92. if bc != nil {
  93. block = bc.GetBlockByHash(bhash)
  94. } else {
  95. block, _ = lc.GetBlockByHash(ctx, bhash)
  96. }
  97. if block == nil {
  98. return nil, nil
  99. }
  100. rlp, _ := rlp.EncodeToBytes(block)
  101. return rlp, nil
  102. }
  103. func TestOdrGetReceiptsLes2(t *testing.T) { testChainOdr(t, 1, odrGetReceipts) }
  104. func odrGetReceipts(ctx context.Context, db ethdb.Database, bc *core.BlockChain, lc *LightChain, bhash common.Hash) ([]byte, error) {
  105. var receipts types.Receipts
  106. if bc != nil {
  107. number := rawdb.ReadHeaderNumber(db, bhash)
  108. if number != nil {
  109. receipts = rawdb.ReadReceipts(db, bhash, *number, bc.Config())
  110. }
  111. } else {
  112. number := rawdb.ReadHeaderNumber(db, bhash)
  113. if number != nil {
  114. receipts, _ = GetBlockReceipts(ctx, lc.Odr(), bhash, *number)
  115. }
  116. }
  117. if receipts == nil {
  118. return nil, nil
  119. }
  120. rlp, _ := rlp.EncodeToBytes(receipts)
  121. return rlp, nil
  122. }
  123. func TestOdrAccountsLes2(t *testing.T) { testChainOdr(t, 1, odrAccounts) }
  124. func odrAccounts(ctx context.Context, db ethdb.Database, bc *core.BlockChain, lc *LightChain, bhash common.Hash) ([]byte, error) {
  125. dummyAddr := common.HexToAddress("1234567812345678123456781234567812345678")
  126. acc := []common.Address{testBankAddress, acc1Addr, acc2Addr, dummyAddr}
  127. var st *state.StateDB
  128. if bc == nil {
  129. header := lc.GetHeaderByHash(bhash)
  130. st = NewState(ctx, header, lc.Odr())
  131. } else {
  132. header := bc.GetHeaderByHash(bhash)
  133. st, _ = state.New(header.Root, state.NewDatabase(db), nil)
  134. }
  135. var res []byte
  136. for _, addr := range acc {
  137. bal := st.GetBalance(addr)
  138. rlp, _ := rlp.EncodeToBytes(bal)
  139. res = append(res, rlp...)
  140. }
  141. return res, st.Error()
  142. }
  143. func TestOdrContractCallLes2(t *testing.T) { testChainOdr(t, 1, odrContractCall) }
  144. type callmsg struct {
  145. types.Message
  146. }
  147. func (callmsg) CheckNonce() bool { return false }
  148. func odrContractCall(ctx context.Context, db ethdb.Database, bc *core.BlockChain, lc *LightChain, bhash common.Hash) ([]byte, error) {
  149. data := common.Hex2Bytes("60CD26850000000000000000000000000000000000000000000000000000000000000000")
  150. config := params.TestChainConfig
  151. var res []byte
  152. for i := 0; i < 3; i++ {
  153. data[35] = byte(i)
  154. var (
  155. st *state.StateDB
  156. header *types.Header
  157. chain core.ChainContext
  158. )
  159. if bc == nil {
  160. chain = lc
  161. header = lc.GetHeaderByHash(bhash)
  162. st = NewState(ctx, header, lc.Odr())
  163. } else {
  164. chain = bc
  165. header = bc.GetHeaderByHash(bhash)
  166. st, _ = state.New(header.Root, state.NewDatabase(db), nil)
  167. }
  168. // Perform read-only call.
  169. st.SetBalance(testBankAddress, math.MaxBig256)
  170. msg := callmsg{types.NewMessage(testBankAddress, &testContractAddr, 0, new(big.Int), 1000000, new(big.Int), data, nil, false)}
  171. txContext := core.NewEVMTxContext(msg)
  172. context := core.NewEVMBlockContext(header, chain, nil)
  173. vmenv := vm.NewEVM(context, txContext, st, st, config, vm.Config{})
  174. gp := new(core.GasPool).AddGas(math.MaxUint64)
  175. result, _ := core.ApplyMessage(vmenv, msg, gp)
  176. res = append(res, result.Return()...)
  177. if st.Error() != nil {
  178. return res, st.Error()
  179. }
  180. }
  181. return res, nil
  182. }
  183. func testChainGen(i int, block *core.BlockGen) {
  184. signer := types.HomesteadSigner{}
  185. switch i {
  186. case 0:
  187. // In block 1, the test bank sends account #1 some ether.
  188. tx, _ := types.SignTx(types.NewTransaction(block.TxNonce(testBankAddress), acc1Addr, big.NewInt(10000), params.TxGas, nil, nil), signer, testBankKey)
  189. block.AddTx(tx)
  190. case 1:
  191. // In block 2, the test bank sends some more ether to account #1.
  192. // acc1Addr passes it on to account #2.
  193. // acc1Addr creates a test contract.
  194. tx1, _ := types.SignTx(types.NewTransaction(block.TxNonce(testBankAddress), acc1Addr, big.NewInt(1000), params.TxGas, nil, nil), signer, testBankKey)
  195. nonce := block.TxNonce(acc1Addr)
  196. tx2, _ := types.SignTx(types.NewTransaction(nonce, acc2Addr, big.NewInt(1000), params.TxGas, nil, nil), signer, acc1Key)
  197. nonce++
  198. tx3, _ := types.SignTx(types.NewContractCreation(nonce, big.NewInt(0), 1000000, big.NewInt(0), testContractCode), signer, acc1Key)
  199. testContractAddr = crypto.CreateAddress(acc1Addr, nonce)
  200. block.AddTx(tx1)
  201. block.AddTx(tx2)
  202. block.AddTx(tx3)
  203. case 2:
  204. // Block 3 is empty but was mined by account #2.
  205. block.SetCoinbase(acc2Addr)
  206. block.SetExtra([]byte("yeehaw"))
  207. data := common.Hex2Bytes("C16431B900000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000001")
  208. tx, _ := types.SignTx(types.NewTransaction(block.TxNonce(testBankAddress), testContractAddr, big.NewInt(0), 100000, nil, data), signer, testBankKey)
  209. block.AddTx(tx)
  210. case 3:
  211. // Block 4 includes blocks 2 and 3 as uncle headers (with modified extra data).
  212. b2 := block.PrevBlock(1).Header()
  213. b2.Extra = []byte("foo")
  214. block.AddUncle(b2)
  215. b3 := block.PrevBlock(2).Header()
  216. b3.Extra = []byte("foo")
  217. block.AddUncle(b3)
  218. data := common.Hex2Bytes("C16431B900000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000002")
  219. tx, _ := types.SignTx(types.NewTransaction(block.TxNonce(testBankAddress), testContractAddr, big.NewInt(0), 100000, nil, data), signer, testBankKey)
  220. block.AddTx(tx)
  221. }
  222. }
  223. func testChainOdr(t *testing.T, protocol int, fn odrTestFn) {
  224. var (
  225. sdb = rawdb.NewMemoryDatabase()
  226. ldb = rawdb.NewMemoryDatabase()
  227. gspec = core.Genesis{Alloc: core.GenesisAlloc{testBankAddress: {Balance: testBankFunds}}}
  228. genesis = gspec.MustCommit(sdb)
  229. )
  230. gspec.MustCommit(ldb)
  231. // Assemble the test environment
  232. blockchain, _ := core.NewBlockChain(sdb, nil, params.TestChainConfig, ethash.NewFullFaker(), vm.Config{}, nil, nil, nil)
  233. gchain, _ := core.GenerateChain(params.TestChainConfig, genesis, ethash.NewFaker(), sdb, 4, testChainGen)
  234. if _, err := blockchain.InsertChain(gchain); err != nil {
  235. t.Fatal(err)
  236. }
  237. odr := &testOdr{sdb: sdb, ldb: ldb, indexerConfig: TestClientIndexerConfig}
  238. lightchain, err := NewLightChain(odr, params.TestChainConfig, ethash.NewFullFaker(), nil)
  239. if err != nil {
  240. t.Fatal(err)
  241. }
  242. headers := make([]*types.Header, len(gchain))
  243. for i, block := range gchain {
  244. headers[i] = block.Header()
  245. }
  246. if _, err := lightchain.InsertHeaderChain(headers, 1); err != nil {
  247. t.Fatal(err)
  248. }
  249. test := func(expFail int) {
  250. for i := uint64(0); i <= blockchain.CurrentHeader().Number.Uint64(); i++ {
  251. bhash := rawdb.ReadCanonicalHash(sdb, i)
  252. b1, err := fn(NoOdr, sdb, blockchain, nil, bhash)
  253. if err != nil {
  254. t.Fatalf("error in full-node test for block %d: %v", i, err)
  255. }
  256. ctx, cancel := context.WithTimeout(context.Background(), 200*time.Millisecond)
  257. defer cancel()
  258. exp := i < uint64(expFail)
  259. b2, err := fn(ctx, ldb, nil, lightchain, bhash)
  260. if err != nil && exp {
  261. t.Errorf("error in ODR test for block %d: %v", i, err)
  262. }
  263. eq := bytes.Equal(b1, b2)
  264. if exp && !eq {
  265. t.Errorf("ODR test output for block %d doesn't match full node", i)
  266. }
  267. }
  268. }
  269. // expect retrievals to fail (except genesis block) without a les peer
  270. t.Log("checking without ODR")
  271. odr.disable = true
  272. test(1)
  273. // expect all retrievals to pass with ODR enabled
  274. t.Log("checking with ODR")
  275. odr.disable = false
  276. test(len(gchain))
  277. // still expect all retrievals to pass, now data should be cached locally
  278. t.Log("checking without ODR, should be cached")
  279. odr.disable = true
  280. test(len(gchain))
  281. }