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