abuse reports: signed reports, gossip and sync, a local hide rule, visitor tips

A report is signed by a node operator (device key and certificate) and
gossiped on one global topic. Each node decides whose reports count: the
operator's own report hides a listing on that node, one trusted report of
illegal content hides it, and --hide-after trusted scam reports hide it
(--trust-reporter names others). Hidden listings stay stored and reachable.
Visitors can tip the node's operator off with a proof-of-work request that
hides nothing.

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-18 21:18:43 +01:00
co-authored by Claude Sonnet 5.5
parent 253eb6e75c
commit 6d55222ac5
17 changed files with 1854 additions and 13 deletions
+14
View File
@@ -58,7 +58,20 @@ func cmdRun(args []string) error {
"proof-of-work bits for messages; must match the rest of the network")
maxNewThreads := fs.Int("max-new-threads", inbox.DefaultMaxNewThreads,
"how many new conversations each of your listings can start per day")
var trustReporters listFlag
fs.Var(&trustReporters, "trust-reporter",
"identity key (64 hex) of a node operator whose abuse reports count here; repeatable. Your own reports always hide a listing on your node")
hideAfter := fs.Int("hide-after", store.DefaultHideThreshold,
"how many trusted operators must report a listing as a scam before your node hides it (one report of illegal content is enough)")
fs.Parse(args)
for _, k := range trustReporters {
if !validKey(k) {
return fmt.Errorf("--trust-reporter %q: want an identity key of 64 hex characters (the \"author\" in a node's /api/v1/status)", k)
}
}
if *hideAfter < 1 {
return errors.New("--hide-after must be at least 1")
}
// Place names become region codes; say what each one turned into.
codes, notes, err := resolveRegions(regions, func() ([]places.Place, error) { return places.Load(web.Files()) })
@@ -112,6 +125,7 @@ func cmdRun(args []string) error {
st, err := store.Open(filepath.Join(*data, dbFile), store.Options{
Difficulty: *difficulty, MessageDifficulty: *msgDifficulty,
Trust: store.Trust{Self: dev.Cert.Author, Reporters: trustReporters, Threshold: *hideAfter},
})
if err != nil {
return err
+16
View File
@@ -0,0 +1,16 @@
package main
// validKey reports whether s is an identity key as shown by a node: 64
// lowercase hex characters.
func validKey(s string) bool {
if len(s) != 64 {
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
}
+25
View File
@@ -0,0 +1,25 @@
package main
import (
"strings"
"testing"
)
func TestValidKey(t *testing.T) {
good := strings.Repeat("ab", 32)
if !validKey(good) {
t.Fatal("a 64-hex key was refused")
}
for name, k := range map[string]string{
"empty": "",
"short": good[:63],
"long": good + "a",
"uppercase": strings.ToUpper(good),
"not hex": strings.Repeat("zz", 32),
"a peer id": "12D3KooWNdEEecKvunKaTxsXd9W57cvaNeSndCACiXyDKBzkgZMQ",
} {
if validKey(k) {
t.Errorf("%s was accepted", name)
}
}
}
+69 -4
View File
@@ -516,13 +516,78 @@ the peers it has met in `peers.json` next to its keys.
## Spam
Proof-of-work per listing and per revocation, plus subscribable blocklists
(not built yet). The format leaves room for vouching signatures later.
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.
## Abuse reports
Implemented in `internal/report` (the record), `internal/store/reports.go`
(storage and the hide rule) and `internal/api/reports.go`. A report is
**information, not a verdict**: no report removes anything from the network.
Each node decides whose reports count, and what a listing that enough trusted
reporters flagged looks like *on that node*: hidden from search, behind a
notice, still stored and still reachable by its link.
**The record.** Canonical JSON, at most 4 KB, signed like a listing (device
key plus the certificate that chains to the reporter's identity key, and
proof-of-work at the listing difficulty): `listing {author, id}`, `category`
(`scam`, `illegal`, `category`, `other` or `withdrawn`), `note` (at most 300
bytes, no control characters), `created_at`, `expires_at` (at most 30 days
later, so a hide lapses unless it is renewed), `reporter`, `device`, `cert`,
`pow`, `sig`. A reporter has **one report per listing**: a newer one replaces
the older (the smaller hash on a tie), and `withdrawn` takes a report back.
Reports of a revoked device are dropped, and none are accepted from it.
**Network.** Reports travel on one global topic, `/allmende/1/reports`
(they are few, and every node may want them), validated like revocations:
canonical form, signature, proof-of-work, certificate; a clock mismatch or a
revoked device is ignored without penalty. Sync adds a `reports` digest to the
`digest` reply and a `reports` kind that returns the live reports (up to
5000); so a node that was offline catches up, and anti-entropy repairs the
rest.
**Who counts (the hide rule).** Local, in `store.Trust`:
- the **node's own operator** (`Self`): one report as `scam` or `illegal`
hides the listing on this node at once;
- **one** report of `illegal` from any trusted reporter hides it;
- `--hide-after N` (default 2) distinct trusted reporters flagging `scam` or
`illegal` hide it;
- trusted reporters are the operator and the keys given with
`--trust-reporter <identity key>` (repeatable; a node shows its key as
`author` in `/api/v1/status`);
- reports from anyone else are kept, shown as a count, and **never** counted;
- `category` and `other` only label.
A hidden listing is left out of search unless `?hidden=1`; its own page
(`#/l/<author>/<id>`) shows who flagged it.
**What visitors can do.** A visitor has no key, so they cannot sign. On a
listing page they can *tip off* the node they are using: `POST
/api/v1/signals` with category, note and proof-of-work at the message
difficulty (a canonical JSON body; the browser mines it as it does for
messages). The node keeps it **only for its operator** (a signal is not
gossiped, hides nothing, is limited per listing and overall, expires after 30
days, and sending the same one twice adds nothing). The operator sees the tips
(`GET /api/v1/signals`, strongest first) and may sign a report of their own
(`POST /api/v1/reports`), which also clears the tips about that listing, or
dismiss them (`DELETE /api/v1/signals/{author}/{id}`). So harassing a seller
with many tips costs work and changes nothing unless the operator agrees.
**HTTP.** Public: `GET /api/v1/reports?author=&id=` (what this node makes of
the reports: `hidden`, `trusted` counts per category, `others`, `signals`,
`own`), `POST /api/v1/signals`, and `GET /api/v1/listings?hidden=1`. Operator
(admin token): `GET /api/v1/signals`, `DELETE /api/v1/signals/{author}/{id}`,
`POST /api/v1/reports` (`{listing, category, note}`).
**Not built yet:** vouching (who becomes trusted is the operator's choice for
now), signed blocklists you subscribe to by curator key, an owner's signed
reply to a report, and reputation for reporters whose reports are overruled.
## Open
Abuse reporting for messages, reciprocity rules, anti-
discrimination (AGG) content rules, blocklists, peer scoring and rate limits,
Abuse reporting for messages (reports cover listings only so far), vouching
and blocklists for reports, reciprocity rules, anti-
discrimination (AGG) content rules, peer scoring and rate limits,
a fallback bootstrap list inside the binary
for networks that block DNS, image hosting,
recovering listings onto a fresh machine with an empty database, a helper to
+9 -1
View File
@@ -120,6 +120,14 @@ func New(cfg Config) http.Handler {
mux.HandleFunc("GET /api/v1/listings/{id}/address", s.admin(s.getAddress))
mux.HandleFunc("DELETE /api/v1/listings/{id}/address", s.admin(s.deleteAddress))
}
// Abuse reports: anyone can read what this node makes of a listing's
// reports and tip the operator off (proof-of-work, no account); the
// operator reads the tips and signs reports.
mux.HandleFunc("GET /api/v1/reports", s.getReports)
mux.HandleFunc("POST /api/v1/signals", s.postSignal)
mux.HandleFunc("GET /api/v1/signals", s.admin(s.listSignals))
mux.HandleFunc("DELETE /api/v1/signals/{author}/{id}", s.admin(s.dismissSignals))
mux.HandleFunc("POST /api/v1/reports", s.admin(s.postReport))
mux.Handle("GET /", s.ui())
return secure(mux)
}
@@ -175,7 +183,7 @@ func (s *server) status(w http.ResponseWriter, r *http.Request) {
func (s *server) search(w http.ResponseWriter, r *http.Request) {
q := r.URL.Query()
query := store.Query{Kind: q.Get("kind"), Category: q.Get("category")}
query := store.Query{Kind: q.Get("kind"), Category: q.Get("category"), IncludeHidden: q.Get("hidden") == "1"}
if g := q.Get("geohash"); g != "" {
for _, p := range strings.Split(g, ",") {
+4 -1
View File
@@ -40,7 +40,10 @@ func newFixture(t *testing.T, tok string, tweak ...func(*Config)) *fixture {
if err != nil {
t.Fatal(err)
}
s, err := store.Open(":memory:", store.Options{Difficulty: difficulty, MessageDifficulty: msgDifficulty})
s, err := store.Open(":memory:", store.Options{
Difficulty: difficulty, MessageDifficulty: msgDifficulty,
Trust: store.Trust{Self: dev.Cert.Author}, // the operator's own reports hide on this node
})
if err != nil {
t.Fatal(err)
}
+227
View File
@@ -0,0 +1,227 @@
package api
import (
"bytes"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
"io"
"net/http"
"strings"
"time"
"git.stinnesbeck.com/nils/allmende/internal/jcs"
"git.stinnesbeck.com/nils/allmende/internal/pow"
"git.stinnesbeck.com/nils/allmende/internal/report"
"git.stinnesbeck.com/nils/allmende/internal/store"
)
// --- public ------------------------------------------------------------------
// getReports tells what this node makes of the reports about a listing: the
// counts, and whether its own rules hide it. Reports decide nothing for other
// nodes, so this is one node's view.
func (s *server) getReports(w http.ResponseWriter, r *http.Request) {
author, id := r.URL.Query().Get("author"), r.URL.Query().Get("id")
if len(author) != 64 || !isLowerHex(author) || len(id) != 32 || !isLowerHex(id) {
fail(w, http.StatusBadRequest, "author must be 64 and id 32 hex characters")
return
}
sum, err := s.Store.Summary(r.Context(), author, id)
if err != nil {
fail(w, http.StatusInternalServerError, "internal error")
return
}
w.Header().Set("Access-Control-Allow-Origin", "*")
noStore(w)
writeJSON(w, http.StatusOK, sum)
}
// signalRequest is what a visitor's browser sends to tip the operator off. It
// is not signed (a visitor has no key), only backed by proof-of-work: the
// SHA-256 of its canonical encoding has leading zero bits, as with messages.
// Field order matters only for the canonical form: pow sorts before v, and the
// browser mines the same bytes.
type signalRequest struct {
Category string `json:"category"`
CreatedAt int64 `json:"created_at"`
Listing struct {
Author string `json:"author"`
ID string `json:"id"`
} `json:"listing"`
Note string `json:"note"`
PoW uint64 `json:"pow"`
Version int `json:"v"`
}
// postSignal records a visitor's tip. Tips stay on this node: they hide
// nothing and are not gossiped; the operator reads them and may sign a report.
func (s *server) postSignal(w http.ResponseWriter, r *http.Request) {
if !s.limiter.allow(clientIP(r)) {
w.Header().Set("Retry-After", "60")
fail(w, http.StatusTooManyRequests, "too many requests from this address; try again in a minute")
return
}
body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, 2048))
if err != nil {
fail(w, http.StatusRequestEntityTooLarge, "request too large")
return
}
var q signalRequest
dec := json.NewDecoder(bytes.NewReader(body))
dec.DisallowUnknownFields()
if err := dec.Decode(&q); err != nil {
fail(w, http.StatusBadRequest, "invalid JSON body")
return
}
canon, err := jcs.Marshal(&q)
if err != nil || !bytes.Equal(canon, body) {
fail(w, http.StatusBadRequest, "the request must be in canonical JSON form")
return
}
probe := report.Report{Version: report.Version, Listing: report.Ref{Author: q.Listing.Author, ID: q.Listing.ID}, Category: q.Category, Note: q.Note}
switch {
case q.Version != report.Version:
fail(w, http.StatusBadRequest, "unsupported version")
return
case !report.ValidCategory(q.Category) || q.Category == report.Withdrawn:
fail(w, http.StatusBadRequest, "unknown category")
return
case len(q.Listing.Author) != 64 || !isLowerHex(q.Listing.Author) || len(q.Listing.ID) != 32 || !isLowerHex(q.Listing.ID):
fail(w, http.StatusBadRequest, "listing must name a 64-hex author and a 32-hex id")
return
case len(q.Note) > report.MaxNote || !validTipNote(probe.Note):
fail(w, http.StatusBadRequest, "the note is too long or has control characters")
return
}
now := s.Clock()
if d := time.Unix(q.CreatedAt, 0).Sub(now); d > report.MaxClockSkew || d < -report.MaxClockSkew {
fail(w, http.StatusBadRequest, "created_at is too far from this node's clock")
return
}
work := pow.LeadingZeroBits(canon)
if work < s.MessageDifficulty {
fail(w, http.StatusBadRequest, "not enough proof-of-work")
return
}
if _, err := s.Store.Region(r.Context(), q.Listing.Author, q.Listing.ID); errors.Is(err, store.ErrNotFound) {
fail(w, http.StatusNotFound, "this node does not know that listing")
return
} else if err != nil {
fail(w, http.StatusInternalServerError, "internal error")
return
}
sum := sha256.Sum256(canon)
err = s.Store.AddSignal(r.Context(), store.Signal{
Hash: hex.EncodeToString(sum[:]), Author: q.Listing.Author, ListingID: q.Listing.ID,
Category: q.Category, Note: q.Note, Work: work,
})
if err != nil {
fail(w, http.StatusInternalServerError, "internal error")
return
}
w.WriteHeader(http.StatusAccepted)
}
func validTipNote(s string) bool {
for _, c := range s {
if c < 0x20 || c == 0x7f {
return false
}
}
return true
}
// --- the operator (admin token) ---------------------------------------------
type signalView struct {
store.Signal
Title string `json:"title,omitempty"`
}
// listSignals is the operator's queue of visitor tips, strongest first.
func (s *server) listSignals(w http.ResponseWriter, r *http.Request) {
tips, err := s.Store.Signals(r.Context())
if err != nil {
fail(w, http.StatusInternalServerError, "internal error")
return
}
out := make([]signalView, 0, len(tips))
for _, g := range tips {
v := signalView{Signal: g}
if l, err := s.Store.Get(r.Context(), g.Author, g.ListingID); err == nil {
v.Title = l.Title
}
out = append(out, v)
}
noStore(w)
writeJSON(w, http.StatusOK, out)
}
// dismissSignals throws away the tips about one listing.
func (s *server) dismissSignals(w http.ResponseWriter, r *http.Request) {
author, id := r.PathValue("author"), r.PathValue("id")
if len(author) != 64 || !isLowerHex(author) || len(id) != 32 || !isLowerHex(id) {
fail(w, http.StatusBadRequest, "malformed listing")
return
}
if _, err := s.Store.DeleteSignals(r.Context(), author, id); err != nil {
fail(w, http.StatusInternalServerError, "internal error")
return
}
w.WriteHeader(http.StatusNoContent)
}
type reportBody struct {
Listing struct {
Author string `json:"author"`
ID string `json:"id"`
} `json:"listing"`
Category string `json:"category"`
Note string `json:"note"`
}
// postReport signs a report as this node's operator and gossips it. The
// operator's own report hides the listing on this node at once; others
// count it only if they trust this operator. Category "withdrawn" takes an
// earlier report back. The tips about the listing are cleared.
func (s *server) postReport(w http.ResponseWriter, r *http.Request) {
var b reportBody
if !decodeBody(w, r, &b) {
return
}
now := s.Clock()
rep := &report.Report{
Listing: report.Ref{Author: b.Listing.Author, ID: b.Listing.ID},
Category: b.Category,
Note: b.Note,
CreatedAt: now.Unix(),
ExpiresAt: now.Add(report.MaxLifetime).Unix(),
}
if err := rep.Seal(s.Device, s.Difficulty); err != nil {
fail(w, http.StatusInternalServerError, "internal error")
return
}
if err := s.Node.PublishReport(r.Context(), rep); err != nil {
switch {
case errors.Is(err, store.ErrInvalid):
fail(w, http.StatusBadRequest, strings.TrimPrefix(err.Error(), store.ErrInvalid.Error()+": "))
case errors.Is(err, store.ErrRevoked):
fail(w, http.StatusConflict, "this node's device has been revoked; run 'allmende recover'")
default:
fail(w, http.StatusInternalServerError, "internal error")
}
return
}
if _, err := s.Store.DeleteSignals(r.Context(), b.Listing.Author, b.Listing.ID); err != nil {
fail(w, http.StatusInternalServerError, "internal error")
return
}
sum, err := s.Store.Summary(r.Context(), b.Listing.Author, b.Listing.ID)
if err != nil {
fail(w, http.StatusInternalServerError, "internal error")
return
}
writeJSON(w, http.StatusOK, sum)
}
+182
View File
@@ -0,0 +1,182 @@
package api
import (
"encoding/json"
"strings"
"testing"
"time"
"git.stinnesbeck.com/nils/allmende/internal/jcs"
"git.stinnesbeck.com/nils/allmende/internal/listing"
"git.stinnesbeck.com/nils/allmende/internal/pow"
"git.stinnesbeck.com/nils/allmende/internal/report"
"git.stinnesbeck.com/nils/allmende/internal/store"
)
func (f *fixture) found(t *testing.T, query string) int {
t.Helper()
code, body := f.do(t, "GET", "/api/v1/listings"+query, "", false)
var ls []json.RawMessage
if code != 200 || json.Unmarshal(body, &ls) != nil {
t.Fatalf("search: %d %s", code, body)
}
return len(ls)
}
func (f *fixture) summary(t *testing.T, l *listing.Listing) store.ReportSummary {
t.Helper()
code, body := f.do(t, "GET", "/api/v1/reports?author="+l.Author+"&id="+l.ID, "", false)
var s store.ReportSummary
if code != 200 || json.Unmarshal(body, &s) != nil {
t.Fatalf("summary: %d %s", code, body)
}
return s
}
func reportJSON(l *listing.Listing, category, note string) string {
b, _ := json.Marshal(map[string]any{
"listing": map[string]string{"author": l.Author, "id": l.ID}, "category": category, "note": note,
})
return string(b)
}
func TestTheOperatorReportsAListingAndItDisappearsFromSearchButNotFromItsLink(t *testing.T) {
f := newFixture(t, token)
l := f.publish(t)
if f.found(t, "") != 1 {
t.Fatal("the listing is not found before the report")
}
if code, _ := f.do(t, "POST", "/api/v1/reports", reportJSON(l, report.Scam, "Vorkasse"), false); code != 401 {
t.Fatalf("reporting without the token: %d", code)
}
if code, body := f.do(t, "POST", "/api/v1/reports", reportJSON(l, "spam", ""), true); code != 400 {
t.Fatalf("an unknown category: %d %s", code, body)
}
code, body := f.do(t, "POST", "/api/v1/reports", reportJSON(l, report.Scam, "Vorkasse"), true)
var sum store.ReportSummary
if code != 200 || json.Unmarshal(body, &sum) != nil || !sum.Hidden || sum.Own != report.Scam {
t.Fatalf("report: %d %s", code, body)
}
if f.found(t, "") != 0 {
t.Fatal("a hidden listing still shows up in search")
}
if f.found(t, "?hidden=1") != 1 {
t.Fatal("hidden=1 must still list it")
}
if code, _ := f.do(t, "GET", "/api/v1/listings/"+l.Author+"/"+l.ID, "", false); code != 200 {
t.Fatalf("a hidden listing must stay reachable by its link: %d", code)
}
if s := f.summary(t, l); !s.Hidden || s.Trusted[report.Scam] != 1 {
t.Fatalf("summary: %+v", s)
}
// Taking the report back makes it visible again.
time.Sleep(1100 * time.Millisecond) // a newer report needs a later second
if code, body := f.do(t, "POST", "/api/v1/reports", reportJSON(l, report.Withdrawn, ""), true); code != 200 {
t.Fatalf("withdraw: %d %s", code, body)
}
if f.found(t, "") != 1 || f.summary(t, l).Hidden {
t.Fatal("a withdrawn report still hides the listing")
}
}
func TestReportSummaryNeedsAWellFormedListing(t *testing.T) {
f := newFixture(t, token)
if code, _ := f.do(t, "GET", "/api/v1/reports?author=zz&id=1", "", false); code != 400 {
t.Fatalf("bad parameters: %d", code)
}
}
// tip is what a visitor's browser sends. With enough = false it has too little
// proof-of-work to count.
func tip(t *testing.T, l *listing.Listing, category, note string, enough bool) string {
t.Helper()
q := signalRequest{Category: category, CreatedAt: time.Now().Unix(), Note: note, Version: 1}
q.Listing.Author, q.Listing.ID = l.Author, l.ID
for ; ; q.PoW++ {
b, err := jcs.Marshal(&q)
if err != nil {
t.Fatal(err)
}
if (pow.LeadingZeroBits(b) >= msgDifficulty) == enough {
return string(b)
}
}
}
// postTo sends a request body without a token and returns the status.
func (f *fixture) postTo(t *testing.T, path, body string) int {
t.Helper()
code, _ := f.do(t, "POST", path, body, false)
return code
}
func TestVisitorsCanTipOffTheOperatorWithoutHidingAnything(t *testing.T) {
f := newFixture(t, token)
l := f.publish(t)
post := func(body string) int { return f.postTo(t, "/api/v1/signals", body) }
good := tip(t, l, report.Scam, "Will Vorkasse nach Spanien", true)
if code := post(good); code != 202 {
t.Fatalf("a tip: %d", code)
}
if code := post(good); code != 202 {
t.Fatalf("the same tip again: %d", code)
}
if f.found(t, "") != 1 || f.summary(t, l).Hidden {
t.Fatal("a tip must never hide a listing")
}
if s := f.summary(t, l); s.Signals != 1 {
t.Fatalf("a tip sent twice counts %d times, want once", s.Signals)
}
// Only the operator reads them.
if code, _ := f.do(t, "GET", "/api/v1/signals", "", false); code != 401 {
t.Fatalf("reading tips without the token: %d", code)
}
var tips []struct {
store.Signal
Title string `json:"title"`
}
code, body := f.do(t, "GET", "/api/v1/signals", "", true)
if code != 200 || json.Unmarshal(body, &tips) != nil || len(tips) != 1 ||
tips[0].Category != report.Scam || tips[0].Title != l.Title || tips[0].Note != "Will Vorkasse nach Spanien" {
t.Fatalf("tips: %d %s", code, body)
}
for name, c := range map[string]struct {
body string
want int
}{
"too little work": {tip(t, l, report.Scam, "x", false), 400},
"unknown category": {tip(t, l, "spam", "x", true), 400},
"withdrawn": {tip(t, l, report.Withdrawn, "x", true), 400},
"a note with controls": {tip(t, l, report.Scam, "a\x01b", true), 400},
"a note too long": {tip(t, l, report.Scam, strings.Repeat("a", report.MaxNote+1), true), 400},
"not canonical": {" " + good, 400},
"not JSON": {"hallo", 400},
} {
if got := post(c.body); got != c.want {
t.Errorf("%s: %d, want %d", name, got, c.want)
}
}
stranger := *l
stranger.ID = strings.Repeat("0", 32)
if code := post(tip(t, &stranger, report.Scam, "x", true)); code != 404 {
t.Fatalf("a listing this node does not know: %d", code)
}
// The operator dismisses them, or turns them into a report (which clears them).
if code, _ := f.do(t, "DELETE", "/api/v1/signals/"+l.Author+"/"+l.ID, "", true); code != 204 {
t.Fatalf("dismiss: %d", code)
}
if f.summary(t, l).Signals != 0 {
t.Fatal("a dismissed tip is still counted")
}
post(tip(t, l, report.Illegal, "anders", true))
f.do(t, "POST", "/api/v1/reports", reportJSON(l, report.Illegal, "bestätigt"), true)
if s := f.summary(t, l); s.Signals != 0 || !s.Hidden {
t.Fatalf("after reporting: %+v", s)
}
}
+77
View File
@@ -38,6 +38,7 @@ import (
"git.stinnesbeck.com/nils/allmende/internal/identity"
"git.stinnesbeck.com/nils/allmende/internal/listing"
"git.stinnesbeck.com/nils/allmende/internal/message"
"git.stinnesbeck.com/nils/allmende/internal/report"
"git.stinnesbeck.com/nils/allmende/internal/store"
)
@@ -48,6 +49,10 @@ const (
messageTopicPrefix = "/allmende/1/messages/"
// RevocationTopic carries identity revocations for the whole network.
RevocationTopic = "/allmende/1/revocations"
// ReportTopic carries signed abuse reports for the whole network. They are
// few (each needs a reporter's certificate and proof-of-work), and a node
// decides for itself which ones count.
ReportTopic = "/allmende/1/reports"
mdnsService = "allmende"
maintenanceTick = time.Hour
@@ -124,6 +129,7 @@ type Node struct {
syncing map[peer.ID]bool
oldSync bool // tests: answer like a node from before digests existed
revTopic *pubsub.Topic
repTopic *pubsub.Topic
}
// New starts a node. Cancel ctx or call Close to stop it.
@@ -236,6 +242,10 @@ func New(ctx context.Context, cfg Config) (*Node, error) {
n.Close()
return nil, err
}
if err := n.startReports(); err != nil {
n.Close()
return nil, err
}
for _, r := range cfg.Regions {
if err := n.subscribeRegion(r); err != nil {
n.Close()
@@ -356,6 +366,18 @@ func (n *Node) PublishRevocation(ctx context.Context, r *identity.Revocation) er
return n.revTopic.Publish(ctx, data)
}
// PublishReport stores r locally and gossips it to the whole network.
func (n *Node) PublishReport(ctx context.Context, r *report.Report) error {
if _, err := n.cfg.Store.PutReport(ctx, r); err != nil {
return err
}
data, err := r.Bytes()
if err != nil {
return err
}
return n.repTopic.Publish(ctx, data)
}
// Close stops the node.
func (n *Node) Close() error {
n.cancel()
@@ -401,6 +423,36 @@ func (n *Node) startRevocations() error {
return nil
}
func (n *Node) startReports() error {
if err := n.ps.RegisterTopicValidator(ReportTopic, n.reportValidator,
pubsub.WithValidatorTimeout(5*time.Second)); err != nil {
return err
}
t, err := n.ps.Join(ReportTopic)
if err != nil {
return err
}
sub, err := t.Subscribe()
if err != nil {
return err
}
n.repTopic = t
n.wg.Add(1)
go func() {
defer n.wg.Done()
n.consume(n.ctx, sub, func(msg *pubsub.Message) {
r, ok := msg.ValidatorData.(*report.Report)
if !ok {
return
}
if _, err := n.cfg.Store.PutReport(n.ctx, r); err != nil && !errors.Is(err, store.ErrRevoked) {
n.log.Warn("store report", "err", err)
}
})
}()
return nil
}
// regionRun is what a followed region keeps running; dropping the region stops it.
type regionRun struct {
ctx context.Context
@@ -689,6 +741,31 @@ func (n *Node) revocationValidator(_ context.Context, _ peer.ID, msg *pubsub.Mes
return res
}
func (n *Node) reportValidator(ctx context.Context, _ peer.ID, msg *pubsub.Message) pubsub.ValidationResult {
if len(msg.Data) > report.MaxSize {
return pubsub.ValidationReject
}
var r report.Report
if err := json.Unmarshal(msg.Data, &r); err != nil {
return pubsub.ValidationReject
}
// Only the canonical encoding, so every node derives the same message ID.
if canon, err := r.Bytes(); err != nil || !bytes.Equal(canon, msg.Data) {
return pubsub.ValidationReject
}
if err := r.Check(n.clock(), n.cfg.Difficulty); err != nil {
if errors.Is(err, report.ErrTimeWindow) {
return pubsub.ValidationIgnore // clocks differ; not the relay's fault
}
return pubsub.ValidationReject
}
if revoked, err := n.cfg.Store.IsRevoked(ctx, r.Reporter, r.Device, r.Cert.IssuedAt); err != nil || revoked {
return pubsub.ValidationIgnore
}
msg.ValidatorData = &r
return pubsub.ValidationAccept
}
func (n *Node) validateRevocation(data []byte) (*identity.Revocation, pubsub.ValidationResult) {
if len(data) > 4096 {
return nil, pubsub.ValidationReject
+13 -6
View File
@@ -101,6 +101,14 @@ func (tn *tnode) listing(t *testing.T, geohash string) *listing.Listing {
return l
}
// store puts l straight into the node's store, failing the test if it is refused.
func (tn *tnode) store(t *testing.T, l *listing.Listing) {
t.Helper()
if _, err := tn.s.Put(context.Background(), l); err != nil {
t.Fatal(err)
}
}
func connect(t *testing.T, from, to *tnode) {
t.Helper()
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
@@ -449,8 +457,8 @@ func TestIncrementalSyncFetchesOnlyTheDifference(t *testing.T) {
var shared []*listing.Listing
for i := 0; i < 5; i++ { // page size is 3: two inventory pages
l := a.listing(t, "u1xjhx")
a.s.Put(ctx, l)
b.s.Put(ctx, l)
a.store(t, l)
b.store(t, l)
shared = append(shared, l)
}
update := &listing.Listing{
@@ -463,8 +471,8 @@ func TestIncrementalSyncFetchesOnlyTheDifference(t *testing.T) {
t.Fatal(err)
}
fresh := a.listing(t, "u1xjhx")
a.s.Put(ctx, update)
a.s.Put(ctx, fresh)
a.store(t, update)
a.store(t, fresh)
connect(t, b, a)
eventually(t, "b has the update and the new listing", func() bool {
@@ -484,9 +492,8 @@ func TestIncrementalSyncFetchesOnlyTheDifference(t *testing.T) {
func TestSyncWithANodeThatKnowsNoDigests(t *testing.T) {
a := startNode(t, nil, "u1x")
a.oldSync = true
ctx := context.Background()
for i := 0; i < 4; i++ {
a.s.Put(ctx, a.listing(t, "u1xjhx"))
a.store(t, a.listing(t, "u1xjhx"))
}
b := startNode(t, nil, "u1x")
connect(t, b, a)
+113
View File
@@ -0,0 +1,113 @@
package p2p
import (
"context"
"encoding/json"
"testing"
"time"
pubsub "github.com/libp2p/go-libp2p-pubsub"
pb "github.com/libp2p/go-libp2p-pubsub/pb"
"git.stinnesbeck.com/nils/allmende/internal/identity"
"git.stinnesbeck.com/nils/allmende/internal/report"
)
// report makes a signed report by this node's operator about a listing.
func (tn *tnode) report(t *testing.T, author, id, category string) *report.Report {
t.Helper()
r := &report.Report{
Listing: report.Ref{Author: author, ID: id},
Category: category,
Note: "Verlangt Vorkasse",
CreatedAt: time.Now().Unix(),
ExpiresAt: time.Now().Add(7 * 24 * time.Hour).Unix(),
}
if err := r.Seal(tn.dev, difficulty); err != nil {
t.Fatal(err)
}
return r
}
func reportCount(tn *tnode) int {
rs, _ := tn.s.Reports(context.Background(), 100)
return len(rs)
}
func TestReportsAreGossipedToEveryone(t *testing.T) {
// Not even in the same region: reports travel on a topic of their own.
a := startNode(t, nil, "u1x")
b := startNode(t, nil, "u30")
connect(t, a, b)
eventually(t, "the report topic has a peer", func() bool { return len(a.ps.ListPeers(ReportTopic)) == 1 })
l := a.listing(t, "u1xjhx")
if err := a.PublishReport(context.Background(), a.report(t, l.Author, l.ID, report.Scam)); err != nil {
t.Fatal(err)
}
eventually(t, "b holds the report", func() bool { return reportCount(b) == 1 })
}
func TestALateJoinerGetsTheReportsBySync(t *testing.T) {
a := startNode(t, nil, "u1x")
l := a.listing(t, "u1xjhx")
if _, err := a.s.PutReport(context.Background(), a.report(t, l.Author, l.ID, report.Illegal)); err != nil {
t.Fatal(err)
}
b := startNode(t, nil, "u1x") // joins after the report was made, never hears the gossip
connect(t, b, a)
eventually(t, "b caught up with the reports", func() bool { return reportCount(b) == 1 })
}
// What a relay does with a report it is handed, checked on the validator itself
// (as the listing validator is): it must be the exact thing the reporter signed,
// from a device that is still valid.
func TestTheReportValidatorJudgesWhatArrives(t *testing.T) {
a := startNode(t, nil, "u1x")
l := a.listing(t, "u1xjhx")
rep := a.report(t, l.Author, l.ID, report.Scam)
data, _ := rep.Bytes()
validate := func(data []byte) pubsub.ValidationResult {
return a.reportValidator(context.Background(), "", &pubsub.Message{Message: &pb.Message{Data: data}})
}
if r := validate(data); r != pubsub.ValidationAccept {
t.Fatalf("a good report: %v", r)
}
if r := validate([]byte(`{"v":1`)); r != pubsub.ValidationReject {
t.Fatalf("garbage: %v", r)
}
tampered := *rep
tampered.Category = report.Illegal // the signature no longer fits
tb, _ := tampered.Bytes()
if r := validate(tb); r != pubsub.ValidationReject {
t.Fatalf("a tampered report: %v", r)
}
var m map[string]any
_ = json.Unmarshal(data, &m)
pretty, _ := json.MarshalIndent(m, "", " ")
if r := validate(pretty); r != pubsub.ValidationReject {
t.Fatalf("a report that is not in canonical form: %v", r)
}
// Clocks differ: ignored, and the relay is not penalised for it.
a.clock = func() time.Time { return time.Now().Add(31 * 24 * time.Hour) }
if r := validate(data); r != pubsub.ValidationIgnore {
t.Fatalf("an expired report: %v", r)
}
a.clock = time.Now
// The reporter's device was revoked: ignored, so it is not passed on.
rev, err := identity.Revoke(a.root, a.dev.Cert, time.Now(), difficulty)
if err != nil {
t.Fatal(err)
}
if _, err := a.s.PutRevocation(context.Background(), rev); err != nil {
t.Fatal(err)
}
if r := validate(data); r != pubsub.ValidationIgnore {
t.Fatalf("a report from a revoked device: %v", r)
}
}
+44 -1
View File
@@ -14,6 +14,7 @@ import (
"git.stinnesbeck.com/nils/allmende/internal/identity"
"git.stinnesbeck.com/nils/allmende/internal/listing"
"git.stinnesbeck.com/nils/allmende/internal/message"
"git.stinnesbeck.com/nils/allmende/internal/report"
"git.stinnesbeck.com/nils/allmende/internal/store"
)
@@ -30,12 +31,14 @@ const (
maxSyncPages = 200 // bounds work per region against a misbehaving peer
maxRevocations = 5000
maxFetch = 100 // records asked for in one fetch
maxReportsSync = 5000
)
// digestReply is the answer to a "digest" request. Listings and Messages are
// left empty when no region was asked about.
type digestReply struct {
Revocations store.Digest `json:"revocations"`
Reports store.Digest `json:"reports"`
Listings store.Digest `json:"listings"`
Messages store.Digest `json:"messages"`
}
@@ -65,7 +68,7 @@ func (n *Node) handleSync(s network.Stream) {
_ = s.Reset()
return
}
if n.oldSync && (req.Kind == "digest" || req.Kind == "inventory" || req.Kind == "fetch") {
if n.oldSync && (req.Kind == "digest" || req.Kind == "inventory" || req.Kind == "fetch" || req.Kind == "reports") {
_ = s.Reset()
return
}
@@ -137,6 +140,18 @@ func (n *Node) handleSync(s network.Stream) {
return
}
}
case "reports":
reps, err := n.cfg.Store.Reports(n.ctx, maxReportsSync)
if err != nil {
_ = s.Reset()
return
}
for _, r := range reps {
if !write(r.Bytes()) {
_ = s.Reset()
return
}
}
case "digest":
var d digestReply
var err error
@@ -144,6 +159,10 @@ func (n *Node) handleSync(s network.Stream) {
_ = s.Reset()
return
}
if d.Reports, err = n.cfg.Store.ReportDigest(n.ctx); err != nil {
_ = s.Reset()
return
}
if req.Region != "" {
if !listing.ValidRegion(req.Region) {
_ = s.Reset()
@@ -294,6 +313,16 @@ func (n *Node) SyncFrom(ctx context.Context, p peer.ID) error {
return err
}
}
// Reports after the revocations, so a revoked reporter's are refused.
oursReports, err := n.cfg.Store.ReportDigest(ctx)
if err != nil {
return err
}
if oursReports != theirs.Reports {
if err := n.syncReports(ctx, p); err != nil {
return err
}
}
for _, region := range regions {
if err := n.digest(ctx, p, region, &theirs); err != nil {
return err
@@ -492,6 +521,20 @@ func (n *Node) syncMessages(ctx context.Context, p peer.ID, region string) error
return nil
}
// syncReports pulls every live report p holds. They are few: each needs a
// reporter's certificate and proof-of-work, and they last at most 30 days.
func (n *Node) syncReports(ctx context.Context, p peer.ID) error {
return n.request(ctx, p, syncRequest{Kind: "reports"}, func(line []byte) {
var r report.Report
if json.Unmarshal(line, &r) != nil {
return
}
if _, err := n.cfg.Store.PutReport(ctx, &r); err != nil && !errors.Is(err, store.ErrRevoked) {
n.log.Debug("sync: report rejected", "peer", p, "err", err)
}
})
}
func (n *Node) syncRevocations(ctx context.Context, p peer.ID) error {
return n.request(ctx, p, syncRequest{Kind: "revocations"}, func(line []byte) {
var r identity.Revocation
+241
View File
@@ -0,0 +1,241 @@
// 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
r.Reporter = dev.Cert.Author
r.Device = dev.Cert.Device
r.Cert = dev.Cert
r.Sig = ""
for r.PoW = 0; ; r.PoW++ {
if r.PoW > maxSafeInt {
return errors.New("report: proof-of-work exhausted")
}
b, err := r.unsignedBytes()
if err != nil {
return err
}
if pow.LeadingZeroBits(b) >= 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
}
+128
View File
@@ -0,0 +1,128 @@
package report
import (
"errors"
"strings"
"testing"
"time"
"git.stinnesbeck.com/nils/allmende/internal/identity"
)
const difficulty = 6
var t0 = time.Date(2026, 11, 18, 12, 0, 0, 0, time.UTC)
func device(t *testing.T) *identity.Device {
t.Helper()
root, _, _ := identity.NewRoot()
dev, err := identity.Enroll(root, t0.Add(-time.Hour), 90*24*time.Hour)
if err != nil {
t.Fatal(err)
}
return dev
}
func sealed(t *testing.T, dev *identity.Device, mutate func(*Report)) *Report {
t.Helper()
r := &Report{
Listing: Ref{Author: strings.Repeat("ab", 32), ID: strings.Repeat("cd", 16)},
Category: Scam,
Note: "Verlangt Vorkasse",
CreatedAt: t0.Unix(),
ExpiresAt: t0.Add(7 * 24 * time.Hour).Unix(),
}
if mutate != nil {
mutate(r)
}
if err := r.Seal(dev, difficulty); err != nil {
t.Fatal(err)
}
return r
}
func TestASealedReportChecks(t *testing.T) {
r := sealed(t, device(t), nil)
if err := r.Check(t0, difficulty); err != nil {
t.Fatal(err)
}
if err := r.Check(t0, difficulty+8); err == nil {
t.Fatal("a report with too little proof-of-work was accepted")
}
}
func TestTamperedReportsAreRefused(t *testing.T) {
dev := device(t)
cases := map[string]func(*Report){
"another listing": func(r *Report) { r.Listing.ID = strings.Repeat("00", 16) },
"another category": func(r *Report) { r.Category = Illegal },
"another note": func(r *Report) { r.Note = "anders" },
"longer lifetime": func(r *Report) { r.ExpiresAt += 3600 },
"another reporter": func(r *Report) { r.Reporter = strings.Repeat("11", 32) },
}
for name, tamper := range cases {
r := sealed(t, dev, nil)
tamper(r)
if err := r.Check(t0, difficulty); err == nil {
t.Errorf("%s: accepted", name)
}
}
}
func TestTheCertificateMustBelongToTheReporter(t *testing.T) {
a, b := device(t), device(t)
r := sealed(t, a, nil)
r.Cert = b.Cert // somebody else's certificate
if err := r.Check(t0, difficulty); err == nil {
t.Fatal("a report carrying another reporter's certificate was accepted")
}
}
func TestFieldRules(t *testing.T) {
dev := device(t)
for name, mutate := range map[string]func(*Report){
"unknown category": func(r *Report) { r.Category = "spam" },
"bad author": func(r *Report) { r.Listing.Author = "xyz" },
"note too long": func(r *Report) { r.Note = strings.Repeat("a", MaxNote+1) },
"control character": func(r *Report) { r.Note = "a\x00b" },
"lifetime over 30 days": func(r *Report) { r.ExpiresAt = r.CreatedAt + int64(31*24*time.Hour/time.Second) },
"expires before start": func(r *Report) { r.ExpiresAt = r.CreatedAt },
} {
r := &Report{
Listing: Ref{Author: strings.Repeat("ab", 32), ID: strings.Repeat("cd", 16)}, Category: Scam,
CreatedAt: t0.Unix(), ExpiresAt: t0.Add(24 * time.Hour).Unix(),
}
mutate(r)
if err := r.Seal(dev, difficulty); err != nil {
t.Fatal(err)
}
if err := r.Check(t0, difficulty); err == nil {
t.Errorf("%s: accepted", name)
}
}
}
func TestClockProblemsAreMarkedAsSuch(t *testing.T) {
dev := device(t)
r := sealed(t, dev, nil)
if err := r.Check(t0.Add(8*24*time.Hour), difficulty); !errors.Is(err, ErrTimeWindow) {
t.Fatalf("expired: %v", err)
}
if err := r.Check(t0.Add(-time.Hour), difficulty); !errors.Is(err, ErrTimeWindow) {
t.Fatalf("from the future: %v", err)
}
}
func TestTheNewerReportWinsAndTiesConverge(t *testing.T) {
dev := device(t)
old := sealed(t, dev, func(r *Report) { r.CreatedAt = t0.Unix() - 100 })
newer := sealed(t, dev, func(r *Report) { r.Category = Withdrawn })
if !newer.Supersedes(old) || old.Supersedes(newer) {
t.Fatal("the newer report must win")
}
a := sealed(t, dev, func(r *Report) { r.Note = "a" })
b := sealed(t, dev, func(r *Report) { r.Note = "b" })
if a.Supersedes(b) == b.Supersedes(a) {
t.Fatal("on a tie exactly one of two reports must win, on every node")
}
}
+321
View File
@@ -0,0 +1,321 @@
package store
import (
"context"
"database/sql"
"encoding/json"
"errors"
"fmt"
"git.stinnesbeck.com/nils/allmende/internal/report"
)
// DefaultHideThreshold is how many distinct trusted reporters it takes to hide
// a listing as a scam.
const DefaultHideThreshold = 2
const (
maxReports = 20000 // live reports a node keeps; the oldest go first
maxSignals = 2000
maxSignalsPerList = 50
)
// Trust says whose abuse reports hide listings on this node. It is a local
// choice, like everything about hiding: other nodes decide for themselves, and
// a hidden listing stays stored and reachable by its link.
//
// A listing is hidden when
// - the node's own operator (Self) reported it as a scam or as illegal, or
// - one trusted reporter flagged it as illegal, or
// - Threshold distinct trusted reporters flagged it as a scam or as illegal.
//
// Reports in the other categories only label a listing.
type Trust struct {
Self string // this node's identity key; may be empty
Reporters []string // other identity keys whose reports count
Threshold int // 0 means DefaultHideThreshold
}
func (t Trust) keys() []string {
out := append([]string(nil), t.Reporters...)
if t.Self != "" {
out = append(out, t.Self)
}
return out
}
// hiddenSQL is a query returning the (author, id) of every listing the node
// hides, with its arguments.
func (s *Store) hiddenSQL() (string, []any) {
keys, _ := json.Marshal(s.trust.keys())
return `
SELECT l_author, l_id FROM reports
WHERE expires_at > ? AND category IN ('scam', 'illegal')
AND reporter IN (SELECT value FROM json_each(?))
GROUP BY l_author, l_id
HAVING COUNT(*) >= ? OR SUM(category = 'illegal') >= 1 OR SUM(reporter = ?) >= 1`,
[]any{s.clock().Unix(), string(keys), s.trust.Threshold, s.trust.Self}
}
// PutReport verifies and stores a signed report. A reporter has one report per
// listing: a newer one (which may withdraw it) replaces the older.
func (s *Store) PutReport(ctx context.Context, r *report.Report) (Outcome, error) {
now := s.clock()
if err := r.Check(now, s.difficulty); err != nil {
return Ignored, fmt.Errorf("%w: %v", ErrInvalid, err)
}
data, err := r.Bytes()
if err != nil {
return Ignored, err
}
hash, err := r.Hash()
if err != nil {
return Ignored, err
}
tx, err := s.db.BeginTx(ctx, nil)
if err != nil {
return Ignored, err
}
defer tx.Rollback()
var revoked int
if err := tx.QueryRowContext(ctx, `
SELECT COUNT(*) FROM revocations
WHERE author = ? AND (device = ? OR (device = '' AND revoked_at > ?))`,
r.Reporter, r.Device, r.Cert.IssuedAt).Scan(&revoked); err != nil {
return Ignored, err
}
if revoked > 0 {
return Ignored, ErrRevoked
}
outcome := Inserted
var held []byte
err = tx.QueryRowContext(ctx,
`SELECT data FROM reports WHERE reporter = ? AND l_author = ? AND l_id = ?`,
r.Reporter, r.Listing.Author, r.Listing.ID).Scan(&held)
switch {
case errors.Is(err, sql.ErrNoRows):
case err != nil:
return Ignored, err
default:
var old report.Report
if err := json.Unmarshal(held, &old); err != nil {
return Ignored, fmt.Errorf("store: corrupt report row: %w", err)
}
if !r.Supersedes(&old) {
return Ignored, nil
}
outcome = Replaced
}
if _, err := tx.ExecContext(ctx, `
INSERT OR REPLACE INTO reports
(reporter, l_author, l_id, device, cert_issued_at, category, created_at, expires_at, hash, data)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
r.Reporter, r.Listing.Author, r.Listing.ID, r.Device, r.Cert.IssuedAt, r.Category,
r.CreatedAt, r.ExpiresAt, hash, data); err != nil {
return Ignored, err
}
// Bounded: when over the cap the oldest reports go.
if _, err := tx.ExecContext(ctx, `
DELETE FROM reports WHERE (reporter, l_author, l_id) IN (
SELECT reporter, l_author, l_id FROM reports ORDER BY created_at DESC LIMIT -1 OFFSET ?)`,
maxReports); err != nil {
return Ignored, err
}
if err := tx.Commit(); err != nil {
return Ignored, err
}
return outcome, nil
}
// Reports returns up to limit live reports, newest first, for sync.
func (s *Store) Reports(ctx context.Context, limit int) ([]*report.Report, error) {
rows, err := s.db.QueryContext(ctx, `
SELECT data FROM reports WHERE expires_at > ?
ORDER BY created_at DESC, reporter, l_author, l_id LIMIT ?`, s.clock().Unix(), limit)
if err != nil {
return nil, err
}
defer rows.Close()
var out []*report.Report
for rows.Next() {
var data []byte
if err := rows.Scan(&data); err != nil {
return nil, err
}
var r report.Report
if err := json.Unmarshal(data, &r); err != nil {
return nil, fmt.Errorf("store: corrupt report row: %w", err)
}
out = append(out, &r)
}
return out, rows.Err()
}
// ReportDigest digests the live reports (reporter, listing and version), so
// peers can tell cheaply whether they hold the same ones.
func (s *Store) ReportDigest(ctx context.Context) (Digest, error) {
rows, err := s.db.QueryContext(ctx, `
SELECT reporter, l_author, l_id, hash FROM reports WHERE expires_at > ?
ORDER BY reporter, l_author, l_id`, s.clock().Unix())
if err != nil {
return Digest{}, err
}
return digestOf(rows, 4)
}
// ReportSummary is what this node makes of the reports about one listing.
type ReportSummary struct {
// Hidden: the node's rules (Trust) hide the listing.
Hidden bool `json:"hidden"`
// Trusted counts live reports from trusted reporters by category
// (withdrawn ones are not counted).
Trusted map[string]int `json:"trusted"`
// Others counts live reports from reporters this node does not trust:
// shown, never counted.
Others int `json:"others"`
// Signals counts what visitors told this node (see AddSignal).
Signals int `json:"signals"`
// Own is the node operator's own live report category, if any.
Own string `json:"own,omitempty"`
}
// Summary describes the reports about a listing.
func (s *Store) Summary(ctx context.Context, author, id string) (ReportSummary, error) {
sum := ReportSummary{Trusted: map[string]int{}}
trusted := map[string]bool{}
for _, k := range s.trust.keys() {
trusted[k] = true
}
rows, err := s.db.QueryContext(ctx, `
SELECT reporter, category FROM reports
WHERE l_author = ? AND l_id = ? AND expires_at > ? AND category != 'withdrawn'`,
author, id, s.clock().Unix())
if err != nil {
return sum, err
}
defer rows.Close()
for rows.Next() {
var reporter, category string
if err := rows.Scan(&reporter, &category); err != nil {
return sum, err
}
if reporter == s.trust.Self && reporter != "" {
sum.Own = category
}
if trusted[reporter] {
sum.Trusted[category]++
} else {
sum.Others++
}
}
if err := rows.Err(); err != nil {
return sum, err
}
var hidden int
sub, args := s.hiddenSQL()
if err := s.db.QueryRowContext(ctx,
`SELECT COUNT(*) FROM (`+sub+`) WHERE l_author = ? AND l_id = ?`, append(args, author, id)...).Scan(&hidden); err != nil {
return sum, err
}
sum.Hidden = hidden > 0
if err := s.db.QueryRowContext(ctx,
`SELECT COUNT(*) FROM signals WHERE l_author = ? AND l_id = ? AND expires_at > ?`,
author, id, s.clock().Unix()).Scan(&sum.Signals); err != nil {
return sum, err
}
return sum, nil
}
// --- what visitors tell this node ----------------------------------------------
// Signal is a tip from a visitor: unsigned, backed only by proof-of-work, and
// kept on this node alone. It never hides anything; the operator reads it and
// may sign a report of their own.
type Signal struct {
ID int64 `json:"id"`
Author string `json:"author"`
ListingID string `json:"listing"`
Category string `json:"category"`
Note string `json:"note"`
CreatedAt int64 `json:"created_at"`
Work int `json:"work"` // proof-of-work bits behind it
// Hash identifies the visitor's request, so repeating it adds nothing.
// Set by the caller when adding; not listed.
Hash string `json:"-"`
}
// SignalTTL is how long a tip is kept.
const SignalTTL = report.MaxLifetime
// AddSignal stores a visitor's tip. Per listing and overall the number is
// bounded; when full the tip with the least work goes.
func (s *Store) AddSignal(ctx context.Context, sg Signal) error {
if !report.ValidCategory(sg.Category) || sg.Category == report.Withdrawn {
return fmt.Errorf("%w: category", ErrInvalid)
}
now := s.clock().Unix()
tx, err := s.db.BeginTx(ctx, nil)
if err != nil {
return err
}
defer tx.Rollback()
if sg.Hash == "" {
return fmt.Errorf("%w: hash", ErrInvalid)
}
if _, err := tx.ExecContext(ctx, `
INSERT OR IGNORE INTO signals (hash, l_author, l_id, category, note, created_at, expires_at, work)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
sg.Hash, sg.Author, sg.ListingID, sg.Category, sg.Note, now, now+int64(SignalTTL.Seconds()), sg.Work); err != nil {
return err
}
for _, q := range []struct {
where string
args []any
cap int
}{
{`l_author = ? AND l_id = ?`, []any{sg.Author, sg.ListingID}, maxSignalsPerList},
{`1 = 1`, nil, maxSignals},
} {
args := append(q.args, q.cap)
if _, err := tx.ExecContext(ctx, `
DELETE FROM signals WHERE id IN (
SELECT id FROM signals WHERE `+q.where+`
ORDER BY work DESC, created_at DESC LIMIT -1 OFFSET ?)`, args...); err != nil {
return err
}
}
return tx.Commit()
}
// Signals lists the live tips, strongest first, then newest.
func (s *Store) Signals(ctx context.Context) ([]Signal, error) {
rows, err := s.db.QueryContext(ctx, `
SELECT id, l_author, l_id, category, note, created_at, work FROM signals
WHERE expires_at > ? ORDER BY work DESC, created_at DESC LIMIT 500`, s.clock().Unix())
if err != nil {
return nil, err
}
defer rows.Close()
var out []Signal
for rows.Next() {
var g Signal
if err := rows.Scan(&g.ID, &g.Author, &g.ListingID, &g.Category, &g.Note, &g.CreatedAt, &g.Work); err != nil {
return nil, err
}
out = append(out, g)
}
return out, rows.Err()
}
// DeleteSignals dismisses every tip about a listing. It reports how many.
func (s *Store) DeleteSignals(ctx context.Context, author, id string) (int64, error) {
res, err := s.db.ExecContext(ctx, `DELETE FROM signals WHERE l_author = ? AND l_id = ?`, author, id)
if err != nil {
return 0, err
}
return res.RowsAffected()
}
+307
View File
@@ -0,0 +1,307 @@
package store
import (
"errors"
"fmt"
"testing"
"time"
"git.stinnesbeck.com/nils/allmende/internal/identity"
"git.stinnesbeck.com/nils/allmende/internal/listing"
"git.stinnesbeck.com/nils/allmende/internal/report"
)
// reporter is somebody who can sign reports.
type reporter struct {
root *identity.Identity
dev *identity.Device
}
func newReporter(t *testing.T) *reporter {
t.Helper()
root, _, _ := identity.NewRoot()
return &reporter{root: root, dev: newDevice(t, root)}
}
func (r *reporter) key() string { return r.dev.Cert.Author }
// reportEnv is an env whose store trusts the given reporters; self is the
// node's own operator.
func reportEnv(t *testing.T, self *reporter, trusted ...*reporter) *env {
t.Helper()
e := &env{now: t0}
e.root, _, _ = identity.NewRoot()
e.dev = newDevice(t, e.root)
tr := Trust{}
if self != nil {
tr.Self = self.key()
}
for _, r := range trusted {
tr.Reporters = append(tr.Reporters, r.key())
}
s, err := Open(":memory:", Options{Difficulty: difficulty, Clock: func() time.Time { return e.now }, Trust: tr})
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { s.Close() })
e.s = s
return e
}
func (e *env) report(t *testing.T, by *reporter, l *listing.Listing, category string, at time.Time) *report.Report {
t.Helper()
r := &report.Report{
Listing: report.Ref{Author: l.Author, ID: l.ID},
Category: category,
CreatedAt: at.Unix(),
ExpiresAt: at.Add(7 * 24 * time.Hour).Unix(),
}
if err := r.Seal(by.dev, difficulty); err != nil {
t.Fatal(err)
}
return r
}
func (e *env) putReport(t *testing.T, r *report.Report) Outcome {
t.Helper()
o, err := e.s.PutReport(ctx, r)
if err != nil {
t.Fatal(err)
}
return o
}
func (e *env) visible(t *testing.T) int {
t.Helper()
ls, err := e.s.Search(ctx, Query{})
if err != nil {
t.Fatal(err)
}
return len(ls)
}
func (e *env) everything(t *testing.T) int {
t.Helper()
ls, err := e.s.Search(ctx, Query{IncludeHidden: true})
if err != nil {
t.Fatal(err)
}
return len(ls)
}
func TestTheOperatorsOwnReportHidesAtOnce(t *testing.T) {
me := newReporter(t)
e := reportEnv(t, me)
l := e.listing(t, nil)
e.put(t, l)
e.put(t, e.listing(t, nil))
e.putReport(t, e.report(t, me, l, report.Scam, e.now))
if e.visible(t) != 1 || e.everything(t) != 2 {
t.Fatalf("visible %d, all %d: want 1 and 2 (hidden, not deleted)", e.visible(t), e.everything(t))
}
if _, err := e.s.Get(ctx, l.Author, l.ID); err != nil {
t.Fatalf("a hidden listing must stay reachable by its link: %v", err)
}
sum, _ := e.s.Summary(ctx, l.Author, l.ID)
if !sum.Hidden || sum.Own != report.Scam || sum.Trusted[report.Scam] != 1 {
t.Fatalf("summary: %+v", sum)
}
}
func TestSeveralTrustedReportersHideAScam(t *testing.T) {
a, b, stranger := newReporter(t), newReporter(t), newReporter(t)
e := reportEnv(t, nil, a, b)
l := e.listing(t, nil)
e.put(t, l)
e.putReport(t, e.report(t, a, l, report.Scam, e.now))
if e.visible(t) != 1 {
t.Fatal("one trusted scam report is not enough to hide")
}
e.putReport(t, e.report(t, stranger, l, report.Scam, e.now))
e.putReport(t, e.report(t, stranger, l, report.Illegal, e.now.Add(time.Second)))
if e.visible(t) != 1 {
t.Fatal("reports from strangers must never hide anything")
}
e.putReport(t, e.report(t, b, l, report.Scam, e.now))
if e.visible(t) != 0 {
t.Fatal("two trusted reporters did not hide the listing")
}
sum, _ := e.s.Summary(ctx, l.Author, l.ID)
if sum.Trusted[report.Scam] != 2 || sum.Others != 1 {
t.Fatalf("summary: %+v", sum)
}
}
func TestOneTrustedReportOfIllegalContentHides(t *testing.T) {
a := newReporter(t)
e := reportEnv(t, nil, a)
l := e.listing(t, nil)
e.put(t, l)
e.putReport(t, e.report(t, a, l, report.Illegal, e.now))
if e.visible(t) != 0 {
t.Fatal("a trusted report of illegal content must hide at once")
}
}
func TestLabelsNeverHide(t *testing.T) {
a, b := newReporter(t), newReporter(t)
e := reportEnv(t, a, b)
l := e.listing(t, nil)
e.put(t, l)
e.putReport(t, e.report(t, a, l, report.Category, e.now))
e.putReport(t, e.report(t, b, l, report.Other, e.now))
if e.visible(t) != 1 {
t.Fatal("category and other reports must only label a listing")
}
sum, _ := e.s.Summary(ctx, l.Author, l.ID)
if sum.Hidden || sum.Trusted[report.Category] != 1 || sum.Trusted[report.Other] != 1 {
t.Fatalf("summary: %+v", sum)
}
}
func TestAReporterCanTakeAReportBackAndTheNewerOneWins(t *testing.T) {
me := newReporter(t)
e := reportEnv(t, me)
l := e.listing(t, nil)
e.put(t, l)
old := e.report(t, me, l, report.Scam, e.now)
e.putReport(t, old)
if e.visible(t) != 0 {
t.Fatal("not hidden")
}
withdrawn := e.report(t, me, l, report.Withdrawn, e.now.Add(time.Minute))
if o := e.putReport(t, withdrawn); o != Replaced {
t.Fatalf("withdrawing: %v", o)
}
if e.visible(t) != 1 {
t.Fatal("a withdrawn report still hides the listing")
}
// The old one arriving late (sync order is arbitrary) changes nothing.
if o := e.putReport(t, old); o != Ignored {
t.Fatalf("an older report replaced a newer one: %v", o)
}
if e.visible(t) != 1 {
t.Fatal("the listing was hidden again by an old report")
}
}
func TestReportsExpireAndHidingLapsesWithThem(t *testing.T) {
me := newReporter(t)
e := reportEnv(t, me)
l := e.listing(t, func(l *listing.Listing) { l.ExpiresAt = e.now.Add(30 * 24 * time.Hour).Unix() })
e.put(t, l)
e.putReport(t, e.report(t, me, l, report.Scam, e.now))
if e.visible(t) != 0 {
t.Fatal("not hidden")
}
e.now = e.now.Add(8 * 24 * time.Hour)
if e.visible(t) != 1 {
t.Fatal("an expired report still hides the listing")
}
if _, err := e.s.Expire(ctx); err != nil {
t.Fatal(err)
}
if reps, _ := e.s.Reports(ctx, 10); len(reps) != 0 {
t.Fatal("an expired report was kept")
}
}
func TestARevokedReportersReportsGoAway(t *testing.T) {
a := newReporter(t)
e := reportEnv(t, nil, a)
l := e.listing(t, nil)
e.put(t, l)
e.putReport(t, e.report(t, a, l, report.Illegal, e.now))
if e.visible(t) != 0 {
t.Fatal("not hidden")
}
rev, err := identity.Revoke(a.root, a.dev.Cert, e.now, difficulty)
if err != nil {
t.Fatal(err)
}
if _, err := e.s.PutRevocation(ctx, rev); err != nil {
t.Fatal(err)
}
if e.visible(t) != 1 {
t.Fatal("the reports of a revoked device still count")
}
if _, err := e.s.PutReport(ctx, e.report(t, a, l, report.Illegal, e.now.Add(time.Minute))); !errors.Is(err, ErrRevoked) {
t.Fatalf("a revoked device's new report: %v", err)
}
}
func TestInvalidReportsAreRefused(t *testing.T) {
a := newReporter(t)
e := reportEnv(t, nil, a)
l := e.listing(t, nil)
r := e.report(t, a, l, report.Scam, e.now)
r.Note = "changed after signing"
if _, err := e.s.PutReport(ctx, r); !errors.Is(err, ErrInvalid) {
t.Fatalf("a tampered report: %v", err)
}
}
func TestReportDigestsMatchWhenTheSetsDo(t *testing.T) {
a, b := newReporter(t), newReporter(t)
x, y := reportEnv(t, nil, a, b), reportEnv(t, nil, a, b)
l := x.listing(t, nil)
r1, r2 := x.report(t, a, l, report.Scam, x.now), x.report(t, b, l, report.Other, x.now)
x.putReport(t, r1)
x.putReport(t, r2)
y.putReport(t, r2)
y.putReport(t, r1)
dx, _ := x.s.ReportDigest(ctx)
dy, _ := y.s.ReportDigest(ctx)
if dx != dy || dx.Count != 2 {
t.Fatalf("digests differ: %+v %+v", dx, dy)
}
y.putReport(t, y.report(t, a, l, report.Withdrawn, y.now.Add(time.Minute)))
if dy2, _ := y.s.ReportDigest(ctx); dy2 == dx {
t.Fatal("a newer report did not change the digest")
}
}
func TestVisitorsTipsAreBoundedAndNeverHide(t *testing.T) {
e := reportEnv(t, nil)
l := e.listing(t, nil)
e.put(t, l)
for i := 0; i < maxSignalsPerList+10; i++ {
err := e.s.AddSignal(ctx, Signal{Hash: fmt.Sprint("h", i), Author: l.Author, ListingID: l.ID, Category: report.Scam, Note: "Betrug", Work: 10 + i%5})
if err != nil {
t.Fatal(err)
}
}
tips, _ := e.s.Signals(ctx)
if len(tips) != maxSignalsPerList {
t.Fatalf("%d tips kept, want %d", len(tips), maxSignalsPerList)
}
if tips[0].Work < tips[len(tips)-1].Work {
t.Fatal("tips are not listed strongest first")
}
if e.visible(t) != 1 {
t.Fatal("visitor tips must never hide a listing")
}
sum, _ := e.s.Summary(ctx, l.Author, l.ID)
if sum.Signals != maxSignalsPerList || sum.Hidden {
t.Fatalf("summary: %+v", sum)
}
if err := e.s.AddSignal(ctx, Signal{Hash: "x", Author: l.Author, ListingID: l.ID, Category: "spam"}); !errors.Is(err, ErrInvalid) {
t.Fatalf("an unknown category: %v", err)
}
// Sending the same request twice adds nothing.
// (h5x tips were kept: the strongest have the highest i%5, so h59 is among them.)
before, _ := e.s.Signals(ctx)
if err := e.s.AddSignal(ctx, Signal{Hash: "h59", Author: l.Author, ListingID: l.ID, Category: report.Scam, Work: 99}); err != nil {
t.Fatal(err)
}
after, _ := e.s.Signals(ctx)
if len(after) != len(before) || after[0].Work == 99 {
t.Fatalf("a repeated tip was added: %d -> %d, strongest %d", len(before), len(after), after[0].Work)
}
if n, _ := e.s.DeleteSignals(ctx, l.Author, l.ID); n != int64(maxSignalsPerList) {
t.Fatalf("dismissed %d", n)
}
}
+64
View File
@@ -54,6 +54,9 @@ type Options struct {
// OwnerQueue and MailboxQueue cap the envelopes per listing and per
// mailbox; 0 means MaxOwnerQueue and MaxMailboxQueue.
OwnerQueue, MailboxQueue int
// Trust says whose abuse reports hide listings on this node (see Trust).
Trust Trust
}
type Store struct {
@@ -64,6 +67,7 @@ type Store struct {
maxMessages int
ownerQueue int
mailboxQueue int
trust Trust
}
const schema = `
@@ -150,6 +154,37 @@ CREATE TABLE IF NOT EXISTS inbox_blocked (
blocked_at INTEGER NOT NULL,
PRIMARY KEY (author, listing_id, thread)
) WITHOUT ROWID;
-- Signed abuse reports (internal/report): one per (reporter, listing).
CREATE TABLE IF NOT EXISTS reports (
reporter TEXT NOT NULL,
l_author TEXT NOT NULL,
l_id TEXT NOT NULL,
device TEXT NOT NULL,
cert_issued_at INTEGER NOT NULL,
category TEXT NOT NULL,
created_at INTEGER NOT NULL,
expires_at INTEGER NOT NULL,
hash TEXT NOT NULL,
data BLOB NOT NULL,
PRIMARY KEY (reporter, l_author, l_id)
) WITHOUT ROWID;
CREATE INDEX IF NOT EXISTS reports_listing ON reports (l_author, l_id);
CREATE INDEX IF NOT EXISTS reports_expires ON reports (expires_at);
-- What visitors told this node about a listing (unsigned, proof-of-work
-- only). Never gossiped: they are tips for the operator, who may turn one into
-- a signed report.
CREATE TABLE IF NOT EXISTS signals (
id INTEGER PRIMARY KEY AUTOINCREMENT,
hash TEXT NOT NULL UNIQUE, -- of the visitor's request: sending it twice adds nothing
l_author TEXT NOT NULL,
l_id TEXT NOT NULL,
category TEXT NOT NULL,
note TEXT NOT NULL,
created_at INTEGER NOT NULL,
expires_at INTEGER NOT NULL,
work INTEGER NOT NULL
);
CREATE INDEX IF NOT EXISTS signals_listing ON signals (l_author, l_id);
-- The exact address of a listing, only ever read by its owner's node.
CREATE TABLE IF NOT EXISTS addresses (
author TEXT NOT NULL,
@@ -181,6 +216,10 @@ func Open(path string, opt Options) (*Store, error) {
s := &Store{db: db, difficulty: opt.Difficulty, clock: opt.Clock,
msgDifficulty: opt.MessageDifficulty, maxMessages: opt.MaxMessages,
ownerQueue: opt.OwnerQueue, mailboxQueue: opt.MailboxQueue}
s.trust = opt.Trust
if s.trust.Threshold <= 0 {
s.trust.Threshold = DefaultHideThreshold
}
if s.ownerQueue <= 0 {
s.ownerQueue = MaxOwnerQueue
}
@@ -302,6 +341,9 @@ type Query struct {
MinRoomsX2 int
Limit int // default 50, max 200
Offset int
// IncludeHidden also returns listings this node hides because trusted
// reporters flagged them (see Trust). They are hidden, never deleted.
IncludeHidden bool
}
// Search returns live listings, newest first.
@@ -345,6 +387,11 @@ func (s *Store) Search(ctx context.Context, q Query) ([]*listing.Listing, error)
where = append(where, "rooms_x2 >= ?")
args = append(args, q.MinRoomsX2)
}
if !q.IncludeHidden {
sub, subArgs := s.hiddenSQL()
where = append(where, "(author, id) NOT IN ("+sub+")")
args = append(args, subArgs...)
}
limit := q.Limit
if limit <= 0 {
@@ -460,6 +507,17 @@ func (s *Store) PutRevocation(ctx context.Context, r *identity.Revocation) (Outc
if err != nil {
return Ignored, err
}
// Reports signed by a voided device do not count either.
if r.AllDevices() {
_, err = tx.ExecContext(ctx,
`DELETE FROM reports WHERE reporter = ? AND cert_issued_at < ?`, r.Author, r.RevokedAt)
} else {
_, err = tx.ExecContext(ctx,
`DELETE FROM reports WHERE reporter = ? AND device = ?`, r.Author, r.Device)
}
if err != nil {
return Ignored, err
}
if err := tx.Commit(); err != nil {
return Ignored, err
}
@@ -525,6 +583,12 @@ func (s *Store) Expire(ctx context.Context) (int64, error) {
if _, err := s.db.ExecContext(ctx, `DELETE FROM inbox_seen WHERE expires_at <= ?`, now); err != nil {
return n + m + k, err
}
if _, err := s.db.ExecContext(ctx, `DELETE FROM reports WHERE expires_at <= ?`, now); err != nil {
return n + m + k, err
}
if _, err := s.db.ExecContext(ctx, `DELETE FROM signals WHERE expires_at <= ?`, now); err != nil {
return n + m + k, err
}
if _, err := s.db.ExecContext(ctx, `
DELETE FROM inbox_blocked WHERE NOT EXISTS (
SELECT 1 FROM listings l WHERE l.author = inbox_blocked.author AND l.id = inbox_blocked.listing_id)`); err != nil {