Source code for fleetmesh_core.services.lifecycle

"""The node says it is alive, and the node says it is finished: heartbeat
(21801) and revocation (11802).

Two kinds the specification defines and the reference had not built. Each is
small, and each carries one rule that is only real once it is executable: a
heartbeat that contradicts the descriptor is a misreport about itself, a leaf
publishes none at all, and a revocation transfers nothing to a successor.

Writing the heartbeat found one construction the prose named and never
defined: the `endpoints` digest. It is stated in constants.json
(descriptor.endpoints_digest) and computed here.

`retiring` is the other thing a heartbeat can say, and it is the only thing
in this protocol that tells a departure from a silence. Under FLP a node that
went away and one that went quiet cannot be told apart, so a peer holding a
schedule against a node that has retired records a partition it was told
about in advance. FLP forbids inferring the difference. It does not forbid
the node saying it.

The coverage claim moved to fleetmesh_core/peering/coverage.py, where the handover door lives
with it.
"""
from __future__ import annotations

from typing import Optional, Sequence

from ..crypto import crypto

from ..wire import schema_files

from ..storage import store
from ..wire import spelling
from ..wire.interfaces import (
    EventLike,
    KindSpec,
    SchemaConstantsDocument,
    UnsignedNostrEvent,
)

CONSTANTS: SchemaConstantsDocument = schema_files.load_constants()
KINDS: dict[str, KindSpec] = schema_files.load_kinds()['kinds']

HEARTBEAT: int = 21801
REVOCATION: int = 11802


# ------------------------------------------------------------ heartbeat ----
[docs]def endpoints_digest(endpoint_tags: Sequence[Sequence[str]]) -> str: """SHA256 over the canonical JSON of the sorted [scheme, address] pairs. The preference value is left out on purpose: it is advice about which address to try first, not a fact about what is being served, and a node reordering its preferences has not changed where it can be reached. """ pairs = sorted([t[1], t[2]] for t in endpoint_tags if t and t[0] == 'endpoint' and len(t) >= 3) return crypto.sha256(crypto.canonical(pairs))
[docs]def heartbeat( pubkey: str, node_class: str, endpoint_tags: Sequence[Sequence[str]], now: int, load: Optional[float] = None, retiring: bool = False, ) -> UnsignedNostrEvent: """A kind 21801. Names no peer and carries nothing about accounting. `retiring` says this node is going, now and on purpose. It is the only thing in this protocol that distinguishes a departure from a silence, and it exists because nothing else can: under FLP a dead node and a quiet one are the same, so a peer that keeps a schedule against a node which has retired records a partition it was told about in advance. The flag is advisory and carries no obligation - a reader that ignores it is where every reader already was. """ tags: list[list[str]] = [['class', node_class], ['endpoints', endpoints_digest(endpoint_tags)]] if load is not None: tags.append(['load', '%.2f' % load]) if retiring: tags.append(['retiring', '1']) return store.make_event(pubkey, now, HEARTBEAT, tags, '')
[docs]def is_retiring(hb: EventLike) -> bool: """Does this heartbeat say its publisher is on its way out? A statement about itself, like the class beside it, and trusted the same way: it costs the publisher its own liveness and buys it nothing. A node that lied about retiring would be telling its peers to stop expecting it, which is the one lie that cannot be made to pay. """ t = store.first_tag(hb, 'retiring') return t is not None and len(t) > 1 and t[1] not in ('', '0')
[docs]def check_heartbeat( hb: EventLike, descriptor: EventLike, ) -> tuple[list[str], list[tuple[str, str]]]: """Everything a reader may hold a heartbeat to. Returns (problems, findings). problems are structural and make the heartbeat invalid. findings are (severity, why) against the publisher: a class that contradicts the live descriptor is a misreport about itself, which the ladder prices as S2. """ problems: list[str] = [] findings: list[tuple[str, str]] = [] if hb.get('kind') != HEARTBEAT: return ['not a kind 21801'], [] if hb.get('content'): problems.append('content must be empty') cls = store.first_tag(hb, 'class') if not cls or len(cls) < 2: problems.append('missing required tag: class') return problems, findings if cls[1] == 'leaf': problems.append('a leaf MUST NOT publish a heartbeat') if hb.get('pubkey') != descriptor.get('pubkey'): problems.append('heartbeat and descriptor are from different keys') dcls = store.first_tag(descriptor, 'class') if dcls and len(dcls) > 1 and dcls[1] != cls[1]: findings.append(('S2', 'heartbeat says %s, descriptor says %s: a misreport about itself' % (cls[1], dcls[1]))) load = store.first_tag(hb, 'load') if load: try: float(load[1]) except (IndexError, ValueError): problems.append('load must be a number') return problems, findings
[docs]def descriptor_is_stale( hb: EventLike, descriptor: EventLike, ) -> bool: """True when the heartbeat's endpoint digest differs from the descriptor's. This is the reason the digest exists: a peer holding a descriptor learns it has gone stale without dialling every address in it. """ e = store.first_tag(hb, 'endpoints') if not e or len(e) < 2: return False return e[1] != endpoints_digest(store.tags(descriptor, 'endpoint'))
[docs]def heartbeat_due( node_class: str, last_at: Optional[int], now: int, shortest_grant_window: Optional[int] = None, ) -> bool: """Anchors MUST publish at least hourly, and at least once per their shortest active grant window if that is shorter. Edges SHOULD. Leaves never.""" if node_class == 'leaf': return False interval = CONSTANTS['grant']['window_seconds_default'] if shortest_grant_window: interval = min(interval, shortest_grant_window) return last_at is None or now - last_at >= interval
# ------------------------------------------------------------ revocation ----
[docs]def revocation( pubkey: str, reason: str, now: int, successor: Optional[str] = None, content: str = '', ) -> UnsignedNostrEvent: """A kind 11802. The key being retired publishes it, so pubkey is that key.""" tags: list[list[str]] = [['reason', reason]] if successor: tags.append(['successor', successor]) return store.make_event(pubkey, now, REVOCATION, tags, content)
[docs]def check_revocation(ev: EventLike) -> list[str]: """Structural. Whether the key holder is the operator or a thief is not decidable here, which is the whole reason a successor inherits nothing.""" out: list[str] = [] if ev.get('kind') != REVOCATION: return ['not a kind 11802'] r = store.first_tag(ev, 'reason') if not r or len(r) < 2 or not r[1]: out.append('missing required tag: reason') s = store.first_tag(ev, 'successor') if s and (len(s) < 2 or not spelling.is_hex(s[1], 64)): out.append('successor is not a 32-byte hex pubkey') if s and len(s) > 1 and s[1] == ev.get('pubkey'): out.append('a node cannot succeed itself') return out
[docs]def successor_of(ev: EventLike) -> Optional[str]: s = store.first_tag(ev, 'successor') return s[1] if s and len(s) > 1 else None