state_test_util.go 7.5 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. "encoding/hex"
  19. "encoding/json"
  20. "fmt"
  21. "math/big"
  22. "strings"
  23. "github.com/ethereum/go-ethereum/common"
  24. "github.com/ethereum/go-ethereum/common/hexutil"
  25. "github.com/ethereum/go-ethereum/common/math"
  26. "github.com/ethereum/go-ethereum/core"
  27. "github.com/ethereum/go-ethereum/core/state"
  28. "github.com/ethereum/go-ethereum/core/types"
  29. "github.com/ethereum/go-ethereum/core/vm"
  30. "github.com/ethereum/go-ethereum/crypto"
  31. "github.com/ethereum/go-ethereum/crypto/sha3"
  32. "github.com/ethereum/go-ethereum/ethdb"
  33. "github.com/ethereum/go-ethereum/params"
  34. "github.com/ethereum/go-ethereum/rlp"
  35. )
  36. // StateTest checks transaction processing without block context.
  37. // See https://github.com/ethereum/EIPs/issues/176 for the test format specification.
  38. type StateTest struct {
  39. json stJSON
  40. }
  41. // StateSubtest selects a specific configuration of a General State Test.
  42. type StateSubtest struct {
  43. Fork string
  44. Index int
  45. }
  46. func (t *StateTest) UnmarshalJSON(in []byte) error {
  47. return json.Unmarshal(in, &t.json)
  48. }
  49. type stJSON struct {
  50. Env stEnv `json:"env"`
  51. Pre core.GenesisAlloc `json:"pre"`
  52. Tx stTransaction `json:"transaction"`
  53. Out hexutil.Bytes `json:"out"`
  54. Post map[string][]stPostState `json:"post"`
  55. }
  56. type stPostState struct {
  57. Root common.UnprefixedHash `json:"hash"`
  58. Logs common.UnprefixedHash `json:"logs"`
  59. Indexes struct {
  60. Data int `json:"data"`
  61. Gas int `json:"gas"`
  62. Value int `json:"value"`
  63. }
  64. }
  65. //go:generate gencodec -type stEnv -field-override stEnvMarshaling -out gen_stenv.go
  66. type stEnv struct {
  67. Coinbase common.Address `json:"currentCoinbase" gencodec:"required"`
  68. Difficulty *big.Int `json:"currentDifficulty" gencodec:"required"`
  69. GasLimit uint64 `json:"currentGasLimit" gencodec:"required"`
  70. Number uint64 `json:"currentNumber" gencodec:"required"`
  71. Timestamp uint64 `json:"currentTimestamp" gencodec:"required"`
  72. }
  73. type stEnvMarshaling struct {
  74. Coinbase common.UnprefixedAddress
  75. Difficulty *math.HexOrDecimal256
  76. GasLimit math.HexOrDecimal64
  77. Number math.HexOrDecimal64
  78. Timestamp math.HexOrDecimal64
  79. }
  80. //go:generate gencodec -type stTransaction -field-override stTransactionMarshaling -out gen_sttransaction.go
  81. type stTransaction struct {
  82. GasPrice *big.Int `json:"gasPrice"`
  83. Nonce uint64 `json:"nonce"`
  84. To string `json:"to"`
  85. Data []string `json:"data"`
  86. GasLimit []uint64 `json:"gasLimit"`
  87. Value []string `json:"value"`
  88. PrivateKey []byte `json:"secretKey"`
  89. }
  90. type stTransactionMarshaling struct {
  91. GasPrice *math.HexOrDecimal256
  92. Nonce math.HexOrDecimal64
  93. GasLimit []math.HexOrDecimal64
  94. PrivateKey hexutil.Bytes
  95. }
  96. // Subtests returns all valid subtests of the test.
  97. func (t *StateTest) Subtests() []StateSubtest {
  98. var sub []StateSubtest
  99. for fork, pss := range t.json.Post {
  100. for i := range pss {
  101. sub = append(sub, StateSubtest{fork, i})
  102. }
  103. }
  104. return sub
  105. }
  106. // Run executes a specific subtest.
  107. func (t *StateTest) Run(subtest StateSubtest, vmconfig vm.Config) (*state.StateDB, error) {
  108. config, ok := Forks[subtest.Fork]
  109. if !ok {
  110. return nil, UnsupportedForkError{subtest.Fork}
  111. }
  112. block := t.genesis(config).ToBlock(nil)
  113. statedb := MakePreState(ethdb.NewMemDatabase(), t.json.Pre)
  114. post := t.json.Post[subtest.Fork][subtest.Index]
  115. msg, err := t.json.Tx.toMessage(post)
  116. if err != nil {
  117. return nil, err
  118. }
  119. context := core.NewEVMContext(msg, block.Header(), nil, &t.json.Env.Coinbase)
  120. context.GetHash = vmTestBlockHash
  121. evm := vm.NewEVM(context, statedb, config, vmconfig)
  122. gaspool := new(core.GasPool)
  123. gaspool.AddGas(block.GasLimit())
  124. snapshot := statedb.Snapshot()
  125. if _, _, _, err := core.ApplyMessage(evm, msg, gaspool); err != nil {
  126. statedb.RevertToSnapshot(snapshot)
  127. }
  128. if logs := rlpHash(statedb.Logs()); logs != common.Hash(post.Logs) {
  129. return statedb, fmt.Errorf("post state logs hash mismatch: got %x, want %x", logs, post.Logs)
  130. }
  131. root, _ := statedb.Commit(config.IsEIP158(block.Number()))
  132. if root != common.Hash(post.Root) {
  133. return statedb, fmt.Errorf("post state root mismatch: got %x, want %x", root, post.Root)
  134. }
  135. return statedb, nil
  136. }
  137. func (t *StateTest) gasLimit(subtest StateSubtest) uint64 {
  138. return t.json.Tx.GasLimit[t.json.Post[subtest.Fork][subtest.Index].Indexes.Gas]
  139. }
  140. func MakePreState(db ethdb.Database, accounts core.GenesisAlloc) *state.StateDB {
  141. sdb := state.NewDatabase(db)
  142. statedb, _ := state.New(common.Hash{}, sdb)
  143. for addr, a := range accounts {
  144. statedb.SetCode(addr, a.Code)
  145. statedb.SetNonce(addr, a.Nonce)
  146. statedb.SetBalance(addr, a.Balance)
  147. for k, v := range a.Storage {
  148. statedb.SetState(addr, k, v)
  149. }
  150. }
  151. // Commit and re-open to start with a clean state.
  152. root, _ := statedb.Commit(false)
  153. statedb, _ = state.New(root, sdb)
  154. return statedb
  155. }
  156. func (t *StateTest) genesis(config *params.ChainConfig) *core.Genesis {
  157. return &core.Genesis{
  158. Config: config,
  159. Coinbase: t.json.Env.Coinbase,
  160. Difficulty: t.json.Env.Difficulty,
  161. GasLimit: t.json.Env.GasLimit,
  162. Number: t.json.Env.Number,
  163. Timestamp: t.json.Env.Timestamp,
  164. Alloc: t.json.Pre,
  165. }
  166. }
  167. func (tx *stTransaction) toMessage(ps stPostState) (core.Message, error) {
  168. // Derive sender from private key if present.
  169. var from common.Address
  170. if len(tx.PrivateKey) > 0 {
  171. key, err := crypto.ToECDSA(tx.PrivateKey)
  172. if err != nil {
  173. return nil, fmt.Errorf("invalid private key: %v", err)
  174. }
  175. from = crypto.PubkeyToAddress(key.PublicKey)
  176. }
  177. // Parse recipient if present.
  178. var to *common.Address
  179. if tx.To != "" {
  180. to = new(common.Address)
  181. if err := to.UnmarshalText([]byte(tx.To)); err != nil {
  182. return nil, fmt.Errorf("invalid to address: %v", err)
  183. }
  184. }
  185. // Get values specific to this post state.
  186. if ps.Indexes.Data > len(tx.Data) {
  187. return nil, fmt.Errorf("tx data index %d out of bounds", ps.Indexes.Data)
  188. }
  189. if ps.Indexes.Value > len(tx.Value) {
  190. return nil, fmt.Errorf("tx value index %d out of bounds", ps.Indexes.Value)
  191. }
  192. if ps.Indexes.Gas > len(tx.GasLimit) {
  193. return nil, fmt.Errorf("tx gas limit index %d out of bounds", ps.Indexes.Gas)
  194. }
  195. dataHex := tx.Data[ps.Indexes.Data]
  196. valueHex := tx.Value[ps.Indexes.Value]
  197. gasLimit := tx.GasLimit[ps.Indexes.Gas]
  198. // Value, Data hex encoding is messy: https://github.com/ethereum/tests/issues/203
  199. value := new(big.Int)
  200. if valueHex != "0x" {
  201. v, ok := math.ParseBig256(valueHex)
  202. if !ok {
  203. return nil, fmt.Errorf("invalid tx value %q", valueHex)
  204. }
  205. value = v
  206. }
  207. data, err := hex.DecodeString(strings.TrimPrefix(dataHex, "0x"))
  208. if err != nil {
  209. return nil, fmt.Errorf("invalid tx data %q", dataHex)
  210. }
  211. msg := types.NewMessage(from, to, tx.Nonce, value, gasLimit, tx.GasPrice, data, true)
  212. return msg, nil
  213. }
  214. func rlpHash(x interface{}) (h common.Hash) {
  215. hw := sha3.NewKeccak256()
  216. rlp.Encode(hw, x)
  217. hw.Sum(h[:0])
  218. return h
  219. }