odr_test.go 12 KB

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