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:
@@ -0,0 +1,166 @@
|
||||
package pow
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/sha256"
|
||||
"encoding"
|
||||
"errors"
|
||||
"math"
|
||||
"runtime"
|
||||
"strconv"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
)
|
||||
|
||||
// marker is how the nonce appears in canonical JSON: its key, then the number.
|
||||
// Keys are sorted, so the same bytes surround it on every attempt.
|
||||
const marker = `"pow":`
|
||||
|
||||
// chunk is how many nonces a worker takes at a time. Chunks are handed out in
|
||||
// ascending order, which is what lets parallel mining still return the
|
||||
// smallest nonce.
|
||||
const chunk = 1 << 14
|
||||
|
||||
// parallelFrom is the difficulty from which mining uses several cores; below
|
||||
// it the answer comes in microseconds and starting goroutines would cost more.
|
||||
const parallelFrom = 14
|
||||
|
||||
// noMidstate makes every attempt hash the whole record, as a hash that cannot
|
||||
// save its state would force; only tests set it.
|
||||
var noMidstate bool
|
||||
|
||||
// ErrExhausted means no nonce up to the limit was good enough.
|
||||
var ErrExhausted = errors.New("pow: no nonce found within the limit")
|
||||
|
||||
// Mine returns the smallest nonce n >= 0 for which sha256 of b, with n written
|
||||
// in place of the 0 after "pow":, has at least bits leading zero bits. b is the
|
||||
// canonical encoding of a record whose nonce field is currently 0; it must
|
||||
// contain `"pow":0` exactly once. The result is exactly what trying 0, 1, 2, ...
|
||||
// one by one would find, just much faster: the bytes before the nonce are
|
||||
// hashed once, and every attempt only hashes the number and what follows it,
|
||||
// on every core but one (so the rest of the node keeps running).
|
||||
func Mine(b []byte, bits int, limit uint64) (uint64, error) {
|
||||
prefix, suffix, err := split(b)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
if bits <= 0 {
|
||||
return 0, nil
|
||||
}
|
||||
workers := 1
|
||||
if bits >= parallelFrom {
|
||||
workers = max(1, runtime.GOMAXPROCS(0)-1)
|
||||
}
|
||||
|
||||
var next atomic.Uint64
|
||||
var best atomic.Uint64
|
||||
best.Store(math.MaxUint64)
|
||||
var wg sync.WaitGroup
|
||||
for w := 0; w < workers; w++ {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
m := newMiner(prefix, suffix, bits)
|
||||
for {
|
||||
start := (next.Add(1) - 1) * chunk
|
||||
if start > limit || start >= best.Load() {
|
||||
return
|
||||
}
|
||||
end := start + chunk // exclusive
|
||||
if end > limit+1 || end < start {
|
||||
end = limit + 1
|
||||
}
|
||||
if n, ok := m.scan(start, end, &best); ok {
|
||||
for cur := best.Load(); n < cur && !best.CompareAndSwap(cur, n); cur = best.Load() {
|
||||
}
|
||||
}
|
||||
}
|
||||
}()
|
||||
}
|
||||
wg.Wait()
|
||||
if n := best.Load(); n != math.MaxUint64 {
|
||||
return n, nil
|
||||
}
|
||||
return 0, ErrExhausted
|
||||
}
|
||||
|
||||
// split cuts b around the nonce: everything up to and including `"pow":` and
|
||||
// everything after the 0.
|
||||
func split(b []byte) (prefix, suffix []byte, err error) {
|
||||
if bytes.Count(b, []byte(marker)) != 1 {
|
||||
return nil, nil, errors.New(`pow: the record must contain "pow": exactly once`)
|
||||
}
|
||||
i := bytes.Index(b, []byte(marker)) + len(marker)
|
||||
if i >= len(b) || b[i] != '0' || (i+1 < len(b) && b[i+1] >= '0' && b[i+1] <= '9') {
|
||||
return nil, nil, errors.New(`pow: the nonce must be 0 while mining`)
|
||||
}
|
||||
return b[:i], b[i+1:], nil
|
||||
}
|
||||
|
||||
// miner hashes attempts for one record. Each worker has its own.
|
||||
type miner struct {
|
||||
bits int
|
||||
state []byte // sha256 state after the whole 64-byte blocks of the prefix; nil if unavailable
|
||||
tail []byte // the rest of the prefix
|
||||
suffix []byte
|
||||
h encoding.BinaryUnmarshaler
|
||||
hash interface {
|
||||
Write([]byte) (int, error)
|
||||
Sum([]byte) []byte
|
||||
}
|
||||
msg []byte
|
||||
sum [sha256.Size]byte
|
||||
num []byte
|
||||
// whole is the full prefix, used when the hash cannot save its state.
|
||||
whole []byte
|
||||
}
|
||||
|
||||
func newMiner(prefix, suffix []byte, bits int) *miner {
|
||||
m := &miner{bits: bits, suffix: suffix, whole: prefix, num: make([]byte, 0, 20)}
|
||||
h := sha256.New()
|
||||
u, canRestore := h.(encoding.BinaryUnmarshaler)
|
||||
s, canSave := h.(encoding.BinaryMarshaler)
|
||||
if canRestore && canSave && !noMidstate {
|
||||
full := len(prefix) &^ (sha256.BlockSize - 1)
|
||||
h.Write(prefix[:full])
|
||||
if state, err := s.MarshalBinary(); err == nil {
|
||||
m.state, m.tail, m.h, m.hash = state, prefix[full:], u, h
|
||||
m.msg = make([]byte, 0, len(m.tail)+20+len(suffix))
|
||||
return m
|
||||
}
|
||||
}
|
||||
m.msg = make([]byte, 0, len(prefix)+20+len(suffix))
|
||||
return m
|
||||
}
|
||||
|
||||
// scan tries nonces from..to-1 in order and returns the first that works. It
|
||||
// gives up early once some worker has found a smaller nonce than any left here.
|
||||
func (m *miner) scan(from, to uint64, best *atomic.Uint64) (uint64, bool) {
|
||||
for n := from; n < to; n++ {
|
||||
if n&255 == 0 && n >= best.Load() {
|
||||
return 0, false
|
||||
}
|
||||
m.num = strconv.AppendUint(m.num[:0], n, 10)
|
||||
if m.good(m.num) {
|
||||
return n, true
|
||||
}
|
||||
}
|
||||
return 0, false
|
||||
}
|
||||
|
||||
func (m *miner) good(num []byte) bool {
|
||||
var sum []byte
|
||||
if m.state != nil {
|
||||
m.msg = append(append(append(m.msg[:0], m.tail...), num...), m.suffix...)
|
||||
if m.h.UnmarshalBinary(m.state) != nil {
|
||||
return false
|
||||
}
|
||||
m.hash.Write(m.msg)
|
||||
sum = m.hash.Sum(m.sum[:0])
|
||||
} else {
|
||||
m.msg = append(append(append(m.msg[:0], m.whole...), num...), m.suffix...)
|
||||
s := sha256.Sum256(m.msg)
|
||||
sum = s[:]
|
||||
}
|
||||
return zeroBits(sum) >= m.bits
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -10,6 +10,10 @@ import (
|
||||
// LeadingZeroBits returns the number of leading zero bits of sha256(data).
|
||||
func LeadingZeroBits(data []byte) int {
|
||||
sum := sha256.Sum256(data)
|
||||
return zeroBits(sum[:])
|
||||
}
|
||||
|
||||
func zeroBits(sum []byte) int {
|
||||
n := 0
|
||||
for _, b := range sum {
|
||||
if b == 0 {
|
||||
|
||||
Reference in New Issue
Block a user