Files
nilsandClaude Sonnet 5.5 52a6d87553 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
2026-11-19 00:15:52 +01:00

250 lines
7.2 KiB
Go

// Package report is the signed abuse report: one node operator saying, in a
// way anyone can verify, that a listing looks like a scam, is illegal, sits in
// the wrong category, or something else.
//
// A report decides nothing by itself. Every node chooses whose reports it
// counts (see internal/store), and a listing that enough trusted reporters
// flag is hidden on that node only, behind a notice, never deleted.
package report
import (
"crypto/sha256"
"encoding/hex"
"errors"
"fmt"
"time"
"unicode"
"unicode/utf8"
"git.stinnesbeck.com/nils/allmende/internal/identity"
"git.stinnesbeck.com/nils/allmende/internal/jcs"
"git.stinnesbeck.com/nils/allmende/internal/pow"
)
const (
// Version of the wire format.
Version = 1
// MaxLifetime is how long a report counts. A listing lives at most as
// long, and a hide that is not renewed lapses with it.
MaxLifetime = 30 * 24 * time.Hour
// MaxClockSkew is how far in the future a report may be dated.
MaxClockSkew = 10 * time.Minute
// MaxSize bounds the canonical encoding.
MaxSize = 4096
// MaxNote is the longest note, in bytes.
MaxNote = 300
reportContext = "allmende-report-v1\n"
maxSafeInt = 1<<53 - 1
)
// Categories. Only Scam and Illegal can hide a listing; Category and Other
// are labels that operators see.
const (
Scam = "scam"
Illegal = "illegal"
Category = "category" // listed in the wrong category or kind
Other = "other"
Withdrawn = "withdrawn" // replaces an earlier report by the same reporter: it is taken back
)
var categories = map[string]bool{Scam: true, Illegal: true, Category: true, Other: true, Withdrawn: true}
// ValidCategory reports whether c is a report category.
func ValidCategory(c string) bool { return categories[c] }
// ErrTimeWindow marks failures caused by the clock, which are not the
// sender's fault.
var ErrTimeWindow = errors.New("outside time window")
// Ref names the listing a report is about.
type Ref struct {
Author string `json:"author"`
ID string `json:"id"`
}
// Report is one signed report. A reporter has at most one per listing: a
// newer one replaces the older (withdrawing is a newer report).
type Report struct {
Version int `json:"v"`
Listing Ref `json:"listing"`
Category string `json:"category"`
Note string `json:"note,omitempty"`
CreatedAt int64 `json:"created_at"`
ExpiresAt int64 `json:"expires_at"`
// Reporter is the identity key of the node operator who signed.
Reporter string `json:"reporter"`
Device string `json:"device"`
Cert *identity.Cert `json:"cert"`
PoW uint64 `json:"pow"`
Sig string `json:"sig,omitempty"`
}
func (r *Report) unsignedBytes() ([]byte, error) {
c := *r
c.Sig = ""
return jcs.Marshal(&c)
}
// Bytes returns the canonical encoding.
func (r *Report) Bytes() ([]byte, error) { return jcs.Marshal(r) }
// Hash identifies this exact report (including its signature).
func (r *Report) Hash() (string, error) {
b, err := r.Bytes()
if err != nil {
return "", err
}
sum := sha256.Sum256(b)
return hex.EncodeToString(sum[:]), nil
}
// Seal fills in the reporter from dev, mines the proof-of-work and signs.
func (r *Report) Seal(dev *identity.Device, difficulty int) error {
r.Version = Version
cert := dev.Current()
r.Reporter = cert.Author
r.Device = cert.Device
r.Cert = cert
r.Sig = ""
r.PoW = 0
b, err := r.unsignedBytes()
if err != nil {
return err
}
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,
// signature and proof-of-work.
func (r *Report) Check(now time.Time, difficulty int) error {
if err := r.validate(now); err != nil {
return err
}
full, err := r.Bytes()
if err != nil {
return err
}
if len(full) > MaxSize {
return fmt.Errorf("report: %d bytes exceeds limit of %d", len(full), MaxSize)
}
unsigned, err := r.unsignedBytes()
if err != nil {
return err
}
sig, err := hex.DecodeString(r.Sig)
if err != nil || len(sig) != 64 {
return errors.New("report: malformed signature")
}
if !identity.Verify(r.Device, append([]byte(reportContext), unsigned...), sig) {
return errors.New("report: bad signature")
}
if pow.LeadingZeroBits(unsigned) < difficulty {
return errors.New("report: insufficient proof-of-work")
}
return nil
}
func (r *Report) validate(now time.Time) error {
if r.Version != Version {
return fmt.Errorf("report: unsupported version %d", r.Version)
}
if !isHex(r.Listing.Author, 64) || !isHex(r.Listing.ID, 32) {
return errors.New("report: listing must name a 64-hex author and a 32-hex id")
}
if !categories[r.Category] {
return fmt.Errorf("report: invalid category %q", r.Category)
}
if err := validNote(r.Note); err != nil {
return fmt.Errorf("report: note: %w", err)
}
if !isHex(r.Reporter, 64) || !isHex(r.Device, 64) {
return errors.New("report: reporter and device must be 64 hex characters")
}
if r.Cert == nil {
return errors.New("report: certificate required")
}
if err := r.Cert.Check(); err != nil {
return fmt.Errorf("report: %w", err)
}
if r.Cert.Author != r.Reporter || r.Cert.Device != r.Device {
return errors.New("report: certificate does not match reporter and device")
}
if !r.Cert.Covers(r.CreatedAt) {
return errors.New("report: created outside the certificate's validity")
}
if now.Unix() >= r.Cert.ExpiresAt {
return fmt.Errorf("report: certificate expired: %w", ErrTimeWindow)
}
if r.PoW > maxSafeInt {
return errors.New("report: number out of range")
}
if r.ExpiresAt <= r.CreatedAt {
return errors.New("report: expires_at must be after created_at")
}
if time.Duration(r.ExpiresAt-r.CreatedAt)*time.Second > MaxLifetime {
return errors.New("report: lifetime exceeds 30 days")
}
if time.Unix(r.CreatedAt, 0).After(now.Add(MaxClockSkew)) {
return fmt.Errorf("report: created_at is in the future: %w", ErrTimeWindow)
}
if !time.Unix(r.ExpiresAt, 0).After(now) {
return fmt.Errorf("report: expired: %w", ErrTimeWindow)
}
return nil
}
// Supersedes reports whether r should replace other, a report by the same
// reporter about the same listing: the newer wins, the smaller hash on a tie,
// so every node converges whatever order they arrive in.
func (r *Report) Supersedes(other *Report) bool {
if r.CreatedAt != other.CreatedAt {
return r.CreatedAt > other.CreatedAt
}
a, _ := r.Hash()
b, _ := other.Hash()
return a < b
}
func validNote(s string) error {
if len(s) > MaxNote {
return fmt.Errorf("longer than %d bytes", MaxNote)
}
if !utf8.ValidString(s) {
return errors.New("invalid UTF-8")
}
for _, c := range s {
if unicode.IsControl(c) {
return errors.New("control characters not allowed")
}
}
return nil
}
func isHex(s string, n int) bool {
if len(s) != n {
return false
}
for i := 0; i < len(s); i++ {
c := s[i]
if !(c >= '0' && c <= '9' || c >= 'a' && c <= 'f') {
return false
}
}
return true
}