block_test_util.go 17 KB

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