consensus_test.go 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. // Copyright 2017 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 ethash
  17. import (
  18. "encoding/json"
  19. "math/big"
  20. "os"
  21. "testing"
  22. "github.com/ethereum/go-ethereum/common/math"
  23. "github.com/ethereum/go-ethereum/params"
  24. )
  25. type diffTest struct {
  26. ParentTimestamp uint64
  27. ParentDifficulty *big.Int
  28. CurrentTimestamp uint64
  29. CurrentBlocknumber *big.Int
  30. CurrentDifficulty *big.Int
  31. }
  32. func (d *diffTest) UnmarshalJSON(b []byte) (err error) {
  33. var ext struct {
  34. ParentTimestamp string
  35. ParentDifficulty string
  36. CurrentTimestamp string
  37. CurrentBlocknumber string
  38. CurrentDifficulty string
  39. }
  40. if err := json.Unmarshal(b, &ext); err != nil {
  41. return err
  42. }
  43. d.ParentTimestamp = math.MustParseUint64(ext.ParentTimestamp)
  44. d.ParentDifficulty = math.MustParseBig256(ext.ParentDifficulty)
  45. d.CurrentTimestamp = math.MustParseUint64(ext.CurrentTimestamp)
  46. d.CurrentBlocknumber = math.MustParseBig256(ext.CurrentBlocknumber)
  47. d.CurrentDifficulty = math.MustParseBig256(ext.CurrentDifficulty)
  48. return nil
  49. }
  50. func TestCalcDifficulty(t *testing.T) {
  51. file, err := os.Open("../../tests/files/BasicTests/difficulty.json")
  52. if err != nil {
  53. t.Fatal(err)
  54. }
  55. defer file.Close()
  56. tests := make(map[string]diffTest)
  57. err = json.NewDecoder(file).Decode(&tests)
  58. if err != nil {
  59. t.Fatal(err)
  60. }
  61. config := &params.ChainConfig{HomesteadBlock: big.NewInt(1150000)}
  62. for name, test := range tests {
  63. number := new(big.Int).Sub(test.CurrentBlocknumber, big.NewInt(1))
  64. diff := CalcDifficulty(config, test.CurrentTimestamp, test.ParentTimestamp, number, test.ParentDifficulty)
  65. if diff.Cmp(test.CurrentDifficulty) != 0 {
  66. t.Error(name, "failed. Expected", test.CurrentDifficulty, "and calculated", diff)
  67. }
  68. }
  69. }