block_test_util.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577
  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/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] /*|| name != "CallingCanonicalContractFromFork_CALLCODE"*/ {
  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, vm.Config{})
  155. if err != nil {
  156. return err
  157. }
  158. defer chain.Stop()
  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. addr := common.HexToAddress(addrString)
  199. statedb.CreateAccount(addr)
  200. statedb.SetCode(addr, code)
  201. statedb.SetBalance(addr, balance)
  202. statedb.SetNonce(addr, nonce)
  203. for k, v := range acct.Storage {
  204. statedb.SetState(common.HexToAddress(addrString), common.HexToHash(k), common.HexToHash(v))
  205. }
  206. }
  207. root, err := statedb.Commit(false)
  208. if err != nil {
  209. return nil, fmt.Errorf("error writing state: %v", err)
  210. }
  211. if t.Genesis.Root() != root {
  212. return nil, fmt.Errorf("computed state root does not match genesis block: genesis=%x computed=%x", t.Genesis.Root().Bytes()[:4], root.Bytes()[:4])
  213. }
  214. return statedb, nil
  215. }
  216. /* See https://github.com/ethereum/tests/wiki/Blockchain-Tests-II
  217. Whether a block is valid or not is a bit subtle, it's defined by presence of
  218. blockHeader, transactions and uncleHeaders fields. If they are missing, the block is
  219. invalid and we must verify that we do not accept it.
  220. Since some tests mix valid and invalid blocks we need to check this for every block.
  221. If a block is invalid it does not necessarily fail the test, if it's invalidness is
  222. expected we are expected to ignore it and continue processing and then validate the
  223. post state.
  224. */
  225. func (t *BlockTest) TryBlocksInsert(blockchain *core.BlockChain) ([]btBlock, error) {
  226. validBlocks := make([]btBlock, 0)
  227. // insert the test blocks, which will execute all transactions
  228. for _, b := range t.Json.Blocks {
  229. cb, err := mustConvertBlock(b)
  230. if err != nil {
  231. if b.BlockHeader == nil {
  232. continue // OK - block is supposed to be invalid, continue with next block
  233. } else {
  234. return nil, fmt.Errorf("Block RLP decoding failed when expected to succeed: %v", err)
  235. }
  236. }
  237. // RLP decoding worked, try to insert into chain:
  238. blocks := types.Blocks{cb}
  239. i, err := blockchain.InsertChain(blocks)
  240. if err != nil {
  241. if b.BlockHeader == nil {
  242. continue // OK - block is supposed to be invalid, continue with next block
  243. } else {
  244. return nil, fmt.Errorf("Block #%v insertion into chain failed: %v", blocks[i].Number(), err)
  245. }
  246. }
  247. if b.BlockHeader == nil {
  248. return nil, fmt.Errorf("Block insertion should have failed")
  249. }
  250. // validate RLP decoding by checking all values against test file JSON
  251. if err = validateHeader(b.BlockHeader, cb.Header()); err != nil {
  252. return nil, fmt.Errorf("Deserialised block header validation failed: %v", err)
  253. }
  254. validBlocks = append(validBlocks, b)
  255. }
  256. return validBlocks, nil
  257. }
  258. func validateHeader(h *btHeader, h2 *types.Header) error {
  259. expectedBloom := mustConvertBytes(h.Bloom)
  260. if !bytes.Equal(expectedBloom, h2.Bloom.Bytes()) {
  261. return fmt.Errorf("Bloom: want: %x have: %x", expectedBloom, h2.Bloom.Bytes())
  262. }
  263. expectedCoinbase := mustConvertBytes(h.Coinbase)
  264. if !bytes.Equal(expectedCoinbase, h2.Coinbase.Bytes()) {
  265. return fmt.Errorf("Coinbase: want: %x have: %x", expectedCoinbase, h2.Coinbase.Bytes())
  266. }
  267. expectedMixHashBytes := mustConvertBytes(h.MixHash)
  268. if !bytes.Equal(expectedMixHashBytes, h2.MixDigest.Bytes()) {
  269. return fmt.Errorf("MixHash: want: %x have: %x", expectedMixHashBytes, h2.MixDigest.Bytes())
  270. }
  271. expectedNonce := mustConvertBytes(h.Nonce)
  272. if !bytes.Equal(expectedNonce, h2.Nonce[:]) {
  273. return fmt.Errorf("Nonce: want: %x have: %x", expectedNonce, h2.Nonce)
  274. }
  275. expectedNumber := mustConvertBigInt(h.Number, 16)
  276. if expectedNumber.Cmp(h2.Number) != 0 {
  277. return fmt.Errorf("Number: want: %v have: %v", expectedNumber, h2.Number)
  278. }
  279. expectedParentHash := mustConvertBytes(h.ParentHash)
  280. if !bytes.Equal(expectedParentHash, h2.ParentHash.Bytes()) {
  281. return fmt.Errorf("Parent hash: want: %x have: %x", expectedParentHash, h2.ParentHash.Bytes())
  282. }
  283. expectedReceiptHash := mustConvertBytes(h.ReceiptTrie)
  284. if !bytes.Equal(expectedReceiptHash, h2.ReceiptHash.Bytes()) {
  285. return fmt.Errorf("Receipt hash: want: %x have: %x", expectedReceiptHash, h2.ReceiptHash.Bytes())
  286. }
  287. expectedTxHash := mustConvertBytes(h.TransactionsTrie)
  288. if !bytes.Equal(expectedTxHash, h2.TxHash.Bytes()) {
  289. return fmt.Errorf("Tx hash: want: %x have: %x", expectedTxHash, h2.TxHash.Bytes())
  290. }
  291. expectedStateHash := mustConvertBytes(h.StateRoot)
  292. if !bytes.Equal(expectedStateHash, h2.Root.Bytes()) {
  293. return fmt.Errorf("State hash: want: %x have: %x", expectedStateHash, h2.Root.Bytes())
  294. }
  295. expectedUncleHash := mustConvertBytes(h.UncleHash)
  296. if !bytes.Equal(expectedUncleHash, h2.UncleHash.Bytes()) {
  297. return fmt.Errorf("Uncle hash: want: %x have: %x", expectedUncleHash, h2.UncleHash.Bytes())
  298. }
  299. expectedExtraData := mustConvertBytes(h.ExtraData)
  300. if !bytes.Equal(expectedExtraData, h2.Extra) {
  301. return fmt.Errorf("Extra data: want: %x have: %x", expectedExtraData, h2.Extra)
  302. }
  303. expectedDifficulty := mustConvertBigInt(h.Difficulty, 16)
  304. if expectedDifficulty.Cmp(h2.Difficulty) != 0 {
  305. return fmt.Errorf("Difficulty: want: %v have: %v", expectedDifficulty, h2.Difficulty)
  306. }
  307. expectedGasLimit := mustConvertBigInt(h.GasLimit, 16)
  308. if expectedGasLimit.Cmp(h2.GasLimit) != 0 {
  309. return fmt.Errorf("GasLimit: want: %v have: %v", expectedGasLimit, h2.GasLimit)
  310. }
  311. expectedGasUsed := mustConvertBigInt(h.GasUsed, 16)
  312. if expectedGasUsed.Cmp(h2.GasUsed) != 0 {
  313. return fmt.Errorf("GasUsed: want: %v have: %v", expectedGasUsed, h2.GasUsed)
  314. }
  315. expectedTimestamp := mustConvertBigInt(h.Timestamp, 16)
  316. if expectedTimestamp.Cmp(h2.Time) != 0 {
  317. return fmt.Errorf("Timestamp: want: %v have: %v", expectedTimestamp, h2.Time)
  318. }
  319. return nil
  320. }
  321. func (t *BlockTest) ValidatePostState(statedb *state.StateDB) error {
  322. // validate post state accounts in test file against what we have in state db
  323. for addrString, acct := range t.postAccounts {
  324. // XXX: is is worth it checking for errors here?
  325. addr, err := hex.DecodeString(addrString)
  326. if err != nil {
  327. return err
  328. }
  329. code, err := hex.DecodeString(strings.TrimPrefix(acct.Code, "0x"))
  330. if err != nil {
  331. return err
  332. }
  333. balance, ok := new(big.Int).SetString(acct.Balance, 0)
  334. if !ok {
  335. return err
  336. }
  337. nonce, err := strconv.ParseUint(prepInt(16, acct.Nonce), 16, 64)
  338. if err != nil {
  339. return err
  340. }
  341. // address is indirectly verified by the other fields, as it's the db key
  342. code2 := statedb.GetCode(common.BytesToAddress(addr))
  343. balance2 := statedb.GetBalance(common.BytesToAddress(addr))
  344. nonce2 := statedb.GetNonce(common.BytesToAddress(addr))
  345. if !bytes.Equal(code2, code) {
  346. return fmt.Errorf("account code mismatch for addr: %s want: %s have: %s", addrString, hex.EncodeToString(code), hex.EncodeToString(code2))
  347. }
  348. if balance2.Cmp(balance) != 0 {
  349. return fmt.Errorf("account balance mismatch for addr: %s, want: %d, have: %d", addrString, balance, balance2)
  350. }
  351. if nonce2 != nonce {
  352. return fmt.Errorf("account nonce mismatch for addr: %s want: %d have: %d", addrString, nonce, nonce2)
  353. }
  354. }
  355. return nil
  356. }
  357. func (test *BlockTest) ValidateImportedHeaders(cm *core.BlockChain, validBlocks []btBlock) error {
  358. // to get constant lookup when verifying block headers by hash (some tests have many blocks)
  359. bmap := make(map[string]btBlock, len(test.Json.Blocks))
  360. for _, b := range validBlocks {
  361. bmap[b.BlockHeader.Hash] = b
  362. }
  363. // iterate over blocks backwards from HEAD and validate imported
  364. // headers vs test file. some tests have reorgs, and we import
  365. // block-by-block, so we can only validate imported headers after
  366. // all blocks have been processed by ChainManager, as they may not
  367. // be part of the longest chain until last block is imported.
  368. for b := cm.CurrentBlock(); b != nil && b.NumberU64() != 0; b = cm.GetBlockByHash(b.Header().ParentHash) {
  369. bHash := common.Bytes2Hex(b.Hash().Bytes()) // hex without 0x prefix
  370. if err := validateHeader(bmap[bHash].BlockHeader, b.Header()); err != nil {
  371. return fmt.Errorf("Imported block header validation failed: %v", err)
  372. }
  373. }
  374. return nil
  375. }
  376. func convertBlockTests(in map[string]*btJSON) (map[string]*BlockTest, error) {
  377. out := make(map[string]*BlockTest)
  378. for name, test := range in {
  379. var err error
  380. if out[name], err = convertBlockTest(test); err != nil {
  381. return out, fmt.Errorf("bad test %q: %v", name, err)
  382. }
  383. }
  384. return out, nil
  385. }
  386. func convertBlockTest(in *btJSON) (out *BlockTest, err error) {
  387. // the conversion handles errors by catching panics.
  388. // you might consider this ugly, but the alternative (passing errors)
  389. // would be much harder to read.
  390. defer func() {
  391. if recovered := recover(); recovered != nil {
  392. buf := make([]byte, 64<<10)
  393. buf = buf[:runtime.Stack(buf, false)]
  394. err = fmt.Errorf("%v\n%s", recovered, buf)
  395. }
  396. }()
  397. out = &BlockTest{preAccounts: in.Pre, postAccounts: in.PostState, Json: in, lastblockhash: in.Lastblockhash}
  398. out.Genesis = mustConvertGenesis(in.GenesisBlockHeader)
  399. return out, err
  400. }
  401. func mustConvertGenesis(testGenesis btHeader) *types.Block {
  402. hdr := mustConvertHeader(testGenesis)
  403. hdr.Number = big.NewInt(0)
  404. return types.NewBlockWithHeader(hdr)
  405. }
  406. func mustConvertHeader(in btHeader) *types.Header {
  407. // hex decode these fields
  408. header := &types.Header{
  409. //SeedHash: mustConvertBytes(in.SeedHash),
  410. MixDigest: mustConvertHash(in.MixHash),
  411. Bloom: mustConvertBloom(in.Bloom),
  412. ReceiptHash: mustConvertHash(in.ReceiptTrie),
  413. TxHash: mustConvertHash(in.TransactionsTrie),
  414. Root: mustConvertHash(in.StateRoot),
  415. Coinbase: mustConvertAddress(in.Coinbase),
  416. UncleHash: mustConvertHash(in.UncleHash),
  417. ParentHash: mustConvertHash(in.ParentHash),
  418. Extra: mustConvertBytes(in.ExtraData),
  419. GasUsed: mustConvertBigInt(in.GasUsed, 16),
  420. GasLimit: mustConvertBigInt(in.GasLimit, 16),
  421. Difficulty: mustConvertBigInt(in.Difficulty, 16),
  422. Time: mustConvertBigInt(in.Timestamp, 16),
  423. Nonce: types.EncodeNonce(mustConvertUint(in.Nonce, 16)),
  424. }
  425. return header
  426. }
  427. func mustConvertBlock(testBlock btBlock) (*types.Block, error) {
  428. var b types.Block
  429. r := bytes.NewReader(mustConvertBytes(testBlock.Rlp))
  430. err := rlp.Decode(r, &b)
  431. return &b, err
  432. }
  433. func mustConvertBytes(in string) []byte {
  434. if in == "0x" {
  435. return []byte{}
  436. }
  437. h := unfuckFuckedHex(strings.TrimPrefix(in, "0x"))
  438. out, err := hex.DecodeString(h)
  439. if err != nil {
  440. panic(fmt.Errorf("invalid hex: %q", h))
  441. }
  442. return out
  443. }
  444. func mustConvertHash(in string) common.Hash {
  445. out, err := hex.DecodeString(strings.TrimPrefix(in, "0x"))
  446. if err != nil {
  447. panic(fmt.Errorf("invalid hex: %q", in))
  448. }
  449. return common.BytesToHash(out)
  450. }
  451. func mustConvertAddress(in string) common.Address {
  452. out, err := hex.DecodeString(strings.TrimPrefix(in, "0x"))
  453. if err != nil {
  454. panic(fmt.Errorf("invalid hex: %q", in))
  455. }
  456. return common.BytesToAddress(out)
  457. }
  458. func mustConvertBloom(in string) types.Bloom {
  459. out, err := hex.DecodeString(strings.TrimPrefix(in, "0x"))
  460. if err != nil {
  461. panic(fmt.Errorf("invalid hex: %q", in))
  462. }
  463. return types.BytesToBloom(out)
  464. }
  465. func mustConvertBigInt(in string, base int) *big.Int {
  466. in = prepInt(base, in)
  467. out, ok := new(big.Int).SetString(in, base)
  468. if !ok {
  469. panic(fmt.Errorf("invalid integer: %q", in))
  470. }
  471. return out
  472. }
  473. func mustConvertUint(in string, base int) uint64 {
  474. in = prepInt(base, in)
  475. out, err := strconv.ParseUint(in, base, 64)
  476. if err != nil {
  477. panic(fmt.Errorf("invalid integer: %q", in))
  478. }
  479. return out
  480. }
  481. func LoadBlockTests(file string) (map[string]*BlockTest, error) {
  482. btjs := make(map[string]*btJSON)
  483. if err := readJsonFile(file, &btjs); err != nil {
  484. return nil, err
  485. }
  486. return convertBlockTests(btjs)
  487. }
  488. // Nothing to see here, please move along...
  489. func prepInt(base int, s string) string {
  490. if base == 16 {
  491. s = strings.TrimPrefix(s, "0x")
  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. }