pow: a fast miner that hashes the bytes before the nonce once (about 100 times faster)

pow.Mine finds the smallest nonce, exactly what trying 0, 1, 2, ... finds, so every signed record and golden fixture stays the same. It saves the SHA-256 state after the whole blocks before the nonce, hashes only the number and what follows per attempt, and uses every core but one from difficulty 14 up. Listing, report, revocation and message mining use it; each re-checks the result before signing. One listing at difficulty 16 takes about 19 ms instead of about 2 s. docs/PROTOCOL.md says what proof-of-work can and cannot do against fast hardware.

allmende-load fills a data directory with signed invented listings for capacity tests and measures mining time (-mine-only).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AeFqV96dVeBX94inzcgZKw
This commit is contained in:
2026-11-19 00:15:52 +01:00
co-authored by Claude Sonnet 5.5
parent 1177754daf
commit 52a6d87553
13 changed files with 747 additions and 44 deletions
+157
View File
@@ -0,0 +1,157 @@
package pow
import (
"bytes"
"errors"
"fmt"
"math/rand/v2"
"runtime"
"strconv"
"strings"
"testing"
)
// record builds canonical-looking bytes with the nonce 0 somewhere inside, with
// before and after bytes of the given sizes (so the nonce lands at every offset
// relative to the 64-byte blocks of the hash).
func record(r *rand.Rand, before, after int) []byte {
pad := func(n int) string {
var b strings.Builder
for i := 0; i < n; i++ {
b.WriteByte("abcdefghijklmnopqrstuvwxyz0123456789 "[r.IntN(37)])
}
return b.String()
}
return []byte(`{"a":"` + pad(before) + `","pow":0,"z":"` + pad(after) + `"}`)
}
// naive is the definition: try 0, 1, 2, ... and hash the whole record each time.
func naive(b []byte, bits int) uint64 {
i := bytes.Index(b, []byte(marker)) + len(marker)
for n := uint64(0); ; n++ {
cand := append(append(append([]byte(nil), b[:i]...), strconv.FormatUint(n, 10)...), b[i+1:]...)
if LeadingZeroBits(cand) >= bits {
return n
}
}
}
func TestMineFindsExactlyWhatTryingEveryNonceInOrderFinds(t *testing.T) {
r := rand.New(rand.NewPCG(1, 2))
// Sizes around the 64-byte hash block, and around zero, so the nonce sits at
// every kind of offset; difficulties from nothing up to the parallel path.
for _, before := range []int{0, 1, 30, 52, 53, 54, 55, 56, 57, 63, 64, 65, 120, 127, 128, 700} {
for _, after := range []int{0, 1, 40, 200} {
for _, bits := range []int{0, 1, 5, 9, 12} {
b := record(r, before, after)
got, err := Mine(b, bits, 1<<53-1)
if err != nil {
t.Fatal(err)
}
if want := naive(b, bits); got != want {
t.Fatalf("before=%d after=%d bits=%d: Mine = %d, trying every nonce finds %d", before, after, bits, got, want)
}
}
}
}
}
func TestWithoutTheSavedHashStateTheAnswerIsTheSame(t *testing.T) {
r := rand.New(rand.NewPCG(11, 12))
noMidstate = true
defer func() { noMidstate = false }()
for _, before := range []int{0, 63, 64, 65, 500} {
b := record(r, before, 90)
got, err := Mine(b, 11, 1<<53-1)
if err != nil || got != naive(b, 11) {
t.Fatalf("before=%d: Mine = %d, %v; trying every nonce finds %d", before, got, err, naive(b, 11))
}
}
}
func TestMiningOnSeveralCoresStillFindsTheSmallestNonce(t *testing.T) {
r := rand.New(rand.NewPCG(3, 4))
for _, bits := range []int{parallelFrom, parallelFrom + 1, parallelFrom + 3} {
for i := 0; i < 3; i++ {
b := record(r, 100+i*37, 60)
want := naive(b, bits)
for _, procs := range []int{1, 2, runtime.NumCPU()} {
old := runtime.GOMAXPROCS(procs)
got, err := Mine(b, bits, 1<<53-1)
runtime.GOMAXPROCS(old)
if err != nil || got != want {
t.Fatalf("bits=%d procs=%d: Mine = %d, %v; smallest is %d", bits, procs, got, err, want)
}
}
}
}
}
func TestTheNonceMineFindsReallyMeetsTheDifficulty(t *testing.T) {
b := record(rand.New(rand.NewPCG(5, 6)), 400, 80)
n, err := Mine(b, 15, 1<<53-1)
if err != nil {
t.Fatal(err)
}
i := bytes.Index(b, []byte(marker)) + len(marker)
done := append(append(append([]byte(nil), b[:i]...), strconv.FormatUint(n, 10)...), b[i+1:]...)
if got := LeadingZeroBits(done); got < 15 {
t.Fatalf("nonce %d gives %d leading zero bits, want at least 15", n, got)
}
if n > 0 {
before := append(append(append([]byte(nil), b[:i]...), strconv.FormatUint(n-1, 10)...), b[i+1:]...)
if LeadingZeroBits(before) >= 15 {
t.Fatalf("nonce %d is not the smallest: %d works too", n, n-1)
}
}
}
func TestMineGivesUpAtTheLimitAndSaysSo(t *testing.T) {
b := record(rand.New(rand.NewPCG(7, 8)), 10, 10)
_, err := Mine(b, 60, 5000) // 60 zero bits in 5000 tries: never
if !errors.Is(err, ErrExhausted) {
t.Fatalf("err = %v, want ErrExhausted", err)
}
// A nonce exactly at the limit is still found.
want := naive(b, 6)
if got, err := Mine(b, 6, want); err != nil || got != want {
t.Fatalf("with the limit at the answer: %d, %v; want %d", got, err, want)
}
if want > 0 {
if _, err := Mine(b, 6, want-1); !errors.Is(err, ErrExhausted) {
t.Fatalf("limit one below the answer: err = %v, want ErrExhausted", err)
}
}
}
func TestMineRefusesRecordsItCannotCut(t *testing.T) {
for name, in := range map[string]string{
"no nonce field": `{"a":1}`,
"two nonce fields": `{"pow":0,"x":{"pow":0}}`,
"nonce not zero": `{"pow":7,"a":1}`,
"nonce with a prefix": `{"pow":05,"a":1}`,
"nonce at the end": `{"a":1,"pow":`,
} {
if _, err := Mine([]byte(in), 8, 1<<53-1); err == nil {
t.Errorf("%s: Mine accepted %q", name, in)
}
}
// The key written inside a string is escaped, so it is not a second nonce.
text := `{"a":"say \"pow\":0 here","pow":0}`
if _, err := Mine([]byte(text), 4, 1<<53-1); err != nil {
t.Errorf("a quoted key inside a string must not count: %v", err)
}
}
func BenchmarkMine(b *testing.B) {
rec := record(rand.New(rand.NewPCG(9, 10)), 1400, 150) // about the size of a listing
for _, bits := range []int{16, 20} {
b.Run(fmt.Sprint("bits", bits), func(b *testing.B) {
for i := 0; i < b.N; i++ {
if _, err := Mine(rec, bits, 1<<53-1); err != nil {
b.Fatal(err)
}
}
})
}
}