"""standing/1.0: what one node tells a third party about another, if it chooses.
The specification says two things about it and both are here. Answering is
discretionary and declining is not adverse, so a node answers only about
subjects it holds a grant to and declines everything else without that
refusal meaning anything. And a tell carries a streak, not a score: the count
of clean windows since the last one that was not, which is the same number the
reader's own age factor uses in reporter_weight.
The Ledger is the per-subject record a window evaluation writes into. Nothing
in it is public; a tell is a summary the holder chooses to give.
"""
from __future__ import annotations
from typing import Any, Iterable, Mapping, Optional
from ..wire import schema_files
from ..wire.interfaces import DIDCommMessage, SchemaConstantsDocument, StandingAskBody, StandingTellBody
CONSTANTS: SchemaConstantsDocument = schema_files.load_constants()
PIURI: str = 'https://fleetmesh.org/standing/1.0'
ADVERSE: tuple[str, ...] = ('S1', 'S2', 'S3', 'S4')
[docs]def message(
kind: str,
body: StandingAskBody | StandingTellBody | Mapping[str, Any],
frm: str,
to: str,
thid: Optional[str] = None,
mid: Optional[str] = None,
) -> DIDCommMessage:
m: DIDCommMessage = {
'id': mid or 'standing-%s-%s' % (kind, frm[-8:]),
'type': '%s/%s' % (PIURI, kind),
'from': frm,
'to': [to],
'body': body,
}
if thid:
m['thid'] = thid
return m
[docs]def ask(target_did: str, query: Optional[Iterable[str]] = None) -> StandingAskBody:
body: StandingAskBody = {'target': target_did}
if query:
body['query'] = list(query)
return body
[docs]class Ledger:
"""Per-subject window history, as the issuer of that subject's grant saw it."""
[docs] def __init__(self) -> None:
self.windows: dict[str, list[tuple[int, str]]] = {} # subject pubkey -> [(epoch, severity)]
self.tier: dict[str, str] = {} # subject pubkey -> current tier
self.reported: set[str] = set() # subjects this node has published a kind 30802 against
# The third term of w(r): reporter pubkey -> {report id: contradicted}.
# Kept per report so re-reading the same one never counts twice, and
# so a reporter that withdraws nothing cannot dilute its own rate by
# republishing. Both halves are decidable by this reader alone, from
# the report and the evidence it cites: see trust.false_report.
self.reports_seen: dict[str, dict[str, bool]] = {}
[docs] def record(self, subject: str, epoch: int | str, severity: str, tier: str) -> None:
"""One window's verdict, kept in WINDOW order rather than arrival order.
Everything downstream reads this list as a history: clean_windows()
takes the streak from the end of it, and the tier a subject holds is
the one its newest window left. Appending made both of those mean "the
most recently recorded", which is a different thing - a window can be
priced late. A contested remedy asks for one to be evaluated again, and
it can arrive days after the window it is about.
On the live mesh one did. Four windows from eight days earlier were
re-priced S2 when a node restarted, and because they landed at the end
of the list they set the peer's tier to probation and its clean streak
to zero - behind about 170 consecutive clean windows, and against a
ladder that only goes down. The ledger recorded the contradiction
plainly: a window whose own severity was S0, holding a tier of
probation.
Re-pricing an old window is still a finding and still reported. What it
is not is news about where the subject stands now.
"""
e = int(epoch)
rows = self.windows.setdefault(subject, [])
for i, (at, _sev) in enumerate(rows):
if at == e:
rows[i] = (e, severity)
break
else:
rows.append((e, severity))
if len(rows) > 1 and e < rows[-2][0]:
rows.sort(key=lambda r: r[0])
if e >= rows[-1][0]:
self.tier[subject] = tier
[docs] def forget_window(self, subject: str, epoch: int | str) -> Optional[str]:
"""Take one window back out of the history. Returns the severity it held.
A window this node no longer stands behind is not a window it priced
S0: it is a window it has nothing to say about, which is what an
unevaluated window already means everywhere else - `evaluations()`
yields severity None for one and the replay skips it. Recording a
retraction as a clean window would be a second false statement in
place of the first.
"""
rows = self.windows.get(subject) or []
for i, (at, sev) in enumerate(rows):
if at == int(epoch):
del rows[i]
if not rows:
self.windows.pop(subject, None)
self.tier.pop(subject, None)
return sev
return None
[docs] def severity_of(self, subject: str, epoch: int | str) -> Optional[str]:
"""What this ledger holds for one window, or None if it holds none."""
for e, sev in self.windows.get(subject) or []:
if e == int(epoch):
return sev
return None
[docs] def amend(self, subject: str, epoch: int | str, severity: str) -> Optional[str]:
"""Correct one window already recorded, in place.
A window is priced when its grace ends and a receipt covering it can
arrive after that: the claim was late, not absent. Recording the
corrected reading as a NEW window would count one window twice and
would leave the streak broken by a reading that no longer stands,
which is the whole of what the correction is for. Returns the severity
it replaced, or None if this subject has no such window.
"""
rows = self.windows.get(subject) or []
for i, (e, _sev) in enumerate(rows):
if e == int(epoch):
was = rows[i][1]
rows[i] = (int(epoch), severity)
return was
return None
[docs] def reported_against(self, subject: str) -> None:
self.reported.add(subject)
[docs] def on_revocation(self, subject: str) -> None:
"""Standing MUST NOT transfer. The subject's record ends here and a
successor starts with none, so there is nothing to move."""
self.tier[subject] = 'revoked'
[docs] def knows(self, subject: str) -> bool:
return subject in self.tier
[docs] def record_report(self, reporter: str, report_id: str, contradicted: bool) -> None:
"""One kind 30802 this node read and could decide about.
contradicted is True when the report is unsupported (its evidence does
not resolve, or resolves to something the subject did not sign) or
refuted (the evidence verifies and the published classifier run over
it does not produce the outcome claimed). Anything else is a finding
this reader has no grounds to dispute, which includes two honest nodes
that measured different traffic.
"""
self.reports_seen.setdefault(reporter, {})[report_id] = bool(contradicted)
[docs] def report_record(self, reporter: str) -> tuple[int, int]:
"""(contradicted, evaluated) for a reporter, as this node has seen it."""
seen = self.reports_seen.get(reporter) or {}
return sum(1 for v in seen.values() if v), len(seen)
[docs] def evaluated_windows(self, subject: str) -> int:
return len(self.windows.get(subject, []))
[docs] def clean_windows(self, subject: str) -> int:
"""The streak: clean windows since the most recent one that was not."""
n = 0
for _, sev in reversed(self.windows.get(subject, [])):
if sev != 'S0':
break
n += 1
return n
[docs] def tell(self, subject: str) -> Optional[StandingTellBody]:
"""The body of a tell, or None if this node has nothing to say."""
if not self.knows(subject):
return None
return {
'target': 'did:nostr:%s' % subject,
'tier': self.tier[subject],
'clean_windows': self.clean_windows(subject),
'evaluated_windows': self.evaluated_windows(subject),
'has_adverse_reports': subject in self.reported,
}
[docs] def answer(
self,
ask_body: StandingAskBody | Mapping[str, Any],
willing: bool = True,
) -> tuple[str, StandingTellBody | dict[str, str] | Mapping[str, Any]]:
"""('tell', body) or ('decline', body). Declining is never a finding."""
target: str = str(ask_body.get('target', ''))
subject: str = target.rsplit(':', 1)[-1]
if not willing:
return 'decline', {'reason': 'policy'}
body = self.tell(subject)
if body is None:
return 'decline', {'reason': 'no grant to that node'}
return 'tell', body