block_test_util.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575
  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. "bytes"
  19. "encoding/hex"
  20. "fmt"
  21. "io"
  22. "math/big"
  23. "runtime"
  24. "strconv"
  25. "strings"
  26. "github.com/ethereum/ethash"
  27. "github.com/ethereum/go-ethereum/common"
  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/crypto"
  33. "github.com/ethereum/go-ethereum/ethdb"
  34. "github.com/ethereum/go-ethereum/event"
  35. "github.com/ethereum/go-ethereum/logger/glog"
  36. "github.com/ethereum/go-ethereum/params"
  37. "github.com/ethereum/go-ethereum/rlp"
  38. )
  39. // Block Test JSON Format
  40. type BlockTest struct {
  41. Genesis *types.Block
  42. Json *btJSON
  43. preAccounts map[string]btAccount
  44. postAccounts map[string]btAccount
  45. lastblockhash string
  46. }
  47. type btJSON struct {
  48. Blocks []btBlock
  49. GenesisBlockHeader btHeader
  50. Pre map[string]btAccount
  51. PostState map[string]btAccount
  52. Lastblockhash string
  53. }
  54. type btBlock struct {
  55. BlockHeader *btHeader
  56. Rlp string
  57. Transactions []btTransaction
  58. UncleHeaders []*btHeader
  59. }
  60. type btAccount struct {
  61. Balance string
  62. Code string
  63. Nonce string
  64. Storage map[string]string
  65. PrivateKey string
  66. }
  67. type btHeader struct {
  68. Bloom string
  69. Coinbase string
  70. MixHash string
  71. Nonce string
  72. Number string
  73. Hash string
  74. ParentHash string
  75. ReceiptTrie string
  76. SeedHash string
  77. StateRoot string
  78. TransactionsTrie string
  79. UncleHash string
  80. ExtraData string
  81. Difficulty string
  82. GasLimit string
  83. GasUsed string
  84. Timestamp string
  85. }
  86. type btTransaction struct {
  87. Data string
  88. GasLimit string
  89. GasPrice string
  90. Nonce string
  91. R string
  92. S string
  93. To string
  94. V string
  95. Value string
  96. }
  97. func RunBlockTestWithReader(homesteadBlock, daoForkBlock, gasPriceFork *big.Int, r io.Reader, skipTests []string) error {
  98. btjs := make(map[string]*btJSON)
  99. if err := readJson(r, &btjs); err != nil {
  100. return err
  101. }
  102. bt, err := convertBlockTests(btjs)
  103. if err != nil {
  104. return err
  105. }
  106. if err := runBlockTests(homesteadBlock, daoForkBlock, gasPriceFork, bt, skipTests); err != nil {
  107. return err
  108. }
  109. return nil
  110. }
  111. func RunBlockTest(homesteadBlock, daoForkBlock, gasPriceFork *big.Int, file string, skipTests []string) error {
  112. btjs := make(map[string]*btJSON)
  113. if err := readJsonFile(file, &btjs); err != nil {
  114. return err
  115. }
  116. bt, err := convertBlockTests(btjs)
  117. if err != nil {
  118. return err
  119. }
  120. if err := runBlockTests(homesteadBlock, daoForkBlock, gasPriceFork, bt, skipTests); err != nil {
  121. return err
  122. }
  123. return nil
  124. }
  125. func runBlockTests(homesteadBlock, daoForkBlock, gasPriceFork *big.Int, bt map[string]*BlockTest, skipTests []string) error {
  126. skipTest := make(map[string]bool, len(skipTests))
  127. for _, name := range skipTests {
  128. skipTest[name] = true
  129. }
  130. for name, test := range bt {
  131. if skipTest[name] {
  132. glog.Infoln("Skipping block test", name)
  133. continue
  134. }
  135. // test the block
  136. if err := runBlockTest(homesteadBlock, daoForkBlock, gasPriceFork, test); err != nil {
  137. return fmt.Errorf("%s: %v", name, err)
  138. }
  139. glog.Infoln("Block test passed: ", name)
  140. }
  141. return nil
  142. }
  143. func runBlockTest(homesteadBlock, daoForkBlock, gasPriceFork *big.Int, test *BlockTest) error {
  144. // import pre accounts & construct test genesis block & state root
  145. db, _ := ethdb.NewMemDatabase()
  146. if _, err := test.InsertPreState(db); err != nil {
  147. return fmt.Errorf("InsertPreState: %v", err)
  148. }
  149. core.WriteTd(db, test.Genesis.Hash(), 0, test.Genesis.Difficulty())
  150. core.WriteBlock(db, test.Genesis)
  151. core.WriteCanonicalHash(db, test.Genesis.Hash(), test.Genesis.NumberU64())
  152. core.WriteHeadBlockHash(db, test.Genesis.Hash())
  153. evmux := new(event.TypeMux)
  154. config := &params.ChainConfig{HomesteadBlock: homesteadBlock, DAOForkBlock: daoForkBlock, DAOForkSupport: true, EIP150Block: gasPriceFork}
  155. chain, err := core.NewBlockChain(db, config, ethash.NewShared(), evmux, vm.Config{})
  156. if err != nil {
  157. return err
  158. }
  159. //vm.Debug = true
  160. validBlocks, err := test.TryBlocksInsert(chain)
  161. if err != nil {
  162. return err
  163. }
  164. lastblockhash := common.HexToHash(test.lastblockhash)
  165. cmlast := chain.LastBlockHash()
  166. if lastblockhash != cmlast {
  167. return fmt.Errorf("lastblockhash validation mismatch: want: %x, have: %x", lastblockhash, cmlast)
  168. }
  169. newDB, err := chain.State()
  170. if err != nil {
  171. return err
  172. }
  173. if err = test.ValidatePostState(newDB); err != nil {
  174. return fmt.Errorf("post state validation failed: %v", err)
  175. }
  176. return test.ValidateImportedHeaders(chain, validBlocks)
  177. }
  178. // InsertPreState populates the given database with the genesis
  179. // accounts defined by the test.
  180. func (t *BlockTest) InsertPreState(db ethdb.Database) (*state.StateDB, error) {
  181. statedb, err := state.New(common.Hash{}, db)
  182. if err != nil {
  183. return nil, err
  184. }
  185. for addrString, acct := range t.preAccounts {
  186. code, err := hex.DecodeString(strings.TrimPrefix(acct.Code, "0x"))
  187. if err != nil {
  188. return nil, err
  189. }
  190. balance, ok := new(big.Int).SetString(acct.Balance, 0)
  191. if !ok {
  192. return nil, err
  193. }
  194. nonce, err := strconv.ParseUint(prepInt(16, acct.Nonce), 16, 64)
  195. if err != nil {
  196. return nil, err
  197. }
  198. obj := statedb.CreateAccount(common.HexToAddress(addrString))
  199. obj.SetCode(crypto.Keccak256Hash(code), code)
  200. obj.SetBalance(balance)
  201. obj.SetNonce(nonce)
  202. for k, v := range acct.Storage {
  203. statedb.SetState(common.HexToAddress(addrString), common.HexToHash(k), common.HexToHash(v))
  204. }
  205. }
  206. root, err := statedb.Commit(false)
  207. if err != nil {
  208. return nil, fmt.Errorf("error writing state: %v", err)
  209. }
  210. if t.Genesis.Root() != root {
  211. return nil, fmt.Errorf("computed state root does not match genesis block: genesis=%x computed=%x", t.Genesis.Root().Bytes()[:4], root.Bytes()[:4])
  212. }
  213. return statedb, nil
  214. }
  215. /* See https://github.com/ethereum/tests/wiki/Blockchain-Tests-II
  216. Whether a block is valid or not is a bit subtle, it's defined by presence of
  217. blockHeader, transactions and uncleHeaders fields. If they are missing, the block is
  218. invalid and we must verify that we do not accept it.
  219. Since some tests mix valid and invalid blocks we need to check this for every block.
  220. If a block is invalid it does not necessarily fail the test, if it's invalidness is
  221. expected we are expected to ignore it and continue processing and then validate the
  222. post state.
  223. */
  224. func (t *BlockTest) TryBlocksInsert(blockchain *core.BlockChain) ([]btBlock, error) {
  225. validBlocks := make([]btBlock, 0)
  226. // insert the test blocks, which will execute all transactions
  227. for _, b := range t.Json.Blocks {
  228. cb, err := mustConvertBlock(b)
  229. if err != nil {
  230. if b.BlockHeader == nil {
  231. continue // OK - block is supposed to be invalid, continue with next block
  232. } else {
  233. return nil, fmt.Errorf("Block RLP decoding failed when expected to succeed: %v", err)
  234. }
  235. }
  236. // RLP decoding worked, try to insert into chain:
  237. blocks := types.Blocks{cb}
  238. i, err := blockchain.InsertChain(blocks)
  239. if err != nil {
  240. if b.BlockHeader == nil {
  241. continue // OK - block is supposed to be invalid, continue with next block
  242. } else {
  243. return nil, fmt.Errorf("Block #%v insertion into chain failed: %v", blocks[i].Number(), err)
  244. }
  245. }
  246. if b.BlockHeader == nil {
  247. return nil, fmt.Errorf("Block insertion should have failed")
  248. }
  249. // validate RLP decoding by checking all values against test file JSON
  250. if err = validateHeader(b.BlockHeader, cb.Header()); err != nil {
  251. return nil, fmt.Errorf("Deserialised block header validation failed: %v", err)
  252. }
  253. validBlocks = append(validBlocks, b)
  254. }
  255. return validBlocks, nil
  256. }
  257. func validateHeader(h *btHeader, h2 *types.Header) error {
  258. expectedBloom := mustConvertBytes(h.Bloom)
  259. if !bytes.Equal(expectedBloom, h2.Bloom.Bytes()) {
  260. return fmt.Errorf("Bloom: want: %x have: %x", expectedBloom, h2.Bloom.Bytes())
  261. }
  262. expectedCoinbase := mustConvertBytes(h.Coinbase)
  263. if !bytes.Equal(expectedCoinbase, h2.Coinbase.Bytes()) {
  264. return fmt.Errorf("Coinbase: want: %x have: %x", expectedCoinbase, h2.Coinbase.Bytes())
  265. }
  266. expectedMixHashBytes := mustConvertBytes(h.MixHash)
  267. if !bytes.Equal(expectedMixHashBytes, h2.MixDigest.Bytes()) {
  268. return fmt.Errorf("MixHash: want: %x have: %x", expectedMixHashBytes, h2.MixDigest.Bytes())
  269. }
  270. expectedNonce := mustConvertBytes(h.Nonce)
  271. if !bytes.Equal(expectedNonce, h2.Nonce[:]) {
  272. return fmt.Errorf("Nonce: want: %x have: %x", expectedNonce, h2.Nonce)
  273. }
  274. expectedNumber := mustConvertBigInt(h.Number, 16)
  275. if expectedNumber.Cmp(h2.Number) != 0 {
  276. return fmt.Errorf("Number: want: %v have: %v", expectedNumber, h2.Number)
  277. }
  278. expectedParentHash := mustConvertBytes(h.ParentHash)
  279. if !bytes.Equal(expectedParentHash, h2.ParentHash.Bytes()) {
  280. return fmt.Errorf("Parent hash: want: %x have: %x", expectedParentHash, h2.ParentHash.Bytes())
  281. }
  282. expectedReceiptHash := mustConvertBytes(h.ReceiptTrie)
  283. if !bytes.Equal(expectedReceiptHash, h2.ReceiptHash.Bytes()) {
  284. return fmt.Errorf("Receipt hash: want: %x have: %x", expectedReceiptHash, h2.ReceiptHash.Bytes())
  285. }
  286. expectedTxHash := mustConvertBytes(h.TransactionsTrie)
  287. if !bytes.Equal(expectedTxHash, h2.TxHash.Bytes()) {
  288. return fmt.Errorf("Tx hash: want: %x have: %x", expectedTxHash, h2.TxHash.Bytes())
  289. }
  290. expectedStateHash := mustConvertBytes(h.StateRoot)
  291. if !bytes.Equal(expectedStateHash, h2.Root.Bytes()) {
  292. return fmt.Errorf("State hash: want: %x have: %x", expectedStateHash, h2.Root.Bytes())
  293. }
  294. expectedUncleHash := mustConvertBytes(h.UncleHash)
  295. if !bytes.Equal(expectedUncleHash, h2.UncleHash.Bytes()) {
  296. return fmt.Errorf("Uncle hash: want: %x have: %x", expectedUncleHash, h2.UncleHash.Bytes())
  297. }
  298. expectedExtraData := mustConvertBytes(h.ExtraData)
  299. if !bytes.Equal(expectedExtraData, h2.Extra) {
  300. return fmt.Errorf("Extra data: want: %x have: %x", expectedExtraData, h2.Extra)
  301. }
  302. expectedDifficulty := mustConvertBigInt(h.Difficulty, 16)
  303. if expectedDifficulty.Cmp(h2.Difficulty) != 0 {
  304. return fmt.Errorf("Difficulty: want: %v have: %v", expectedDifficulty, h2.Difficulty)
  305. }
  306. expectedGasLimit := mustConvertBigInt(h.GasLimit, 16)
  307. if expectedGasLimit.Cmp(h2.GasLimit) != 0 {
  308. return fmt.Errorf("GasLimit: want: %v have: %v", expectedGasLimit, h2.GasLimit)
  309. }
  310. expectedGasUsed := mustConvertBigInt(h.GasUsed, 16)
  311. if expectedGasUsed.Cmp(h2.GasUsed) != 0 {
  312. return fmt.Errorf("GasUsed: want: %v have: %v", expectedGasUsed, h2.GasUsed)
  313. }
  314. expectedTimestamp := mustConvertBigInt(h.Timestamp, 16)
  315. if expectedTimestamp.Cmp(h2.Time) != 0 {
  316. return fmt.Errorf("Timestamp: want: %v have: %v", expectedTimestamp, h2.Time)
  317. }
  318. return nil
  319. }
  320. func (t *BlockTest) ValidatePostState(statedb *state.StateDB) error {
  321. // validate post state accounts in test file against what we have in state db
  322. for addrString, acct := range t.postAccounts {
  323. // XXX: is is worth it checking for errors here?
  324. addr, err := hex.DecodeString(addrString)
  325. if err != nil {
  326. return err
  327. }
  328. code, err := hex.DecodeString(strings.TrimPrefix(acct.Code, "0x"))
  329. if err != nil {
  330. return err
  331. }
  332. balance, ok := new(big.Int).SetString(acct.Balance, 0)
  333. if !ok {
  334. return err
  335. }
  336. nonce, err := strconv.ParseUint(prepInt(16, acct.Nonce), 16, 64)
  337. if err != nil {
  338. return err
  339. }
  340. // address is indirectly verified by the other fields, as it's the db key
  341. code2 := statedb.GetCode(common.BytesToAddress(addr))
  342. balance2 := statedb.GetBalance(common.BytesToAddress(addr))
  343. nonce2 := statedb.GetNonce(common.BytesToAddress(addr))
  344. if !bytes.Equal(code2, code) {
  345. return fmt.Errorf("account code mismatch for addr: %s want: %s have: %s", addrString, hex.EncodeToString(code), hex.EncodeToString(code2))
  346. }
  347. if balance2.Cmp(balance) != 0 {
  348. return fmt.Errorf("account balance mismatch for addr: %s, want: %d, have: %d", addrString, balance, balance2)
  349. }
  350. if nonce2 != nonce {
  351. return fmt.Errorf("account nonce mismatch for addr: %s want: %d have: %d", addrString, nonce, nonce2)
  352. }
  353. }
  354. return nil
  355. }
  356. func (test *BlockTest) ValidateImportedHeaders(cm *core.BlockChain, validBlocks []btBlock) error {
  357. // to get constant lookup when verifying block headers by hash (some tests have many blocks)
  358. bmap := make(map[string]btBlock, len(test.Json.Blocks))
  359. for _, b := range validBlocks {
  360. bmap[b.BlockHeader.Hash] = b
  361. }
  362. // iterate over blocks backwards from HEAD and validate imported
  363. // headers vs test file. some tests have reorgs, and we import
  364. // block-by-block, so we can only validate imported headers after
  365. // all blocks have been processed by ChainManager, as they may not
  366. // be part of the longest chain until last block is imported.
  367. for b := cm.CurrentBlock(); b != nil && b.NumberU64() != 0; b = cm.GetBlockByHash(b.Header().ParentHash) {
  368. bHash := common.Bytes2Hex(b.Hash().Bytes()) // hex without 0x prefix
  369. if err := validateHeader(bmap[bHash].BlockHeader, b.Header()); err != nil {
  370. return fmt.Errorf("Imported block header validation failed: %v", err)
  371. }
  372. }
  373. return nil
  374. }
  375. func convertBlockTests(in map[string]*btJSON) (map[string]*BlockTest, error) {
  376. out := make(map[string]*BlockTest)
  377. for name, test := range in {
  378. var err error
  379. if out[name], err = convertBlockTest(test); err != nil {
  380. return out, fmt.Errorf("bad test %q: %v", name, err)
  381. }
  382. }
  383. return out, nil
  384. }
  385. func convertBlockTest(in *btJSON) (out *BlockTest, err error) {
  386. // the conversion handles errors by catching panics.
  387. // you might consider this ugly, but the alternative (passing errors)
  388. // would be much harder to read.
  389. defer func() {
  390. if recovered := recover(); recovered != nil {
  391. buf := make([]byte, 64<<10)
  392. buf = buf[:runtime.Stack(buf, false)]
  393. err = fmt.Errorf("%v\n%s", recovered, buf)
  394. }
  395. }()
  396. out = &BlockTest{preAccounts: in.Pre, postAccounts: in.PostState, Json: in, lastblockhash: in.Lastblockhash}
  397. out.Genesis = mustConvertGenesis(in.GenesisBlockHeader)
  398. return out, err
  399. }
  400. func mustConvertGenesis(testGenesis btHeader) *types.Block {
  401. hdr := mustConvertHeader(testGenesis)
  402. hdr.Number = big.NewInt(0)
  403. return types.NewBlockWithHeader(hdr)
  404. }
  405. func mustConvertHeader(in btHeader) *types.Header {
  406. // hex decode these fields
  407. header := &types.Header{
  408. //SeedHash: mustConvertBytes(in.SeedHash),
  409. MixDigest: mustConvertHash(in.MixHash),
  410. Bloom: mustConvertBloom(in.Bloom),
  411. ReceiptHash: mustConvertHash(in.ReceiptTrie),
  412. TxHash: mustConvertHash(in.TransactionsTrie),
  413. Root: mustConvertHash(in.StateRoot),
  414. Coinbase: mustConvertAddress(in.Coinbase),
  415. UncleHash: mustConvertHash(in.UncleHash),
  416. ParentHash: mustConvertHash(in.ParentHash),
  417. Extra: mustConvertBytes(in.ExtraData),
  418. GasUsed: mustConvertBigInt(in.GasUsed, 16),
  419. GasLimit: mustConvertBigInt(in.GasLimit, 16),
  420. Difficulty: mustConvertBigInt(in.Difficulty, 16),
  421. Time: mustConvertBigInt(in.Timestamp, 16),
  422. Nonce: types.EncodeNonce(mustConvertUint(in.Nonce, 16)),
  423. }
  424. return header
  425. }
  426. func mustConvertBlock(testBlock btBlock) (*types.Block, error) {
  427. var b types.Block
  428. r := bytes.NewReader(mustConvertBytes(testBlock.Rlp))
  429. err := rlp.Decode(r, &b)
  430. return &b, err
  431. }
  432. func mustConvertBytes(in string) []byte {
  433. if in == "0x" {
  434. return []byte{}
  435. }
  436. h := unfuckFuckedHex(strings.TrimPrefix(in, "0x"))
  437. out, err := hex.DecodeString(h)
  438. if err != nil {
  439. panic(fmt.Errorf("invalid hex: %q", h))
  440. }
  441. return out
  442. }
  443. func mustConvertHash(in string) common.Hash {
  444. out, err := hex.DecodeString(strings.TrimPrefix(in, "0x"))
  445. if err != nil {
  446. panic(fmt.Errorf("invalid hex: %q", in))
  447. }
  448. return common.BytesToHash(out)
  449. }
  450. func mustConvertAddress(in string) common.Address {
  451. out, err := hex.DecodeString(strings.TrimPrefix(in, "0x"))
  452. if err != nil {
  453. panic(fmt.Errorf("invalid hex: %q", in))
  454. }
  455. return common.BytesToAddress(out)
  456. }
  457. func mustConvertBloom(in string) types.Bloom {
  458. out, err := hex.DecodeString(strings.TrimPrefix(in, "0x"))
  459. if err != nil {
  460. panic(fmt.Errorf("invalid hex: %q", in))
  461. }
  462. return types.BytesToBloom(out)
  463. }
  464. func mustConvertBigInt(in string, base int) *big.Int {
  465. in = prepInt(base, in)
  466. out, ok := new(big.Int).SetString(in, base)
  467. if !ok {
  468. panic(fmt.Errorf("invalid integer: %q", in))
  469. }
  470. return out
  471. }
  472. func mustConvertUint(in string, base int) uint64 {
  473. in = prepInt(base, in)
  474. out, err := strconv.ParseUint(in, base, 64)
  475. if err != nil {
  476. panic(fmt.Errorf("invalid integer: %q", in))
  477. }
  478. return out
  479. }
  480. func LoadBlockTests(file string) (map[string]*BlockTest, error) {
  481. btjs := make(map[string]*btJSON)
  482. if err := readJsonFile(file, &btjs); err != nil {
  483. return nil, err
  484. }
  485. return convertBlockTests(btjs)
  486. }
  487. // Nothing to see here, please move along...
  488. func prepInt(base int, s string) string {
  489. if base == 16 {
  490. s = strings.TrimPrefix(s, "0x")
  491. if len(s) == 0 {
  492. s = "00"
  493. }
  494. s = nibbleFix(s)
  495. }
  496. return s
  497. }
  498. // don't ask
  499. func unfuckFuckedHex(almostHex string) string {
  500. return nibbleFix(strings.Replace(almostHex, "v", "", -1))
  501. }
  502. func nibbleFix(s string) string {
  503. if len(s)%2 != 0 {
  504. s = "0" + s
  505. }
  506. return s
  507. }