state_test_util.go 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245
  1. // Copyright 2015 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 tests
  17. import (
  18. "bytes"
  19. "encoding/hex"
  20. "fmt"
  21. "io"
  22. "math/big"
  23. "strconv"
  24. "testing"
  25. "github.com/ethereum/go-ethereum/common"
  26. "github.com/ethereum/go-ethereum/core"
  27. "github.com/ethereum/go-ethereum/core/state"
  28. "github.com/ethereum/go-ethereum/core/vm"
  29. "github.com/ethereum/go-ethereum/crypto"
  30. "github.com/ethereum/go-ethereum/ethdb"
  31. "github.com/ethereum/go-ethereum/logger/glog"
  32. )
  33. func RunStateTestWithReader(ruleSet RuleSet, r io.Reader, skipTests []string) error {
  34. tests := make(map[string]VmTest)
  35. if err := readJson(r, &tests); err != nil {
  36. return err
  37. }
  38. if err := runStateTests(ruleSet, tests, skipTests); err != nil {
  39. return err
  40. }
  41. return nil
  42. }
  43. func RunStateTest(ruleSet RuleSet, p string, skipTests []string) error {
  44. tests := make(map[string]VmTest)
  45. if err := readJsonFile(p, &tests); err != nil {
  46. return err
  47. }
  48. if err := runStateTests(ruleSet, tests, skipTests); err != nil {
  49. return err
  50. }
  51. return nil
  52. }
  53. func BenchStateTest(ruleSet RuleSet, p string, conf bconf, b *testing.B) error {
  54. tests := make(map[string]VmTest)
  55. if err := readJsonFile(p, &tests); err != nil {
  56. return err
  57. }
  58. test, ok := tests[conf.name]
  59. if !ok {
  60. return fmt.Errorf("test not found: %s", conf.name)
  61. }
  62. // XXX Yeah, yeah...
  63. env := make(map[string]string)
  64. env["currentCoinbase"] = test.Env.CurrentCoinbase
  65. env["currentDifficulty"] = test.Env.CurrentDifficulty
  66. env["currentGasLimit"] = test.Env.CurrentGasLimit
  67. env["currentNumber"] = test.Env.CurrentNumber
  68. env["previousHash"] = test.Env.PreviousHash
  69. if n, ok := test.Env.CurrentTimestamp.(float64); ok {
  70. env["currentTimestamp"] = strconv.Itoa(int(n))
  71. } else {
  72. env["currentTimestamp"] = test.Env.CurrentTimestamp.(string)
  73. }
  74. b.ResetTimer()
  75. for i := 0; i < b.N; i++ {
  76. benchStateTest(ruleSet, test, env, b)
  77. }
  78. return nil
  79. }
  80. func benchStateTest(ruleSet RuleSet, test VmTest, env map[string]string, b *testing.B) {
  81. b.StopTimer()
  82. db, _ := ethdb.NewMemDatabase()
  83. statedb, _ := state.New(common.Hash{}, db)
  84. for addr, account := range test.Pre {
  85. obj := StateObjectFromAccount(db, addr, account)
  86. statedb.SetStateObject(obj)
  87. for a, v := range account.Storage {
  88. obj.SetState(common.HexToHash(a), common.HexToHash(v))
  89. }
  90. }
  91. b.StartTimer()
  92. RunState(ruleSet, statedb, env, test.Exec)
  93. }
  94. func runStateTests(ruleSet RuleSet, tests map[string]VmTest, skipTests []string) error {
  95. skipTest := make(map[string]bool, len(skipTests))
  96. for _, name := range skipTests {
  97. skipTest[name] = true
  98. }
  99. for name, test := range tests {
  100. if skipTest[name] /*|| name != "callcodecallcode_11" */ {
  101. glog.Infoln("Skipping state test", name)
  102. continue
  103. }
  104. //fmt.Println("StateTest:", name)
  105. if err := runStateTest(ruleSet, test); err != nil {
  106. return fmt.Errorf("%s: %s\n", name, err.Error())
  107. }
  108. //glog.Infoln("State test passed: ", name)
  109. //fmt.Println(string(statedb.Dump()))
  110. }
  111. return nil
  112. }
  113. func runStateTest(ruleSet RuleSet, test VmTest) error {
  114. db, _ := ethdb.NewMemDatabase()
  115. statedb, _ := state.New(common.Hash{}, db)
  116. for addr, account := range test.Pre {
  117. obj := StateObjectFromAccount(db, addr, account)
  118. statedb.SetStateObject(obj)
  119. for a, v := range account.Storage {
  120. obj.SetState(common.HexToHash(a), common.HexToHash(v))
  121. }
  122. }
  123. // XXX Yeah, yeah...
  124. env := make(map[string]string)
  125. env["currentCoinbase"] = test.Env.CurrentCoinbase
  126. env["currentDifficulty"] = test.Env.CurrentDifficulty
  127. env["currentGasLimit"] = test.Env.CurrentGasLimit
  128. env["currentNumber"] = test.Env.CurrentNumber
  129. env["previousHash"] = test.Env.PreviousHash
  130. if n, ok := test.Env.CurrentTimestamp.(float64); ok {
  131. env["currentTimestamp"] = strconv.Itoa(int(n))
  132. } else {
  133. env["currentTimestamp"] = test.Env.CurrentTimestamp.(string)
  134. }
  135. var (
  136. ret []byte
  137. // gas *big.Int
  138. // err error
  139. logs vm.Logs
  140. )
  141. ret, logs, _, _ = RunState(ruleSet, statedb, env, test.Transaction)
  142. // Compare expected and actual return
  143. rexp := common.FromHex(test.Out)
  144. if bytes.Compare(rexp, ret) != 0 {
  145. return fmt.Errorf("return failed. Expected %x, got %x\n", rexp, ret)
  146. }
  147. // check post state
  148. for addr, account := range test.Post {
  149. obj := statedb.GetStateObject(common.HexToAddress(addr))
  150. if obj == nil {
  151. return fmt.Errorf("did not find expected post-state account: %s", addr)
  152. }
  153. if obj.Balance().Cmp(common.Big(account.Balance)) != 0 {
  154. return fmt.Errorf("(%x) balance failed. Expected: %v have: %v\n", obj.Address().Bytes()[:4], common.String2Big(account.Balance), obj.Balance())
  155. }
  156. if obj.Nonce() != common.String2Big(account.Nonce).Uint64() {
  157. return fmt.Errorf("(%x) nonce failed. Expected: %v have: %v\n", obj.Address().Bytes()[:4], account.Nonce, obj.Nonce())
  158. }
  159. for addr, value := range account.Storage {
  160. v := obj.GetState(common.HexToHash(addr))
  161. vexp := common.HexToHash(value)
  162. if v != vexp {
  163. return fmt.Errorf("storage failed:\n%x: %s:\nexpected: %x\nhave: %x\n(%v %v)\n", obj.Address().Bytes(), addr, vexp, v, vexp.Big(), v.Big())
  164. }
  165. }
  166. }
  167. root, _ := statedb.Commit()
  168. if common.HexToHash(test.PostStateRoot) != root {
  169. return fmt.Errorf("Post state root error. Expected: %s have: %x", test.PostStateRoot, root)
  170. }
  171. // check logs
  172. if len(test.Logs) > 0 {
  173. if err := checkLogs(test.Logs, logs); err != nil {
  174. return err
  175. }
  176. }
  177. return nil
  178. }
  179. func RunState(ruleSet RuleSet, statedb *state.StateDB, env, tx map[string]string) ([]byte, vm.Logs, *big.Int, error) {
  180. var (
  181. data = common.FromHex(tx["data"])
  182. gas = common.Big(tx["gasLimit"])
  183. price = common.Big(tx["gasPrice"])
  184. value = common.Big(tx["value"])
  185. nonce = common.Big(tx["nonce"]).Uint64()
  186. )
  187. var to *common.Address
  188. if len(tx["to"]) > 2 {
  189. t := common.HexToAddress(tx["to"])
  190. to = &t
  191. }
  192. // Set pre compiled contracts
  193. vm.Precompiled = vm.PrecompiledContracts()
  194. snapshot := statedb.Copy()
  195. gaspool := new(core.GasPool).AddGas(common.Big(env["currentGasLimit"]))
  196. key, _ := hex.DecodeString(tx["secretKey"])
  197. addr := crypto.PubkeyToAddress(crypto.ToECDSA(key).PublicKey)
  198. message := NewMessage(addr, to, data, value, gas, price, nonce)
  199. vmenv := NewEnvFromMap(ruleSet, statedb, env, tx)
  200. vmenv.origin = addr
  201. ret, _, err := core.ApplyMessage(vmenv, message, gaspool)
  202. if core.IsNonceErr(err) || core.IsInvalidTxErr(err) || core.IsGasLimitErr(err) {
  203. statedb.Set(snapshot)
  204. }
  205. statedb.Commit()
  206. return ret, vmenv.state.Logs(), vmenv.Gas, err
  207. }