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