github.com/sberex/go-sberex@v1.8.2-0.20181113200658-ed96ac38f7d7/consensus/ethash/consensus_test.go (about) 1 // This file is part of the go-sberex library. The go-sberex library is 2 // free software: you can redistribute it and/or modify it under the terms 3 // of the GNU Lesser General Public License as published by the Free 4 // Software Foundation, either version 3 of the License, or (at your option) 5 // any later version. 6 // 7 // The go-sberex library is distributed in the hope that it will be useful, 8 // but WITHOUT ANY WARRANTY; without even the implied warranty of 9 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser 10 // General Public License <http://www.gnu.org/licenses/> for more details. 11 12 package ethash 13 14 import ( 15 "encoding/json" 16 "math/big" 17 "os" 18 "path/filepath" 19 "testing" 20 21 "github.com/Sberex/go-sberex/common/math" 22 "github.com/Sberex/go-sberex/core/types" 23 "github.com/Sberex/go-sberex/params" 24 ) 25 26 type diffTest struct { 27 ParentTimestamp uint64 28 ParentDifficulty *big.Int 29 CurrentTimestamp uint64 30 CurrentBlocknumber *big.Int 31 CurrentDifficulty *big.Int 32 } 33 34 func (d *diffTest) UnmarshalJSON(b []byte) (err error) { 35 var ext struct { 36 ParentTimestamp string 37 ParentDifficulty string 38 CurrentTimestamp string 39 CurrentBlocknumber string 40 CurrentDifficulty string 41 } 42 if err := json.Unmarshal(b, &ext); err != nil { 43 return err 44 } 45 46 d.ParentTimestamp = math.MustParseUint64(ext.ParentTimestamp) 47 d.ParentDifficulty = math.MustParseBig256(ext.ParentDifficulty) 48 d.CurrentTimestamp = math.MustParseUint64(ext.CurrentTimestamp) 49 d.CurrentBlocknumber = math.MustParseBig256(ext.CurrentBlocknumber) 50 d.CurrentDifficulty = math.MustParseBig256(ext.CurrentDifficulty) 51 52 return nil 53 } 54 55 func TestCalcDifficulty(t *testing.T) { 56 file, err := os.Open(filepath.Join("..", "..", "tests", "testdata", "BasicTests", "difficulty.json")) 57 if err != nil { 58 t.Skip(err) 59 } 60 defer file.Close() 61 62 tests := make(map[string]diffTest) 63 err = json.NewDecoder(file).Decode(&tests) 64 if err != nil { 65 t.Fatal(err) 66 } 67 68 config := ¶ms.ChainConfig{HomesteadBlock: big.NewInt(0)} 69 70 for name, test := range tests { 71 number := new(big.Int).Sub(test.CurrentBlocknumber, big.NewInt(1)) 72 diff := CalcDifficulty(config, test.CurrentTimestamp, &types.Header{ 73 Number: number, 74 Time: new(big.Int).SetUint64(test.ParentTimestamp), 75 Difficulty: test.ParentDifficulty, 76 }) 77 if diff.Cmp(test.CurrentDifficulty) != 0 { 78 t.Error(name, "failed. Expected", test.CurrentDifficulty, "and calculated", diff) 79 } 80 } 81 }