diff --git a/cmd/ingestor/client_reception.go b/cmd/ingestor/client_reception.go index f3e73609d..12276fa34 100644 --- a/cmd/ingestor/client_reception.go +++ b/cmd/ingestor/client_reception.go @@ -172,54 +172,36 @@ type ClientReception struct { // deriveHeardKey applies the RX capture HARD RULE: record only what the // companion heard itself and directly. // - direction must be "rx". -// - payload type must not repurpose the header path bytes (TRACE stores -// per-hop SNR there, not node hashes — packetpath.PathBytesAreHops). -// - hops present AND a FLOOD route → the directly-heard node is the LAST hop -// (path[len-1] = the forwarder that just transmitted; each FLOOD forwarder -// appends its hash to the end). 1-byte (2 hex char) prefixes are rejected. -// - hops present on a DIRECT route → NOT attributable: direct forwarders -// consume the next hop from the FRONT (firmware Mesh.cpp removeSelfFromPath), -// so path[len-1] is the route's destination-side end, not who was heard. -// - hops empty + isAdvert → the 0-hop advertiser, by its full pubkey. -// - hops empty + isDiscoverResp → the 0-hop responder, by its pubkey (8 or -// 32 bytes — CTL_TYPE_NODE_DISCOVER_RESP always carries an 8-byte prefix -// or the full 32-byte key; anything else is rejected outright, not -// truncated). A node-discover reply is always a direct, zero-hop RX — +// - the path and advert part is the shared rule, packetpath.HeardKey: last +// hop of a flood route (at least 2 bytes), or the 0-hop advertiser; never +// a direct route with a path, never TRACE. +// - hops empty + isDiscoverResp: the 0-hop responder, by its pubkey (8 or +// 32 bytes; CTL_TYPE_NODE_DISCOVER_RESP always carries an 8-byte prefix +// or the full 32-byte key, anything else is rejected outright, not +// truncated). A node-discover reply is always a direct, zero-hop RX, // stronger identification than a path hash, since it carries the // responder's own identity rather than an inferred forwarder. -// - otherwise → not attributable (ok=false). +// - otherwise: not attributable (ok=false). // // Returns (heardKey lowercased, keylenBytes, src, ok). func deriveHeardKey(direction string, routeType, payloadType int, hops []string, advertPubkey string, isAdvert bool, isDiscoverResp bool, discoverPubkey string) (string, int, string, bool) { if !strings.EqualFold(direction, "rx") { return "", 0, "", false } - if !packetpath.PathBytesAreHops(byte(payloadType)) { - return "", 0, "", false - } + last, pk := "", "" if len(hops) > 0 { - // FLOOD routes (TRANSPORT_FLOOD 0, FLOOD 1) APPEND each forwarder's hash to - // the END of the path, so path[last] is the immediate RF transmitter. DIRECT - // routes (2, 3) consume the next hop from the FRONT, so path[last] is the - // route's destination-side end, NOT who was heard. - if routeType != packetpath.RouteTransportFlood && routeType != packetpath.RouteFlood { // direct route: path[last] is not the transmitter - return "", 0, "", false - } - last := strings.ToLower(strings.TrimSpace(hops[len(hops)-1])) - keylen := len(last) / 2 - if keylen < 2 { // exclude 1-byte (collision-prone), matching Reach - return "", 0, "", false - } - return last, keylen, "rxlog", true + last = hops[len(hops)-1] + } + if isAdvert { + pk = advertPubkey } - if isAdvert && advertPubkey != "" { - pk := strings.ToLower(strings.TrimSpace(advertPubkey)) - return pk, len(pk) / 2, "advert", true + if key, src, ok := packetpath.HeardKey(routeType, byte(payloadType), last, pk); ok { + return key, len(key) / 2, src, true } - if isDiscoverResp && discoverPubkey != "" { + if len(hops) == 0 && isDiscoverResp && discoverPubkey != "" && packetpath.PathBytesAreHops(byte(payloadType)) { pk := strings.ToLower(strings.TrimSpace(discoverPubkey)) keylen := len(pk) / 2 - if keylen != 8 && keylen != 32 { // discover pubkeys are always 8B (prefix) or 32B (full) — no floor, an exact set + if keylen != 8 && keylen != 32 { // discover pubkeys are always 8B (prefix) or 32B (full), no floor, an exact set return "", 0, "", false } return pk, keylen, "discover", true diff --git a/cmd/ingestor/client_reception_test.go b/cmd/ingestor/client_reception_test.go index c29662bf4..0b92435c9 100644 --- a/cmd/ingestor/client_reception_test.go +++ b/cmd/ingestor/client_reception_test.go @@ -823,3 +823,40 @@ func TestHandleClientPacketRejectsNonHexPubkey(t *testing.T) { t.Fatalf("non-hex pubkey must write nothing, got %d receptions, %d observers", nRecept, nObs) } } + +// TestDeriveHeardKey_MatchesPacketpath pins deriveHeardKey to the shared +// packetpath.HeardKey rule for every case that rule covers. +func TestDeriveHeardKey_MatchesPacketpath(t *testing.T) { + cases := []struct { + name string + routeType int + payloadType int + lastHop string + advertPubkey string + }{ + {"flood, 2-byte last hop", packetpath.RouteFlood, 0x05, "BB11", ""}, + {"transport flood counts as flood", packetpath.RouteTransportFlood, 0x05, "bb11", ""}, + {"3-byte last hop", packetpath.RouteFlood, 0x05, "bbccdd", ""}, + {"1-byte last hop refused", packetpath.RouteFlood, 0x05, "BB", ""}, + {"direct route with a path refused", packetpath.RouteDirect, 0x05, "bb11", ""}, + {"transport direct with a path refused", packetpath.RouteTransportDirect, 0x05, "bb11", ""}, + {"TRACE refused even on flood", packetpath.RouteFlood, packetpath.PayloadTRACE, "bb11", ""}, + {"0-hop advert on flood", packetpath.RouteFlood, 0x04, "", "ABCDEF01"}, + {"0-hop advert on direct (sendZeroHop)", packetpath.RouteDirect, 0x04, "", "abcdef01"}, + {"empty path, no advert pubkey", packetpath.RouteFlood, 0x05, "", ""}, + {"TRACE with empty path refused", packetpath.RouteFlood, packetpath.PayloadTRACE, "", "abcdef01"}, + } + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + var hops []string + if c.lastHop != "" { + hops = []string{"aa", c.lastHop} + } + wantKey, wantSrc, wantOK := packetpath.HeardKey(c.routeType, byte(c.payloadType), c.lastHop, c.advertPubkey) + key, keylen, src, ok := deriveHeardKey("rx", c.routeType, c.payloadType, hops, c.advertPubkey, c.advertPubkey != "", false, "") + if key != wantKey || src != wantSrc || ok != wantOK || keylen != len(wantKey)/2 { + t.Errorf("deriveHeardKey = (%q, %d, %q, %v), HeardKey = (%q, %q, %v)", key, keylen, src, ok, wantKey, wantSrc, wantOK) + } + }) + } +} diff --git a/cmd/server/direct_heard.go b/cmd/server/direct_heard.go index b99408670..8fd7dc3d9 100644 --- a/cmd/server/direct_heard.go +++ b/cmd/server/direct_heard.go @@ -6,30 +6,30 @@ // file existed, and it is the only one for which the SNR and RSSI printed // next to an observer belong to the node the row names. // -// The rule follows the firmware: +// The rule is packetpath.HeardKey, shared with the ingestor's client +// receptions: the last hop of a flood route, or the advertiser of a zero-hop +// ADVERT (flood, or direct via Mesh::sendZeroHop). It refuses three things, +// each because it can name the wrong node: // -// - Flood routes build the path up as they travel: a forwarding repeater -// appends its own hash before retransmitting (Mesh.cpp:349). The last -// hop is therefore the node whose transmission the observer received. -// - Direct routes carry the REMAINING route, not the travelled one. A -// forwarder matches itself against the head of the path and calls -// removeSelfFromPath (Mesh.cpp:89,103) before retransmitting, so the -// node the observer heard is not in the path at all. Direct routes -// therefore never attribute. -// - An empty flood path means the observer received the originator's own -// transmission. Only ADVERTs carry the originator's pubkey in the -// clear, so other payload types with an empty path attribute to nobody. -// - A hop prefix that matches more than one node attributes to nobody. -// Path hop sizes are chosen by the originator (Packet.h:83, -// Mesh.cpp:649) and default to one byte, so a hop often matches many -// candidates. resolveWithContext guesses in that case; this file does -// not. The gate matches resolvePathForObsColdLoad: under-attribute -// rather than credit the wrong node. +// - a 1-byte last hop: a node CoreScope does not know can share that byte, +// so even a prefix with one known candidate is not proof; +// - TRACE: its path bytes carry per-hop SNR, not node hashes; +// - a zero-hop ADVERT whose signature failed to verify: the pubkey in it +// is not proven to belong to the transmitter. +// +// Direct routes with a path never attribute: a forwarder calls +// removeSelfFromPath (Mesh.cpp:89,103) before retransmitting, so the path +// left behind is the remaining route. A hop prefix of 2 bytes or more that +// matches more than one node, or that a retired repeater shares, also +// attributes to nobody: under-attribute rather than credit the wrong node, +// as resolvePathForObsColdLoad and uniqueHopPrefix do. package main import ( "sort" "strings" + + "github.com/meshcore-analyzer/packetpath" ) // directHeardAgg accumulates one observer's direct receptions of one node. @@ -101,49 +101,41 @@ func advertOriginPubkey(tx *StoreTx) string { // directHeardNode returns the lowercase pubkey of the node whose // transmission this observation received off the air, or "" when that cannot -// be established. See the package comment for the rule and its firmware -// grounding. +// be established. See the package comment for the rule. func directHeardNode(tx *StoreTx, obs *StoreObs, pm *prefixMap) string { - if tx == nil || obs == nil || tx.RouteType == nil { + if tx == nil || obs == nil || tx.RouteType == nil || tx.PayloadType == nil { return "" } hop := lastPathHop(obs.PathJSON) - switch *tx.RouteType { - case RouteFlood, RouteTransportFlood: - // Handled below: empty path means the originator, otherwise the last - // hop is whoever was heard. - case RouteDirect, RouteTransportDirect: - // A direct route normally says nothing about the transmitter, because - // the forwarder calls removeSelfFromPath before retransmitting - // (firmware Mesh.cpp) and the path left behind is the REMAINING route. - // - // The exception is a zero hop. Mesh::sendZeroHop sets ROUTE_TYPE_DIRECT - // (its transport overload ROUTE_TYPE_TRANSPORT_DIRECT) and path_len = 0, - // commented there as "path_len of zero means Zero Hop". Repeaters send - // their periodic local advert that way (simple_repeater/MyMesh.cpp, the - // next_local_advert branch and sendSelfAdvertisement with flood=false), - // and so do companions. An ADVERT arriving on a direct route with an - // empty path therefore cannot have been forwarded: the observer heard - // the advertiser's own transmission, and the advert carries its pubkey - // in the clear. That is the strongest direct-RF evidence there is. - // - // Anything else direct still says nothing: a non-empty path is the - // remaining route, and advertOriginPubkey returns "" for every payload - // type other than ADVERT. - if hop == "" { - return advertOriginPubkey(tx) + adv := "" + if hop == "" { + // advertOriginPubkey checks the type first, so signatureFailed (which + // may parse DecodedJSON) only runs for ADVERTs. + if pk := advertOriginPubkey(tx); pk != "" && !tx.signatureFailed() { + adv = pk } - return "" - default: + } + key, src, ok := packetpath.HeardKey(*tx.RouteType, byte(*tx.PayloadType), hop, adv) + if !ok { return "" } - if hop == "" { - return advertOriginPubkey(tx) + if src == "advert" { + return key } if pm == nil { return "" } - candidates := pm.relayCandidates(hop) + // A retired repeater (moved to inactive_nodes) may still relay on this + // prefix, so the one active candidate is not proven (uniqueHopPrefix). + if _, shared := pm.retired[key]; shared { + return "" + } + // key is already lower case: look it up directly instead of through + // relayCandidates, which lower-cases again on every observation. + candidates, found := pm.relay[key] + if !found { + candidates = pm.m[key] + } if len(candidates) != 1 { return "" } diff --git a/cmd/server/direct_heard_test.go b/cmd/server/direct_heard_test.go index d93702513..fb9bbe697 100644 --- a/cmd/server/direct_heard_test.go +++ b/cmd/server/direct_heard_test.go @@ -1,6 +1,7 @@ package main import ( + "strconv" "testing" ) @@ -177,6 +178,36 @@ func TestDirectHeardNode(t *testing.T) { pathJSON: `["BB11"]`, want: "", }, + { + name: "unique one-byte last hop credits nobody", + tx: dhTx(RouteFlood, PayloadTXT_MSG, ""), + pathJSON: `["66","BB"]`, + want: "", + }, + { + name: "TRACE flood with a unique two-byte last hop credits nobody", + tx: dhTx(RouteFlood, PayloadTRACE, ""), + pathJSON: `["BB11"]`, + want: "", + }, + { + name: "zero-hop advert with a failed signature credits nobody", + tx: dhTx(RouteFlood, PayloadADVERT, `{"type":"ADVERT","pubKey":"`+dhUnique+`","signatureValid":false}`), + pathJSON: `[]`, + want: "", + }, + { + name: "zero-hop advert with a valid signature credits the advertiser", + tx: dhTx(RouteFlood, PayloadADVERT, `{"type":"ADVERT","pubKey":"`+dhUnique+`","signatureValid":true}`), + pathJSON: `[]`, + want: dhUnique, + }, + { + name: "missing payload type credits nobody", + tx: &StoreTx{RouteType: dhRoute(RouteFlood)}, + pathJSON: `["BB11"]`, + want: "", + }, } for _, tc := range cases { @@ -334,3 +365,62 @@ func TestBuildDirectHeardIndex_SkipsOwnTransmissions(t *testing.T) { t.Fatalf("rx copy of the forwarded packet = %#v, want Count 1", a) } } + +// BenchmarkBuildDirectHeardIndex_MixedHops runs the compute pass over 50,000 +// transmissions with 10 observations each: mixed 1-, 2- and 3-byte last +// hops, 5% zero-hop adverts. +func BenchmarkBuildDirectHeardIndex_MixedHops(b *testing.B) { + pm := buildPrefixMap(directHeardNodes) + advert := `{"type":"ADVERT","pubKey":"` + dhUnique + `","signatureValid":true}` + paths := []string{`["66","BB"]`, `["66","A4"]`, `["66","BB11"]`, `["66","A433"]`, `["66","BB1122"]`, `["9999"]`} + packets := make([]*StoreTx, 0, 50000) + for i := 0; i < 50000; i++ { + var tx *StoreTx + path := paths[i%len(paths)] + if i%20 == 0 { + tx = dhTx(RouteFlood, PayloadADVERT, advert) + path = `[]` + } else { + tx = dhTx(RouteFlood, PayloadTXT_MSG, "") + } + for j := 0; j < 10; j++ { + tx.Observations = append(tx.Observations, &StoreObs{ObserverID: "obs" + strconv.Itoa(j), PathJSON: path}) + } + packets = append(packets, tx) + } + b.ResetTimer() + for i := 0; i < b.N; i++ { + buildDirectHeardIndex(packets, pm) + } +} + +// TestDirectHeardNode_ZeroHopNonAdvertLeavesDecodedCacheCold pins that the +// signature check runs for ADVERTs only: the compute pass walks every +// observation, and a zero-hop message must not parse and cache its decoded +// JSON (signatureFailed parses when the text holds a \u escape). +func TestDirectHeardNode_ZeroHopNonAdvertLeavesDecodedCacheCold(t *testing.T) { + pm := buildPrefixMap(directHeardNodes) + tx := dhTx(RouteFlood, PayloadTXT_MSG, `{"type":"TXT_MSG","text":"caf\u00e9"}`) + obs := &StoreObs{ObserverID: "obs1", PathJSON: `[]`} + if got := directHeardNode(tx, obs, pm); got != "" { + t.Fatalf("directHeardNode = %q, want \"\"", got) + } + if tx.parsedDecoded != nil { + t.Fatalf("decoded JSON was parsed for a zero-hop non-advert") + } +} + +// TestDirectHeardNode_RetiredPrefixCreditsNobody: a hop whose prefix a +// retired repeater (moved to inactive_nodes, still able to relay) shares is +// no proof the one active candidate transmitted, as in uniqueHopPrefix. +func TestDirectHeardNode_RetiredPrefixCreditsNobody(t *testing.T) { + pm := buildPrefixMap(directHeardNodes) + pm.retired = map[string]struct{}{"bb11": {}} + tx := dhTx(RouteFlood, PayloadTXT_MSG, "") + if got := directHeardNode(tx, &StoreObs{ObserverID: "obs1", PathJSON: `["66","BB11"]`}, pm); got != "" { + t.Fatalf("directHeardNode = %q, want \"\" for a hop shared with a retired node", got) + } + if got := directHeardNode(tx, &StoreObs{ObserverID: "obs1", PathJSON: `["66","BB1122"]`}, pm); got != dhUnique { + t.Fatalf("directHeardNode = %q, want %q: the 3-byte hop is not retired", got, dhUnique) + } +} diff --git a/internal/packetpath/heard.go b/internal/packetpath/heard.go new file mode 100644 index 000000000..c41ca810a --- /dev/null +++ b/internal/packetpath/heard.go @@ -0,0 +1,46 @@ +package packetpath + +import "strings" + +// MinHeardHopBytes is the shortest path hop that may identify the node an +// observation heard. A 1-byte hop is refused: a node CoreScope does not know +// can share that byte with the one it does know, so even a prefix with a +// single known candidate can name the wrong transmitter. +const MinHeardHopBytes = 2 + +// HeardKey returns the key of the node whose own transmission an observation +// received off the air, following the firmware: +// +// - Flood routes (TRANSPORT_FLOOD 0, FLOOD 1) build the path up as they +// travel: a forwarder appends its own hash before retransmitting +// (Mesh.cpp:349), so the last hop is the node that was heard. +// - Direct routes (2, 3) carry the REMAINING route: a forwarder calls +// removeSelfFromPath before retransmitting, so a non-empty direct path +// never names the node that was heard. +// - An empty path means the originator was heard. Only an ADVERT carries +// the originator's pubkey in the clear, on a flood route or as a zero hop +// on a direct route (Mesh::sendZeroHop). +// - TRACE reuses the path bytes for per-hop SNR, so it never attributes. +// +// lastHop is the final path element as hex ("" for an empty path). +// advertPubkey is the advertised pubkey when the packet is an ADVERT, else "". +// The returned key is lower case; src is "rxlog" (from the path) or "advert". +func HeardKey(routeType int, payloadType byte, lastHop, advertPubkey string) (key, src string, ok bool) { + if !PathBytesAreHops(payloadType) { + return "", "", false + } + if lastHop != "" { + if routeType != RouteTransportFlood && routeType != RouteFlood { + return "", "", false + } + hop := strings.ToLower(strings.TrimSpace(lastHop)) + if len(hop)/2 < MinHeardHopBytes { + return "", "", false + } + return hop, "rxlog", true + } + if advertPubkey != "" { + return strings.ToLower(strings.TrimSpace(advertPubkey)), "advert", true + } + return "", "", false +} diff --git a/internal/packetpath/heard_test.go b/internal/packetpath/heard_test.go new file mode 100644 index 000000000..ae87f613e --- /dev/null +++ b/internal/packetpath/heard_test.go @@ -0,0 +1,47 @@ +package packetpath + +import "testing" + +func TestHeardKey(t *testing.T) { + cases := []struct { + name string + routeType int + payloadType byte + lastHop string + advertPubkey string + wantKey string + wantSrc string + wantOK bool + }{ + {"flood, 2-byte last hop", RouteFlood, 0x05, "BB11", "", "bb11", "rxlog", true}, + {"transport flood counts as flood", RouteTransportFlood, 0x05, "bb11", "", "bb11", "rxlog", true}, + {"3-byte last hop", RouteFlood, 0x05, "bbccdd", "", "bbccdd", "rxlog", true}, + {"1-byte last hop refused", RouteFlood, 0x05, "BB", "", "", "", false}, + {"direct route with a path refused", RouteDirect, 0x05, "bb11", "", "", "", false}, + {"transport direct with a path refused", RouteTransportDirect, 0x05, "bb11", "", "", "", false}, + {"TRACE refused even on flood", RouteFlood, PayloadTRACE, "bb11", "", "", "", false}, + {"0-hop advert on flood", RouteFlood, 0x04, "", "ABCDEF01", "abcdef01", "advert", true}, + {"0-hop advert on direct (sendZeroHop)", RouteDirect, 0x04, "", "abcdef01", "abcdef01", "advert", true}, + {"empty path, no advert pubkey", RouteFlood, 0x05, "", "", "", "", false}, + {"TRACE with empty path refused", RouteFlood, PayloadTRACE, "", "abcdef01", "", "", false}, + } + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + key, src, ok := HeardKey(c.routeType, c.payloadType, c.lastHop, c.advertPubkey) + if key != c.wantKey || src != c.wantSrc || ok != c.wantOK { + t.Errorf("HeardKey(%d, %#x, %q, %q) = (%q, %q, %v), want (%q, %q, %v)", + c.routeType, c.payloadType, c.lastHop, c.advertPubkey, key, src, ok, c.wantKey, c.wantSrc, c.wantOK) + } + }) + } +} + +// Callers pass only the last element of the path, so a 1-byte hop earlier in +// a mixed-size path (["A4","BB11"]) does not matter. +func TestHeardKey_OnlyLastHopLengthCounts(t *testing.T) { + path := []string{"A4", "BB11"} + key, src, ok := HeardKey(RouteFlood, 0x05, path[len(path)-1], "") + if key != "bb11" || src != "rxlog" || !ok { + t.Errorf("got (%q, %q, %v), want (\"bb11\", \"rxlog\", true)", key, src, ok) + } +} diff --git a/public/nodes.js b/public/nodes.js index 72a547732..68e6d0c8c 100644 --- a/public/nodes.js +++ b/public/nodes.js @@ -922,8 +922,8 @@ ${observers.length || relayObserverCount ? `
-

Heard By — direct (${observers.length} observer${observers.length === 1 ? '' : 's'})

- ${observers.length ? '' : '
No observation proves a direct reception here, which is not the same as being out of range.
'} +

Heard By — direct (${observers.length} observer${observers.length === 1 ? '' : 's'})

+ ${observers.length ? '' : '
No observation proves a direct reception here, which is not the same as being out of range.
'} ${observers.length ? ` @@ -2025,8 +2025,8 @@ ${observers.length || relayObserverCount ? `
-

Heard By — direct (${observers.length} observer${observers.length === 1 ? '' : 's'})

- ${observers.length ? '' : '
No observation proves a direct reception here, which is not the same as being out of range.
'} +

Heard By — direct (${observers.length} observer${observers.length === 1 ? '' : 's'})

+ ${observers.length ? '' : '
No observation proves a direct reception here, which is not the same as being out of range.
'}
${observers.map(o => { const stats = [`${o.packetCount} pkts`]; diff --git a/tests/unit/test-direct-rf-heard-by.js b/tests/unit/test-direct-rf-heard-by.js index b1401349b..ef2109137 100644 --- a/tests/unit/test-direct-rf-heard-by.js +++ b/tests/unit/test-direct-rf-heard-by.js @@ -79,6 +79,11 @@ test('a node nobody hears directly still renders the card, with an empty state', 'the empty state must not assert that nobody is in range'); assert.ok(/not the same as being out of range/i.test(html), 'the empty state must say what it cannot conclude, not only what it found'); + // The most common reason for an empty list since the shared rule: a + // 1-byte hop, even with one known candidate, is not proof. + const emptyTitle = (html.match(/
]*title="([^"]*)"[^>]*>[^<]*No observation proves/) || [])[1] || ''; + assert.ok(/1-byte (path )?hop/.test(emptyTitle), + 'the empty state title must say a 1-byte hop is not taken as proof'); assert.ok(/Seen via relay by 35 observers/.test(html), 'expected the relay count'); assert.ok(!/observer-sort-table/.test(html), 'an empty direct list must not render a table header with no rows');
Observer