block_test_util.go 15 KB

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