refactor
This commit is contained in:
@@ -3,19 +3,20 @@ package main
|
||||
import (
|
||||
"crypto"
|
||||
_ "crypto/sha1"
|
||||
"encoding/hex"
|
||||
"encoding/base64"
|
||||
"fmt"
|
||||
"math/rand"
|
||||
"os"
|
||||
"time"
|
||||
)
|
||||
|
||||
func main() {
|
||||
g := Generator{
|
||||
Difficulty: 26,
|
||||
Difficulty: 25,
|
||||
}
|
||||
c := g.RandomChallenge()
|
||||
c.Solve()
|
||||
fmt.Println(c.String())
|
||||
fmt.Println(c.Solve().String())
|
||||
}
|
||||
|
||||
type Challenge struct {
|
||||
@@ -23,6 +24,7 @@ type Challenge struct {
|
||||
Date [20]byte
|
||||
Difficulty byte
|
||||
Solution int64
|
||||
bytes []byte
|
||||
}
|
||||
type Generator struct {
|
||||
Difficulty byte
|
||||
@@ -63,17 +65,30 @@ var prefixLookup = []int{
|
||||
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
|
||||
}
|
||||
|
||||
func (c Challenge) Solve() Challenge {
|
||||
bytes := make([]byte, 76)
|
||||
bytes = append(bytes, c.Input[:]...)
|
||||
bytes = append(bytes, c.Date[:]...)
|
||||
func (c *Challenge) Solve() {
|
||||
c.bytes = make([]byte, 76)
|
||||
c.bytes = append(c.bytes, c.Input[:]...)
|
||||
c.bytes = append(c.bytes, c.Date[:]...)
|
||||
timer := time.Now()
|
||||
for {
|
||||
s := c.Validate()
|
||||
if s {
|
||||
fmt.Fprintf(os.Stderr, "%s: found solution %d in %dms\n", c.String(), c.Solution, time.Since(timer).Milliseconds())
|
||||
break
|
||||
}
|
||||
if c.Solution > 0xffffffffffffff {
|
||||
fmt.Fprintf(os.Stderr, "%s: could not find solution!", c.String())
|
||||
}
|
||||
c.Solution++
|
||||
}
|
||||
}
|
||||
func (c *Challenge) CheckValue(v int64) bool {
|
||||
for i := range 8 {
|
||||
bytes[75-i] = byte(c.Solution >> (i * 8))
|
||||
c.bytes[75-i] = byte(v >> (i * 8))
|
||||
}
|
||||
sum := make([]byte, 20)
|
||||
hash := crypto.SHA1.New()
|
||||
hash.Write(bytes)
|
||||
hash.Write(c.bytes)
|
||||
sum = hash.Sum(nil)
|
||||
count := 0
|
||||
for _, c := range sum {
|
||||
@@ -83,18 +98,12 @@ func (c Challenge) Solve() Challenge {
|
||||
break
|
||||
}
|
||||
}
|
||||
if c.Solution%20000000 == 0 {
|
||||
println(c.Solution)
|
||||
}
|
||||
if count >= int(c.Difficulty) {
|
||||
println(c.Solution)
|
||||
break
|
||||
}
|
||||
c.Solution++
|
||||
}
|
||||
return c
|
||||
return count >= int(c.Difficulty)
|
||||
}
|
||||
func (c Challenge) String() string {
|
||||
func (c *Challenge) Validate() bool {
|
||||
return c.CheckValue(c.Solution)
|
||||
}
|
||||
func (c *Challenge) String() string {
|
||||
bytes := make([]byte, 0)
|
||||
bytes = append(bytes, c.Input[:]...)
|
||||
bytes = append(bytes, c.Date[:]...)
|
||||
@@ -103,5 +112,5 @@ func (c Challenge) String() string {
|
||||
for i := range 7 {
|
||||
bytes[75-i] = byte(c.Solution >> (i * 8))
|
||||
}
|
||||
return hex.EncodeToString(bytes)
|
||||
return base64.URLEncoding.EncodeToString(bytes)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user