"""What this node knows about other nodes: their live descriptors.
A peer is addressed by its node pubkey. From its descriptor come the
agreement key an envelope is encrypted to, the class, the protocols it
implements and the endpoints. Descriptors are cached and refreshed from
relays when missing or expired, and every one goes through
fleetmesh_core.identity.validate_descriptor before it is believed.
"""
from __future__ import annotations
import threading
import time
from typing import Callable, Optional, Sequence
from cryptography.hazmat.primitives.asymmetric import x25519
from fleetmesh_core.crypto import keys # noqa: E402
from fleetmesh_core.identity import identity # noqa: E402
from fleetmesh_node.interfaces import NostrEvent # noqa: E402
from . import descriptor # noqa: E402
[docs]def agreement_key(desc: NostrEvent) -> Optional[x25519.X25519PublicKey]:
"""The X25519 public key a descriptor's agreement Multikey names, or None."""
for t in desc.get('tags', []):
if t and t[0] == 'key' and len(t) > 2 and t[1] == 'agreement':
kind, raw = keys.parse_multikey(t[2])
if kind == 'agreement':
return keys.agreement_public(raw)
return None
from fleetmesh_core.identity.did import node_of_did
__all__ = ['Peers', 'agreement_key']
[docs]class Peers:
# A descriptor that is not on the relays is asked for again on every
# message its key sends, and the asking happens on the transport's
# listener thread with the relay timeout in front of it. A stranger with
# no descriptor could hold that thread for fifteen seconds per wrap. A
# miss is remembered for this long before the relays are asked again.
MISS_TTL: int = 60
[docs] def __init__(
self,
relay_urls: Sequence[str] = (),
clock: Optional[Callable[[], int]] = None,
timeout: float = 15.0,
resolver: Optional[Callable[[str, Sequence[str], Optional[int], float], Optional[NostrEvent]]] = None,
) -> None:
self.relays: list[str] = list(relay_urls)
self.clock: Callable[[], int] = clock or (lambda: int(time.time()))
self.timeout: float = timeout
# How a descriptor not held is looked up; given so a test can count
# the lookups without touching the descriptor module.
self.resolver = resolver or (lambda pk, urls, now, timeout: descriptor.resolve(pk, urls, now=now, timeout=timeout))
self._cache: dict[str, NostrEvent] = {}
self._missing: dict[str, int] = {} # pubkey -> when a failed resolve may be retried
self._lock: threading.Lock = threading.Lock()
[docs] def learn(self, desc: NostrEvent) -> bool:
"""Accept a descriptor if it is genuine, validates and is newer than what we hold."""
if not descriptor.genuine(desc) or identity.validate_descriptor(desc, now=self.clock(), digest=descriptor.DIGEST):
return False
with self._lock:
have = self._cache.get(desc['pubkey'])
if have is None or desc['created_at'] > have['created_at']:
self._cache[desc['pubkey']] = desc
self._missing.pop(desc['pubkey'], None)
return True
return False
[docs] def descriptor(self, pubkey: str, refresh: bool = False) -> Optional[NostrEvent]:
now = self.clock()
with self._lock:
d = self._cache.get(pubkey)
if d is not None and not refresh and not identity.validate_descriptor(d, now=now, digest=descriptor.DIGEST):
return d
with self._lock:
until = self._missing.get(pubkey)
if until is not None and now < until and not refresh:
return None
if self.relays:
fresh = self.resolver(pubkey, self.relays, now, self.timeout)
if fresh is not None:
self.learn(fresh)
return fresh
with self._lock:
self._missing[pubkey] = now + self.MISS_TTL
return None
[docs] def agreement(self, pubkey: str) -> Optional[x25519.X25519PublicKey]:
d = self.descriptor(pubkey)
return agreement_key(d) if d is not None else None
[docs] def resolve_sender(self, skid: str) -> Optional[x25519.X25519PublicKey]:
"""For didcomm.decrypt: the static agreement key a skid names, if the
descriptor behind it is live. The kid must be the #agree fragment."""
if not skid.endswith('#agree'):
return None
try:
return self.agreement(node_of_did(skid))
except ValueError:
return None
[docs] def known(self) -> list[str]:
with self._lock:
return sorted(self._cache)