state_test_util.go 10 KB

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