block_test_util.go 16 KB

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