"""Kind 30166: the node's relay face described for anyone who reads NIP-66.
A relay list or an explorer that knows nothing about fleetmesh finds relays
through NIP-66 discovery events. A node with a public face MAY publish one
about itself, one per endpoint, so that it is found the way any relay is.
It says what the face is and what it accepts and nothing about how well it
performs. NIP-66 has rtt tags for a monitor that dialled the relay; a node
timing itself would be publishing a claim about itself, which is the thing
the heartbeat was designed not to do. Liveness and latency belong to a
monitor. Everything here is read from things the node already publishes or
serves: the descriptor's endpoints, the face's NIP-11 document, the shards
it claims. The shape is `discovery` in constants.json.
"""
from __future__ import annotations
import json
from typing import Any, Iterable, Mapping, Optional, Sequence
from ..crypto import crypto
from ..peering import projection
from ..wire import schema_files
from ..storage import store
from ..wire.interfaces import (
DiscoveryConstants,
EventLike,
NIP11RelayInfo,
SchemaConstantsDocument,
UnsignedNostrEvent,
)
CONSTANTS: SchemaConstantsDocument = schema_files.load_constants()
D: DiscoveryConstants = CONSTANTS['discovery']
KIND: int = D['kind']
# NIP-11 limitation keys that NIP-66 spells as requirement tags, and the word each becomes.
REQUIREMENTS: tuple[tuple[str, str], ...] = (
('auth_required', 'auth'),
('payment_required', 'payment'),
('restricted_writes', 'writes'),
('min_pow_difficulty', 'pow'),
)
[docs]def network(url: str) -> str:
"""NIP-66's n tag for an address: tor, i2p or clearnet, by the host."""
host = url.split('://', 1)[-1].split('/', 1)[0].rsplit(':', 1)[0].strip('[]').lower()
if host.endswith('.onion'):
return 'tor'
if host.endswith('.i2p'):
return 'i2p'
return 'clearnet'
# Fields of the NIP-11 document that restate the clock rather than the face.
# NIP-11 asks for created_at_upper_limit as an ABSOLUTE timestamp, so it is a
# different number every time the document is built.
VOLATILE: tuple[str, ...] = ('created_at_upper_limit',)
[docs]def settled(event: EventLike) -> str:
"""What a discovery event claims, with the moving parts taken out.
A node republishes one of these when what it says changes, and decided
that by comparing the whole event to the last one. The document carries an
absolute timestamp, so nothing ever compared equal and "only when it
changes" meant every tick: a kind 30166 to every relay every 35 seconds,
about 2,500 a day per node, for a face that had not moved in a week.
The published event still carries the live value. This is only the
question of whether it is worth publishing again.
"""
raw = event.get('content') or ''
doc: Any = {}
if raw:
try:
doc = json.loads(raw)
except ValueError:
doc = raw # not a document; compare it as the string it is
if isinstance(doc, dict) and isinstance(doc.get('limitation'), dict):
doc = dict(doc, limitation={k: v for k, v in doc['limitation'].items()
if k not in VOLATILE})
return json.dumps([event.get('tags', []), doc], sort_keys=True)
[docs]def discovery(
descriptor: EventLike,
nip11: Optional[NIP11RelayInfo | Mapping[str, Any]],
shards: Optional[Sequence[str] | Iterable[str]],
now: Optional[int] = None,
) -> list[UnsignedNostrEvent]:
"""The kind 30166 events a node publishes about its own face: one per ws
or wss endpoint the descriptor declares, unsigned. Nothing to declare
means nothing to publish."""
doc = nip11 or {}
exp_ts = store.expiration(descriptor)
created_at = descriptor.get('created_at', 0) if now is None else now
out: list[UnsignedNostrEvent] = []
for url in projection.relay_endpoints(descriptor):
tags: list[list[str]] = [['d', url], ['n', network(url)]]
# NIP-11 lists NIP numbers as integers; a value that is not one is
# not a NIP and makes no N tag rather than an N that fails check.
tags += [['N', str(n)] for n in doc.get('supported_nips') or [] if store.is_int(n) and n >= 0]
tags += requirement_tags(doc)
tags += [['t', s] for s in sorted(set(shards or []))]
if exp_ts is not None:
tags.append(['expiration', str(exp_ts)])
content = crypto.canonical(doc).decode() if doc else ''
out.append(store.make_event(descriptor.get('pubkey', ''), created_at, KIND, tags, content))
return out
[docs]def check_discovery(
event: EventLike,
descriptor: Optional[EventLike] = None,
) -> list[str]:
"""Everything a reader may hold a discovery event to. Returns problems."""
p: list[str] = []
if not store.is_int(event.get('kind')) or event.get('kind') != KIND:
p.append('kind must be %d' % KIND)
if not isinstance(event.get('tags'), list) or any(
not isinstance(t, list) or not t or not all(isinstance(x, str) for x in t) for t in event['tags']):
p.append('every tag must be a non-empty array of strings')
d = store.tags(event, 'd')
if len(d) != 1 or len(d[0]) < 2 or not d[0][1]:
p.append('one d, the relay address')
else:
try:
if projection.canonical_relay(d[0][1]) != d[0][1]:
p.append('d is not canonical: %r' % d[0][1])
except ValueError as e:
p.append('d is not a relay address: %s' % e)
n = store.tags(event, 'n')
if len(n) != 1 or n[0][1:2] != [network(d[0][1])]:
p.append('n must be the network of d: %s' % network(d[0][1]))
for t in store.tags(event, 'N'):
if len(t) < 2 or store.ascii_int(t[1]) is None:
p.append('N carries a NIP number')
break
words = {w for _, w in REQUIREMENTS}
for t in store.tags(event, 'R'):
if len(t) < 2 or t[1].lstrip('!') not in words:
p.append('R is one of %s, with ! for false' % ', '.join(sorted(words)))
break
if any(t[0].startswith('rtt') for t in event.get('tags', []) if isinstance(t, list) and t and isinstance(t[0], str)):
p.append('no rtt: a node does not time itself')
if event.get('content'):
try:
doc = json.loads(event['content'])
if not isinstance(doc, dict):
raise ValueError('not an object')
except ValueError as e:
p.append('content is the NIP-11 document as JSON: %s' % e)
else:
listed = {str(x) for x in doc.get('supported_nips') or [] if store.is_int(x) and x >= 0}
tagged = {t[1] for t in store.tags(event, 'N') if len(t) > 1}
if listed != tagged:
p.append('N tags and the document disagree about supported NIPs')
if sorted(requirement_tags(doc)) != sorted(t[:2] for t in store.tags(event, 'R')):
p.append('R tags and the document disagree about limitations')
if descriptor is not None:
if descriptor.get('pubkey') != event.get('pubkey'):
p.append('the descriptor and the discovery event have different authors')
if d and len(d[0]) > 1 and d[0][1] not in projection.relay_endpoints(descriptor):
p.append('d is not an endpoint the descriptor declares')
if store.expiration(descriptor) != store.expiration(event):
p.append('expiration is the descriptor\'s')
return p