block_test_util.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325
  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 implements execution of Ethereum JSON tests.
  17. package tests
  18. import (
  19. "bytes"
  20. "encoding/hex"
  21. "encoding/json"
  22. "fmt"
  23. "math/big"
  24. "os"
  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/consensus"
  29. "github.com/ethereum/go-ethereum/consensus/ethash"
  30. "github.com/ethereum/go-ethereum/core"
  31. "github.com/ethereum/go-ethereum/core/rawdb"
  32. "github.com/ethereum/go-ethereum/core/state"
  33. "github.com/ethereum/go-ethereum/core/types"
  34. "github.com/ethereum/go-ethereum/core/vm"
  35. "github.com/ethereum/go-ethereum/params"
  36. "github.com/ethereum/go-ethereum/rlp"
  37. )
  38. // A BlockTest checks handling of entire blocks.
  39. type BlockTest struct {
  40. json btJSON
  41. }
  42. // UnmarshalJSON implements json.Unmarshaler interface.
  43. func (t *BlockTest) UnmarshalJSON(in []byte) error {
  44. return json.Unmarshal(in, &t.json)
  45. }
  46. type btJSON struct {
  47. Blocks []btBlock `json:"blocks"`
  48. Genesis btHeader `json:"genesisBlockHeader"`
  49. Pre core.GenesisAlloc `json:"pre"`
  50. Post core.GenesisAlloc `json:"postState"`
  51. BestBlock common.UnprefixedHash `json:"lastblockhash"`
  52. Network string `json:"network"`
  53. SealEngine string `json:"sealEngine"`
  54. }
  55. type btBlock struct {
  56. BlockHeader *btHeader
  57. ExpectException string
  58. Rlp string
  59. UncleHeaders []*btHeader
  60. }
  61. //go:generate go run github.com/fjl/gencodec -type btHeader -field-override btHeaderMarshaling -out gen_btheader.go
  62. type btHeader struct {
  63. Bloom types.Bloom
  64. Coinbase common.Address
  65. MixHash common.Hash
  66. Nonce types.BlockNonce
  67. Number *big.Int
  68. Hash common.Hash
  69. ParentHash common.Hash
  70. ReceiptTrie common.Hash
  71. StateRoot common.Hash
  72. TransactionsTrie common.Hash
  73. UncleHash common.Hash
  74. ExtraData []byte
  75. Difficulty *big.Int
  76. GasLimit uint64
  77. GasUsed uint64
  78. Timestamp uint64
  79. BaseFeePerGas *big.Int
  80. }
  81. type btHeaderMarshaling struct {
  82. ExtraData hexutil.Bytes
  83. Number *math.HexOrDecimal256
  84. Difficulty *math.HexOrDecimal256
  85. GasLimit math.HexOrDecimal64
  86. GasUsed math.HexOrDecimal64
  87. Timestamp math.HexOrDecimal64
  88. BaseFeePerGas *math.HexOrDecimal256
  89. }
  90. func (t *BlockTest) Run(snapshotter bool) error {
  91. config, ok := Forks[t.json.Network]
  92. if !ok {
  93. return UnsupportedForkError{t.json.Network}
  94. }
  95. // import pre accounts & construct test genesis block & state root
  96. db := rawdb.NewMemoryDatabase()
  97. gblock, err := t.genesis(config).Commit(db)
  98. if err != nil {
  99. return err
  100. }
  101. if gblock.Hash() != t.json.Genesis.Hash {
  102. return fmt.Errorf("genesis block hash doesn't match test: computed=%x, test=%x", gblock.Hash().Bytes()[:6], t.json.Genesis.Hash[:6])
  103. }
  104. if gblock.Root() != t.json.Genesis.StateRoot {
  105. return fmt.Errorf("genesis block state root does not match test: computed=%x, test=%x", gblock.Root().Bytes()[:6], t.json.Genesis.StateRoot[:6])
  106. }
  107. var engine consensus.Engine
  108. if t.json.SealEngine == "NoProof" {
  109. engine = ethash.NewFaker()
  110. } else {
  111. engine = ethash.NewShared()
  112. }
  113. cache := &core.CacheConfig{TrieCleanLimit: 0}
  114. if snapshotter {
  115. cache.SnapshotLimit = 1
  116. cache.SnapshotWait = true
  117. }
  118. chain, err := core.NewBlockChain(db, cache, config, engine, vm.Config{}, nil, nil)
  119. if err != nil {
  120. return err
  121. }
  122. defer chain.Stop()
  123. validBlocks, err := t.insertBlocks(chain)
  124. if err != nil {
  125. return err
  126. }
  127. cmlast := chain.CurrentBlock().Hash()
  128. if common.Hash(t.json.BestBlock) != cmlast {
  129. return fmt.Errorf("last block hash validation mismatch: want: %x, have: %x", t.json.BestBlock, cmlast)
  130. }
  131. newDB, err := chain.State()
  132. if err != nil {
  133. return err
  134. }
  135. if err = t.validatePostState(newDB); err != nil {
  136. return fmt.Errorf("post state validation failed: %v", err)
  137. }
  138. // Cross-check the snapshot-to-hash against the trie hash
  139. if snapshotter {
  140. if err := chain.Snapshots().Verify(chain.CurrentBlock().Root()); err != nil {
  141. return err
  142. }
  143. }
  144. return t.validateImportedHeaders(chain, validBlocks)
  145. }
  146. func (t *BlockTest) genesis(config *params.ChainConfig) *core.Genesis {
  147. return &core.Genesis{
  148. Config: config,
  149. Nonce: t.json.Genesis.Nonce.Uint64(),
  150. Timestamp: t.json.Genesis.Timestamp,
  151. ParentHash: t.json.Genesis.ParentHash,
  152. ExtraData: t.json.Genesis.ExtraData,
  153. GasLimit: t.json.Genesis.GasLimit,
  154. GasUsed: t.json.Genesis.GasUsed,
  155. Difficulty: t.json.Genesis.Difficulty,
  156. Mixhash: t.json.Genesis.MixHash,
  157. Coinbase: t.json.Genesis.Coinbase,
  158. Alloc: t.json.Pre,
  159. BaseFee: t.json.Genesis.BaseFeePerGas,
  160. }
  161. }
  162. /* See https://github.com/ethereum/tests/wiki/Blockchain-Tests-II
  163. Whether a block is valid or not is a bit subtle, it's defined by presence of
  164. blockHeader, transactions and uncleHeaders fields. If they are missing, the block is
  165. invalid and we must verify that we do not accept it.
  166. Since some tests mix valid and invalid blocks we need to check this for every block.
  167. If a block is invalid it does not necessarily fail the test, if it's invalidness is
  168. expected we are expected to ignore it and continue processing and then validate the
  169. post state.
  170. */
  171. func (t *BlockTest) insertBlocks(blockchain *core.BlockChain) ([]btBlock, error) {
  172. validBlocks := make([]btBlock, 0)
  173. // insert the test blocks, which will execute all transactions
  174. for bi, b := range t.json.Blocks {
  175. cb, err := b.decode()
  176. if err != nil {
  177. if b.BlockHeader == nil {
  178. continue // OK - block is supposed to be invalid, continue with next block
  179. } else {
  180. return nil, fmt.Errorf("block RLP decoding failed when expected to succeed: %v", err)
  181. }
  182. }
  183. // RLP decoding worked, try to insert into chain:
  184. blocks := types.Blocks{cb}
  185. i, err := blockchain.InsertChain(blocks)
  186. if err != nil {
  187. if b.BlockHeader == nil {
  188. continue // OK - block is supposed to be invalid, continue with next block
  189. } else {
  190. return nil, fmt.Errorf("block #%v insertion into chain failed: %v", blocks[i].Number(), err)
  191. }
  192. }
  193. if b.BlockHeader == nil {
  194. if data, err := json.MarshalIndent(cb.Header(), "", " "); err == nil {
  195. fmt.Fprintf(os.Stderr, "block (index %d) insertion should have failed due to: %v:\n%v\n",
  196. bi, b.ExpectException, string(data))
  197. }
  198. return nil, fmt.Errorf("block (index %d) insertion should have failed due to: %v",
  199. bi, b.ExpectException)
  200. }
  201. // validate RLP decoding by checking all values against test file JSON
  202. if err = validateHeader(b.BlockHeader, cb.Header()); err != nil {
  203. return nil, fmt.Errorf("deserialised block header validation failed: %v", err)
  204. }
  205. validBlocks = append(validBlocks, b)
  206. }
  207. return validBlocks, nil
  208. }
  209. func validateHeader(h *btHeader, h2 *types.Header) error {
  210. if h.Bloom != h2.Bloom {
  211. return fmt.Errorf("bloom: want: %x have: %x", h.Bloom, h2.Bloom)
  212. }
  213. if h.Coinbase != h2.Coinbase {
  214. return fmt.Errorf("coinbase: want: %x have: %x", h.Coinbase, h2.Coinbase)
  215. }
  216. if h.MixHash != h2.MixDigest {
  217. return fmt.Errorf("MixHash: want: %x have: %x", h.MixHash, h2.MixDigest)
  218. }
  219. if h.Nonce != h2.Nonce {
  220. return fmt.Errorf("nonce: want: %x have: %x", h.Nonce, h2.Nonce)
  221. }
  222. if h.Number.Cmp(h2.Number) != 0 {
  223. return fmt.Errorf("number: want: %v have: %v", h.Number, h2.Number)
  224. }
  225. if h.ParentHash != h2.ParentHash {
  226. return fmt.Errorf("parent hash: want: %x have: %x", h.ParentHash, h2.ParentHash)
  227. }
  228. if h.ReceiptTrie != h2.ReceiptHash {
  229. return fmt.Errorf("receipt hash: want: %x have: %x", h.ReceiptTrie, h2.ReceiptHash)
  230. }
  231. if h.TransactionsTrie != h2.TxHash {
  232. return fmt.Errorf("tx hash: want: %x have: %x", h.TransactionsTrie, h2.TxHash)
  233. }
  234. if h.StateRoot != h2.Root {
  235. return fmt.Errorf("state hash: want: %x have: %x", h.StateRoot, h2.Root)
  236. }
  237. if h.UncleHash != h2.UncleHash {
  238. return fmt.Errorf("uncle hash: want: %x have: %x", h.UncleHash, h2.UncleHash)
  239. }
  240. if !bytes.Equal(h.ExtraData, h2.Extra) {
  241. return fmt.Errorf("extra data: want: %x have: %x", h.ExtraData, h2.Extra)
  242. }
  243. if h.Difficulty.Cmp(h2.Difficulty) != 0 {
  244. return fmt.Errorf("difficulty: want: %v have: %v", h.Difficulty, h2.Difficulty)
  245. }
  246. if h.GasLimit != h2.GasLimit {
  247. return fmt.Errorf("gasLimit: want: %d have: %d", h.GasLimit, h2.GasLimit)
  248. }
  249. if h.GasUsed != h2.GasUsed {
  250. return fmt.Errorf("gasUsed: want: %d have: %d", h.GasUsed, h2.GasUsed)
  251. }
  252. if h.Timestamp != h2.Time {
  253. return fmt.Errorf("timestamp: want: %v have: %v", h.Timestamp, h2.Time)
  254. }
  255. return nil
  256. }
  257. func (t *BlockTest) validatePostState(statedb *state.StateDB) error {
  258. // validate post state accounts in test file against what we have in state db
  259. for addr, acct := range t.json.Post {
  260. // address is indirectly verified by the other fields, as it's the db key
  261. code2 := statedb.GetCode(addr)
  262. balance2 := statedb.GetBalance(addr)
  263. nonce2 := statedb.GetNonce(addr)
  264. if !bytes.Equal(code2, acct.Code) {
  265. return fmt.Errorf("account code mismatch for addr: %s want: %v have: %s", addr, acct.Code, hex.EncodeToString(code2))
  266. }
  267. if balance2.Cmp(acct.Balance) != 0 {
  268. return fmt.Errorf("account balance mismatch for addr: %s, want: %d, have: %d", addr, acct.Balance, balance2)
  269. }
  270. if nonce2 != acct.Nonce {
  271. return fmt.Errorf("account nonce mismatch for addr: %s want: %d have: %d", addr, acct.Nonce, nonce2)
  272. }
  273. }
  274. return nil
  275. }
  276. func (t *BlockTest) validateImportedHeaders(cm *core.BlockChain, validBlocks []btBlock) error {
  277. // to get constant lookup when verifying block headers by hash (some tests have many blocks)
  278. bmap := make(map[common.Hash]btBlock, len(t.json.Blocks))
  279. for _, b := range validBlocks {
  280. bmap[b.BlockHeader.Hash] = b
  281. }
  282. // iterate over blocks backwards from HEAD and validate imported
  283. // headers vs test file. some tests have reorgs, and we import
  284. // block-by-block, so we can only validate imported headers after
  285. // all blocks have been processed by BlockChain, as they may not
  286. // be part of the longest chain until last block is imported.
  287. for b := cm.CurrentBlock(); b != nil && b.NumberU64() != 0; b = cm.GetBlockByHash(b.Header().ParentHash) {
  288. if err := validateHeader(bmap[b.Hash()].BlockHeader, b.Header()); err != nil {
  289. return fmt.Errorf("imported block header validation failed: %v", err)
  290. }
  291. }
  292. return nil
  293. }
  294. func (bb *btBlock) decode() (*types.Block, error) {
  295. data, err := hexutil.Decode(bb.Rlp)
  296. if err != nil {
  297. return nil, err
  298. }
  299. var b types.Block
  300. err = rlp.DecodeBytes(data, &b)
  301. return &b, err
  302. }