mirror of
https://github.com/Kpa-clawbot/meshcore-analyzer.git
synced 2026-11-11 11:57:57 +00:00
Part of #2238. Path hops through such a repeater (`/api/nodes`, `/api/resolve-hops`, the frontend hop resolver) still show a bare prefix; that part of the issue stays open. ## Summary A repeater that never sends an advert can still tell a nearby companion its name. CoreDrive RX v1.20.0 asks for it (`ANON_REQ_TYPE_OWNER`) and publishes the answer as `NODE_NAME` on `meshcore/client/{pk}/names`. This PR stores those answers, resolves names with them, and shows these repeaters on the map, in the nodes list and in search, marked as self-reported. ### Ingestor: store the names - `367ecde1` adds a new `names` subtopic. - It is gated on `clientNodeNames.enabled`, default off. - Answers go into a new table, `client_node_names`: one row per observation, `UNIQUE(target, rx_pubkey, observed_at)`. - **Validation.** - `target` must be 64 hex. - The name is trimmed and rejected when it is empty, over 31 runes (firmware `node_name[32]`, `src/helpers/CommonCLI.h:29`), invalid UTF-8, or contains a control character. - **Retention.** `retention.clientNodeNamesDays` (0 = keep). `config.example.json` sets 30, like the other client tables: a companion only asks a repeater for its name when CoreScope has none (`nameMissing` in CoreDrive's `src/names.js`), so pruning is also how a renamed repeater gets its new name. - **Compatibility.** An ingestor without this change drops `/names` silently, so CoreDrive v1.20.0 works against either version. ### Server: resolve by the reported name - `11d97b36` makes `lookupPrefixes` count candidates in both `nodes` and `client_node_names`. `/api/nodes/resolve` and `batchResolveHeardKeys` (the coverage tooltips) both use it. - **Which name wins.** The advert name, otherwise the newest reported name by `observed_at`. A prefix that matches different pubkeys across the two tables stays ambiguous. - **Only repeaters heard directly.** A reported name counts only once its target has at least one `discover` or `advert` reception in `client_receptions`, keyed by the full pubkey, or by its 8-byte prefix when no other pubkey in `nodes`, `inactive_nodes` or `client_node_names` starts with that prefix (`clientNameHeard`). A name for a pubkey nobody heard adds no candidate, so it cannot make a real node's prefix ambiguous. Without the uniqueness check, a made-up pubkey that shares a heard repeater's first 8 bytes borrowed that repeater's receptions and passed (fixed in `4c569f91`). - **Filters.** The blacklist and the hidden name prefixes apply to both sources. - **Missing table.** A database without the table resolves from `nodes` alone, and the server checks for the table again until the ingestor has created it. - **Response shape.** `/api/nodes/resolve` keeps `{prefix, pubkey?, name?, ambiguous}`. ### Server: estimated position - `98c76957` adds `GET /api/nodes/reported`, documented in `openapi.go`. It lists every repeater in `client_node_names` that never sent an advert (no row in `nodes` or `inactive_nodes`) and was heard directly at least once (see above). A node with an advert but no position stays out: it is already in `/api/nodes` under its advert name. - **Gated** like the other endpoints on `client_receptions`: 404 when `clientRxCoverage.enabled` is off, because the counts and the estimate come from companion GPS fixes. - **Which receptions count.** Only direct ones: - `discover` and `advert` rows, keyed by the full pubkey, or by its 8-byte prefix when no other known pubkey shares it; - `rxlog` rows whose 2-3 byte hash resolves to this repeater alone. `geo` rows are left out. - **How the estimate is made.** - Receptions within 100 m form one spot, with the best SNR of that spot. - An estimate needs at least 3 spots, at least 200 m apart. - The position is the SNR-weighted centroid (`10^(snr/20)`). The radius is the distance to the farthest spot, at least 500 m. - The response is cached for 5 minutes, and the compute time is logged. ### Map - `5fcde554` adds `public/map-estimated.js`, which draws each estimate on its own layer: - a hollow, dashed "≈" marker and a dashed uncertainty circle; - a popup with an "Estimated position" badge, the method, the caveat that one-sided driving skews the estimate, and a link to the coverage map; - a Display toggle, "Estimated positions": on by default, kept in localStorage, and also hidden by the repeater role filter and in route view. ### Nodes page and search - `12e6b345` adds a "Self-reported repeaters" section under the nodes table, on the All and Repeaters tabs, filtered by the search box. - **`#/nodes/<pubkey>`.** Where `/api/nodes/<pubkey>` answers 404, a self-reported detail view replaces "Node not found": - who reported the name; - the receptions; - the estimate, or why there is none; - links to the map and the coverage map. An unknown key still shows "Node not found". - **Header search** adds matching self-reported repeaters, tagged "self-reported". - **Unchanged on purpose.** `/api/nodes` and `/api/nodes/search` stay as they are. These repeaters have no packets, so the packet filters, the live view and the channel sender lookup must not match them. ### Docs - `03580437` corrects the `/regions` section of `docs/client-rx-coverage.md`: it named `clientRxCoverage.enabled` as the switch, but the code uses `clientRegions.enabled`. - The new subtopic, endpoint and config keys are documented in the same file. ## Trust Any companion the broker lets publish can report a name for any repeater, and the newest report wins. This is the same model as `/regions`. `clientRxCoverage.requireLinkedCompanion` limits it to linked companions. A report for a repeater nobody heard directly is stored but not used: it is not listed and adds no prefix candidate. A companion can still report a wrong name for a repeater that was heard. The same companion can also publish a fake `discover` reception for a made-up pubkey, so the "heard directly" check filters junk, not a malicious companion; `requireLinkedCompanion` is the control for that (its gate runs before the `/names` handler too). ## Performance - **`lookupPrefixes`** adds one term per key on `client_node_names`. - It matches the prefix as a range, `target >= ? AND target < ?` (upper bound prefix + `"g"`), not with `LIKE`: `LIKE` on this case-sensitive column cannot use the index. `EXPLAIN QUERY PLAN`: `SEARCH c USING INDEX idx_cnn_target (target>? AND target<?)`, and the reception check is `SEARCH r USING INDEX idx_client_recept_heard_geo (heard_key=?)`. - It is still one query per chunk of 200 keys: 400 compound terms, under SQLite's default limit of 500. - `TestLookupPrefixesManyKeys` covers 250 keys over two chunks. - **`/api/nodes/reported`** makes three kinds of query: - one grouped query on `client_node_names`; - one `lookupPrefixes` call for the short hashes; - one `IN` query per 400 keys on `client_receptions`, served by `idx_client_recept_heard_geo`. The spread check is O(spots²) per repeater, with at most one spot per 100 m visited. The result is cached for 5 minutes; concurrent misses wait for one computation, and the response is written after the lock is released. - **The map does not wait for it.** It draws its markers first and adds the estimates when the list arrives. The map and the nodes page share one cached fetch (`ReportedNodes.load()`). - **Not benchmarked.** On the instance where this runs, `client_node_names` holds one row today. I expect at most tens of such repeaters per instance, but have not measured that. ## Notes - **`map[string]interface{}`.** `cmd/ingestor/client_names.go` has 2 occurrences: the handler's `msg` parameter and its `gps` field. That is the decoded MQTT message, passed in the same shape as `handleClientPacket` and `handleClientRegions` already take it. No API response or internal structure uses it. - **Thresholds are hardcoded:** 100 m, 3 spots / 200 m, 500 m, 5 min TTL. They should move to the customizer later (rule 8). - **Map filters.** The estimates follow the "Estimated positions" toggle and the repeater role filter, not the area, region or last-heard filters. The toggle's tooltip says so. - **Name characters.** Names are rejected for control characters but not for Unicode format characters (bidi overrides, zero-width joiners), because emoji sequences in node names use the zero-width joiner. All output goes through `escapeHtml`. - **Not done:** the home-page search box (`home.js`, `/api/nodes/search` with a Claim button) does not list these repeaters. Claiming a node without adverts would have nothing to show. ## Tests On this branch (based on `550829af`): - `go vet ./...` and `go test -count=1 ./...` pass in `cmd/server` and `cmd/ingestor`. - **New Go tests:** - handler and validation cases; - idempotent redelivery; - newest `observed_at` wins; - prune; - the gate on and off, without falling through to the observer path; - client-only node, nameless `nodes` row, advert name wins, ambiguity across the two sources; - hidden and blacklisted nodes; - absent-then-created table; - spot merging, threshold, weighted centroid and radius floor; - `discover` / `rxlog` / `geo` handling, an ambiguous path hash, an advert position and a missing table; - an advert without a position, a never-heard name, a name heard only in `rxlog` paths, and the `clientRxCoverage` gate (404). These fail on `12e6b345` and pass at head. - a made-up pubkey sharing a heard repeater's 8-byte prefix, and two reported targets sharing one (`4c569f91`). Both fail without that commit. - **New frontend unit suites:** `tests/unit/test-map-estimated.js` and `tests/unit/test-reported-nodes.js` pass. Both load the real `escapeHtml` from `app.js`. - **`test-all.sh`** passes, all suites (with Python available for the XSS gate self-tests). `scripts/check-xss-sinks.sh --file` passes on the four changed frontend files. - **E2E**, against a static server with a mocked API: - `test-map-estimated-e2e.js`: 6/6, including the repeater role filter and route view hiding the estimates. Mutating either hide makes its step fail. - `test-reported-nodes-e2e.js`: 6/6. - `test-issue-1150-404-state-e2e.js`: 5/5. - **Real data, API only.** On the fork's staging, `/api/nodes/reported` lists one repeater: 5 spots, 17 receptions, an estimate with a radius of 2,305 m. It has no `nodes` row and 24 `discover` receptions, so it stays listed under the stricter rules. Not re-checked after `4c569f91`. - **Not done:** a check of that repeater in a browser. --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
436 lines
15 KiB
Go
436 lines
15 KiB
Go
package main
|
|
|
|
import (
|
|
"context"
|
|
"database/sql"
|
|
"encoding/json"
|
|
"log"
|
|
"net/http"
|
|
"sort"
|
|
"strconv"
|
|
"strings"
|
|
"time"
|
|
)
|
|
|
|
// scanCoverageRows reads (lat,lon,snr,rssi,heard_key,rx_at) rows into coverageRow values.
|
|
func scanCoverageRows(rows *sql.Rows) ([]coverageRow, error) {
|
|
out := []coverageRow{}
|
|
for rows.Next() {
|
|
var lat, lon float64
|
|
var snr sql.NullFloat64
|
|
var rssi sql.NullInt64
|
|
var heardKey, rxAt sql.NullString
|
|
if err := rows.Scan(&lat, &lon, &snr, &rssi, &heardKey, &rxAt); err != nil {
|
|
return nil, err
|
|
}
|
|
cr := coverageRow{Lat: lat, Lon: lon, HeardKey: strings.ToLower(heardKey.String), RxAt: rxAt.String}
|
|
if snr.Valid {
|
|
v := snr.Float64
|
|
cr.SNR = &v
|
|
}
|
|
if rssi.Valid {
|
|
v := int(rssi.Int64)
|
|
cr.RSSI = &v
|
|
}
|
|
out = append(out, cr)
|
|
}
|
|
return out, rows.Err()
|
|
}
|
|
|
|
// heardKeyResolverFor builds a nodeResolver for exactly the distinct heard_keys
|
|
// present in rows, resolving them all in one batched query instead of one query
|
|
// per key (the previous per-key resolver was N+1 on the read connection). Maps a
|
|
// heard_key to (pubkey, name) on a unique, non-hidden match; to (heardKey, "")
|
|
// otherwise. nil when there's no DB.
|
|
func (s *Server) heardKeyResolverFor(rows []coverageRow) nodeResolver {
|
|
if s.db == nil || s.db.conn == nil {
|
|
return nil
|
|
}
|
|
keys := make([]string, 0, len(rows))
|
|
seen := map[string]bool{}
|
|
for _, r := range rows {
|
|
if r.HeardKey != "" && !seen[r.HeardKey] {
|
|
seen[r.HeardKey] = true
|
|
keys = append(keys, r.HeardKey)
|
|
}
|
|
}
|
|
resolved := s.batchResolveHeardKeys(keys)
|
|
return func(heardKey string) (string, string) {
|
|
if v, ok := resolved[heardKey]; ok {
|
|
return v[0], v[1]
|
|
}
|
|
return heardKey, ""
|
|
}
|
|
}
|
|
|
|
// batchResolveHeardKeys resolves many heard_keys (2-3 byte prefixes or full
|
|
// pubkeys) to their canonical (pubkey, name) in a single round-trip per chunk
|
|
// (lookupPrefixes), so the whole set costs one query, not N. A unique match
|
|
// returns [pubkey, name], where name falls back to the repeater's own reported
|
|
// name (client_node_names) when nodes has none; unknown / ambiguous /
|
|
// blacklisted / hidden-prefix keys (#15, #1181) return [heardKey, ""].
|
|
func (s *Server) batchResolveHeardKeys(keys []string) map[string][2]string {
|
|
res := make(map[string][2]string, len(keys))
|
|
valid := make([]string, 0, len(keys))
|
|
seen := map[string]bool{}
|
|
for _, k := range keys {
|
|
if k == "" || seen[k] {
|
|
continue
|
|
}
|
|
seen[k] = true
|
|
if !hexPrefixRe.MatchString(k) {
|
|
res[k] = [2]string{k, ""}
|
|
continue
|
|
}
|
|
valid = append(valid, k)
|
|
}
|
|
hits := s.lookupPrefixes(valid)
|
|
for _, k := range valid {
|
|
if h, ok := hits[k]; ok && s.visible(h) {
|
|
res[k] = [2]string{h.pubkey, h.name}
|
|
} else {
|
|
res[k] = [2]string{k, ""}
|
|
}
|
|
}
|
|
return res
|
|
}
|
|
|
|
// resolveHeardKey resolves a single heard_key (2-3 byte prefix or full pubkey)
|
|
// to its canonical (pubkey, name), or (heardKey, "") when unknown / ambiguous /
|
|
// hidden. Thin wrapper over batchResolveHeardKeys so there is one code path.
|
|
func (s *Server) resolveHeardKey(heardKey string) (string, string) {
|
|
v := s.batchResolveHeardKeys([]string{heardKey})[heardKey]
|
|
if v[0] == "" && v[1] == "" {
|
|
return heardKey, "" // empty/unresolved → echo the key
|
|
}
|
|
return v[0], v[1]
|
|
}
|
|
|
|
// queryCoverageFiltered returns coverage rows within a bbox, optionally filtered
|
|
// by heard node (prefix/pubkey), contributing client (rx_pubkey), and time window
|
|
// (days; 0 = all time). Powers the global and per-observer coverage maps.
|
|
// rxIn, when non-nil, keeps only receptions by those companions (rx_pubkey,
|
|
// lowercase); an empty non-nil rxIn matches nothing.
|
|
func (s *Server) queryCoverageFiltered(node, rx string, rxIn []string, days int, b bbox) ([]coverageRow, error) {
|
|
if rxIn != nil && len(rxIn) == 0 {
|
|
return nil, nil
|
|
}
|
|
where := []string{"lat BETWEEN ? AND ?", "lon BETWEEN ? AND ?"}
|
|
args := []interface{}{b.MinLat, b.MaxLat, b.MinLon, b.MaxLon}
|
|
if node != "" {
|
|
// Sargable heard_key IN-list (see coverageHeardKeyCandidates) so the
|
|
// (heard_key, …) composite index is used instead of a substr() scan (#5).
|
|
cands := coverageHeardKeyCandidates(node)
|
|
where = append(where, "heard_key IN ("+sqlPlaceholders(len(cands))+")")
|
|
for _, c := range cands {
|
|
args = append(args, c)
|
|
}
|
|
}
|
|
if rx != "" {
|
|
where = append(where, "rx_pubkey = ?")
|
|
args = append(args, strings.ToLower(rx))
|
|
}
|
|
if len(rxIn) > 0 {
|
|
where = append(where, "rx_pubkey IN ("+sqlPlaceholders(len(rxIn))+")")
|
|
for _, pk := range rxIn {
|
|
args = append(args, pk)
|
|
}
|
|
}
|
|
if days > 0 {
|
|
since := time.Now().UTC().AddDate(0, 0, -days).Format(time.RFC3339)
|
|
where = append(where, "rx_at >= ?")
|
|
args = append(args, since)
|
|
}
|
|
rows, err := s.db.conn.Query("SELECT lat, lon, snr, rssi, heard_key, rx_at FROM client_receptions WHERE "+strings.Join(where, " AND "), args...)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer rows.Close()
|
|
return scanCoverageRows(rows)
|
|
}
|
|
|
|
// handleRxCoverage serves global (or per-observer via ?rx=) coverage as GeoJSON
|
|
// hexbins, over a time window. ?node= also works (same as the per-node endpoint).
|
|
// requireClientRxCoverage writes a 404 and returns false when the opt-in
|
|
// client-RX coverage feature is disabled, so the coverage endpoints read as
|
|
// "not found" instead of serving data on deployments that haven't enabled it.
|
|
func (s *Server) requireClientRxCoverage(w http.ResponseWriter, r *http.Request) bool {
|
|
// Routes are registered unconditionally, so guard against a nil server/cfg
|
|
// (e.g. handlers exercised in isolation) rather than panicking (#4).
|
|
// ClientRxCoverageEnabled is itself nil-receiver-safe.
|
|
if s == nil || s.cfg == nil || !s.cfg.ClientRxCoverageEnabled() {
|
|
http.NotFound(w, r)
|
|
return false
|
|
}
|
|
return true
|
|
}
|
|
|
|
func (s *Server) handleRxCoverage(w http.ResponseWriter, r *http.Request) {
|
|
if !s.requireClientRxCoverage(w, r) {
|
|
return
|
|
}
|
|
var mine []string
|
|
if r.URL.Query().Get("mine") == "1" {
|
|
var ok bool
|
|
if mine, ok = s.myCompanionPubkeys(w, r); !ok {
|
|
return
|
|
}
|
|
}
|
|
b, ok := parseBBox(r.URL.Query().Get("bbox"))
|
|
if !ok {
|
|
http.Error(w, "bbox required as minLat,minLon,maxLat,maxLon", http.StatusBadRequest)
|
|
return
|
|
}
|
|
if s.db == nil || s.db.conn == nil {
|
|
http.Error(w, "unavailable", http.StatusServiceUnavailable)
|
|
return
|
|
}
|
|
days := clampDays(atoiDefault(r.URL.Query().Get("days"), 7))
|
|
z, _ := strconv.Atoi(r.URL.Query().Get("z"))
|
|
node, rx := r.URL.Query().Get("node"), r.URL.Query().Get("rx")
|
|
rows, err := s.queryCoverageFiltered(node, rx, mine, days, b)
|
|
if err != nil {
|
|
http.Error(w, "query failed", http.StatusInternalServerError)
|
|
return
|
|
}
|
|
fc := aggregateCoverage(rows, zoomToHexRes(z), s.heardKeyResolverFor(rows))
|
|
// "Nothing received" cells need the track, so only with the RF sample
|
|
// stream on; with ?node= the question would be "this node not heard",
|
|
// which these cells do not answer. Not with ?mine=1 either: the track
|
|
// query cannot narrow to a set of companions yet.
|
|
if r.URL.Query().Get("gaps") == "1" && node == "" && mine == nil && s.cfg.ClientRfSamplesEnabled() {
|
|
track, err := s.queryTrackPoints(rx, days, b)
|
|
if err != nil {
|
|
http.Error(w, "query failed", http.StatusInternalServerError)
|
|
return
|
|
}
|
|
fc.Gaps, fc.GapsTruncated = aggregateGaps(track, rows, zoomToHexRes(z))
|
|
}
|
|
w.Header().Set("Content-Type", "application/json")
|
|
json.NewEncoder(w).Encode(fc)
|
|
}
|
|
|
|
// myCompanionPubkeys resolves ?mine=1 to the caller's linked companions
|
|
// (never nil, so an empty list filters everything out). Browser session
|
|
// only: 404 with user management off, 403 for a bearer token (coverage is
|
|
// outside its scope), 401 without a session.
|
|
func (s *Server) myCompanionPubkeys(w http.ResponseWriter, r *http.Request) ([]string, bool) {
|
|
if s.auth == nil {
|
|
http.NotFound(w, r)
|
|
return nil, false
|
|
}
|
|
if _, ok := bearerToken(r); ok {
|
|
writeBearerFail(w, http.StatusForbidden)
|
|
return nil, false
|
|
}
|
|
u, _ := s.auth.currentUser(w, r)
|
|
if u == nil {
|
|
writeError(w, http.StatusUnauthorized, "not logged in")
|
|
return nil, false
|
|
}
|
|
links, err := s.auth.st.ListCompanionLinks(u.ID)
|
|
if err != nil {
|
|
log.Printf("[users] coverage mine for user #%d: %v", u.ID, err)
|
|
http.Error(w, "query failed", http.StatusInternalServerError)
|
|
return nil, false
|
|
}
|
|
out := make([]string, 0, len(links))
|
|
for _, l := range links {
|
|
out = append(out, l.Pubkey)
|
|
}
|
|
return out, true
|
|
}
|
|
|
|
// --- Leaderboard (top mobile observers) ---
|
|
|
|
type LeaderObserver struct {
|
|
Pubkey string `json:"pubkey"`
|
|
Name string `json:"name"`
|
|
Receptions int `json:"receptions"`
|
|
Nodes int `json:"nodes"`
|
|
Cells int `json:"cells"` // distinct fixed-res hex cells covered
|
|
Score float64 `json:"score"` // frontier-weighted coverage score
|
|
}
|
|
type RxLeaderboardResp struct {
|
|
Days int `json:"days"`
|
|
Observers []LeaderObserver `json:"observers"`
|
|
}
|
|
|
|
// leaderboardHexRes is the fixed hex resolution used to bucket receptions into
|
|
// "cells visited" for the frontier-weighted score. ~150 m ground cells at our
|
|
// latitude: coarse enough that a parked node's GPS jitter stays in one cell,
|
|
// fine enough that real driving paints many. Independent of the coverage map's
|
|
// zoom-dependent render resolution so the ranking is stable across views.
|
|
const leaderboardHexRes = 13
|
|
|
|
// leaderboardScanCap bounds how many rows the leaderboard aggregates in memory.
|
|
// The endpoint is unauthenticated (only requireClientRxCoverage), and the Go-side
|
|
// rarity weighting can't push the GROUP BY into SQLite, so without a cap a wide
|
|
// window on a busy network would stream the whole table into maps. At the cap we
|
|
// log and return a partial (best-effort) ranking rather than OOM (#review r2).
|
|
const leaderboardScanCap = 500000
|
|
|
|
// rxLeaderboard ranks mobile observers by frontier-weighted cell coverage over
|
|
// the time window. Each distinct cell an observer covers contributes
|
|
// 1/(observers covering that cell): a cell only they reached weighs 1.0, a cell
|
|
// shared by N observers weighs 1/N. This rewards expanding the map's edge and is
|
|
// spam-proof — a stationary node covers exactly one cell regardless of how many
|
|
// receptions it logs. Bucketing + the rarity weight can't be expressed in SQL,
|
|
// so we aggregate the window's rows in Go (bounded by leaderboardScanCap).
|
|
func (s *Server) rxLeaderboard(ctx context.Context, days, limit int) ([]LeaderObserver, error) {
|
|
since := time.Now().UTC().AddDate(0, 0, -days).Format(time.RFC3339)
|
|
// Name preference: the node's advertised name, else the companion's
|
|
// self-reported name (client_observers), else empty (UI shows the prefix).
|
|
// Hard LIMIT bounds memory; ORDER BY rx_at DESC so a truncated window keeps
|
|
// the most recent receptions.
|
|
rows, err := s.db.conn.QueryContext(ctx, `
|
|
SELECT cr.rx_pubkey, COALESCE(NULLIF(n.name,''), NULLIF(co.name,''), ''),
|
|
cr.lat, cr.lon, cr.heard_key
|
|
FROM client_receptions cr
|
|
LEFT JOIN nodes n ON n.public_key = cr.rx_pubkey
|
|
LEFT JOIN client_observers co ON co.pubkey = cr.rx_pubkey
|
|
WHERE cr.rx_at >= ?
|
|
ORDER BY cr.rx_at DESC
|
|
LIMIT ?`, since, leaderboardScanCap)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer rows.Close()
|
|
|
|
type agg struct {
|
|
name string
|
|
receptions int
|
|
cells map[string]struct{}
|
|
nodes map[string]struct{}
|
|
}
|
|
obsAgg := map[string]*agg{}
|
|
cellObservers := map[string]map[string]struct{}{} // cell -> set of rx_pubkey
|
|
|
|
scanned := 0
|
|
for rows.Next() {
|
|
// Honour client cancellation/timeout on the long scan (checked in batches
|
|
// to avoid a per-row context mutex on up to 500k rows).
|
|
if scanned&2047 == 0 && ctx.Err() != nil {
|
|
return nil, ctx.Err()
|
|
}
|
|
var pk, name, heardKey string
|
|
var lat, lon float64
|
|
if err := rows.Scan(&pk, &name, &lat, &lon, &heardKey); err != nil {
|
|
return nil, err
|
|
}
|
|
scanned++
|
|
a := obsAgg[pk]
|
|
if a == nil {
|
|
a = &agg{name: name, cells: map[string]struct{}{}, nodes: map[string]struct{}{}}
|
|
obsAgg[pk] = a
|
|
}
|
|
a.receptions++
|
|
a.nodes[heardKey] = struct{}{}
|
|
cell := hexCellAt(lat, lon, leaderboardHexRes)
|
|
a.cells[cell] = struct{}{}
|
|
set := cellObservers[cell]
|
|
if set == nil {
|
|
set = map[string]struct{}{}
|
|
cellObservers[cell] = set
|
|
}
|
|
set[pk] = struct{}{}
|
|
}
|
|
if err := rows.Err(); err != nil {
|
|
return nil, err
|
|
}
|
|
if scanned >= leaderboardScanCap {
|
|
log.Printf("[rx-leaderboard] scan hit cap %d over %dd window; ranking is partial (most-recent rows)", leaderboardScanCap, days)
|
|
}
|
|
|
|
// Per-cell observer counts EXCLUDING blacklisted contributors, so an operator
|
|
// of a blacklisted node parked in a cell can't silently dilute everyone else's
|
|
// frontier weight (#review r2). Name-hidden (not blacklisted) observers are
|
|
// legitimate contributors and still count.
|
|
cellCount := make(map[string]int, len(cellObservers))
|
|
for cell, set := range cellObservers {
|
|
n := 0
|
|
for pk := range set {
|
|
if !s.cfg.IsObserverBlacklisted(pk) && !s.cfg.IsBlacklisted(pk) {
|
|
n++
|
|
}
|
|
}
|
|
cellCount[cell] = n
|
|
}
|
|
|
|
out := make([]LeaderObserver, 0, len(obsAgg))
|
|
for pk, a := range obsAgg {
|
|
var score float64
|
|
for cell := range a.cells {
|
|
if c := cellCount[cell]; c > 0 {
|
|
score += 1.0 / float64(c)
|
|
}
|
|
}
|
|
out = append(out, LeaderObserver{
|
|
Pubkey: pk,
|
|
Name: a.name,
|
|
Receptions: a.receptions,
|
|
Nodes: len(a.nodes),
|
|
Cells: len(a.cells),
|
|
Score: score,
|
|
})
|
|
}
|
|
|
|
// Rank by frontier score; ties broken by raw receptions then pubkey so the
|
|
// order is deterministic (keeps same-location fixtures stable).
|
|
sort.Slice(out, func(i, j int) bool {
|
|
if out[i].Score != out[j].Score {
|
|
return out[i].Score > out[j].Score
|
|
}
|
|
if out[i].Receptions != out[j].Receptions {
|
|
return out[i].Receptions > out[j].Receptions
|
|
}
|
|
return out[i].Pubkey < out[j].Pubkey
|
|
})
|
|
|
|
// Identity hiding parity (#1727 r2): drop observer-blacklisted contributors,
|
|
// blank node-blacklisted / hidden-prefix names, cap at limit. nil cfg ⇒ no-ops.
|
|
filtered := make([]LeaderObserver, 0, limit)
|
|
for _, o := range out {
|
|
if s.cfg.IsObserverBlacklisted(o.Pubkey) {
|
|
continue
|
|
}
|
|
if s.cfg.IsBlacklisted(o.Pubkey) || s.cfg.IsNameHidden(o.Name) {
|
|
o.Name = ""
|
|
}
|
|
filtered = append(filtered, o)
|
|
if len(filtered) >= limit {
|
|
break
|
|
}
|
|
}
|
|
return filtered, nil
|
|
}
|
|
|
|
func (s *Server) handleRxLeaderboard(w http.ResponseWriter, r *http.Request) {
|
|
if !s.requireClientRxCoverage(w, r) {
|
|
return
|
|
}
|
|
if s.db == nil || s.db.conn == nil {
|
|
http.Error(w, "unavailable", http.StatusServiceUnavailable)
|
|
return
|
|
}
|
|
days := clampDays(atoiDefault(r.URL.Query().Get("days"), 7))
|
|
limit := atoiDefault(r.URL.Query().Get("limit"), 20)
|
|
if limit < 1 || limit > 100 {
|
|
limit = 20
|
|
}
|
|
obs, err := s.rxLeaderboard(r.Context(), days, limit)
|
|
if err != nil {
|
|
http.Error(w, "query failed", http.StatusInternalServerError)
|
|
return
|
|
}
|
|
w.Header().Set("Content-Type", "application/json")
|
|
json.NewEncoder(w).Encode(RxLeaderboardResp{Days: days, Observers: obs})
|
|
}
|
|
|
|
func atoiDefault(s string, d int) int {
|
|
if n, err := strconv.Atoi(strings.TrimSpace(s)); err == nil {
|
|
return n
|
|
}
|
|
return d
|
|
}
|