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