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:
+14
-12
@@ -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
|
||||
}
|
||||
|
||||
@@ -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()
|
||||
|
||||
Reference in New Issue
Block a user