state_test_util.go 6.7 KB

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