github.com/linapex/ethereum-go-chinese@v0.0.0-20190316121929-f8b7a73c3fa1/consensus/ethash/consensus_test.go (about) 1 2 //<developer> 3 // <name>linapex 曹一峰</name> 4 // <email>linapex@163.com</email> 5 // <wx>superexc</wx> 6 // <qqgroup>128148617</qqgroup> 7 // <url>https://jsq.ink</url> 8 // <role>pku engineer</role> 9 // <date>2019-03-16 19:16:34</date> 10 //</624450075019448320> 11 12 13 package ethash 14 15 import ( 16 "encoding/json" 17 "math/big" 18 "os" 19 "path/filepath" 20 "testing" 21 22 "github.com/ethereum/go-ethereum/common/math" 23 "github.com/ethereum/go-ethereum/core/types" 24 "github.com/ethereum/go-ethereum/params" 25 ) 26 27 type diffTest struct { 28 ParentTimestamp uint64 29 ParentDifficulty *big.Int 30 CurrentTimestamp uint64 31 CurrentBlocknumber *big.Int 32 CurrentDifficulty *big.Int 33 } 34 35 func (d *diffTest) UnmarshalJSON(b []byte) (err error) { 36 var ext struct { 37 ParentTimestamp string 38 ParentDifficulty string 39 CurrentTimestamp string 40 CurrentBlocknumber string 41 CurrentDifficulty string 42 } 43 if err := json.Unmarshal(b, &ext); err != nil { 44 return err 45 } 46 47 d.ParentTimestamp = math.MustParseUint64(ext.ParentTimestamp) 48 d.ParentDifficulty = math.MustParseBig256(ext.ParentDifficulty) 49 d.CurrentTimestamp = math.MustParseUint64(ext.CurrentTimestamp) 50 d.CurrentBlocknumber = math.MustParseBig256(ext.CurrentBlocknumber) 51 d.CurrentDifficulty = math.MustParseBig256(ext.CurrentDifficulty) 52 53 return nil 54 } 55 56 func TestCalcDifficulty(t *testing.T) { 57 file, err := os.Open(filepath.Join("..", "..", "tests", "testdata", "BasicTests", "difficulty.json")) 58 if err != nil { 59 t.Skip(err) 60 } 61 defer file.Close() 62 63 tests := make(map[string]diffTest) 64 err = json.NewDecoder(file).Decode(&tests) 65 if err != nil { 66 t.Fatal(err) 67 } 68 69 config := ¶ms.ChainConfig{HomesteadBlock: big.NewInt(1150000)} 70 71 for name, test := range tests { 72 number := new(big.Int).Sub(test.CurrentBlocknumber, big.NewInt(1)) 73 diff := CalcDifficulty(config, test.CurrentTimestamp, &types.Header{ 74 Number: number, 75 Time: new(big.Int).SetUint64(test.ParentTimestamp), 76 Difficulty: test.ParentDifficulty, 77 }) 78 if diff.Cmp(test.CurrentDifficulty) != 0 { 79 t.Error(name, "failed. Expected", test.CurrentDifficulty, "and calculated", diff) 80 } 81 } 82 } 83