diff --git a/Dockerfile b/Dockerfile index 76514d2a9..e94d7c655 100644 --- a/Dockerfile +++ b/Dockerfile @@ -56,6 +56,7 @@ ENV CC=zigcc CGO_ENABLED=1 # Build server WORKDIR /build/server COPY cmd/server/go.mod cmd/server/go.sum ./ +COPY internal/areamap/ ../../internal/areamap/ COPY internal/geofilter/ ../../internal/geofilter/ COPY internal/sigvalidate/ ../../internal/sigvalidate/ COPY internal/packetpath/ ../../internal/packetpath/ diff --git a/cmd/server/areas.go b/cmd/server/areas.go new file mode 100644 index 000000000..d102d7796 --- /dev/null +++ b/cmd/server/areas.go @@ -0,0 +1,76 @@ +package main + +import ( + "fmt" + "os" + "path/filepath" + "sort" + + "github.com/meshcore-analyzer/areamap" +) + +// LoadAreaMap builds the map of every area: config.json's areas (layer +// "region") and the features of AreasFile. It stores the map on cfg, where +// the store and the handlers find it. A code defined twice, a missing file +// or a file that is not GeoJSON is an error: the caller refuses to start +// rather than run with areas silently missing. +func LoadAreaMap(cfg *Config, configDir string) (*areamap.Map, error) { + var areas []areamap.Area + keys := make([]string, 0, len(cfg.Areas)) + for k := range cfg.Areas { + keys = append(keys, k) + } + sort.Strings(keys) + for _, k := range keys { + e := cfg.Areas[k] + if e.Label == "" { + continue // "_comment" and other non-areas + } + var ring [][2]float64 + switch { + case len(e.Polygon) >= 3: + // config.json polygons are [lat, lon]; GeoJSON rings are [lon, lat]. + for _, p := range e.Polygon { + ring = append(ring, [2]float64{p[1], p[0]}) + } + case e.LatMin != nil && e.LatMax != nil && e.LonMin != nil && e.LonMax != nil: + ring = [][2]float64{{*e.LonMin, *e.LatMin}, {*e.LonMax, *e.LatMin}, {*e.LonMax, *e.LatMax}, {*e.LonMin, *e.LatMax}} + default: + continue // listed by name only, with nothing to locate against + } + areas = append(areas, areamap.Area{Code: k, Label: e.Label, Layer: areamap.DefaultLayer, Polygons: [][][][2]float64{{ring}}}) + } + if cfg.AreasFile != "" { + path := cfg.AreasFile + if !filepath.IsAbs(path) { + path = filepath.Join(configDir, path) + } + data, err := os.ReadFile(path) + if err != nil { + return nil, fmt.Errorf("areasFile: %w", err) + } + fromFile, err := areamap.ParseGeoJSON(data) + if err != nil { + return nil, fmt.Errorf("areasFile %s: %w", path, err) + } + areas = append(areas, fromFile...) + } + m, err := areamap.New(areas) + if err != nil { + return nil, err + } + cfg.areaMap = m + return m, nil +} + +// fileArea reports whether code names an area that only the areas file +// defines, so area= resolves it by position instead of config.json's entry. +func (c *Config) fileArea(code string) bool { + if c == nil || c.areaMap == nil { + return false + } + if _, inConfig := c.Areas[code]; inConfig { + return false + } + return c.areaMap.Has(code) +} diff --git a/cmd/server/areas_test.go b/cmd/server/areas_test.go new file mode 100644 index 000000000..cd62d6f8d --- /dev/null +++ b/cmd/server/areas_test.go @@ -0,0 +1,137 @@ +package main + +import ( + "encoding/json" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "testing" + + "github.com/gorilla/mux" + "github.com/meshcore-analyzer/areamap" +) + +// A rough Scotland on the "country" layer, in GeoJSON's [lon, lat] order. +const scotlandGeoJSON = `{"type":"FeatureCollection","features":[ + {"type":"Feature","properties":{"code":"SCO","label":"Scotland","layer":"country","iata":["EDI"]}, + "geometry":{"type":"Polygon","coordinates":[[[-7.5,55.0],[-1.5,55.0],[-1.5,60.9],[-7.5,60.9],[-7.5,55.0]]]}}]}` + +func writeAreasFile(t *testing.T, body string) string { + t.Helper() + dir := t.TempDir() + if err := os.WriteFile(filepath.Join(dir, "areas.geojson"), []byte(body), 0o644); err != nil { + t.Fatal(err) + } + return dir +} + +func belgium() map[string]AreaEntry { + return map[string]AreaEntry{ + "BEL": {Label: "Belgium", Polygon: [][2]float64{{50.0, 2.5}, {51.5, 2.5}, {51.5, 6.4}, {50.0, 6.4}}}, + "_comment": {}, + } +} + +func TestLoadAreaMapReadsConfigAreasAndTheFile(t *testing.T) { + dir := writeAreasFile(t, scotlandGeoJSON) + cfg := &Config{Areas: belgium(), AreasFile: "areas.geojson"} + m, err := LoadAreaMap(cfg, dir) + if err != nil { + t.Fatal(err) + } + if cfg.areaMap != m { + t.Error("the map must be kept on the config for the store and handlers") + } + // config.json polygons are [lat, lon]; they must land the right way round. + if got, _ := m.Locate(areamap.DefaultLayer, 50.85, 4.35); got != "BEL" { + t.Errorf("Brussels = %q, want BEL from config.json", got) + } + if got, _ := m.Locate("country", 55.95, -3.19); got != "SCO" { + t.Errorf("Edinburgh = %q, want SCO from the file", got) + } + if got, _ := m.LocateIATA("country", "edi"); got != "SCO" { + t.Errorf("EDI = %q, want SCO", got) + } +} + +func TestLoadAreaMapRefusesBadFiles(t *testing.T) { + dup := `{"type":"FeatureCollection","features":[{"type":"Feature","properties":{"code":"BEL","label":"Again"},"geometry":{"type":"Polygon","coordinates":[[[0,0],[1,0],[1,1],[0,0]]]}}]}` + cases := map[string]struct { + body, file string + }{ + "a code also in config.json": {dup, "areas.geojson"}, + "a missing file": {scotlandGeoJSON, "nope.geojson"}, + "not GeoJSON": {`{`, "areas.geojson"}, + } + for name, c := range cases { + dir := writeAreasFile(t, c.body) + if _, err := LoadAreaMap(&Config{Areas: belgium(), AreasFile: c.file}, dir); err == nil { + t.Errorf("%s: accepted, want an error", name) + } + } + if m, err := LoadAreaMap(&Config{}, t.TempDir()); err != nil || len(m.Areas("")) != 0 { + t.Errorf("no areas at all = %v, %v; want an empty map and no error", m, err) + } +} + +func TestHandleConfigAreasListsFileAreasWithTheirLayer(t *testing.T) { + dir := writeAreasFile(t, scotlandGeoJSON) + cfg := &Config{Areas: belgium(), AreasFile: "areas.geojson"} + if _, err := LoadAreaMap(cfg, dir); err != nil { + t.Fatal(err) + } + r := mux.NewRouter() + srv := &Server{db: setupTestDBv2(t), cfg: cfg} + r.HandleFunc("/api/config/areas", srv.handleConfigAreas).Methods("GET") + w := httptest.NewRecorder() + r.ServeHTTP(w, httptest.NewRequest(http.MethodGet, "/api/config/areas", nil)) + var got []map[string]string + if err := json.NewDecoder(w.Body).Decode(&got); err != nil { + t.Fatal(err) + } + layers := map[string]string{} + for _, a := range got { + layers[a["key"]] = a["layer"] + } + if len(got) != 2 || layers["BEL"] != areamap.DefaultLayer || layers["SCO"] != "country" { + t.Errorf("areas = %v, want BEL (region) and SCO (country)", got) + } +} + +func TestAreaFilterWorksForFileAreas(t *testing.T) { + db := setupTestDBv2(t) + mustExecDB(t, db, `INSERT INTO nodes (public_key, lat, lon) VALUES ('edinburgh', 55.95, -3.19)`) + mustExecDB(t, db, `INSERT INTO nodes (public_key, lat, lon) VALUES ('newcastle', 54.97, -1.61)`) + mustExecDB(t, db, `INSERT INTO nodes (public_key, lat, lon) VALUES ('dublin', 53.35, -6.26)`) + dir := writeAreasFile(t, scotlandGeoJSON) + cfg := &Config{AreasFile: "areas.geojson"} + if _, err := LoadAreaMap(cfg, dir); err != nil { + t.Fatal(err) + } + s := newTestStoreWithDB(t, db, cfg) + got := s.resolveAreaNodes("SCO") + if len(got) != 1 || !got["edinburgh"] { + t.Errorf("nodes in SCO = %v, want only edinburgh", got) + } + // config.json areas keep their own path, unchanged. + cfg.Areas = belgium() + if got := s.resolveAreaNodes("BEL"); got != nil { + t.Errorf("no Belgian nodes, got %v", got) + } +} + +// The example in docs/ must load as documented. +func TestTheDocumentedExampleAreasFileLoads(t *testing.T) { + cfg := &Config{AreasFile: "../../docs/examples/areas.example.geojson"} + m, err := LoadAreaMap(cfg, ".") + if err != nil { + t.Fatal(err) + } + if got, _ := m.Locate(areamap.DefaultLayer, 37.34, -121.89); got != "BAY" { + t.Errorf("San Jose = %q, want BAY", got) + } + if got, _ := m.LocateIATA(areamap.DefaultLayer, "MRY"); got != "MRY" { + t.Errorf("observer MRY = %q, want MRY", got) + } +} diff --git a/cmd/server/config.go b/cmd/server/config.go index efa6ed279..775ab4123 100644 --- a/cmd/server/config.go +++ b/cmd/server/config.go @@ -11,6 +11,7 @@ import ( "sync/atomic" "time" + "github.com/meshcore-analyzer/areamap" "github.com/meshcore-analyzer/dbconfig" "github.com/meshcore-analyzer/geofilter" "github.com/meshcore-analyzer/packetpath" @@ -24,6 +25,9 @@ type AreaEntry struct { LatMax *float64 `json:"latMax,omitempty"` LonMin *float64 `json:"lonMin,omitempty"` LonMax *float64 `json:"lonMax,omitempty"` + // match, when set, decides membership instead of the polygon or box: an + // area from areasFile, tested against its GeoJSON geometry. + match func(lat, lon float64) bool } // ListLimitsConfig defines maximum row limits for list endpoints to prevent DoS. @@ -139,6 +143,14 @@ type Config struct { GeoFilter *GeoFilterConfig `json:"geo_filter,omitempty"` Areas map[string]AreaEntry `json:"areas,omitempty"` + // AreasFile names a GeoJSON FeatureCollection of further areas, relative + // to the config directory: real boundaries (coastlines, islands, holes) + // in layers, which config.json's polygons cannot hold. See + // internal/areamap for the feature properties it reads. + AreasFile string `json:"areasFile,omitempty"` + // areaMap holds every area, from Areas and AreasFile, once LoadAreaMap + // has run. Nil until then. + areaMap *areamap.Map Timestamps *TimestampConfig `json:"timestamps,omitempty"` diff --git a/cmd/server/db.go b/cmd/server/db.go index b396a266d..9c2c6fc15 100644 --- a/cmd/server/db.go +++ b/cmd/server/db.go @@ -3190,6 +3190,10 @@ func (db *DB) GetNodePubkeysInArea(entry AreaEntry) ([]string, error) { LonMin: entry.LonMin, LonMax: entry.LonMax, } + inside := func(lat, lon float64) bool { return geofilter.PassesFilter(lat, lon, gf) } + if entry.match != nil { + inside = entry.match + } var result []string for rows.Next() { @@ -3205,7 +3209,7 @@ func (db *DB) GetNodePubkeysInArea(entry AreaEntry) ([]string, error) { if lat.Float64 == 0 && lon.Float64 == 0 { continue } - if geofilter.PassesFilter(lat.Float64, lon.Float64, gf) { + if inside(lat.Float64, lon.Float64) { result = append(result, pk) } } diff --git a/cmd/server/go.mod b/cmd/server/go.mod index badbe96db..c2fb40d7a 100644 --- a/cmd/server/go.mod +++ b/cmd/server/go.mod @@ -5,10 +5,13 @@ go 1.22 require ( github.com/gorilla/mux v1.8.1 github.com/gorilla/websocket v1.5.3 + github.com/meshcore-analyzer/areamap v0.0.0 github.com/meshcore-analyzer/geofilter v0.0.0 github.com/meshcore-analyzer/sigvalidate v0.0.0 ) +replace github.com/meshcore-analyzer/areamap => ../../internal/areamap + replace github.com/meshcore-analyzer/geofilter => ../../internal/geofilter replace github.com/meshcore-analyzer/sigvalidate => ../../internal/sigvalidate diff --git a/cmd/server/main.go b/cmd/server/main.go index 58a679825..b281e0f49 100644 --- a/cmd/server/main.go +++ b/cmd/server/main.go @@ -105,6 +105,14 @@ func main() { if err != nil { log.Printf("[config] warning: %v (using defaults)", err) } + // Areas from config.json and areasFile. A bad areas file stops startup: + // running with areas silently missing would put packets in the wrong + // place without anyone noticing. + if am, err := LoadAreaMap(cfg, configDir); err != nil { + log.Fatalf("[areas] %v", err) + } else if n := len(am.Areas("")); n > 0 { + log.Printf("[areas] %d areas in layers %v", n, am.Layers()) + } // CLI flags override config if port > 0 { diff --git a/cmd/server/routes.go b/cmd/server/routes.go index 066404d6c..8726e8f34 100644 --- a/cmd/server/routes.go +++ b/cmd/server/routes.go @@ -6,6 +6,7 @@ import ( "encoding/json" "errors" "fmt" + "github.com/meshcore-analyzer/areamap" "log" "math" "net/http" @@ -541,13 +542,22 @@ func (s *Server) handleConfigAreas(w http.ResponseWriter, r *http.Request) { type areaListEntry struct { Key string `json:"key"` Label string `json:"label"` + Layer string `json:"layer"` } result := make([]areaListEntry, 0, len(s.cfg.Areas)) for k, v := range s.cfg.Areas { if v.Label == "" { continue // skip comment/invalid entries (e.g. "_comment" keys in config) } - result = append(result, areaListEntry{Key: k, Label: v.Label}) + result = append(result, areaListEntry{Key: k, Label: v.Label, Layer: areamap.DefaultLayer}) + } + // Areas from areasFile, in the file's order, with their layer. + if s.cfg.areaMap != nil { + for _, a := range s.cfg.areaMap.Areas("") { + if s.cfg.fileArea(a.Code) { + result = append(result, areaListEntry{Key: a.Code, Label: a.Label, Layer: a.Layer}) + } + } } writeJSON(w, result) } @@ -1594,8 +1604,13 @@ func (s *Server) handleNodes(w http.ResponseWriter, r *http.Request) { var areaNodes map[string]bool if s.store != nil { areaNodes = s.store.resolveAreaNodes(area) - } else if s.cfg != nil && s.cfg.Areas != nil { - if entry, ok := s.cfg.Areas[area]; ok { + } else if s.cfg != nil { + entry, ok := s.cfg.Areas[area] + if !ok && s.cfg.fileArea(area) { + m := s.cfg.areaMap + entry, ok = AreaEntry{match: func(lat, lon float64) bool { return m.Contains(area, lat, lon) }}, true + } + if ok { pks, err := s.db.GetNodePubkeysInArea(entry) if err == nil { areaNodes = make(map[string]bool, len(pks)) diff --git a/cmd/server/store.go b/cmd/server/store.go index 2d9552850..4e0e71125 100644 --- a/cmd/server/store.go +++ b/cmd/server/store.go @@ -3860,12 +3860,18 @@ const areaNodeTTL = 30 * time.Second // TTL is served as-is while one background refresh re-queries it (#2146). // Uses its own RWMutex so callers holding s.mu won't deadlock. func (s *PacketStore) resolveAreaNodes(areaKey string) map[string]bool { - if s.config == nil || s.config.Areas == nil { + if s.config == nil { return nil } entry, ok := s.config.Areas[areaKey] if !ok { - return nil + if !s.config.fileArea(areaKey) { + return nil + } + // An area from areasFile: matched by position against its GeoJSON + // geometry, through the same cache as config.json's areas. + m := s.config.areaMap + entry = AreaEntry{match: func(lat, lon float64) bool { return m.Contains(areaKey, lat, lon) }} } s.areaNodeMu.RLock() diff --git a/config.example.json b/config.example.json index 012a35ec6..e57bb948c 100644 --- a/config.example.json +++ b/config.example.json @@ -272,6 +272,8 @@ "mode": "flag", "_comment": "Controls how the ingestor handles ADVERTs whose GPS is OUTSIDE the geo_filter polygon (#730). 'flag' (default): store the advert/node and tag it foreign_advert=1 so operators can see bridged/leaked nodes via the API ('foreign': true on /api/nodes). 'drop': legacy behavior — silently discard the advert (no log, no node row). Only applies when geo_filter is configured; otherwise has no effect." }, + "_comment_areasFile": "Optional. A GeoJSON FeatureCollection of further areas, path relative to this file (or absolute). Use it for real boundaries that the polygons below cannot hold: coastlines, islands (MultiPolygon) and holes. Each feature is one area; its properties are code (required, unique across every area including those below), label, layer (default \"region\"; one file can hold several sets, such as countries and counties) and iata (airport codes of observers that report no position, so they still belong to an area). Coordinates are GeoJSON's [lon, lat]. Its areas join the area filter beside the ones below. A missing or invalid file stops the server at startup. Example: docs/examples/areas.example.geojson.", + "areasFile": "", "areas": { "_comment": "Optional. GPS-based display filter. Each entry defines a geographic area by polygon ([lat, lon] pairs) or bounding box (latMin/latMax/lonMin/lonMax). Packets and nodes are attributed to an area based on the transmitting node's own GPS coordinates — not the observer's location. Areas appear as a filter pill bar in the dashboard. Remove this section to disable the area filter UI.", "BAY": { diff --git a/docs/api-spec.md b/docs/api-spec.md index 9875009e8..6aca3370e 100644 --- a/docs/api-spec.md +++ b/docs/api-spec.md @@ -2252,22 +2252,23 @@ Returns a flat key-value object. ## GET /api/config/areas -Available area filters defined in `config.json` under `areas`. Used by the frontend to populate the area pill bar. Entries with an empty `label` (e.g. comment keys) are excluded. +Available area filters: those defined in `config.json` under `areas`, then those in the GeoJSON file named by `areasFile`, in the file's order. Used by the frontend to populate the area pill bar. Entries with an empty `label` (e.g. comment keys) are excluded. ### Response `200` ```jsonc [ { - "key": string, // area key as defined in config (e.g. "bayarea") - "label": string // display name (e.g. "Bay Area") + "key": string, // area key as defined in config (e.g. "bayarea"), or a feature's code in areasFile + "label": string, // display name (e.g. "Bay Area") + "layer": string // "region" for config.json areas; the feature's layer for areasFile areas } ] ``` Returns `[]` when no areas are configured. -**Note:** Polygon coordinates are **not** included. Use `/api/config/areas/polygons` for the full geometry. +**Note:** Polygon coordinates are **not** included. Use `/api/config/areas/polygons` for the full geometry of `config.json` areas; areas from `areasFile` are not repeated there (their geometry is the file itself). --- diff --git a/docs/examples/areas.example.geojson b/docs/examples/areas.example.geojson new file mode 100644 index 000000000..2512e0aaf --- /dev/null +++ b/docs/examples/areas.example.geojson @@ -0,0 +1,23 @@ +{ + "type": "FeatureCollection", + "features": [ + { + "type": "Feature", + "properties": { "code": "BAY", "label": "Bay Area", "layer": "region", "iata": ["SJC", "SFO", "OAK"] }, + "geometry": { + "type": "Polygon", + "coordinates": [[[-122.55, 37.90], [-121.75, 37.90], [-121.75, 37.25], [-122.55, 37.25], [-122.55, 37.90]]] + } + }, + { + "type": "Feature", + "properties": { "code": "MRY", "label": "Monterey Bay", "layer": "region", "iata": ["MRY"] }, + "geometry": { + "type": "MultiPolygon", + "coordinates": [ + [[[-122.05, 37.05], [-121.60, 37.05], [-121.60, 36.45], [-122.05, 36.45], [-122.05, 37.05]]] + ] + } + } + ] +} diff --git a/internal/areamap/areamap.go b/internal/areamap/areamap.go new file mode 100644 index 000000000..ca90363b9 --- /dev/null +++ b/internal/areamap/areamap.go @@ -0,0 +1,295 @@ +// Package areamap places a position in a named area: the regions a deployment +// draws for itself in a GeoJSON file, so packets and nodes can be attributed +// to where they are, not to the observer that heard them. +// +// Each feature of the FeatureCollection is one area. Its properties name it +// (code, label), put it in a layer (several sets of areas can share a file: +// countries, counties), and may list the airport codes of observers that +// report no position. Geometry is a Polygon or MultiPolygon, holes respected, +// in GeoJSON's [lon, lat] order. +package areamap + +import ( + "encoding/json" + "errors" + "fmt" + "math" + "strings" +) + +// DefaultLayer is the layer of an area that names none. +const DefaultLayer = "region" + +// Area is one named area. +type Area struct { + Code string + Label string + Layer string + // IATA lists airport codes of observers without a position that belong + // to this area. + IATA []string + // Polygons are the area's parts; each is an outer ring and its holes, in + // [lon, lat] order. + Polygons [][][][2]float64 +} + +// Info is an area without its geometry, for listings. +type Info struct { + Code string `json:"code"` + Label string `json:"label"` + Layer string `json:"layer"` +} + +// part is one polygon prepared for lookups: its rings and bounding box. +type part struct { + rings [][][2]float64 + minLon, minLat, maxLon, maxLat float64 +} + +type prepared struct { + Area + parts []part + size float64 // area in roughly square kilometres, to pick the smallest + iata map[string]bool +} + +// Map answers which area of a layer holds a position. +type Map struct { + areas []prepared + layers []string + byCode map[string]int +} + +// ErrDuplicate is returned when two areas share a code. +var ErrDuplicate = errors.New("areamap: duplicate area code") + +type geoJSON struct { + Type string `json:"type"` + Features []struct { + Type string `json:"type"` + Properties struct { + Code string `json:"code"` + Label string `json:"label"` + Layer string `json:"layer"` + IATA []string `json:"iata"` + } `json:"properties"` + Geometry struct { + Type string `json:"type"` + Coordinates json.RawMessage `json:"coordinates"` + } `json:"geometry"` + } `json:"features"` +} + +// ParseGeoJSON reads a FeatureCollection into areas. +func ParseGeoJSON(data []byte) ([]Area, error) { + var g geoJSON + if err := json.Unmarshal(data, &g); err != nil { + return nil, fmt.Errorf("areamap: %w", err) + } + if g.Type != "FeatureCollection" { + return nil, fmt.Errorf("areamap: want a FeatureCollection, got %q", g.Type) + } + out := make([]Area, 0, len(g.Features)) + for i, f := range g.Features { + p := f.Properties + code := strings.TrimSpace(p.Code) + if code == "" { + return nil, fmt.Errorf("areamap: feature %d has no code", i) + } + a := Area{Code: code, Label: strings.TrimSpace(p.Label), Layer: strings.TrimSpace(p.Layer), IATA: p.IATA} + if a.Label == "" { + a.Label = code + } + if a.Layer == "" { + a.Layer = DefaultLayer + } + switch f.Geometry.Type { + case "Polygon": + var poly [][][2]float64 + if err := json.Unmarshal(f.Geometry.Coordinates, &poly); err != nil { + return nil, fmt.Errorf("areamap: %s: %w", code, err) + } + a.Polygons = [][][][2]float64{poly} + case "MultiPolygon": + if err := json.Unmarshal(f.Geometry.Coordinates, &a.Polygons); err != nil { + return nil, fmt.Errorf("areamap: %s: %w", code, err) + } + default: + return nil, fmt.Errorf("areamap: %s: geometry %q is not a Polygon or MultiPolygon", code, f.Geometry.Type) + } + for _, poly := range a.Polygons { + if len(poly) == 0 { + return nil, fmt.Errorf("areamap: %s: a polygon with no rings", code) + } + for _, ring := range poly { + if len(ring) < 3 { + return nil, fmt.Errorf("areamap: %s: a ring needs at least three points", code) + } + } + } + out = append(out, a) + } + return out, nil +} + +// New builds a map. Codes must be unique across every layer. +func New(areas []Area) (*Map, error) { + m := &Map{byCode: make(map[string]int, len(areas))} + seenLayer := map[string]bool{} + for _, a := range areas { + if _, dup := m.byCode[a.Code]; dup { + return nil, fmt.Errorf("%w: %s", ErrDuplicate, a.Code) + } + if a.Layer == "" { + a.Layer = DefaultLayer + } + p := prepared{Area: a, iata: map[string]bool{}} + for _, c := range a.IATA { + p.iata[strings.ToUpper(strings.TrimSpace(c))] = true + } + for _, poly := range a.Polygons { + pt := part{rings: poly, minLon: math.Inf(1), minLat: math.Inf(1), maxLon: math.Inf(-1), maxLat: math.Inf(-1)} + for _, c := range poly[0] { + pt.minLon, pt.maxLon = math.Min(pt.minLon, c[0]), math.Max(pt.maxLon, c[0]) + pt.minLat, pt.maxLat = math.Min(pt.minLat, c[1]), math.Max(pt.maxLat, c[1]) + } + p.parts = append(p.parts, pt) + for i, ring := range poly { + s := ringSize(ring) + if i > 0 { + s = -s + } + p.size += s + } + } + m.byCode[a.Code] = len(m.areas) + m.areas = append(m.areas, p) + if !seenLayer[a.Layer] { + seenLayer[a.Layer] = true + m.layers = append(m.layers, a.Layer) + } + } + return m, nil +} + +// ringSize is a ring's area in roughly square kilometres: the shoelace sum +// with longitude scaled by the cosine of the ring's mean latitude. It only +// has to order overlapping areas by size. +func ringSize(ring [][2]float64) float64 { + var lat float64 + for _, c := range ring { + lat += c[1] + } + k := math.Cos(lat / float64(len(ring)) * math.Pi / 180) + var s float64 + for i, j := 0, len(ring)-1; i < len(ring); j, i = i, i+1 { + s += (ring[j][0]*k)*ring[i][1] - (ring[i][0]*k)*ring[j][1] + } + return math.Abs(s) / 2 * 111.32 * 111.32 +} + +// inRing is the even-odd test on one ring, x = lon, y = lat. +func inRing(ring [][2]float64, lat, lon float64) bool { + in := false + for i, j := 0, len(ring)-1; i < len(ring); j, i = i, i+1 { + xi, yi := ring[i][0], ring[i][1] + xj, yj := ring[j][0], ring[j][1] + if (yi > lat) != (yj > lat) && lon < (xj-xi)*(lat-yi)/(yj-yi)+xi { + in = !in + } + } + return in +} + +func (p *prepared) contains(lat, lon float64) bool { + for i := range p.parts { + pt := &p.parts[i] + if lon < pt.minLon || lon > pt.maxLon || lat < pt.minLat || lat > pt.maxLat { + continue + } + if !inRing(pt.rings[0], lat, lon) { + continue + } + hole := false + for _, h := range pt.rings[1:] { + if inRing(h, lat, lon) { + hole = true + break + } + } + if !hole { + return true + } + } + return false +} + +// Layers lists the layers, in the order their first area appeared. +func (m *Map) Layers() []string { return append([]string(nil), m.layers...) } + +// Areas lists one layer's areas, or every area when layer is "". +func (m *Map) Areas(layer string) []Info { + out := []Info{} + for i := range m.areas { + a := &m.areas[i] + if layer == "" || a.Layer == layer { + out = append(out, Info{Code: a.Code, Label: a.Label, Layer: a.Layer}) + } + } + return out +} + +// Locate returns the code of the smallest area of layer containing the +// position. 0,0 is an unset GPS, never a place. +func (m *Map) Locate(layer string, lat, lon float64) (string, bool) { + if m == nil || (lat == 0 && lon == 0) { + return "", false + } + best, bestSize := -1, math.Inf(1) + for i := range m.areas { + a := &m.areas[i] + if a.Layer != layer || a.size >= bestSize { + continue + } + if a.contains(lat, lon) { + best, bestSize = i, a.size + } + } + if best < 0 { + return "", false + } + return m.areas[best].Code, true +} + +// LocateIATA returns the area of layer whose IATA list holds code. +func (m *Map) LocateIATA(layer, code string) (string, bool) { + if m == nil { + return "", false + } + code = strings.ToUpper(strings.TrimSpace(code)) + for i := range m.areas { + a := &m.areas[i] + if a.Layer == layer && a.iata[code] { + return a.Code, true + } + } + return "", false +} + +// Has reports whether an area with code exists. +func (m *Map) Has(code string) bool { + if m == nil { + return false + } + _, ok := m.byCode[code] + return ok +} + +// Contains reports whether the area with code holds the position. +func (m *Map) Contains(code string, lat, lon float64) bool { + if m == nil || (lat == 0 && lon == 0) { + return false + } + i, ok := m.byCode[code] + return ok && m.areas[i].contains(lat, lon) +} diff --git a/internal/areamap/areamap_test.go b/internal/areamap/areamap_test.go new file mode 100644 index 000000000..6ea3f7238 --- /dev/null +++ b/internal/areamap/areamap_test.go @@ -0,0 +1,188 @@ +package areamap + +import ( + "errors" + "testing" +) + +// Two countries and a city: "Mainland" has a lake (a hole) and an island (a +// second polygon); "City" sits inside Mainland on another layer; "Neighbour" +// borders Mainland to the east. +const fixture = `{ + "type": "FeatureCollection", + "features": [ + {"type": "Feature", "properties": {"code": "MLD", "label": "Mainland", "layer": "country", "iata": ["MLA", "mlb"]}, + "geometry": {"type": "MultiPolygon", "coordinates": [ + [[[0,0],[10,0],[10,10],[0,10],[0,0]], [[4,4],[6,4],[6,6],[4,6],[4,4]]], + [[[-5,2],[-3,2],[-3,4],[-5,4],[-5,2]]] + ]}}, + {"type": "Feature", "properties": {"code": "NBR", "label": "Neighbour", "layer": "country"}, + "geometry": {"type": "Polygon", "coordinates": [[[10,0],[20,0],[20,10],[10,10],[10,0]]]}}, + {"type": "Feature", "properties": {"code": "CTY", "label": "City"}, + "geometry": {"type": "Polygon", "coordinates": [[[1,1],[3,1],[3,3],[1,3],[1,1]]]}} + ] +}` + +func load(t *testing.T) *Map { + t.Helper() + areas, err := ParseGeoJSON([]byte(fixture)) + if err != nil { + t.Fatal(err) + } + m, err := New(areas) + if err != nil { + t.Fatal(err) + } + return m +} + +func TestParseGeoJSONReadsEveryFeature(t *testing.T) { + areas, err := ParseGeoJSON([]byte(fixture)) + if err != nil { + t.Fatal(err) + } + if len(areas) != 3 { + t.Fatalf("areas = %d, want 3", len(areas)) + } + if a := areas[0]; a.Code != "MLD" || a.Label != "Mainland" || a.Layer != "country" || len(a.Polygons) != 2 || len(a.Polygons[0]) != 2 { + t.Errorf("Mainland = %+v, want two parts, the first with a hole", a) + } + if a := areas[2]; a.Layer != DefaultLayer { + t.Errorf("an area naming no layer is in %q, want %q", a.Layer, DefaultLayer) + } +} + +func TestLocateUsesLonLatOrderHolesAndIslands(t *testing.T) { + m := load(t) + cases := []struct { + name string + lat, lon float64 + want string + }{ + {"inside the mainland", 8, 2, "MLD"}, + {"on the island", 3, -4, "MLD"}, + {"in the lake", 5, 5, ""}, + {"in the neighbour", 5, 15, "NBR"}, + {"at sea", 50, 50, ""}, + {"lat and lon swapped would land in the neighbour", 2, 15, "NBR"}, + {"unset GPS", 0, 0, ""}, + } + for _, c := range cases { + got, ok := m.Locate("country", c.lat, c.lon) + if got != c.want || ok != (c.want != "") { + t.Errorf("%s (%v, %v) = %q %v, want %q", c.name, c.lat, c.lon, got, ok, c.want) + } + } +} + +func TestLocateStaysInsideItsLayer(t *testing.T) { + m := load(t) + if got, _ := m.Locate("country", 2, 2); got != "MLD" { + t.Errorf("country layer at the city = %q, want MLD", got) + } + if got, _ := m.Locate(DefaultLayer, 2, 2); got != "CTY" { + t.Errorf("region layer at the city = %q, want CTY", got) + } + if got, ok := m.Locate("no-such-layer", 2, 2); ok { + t.Errorf("an unknown layer placed a point in %q", got) + } +} + +func TestSmallestAreaWinsWhereALayerOverlaps(t *testing.T) { + big := Area{Code: "BIG", Label: "Big", Layer: "x", Polygons: [][][][2]float64{{{{0, 0}, {10, 0}, {10, 10}, {0, 10}}}}} + small := Area{Code: "SML", Label: "Small", Layer: "x", Polygons: [][][][2]float64{{{{2, 2}, {4, 2}, {4, 4}, {2, 4}}}}} + m, err := New([]Area{big, small}) + if err != nil { + t.Fatal(err) + } + if got, _ := m.Locate("x", 3, 3); got != "SML" { + t.Errorf("overlap = %q, want the smaller area SML", got) + } + if got, _ := m.Locate("x", 8, 8); got != "BIG" { + t.Errorf("outside the small area = %q, want BIG", got) + } +} + +func TestLayersAreasAndIATA(t *testing.T) { + m := load(t) + if l := m.Layers(); len(l) != 2 || l[0] != "country" || l[1] != DefaultLayer { + t.Errorf("layers = %v, want [country region]", l) + } + if a := m.Areas("country"); len(a) != 2 || a[0].Code != "MLD" || a[1].Label != "Neighbour" { + t.Errorf("country areas = %+v", a) + } + if a := m.Areas(""); len(a) != 3 { + t.Errorf("all areas = %d, want 3", len(a)) + } + if got, ok := m.LocateIATA("country", "MLB"); !ok || got != "MLD" { + t.Errorf("IATA MLB = %q %v, want MLD (case-insensitive)", got, ok) + } + if _, ok := m.LocateIATA(DefaultLayer, "MLA"); ok { + t.Error("an IATA code belongs to its own layer only") + } + if !m.Has("CTY") || m.Has("NOPE") { + t.Error("Has must know every code and only those") + } + if !m.Contains("MLD", 3, -4) || m.Contains("MLD", 5, 5) || m.Contains("NOPE", 1, 1) { + t.Error("Contains disagrees with Locate") + } +} + +func TestBadInputIsRefused(t *testing.T) { + cases := map[string]string{ + "not json": `{`, + "not a collection": `{"type":"Feature"}`, + "no code": `{"type":"FeatureCollection","features":[{"type":"Feature","properties":{"label":"x"},"geometry":{"type":"Polygon","coordinates":[[[0,0],[1,0],[1,1],[0,0]]]}}]}`, + "a point": `{"type":"FeatureCollection","features":[{"type":"Feature","properties":{"code":"P","label":"x"},"geometry":{"type":"Point","coordinates":[0,0]}}]}`, + "a two-point ring": `{"type":"FeatureCollection","features":[{"type":"Feature","properties":{"code":"P","label":"x"},"geometry":{"type":"Polygon","coordinates":[[[0,0],[1,0]]]}}]}`, + } + for name, in := range cases { + if _, err := ParseGeoJSON([]byte(in)); err == nil { + t.Errorf("%s: accepted, want an error", name) + } + } + dup := []Area{ + {Code: "A", Label: "One", Layer: "x", Polygons: [][][][2]float64{{{{0, 0}, {1, 0}, {1, 1}}}}}, + {Code: "A", Label: "Two", Layer: "y", Polygons: [][][][2]float64{{{{0, 0}, {1, 0}, {1, 1}}}}}, + } + if _, err := New(dup); !errors.Is(err, ErrDuplicate) { + t.Errorf("duplicate code across layers: err = %v, want ErrDuplicate", err) + } +} + +// A realistic boundary: six areas of 2,000 vertices each. +func BenchmarkLocate(b *testing.B) { + var areas []Area + for a := 0; a < 6; a++ { + ring := make([][2]float64, 0, 2000) + for i := 0; i < 2000; i++ { + // a jagged square, each area offset east of the last + t := float64(i) / 2000 + var x, y float64 + switch { + case t < .25: + x, y = t*4, 0 + case t < .5: + x, y = 1, (t-.25)*4 + case t < .75: + x, y = 1-(t-.5)*4, 1 + default: + x, y = 0, 1-(t-.75)*4 + } + if i%2 == 1 { + x, y = x*0.999+0.0005, y*0.999+0.0005 + } + ring = append(ring, [2]float64{float64(a) + x, y}) + } + areas = append(areas, Area{Code: string(rune('A' + a)), Label: "x", Layer: "x", Polygons: [][][][2]float64{{ring}}}) + } + m, err := New(areas) + if err != nil { + b.Fatal(err) + } + b.ReportAllocs() + b.ResetTimer() + for i := 0; i < b.N; i++ { + m.Locate("x", 0.5, float64(i%6)+0.5) + } +} diff --git a/internal/areamap/go.mod b/internal/areamap/go.mod new file mode 100644 index 000000000..09e3d8f88 --- /dev/null +++ b/internal/areamap/go.mod @@ -0,0 +1,3 @@ +module github.com/meshcore-analyzer/areamap + +go 1.22 diff --git a/internal/origin/go.mod b/internal/origin/go.mod new file mode 100644 index 000000000..44f003701 --- /dev/null +++ b/internal/origin/go.mod @@ -0,0 +1,7 @@ +module github.com/meshcore-analyzer/origin + +go 1.22 + +require github.com/meshcore-analyzer/areamap v0.0.0 + +replace github.com/meshcore-analyzer/areamap => ../areamap diff --git a/internal/origin/origin.go b/internal/origin/origin.go new file mode 100644 index 000000000..4ba544583 --- /dev/null +++ b/internal/origin/origin.go @@ -0,0 +1,510 @@ +// Package origin decides where a MeshCore packet started and how each area +// heard it, from the packet's observations, the node positions CoreScope +// holds and a map of named areas (internal/areamap). +// +// Areas are places, not operators: a repeater counts for where it stands, +// whoever runs it. Nothing is guessed: what cannot be placed is Unknown. +package origin + +import ( + "strings" + + "github.com/meshcore-analyzer/areamap" +) + +// Unknown is the area of anything that cannot be placed. +const Unknown = "" + +// Bases: how a packet's starting area was decided, first rule that answers. +const ( + BasisAdvert = "advert" // the advert's own reported position + BasisNode = "node" // an advert without one: the sender's node record + BasisRelay = "first-relay" // the first repeater to pass it on + BasisHeard = "zero-hop" // heard with no relay, so near the observer + BasisNone = "unknown" +) + +// minHopHex is the shortest hop prefix allowed to place a relay. A 1-byte +// prefix is shared by many relays on a mesh of any size and CoreScope resolves +// many of them by guessing, so a 1-byte hop places nothing. +const minHopHex = 4 + +// prefixLens are the hop prefix sizes indexed, in hex characters. +var prefixLens = [...]int{2, 4, 6, 8} + +// Options configures a Locator. +type Options struct { + // Areas places positions; nil places nothing. + Areas *areamap.Map + // Layer is the areamap layer to place in; "" is areamap.DefaultLayer. + Layer string + // Home, when set, is the area whose boundary relays are reported as Gate. + Home string +} + +// Node is what the locator needs to know about a node. +type Node struct { + PublicKey string + Name string + // Relay is true for nodes that pass packets on (repeaters, rooms): only + // these can be a hop. + Relay bool + Lat, Lon *float64 +} + +// Observer is what the locator needs to know about an observer. +type Observer struct { + ID string + // IATA places an observer that reports no position, through the areas' + // iata lists. + IATA string + Lat, Lon *float64 +} + +// Packet is one transmission and every observation of it. +type Packet struct { + Hash string + At int64 + Type int + Route int + // Scope is the scope name the packet carried; Scoped is false when it + // carried no transport code at all. + Scope string + Scoped bool + Channel string + // Advert is set for adverts: the sender's own key and reported position. + Advert *Advert + Observations []Observation +} + +// Advert is what an advert says about its sender. +type Advert struct { + PublicKey string + Lat, Lon *float64 +} + +// Observation is one observer's copy of a packet. +type Observation struct { + ObserverID string + // Relayed is true when the observer is itself a repeater that passed the + // packet on, in which case it is the last entry of its own path. + Relayed bool + // Path is the hop prefixes in order, origin side first. + Path []string + // Resolved is CoreScope's full key for each hop, "" where it could not + // decide. It may be shorter than Path or absent. + Resolved []string +} + +// Heard is how one area heard a packet. +type Heard struct { + Area string + Observers int + // Relayed: an observer there received it from a repeater standing there. + Relayed bool + // Across: an observer there received it straight from the starting area, + // with no repeater of its own involved. + Across bool + // From is the relay an observer there heard it from. + From string + // Gate is the home relay at the boundary: for an area outside home, the + // last home relay before it left; for home, the first one it reached. + Gate string +} + +// Record is one packet, reduced to where it started and who heard it. +type Record struct { + Hash string + At int64 + Type int + Route int + Scope string + Scoped bool + Channel string + Origin string + Basis string + // Heard has one entry per receiving area, ordered by area code. + Heard []Heard + // Via lists, in order, every area whose placeable repeaters passed it on. + Via []string +} + +type nodeInfo struct{ key, name, area string } + +type prefixInfo struct { + key string // the prefix, lower case + area string // the area every placed holder stands in, or Unknown + unique *nodeInfo // the one relay holding it, if only one does +} + +// Locator places nodes, hops and observers. It is read-only once built and +// safe for concurrent use. +type Locator struct { + areas *areamap.Map + layer string + home string + byKey map[string]*nodeInfo + byPrefix map[string]*prefixInfo + observer map[string]string +} + +// NewLocator indexes the nodes and observers known now. +func NewLocator(opt Options, nodes []Node, observers []Observer) *Locator { + if opt.Layer == "" { + opt.Layer = areamap.DefaultLayer + } + l := &Locator{ + areas: opt.Areas, layer: opt.Layer, home: opt.Home, + byKey: make(map[string]*nodeInfo, len(nodes)), + byPrefix: map[string]*prefixInfo{}, + observer: make(map[string]string, len(observers)), + } + holders := map[string]int{} + conflict := map[string]bool{} + for _, n := range nodes { + key := strings.ToLower(n.PublicKey) + ni := &nodeInfo{key: key, name: n.Name, area: l.at(n.Lat, n.Lon)} + l.byKey[key] = ni + if !n.Relay { + continue + } + for _, k := range prefixLens { + if len(key) < k { + continue + } + p := key[:k] + pi := l.byPrefix[p] + if pi == nil { + pi = &prefixInfo{key: p} + l.byPrefix[p] = pi + } + holders[p]++ + pi.unique = ni + if ni.area == Unknown || conflict[p] { + continue + } + if pi.area == Unknown { + pi.area = ni.area + } else if pi.area != ni.area { + pi.area, conflict[p] = Unknown, true + } + } + } + for p, n := range holders { + if n > 1 { + l.byPrefix[p].unique = nil + } + } + for _, o := range observers { + area := l.at(o.Lat, o.Lon) + if area == Unknown { + // An observer is a node too, so its own advert may carry a position. + if ni := l.node(o.ID); ni != nil { + area = ni.area + } + } + if area == Unknown && l.areas != nil && o.IATA != "" { + area, _ = l.areas.LocateIATA(l.layer, o.IATA) + } + l.observer[strings.ToLower(o.ID)] = area + } + return l +} + +func (l *Locator) at(lat, lon *float64) string { + if l.areas == nil || lat == nil || lon == nil { + return Unknown + } + a, _ := l.areas.Locate(l.layer, *lat, *lon) + return a +} + +// get looks s up in a map keyed in lower case without allocating. +func get[V any](m map[string]V, s string) (V, bool) { + var buf [80]byte + if len(s) > len(buf) { + v, ok := m[strings.ToLower(s)] + return v, ok + } + b := buf[:len(s)] + for i := 0; i < len(s); i++ { + c := s[i] + if 'A' <= c && c <= 'Z' { + c += 'a' - 'A' + } + b[i] = c + } + v, ok := m[string(b)] + return v, ok +} + +func (l *Locator) node(key string) *nodeInfo { + ni, _ := get(l.byKey, key) + return ni +} + +// Key places a node by its full public key. +func (l *Locator) Key(pubkey string) string { + if ni := l.node(pubkey); ni != nil { + return ni.area + } + return Unknown +} + +// Prefix places a hop by its prefix. A short prefix is shared by many relays, +// but that only matters when they stand in different areas: if every relay +// with the prefix and a known position is in one area, the hop is there. +func (l *Locator) Prefix(hex string) string { + if pi, ok := get(l.byPrefix, hex); ok { + return pi.area + } + return Unknown +} + +// Relay names a relay from its full key or a prefix of it, with its area. An +// unknown or shared prefix comes back as the prefix itself, upper case. +func (l *Locator) Relay(key string) (name, area string) { + if pi, ok := get(l.byPrefix, key); ok && pi.unique != nil { + return pi.unique.name, pi.unique.area + } + if ni := l.node(key); ni != nil { + return ni.name, ni.area + } + return strings.ToUpper(key), l.Prefix(key) +} + +// Observer places an observer. +func (l *Locator) Observer(id string) string { + a, _ := get(l.observer, id) + return a +} + +func resolved(o *Observation, i int) string { + if i < len(o.Resolved) { + return o.Resolved[i] + } + return "" +} + +// hop places hop i of an observation: CoreScope's resolved key first, then +// the prefix. A 1-byte hop places nothing. +func (l *Locator) hop(o *Observation, i int) string { + if i >= len(o.Path) || len(o.Path[i]) < minHopHex { + return Unknown + } + if r := resolved(o, i); r != "" { + if a := l.Key(r); a != Unknown { + return a + } + } + return l.Prefix(o.Path[i]) +} + +// hopKey names hop i as well as the packet allows, in lower case: the +// resolved key where there is one, otherwise the prefix. "" for a 1-byte hop. +func (l *Locator) hopKey(o *Observation, i int) string { + if i >= len(o.Path) || len(o.Path[i]) < minHopHex { + return "" + } + if r := resolved(o, i); r != "" { + if ni := l.node(r); ni != nil { + return ni.key + } + return strings.ToLower(r) + } + if pi, ok := get(l.byPrefix, o.Path[i]); ok { + return pi.key + } + return strings.ToLower(o.Path[i]) +} + +// tally counts votes for areas in a small fixed array. +type tally struct { + area [8]string + n [8]int + len int +} + +func (t *tally) add(a string) { + for i := 0; i < t.len; i++ { + if t.area[i] == a { + t.n[i]++ + return + } + } + if t.len < len(t.area) { + t.area[t.len], t.n[t.len] = a, 1 + t.len++ + } +} + +// top is the area with most votes, the lower code on a tie. +func (t *tally) top() string { + best, n := Unknown, 0 + for i := 0; i < t.len; i++ { + if t.n[i] > n || (t.n[i] == n && t.area[i] < best) { + best, n = t.area[i], t.n[i] + } + } + return best +} + +func (l *Locator) origin(p *Packet) (string, string) { + if p.Advert != nil { + if a := l.at(p.Advert.Lat, p.Advert.Lon); a != Unknown { + return a, BasisAdvert + } + if a := l.Key(p.Advert.PublicKey); a != Unknown { + return a, BasisNode + } + } + // Each observation names a first relay; they normally agree, and where a + // flood left through two repeaters the majority decides. + var relay, zero tally + for i := range p.Observations { + o := &p.Observations[i] + if len(o.Path) == 0 { + if a := l.Observer(o.ObserverID); a != Unknown { + zero.add(a) + } + continue + } + if a := l.hop(o, 0); a != Unknown { + relay.add(a) + } + } + if a := relay.top(); a != Unknown { + return a, BasisRelay + } + if a := zero.top(); a != Unknown { + return a, BasisHeard + } + return Unknown, BasisNone +} + +// gate finds the home relay at the boundary on one observation's path. +func (l *Locator) gate(o *Observation, path []string, heard, origin string) string { + switch { + case l.home == "": + case heard != l.home && heard != Unknown: + for i := len(path) - 1; i >= 0; i-- { + if l.hop(o, i) == l.home { + return l.hopKey(o, i) + } + } + case heard == l.home && origin != l.home && origin != Unknown: + for i := range path { + if l.hop(o, i) == l.home { + return l.hopKey(o, i) + } + } + } + return "" +} + +// Derive reduces a packet to a record. It allocates only the record's Heard +// and Via slices. +func (l *Locator) Derive(p Packet) Record { + rec := Record{ + Hash: p.Hash, At: p.At, Type: p.Type, Route: p.Route, + Scope: p.Scope, Scoped: p.Scoped, Channel: p.Channel, + } + rec.Origin, rec.Basis = l.origin(&p) + + var heardBuf [8]Heard + heard := heardBuf[:0] + var viaBuf [8]string + via := viaBuf[:0] + type seenObs struct{ area, id string } + var seenBuf [16]seenObs + seen := seenBuf[:0] + + for oi := range p.Observations { + o := &p.Observations[oi] + area := l.Observer(o.ObserverID) + path := o.Path + if o.Relayed && len(path) > 0 { + path = path[:len(path)-1] + } + from := rec.Origin + if len(path) > 0 { + from = l.hop(o, len(path)-1) + } + for i := range path { + if a := l.hop(o, i); a != Unknown && !contains(via, a) { + via = append(via, a) + } + } + hi := -1 + for i := range heard { + if heard[i].Area == area { + hi = i + break + } + } + if hi < 0 { + heard = append(heard, Heard{Area: area}) + hi = len(heard) - 1 + } + h := &heard[hi] + dup := false + for _, s := range seen { + if s.area == area && strings.EqualFold(s.id, o.ObserverID) { + dup = true + break + } + } + if !dup { + seen = append(seen, seenObs{area, o.ObserverID}) + h.Observers++ + } + if from != Unknown && from == area && len(path) > 0 { + h.Relayed = true + } + if from != Unknown && from != area && from == rec.Origin { + h.Across = true + } + if h.From == "" && len(path) > 0 { + h.From = l.hopKey(o, len(path)-1) + } + if h.Gate == "" { + h.Gate = l.gate(o, path, area, rec.Origin) + } + } + if len(heard) > 0 { + sortHeard(heard) + rec.Heard = append(make([]Heard, 0, len(heard)), heard...) + } + if len(via) > 0 { + sortStrings(via) + rec.Via = append(make([]string, 0, len(via)), via...) + } + return rec +} + +func contains(s []string, v string) bool { + for _, x := range s { + if x == v { + return true + } + } + return false +} + +// Insertion sorts: the slices hold a handful of areas, and sort.Slice would +// allocate. +func sortHeard(h []Heard) { + for i := 1; i < len(h); i++ { + for j := i; j > 0 && h[j].Area < h[j-1].Area; j-- { + h[j], h[j-1] = h[j-1], h[j] + } + } +} + +func sortStrings(s []string) { + for i := 1; i < len(s); i++ { + for j := i; j > 0 && s[j] < s[j-1]; j-- { + s[j], s[j-1] = s[j-1], s[j] + } + } +} diff --git a/internal/origin/origin_test.go b/internal/origin/origin_test.go new file mode 100644 index 000000000..7fefc21cc --- /dev/null +++ b/internal/origin/origin_test.go @@ -0,0 +1,283 @@ +package origin + +import ( + "testing" + + "github.com/meshcore-analyzer/areamap" +) + +func fp(v float64) *float64 { return &v } + +// Three rectangles standing in for real boundaries: SCO above 55°N, IOI west +// of 5.5°W below it, and NEE east of 2.5°W below it. Knock's airport code +// places observers that report no position. +const testAreas = `{"type":"FeatureCollection","features":[ + {"type":"Feature","properties":{"code":"SCO","label":"Scotland"}, + "geometry":{"type":"Polygon","coordinates":[[[-8,55.0],[-0.5,55.0],[-0.5,61],[-8,61],[-8,55.0]]]}}, + {"type":"Feature","properties":{"code":"IOI","label":"Island of Ireland","iata":["NOC"]}, + "geometry":{"type":"Polygon","coordinates":[[[-11,51],[-5.5,51],[-5.5,55.0],[-11,55.0],[-11,51]]]}}, + {"type":"Feature","properties":{"code":"NEE","label":"North East","iata":["MME"]}, + "geometry":{"type":"Polygon","coordinates":[[[-2.5,54],[-0.5,54],[-0.5,55.0],[-2.5,55.0],[-2.5,54]]]}} +]}` + +// The test mesh: two Scottish repeaters, one in Belfast, one in Newcastle, one +// in Dublin, and observers in Edinburgh, Knock (no position) and Teesside (no +// position). +func testLocator(t testing.TB, home string) *Locator { + t.Helper() + areas, err := areamap.ParseGeoJSON([]byte(testAreas)) + if err != nil { + t.Fatal(err) + } + m, err := areamap.New(areas) + if err != nil { + t.Fatal(err) + } + nodes := []Node{ + {PublicKey: "AA111100", Name: "Edinburgh", Relay: true, Lat: fp(55.95), Lon: fp(-3.19)}, + {PublicKey: "AB222200", Name: "Glasgow", Relay: true, Lat: fp(55.86), Lon: fp(-4.25)}, + {PublicKey: "CC333300", Name: "Belfast", Relay: true, Lat: fp(54.60), Lon: fp(-5.93)}, + {PublicKey: "DD444400", Name: "Newcastle", Relay: true, Lat: fp(54.97), Lon: fp(-1.61)}, + {PublicKey: "AC555500", Name: "Dublin", Relay: true, Lat: fp(53.35), Lon: fp(-6.26)}, + {PublicKey: "EE666600", Name: "Dundee companion", Lat: fp(56.46), Lon: fp(-2.97)}, + } + obs := []Observer{ + {ID: "OBS-EDI", IATA: "EDI", Lat: fp(56.05), Lon: fp(-3.29)}, + {ID: "OBS-NOC", IATA: "NOC"}, + {ID: "OBS-MME", IATA: "mme"}, + } + return NewLocator(Options{Areas: m, Home: home}, nodes, obs) +} + +func heard(r Record, area string) Heard { + for _, h := range r.Heard { + if h.Area == area { + return h + } + } + return Heard{} +} + +func TestLocatorPlacesNodesObserversAndPrefixes(t *testing.T) { + l := testLocator(t, "") + if got := l.Key("aa111100"); got != "SCO" { + t.Errorf("node by key = %q, want SCO", got) + } + if got := l.Key("ffff"); got != Unknown { + t.Errorf("an unknown key = %q, want unknown", got) + } + if got := l.Prefix("CC33"); got != "IOI" { + t.Errorf("a prefix one relay holds = %q, want IOI", got) + } + // "a" prefixes: Edinburgh and Glasgow are Scottish, Dublin is not. + if got := l.Prefix("AA11"); got != "SCO" { + t.Errorf("AA11 = %q, want SCO", got) + } + if got := l.Prefix("EE66"); got != Unknown { + t.Errorf("a companion never places a hop, got %q", got) + } + if got := l.Observer("obs-noc"); got != "IOI" { + t.Errorf("an observer with no position = %q, want IOI by its airport code", got) + } + if got := l.Observer("OBS-MME"); got != "NEE" { + t.Errorf("airport codes match whatever their case, got %q", got) + } + if got := l.Observer("OBS-EDI"); got != "SCO" { + t.Errorf("an observer with a position = %q, want SCO", got) + } + if name, area := l.Relay("ab22"); name != "Glasgow" || area != "SCO" { + t.Errorf("relay ab22 = %q/%q, want Glasgow/SCO", name, area) + } + if name, area := l.Relay("9f9f"); name != "9F9F" || area != Unknown { + t.Errorf("an unknown relay = %q/%q, want its prefix and unknown", name, area) + } +} + +func TestAShortPrefixPlacesOnlyWhenEveryHolderAgrees(t *testing.T) { + l := NewLocator(Options{Areas: testLocator(t, "").areas}, []Node{ + {PublicKey: "A5000001", Relay: true, Lat: fp(55.95), Lon: fp(-3.19)}, // Scotland + {PublicKey: "A5000002", Relay: true, Lat: fp(54.60), Lon: fp(-5.93)}, // Ireland + {PublicKey: "A6000001", Relay: true, Lat: fp(55.95), Lon: fp(-3.19)}, // Scotland + {PublicKey: "A6000002", Relay: true, Lat: fp(57.10), Lon: fp(-2.10)}, // Scotland + {PublicKey: "A6000003", Relay: true}, // no position + }, nil) + if got := l.Prefix("A500"); got != Unknown { + t.Errorf("a prefix shared across a border = %q, want unknown", got) + } + if got := l.Prefix("A600"); got != "SCO" { + t.Errorf("a prefix shared inside one area = %q, want SCO", got) + } +} + +func TestDeriveSplitsRelayedFromHeardAcross(t *testing.T) { + l := testLocator(t, "SCO") + r := l.Derive(Packet{ + Hash: "h1", At: 1000, Type: 5, Route: 0, Scope: "#sco", Scoped: true, + Observations: []Observation{ + {ObserverID: "OBS-EDI", Path: []string{"AA11"}}, // from the Edinburgh repeater + {ObserverID: "OBS-NOC", Path: []string{"AA11", "AB22", "CC33"}}, // after Belfast passed it on + {ObserverID: "OBS-MME", Path: []string{"AA11", "AB22"}}, // straight from Glasgow + }, + }) + if r.Origin != "SCO" || r.Basis != BasisRelay { + t.Fatalf("origin = %q/%q, want SCO by first relay", r.Origin, r.Basis) + } + if r.Hash != "h1" || r.At != 1000 || r.Type != 5 || r.Scope != "#sco" || !r.Scoped { + t.Errorf("packet fields not carried: %+v", r) + } + if h := heard(r, "IOI"); !h.Relayed || h.Across || h.Observers != 1 { + t.Errorf("IOI = %+v, want relayed in by its own repeater", h) + } + if h := heard(r, "NEE"); h.Relayed || !h.Across { + t.Errorf("NEE = %+v, want heard straight across", h) + } + if h := heard(r, "SCO"); !h.Relayed || h.Observers != 1 { + t.Errorf("SCO = %+v, want relayed by its own repeater", h) + } + if len(r.Heard) != 3 || r.Heard[0].Area != "IOI" || r.Heard[1].Area != "NEE" || r.Heard[2].Area != "SCO" { + t.Errorf("heard = %+v, want IOI, NEE, SCO in order", r.Heard) + } + if len(r.Via) != 2 || r.Via[0] != "IOI" || r.Via[1] != "SCO" { + t.Errorf("via = %v, want [IOI SCO]", r.Via) + } + if h := heard(r, "IOI"); h.From != "cc33" || h.Gate != "ab22" { + t.Errorf("IOI from/gate = %q/%q, want Belfast and the Glasgow relay that handed it over", h.From, h.Gate) + } +} + +func TestGateIsTheHomeRelayAtTheBoundary(t *testing.T) { + // Arriving: the first home relay it reached. + l := testLocator(t, "SCO") + in := l.Derive(Packet{Type: 2, Observations: []Observation{ + {ObserverID: "OBS-EDI", Path: []string{"CC33", "AB22", "AA11"}}, + }}) + if h := heard(in, "SCO"); h.Gate != "ab22" { + t.Errorf("arriving gate = %q, want ab22, the first Scottish relay", h.Gate) + } + // Without a home area there is no gate. + none := testLocator(t, "").Derive(Packet{Type: 2, Observations: []Observation{ + {ObserverID: "OBS-NOC", Path: []string{"AA11", "AB22", "CC33"}}, + }}) + if h := heard(none, "IOI"); h.Gate != "" { + t.Errorf("gate with no home area = %q, want none", h.Gate) + } +} + +func TestDeriveOrigin(t *testing.T) { + l := testLocator(t, "") + // An advert says where its sender is, whatever the path says. + ad := l.Derive(Packet{Type: 4, Route: 1, Advert: &Advert{PublicKey: "x", Lat: fp(54.60), Lon: fp(-5.93)}, + Observations: []Observation{{ObserverID: "OBS-EDI", Path: []string{"AA11"}}}}) + if ad.Origin != "IOI" || ad.Basis != BasisAdvert { + t.Errorf("advert origin = %q/%q, want IOI by advert", ad.Origin, ad.Basis) + } + // An advert at 0,0 falls back to the sender's node record. + ad2 := l.Derive(Packet{Type: 4, Route: 1, Advert: &Advert{PublicKey: "DD444400", Lat: fp(0), Lon: fp(0)}}) + if ad2.Origin != "NEE" || ad2.Basis != BasisNode { + t.Errorf("positionless advert origin = %q/%q, want NEE from its node record", ad2.Origin, ad2.Basis) + } + // Heard with no relay at all: the sender is in range of the observer. + zh := l.Derive(Packet{Type: 2, Route: 1, Observations: []Observation{{ObserverID: "OBS-NOC"}}}) + if zh.Origin != "IOI" || zh.Basis != BasisHeard { + t.Errorf("zero-hop origin = %q/%q, want IOI zero-hop", zh.Origin, zh.Basis) + } + // An observer that relayed the packet is the last hop of its own path. + self := l.Derive(Packet{Type: 2, Route: 1, Observations: []Observation{{ObserverID: "OBS-MME", Relayed: true, Path: []string{"DD44"}}}}) + if self.Origin != "NEE" { + t.Errorf("origin through a relaying observer = %q, want NEE", self.Origin) + } + if h := heard(self, "NEE"); h.Relayed { + t.Errorf("an observer relaying its own copy is not its area relaying it in: %+v", h) + } + // A resolved key beats an ambiguous prefix. + key := "cc333300" + res := l.Derive(Packet{Type: 2, Route: 1, Observations: []Observation{{ObserverID: "OBS-EDI", Path: []string{"ZZZZ"}, Resolved: []string{key}}}}) + if res.Origin != "IOI" { + t.Errorf("resolved origin = %q, want IOI", res.Origin) + } + // A 1-byte hop places nothing, even when CoreScope resolved it. + one := l.Derive(Packet{Type: 2, Route: 1, Observations: []Observation{{ObserverID: "OBS-NOC", Path: []string{"AA", "CC"}, Resolved: []string{key, key}}}}) + if one.Origin != Unknown || one.Basis != BasisNone || len(one.Via) != 0 { + t.Errorf("1-byte path: origin %q/%q via %v, want unknown and no relays placed", one.Origin, one.Basis, one.Via) + } + if h := heard(one, "IOI"); h.Relayed || h.Across || h.Observers != 1 { + t.Errorf("1-byte path heard as %+v, want counted but neither relayed nor across", h) + } + // Two observers that disagree on the first relay: the majority decides. + maj := l.Derive(Packet{Type: 2, Observations: []Observation{ + {ObserverID: "OBS-EDI", Path: []string{"AA11"}}, + {ObserverID: "OBS-NOC", Path: []string{"AB22", "CC33"}}, + {ObserverID: "OBS-MME", Path: []string{"DD44"}}, + }}) + if maj.Origin != "SCO" { + t.Errorf("majority origin = %q, want SCO", maj.Origin) + } +} + +func TestAnObserverCountsOncePerArea(t *testing.T) { + l := testLocator(t, "") + r := l.Derive(Packet{Type: 2, Observations: []Observation{ + {ObserverID: "OBS-EDI", Path: []string{"AA11"}}, + {ObserverID: "obs-edi", Path: []string{"AB22", "AA11"}}, + {ObserverID: "OBS-UNPLACED"}, + }}) + if h := heard(r, "SCO"); h.Observers != 1 { + t.Errorf("SCO observers = %d, want the one observer counted once", h.Observers) + } + if h := heard(r, Unknown); h.Observers != 1 { + t.Errorf("an observer that cannot be placed still counts, under unknown: %+v", r.Heard) + } +} + +func TestLayersAreIndependent(t *testing.T) { + areas, _ := areamap.ParseGeoJSON([]byte(`{"type":"FeatureCollection","features":[ + {"type":"Feature","properties":{"code":"GB","layer":"country"},"geometry":{"type":"Polygon","coordinates":[[[-8,50],[2,50],[2,61],[-8,61],[-8,50]]]}}, + {"type":"Feature","properties":{"code":"EDN","layer":"city"},"geometry":{"type":"Polygon","coordinates":[[[-3.4,55.85],[-3.0,55.85],[-3.0,56.0],[-3.4,56.0],[-3.4,55.85]]]}}]}`)) + m, err := areamap.New(areas) + if err != nil { + t.Fatal(err) + } + nodes := []Node{{PublicKey: "AA111100", Relay: true, Lat: fp(55.95), Lon: fp(-3.19)}} + if got := NewLocator(Options{Areas: m, Layer: "country"}, nodes, nil).Key("AA111100"); got != "GB" { + t.Errorf("country layer = %q, want GB", got) + } + if got := NewLocator(Options{Areas: m, Layer: "city"}, nodes, nil).Key("AA111100"); got != "EDN" { + t.Errorf("city layer = %q, want EDN", got) + } +} + +func TestANilAreaMapPlacesNothing(t *testing.T) { + l := NewLocator(Options{}, []Node{{PublicKey: "AA111100", Relay: true, Lat: fp(55.95), Lon: fp(-3.19)}}, nil) + r := l.Derive(Packet{Type: 2, Observations: []Observation{{ObserverID: "X", Path: []string{"AA11"}}}}) + if r.Origin != Unknown || len(r.Heard) != 1 || r.Heard[0].Area != Unknown { + t.Errorf("with no areas: %+v, want everything unknown", r) + } +} + +func BenchmarkDerive(b *testing.B) { + l := testLocator(b, "SCO") + key := "cc333300" + p := Packet{Hash: "h", At: 1, Type: 5, Scope: "#sco", Scoped: true, Observations: []Observation{ + {ObserverID: "OBS-EDI", Path: []string{"AA11"}}, + {ObserverID: "OBS-NOC", Path: []string{"AA11", "AB22", "CC33"}, Resolved: []string{"", "", key}}, + {ObserverID: "OBS-MME", Path: []string{"AA11", "AB22"}}, + }} + b.ReportAllocs() + b.ResetTimer() + for i := 0; i < b.N; i++ { + _ = l.Derive(p) + } +} + +func TestDeriveAllocations(t *testing.T) { + l := testLocator(t, "SCO") + p := Packet{Type: 5, Observations: []Observation{ + {ObserverID: "OBS-EDI", Path: []string{"AA11"}}, + {ObserverID: "OBS-NOC", Path: []string{"AA11", "AB22", "CC33"}}, + {ObserverID: "OBS-MME", Path: []string{"AA11", "AB22"}}, + }} + // One slice for Heard and one for Via; nothing per hop or per observer. + if n := testing.AllocsPerRun(200, func() { _ = l.Derive(p) }); n > 2 { + t.Errorf("Derive allocates %.0f times per packet, want at most 2", n) + } +}