chain_util_test.go 2.3 KB

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