"""The kind 11801 a node publishes, and the DID document a resolver derives.
Built from the node's keys and its MeshNode manifest: class, endpoints,
operator, the protocols it implements as c tags, the plain capabilities as
hints, expiry within the class maximum, and a NIP-13 nonce mined to the
policy's bits. Every descriptor is run through fleetmesh_core.identity.validate_descriptor
before it leaves, so this node can never publish what it would decline.
"""
from __future__ import annotations
import time
from typing import TYPE_CHECKING, Any, Mapping, Optional, Sequence, TypedDict
from fleetmesh_core.crypto import crypto
from fleetmesh_core.identity import did, identity
from fleetmesh_core.identity.did import Document as DIDDocument
from fleetmesh_core.wire import schema_files
from fleetmesh_core.storage import store # noqa: E402
from fleetmesh_node.interfaces import EventLike, NostrEvent, TagList
if TYPE_CHECKING:
from fleetmesh_node.keystore import Keystore
CONSTANTS = identity.CONSTANTS
DIGEST = schema_files.digest()
VERSION = schema_files.load_kinds()['version']
SOFTWARE = (identity.FLEETMESH.rstrip('/'), '0.0.1') # the project URL, derived and never written down
KIND: int = 11801
[docs]def mine(
pubkey: str,
created_at: int,
kind: int,
tags: TagList,
content: str,
bits: int,
max_tries: int = 1 << 26,
) -> tuple[TagList, str]:
"""Find a NIP-13 nonce so the event id has at least `bits` leading zeros.
The nonce tag is ['nonce', '<n>', '<target bits>'] and it is the last tag,
so everything else about the event is fixed before mining starts.
"""
base = [t for t in tags if t[0] != 'nonce']
for n in range(max_tries):
trial = base + [['nonce', str(n), str(bits)]]
eid = store.event_id(pubkey, created_at, kind, trial, content)
if identity.pow_bits(eid) >= bits:
return trial, eid
raise RuntimeError('no nonce found in %d tries' % max_tries)
[docs]def build(
keystore: Keystore,
node_class: str,
endpoints: Sequence[tuple[str, str, int] | list[Any]],
operator_pubkey: Optional[str],
protocols: Sequence[str],
now: Optional[int] = None,
capabilities: Sequence[str] = (),
mediator: Optional[str] = None,
policy: Optional[tuple[str, ...] | list[str]] = None,
coverage: Optional[str] = None,
nips: Optional[Sequence[int]] = None,
lifetime: Optional[int] = None,
bits: Optional[int] = None,
content: str = '',
fips_key: Optional[str] = None,
extra_tags: Sequence[Sequence[str]] = (),
) -> NostrEvent:
"""A signed kind 11801.
endpoints: [(scheme, address, preference)]. protocols: the fleetmesh protocol
identifiers this node implements; peering/1.0 and budget/1.0 are required
of every class and are added if missing. policy: (sha256 hex, url).
extra_tags: optional tags a subsystem contributes (mint, price), placed
before operator so the fixed tail stays where readers expect it.
"""
now = int(now if now is not None else time.time())
cap = CONSTANTS['descriptor']
max_life = cap['max_lifetime_seconds_leaf' if node_class == 'leaf' else 'max_lifetime_seconds_anchor_edge']
lifetime = min(lifetime or max_life, max_life)
bits = cap['default_pow_bits'] if bits is None else bits
mk = keystore.multikeys()
protos = sorted(set(protocols) | set(identity.REQUIRED_PROTOCOLS))
tags: TagList = [
['class', node_class],
['protocol', VERSION, DIGEST],
['software', SOFTWARE[0], SOFTWARE[1]],
['key', 'agreement', mk['agreement']],
['key', 'transport', mk['transport']],
]
if fips_key:
tags.append(['key', 'fips', fips_key])
for scheme, address, pref in sorted(endpoints, key=lambda e: (int(e[2]), e[0])):
tags.append(['endpoint', scheme, address, str(pref)])
if mediator:
tags.append(['mediator', mediator])
tags += [['c', p] for p in protos]
tags += [['c', c] for c in capabilities]
if nips:
tags.append(['nips'] + [str(n) for n in nips])
if coverage:
tags.append(['coverage', coverage])
if policy:
tags.append(['policy', policy[0]] + ([policy[1]] if len(policy) > 1 and policy[1] else []))
for t in extra_tags:
tags.append([str(x) for x in t])
# operator is optional on a kind 11801 (kinds.json): fresh hardware runs
# with none until `meshnode enrol` gives it one (plan D18/D19).
if operator_pubkey:
tags.append(['operator', operator_pubkey])
tags.append(['expiration', str(now + lifetime)])
if bits:
tags, _ = mine(keystore.node_pk, now, KIND, tags, content, bits)
ev: NostrEvent = store.make_signed_event(keystore.node_sk, now, KIND, tags, content)
problems = identity.validate_descriptor(ev, now=now, digest=DIGEST)
if problems:
raise ValueError('refusing to publish an invalid descriptor: %s' % '; '.join(problems))
return ev
[docs]class ManifestEndpoint(TypedDict, total=False):
transport: str
address: str
ticket: str
priority: int
[docs]class ManifestOperator(TypedDict, total=False):
pubkey: str
policyUrl: str
ManifestSpecDict = TypedDict('ManifestSpecDict', {
'class': str,
'endpoints': list[ManifestEndpoint],
'capabilities': list[str],
'operator': ManifestOperator,
}, total=False)
[docs]class MeshNodeManifest(TypedDict, total=False):
spec: ManifestSpecDict
[docs]def from_manifest(
keystore: Keystore,
manifest: MeshNodeManifest | Mapping[str, Any],
now: Optional[int] = None,
bits: Optional[int] = None,
) -> NostrEvent:
"""A descriptor from a MeshNode manifest (manifests/meshnode-*.yaml, parsed)."""
spec = manifest['spec']
eps: list[tuple[str, str, int]] = []
for e in spec.get('endpoints', []):
addr = str(e.get('address') or e.get('ticket') or '')
eps.append((str(e.get('transport', '')), addr, int(e.get('priority', 50))))
caps = [c for c in spec.get('capabilities', []) if not c.startswith('https://')]
protos = [c for c in spec.get('capabilities', []) if c.startswith('https://')]
pol = spec.get('operator', {}).get('policyUrl')
policy = (crypto.sha256(pol.encode()), pol) if pol else None
return build(keystore, spec['class'], eps, spec['operator']['pubkey'], protos, now=now,
capabilities=caps, policy=policy, bits=bits)
# ---------------------------------------------------------- resolution ----
[docs]def genuine(desc: Any, pubkey: Optional[str] = None) -> bool:
"""Signed by its own pubkey, and by the pubkey it was asked for.
A relay answers a query by author with whatever it chooses to serve under
that name. Nothing verified the signature of a resolved descriptor, so a
relay could hand a node a descriptor naming an agreement key of the
relay's choosing, and every envelope to that peer would then be encrypted
to it. The rule for heartbeats already says it: believing an event
unsigned lets a relay speak as any peer.
"""
from fleetmesh_core.crypto import giftwrap
return (isinstance(desc, dict) and (pubkey is None or desc.get('pubkey') == pubkey)
and giftwrap.verify_event(desc))
[docs]def newest(
descriptors: Sequence[NostrEvent | EventLike],
now: Optional[int] = None,
digest: str = DIGEST,
pubkey: Optional[str] = None,
) -> Optional[NostrEvent]:
"""The live, genuine descriptor among candidates for one pubkey, or None."""
now = int(now if now is not None else time.time())
cands = list(descriptors)
live = [d for d in cands if genuine(d, pubkey)
and not identity.validate_descriptor(d, now=now, digest=digest)]
picked = max(live, key=lambda d: int(d['created_at'])) if live else None
return picked # type: ignore[return-value]
[docs]def resolve(
pubkey: str,
relay_urls: Sequence[str],
now: Optional[int] = None,
timeout: float = 15.0,
) -> Optional[NostrEvent]:
"""The live kind 11801 for a pubkey from these relays, or None."""
from . import client
found = client.query_all(relay_urls, [{'kinds': [KIND], 'authors': [pubkey]}], timeout)
return newest(found, now, pubkey=pubkey)
[docs]def did_document(desc: EventLike) -> DIDDocument:
"""The node profile a did:nostr resolver emits for a kind 11801 (fleetmesh_core/did)."""
return did.document(desc)