state_test_util.go 10 KB

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