state_test_util.go 8.1 KB

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