Skip to content

Commit 19c7b10

Browse files
authored
Merge pull request #142 from kochd/patch-optimize-pow
optimize randHex() and solvePow()
2 parents 145c982 + 0222175 commit 19c7b10

File tree

1 file changed

+37
-13
lines changed

1 file changed

+37
-13
lines changed

client/uploader_http_pow.go

Lines changed: 37 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -114,12 +114,12 @@ func (u *httpUploaderPow) uploadWithPow(pow Pow, solution string, natsmsg []byte
114114
}
115115

116116
// Generates a random hex string e.g.: faa2743d9181dca5
117-
func randomHex(n int) (string, error) {
118-
bytes := make([]byte, n)
119-
if _, err := rand.Read(bytes); err != nil {
120-
return "", err
121-
}
122-
return hex.EncodeToString(bytes), nil
117+
func randomHex(n int) string {
118+
b := make([]byte, n)
119+
rand.Read(b)
120+
dst := make([]byte, n*2)
121+
hex.Encode(dst, b)
122+
return string(dst)
123123
}
124124

125125
// Converts a string to bits e.g.: 0110011...
@@ -135,16 +135,40 @@ func toBinaryBytes(s string) string {
135135
// until a correct one is found
136136
// returns the solution
137137
func solvePow(pow Pow) string {
138-
solution := ""
138+
wantedLen := len(pow.Wanted)
139+
var hexBuf [64]byte
140+
var binBuf [512]byte
141+
142+
prefix := "aod^"
143+
sep := "^"
139144
for {
140-
randhex, _ := randomHex(8)
141-
if strings.HasPrefix(toBinaryBytes(fmt.Sprintf("%x", sha256.Sum256([]byte("aod^"+randhex+"^"+pow.Key)))), pow.Wanted) {
142-
log.Debugf("SOLVED!")
143-
solution = randhex
144-
break
145+
randhex := randomHex(16)
146+
challenge := prefix + randhex + sep + pow.Key
147+
hash := sha256.Sum256([]byte(challenge))
148+
hex.Encode(hexBuf[:], hash[:])
149+
150+
idx := 0
151+
for i := 0; i < 64; i++ {
152+
b := hexBuf[i]
153+
for j := 7; j >= 0; j-- {
154+
if (b>>j)&1 == 1 {
155+
binBuf[idx] = '1'
156+
} else {
157+
binBuf[idx] = '0'
158+
}
159+
idx++
160+
if idx >= wantedLen {
161+
break
162+
}
163+
}
164+
if idx >= wantedLen {
165+
break
166+
}
167+
}
168+
if string(binBuf[:wantedLen]) == pow.Wanted {
169+
return randhex
145170
}
146171
}
147-
return solution
148172
}
149173

150174
func (u *httpUploaderPow) sendToIngest(body []byte, topic string, state *albionState, identifier string) {

0 commit comments

Comments
 (0)