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() }