use string instead of bytes, fix off by 1

This commit is contained in:
2026-07-24 22:59:05 -05:00
parent d1dd21b61c
commit ef24f343e6
+27 -19
View File
@@ -4,17 +4,18 @@ import (
"context"
"crypto"
_ "crypto/sha1"
"encoding/hex"
"encoding/base64"
"fmt"
"math/rand"
"os"
"runtime"
"strings"
"time"
)
func main() {
g := Generator{
Difficulty: 25,
Difficulty: 20,
Timeout: 10 * time.Second,
}
c := g.RandomChallenge()
@@ -28,7 +29,6 @@ type Challenge struct {
Input [48]byte
Date [20]byte
Solution int64
bytes []byte
Generator
}
type Generator struct {
@@ -72,9 +72,6 @@ var prefixLookup = []int{
}
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()
solution := make(chan int64)
ctx, cancel := context.WithCancel(context.Background())
@@ -95,7 +92,7 @@ func (c *Challenge) Solve() {
cancel()
break
}
if c.Solution > 0xffffffffffffff {
if c.Solution > 0xfffffff {
fmt.Fprintf(os.Stderr, "%s (thread %d): could not find solution!\n", c.String(), id)
cancel()
break
@@ -121,14 +118,12 @@ func (c *Challenge) Solve() {
}
}
func (c *Challenge) CheckValue(v int64) bool {
bytes := make([]byte, len(c.bytes))
copy(bytes, c.bytes)
for i := range 8 {
bytes[75-i] = byte(v >> (i * 8))
}
var sb strings.Builder
sb.WriteString(c.StringNoSolution())
sb.WriteString(StringSolution(v))
sum := make([]byte, 20)
hash := crypto.SHA1.New()
hash.Write(bytes)
hash.Write([]byte(sb.String()))
sum = hash.Sum(nil)
count := 0
for _, c := range sum {
@@ -144,13 +139,26 @@ func (c *Challenge) Validate() bool {
return c.CheckValue(c.Solution)
}
func (c *Challenge) String() string {
var sb strings.Builder
sb.WriteString(c.StringNoSolution())
sb.WriteString(c.StringThisSolution())
return sb.String()
}
func (c *Challenge) StringNoSolution() string {
var sb strings.Builder
bytes := make([]byte, 0)
bytes = append(bytes, c.Input[:]...)
bytes = append(bytes, c.Date[:]...)
bytes = append(bytes, make([]byte, 8)...)
bytes[68] = c.Difficulty
for i := range 7 {
bytes[75-i] = byte(c.Solution >> (i * 8))
}
return hex.EncodeToString(bytes)
bytes = append(bytes, c.Difficulty)
sb.WriteString(base64.URLEncoding.EncodeToString(bytes))
return sb.String()
}
func (c *Challenge) StringThisSolution() string {
return StringSolution(c.Solution)
}
func StringSolution(v int64) string {
var sb strings.Builder
sb.WriteRune(';')
sb.WriteString(fmt.Sprintf("%07x", v))
return sb.String()
}