From 19d42888fbce47e6776f41733bf18324719daf1e Mon Sep 17 00:00:00 2001 From: mae Date: Fri, 24 Jul 2026 12:16:29 -0500 Subject: [PATCH] refactor --- main.go | 69 ++++++++++++++++++++++++++++++++------------------------- 1 file changed, 39 insertions(+), 30 deletions(-) diff --git a/main.go b/main.go index 794ab4e..9e20b12 100644 --- a/main.go +++ b/main.go @@ -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,38 +65,45 @@ 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 { - for i := range 8 { - bytes[75-i] = byte(c.Solution >> (i * 8)) - } - sum := make([]byte, 20) - hash := crypto.SHA1.New() - hash.Write(bytes) - sum = hash.Sum(nil) - count := 0 - for _, c := range sum { - p := prefixLookup[c] - count += p - if p != 8 { - break - } - } - if c.Solution%20000000 == 0 { - println(c.Solution) - } - if count >= int(c.Difficulty) { - println(c.Solution) + 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++ } - return c } -func (c Challenge) String() string { +func (c *Challenge) CheckValue(v int64) bool { + for i := range 8 { + c.bytes[75-i] = byte(v >> (i * 8)) + } + sum := make([]byte, 20) + hash := crypto.SHA1.New() + hash.Write(c.bytes) + sum = hash.Sum(nil) + count := 0 + for _, c := range sum { + p := prefixLookup[c] + count += p + if p != 8 { + break + } + } + return count >= int(c.Difficulty) +} +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) }