"""One rung of the transport ladder, and the four the node has.
The router used to know how every rung dials: four if-blocks, each with
its own seal, its own breaker lookup, its own cascade note. Now a rung is
one object that says whether it is up, whether it can reach a peer and
where, and makes one delivery attempt; the router walks the ladder and
keeps the books. A rung that is a compartment elsewhere (the relay rung,
the libp2p transport) is reached through a thin adapter here so that it
need not know the ladder exists.
Adapters read their daemon off the router at call time (`router.fips`,
`router.iroh`, `router.p2p`) rather than at construction: a test swaps a
fake in after the router is built, and a sidecar registers itself later.
Every rung answers the same four questions the same way - up?, where?,
deliver, and what it did (health(), fault_log()) - so the router walks the
ladder blindly for all of them. There is no rung the router knows by name.
"""
from __future__ import annotations
import json
from typing import Any, Callable, Mapping, Optional, Protocol, TypedDict, runtime_checkable
from . import fips_rung as fips_transport
from .const import TransportError
from .ladder import FaultLog
Verdict = dict[str, tuple[bool, str]]
Jwe = Mapping[str, Any] # a DIDComm JWE as didcomm.encrypt returns it
Seal = Callable[[Mapping[str, Any], str, bool], Jwe]
[docs]class RungHealth(TypedDict, total=False):
"""What a rung reports about itself; the daemon-backed rungs add their own keys."""
available: bool
[docs]@runtime_checkable
class RungProtocol(Protocol):
"""What the ladder needs from a rung, and nothing it does not."""
name: str # the scheme negotiate() ranks: 'fips-native', 'iroh', 'libp2p', 'nostr'
rank: int # this node's preference; lower is tried first
[docs] def available(self) -> bool:
"""The local side of this rung is up (daemon reachable, listener bound)."""
...
[docs] def target_of(self, desc: Optional[Mapping[str, Any]], theirs: Mapping[str, int]) -> Optional[str]:
"""Where this rung would reach the peer that published `desc`, or
None when the descriptor does not advertise it. `theirs` is the
peer's scheme -> preference map already read from the descriptor."""
...
[docs] def deliver(self, message: Mapping[str, Any], to_pubkey: str, target: str, anonymous: bool) -> Verdict:
"""One attempt. Returns {scheme: (delivered, note)}; raises on failure
so the ladder records it and moves on."""
...
[docs] def health(self) -> Optional[Mapping[str, Any]]:
"""What this rung reports about itself, or None when its daemon is
not built; the router keys it by rung name."""
...
[docs] def fault_log(self) -> Optional[FaultLog]:
"""The log of what this rung refused or lost, or None when it keeps
none; the router merges every log it is given."""
...
class Rung:
"""Defaults for a rung that has nothing to report. The four rungs here
and any test double inherit it so the ladder never probes for a method."""
name: str = 'rung'
rank: int = 50
def available(self) -> bool:
return False
def target_of(self, desc: Optional[Mapping[str, Any]], theirs: Mapping[str, int]) -> Optional[str]:
return None
def deliver(self, message: Mapping[str, Any], to_pubkey: str, target: str, anonymous: bool) -> Verdict:
raise TransportError('%s rung does not deliver' % self.name)
def health(self) -> Optional[Mapping[str, Any]]:
return None
def fault_log(self) -> Optional[FaultLog]:
return None
def _log_of(owner: Any) -> Optional[FaultLog]:
log = getattr(owner, 'faults', None)
return log if isinstance(log, FaultLog) else None
[docs]def endpoints_of(desc: Optional[Mapping[str, Any]]) -> tuple[dict[str, int], dict[str, str]]:
"""A descriptor's advertised rungs: (scheme -> preference, scheme -> address).
The 'key' tag with a fips transport key counts as a fips-native endpoint
at the strongest preference, the way the handshake reads it.
"""
theirs: dict[str, int] = {}
where: dict[str, str] = {}
if desc is None:
return theirs, where
for t in desc.get('tags', []):
if not t:
continue
if t[0] == 'endpoint' and len(t) > 2:
scheme = 'fips-native' if t[1] == 'fips' else t[1]
pref = int(t[3]) if len(t) > 3 and str(t[3]).isdigit() else 50
theirs[scheme] = pref
where[scheme] = t[2]
elif t[0] == 'key' and len(t) > 2 and t[1] == 'fips':
where['fips-native'] = t[2]
theirs['fips-native'] = 5
return theirs, where
[docs]class FipsRung(Rung):
"""Datagram flows through the fips sidecar; mesh-encrypted by the daemon."""
name = 'fips-native'
rank = 5
[docs] def __init__(self, router: Any, seal: Seal) -> None:
self.router = router
self.seal = seal
[docs] def available(self) -> bool:
return self.router.fips is not None
[docs] def target_of(self, desc: Optional[Mapping[str, Any]], theirs: Mapping[str, int]) -> Optional[str]:
_, where = endpoints_of(desc)
if 'fips-native' in where:
return where['fips-native']
return '' if 'fips-native' in theirs else None
[docs] def deliver(self, message: Mapping[str, Any], to_pubkey: str, target: str, anonymous: bool) -> Verdict:
fips = self.router.fips
peer_key = target or to_pubkey
port = self.router.fips_port
if ':' in peer_key and not peer_key.startswith('did:'):
host, _, p = peer_key.partition(':')
if p.isdigit():
peer_key, port = host, int(p)
their_agree = self.router.peers.agreement(to_pubkey)
if their_agree is None:
raise TransportError('no live agreement key for peer %s' % to_pubkey[:16])
flow = fips.open_flow(peer_key, port=port)
jwe = self.seal(message, to_pubkey, anonymous)
raw = json.dumps(jwe, separators=(',', ':'), sort_keys=True).encode('utf-8')
# Fragments to the flow's max_payload; raises rather than silently
# dropping an oversize datagram, so the ladder cascades.
fips.send_message(flow, raw, flags=fips_transport.FLAG_DIDCOMM)
return {self.name: (True, 'delivered via fips native flow to %s:%d' % (peer_key, port))}
[docs] def health(self) -> Optional[Mapping[str, Any]]:
fips = self.router.fips
if fips is None:
return None
return {
'available': fips.is_available(),
'sock_path': getattr(fips, 'sock_path', None),
'port': self.router.fips_port,
'listening': getattr(self.router, '_fips_listener_sock', None) is not None,
'flows_count': len(getattr(fips, 'open_flows', {})),
'listeners_count': len(getattr(fips, 'listeners', {})),
'success_count': self.router.success_counts['fips-native'],
}
[docs]class IrohRung(Rung):
"""EXPERIMENTAL. A direct stream the wire itself neither encrypts nor
authenticates; only the JWE inside does. Built only when configured."""
name = 'iroh'
rank = 10
[docs] def __init__(self, router: Any) -> None:
self.router = router
[docs] def available(self) -> bool:
return self.router.iroh is not None
[docs] def target_of(self, desc: Optional[Mapping[str, Any]], theirs: Mapping[str, int]) -> Optional[str]:
_, where = endpoints_of(desc)
# Without a ticket there is nothing to dial, whatever the preference says.
return where.get('iroh') or None
[docs] def deliver(self, message: Mapping[str, Any], to_pubkey: str, target: str, anonymous: bool) -> Verdict:
res: Verdict = self.router.iroh.send(message, to_pubkey, ticket=target, anonymous=anonymous)
return res
[docs] def health(self) -> Optional[Mapping[str, Any]]:
iroh = self.router.iroh
return None if iroh is None else dict(iroh.health)
[docs] def fault_log(self) -> Optional[FaultLog]:
return _log_of(self.router.iroh)
[docs]class Libp2pRung(Rung):
"""A stream through the p2p sidecar; the target is derived from the
descriptor's transport key, so the dial is bound to what it signed."""
name = 'libp2p'
rank = 20
[docs] def __init__(self, router: Any, seal: Seal) -> None:
self.router = router
self.seal = seal
[docs] def available(self) -> bool:
p2p = self.router.p2p
return p2p is not None and bool(getattr(p2p, 'connected', False))
[docs] def target_of(self, desc: Optional[Mapping[str, Any]], theirs: Mapping[str, int]) -> Optional[str]:
if 'libp2p' not in theirs:
return None
from ..planes.transport.p2p import compartment as p2p_wire
target, why = p2p_wire.target_of(desc)
# An advertised but unusable endpoint is still an attempt the ladder
# should record as this rung's failure, not skip in silence.
return target if target is not None else 'unusable: %s' % why
[docs] def deliver(self, message: Mapping[str, Any], to_pubkey: str, target: str, anonymous: bool) -> Verdict:
if target.startswith('unusable: '):
raise TransportError('libp2p endpoint ' + target)
their_agree = self.router.peers.agreement(to_pubkey)
if their_agree is None:
raise TransportError('no live agreement key for peer %s' % to_pubkey[:16])
jwe = self.seal(message, to_pubkey, anonymous)
sent, note = self.router.p2p.send_direct(target, jwe)
if not sent:
raise TransportError(note or 'libp2p stream not acknowledged')
return {self.name: (True, note)}
[docs] def health(self) -> Optional[Mapping[str, Any]]:
p2p = self.router.p2p
return None if p2p is None else RungHealth(available=self.available())
[docs]class RelayRungAdapter(Rung):
"""The floor of the ladder: gift-wraps over the relays. Reaches every
peer, so it never says no; the relay rung itself reports which relays
took the wrap."""
name = 'nostr'
rank = 100
[docs] def __init__(self, router: Any) -> None:
self.router = router
[docs] def available(self) -> bool:
return True
[docs] def target_of(self, desc: Optional[Mapping[str, Any]], theirs: Mapping[str, int]) -> Optional[str]:
return ''
[docs] def deliver(self, message: Mapping[str, Any], to_pubkey: str, target: str, anonymous: bool) -> Verdict:
res: Verdict = self.router.nostr.send(message, to_pubkey, anonymous=anonymous, stored=False)
return res
[docs] def health(self) -> Optional[Mapping[str, Any]]:
return dict(self.router.nostr.health)
[docs] def fault_log(self) -> Optional[FaultLog]:
return _log_of(self.router.nostr)
__all__ = ['FipsRung', 'IrohRung', 'Jwe', 'Libp2pRung', 'RelayRungAdapter', 'RungHealth', 'RungProtocol', 'Seal',
'Verdict', 'endpoints_of']