block_test_util.go 17 KB

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