"""Whether a kind 30802 report may be counted at all.
Two rules do the work, and both are about the reporter rather than the finding:
a report must cite a grant the reporter itself issued to the subject, and must
carry evidence the subject signed. A report failing either is discarded unread,
which is what keeps the reputation system evidence-backed rather than hearsay.
Evidence pins the subject's half of a disagreement and nothing else. Nobody but
the reporter saw the traffic, so a reader takes the measurement on the
reporter's standing and checks only that the subject really said what it is
quoted as saying. That is why `immune()` lets two nodes disagree without either
being refuted.
Evidence travels **inline**, in the report's own content, and is verified there.
It used to be a hash a reader resolved from a relay, which worked only for the
one artefact that is a public nostr event. Everything else that proves what a
subject did - its receipts, the hops it signed on a delivery envelope - is a
private DIDComm body that no relay serves, so a report about the protocol's
central offence could not be checked by anybody. An artefact carried in the
report needs nothing served: hash it, compare it to the tag, verify the
subject's signature on it. Resolution is still tried for an `event`, because a
nostr event genuinely is public and need not be copied.
"""
from __future__ import annotations
import json
from typing import Any, Callable, Mapping, Optional, Sequence
from ..crypto import crypto
from ..storage import store
from ..wire.interfaces import EventLike, NostrEvent, UnsignedNostrEvent
ADVERSE: tuple[str, ...] = ('S1', 'S2', 'S3', 'S4')
INLINE_KINDS: tuple[str, ...] = ('receipt', 'envelope', 'event')
[docs]def build(
reporter_pubkey: str,
subject_pubkey: str,
severity: str,
grant_id: str,
windows: tuple[int, int] | Sequence[int],
evidence: Sequence[tuple[str, str] | tuple[str, str, Any] | Sequence[Any]],
now: int,
ttl_seconds: int,
observed: Optional[tuple[str, Any, Any] | Sequence[Any]] = None,
claimed: Optional[tuple[str, Any] | Sequence[Any]] = None,
notice: Optional[tuple[str, int] | Sequence[Any]] = None,
content: str = '',
grant_envelope: Optional[EventLike] = None,
) -> UnsignedNostrEvent:
"""A kind 30802, shaped so that admissible() accepts it.
windows is (first_epoch, last_epoch). evidence is [(type, ref)], each ref
something the subject signed. observed is (metric, measured, limit) and
claimed (metric, value); notice is (thid, delivered_at) from complaint/1.0.
The report is the reporter's current verdict, not a log: d is the subject,
so a later one replaces it.
grant_envelope is the kind 30801 the grant tag names, carried inline for
the same reason the evidence is. A grant is addressable under a blinded
tag, so every new grant to a subject replaces the last at that coordinate
and relays drop the superseded one - and a report is about a window, so it
cites the grant that governed *then*. The ladder amends a grant whenever
it adjusts a limit, which includes the increase a clean window earns, so
within about an hour of publication a report's citation resolved to
nothing and it became inadmissible to every reader. Measured on a running
node: five envelopes issued to one peer, one still served. A report that
carries its own is checkable for as long as it exists.
"""
if severity not in ADVERSE:
raise ValueError('a report is adverse only; %s is not a finding' % severity)
ev_list: list[tuple[Any, ...]] = [tuple(e) for e in evidence]
if not ev_list:
raise ValueError('evidence or nothing')
inline = {}
if grant_envelope is not None:
if grant_envelope.get('id') != grant_id:
raise ValueError('the grant envelope carried is not the one the grant tag names')
inline[grant_id] = grant_envelope
for i, entry in enumerate(ev_list):
if len(entry) == 3: # (kind, id, artefact): carried inline
kind, ref, artefact = entry
inline[ref] = artefact
ev_list[i] = (kind, ref)
tags: list[list[str]] = [
['d', subject_pubkey],
['outcome', severity],
['grant', grant_id],
['windows', str(windows[0]), str(windows[1])],
]
if observed:
tags.append(['observed', str(observed[0]), str(observed[1]), str(observed[2])])
if claimed:
tags.append(['claimed', str(claimed[0]), str(claimed[1])])
for kind, ref in ev_list:
tags.append(['evidence', str(kind), str(ref)])
if notice:
tags.append(['notice', str(notice[0]), str(notice[1])])
tags.append(['expiration', str(now + ttl_seconds)])
if inline:
content = crypto.canonical({'note': content, 'evidence': inline}).decode()
return store.make_event(reporter_pubkey, now, 30802, tags, content)
[docs]def evidence_id(artefact: Any) -> str:
"""The identifier an evidence tag carries for an inline artefact.
SHA-256 of its canonical form, which for a receipt is exactly the chain link
the issuer already acknowledges, so a receipt is cited by the same 32 bytes
it was acked with.
"""
from ..accounting import accounting
return accounting.link(artefact)
[docs]def inline_evidence(report: EventLike) -> Mapping[str, Any]:
"""{id: artefact} carried in the report's content, or {} if none is."""
body = report.get('content') or ''
if not body.startswith('{'):
return {}
try:
doc = json.loads(body)
except ValueError:
return {}
ev = doc.get('evidence')
return ev if isinstance(ev, dict) else {}
[docs]def note_of(report: EventLike) -> str:
"""The human half of the content, whatever shape the content is in."""
body = report.get('content') or ''
if not body.startswith('{'):
return body
try:
return json.loads(body).get('note', '')
except ValueError:
return body
def _signed_by_subject(
kind: str,
artefact: Any,
subject: str,
verify_sig: Callable[[Any], bool],
) -> bool:
"""Does this inline artefact carry the subject's own signature?"""
from ..accounting import accounting
from ..storage import replication
match kind:
case 'receipt':
return accounting.verify_receipt(artefact, subject)
case 'envelope':
return replication.signed_by(artefact, subject)
case 'event':
return isinstance(artefact, Mapping) and artefact.get('pubkey') == subject and bool(verify_sig(artefact))
case 'handover':
# A handover is the signer's asserted claim over the set it names,
# so it is evidence against the signer the way a kind 30803 is.
from . import coverage
return isinstance(artefact, Mapping) and coverage.verify_handover(artefact, subject)
case _:
return False
def _barred_by_handover(kind: str, artefact: Any, reporter_pubkey: str) -> list[str]:
"""Why this reporter may not cite this coverage claim, or nothing.
A claim resting on a handover names everyone who signed for the set, and a
hole any of them files in it is their own. The rule is coverage's; this is
where a report meets it, beside the rule that discards a report with no
grant behind it.
"""
if kind != 'event' or not isinstance(artefact, dict) or artefact.get('kind') != 30803:
return []
from . import coverage
why = coverage.barred_reporter(artefact, reporter_pubkey)
return [why] if why else []
[docs]def admissible(
report: EventLike,
reporter_pubkey: str,
resolve_event: Callable[[str], Optional[NostrEvent]],
verify_sig: Callable[[Any], bool],
) -> tuple[bool, list[str]]:
"""Returns (ok, reasons). resolve_event(id) -> event or None."""
reasons: list[str] = []
# First tag of a name wins, as everywhere else a descriptor or report is
# read (store.first_tag, identity): a second `outcome` or `grant` appended
# after the one the reporter signed over cannot replace it.
first = lambda n: store.first_tag(report, n)
multi = lambda n: store.tags(report, n)
outcome = first('outcome')
if not outcome or len(outcome) < 2 or outcome[1] not in ADVERSE:
reasons.append('outcome must be S1..S4; there is no positive attestation')
subject_tag = first('d')
subject = subject_tag[1] if subject_tag and len(subject_tag) > 1 else None
if not subject:
reasons.append('no subject')
grant = first('grant')
if not grant or len(grant) < 2:
reasons.append('no grant tag: a report needs a relationship the reporter entered into')
else:
# The report's own copy first, then the relays. A superseded grant is
# served by nobody, and a report about a past window cites exactly
# that. An inline copy is held to more than a resolved one: it must
# be the id it is filed under, and it must verify.
carried = inline_evidence(report).get(grant[1])
if carried is not None:
if not isinstance(carried, Mapping) or carried.get('id') != grant[1] or not verify_sig(carried):
reasons.append('the grant carried inline is not a signed kind 30801 with that id')
elif carried.get('pubkey') != reporter_pubkey:
reasons.append('the grant carried inline was published by %s, not the reporter'
% (carried.get('pubkey') or '?')[:16])
elif carried.get('kind') != 30801:
reasons.append('the grant carried inline is a kind %s, not a grant' % carried.get('kind'))
else:
ev = resolve_event(grant[1])
if ev is None:
reasons.append('grant tag does not resolve and the report carries no copy of it')
elif ev.get('pubkey') != reporter_pubkey:
reasons.append('grant was published by %s, not the reporter'
% (ev.get('pubkey') or '?')[:16])
elif ev.get('kind') != 30801:
reasons.append('grant tag points at a kind %s, not a grant' % ev.get('kind'))
evidence = multi('evidence')
inline = inline_evidence(report)
if not evidence:
reasons.append('no evidence tag')
else:
signed_by_subject = False
for e in evidence:
if len(e) < 3:
reasons.append('malformed evidence tag')
continue
kind, ident = e[1], e[2]
artefact = inline.get(ident)
if artefact is not None:
if not isinstance(artefact, Mapping) or evidence_id(artefact) != ident:
reasons.append('inline %s does not hash to the id it is filed under' % kind)
continue
if subject and _signed_by_subject(kind, artefact, subject, verify_sig):
signed_by_subject = True
reasons += _barred_by_handover(kind, artefact, reporter_pubkey)
continue
ev = resolve_event(ident)
if ev is None:
continue
if subject and ev.get('pubkey') == subject and verify_sig(ev):
signed_by_subject = True
reasons += _barred_by_handover(kind, ev, reporter_pubkey)
if not signed_by_subject:
reasons.append('no evidence carries or resolves to something the subject itself signed')
return (not reasons), reasons
[docs]def refuted(
report: EventLike,
cited_limits: Mapping[str, Any],
cited_measured: Mapping[str, Any],
cited_claimed: Mapping[str, Any],
classifier: Callable[[Mapping[str, Any], Mapping[str, Any], Mapping[str, Any]], Mapping[str, Any]],
) -> tuple[bool, str]:
"""Does the report's own cited evidence produce the outcome it claims?
The classifier is deterministic, so any reader holding the grant and the
evidence can decide this alone. A reporter citing a valid receipt and then
claiming a severity the arithmetic does not support is refuted - which is
what puts a price on filing a finding, and what the attack surface means by
a trusted node spending its standing exactly once.
"""
claimed_outcome_tag = store.first_tag(report, 'outcome')
claimed_outcome = claimed_outcome_tag[1] if claimed_outcome_tag and len(claimed_outcome_tag) > 1 else ''
got: str = classifier(cited_limits, cited_measured, cited_claimed)['severity']
return got != claimed_outcome, got
[docs]def immune(evidence_verified: bool, finding_follows: bool) -> bool:
"""Objective evidence immunity, narrowed.
A reporter is immune when its evidence verifies AND the finding follows from
that evidence. "Objective" means objectively checkable by the reader, not
"unconditional". Immunity on verification alone would make a false report
free, which contradicts the price the severity ladder claims to put on one.
Two nodes that measured different traffic still disagree without either being
refuted: they cited different evidence, and each one's arithmetic follows.
"""
return bool(evidence_verified) and bool(finding_follows)
[docs]def false_report_rate(evaluated: int, unsupported: int, refuted_count: int) -> float:
"""The reporter-accountability term in the trust weight.
Both numerator categories are decidable by the reader alone. Undefined when
nothing has been evaluated, which constants.json fixes at zero.
"""
if not evaluated:
return 0.0
return (unsupported + refuted_count) / evaluated