odr_test.go 12 KB

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