"""The router: TransportRouter, the ladder from direct rungs down to the gift-wrap rung.
Separate from the rungs because it is the only module that knows about all of them,
and the direct rungs import from const.py without ever importing the router back.
"""
from __future__ import annotations
import collections
import logging
import os
import queue
import threading
import time
from typing import (
Any,
Callable,
Counter,
Deque,
Mapping,
MutableMapping,
Optional,
Sequence,
TypedDict,
)
from fleetmesh_core.identity.did import did_nostr
from fleetmesh_core.identity import didcomm
from . import didcomm_inbound, fips_rung
from fleetmesh_core.identity import iroh_ticket
from . import ladder as transport_ladder
from fleetmesh_core.storage import replication
from . import const
from .const import Inbound
from .fips_rung import FipsRungMixin
from . import rung as rung_mod
from ..interfaces import DIDCommMessage, RelayHealthRow
from .relay_rung import RelayRung as NostrTransport
from .relay_rung.cooldown import RelayCooldown
from .relay_rung.types import AckVerdict, AwaitingEntry
[docs]class RefusalRow(TypedDict):
"""A direct rung's refusal of one peer, for the ladder's telemetry."""
peer: str
transport: str
error: str
at: int
[docs]class LadderHealthRow(TypedDict):
"""Circuit breaker and availability status of one transport rung."""
available: bool
circuit_breakers: dict[str, str]
failures: dict[str, int]
log = logging.getLogger(__name__)
[docs]class NullTransport:
"""A null transport rung used when Nostr is disabled in configuration."""
name: str = 'none'
health: Mapping[str, Any] = {}
awaiting: Mapping[str, Any] = {}
acked: Mapping[str, int] = {}
acks_in: int = 0
acks_out: int = 0
unacked: Sequence[Any] = ()
wraps_in: Mapping[str, int] = {}
wraps_seen_again: Mapping[str, int] = {}
cooldown: Optional[Any] = None
[docs] def listening(self) -> tuple[str, ...]:
return ()
[docs] def wait_listening(self, timeout: float = 0) -> bool:
return True
[docs] def start(self, since: int = 0) -> None:
pass
[docs] def stop(self) -> None:
pass
[docs] def unfinished(self) -> list[Any]:
return []
[docs] def sweep(self, now: int) -> list[Any]:
return []
[docs] def take_unacked(self) -> list[Any]:
return []
[docs] def listen(self, thid: str) -> None:
pass
[docs] def unlisten(self, thid: str) -> None:
pass
[docs] def available(self) -> bool:
return False
[docs] def send(self, *args: Any, **kwargs: Any) -> Mapping[str, Any]:
return {}
[docs]class TransportRouter(FipsRungMixin):
"""The multi-transport router and ladder negotiator.
Implements TransportProtocol across all active transports:
- fips-native: datagram flows through the fips sidecar (mesh-encrypted)
- iroh: EXPERIMENTAL / unauthenticated. Direct TCP stream or the
iroh_live UDP framing; the wire itself is neither encrypted nor
authenticated, only the DIDComm JWE inside is. Opt-in: built only
when config names an iroh endpoint (see __init__).
- libp2p: stream through the p2p sidecar, when the node builds one
- nostr: NIP-59 gift-wrapped DIDComm over relays (Kinds 21059 / 1059)
The ladder in send() ranks fips-native, iroh, libp2p, nostr by
preference; the rank says which is tried first, not which is safer.
Every rung is held to the same envelope rule (didcomm_inbound).
Performs dynamic ladder negotiation (fleetmesh_core.storage.replication.negotiate) based on
peer descriptor endpoints, automatically falling back down the ladder to
Nostr when direct streams fail or are unavailable.
"""
scheme: str = 'router'
[docs] def __init__(
self,
keystore: Any,
peers: Any,
relay_urls: Sequence[str] = (),
endpoints: Optional[Sequence[Any]] = None,
clock: Optional[Callable[[], int]] = None,
timeout: float = 15.0,
seen_store: Optional[tuple[Callable[[str], bool], Callable[[str, int], None]]] = None,
ack_store: Optional[Any] = None,
iroh_host: str = '127.0.0.1',
iroh_port: int = 0,
sidecar_dir: Optional[str] = None,
enable_iroh: Optional[bool] = None,
iroh_mode: str = 'stream',
fips_sock_path: Optional[str] = None,
enable_fips: bool = True,
fips_port: int = 11801,
fips_client: Optional[Any] = None,
enable_nostr: bool = True,
) -> None:
self.ks: Any = keystore
self.peers: Any = peers
self.relays: list[str] = list(relay_urls)
self.clock: Callable[[], int] = clock or (lambda: int(time.time()))
self.timeout: float = timeout
self.endpoints_cfg: list[Any] = list(endpoints or ())
self.enable_nostr: bool = enable_nostr
if enable_nostr:
self.nostr: Any = NostrTransport(
keystore=keystore,
peers=peers,
relay_urls=relay_urls,
clock=clock,
timeout=timeout,
seen_store=seen_store,
ack_store=ack_store,
)
else:
self.nostr = NullTransport()
# Check for configured iroh endpoint
iroh_ep = None
for ep in self.endpoints_cfg:
if isinstance(ep, dict) and ep.get('transport') == 'iroh':
iroh_ep = ep
break
elif isinstance(ep, (tuple, list)) and len(ep) >= 2 and ep[0] == 'iroh':
iroh_ep = {'transport': 'iroh', 'address': ep[1], 'priority': ep[2] if len(ep) > 2 else 10}
break
self.iroh: Optional[Any] = None
# The iroh rung is EXPERIMENTAL and opt-in. Its framing (TCP stream
# or the iroh_live UDP engine) is neither encrypted nor authenticated
# at the transport layer: only the DIDComm JWE inside protects the
# message. So the rung is built only when the operator names an iroh
# endpoint in config (or a caller passes enable_iroh=True); a node
# with no such endpoint binds no iroh listener and never dials iroh.
if enable_iroh is None:
enable_iroh = iroh_ep is not None
if enable_iroh:
from .iroh_rung import IrohTransport
specified_ticket = iroh_ep.get('address') or iroh_ep.get('ticket') if iroh_ep else None
h = iroh_host
p = iroh_port
if specified_ticket:
try:
t_parsed = iroh_ticket.IrohTicket.parse(specified_ticket)
h, p = t_parsed.host, t_parsed.port
except ValueError as e:
# An empty or non-numeric-port ticket: the configured
# host/port stand, and the ticket string is still handed
# to the transport as the advertised address.
log.warning('iroh: configured ticket unparseable, using host/port: %s', e)
eff_mode = (iroh_ep.get('mode') if iroh_ep else None) or iroh_mode
self.iroh = IrohTransport(
keystore=keystore,
peers=peers,
host=h,
port=p,
ticket=specified_ticket,
sidecar_dir=sidecar_dir,
clock=clock,
timeout=min(timeout, 5.0),
mode=eff_mode,
)
# Check for configured fips endpoint
fips_ep = None
for ep in self.endpoints_cfg:
if isinstance(ep, dict) and ep.get('transport') in ('fips', 'fips-native'):
fips_ep = ep
break
elif isinstance(ep, (tuple, list)) and len(ep) >= 2 and ep[0] in ('fips', 'fips-native'):
fips_ep = {'transport': ep[0], 'address': ep[1], 'priority': ep[2] if len(ep) > 2 else 5}
break
self.fips: Optional[Any] = fips_client
self.fips_port: int = fips_port
self.fips_sock_path: Optional[str] = fips_sock_path or (fips_ep.get('sock_path') if fips_ep else None)
self._fips_listener_sock: Optional[Any] = None
self._fips_thread: Optional[threading.Thread] = None
if enable_fips and self.fips is None:
sock_p = self.fips_sock_path or fips_rung.find_api_socket()
if sock_p and os.path.exists(sock_p):
try:
self.fips = fips_rung.FipsNativeTransport(sock_path=sock_p, node_pk=self.ks.node_pk)
except Exception:
self.fips = None
# The libp2p rung is a compartment (fleetmesh_node/p2p_wire.P2PTransport) that
# registers itself here when the node builds it; a router without one
# simply has no rung to try.
self.p2p: Optional[Any] = None
self.transports: MutableMapping[str, Any] = {'nostr': self.nostr} if self.enable_nostr else {}
if self.iroh is not None:
self.transports['iroh'] = self.iroh
if self.fips is not None:
self.transports['fips-native'] = self.fips
# Unified inbox and thread routing: directly shared with underlying transports
self.inbox: queue.Queue[Inbound] = queue.Queue(maxsize=const.INBOX_MAX)
self._waiting: dict[str, queue.Queue[Inbound]] = {}
self._lock: threading.Lock = threading.Lock()
# Connect both transports directly to this router's inbox and waiter map
self.nostr.inbox = self.inbox
self.nostr._waiting = self._waiting
if self.iroh is not None:
self.iroh.inbox = self.inbox
self.iroh._waiting = self._waiting
# Telemetry metrics
self.success_counts: Counter[str] = collections.Counter()
self.refusals_log: Deque[RefusalRow] = collections.deque(maxlen=const.DROPPED_KEPT)
# What the ladder itself refused: a direct-rung payload that would
# not open, a rung that failed and was cascaded past. Each rung keeps
# its own; faults() reads them all.
self.faults: transport_ladder.FaultLog = transport_ladder.FaultLog('router', clock=self.clock,
keep=const.DROPPED_KEPT)
# Replay and freshness for the direct rungs that deliver through
# deliver_direct (fips-native, libp2p). The iroh rung holds its own.
self.guard: didcomm_inbound.InboundGuard = didcomm_inbound.InboundGuard()
self.circuit_breakers: dict[str, transport_ladder.CircuitBreaker] = {
'fips-native': transport_ladder.CircuitBreaker(failure_threshold=3, recovery_timeout=30.0),
'iroh': transport_ladder.CircuitBreaker(failure_threshold=3, recovery_timeout=30.0),
'libp2p': transport_ladder.CircuitBreaker(failure_threshold=3, recovery_timeout=30.0),
'nostr': transport_ladder.CircuitBreaker(failure_threshold=5, recovery_timeout=15.0),
}
# The ladder, top to floor. Each rung knows how to reach a peer and
# how to deliver once; send() walks them and keeps the books. The
# relay rung is the floor and is always last.
seal: rung_mod.Seal = lambda m, pk, anon: self._seal_direct(m, pk, self.peers.agreement(pk), anon)
self.rungs: list[rung_mod.RungProtocol] = [
rung_mod.FipsRung(self, seal),
rung_mod.IrohRung(self),
rung_mod.Libp2pRung(self, seal),
]
if self.enable_nostr:
self.rungs.append(rung_mod.RelayRungAdapter(self))
self._send_interceptor: Optional[Callable[..., dict[str, tuple[bool, str]]]] = None
self._rung_interceptor: Optional[Callable[[str, DIDCommMessage | Mapping[str, Any], str, Any, bool], Optional[dict[str, tuple[bool, str]]]]] = None
[docs] def register_rung(self, rung: rung_mod.RungProtocol) -> None:
"""Register a dynamic transport rung into the ladder."""
if not hasattr(rung, 'name') or not hasattr(rung, 'deliver'):
raise TypeError(f"Object {rung!r} does not conform to RungProtocol")
# Replace existing rung if already present, else append
existing_idx = next((i for i, r in enumerate(self.rungs) if r.name == rung.name), None)
if existing_idx is not None:
self.rungs[existing_idx] = rung
else:
self.rungs.append(rung)
# Keep ladder sorted by preference rank (lower rank is tried first)
self.rungs.sort(key=lambda r: getattr(r, 'rank', 50))
if rung.name not in self.circuit_breakers:
self.circuit_breakers[rung.name] = transport_ladder.CircuitBreaker(
failure_threshold=3, recovery_timeout=30.0
)
[docs] def add_rung(self, rung: rung_mod.RungProtocol) -> None:
"""Alias for register_rung to satisfy ProtocolManager."""
self.register_rung(rung)
[docs] def unregister_rung(self, name: str) -> Optional[rung_mod.RungProtocol]:
"""Remove a transport rung by name from the ladder."""
removed: Optional[rung_mod.RungProtocol] = None
new_rungs = []
for r in self.rungs:
if r.name == name:
removed = r
else:
new_rungs.append(r)
self.rungs = new_rungs
return removed
[docs] def get_rung(self, name: str) -> Optional[rung_mod.RungProtocol]:
"""Retrieve a registered transport rung by name."""
return next((r for r in self.rungs if r.name == name), None)
# ---- What the ladder shows the compartments: the relay rung's books
# by name (it is the store-and-forward floor), every rung's health and
# faults through the ladder. Nothing resolves by accident.
@property
def health(self) -> Mapping[str, RelayHealthRow]:
# Expose relay health map expected by Link subsystem
h: Mapping[str, RelayHealthRow] = dict(self.nostr.health)
return h
[docs] def rung_health(self) -> dict[str, Mapping[str, int | str | bool | float]]:
"""Every rung's own report, keyed by rung name; a rung whose daemon
is not built is absent. The one view of the ladder's state."""
out: dict[str, Mapping[str, int | str | bool | float]] = {}
for rung in self.rungs:
h = rung.health()
if h is not None:
out[rung.name] = h
return out
@property
def ladder_health(self) -> dict[str, LadderHealthRow]:
"""Circuit breaker and availability status across transport rungs."""
return {
name: {
'available': name in self.transports or (name == 'libp2p' and self._p2p_ready()),
'circuit_breakers': dict(cb._states),
'failures': dict(cb._failures),
}
for name, cb in self.circuit_breakers.items()
}
def _p2p_ready(self) -> bool:
return self.p2p is not None and bool(getattr(self.p2p, 'connected', False))
[docs] def fault_logs(self) -> list[transport_ladder.FaultLog]:
"""The ladder's own fault log and every rung's that keeps one."""
logs = [self.faults]
for rung in self.rungs:
log = rung.fault_log()
if log is not None:
logs.append(log)
return logs
[docs] def recent_faults(self, since: Optional[int] = None) -> list[transport_ladder.Fault]:
"""What every rung refused or lost, newest last, with reasons."""
return transport_ladder.merge_faults(self.fault_logs(), since)
@property
def drop_counts(self) -> Counter[str]:
c: Counter[str] = collections.Counter()
for lg in self.fault_logs():
c.update(lg.counts)
return c
@property
def dropped(self) -> Deque[tuple[str, Optional[str]]]:
return collections.deque(
((f['reason'], f['ident']) for f in self.recent_faults()), maxlen=const.DROPPED_KEPT)
@property
def cooldown(self) -> Optional[RelayCooldown]:
"""The relay rung's cooldown ledger: which relays are being rested
after a rate-limit and until when. None for a relay-rung double
that keeps none."""
cd = getattr(self.nostr, 'cooldown', None)
return cd if isinstance(cd, RelayCooldown) else None
@property
def awaiting(self) -> dict[str, AwaitingEntry]:
return self.nostr.awaiting
@property
def acked(self) -> Counter[str]:
return self.nostr.acked
@property
def acks_in(self) -> int:
return self.nostr.acks_in
@property
def acks_out(self) -> int:
return self.nostr.acks_out
@property
def unacked(self) -> Deque[AckVerdict]:
return self.nostr.unacked
@property
def wraps_in(self) -> Counter[Optional[int]]:
return self.nostr.wraps_in
@property
def wraps_seen_again(self) -> Counter[Optional[int]]:
return self.nostr.wraps_seen_again
[docs] def unfinished(self) -> int:
return self.nostr.unfinished()
[docs] def sweep(self, now: Optional[int] = None) -> list[AckVerdict]:
return self.nostr.sweep(now)
[docs] def take_unacked(self) -> list[AckVerdict]:
return self.nostr.take_unacked()
[docs] def listening(self) -> int:
base = self.nostr.listening()
if self.iroh is not None and getattr(self.iroh, '_server_sock', None) is not None:
base += 1
if self._fips_listener_sock is not None:
base += 1
return base
[docs] def wait_listening(self, timeout: float = 8.0) -> bool:
return self.nostr.wait_listening(timeout)
# ---- Lifecycle ---------------------------------------------------------
[docs] def start(self, since: Optional[int] = None) -> TransportRouter:
self.nostr.start(since=since)
if self.iroh is not None:
self.iroh.start()
if self.fips is not None and self.fips.is_available():
try:
self.fips.connect()
self._fips_listener_sock = self.fips.listen_port(self.fips_port)
self._fips_thread = threading.Thread(target=self._listen_fips, daemon=True)
self._fips_thread.start()
except (OSError, fips_rung.FipsTransportError) as e:
# The daemon answered is_available() but would not give us a
# listener: the rung stays built but inert, and the ladder
# falls through to the next rung. Said once, loudly.
log.warning('fips-native: listener not started, rung inert: %s', e)
return self
[docs] def deliver_direct(
self,
scheme: str,
payload: Any,
wrap_id: str,
origin: Optional[str] = None,
) -> Optional[str]:
"""One payload off a direct rung (fips-native, libp2p): a JWE, or nothing.
Returns None when the message was queued or was an empty ping, else
the reason it was dropped, which is also recorded.
The daemon behind a direct rung proves for itself who the other end
of a flow or stream is, but this node never sees that proof - it
reads a payload off a local socket, and on a cluster daemon, a mock,
or a shared host anyone with the socket can write one. So the payload
is treated exactly as a stream off the internet is: it must be a JWE
this node can open, and the sender is whoever the agreement proves,
never the `from` field. A plaintext frame on this path used to arrive
as an authenticated message from anyone it cared to name, and
resolved whatever request() was waiting for; now it is a drop with a
reason, and nothing else.
`origin`, when a sidecar reports one, is the raw Ed25519 transport
key hex the remote stream authenticated with. It is a hint, not the
sender: the sender's descriptor publishes its transport key, and a
message whose proven sender advertises a different one did not come
from that sender's node, so it is dropped rather than delivered as
something it is not.
Nothing in here may raise: the reader loop ends on any exception,
which would let one malformed frame take the flow down.
"""
if not payload:
return None
try:
inbound, why = didcomm_inbound.open_inbound(payload, self.ks, self.peers, wrap_id,
guard=self.guard, now=self.clock())
except Exception as e: # belt and braces: open_inbound is meant not to raise
inbound, why = None, 'envelope: %s: %s' % (type(e).__name__, e)
if inbound is None:
reason = '%s: %s' % (scheme, why or 'refused')
self.faults.record(reason, wrap_id)
return reason
if not inbound.authenticated and not const.anonymous_allowed(inbound.message.get('type')):
# Anoncrypt off a direct rung: no skid and no seal, so the sender
# is a claim. Only a type whose handler treats the sender as a
# stranger (const.ANONYMOUS_OK) is delivered; everything else is
# refused here, before any handler can read inbound.sender.
reason = '%s: unauthenticated: anoncrypt %s is not a first-contact type' % (
scheme, str(inbound.message.get('type'))[:80])
self.refusals_log.append(RefusalRow(peer=inbound.sender, transport=scheme, error='unauthenticated %s' % str(inbound.message.get('type'))[:80], at=self.clock()))
self.faults.record(reason, wrap_id)
return reason
if origin is not None and inbound.authenticated:
try:
from ..planes.transport.p2p import compartment as p2p_wire
published = p2p_wire.transport_key_of(self.peers.descriptor(inbound.sender))
except Exception:
published = None
if published is not None and published.hex() != origin:
reason = '%s: stream from transport key %s, but sender %s publishes %s' % (
scheme, origin[:8], inbound.sender[:8], published.hex()[:8])
self.faults.record(reason, wrap_id)
return reason
if inbound.message.get('type') == const.EMPTY_TYPE:
return None
thid = inbound.thid
with self._lock:
waiter = self._waiting.get(thid) if thid else None
try:
(waiter if waiter is not None else self.inbox).put_nowait(inbound)
except queue.Full:
# Queue saturated; drop the frame rather than block the reader.
reason = '%s: inbox full' % scheme
self.faults.record(reason, wrap_id)
return reason
return None
[docs] def stop(self) -> None:
if self._fips_listener_sock is not None:
try:
self._fips_listener_sock.close()
except OSError:
pass # best-effort close on shutdown
self._fips_listener_sock = None
if self.fips is not None:
try:
self.fips.close()
except (OSError, fips_rung.FipsTransportError):
pass # best-effort close on shutdown; the daemon may be gone already
if self.iroh is not None:
self.iroh.stop()
self.nostr.stop()
# ---- Dispatch & Ladder Negotiation ------------------------------------
[docs] def set_send_interceptor(
self,
interceptor: Optional[Callable[..., dict[str, tuple[bool, str]]]],
) -> None:
"""Register a send interceptor (e.g. for cluster partition and loss simulation)."""
self._send_interceptor = interceptor
[docs] def clear_send_interceptor(self) -> None:
"""Remove any registered send interceptor."""
self._send_interceptor = None
[docs] def set_rung_interceptor(
self,
interceptor: Optional[Callable[[str, DIDCommMessage | Mapping[str, Any], str, Any, bool], Optional[dict[str, tuple[bool, str]]]]],
) -> None:
"""Register a per-rung delivery interceptor (e.g. for directed partition and cascade testing)."""
self._rung_interceptor = interceptor
[docs] def clear_rung_interceptor(self) -> None:
"""Remove any registered rung interceptor."""
self._rung_interceptor = None
[docs] def send(
self,
message: DIDCommMessage | Mapping[str, Any],
to_pubkey: str,
anonymous: bool = False,
stored: bool = False,
) -> dict[str, tuple[bool, str]]:
"""Dispatch a message over the top negotiated transport ladder rung.
`stored=True` requires store-and-forward relays (NIP-59 Kind 1059).
Live messages negotiate `fips-native` or `iroh` if mutually supported,
falling back down the ladder to relay gift-wraps if dialing fails.
"""
if self._send_interceptor is not None:
return self._send_interceptor(message, to_pubkey, anonymous=anonymous, stored=stored)
return self._send_ladder(message, to_pubkey, anonymous=anonymous, stored=stored)
def _send_ladder(
self,
message: DIDCommMessage | Mapping[str, Any],
to_pubkey: str,
anonymous: bool = False,
stored: bool = False,
) -> dict[str, tuple[bool, str]]:
if stored:
nostr_rung = getattr(self, 'nostr', None)
if nostr_rung is not None and hasattr(nostr_rung, 'send') and getattr(nostr_rung, 'available', lambda: True)():
res = self.nostr.send(message, to_pubkey, anonymous=anonymous, stored=True)
if any(v[0] for v in res.values()):
self.success_counts['nostr'] += 1
return res
return {'router': (False, 'no store-and-forward transport available')}
desc = self.peers.descriptor(to_pubkey)
theirs, _ = rung_mod.endpoints_of(desc)
mine = {r.name: r.rank for r in self.rungs if r.available()}
if self.enable_nostr:
mine['wss'] = 40
order = replication.negotiate(mine, theirs) if theirs else [r.name for r in self.rungs]
by_name = {r.name: r for r in self.rungs}
# The walk. Each rung in negotiated order that is up, that the peer
# advertises, and whose breaker allows the peer gets one attempt;
# a failure is this rung's fault and the next rung's turn. The
# relay rung is appended if available and negotiation left it out.
nostr_rung = by_name.get('nostr')
if nostr_rung is not None and nostr_rung.available() and 'nostr' not in order:
order.append('nostr')
last: rung_mod.Verdict = {}
for name in order:
rung = by_name.get(name)
if rung is None or not rung.available():
continue
target = rung.target_of(desc, theirs)
if target is None:
continue
cb = self.circuit_breakers.get(name)
if cb is not None and not cb.allow_attempt(to_pubkey, now=self.clock()):
continue
try:
if self._rung_interceptor is not None:
inter_res = self._rung_interceptor(name, message, to_pubkey, target, anonymous)
if inter_res is not None:
res = inter_res
else:
res = rung.deliver(message, to_pubkey, target, anonymous)
else:
res = rung.deliver(message, to_pubkey, target, anonymous)
except Exception as e:
if cb is not None:
cb.record_failure(to_pubkey, now=self.clock())
self.refusals_log.append(RefusalRow(peer=to_pubkey, transport=name, error=str(e), at=self.clock()))
self.faults.record('%s failed, cascading down the ladder: %s' % (name, e), None)
continue
if any(v[0] for v in res.values()):
self.success_counts[name] += 1
if cb is not None:
cb.record_success(to_pubkey)
if name == 'nostr' or any(v[0] for v in res.values()):
return res
last = res
return last
def _seal_direct(
self,
message: DIDCommMessage | Mapping[str, Any],
to_pubkey: str,
their_agree: Any,
anonymous: bool,
) -> Mapping[str, Any]:
"""The envelope every direct rung sends: the same JWE the relays carry.
A direct path is one its daemon authenticates for itself, but the
node's proof of who wrote a message is the ECDH-1PU agreement, and
the receiving side (deliver_direct) accepts nothing else.
"""
msg_dict = dict(message)
msg_dict.setdefault('from', self.ks.did)
msg_dict.setdefault('to', [did_nostr(to_pubkey)])
msg_dict.setdefault('created_time', self.clock())
kid = did_nostr(to_pubkey) + '#agree'
sender = None if anonymous else (self.ks.kid('agreement'), self.ks.agreement_priv)
jwe = didcomm.encrypt(msg_dict, [(kid, their_agree)], sender=sender)
return jwe
[docs] def request(
self,
message: DIDCommMessage | Mapping[str, Any],
to_pubkey: str,
timeout: float = 30.0,
anonymous: bool = False,
) -> Optional[Inbound]:
"""Send and wait for the reply threaded on this message's id."""
return self.converse(message, to_pubkey, message['id'], timeout, anonymous)
[docs] def converse(
self,
message: DIDCommMessage | Mapping[str, Any],
to_pubkey: str,
thid: str,
timeout: float = 30.0,
anonymous: bool = False,
) -> Optional[Inbound]:
"""Send and wait for next message on thread across any active transport."""
q = self.listen(thid)
try:
self.send(message, to_pubkey, anonymous=anonymous, stored=False)
try:
return q.get(timeout=timeout)
except queue.Empty:
return None
finally:
self.unlisten(thid)
[docs] def listen(self, thid: str) -> queue.Queue[Inbound]:
"""Route messages on this thread to a dedicated queue."""
with self._lock:
q = self._waiting.get(thid)
if q is None:
q = self._waiting[thid] = queue.Queue()
self.nostr.listen(thid)
if self.iroh is not None:
self.iroh.listen(thid)
return q
[docs] def unlisten(self, thid: str) -> None:
with self._lock:
self._waiting.pop(thid, None)
self.nostr.unlisten(thid)
if self.iroh is not None:
self.iroh.unlisten(thid)
[docs] def receive(self, timeout: Optional[float] = None) -> Optional[Inbound]:
"""Fetch next delivered message from unified inbox."""
try:
return self.inbox.get(timeout=timeout)
except queue.Empty:
return None