difficulty_test_util.go 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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. //
  17. package tests
  18. import (
  19. "fmt"
  20. "math/big"
  21. "github.com/ethereum/go-ethereum/common"
  22. "github.com/ethereum/go-ethereum/common/math"
  23. "github.com/ethereum/go-ethereum/consensus/ethash"
  24. "github.com/ethereum/go-ethereum/core/types"
  25. "github.com/ethereum/go-ethereum/params"
  26. )
  27. //go:generate gencodec -type DifficultyTest -field-override difficultyTestMarshaling -out gen_difficultytest.go
  28. type DifficultyTest struct {
  29. ParentTimestamp *big.Int `json:"parentTimestamp"`
  30. ParentDifficulty *big.Int `json:"parentDifficulty"`
  31. UncleHash common.Hash `json:"parentUncles"`
  32. CurrentTimestamp *big.Int `json:"currentTimestamp"`
  33. CurrentBlockNumber uint64 `json:"currentBlockNumber"`
  34. CurrentDifficulty *big.Int `json:"currentDifficulty"`
  35. }
  36. type difficultyTestMarshaling struct {
  37. ParentTimestamp *math.HexOrDecimal256
  38. ParentDifficulty *math.HexOrDecimal256
  39. CurrentTimestamp *math.HexOrDecimal256
  40. CurrentDifficulty *math.HexOrDecimal256
  41. UncleHash common.Hash
  42. CurrentBlockNumber math.HexOrDecimal64
  43. }
  44. func (test *DifficultyTest) Run(config *params.ChainConfig) error {
  45. parentNumber := big.NewInt(int64(test.CurrentBlockNumber - 1))
  46. parent := &types.Header{
  47. Difficulty: test.ParentDifficulty,
  48. Time: test.ParentTimestamp,
  49. Number: parentNumber,
  50. UncleHash: test.UncleHash,
  51. }
  52. actual := ethash.CalcDifficulty(config, test.CurrentTimestamp.Uint64(), parent)
  53. exp := test.CurrentDifficulty
  54. if actual.Cmp(exp) != 0 {
  55. return fmt.Errorf("parent[time %v diff %v unclehash:%x] child[time %v number %v] diff %v != expected %v",
  56. test.ParentTimestamp, test.ParentDifficulty, test.UncleHash,
  57. test.CurrentTimestamp, test.CurrentBlockNumber, actual, exp)
  58. }
  59. return nil
  60. }