Source code for fleetmesh_core.wire.interfaces

"""Formal interfaces, protocols, and data contracts for fleetmesh_core/.

Standard library only. All wire types reflect the normative JSON Schemas in
schemas/ and the protocol invariants verified across the reference implementation.
"""
from __future__ import annotations

from dataclasses import dataclass
from typing import (
    Any,
    Callable,
    Mapping,
    Optional,
    Protocol,
    Sequence,
    TypedDict,
    Union,
    runtime_checkable,
)

Tag = list[str]
TagList = list[Tag]


[docs]class NostrEvent(TypedDict): id: str pubkey: str created_at: int kind: int tags: TagList content: str sig: str
[docs]class UnsignedNostrEvent(TypedDict): id: str pubkey: str created_at: int kind: int tags: TagList content: str
# What a reader accepts: a signed event, one still unsigned (the builders in # fleetmesh_core/ produce those; node/ signs them), or any mapping off the wire. Readers # only look at tags and fields, so neither the presence of `sig` nor the # concrete dict type is theirs to demand. EventLike = Union[NostrEvent, UnsignedNostrEvent, Mapping[str, Any]] # Functional form because tag filter keys ('#p', '#e', '#t', '#d', '#a', '#g', '#r', '#q') are not valid Python identifiers. NostrFilter = TypedDict('NostrFilter', { 'ids': list[str], 'authors': list[str], 'kinds': list[int], 'since': int, 'until': int, 'limit': int, 'search': str, '#p': list[str], '#e': list[str], '#t': list[str], '#d': list[str], '#a': list[str], '#g': list[str], '#r': list[str], '#q': list[str], }, total=False)
[docs]class DeliveryHop(TypedDict): node: str at: int sig: str
[docs]class DeliveryEnvelope(TypedDict): event: NostrEvent path: list[DeliveryHop]
[docs]class ReceiptCounters(TypedDict, total=False): conn_open: int conn_rate: int req: int events_in: int bytes_in: int bytes_out: int blob_bytes: int sync_ranges: int errors: int dups_sent: int
[docs]class ReceiptBody(TypedDict, total=False): grant: str window: int seq: int prev: str counters: dict[str, int] at: int sig: str
[docs]class ReceiptChainEntry(TypedDict, total=False): receipt: ReceiptBody canonical: str sha256: str
[docs]class ReceiptChainDoc(TypedDict): chain: list[ReceiptChainEntry] head: str
[docs]class SilenceEvaluation(TypedDict): state: str severity: Optional[str] remedy: str
[docs]class WindowEvaluationDetail(TypedDict): measured: int | float claimed: Optional[int | float] limit: int | float overrun: float divergence: float severity: str
[docs]class CapacitySummary(TypedDict): declared: bool pressure: Optional[float] binding: Optional[str] rungs: list[str] measured: dict[str, int | float]
[docs]class DescriptorConstants(TypedDict, total=False): max_lifetime_seconds_anchor_edge: int max_lifetime_seconds_leaf: int default_pow_bits: int pow_bits_of: str required_protocols: list[str] protocol_floors: dict[str, str] protocol_floors_note: str required_protocols_note: str optional_protocols: list[str] optional_protocols_note: str endpoints_digest: str did_contexts: list[str] did_contexts_note: str
[docs]class GrantConstants(TypedDict, total=False): window_seconds_default: int window_grace_fraction: float opening_limit_fraction: float opening_applies_to: list[str] opening_limit_why: str divergence_floor_fraction: float divergence_floor_sessions: int divergence_floor_why: str overrun_tolerance: float aimd_increase_fraction: float aimd_increase_is_load_weighted: bool aimd_increase_weighting: str aimd_min_increase_fraction: float aimd_min_increase_why: str decay_fraction: float decay_idle_windows: int decay_by_disuse: str decay_floor: str decay_is_not_adverse: str aimd_used_is_required: str aimd_decrease_s1: float aimd_decrease_s2: float s3_zero_hours: int max_clock_skew_seconds: int visibility: str pair_blinding: str divergence_tolerance: float schedule_is_a_ratio: str severity_classification: Mapping[str, Any] epoch: str epoch_note: str window_evaluation: Mapping[str, Any] receipt_signature: str counter_of: dict[str, str] advisory_limits: Mapping[str, Any] evidence: str
[docs]class HopSignatureConstants(TypedDict, total=False): domain: str hash: str
[docs]class DeliveryConstants(TypedDict, total=False): max_forward_hops: int hop_signature: HopSignatureConstants
[docs]class VerifyModeSpec(TypedDict, total=False): param: str evidence: str needs_plaintext: bool default_rate: float status: str
[docs]class MarketConstants(TypedDict, total=False): default_verify_sample_rate: float settlement: str sampling_model: str verify_modes: dict[str, VerifyModeSpec] progress_states: list[str]
[docs]class ProjectionConstants(TypedDict, total=False): kind: int subject: str canonical_relay: str rank_by_outcome: dict[str, int] published_when: str
[docs]class DiscoveryConstants(TypedDict, total=False): kind: int subject: str tags: str content: str published_when: str
[docs]class NIP11Limitation(TypedDict, total=False): max_message_length: int max_subscriptions: int max_filters: int max_limit: int max_subid_length: int min_pow_difficulty: int | float | str auth_required: bool | int payment_required: bool | int restricted_writes: bool | int
[docs]class NIP11RelayInfo(TypedDict, total=False): name: str description: str pubkey: str contact: str supported_nips: list[int] software: str version: str limitation: NIP11Limitation | Mapping[str, Any]
[docs]class ComplaintConstants(TypedDict, total=False): notice_required_for: list[str] immediate: list[str] wait_windows: int remedy_actions: list[str]
[docs]class TransportConstants(TypedDict, total=False): ladder_rank: dict[str, int] ladder_tie_break: str attempt_timeout_seconds: int
[docs]class SchemaConstantsDocument(TypedDict, total=False): version: str crypto: Mapping[str, Any] grant: GrantConstants blinding: Mapping[str, Any] tier_weight: dict[str, float] trust: Mapping[str, Any] delivery: DeliveryConstants descriptor: DescriptorConstants did: Mapping[str, Any] leaf: Mapping[str, Any] market: MarketConstants tier_limits: Mapping[str, Any] capacity: Mapping[str, Any] resilience: Mapping[str, Any] commitment: Mapping[str, Any] canonical: Mapping[str, Any] transport: TransportConstants blob_wire: Mapping[str, Any] store: Mapping[str, Any] complaint: ComplaintConstants projection: ProjectionConstants discovery: DiscoveryConstants roster: Mapping[str, Any]
[docs]class KindSpec(TypedDict, total=False): description: str rfc: str tags: dict[str, list[str]] required_tags: list[str]
[docs]class SchemaKindsDocument(TypedDict, total=False): version: str kinds: dict[str, KindSpec] reused: Mapping[str, Mapping[str, Any]]
[docs]class SchemaMessagesDocument(TypedDict, total=False): version: str envelope: str protocols: Mapping[str, Mapping[str, Any]] reused_protocols: list[str] transports: Mapping[str, Mapping[str, Any]] topics: Mapping[str, Mapping[str, Any]] surfaces: Mapping[str, Any]
[docs]class PeeringWant(TypedDict, total=False): shard: str filter: NostrFilter mode: str since: int
[docs]class PeeringOfferItem(TypedDict, total=False): shard: str completeness: str fingerprint: str
[docs]class PeeringBudgetSelf(TypedDict, total=False): events_in: int bytes_in: int window: int
[docs]class PeeringPow(TypedDict, total=False): bits: int event: str
[docs]class GrantLimits(TypedDict, total=False): conn_rate: int req: int events_in: int bytes_in: int bytes_out: int blob_bytes: int sync_ranges: int errors: int dup_ratio: float
[docs]class GrantScope(TypedDict, total=False): push: NostrFilter pull: NostrFilter
[docs]class GrantPayload(TypedDict, total=False): subject: str tier: str window: int limits: Mapping[str, Any] scope: GrantScope | Mapping[str, Any] receipt: list[int] settlement: str blinding: str
[docs]class DIDCommAttachmentData(TypedDict, total=False): json: Mapping[str, Any] base64: str
[docs]class DIDCommAttachment(TypedDict, total=False): id: str mime_type: str data: DIDCommAttachmentData
DIDCommMessage = TypedDict('DIDCommMessage', { 'id': str, 'type': str, 'from': str, 'to': list[str], 'body': Mapping[str, Any], 'thid': str, 'attachments': list[DIDCommAttachment], 'ack': list[str], 'please_ack': list[str], 'created_time': int, 'expires_time': int, }, total=False)
[docs]class StandingTellBody(TypedDict): target: str tier: str clean_windows: int evaluated_windows: int has_adverse_reports: bool
[docs]class StandingAskBody(TypedDict, total=False): target: str query: list[str]
[docs]class ComplaintNoticeBody(TypedDict, total=False): outcome: str grant: str window: int metric: str observed: int | float limit: int | float deadline: int claimed: int | float description: str
[docs]class ComplaintEvidenceBody(TypedDict, total=False): evidence_type: str proof_hash: str payload: Any description: str
[docs]class ComplaintRemedyBody(TypedDict, total=False): action: str explanation: str counter_evidence: Any
Point2D = tuple[int, int] StrainDirection = tuple[str, str, str]
[docs]@runtime_checkable class MeshStoreProtocol(Protocol): """Storage backend contract for Nostr events and range queries."""
[docs] def get_event(self, event_id: str) -> Optional[Mapping[str, Any]]: ...
[docs] def has_event(self, event_id: str) -> bool: ...
[docs] def insert_event(self, event: Mapping[str, Any], now: int) -> str: ...
[docs] def enumerate_range(self, filt: Mapping[str, Any], since: int, until: int, now: int) -> list[str]: ...
[docs] def items_range(self, filt: Mapping[str, Any], since: int, until: int, now: int) -> list[tuple[int, str]]: ...
[docs] def fingerprint_range(self, filt: Mapping[str, Any], since: int, until: int, now: int) -> str: ...
[docs] def newest_matching(self, filt: Mapping[str, Any], since: int, until: int,
now: int, cap: int) -> list[Mapping[str, Any]]: ...
[docs]@runtime_checkable class GrantProtocol(Protocol): """Bilateral grant contract governing session capacity and filtering.""" event_id: str tier: str limits: Mapping[str, Any] scope: Mapping[str, Any] window: int
[docs] def permits(self, event: Mapping[str, Any], direction: str = 'push') -> bool: ...
[docs] def exceeded(self, counters: Mapping[str, int]) -> dict[str, float]: ...
[docs]@runtime_checkable class SessionProtocol(Protocol): """Sync session state machine interface.""" grant: GrantProtocol counters: dict[str, int] findings: list[tuple[str, str]] shard: str since: int until: int now: int is_initiator: bool
[docs] def open(self) -> Mapping[str, Any]: ...
[docs] def on_open(self, msg: Mapping[str, Any]) -> Optional[Mapping[str, Any]]: ...
[docs] def on_range(self, msg: Mapping[str, Any]) -> Optional[Mapping[str, Any]]: ...
[docs] def on_need(self, msg: Mapping[str, Any]) -> Optional[Mapping[str, Any]]: ...
[docs] def on_deliver(self, msg: Mapping[str, Any]) -> Optional[Mapping[str, Any]]: ...
[docs] def dup_ratio(self) -> float: ...
[docs] def receipt(self, seq: int = 0, prev: Optional[str] = None, at: Optional[int] = None) -> ReceiptBody: ...
[docs]@runtime_checkable class LedgerProtocol(Protocol): """Standing ledger query and evaluation protocol.""" windows: dict[str, list[tuple[int, str]]] tier: dict[str, str] reported: set[str] reports_seen: dict[str, dict[str, bool]]
[docs] def record(self, subject: str, epoch: int, severity: str, tier: str) -> None: ...
[docs] def severity_of(self, subject: str, epoch: int) -> Optional[str]: ...
[docs] def amend(self, subject: str, epoch: int, severity: str) -> Optional[str]: ...
[docs] def reported_against(self, subject: str) -> None: ...
[docs] def on_revocation(self, subject: str) -> None: ...
[docs] def knows(self, subject: str) -> bool: ...
[docs] def record_report(self, reporter: str, report_id: str, contradicted: bool) -> None: ...
[docs] def report_record(self, reporter: str) -> tuple[int, int]: ...
[docs] def evaluated_windows(self, subject: str) -> int: ...
[docs] def clean_windows(self, subject: str) -> int: ...
[docs] def tell(self, subject: str) -> Optional[Mapping[str, Any]]: ...
[docs] def answer(self, ask_body: Mapping[str, Any], willing: bool = True) -> tuple[str, Mapping[str, Any]]: ...
[docs]@runtime_checkable class PolicyProtocol(Protocol): """Peering policy requirements for admitting a peer.""" pow_bits: int transports: dict[str, int] shards: Mapping[str, Any] open_enrolment: bool opening_tier: str protocols: set[str] tiers: dict[str, str]
[docs] def tier_for(self, subject_pubkey: str) -> str: ...
[docs]@dataclass(frozen=True) class ProtocolHealth: """Operational telemetry and status of a protocol package.""" healthy: bool status: str connections_active: int messages_in: int messages_out: int errors: Sequence[str] = ()
[docs]@dataclass(frozen=True) class RouteMatch: """A matched HTTP or WebSocket route handler.""" path_prefix: str methods: tuple[str, ...] handler: Callable[[Any], Any] is_websocket: bool = False
[docs]@runtime_checkable class ProtocolHostRouter(Protocol): """Unified HTTP / WebSocket multiplexer mounted on the node's public port."""
[docs] def mount_route(
self, prefix: str, handler: Callable[..., Any], methods: Sequence[str] = ('GET',), owner: str = '', ) -> None: ...
[docs] def mount_websocket(
self, path: str, handler: Callable[..., Any], owner: str = '', ) -> None: ...
[docs] def unmount_all(self, owner: str) -> None: ...
[docs]@runtime_checkable class ProtocolIdentityAdapter(Protocol): """Translates between Fleetmesh keys and foreign protocol identity models."""
[docs] def resolve_id(self, uri: str) -> Optional[str]: ...
[docs] def sign_assertion(self, payload: bytes) -> bytes: ...
[docs] def verify_assertion(self, payload: bytes, signature: bytes, pubkey: str) -> bool: ...
[docs]@runtime_checkable class ProtocolPackage(Protocol): """The formal interface implemented by every pluggable protocol package.""" name: str # 'nostr', 'atproto', 'activitypub', 'ssb' version: str # '1.0.0' standards: tuple[str, ...] # ('com.atproto.sync', 'did:plc', etc.)
[docs] def configure(self, config: Mapping[str, Any]) -> None: """Parse, validate, and store the protocol-specific configuration block.""" ...
[docs] def identity_adapter(self, keystore: Any) -> Optional[ProtocolIdentityAdapter]: """Return the identity and cryptographic adapter for this protocol family. The node does not call this yet: packages build and use their adapters themselves, and nothing resolves an identity across packages. It is kept as the extension point for that, not as a contract anything exercises - an implementation is tested by its own suite, not by a running node (audit 2026-10-15). `storage_adapter` beside it was removed: every package already receives its stores in its constructor. """ ...
[docs] def mount_ingress(self, host: ProtocolHostRouter) -> None: """Register HTTP and WebSocket route handlers onto the shared public host face.""" ...
[docs] def transport_rung(self, context: Any) -> Optional[Any]: """Return an outbound TransportProtocol rung for TransportRouter, if supported.""" ...
[docs] def compartments(self) -> tuple[type[Any], ...]: """Return any background Compartment classes to splice into NodeApp MANIFEST.""" ...
[docs] def start(self) -> None: """Boot the protocol runtime (open sockets, connect to upstreams).""" ...
[docs] def stop(self) -> None: """Gracefully terminate connections and release listeners.""" ...
[docs] def health(self) -> ProtocolHealth: """Return real-time operational metrics and health status.""" ...
[docs] def descriptor_capabilities(self) -> tuple[tuple[str, str], ...]: """Return protocol capability tags (e.g. ('c', 'https://example.org/atproto/...')) for kind 11801.""" ...