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
+243
View File
@@ -0,0 +1,243 @@
// Command allmende-load fills a node's data directory with many invented but
// validly signed listings, for capacity tests: how large the database gets,
// what a node holding them costs in memory, how fast it searches, and how a
// newcomer catches up from it.
//
// allmende init --data DIR --no-phrase
// allmende-load --data DIR -n 100000 -difficulty 8
// allmende run --data DIR --difficulty 8 ...
//
// The listings come from many authors (so the store's per-author keys look
// like a real network), are spread over the area around a point, and are dated
// over the last ten days. Every description says the listing is invented.
//
// Proof-of-work is the expensive part of making a listing at the network's
// real difficulty; -mine-only measures it without storing anything.
package main
import (
"context"
"flag"
"fmt"
"math"
"math/rand/v2"
"os"
"path/filepath"
"runtime"
"strings"
"sync"
"time"
"git.stinnesbeck.com/nils/allmende/internal/identity"
"git.stinnesbeck.com/nils/allmende/internal/listing"
"git.stinnesbeck.com/nils/allmende/internal/places"
"git.stinnesbeck.com/nils/allmende/internal/store"
)
func main() {
data := flag.String("data", "", "data directory of a node made with 'allmende init' (its identity is not used; the database is filled)")
n := flag.Int("n", 100000, "listings to make")
difficulty := flag.Int("difficulty", 8, "proof-of-work bits; the node that serves them must use the same (the network's is "+fmt.Sprint(listing.DefaultDifficulty)+")")
authors := flag.Int("authors", 1000, "distinct authors to spread the listings over")
lat := flag.Float64("lat", 50.59, "centre latitude (default: Mechernich)")
lon := flag.Float64("lon", 6.65, "centre longitude")
spread := flag.Float64("spread-km", 25, "radius around the centre, in km")
workers := flag.Int("workers", runtime.NumCPU(), "parallel miners")
seed := flag.Uint64("seed", 1, "same seed, same listings")
mineOnly := flag.Bool("mine-only", false, "only make and sign the listings and report how long that took; store nothing")
countOnly := flag.Bool("count", false, "make nothing: print how many live listings --data holds in each region around the centre")
flag.Parse()
if *n <= 0 || *authors <= 0 || *workers <= 0 || (*data == "" && !*mineOnly) {
fmt.Fprintln(os.Stderr, "usage: allmende-load --data DIR [-n 100000] [-difficulty 8] [-authors 1000] [-lat 50.59 -lon 6.65 -spread-km 25] [-seed 1] [-mine-only | -count]")
os.Exit(2)
}
if *countOnly {
if err := count(*data, *difficulty, *lat, *lon, *spread); err != nil {
fmt.Fprintln(os.Stderr, "allmende-load:", err)
os.Exit(1)
}
return
}
if err := run(*data, *n, *difficulty, *authors, *lat, *lon, *spread, *workers, *seed, *mineOnly); err != nil {
fmt.Fprintln(os.Stderr, "allmende-load:", err)
os.Exit(1)
}
}
// count prints the live listings per region around the centre, which is what a
// node following those regions would hold and what a newcomer should receive.
func count(data string, difficulty int, lat, lon, spread float64) error {
st, err := store.Open(filepath.Join(data, "allmende.db"), store.Options{Difficulty: difficulty})
if err != nil {
return err
}
defer st.Close()
total := 0
for _, cell := range places.CellsNear(lat, lon, spread+10) {
d, err := st.ListingDigest(context.Background(), cell)
if err != nil {
return err
}
fmt.Printf("%s %d\n", cell, d.Count)
total += d.Count
}
fmt.Printf("total %d\n", total)
return nil
}
func run(data string, n, difficulty, authors int, lat, lon, spread float64, workers int, seed uint64, mineOnly bool) error {
now := time.Now()
// Devices certified 25 days ago, so listings dated up to 10 days back are
// inside the certificate's term and still live for another 10+ days.
devs := make([]*identity.Device, authors)
for i := range devs {
root, _, err := identity.NewRoot()
if err != nil {
return err
}
if devs[i], err = identity.Enroll(root, now.Add(-25*24*time.Hour), 90*24*time.Hour); err != nil {
return err
}
}
var st *store.Store
if !mineOnly {
var err error
st, err = store.Open(filepath.Join(data, "allmende.db"), store.Options{Difficulty: difficulty})
if err != nil {
return err
}
defer st.Close()
}
type job struct{ i int }
jobs := make(chan job)
made := make(chan *listing.Listing, workers*4)
var wg sync.WaitGroup
var mineErr error
var errOnce sync.Once
for w := 0; w < workers; w++ {
wg.Add(1)
go func() {
defer wg.Done()
for j := range jobs {
rng := rand.New(rand.NewPCG(seed, uint64(j.i)))
l, err := invent(rng, now, lat, lon, spread)
if err == nil {
err = l.Seal(devs[j.i%authors], difficulty)
}
if err != nil {
errOnce.Do(func() { mineErr = err })
return
}
made <- l
}
}()
}
go func() {
for i := 0; i < n; i++ {
jobs <- job{i}
}
close(jobs)
wg.Wait()
close(made)
}()
start := time.Now()
done, bytes := 0, 0
ctx := context.Background()
for l := range made {
if st != nil {
if _, err := st.Put(ctx, l); err != nil {
return fmt.Errorf("listing %d: %w", done, err)
}
}
if b, err := l.Bytes(); err == nil {
bytes += len(b)
}
done++
if done%5000 == 0 || done == n {
el := time.Since(start)
fmt.Printf("%7d / %d %6.0f listings/s %s\n", done, n, float64(done)/el.Seconds(), el.Round(time.Second))
}
}
if mineErr != nil {
return mineErr
}
el := time.Since(start)
fmt.Printf("\n%d listings, difficulty %d, %d workers: %s (%.1f ms of CPU each, %.0f listings/s)\n",
done, difficulty, workers, el.Round(time.Millisecond),
float64(workers)*el.Seconds()*1000/float64(done), float64(done)/el.Seconds())
fmt.Printf("average size on the wire: %d bytes\n", bytes/max(done, 1))
if st != nil {
if info, err := os.Stat(filepath.Join(data, "allmende.db")); err == nil {
fmt.Printf("database file: %.1f MB\n", float64(info.Size())/1e6)
}
}
return nil
}
var (
moods = []string{"Helle", "Ruhige", "Gepflegte", "Moderne", "Gemütliche", "Sanierte", "Geräumige", "Zentrale", "Sonnige", "Familienfreundliche"}
places_ = []string{"Mechernich", "Kommern", "Satzvey", "Vussem", "Strempt", "Lessenich", "Antweiler", "Bleibuir", "Firmenich", "Holzheim", "Kallmuth", "Eiserfey", "Weyer", "Harzheim", "Euskirchen", "Zülpich", "Bad Münstereifel", "Schleiden", "Kall", "Blankenheim"}
feats = []string{"Balkon", "Terrasse", "Garten", "Garage", "Stellplatz", "Keller", "Aufzug", "Einbauküche", "Fußbodenheizung", "Neubau", "Altbau", "Barrierefrei", "Haustiere erlaubt", "Photovoltaik", "Kamin", "Dachboden", "Gäste-WC"}
words = strings.Fields("Die Wohnung liegt ruhig und doch zentral, mit guter Anbindung an Bus und Bahn. Einkaufsmöglichkeiten, Schulen und Ärzte sind zu Fuß erreichbar. Der Grundriss ist durchdacht, die Räume sind hell und haben große Fenster. Böden aus Parkett oder Fliesen, Bad mit Dusche und Fenster, Küche gerne mit Möbeln. Der Keller bietet Platz für Fahrräder und Vorräte. Die Heizung wurde erneuert, die Nebenkosten sind gering. Besichtigung nach Absprache, Kaution nach Vereinbarung, kein Makler.")
nouns = map[string]string{"apartment": "Wohnung", "house": "Haus", "room": "Zimmer", "commercial": "Gewerbefläche"}
)
func between(r *rand.Rand, a, b int) int { return a + r.IntN(b-a+1) }
func invent(r *rand.Rand, now time.Time, lat0, lon0, spread float64) (*listing.Listing, error) {
id, err := listing.NewID()
if err != nil {
return nil, err
}
cat := []string{"apartment", "apartment", "apartment", "house", "house", "room", "commercial"}[r.IntN(7)]
kind := "rent"
if cat != "room" && r.IntN(10) < 3 {
kind = "sale"
}
area := map[string][2]int{"apartment": {30, 120}, "house": {90, 220}, "room": {10, 30}, "commercial": {30, 300}}[cat]
m2 := between(r, area[0], area[1])
euros := m2 * 10
if kind == "sale" {
euros = m2 * 2800
}
rad, ang := spread*math.Sqrt(r.Float64()), r.Float64()*2*math.Pi
lat := lat0 + rad*math.Cos(ang)/111
lon := lon0 + rad*math.Sin(ang)/(111*math.Cos(lat0*math.Pi/180))
var fs []string
for i := between(r, 0, 5); i > 0; i-- {
f := feats[r.IntN(len(feats))]
dup := false
for _, g := range fs {
dup = dup || g == f
}
if !dup {
fs = append(fs, f)
}
}
var d strings.Builder
for d.Len() < between(r, 150, 900) {
d.WriteString(words[r.IntN(len(words))])
d.WriteByte(' ')
}
d.WriteString("\n\nTestanzeige: erfunden, kein echtes Angebot.")
created := now.Add(-time.Duration(r.Int64N(int64(10*24*time.Hour))) - time.Minute)
period := "month"
if kind == "sale" {
period = "once"
}
return &listing.Listing{
Version: listing.Version, ID: id, Seq: 1,
CreatedAt: created.Unix(), ExpiresAt: created.Add(time.Duration(between(r, 20, 30)) * 24 * time.Hour).Unix(),
Kind: kind, Category: cat, Geohash: places.Encode(lat, lon, 6),
Price: &listing.Price{AmountCents: int64(euros) * 100, Currency: "EUR", Period: period},
AreaM2: m2, RoomsX2: between(r, 2, 8), Features: fs,
Title: fmt.Sprintf("%s %s in %s", moods[r.IntN(len(moods))], nouns[cat], places_[r.IntN(len(places_))]),
Description: d.String(),
}, nil
}
+21
View File
@@ -533,6 +533,27 @@ Proof-of-work per listing and per revocation, abuse reports (below), and
subscribable blocklists (not built yet). The format leaves room for vouching
signatures later.
**Mining** (`internal/pow`, `pow.Mine`): the nonce is the smallest number that
makes the canonical bytes hash to enough leading zero bits, so every miner that
tries 0, 1, 2, ... finds the same one. The node hashes the bytes before the
nonce once and, per attempt, only the number and what follows, on every core
but one. Measured on an 8-core machine under other load, mining one listing
takes about 19 ms at difficulty 16 (the default), 0.14 s at 20, 1.1 s at 22,
3.6 s at 24 and 15 s at 26: about 16 times longer per 4 bits. (Before this,
every attempt re-encoded the JSON and one listing at 16 took about 2 s.)
**What it can and cannot do.** The difficulty is a number of hashes, so it
prices the work the same for everyone, but hardware is not equal: an attacker
with an optimized miner or a GPU does what the node does in a fraction of the
time. A difficulty that takes an honest laptop 30 s (about 27 bits) takes a GPU
well under a second, and one that takes a GPU 30 s would take the laptop hours.
So proof-of-work stops casual bulk posting, not a determined spammer, and is
only one layer: it is paired with what a node does with the traffic it gets
(rate limits and peer scoring, the reports and the hide rule, later vouching
and blocklists). The difficulty is network-wide: nodes check it against their
own `--difficulty`, so changing the default needs every node to change, and a
node with a higher value refuses listings mined for a lower one.
## Abuse reports
Implemented in `internal/report` (the record), `internal/store/reports.go`
+28
View File
@@ -4,6 +4,8 @@ import (
"strings"
"testing"
"time"
"git.stinnesbeck.com/nils/allmende/internal/pow"
)
var testNow = time.Unix(1_800_000_000, 0)
@@ -103,6 +105,32 @@ func TestRevocation(t *testing.T) {
}
}
// The fast miner must keep finding what the old loop found.
func TestRevocationMiningFindsTheSmallestNonceThatTryingEachOneInOrderWouldFind(t *testing.T) {
root, _, _ := NewRoot()
dev, _ := Enroll(root, testNow, 24*time.Hour)
const bits = 11
r, err := Revoke(root, dev.Cert, testNow, bits)
if err != nil {
t.Fatal(err)
}
probe := *r
probe.Sig = ""
for n := uint64(0); ; n++ {
probe.PoW = n
b, err := probe.signingBytes()
if err != nil {
t.Fatal(err)
}
if pow.LeadingZeroBits(b) >= bits {
if n != r.PoW {
t.Fatalf("Revoke chose nonce %d, the smallest that works is %d", r.PoW, n)
}
return
}
}
}
func TestDeviceSaveLoad(t *testing.T) {
root, _, _ := NewRoot()
dev, _ := Enroll(root, testNow, 24*time.Hour)
+11 -4
View File
@@ -68,16 +68,23 @@ func RevokeAll(root *Identity, at time.Time, difficulty int) (*Revocation, error
}
func mineRevocation(root *Identity, r *Revocation, difficulty int) (*Revocation, error) {
for ; ; r.PoW++ {
r.Sig = ""
r.PoW = 0
b, err := r.signingBytes()
if err != nil {
return nil, err
}
if pow.LeadingZeroBits(b) >= difficulty {
if r.PoW, err = pow.Mine(b, difficulty, 1<<53-1); err != nil {
return nil, err
}
if b, err = r.signingBytes(); err != nil {
return nil, err
}
if pow.LeadingZeroBits(b) < difficulty { // cannot happen; a wrong miner must not sign
return nil, errors.New("identity: mined nonce does not meet the difficulty")
}
r.Sig = hex.EncodeToString(root.Sign(b))
return r, nil
}
}
}
// AllDevices reports whether r covers every earlier device of the author.
+14 -12
View File
@@ -150,22 +150,24 @@ func (l *Listing) Seal(dev *identity.Device, difficulty int) error {
l.Device = cert.Device
l.Cert = cert
l.Sig = ""
for l.PoW = 0; ; l.PoW++ {
if l.PoW > maxSafeInt {
return errors.New("listing: proof-of-work exhausted")
}
ok, err := l.powOK(difficulty)
if err != nil {
return err
}
if ok {
break
}
}
l.PoW = 0
b, err := l.unsignedBytes()
if err != nil {
return err
}
l.PoW, err = pow.Mine(b, difficulty, maxSafeInt)
if errors.Is(err, pow.ErrExhausted) {
return errors.New("listing: proof-of-work exhausted")
}
if err != nil {
return err
}
if b, err = l.unsignedBytes(); err != nil {
return err
}
if pow.LeadingZeroBits(b) < difficulty { // cannot happen; a wrong miner must not sign
return errors.New("listing: mined nonce does not meet the difficulty")
}
l.Sig = hex.EncodeToString(dev.Key.Sign(append([]byte(listingContext), b...)))
return nil
}
+21
View File
@@ -69,6 +69,27 @@ func TestSealCheckRoundTrip(t *testing.T) {
}
}
// The fast miner must keep finding what the old loop found, or every golden
// fixture and every signed record in the wild would change.
func TestSealFindsTheSmallestNonceThatTryingEachOneInOrderWouldFind(t *testing.T) {
l, _ := sealed(t)
probe := *l
probe.Sig = ""
for n := uint64(0); ; n++ {
probe.PoW = n
ok, err := probe.powOK(testDifficulty)
if err != nil {
t.Fatal(err)
}
if ok {
if n != l.PoW {
t.Fatalf("Seal chose nonce %d, the smallest that works is %d", l.PoW, n)
}
return
}
}
}
func TestCanonicalBytesDeterministic(t *testing.T) {
l, _ := sealed(t)
a, _ := l.Bytes()
+12 -8
View File
@@ -111,18 +111,22 @@ func (e *Envelope) Work() (int, error) {
}
func (e *Envelope) mine(difficulty int) error {
for e.PoW = 0; ; e.PoW++ {
if e.PoW > maxSafeInt {
return errors.New("message: proof-of-work exhausted")
}
ok, err := e.powOK(difficulty)
e.PoW = 0
b, err := e.Bytes()
if err != nil {
return err
}
if ok {
e.PoW, err = pow.Mine(b, difficulty, maxSafeInt)
if errors.Is(err, pow.ErrExhausted) {
return errors.New("message: proof-of-work exhausted")
}
if err != nil {
return err
}
if ok, err := e.powOK(difficulty); err != nil || !ok { // cannot happen; a wrong miner must not send
return errors.New("message: mined nonce does not meet the difficulty")
}
return nil
}
}
}
// Check validates a received envelope as a relay can: structure, size,
+22
View File
@@ -95,6 +95,28 @@ func TestBuyerToOwnerRoundTrip(t *testing.T) {
}
}
// The fast miner must keep finding what the old loop found.
func TestMiningFindsTheSmallestNonceThatTryingEachOneInOrderWouldFind(t *testing.T) {
e, err := SealToOwner(newOwner(t).l, thread(t), hello("Hallo"), now, testDifficulty)
if err != nil {
t.Fatal(err)
}
probe := *e
for n := uint64(0); ; n++ {
probe.PoW = n
ok, err := probe.powOK(testDifficulty)
if err != nil {
t.Fatal(err)
}
if ok {
if n != e.PoW {
t.Fatalf("mining chose nonce %d, the smallest that works is %d", e.PoW, n)
}
return
}
}
}
func TestOwnerReplyAndGrantRoundTrip(t *testing.T) {
o := newOwner(t)
tk := thread(t)
+166
View File
@@ -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
}
+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)
}
}
})
}
}
+4
View File
@@ -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 {
+14 -7
View File
@@ -107,19 +107,26 @@ func (r *Report) Seal(dev *identity.Device, difficulty int) error {
r.Device = cert.Device
r.Cert = cert
r.Sig = ""
for r.PoW = 0; ; r.PoW++ {
if r.PoW > maxSafeInt {
return errors.New("report: proof-of-work exhausted")
}
r.PoW = 0
b, err := r.unsignedBytes()
if err != nil {
return err
}
if pow.LeadingZeroBits(b) >= difficulty {
r.PoW, err = pow.Mine(b, difficulty, maxSafeInt)
if errors.Is(err, pow.ErrExhausted) {
return errors.New("report: proof-of-work exhausted")
}
if err != nil {
return err
}
if b, err = r.unsignedBytes(); err != nil {
return err
}
if pow.LeadingZeroBits(b) < difficulty { // cannot happen; a wrong miner must not sign
return errors.New("report: mined nonce does not meet the difficulty")
}
r.Sig = hex.EncodeToString(dev.Key.Sign(append([]byte(reportContext), b...)))
return nil
}
}
}
// Check validates a received report: structure, size, certificate,
+21
View File
@@ -7,6 +7,7 @@ import (
"time"
"git.stinnesbeck.com/nils/allmende/internal/identity"
"git.stinnesbeck.com/nils/allmende/internal/pow"
)
const difficulty = 6
@@ -41,6 +42,26 @@ func sealed(t *testing.T, dev *identity.Device, mutate func(*Report)) *Report {
return r
}
// The fast miner must keep finding what the old loop found.
func TestSealFindsTheSmallestNonceThatTryingEachOneInOrderWouldFind(t *testing.T) {
r := sealed(t, device(t), nil)
probe := *r
probe.Sig = ""
for n := uint64(0); ; n++ {
probe.PoW = n
b, err := probe.unsignedBytes()
if err != nil {
t.Fatal(err)
}
if pow.LeadingZeroBits(b) >= difficulty {
if n != r.PoW {
t.Fatalf("Seal chose nonce %d, the smallest that works is %d", r.PoW, n)
}
return
}
}
}
func TestASealedReportChecks(t *testing.T) {
r := sealed(t, device(t), nil)
if err := r.Check(t0, difficulty); err != nil {