block_test_util.go 10 KB

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