"""complaint/1.0: present a finding to its subject before publishing it.
Mandatory-first for S1 and S2: an issuer MUST deliver a notice and wait one
window before publishing a kind 30802 against a reachable peer. S3 and S4 MAY
be published at once. The reason is in the specification: most conformance
failures are clock skew, a bug or a misread limit, and a protocol that
publishes before it asks produces a permanent public record of transient
faults. The constants live in constants.json under `complaint`.
The remedy is the subject's answer. Three of its four actions say the subject
fixed something; the fourth contests the finding with counter-evidence. What
the issuer does next is its own decision. `resolve()` states the reference's:
a fix makes the notice eligible for withdrawal, a contest sends the issuer back
to the arithmetic, and neither changes what the window already measured.
"""
from __future__ import annotations
from typing import Any, Iterable, Mapping, Optional, TypedDict
from ..crypto import crypto
from ..wire import schema_files
from ..wire.interfaces import (
ComplaintConstants,
ComplaintEvidenceBody,
ComplaintNoticeBody,
ComplaintRemedyBody,
DIDCommMessage,
SchemaConstantsDocument,
)
ComplaintBody = ComplaintNoticeBody | ComplaintEvidenceBody | ComplaintRemedyBody | Mapping[str, Any]
CONSTANTS: SchemaConstantsDocument = schema_files.load_constants()
C: ComplaintConstants = CONSTANTS['complaint']
PIURI: str = 'https://fleetmesh.org/complaint/1.0'
[docs]def message(
kind: str,
body: ComplaintBody,
frm: str,
to: str,
thid: Optional[str] = None,
mid: Optional[str] = None,
) -> DIDCommMessage:
m: DIDCommMessage = {
'id': mid or 'complaint-%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 notice(
severity: str,
grant_id: str,
epoch: int | str,
metric: str,
detail: Mapping[str, Any],
now: int,
window_seconds: int,
description: str = '',
) -> ComplaintNoticeBody:
"""The finding, presented. detail is one entry of evaluate_window()['per_limit']."""
if severity not in C['notice_required_for'] + C['immediate']:
raise ValueError('a notice presents an adverse finding, not %s' % severity)
body: ComplaintNoticeBody = {
'outcome': severity,
'grant': grant_id,
'window': int(epoch),
'metric': metric,
'observed': detail['measured'],
'limit': detail['limit'],
'deadline': now + C['wait_windows'] * window_seconds,
}
if detail.get('claimed') is not None:
body['claimed'] = detail['claimed']
if description:
body['description'] = description
return body
[docs]def evidence(
evidence_type: str,
payload: Any,
description: str = '',
) -> ComplaintEvidenceBody:
"""What the notice rests on. proof_hash is over the canonical payload, so
the subject can check it is being shown the thing it signed."""
if evidence_type not in ('receipt', 'event', 'envelope'):
raise ValueError('evidence_type must be receipt, event or envelope')
canon = crypto.canonical(payload)
body: ComplaintEvidenceBody = {
'evidence_type': evidence_type,
'proof_hash': crypto.sha256(canon),
'payload': payload,
}
if description:
body['description'] = description
return body
[docs]def remedy(
action: str,
explanation: str = '',
counter_evidence: Optional[Any] = None,
) -> ComplaintRemedyBody:
if action not in C['remedy_actions']:
raise ValueError('remedy action must be one of %s' % C['remedy_actions'])
body: ComplaintRemedyBody = {'action': action}
if explanation:
body['explanation'] = explanation
if counter_evidence is not None:
body['counter_evidence'] = counter_evidence
if action == 'contested' and counter_evidence is None:
raise ValueError('a contest carries counter-evidence or it is a denial')
return body
[docs]class ComplaintAppealBody(TypedDict, total=False):
grounds: str
audit_logs: list[Any]
[docs]class ComplaintWithdrawBody(TypedDict, total=False):
withdrawn_at: int
reason: str
[docs]def appeal(grounds: str, audit_logs: Optional[Iterable[Any]] = None) -> ComplaintAppealBody:
body: ComplaintAppealBody = {'grounds': grounds}
if audit_logs:
body['audit_logs'] = list(audit_logs)
return body
[docs]def withdraw(now: int, reason: str = '') -> ComplaintWithdrawBody:
body: ComplaintWithdrawBody = {'withdrawn_at': now}
if reason:
body['reason'] = reason
return body
[docs]def may_publish(
severity: str,
now: int,
notice_at: Optional[int] = None,
window_seconds: Optional[int] = None,
reachable: bool = True,
) -> bool:
"""Whether a kind 30802 with this outcome may be published now.
S3 and S4: yes. S1 and S2 against a reachable peer: only after a notice
was delivered and a window has passed. Against an unreachable peer there
is nobody to notify, and the rule says reachable.
"""
if severity in C['immediate']:
return True
if severity not in C['notice_required_for']:
return False
if not reachable:
return True
if notice_at is None:
return False
if window_seconds is None:
window_seconds = CONSTANTS['grant']['window_seconds_default']
if isinstance(window_seconds, bool) or not isinstance(window_seconds, int) or window_seconds <= 0:
# Zero or negative would make the wait vanish; `or` once turned 0
# into the default, which hid the misconfiguration instead.
raise ValueError('window_seconds must be a positive integer')
return now >= notice_at + C['wait_windows'] * window_seconds
[docs]def resolve(remedy_body: Mapping[str, Any]) -> str:
"""The reference's reading of a remedy. Returns 'withdraw-eligible' or 'reevaluate'."""
return 'reevaluate' if remedy_body.get('action') == 'contested' else 'withdraw-eligible'