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