block_test_util.go 17 KB

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