block_test_util.go 11 KB

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