state_test_util.go 7.0 KB

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