block_test_util.go 17 KB

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