state_test_util.go 6.9 KB

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