state_test_util.go 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199
  1. // Copyright 2014 The go-ethereum Authors
  2. // This file is part of go-ethereum.
  3. //
  4. // go-ethereum 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. // go-ethereum 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 go-ethereum. 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. "github.com/ethereum/go-ethereum/common"
  25. "github.com/ethereum/go-ethereum/core"
  26. "github.com/ethereum/go-ethereum/core/state"
  27. "github.com/ethereum/go-ethereum/core/vm"
  28. "github.com/ethereum/go-ethereum/crypto"
  29. "github.com/ethereum/go-ethereum/ethdb"
  30. "github.com/ethereum/go-ethereum/logger/glog"
  31. )
  32. func RunStateTestWithReader(r io.Reader, skipTests []string) error {
  33. tests := make(map[string]VmTest)
  34. if err := readJson(r, &tests); err != nil {
  35. return err
  36. }
  37. if err := runStateTests(tests, skipTests); err != nil {
  38. return err
  39. }
  40. return nil
  41. }
  42. func RunStateTest(p string, skipTests []string) error {
  43. tests := make(map[string]VmTest)
  44. if err := readJsonFile(p, &tests); err != nil {
  45. return err
  46. }
  47. if err := runStateTests(tests, skipTests); err != nil {
  48. return err
  49. }
  50. return nil
  51. }
  52. func runStateTests(tests map[string]VmTest, skipTests []string) error {
  53. skipTest := make(map[string]bool, len(skipTests))
  54. for _, name := range skipTests {
  55. skipTest[name] = true
  56. }
  57. for name, test := range tests {
  58. if skipTest[name] {
  59. glog.Infoln("Skipping state test", name)
  60. return nil
  61. }
  62. if err := runStateTest(test); err != nil {
  63. return fmt.Errorf("%s: %s\n", name, err.Error())
  64. }
  65. glog.Infoln("State test passed: ", name)
  66. //fmt.Println(string(statedb.Dump()))
  67. }
  68. return nil
  69. }
  70. func runStateTest(test VmTest) error {
  71. db, _ := ethdb.NewMemDatabase()
  72. statedb := state.New(common.Hash{}, db)
  73. for addr, account := range test.Pre {
  74. obj := StateObjectFromAccount(db, addr, account)
  75. statedb.SetStateObject(obj)
  76. for a, v := range account.Storage {
  77. obj.SetState(common.HexToHash(a), common.HexToHash(v))
  78. }
  79. }
  80. // XXX Yeah, yeah...
  81. env := make(map[string]string)
  82. env["currentCoinbase"] = test.Env.CurrentCoinbase
  83. env["currentDifficulty"] = test.Env.CurrentDifficulty
  84. env["currentGasLimit"] = test.Env.CurrentGasLimit
  85. env["currentNumber"] = test.Env.CurrentNumber
  86. env["previousHash"] = test.Env.PreviousHash
  87. if n, ok := test.Env.CurrentTimestamp.(float64); ok {
  88. env["currentTimestamp"] = strconv.Itoa(int(n))
  89. } else {
  90. env["currentTimestamp"] = test.Env.CurrentTimestamp.(string)
  91. }
  92. var (
  93. ret []byte
  94. // gas *big.Int
  95. // err error
  96. logs state.Logs
  97. )
  98. ret, logs, _, _ = RunState(statedb, env, test.Transaction)
  99. // // Compare expected and actual return
  100. rexp := common.FromHex(test.Out)
  101. if bytes.Compare(rexp, ret) != 0 {
  102. return fmt.Errorf("return failed. Expected %x, got %x\n", rexp, ret)
  103. }
  104. // check post state
  105. for addr, account := range test.Post {
  106. obj := statedb.GetStateObject(common.HexToAddress(addr))
  107. if obj == nil {
  108. continue
  109. }
  110. if obj.Balance().Cmp(common.Big(account.Balance)) != 0 {
  111. 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()))
  112. }
  113. if obj.Nonce() != common.String2Big(account.Nonce).Uint64() {
  114. return fmt.Errorf("(%x) nonce failed. Expected %v, got %v\n", obj.Address().Bytes()[:4], account.Nonce, obj.Nonce())
  115. }
  116. for addr, value := range account.Storage {
  117. v := obj.GetState(common.HexToHash(addr))
  118. vexp := common.HexToHash(value)
  119. if v != vexp {
  120. 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())
  121. }
  122. }
  123. }
  124. statedb.Sync()
  125. if common.HexToHash(test.PostStateRoot) != statedb.Root() {
  126. return fmt.Errorf("Post state root error. Expected %s, got %x", test.PostStateRoot, statedb.Root())
  127. }
  128. // check logs
  129. if len(test.Logs) > 0 {
  130. if err := checkLogs(test.Logs, logs); err != nil {
  131. return err
  132. }
  133. }
  134. return nil
  135. }
  136. func RunState(statedb *state.StateDB, env, tx map[string]string) ([]byte, state.Logs, *big.Int, error) {
  137. var (
  138. data = common.FromHex(tx["data"])
  139. gas = common.Big(tx["gasLimit"])
  140. price = common.Big(tx["gasPrice"])
  141. value = common.Big(tx["value"])
  142. nonce = common.Big(tx["nonce"]).Uint64()
  143. caddr = common.HexToAddress(env["currentCoinbase"])
  144. )
  145. var to *common.Address
  146. if len(tx["to"]) > 2 {
  147. t := common.HexToAddress(tx["to"])
  148. to = &t
  149. }
  150. // Set pre compiled contracts
  151. vm.Precompiled = vm.PrecompiledContracts()
  152. snapshot := statedb.Copy()
  153. coinbase := statedb.GetOrNewStateObject(caddr)
  154. coinbase.SetGasLimit(common.Big(env["currentGasLimit"]))
  155. key, _ := hex.DecodeString(tx["secretKey"])
  156. addr := crypto.PubkeyToAddress(crypto.ToECDSA(key).PublicKey)
  157. message := NewMessage(addr, to, data, value, gas, price, nonce)
  158. vmenv := NewEnvFromMap(statedb, env, tx)
  159. vmenv.origin = addr
  160. ret, _, err := core.ApplyMessage(vmenv, message, coinbase)
  161. if core.IsNonceErr(err) || core.IsInvalidTxErr(err) || state.IsGasLimitErr(err) {
  162. statedb.Set(snapshot)
  163. }
  164. statedb.SyncObjects()
  165. return ret, vmenv.state.Logs(), vmenv.Gas, err
  166. }