"""DIDs: did:nostr is the identity; did:key and did:peer are derived views of it.
A node IS its did:nostr - the subject is the secp256k1 x-only pubkey that signs
every event. did:key and did:peer are deterministic re-encodings of the keys the
descriptor already carries, so off-the-shelf DIDComm and VC tooling can address
a node without a did:nostr resolver (`constants.json#did`, profile
`did-aliases`). Neither adds a key, a curve or a trust root.
did:key did:key:z<base58btc(multicodec || raw key)>; one per key kind.
The node key is secp256k1-pub (0xe7 0x01) over the COMPRESSED
point (02 || x, even y as BIP-340 implies), the agreement key is
x25519-pub (0xec 0x01), the transport key ed25519-pub (0xed 0x01).
did:peer numalgo 2 (did:peer:2.<V|E|S elements>): the authentication key
as V, the agreement key as E, the DIDCommMessaging service as S
with the spec's abbreviations, base64url-nopad JSON. It is a
SNAPSHOT of the descriptor: it changes when the endpoint or a key
does. The descriptor is the source of truth; the did:peer is how
that truth is spelt to a DIDComm library.
Standard library only; the point math is fleetmesh_core/crypto/crypto's.
"""
from __future__ import annotations
import base64
import json
from typing import Any, Mapping, MutableMapping, Optional, TypedDict, cast
from ..crypto import crypto
from ..wire import schema_files
from ..wire import spelling
CONSTANTS: Mapping[str, Any] = schema_files.load_constants()
[docs]class ServiceEndpoint(TypedDict, total=False):
uri: str
accept: list[str]
routingKeys: list[str]
[docs]class Service(TypedDict, total=False):
id: str
type: str
serviceEndpoint: ServiceEndpoint
[docs]class PeerParts(TypedDict):
node: Optional[str]
agreement: Optional[str]
service: Optional[Service]
[docs]class Parsed(TypedDict, total=False):
method: str
kind: str
node: Optional[str]
[docs]class VerificationMethod(TypedDict):
id: str
type: str
controller: str
publicKeyMultibase: str
Document = TypedDict('Document', {
'@context': list[str],
'id': str,
'alsoKnownAs': list[str],
'verificationMethod': list[VerificationMethod],
'authentication': list[str],
'assertionMethod': list[str],
'keyAgreement': list[str],
'service': list[Service],
})
Json = Mapping[str, Any]
DID: Mapping[str, Any] = cast(Mapping[str, Any], CONSTANTS['did'])
_ALPHABET = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
_CODEC = {k: bytes.fromhex(v) for k, v in DID['multicodec'].items()}
_ABBREV: Mapping[str, str] = DID['peer']['service_abbreviations']
_UNABBREV = {v: k for k, v in _ABBREV.items()}
[docs]def b58encode(raw: bytes) -> str:
n = int.from_bytes(raw, 'big')
out = ''
while n:
n, r = divmod(n, 58)
out = _ALPHABET[r] + out
pad = len(raw) - len(raw.lstrip(b'\0'))
return '1' * pad + out
[docs]def b58decode(s: str) -> bytes:
n = 0
for ch in s:
i = _ALPHABET.find(ch)
if i < 0:
raise ValueError('not base58btc: %r' % ch)
n = n * 58 + i
raw = n.to_bytes((n.bit_length() + 7) // 8, 'big') if n else b''
return b'\0' * (len(s) - len(s.lstrip('1'))) + raw
[docs]def compressed_node_key(x_only_hex: str) -> bytes:
"""02 || x: the even-y point BIP-340 x-only keys stand for."""
try:
x = crypto._x_coord(x_only_hex)
except ValueError:
x = 0
if crypto.lift_x(x) is None:
raise ValueError('not an x-only secp256k1 public key')
return b'\x02' + bytes.fromhex(x_only_hex)
[docs]def did_key(kind: str, raw: bytes) -> str:
if kind not in _CODEC:
raise ValueError('did:key kinds are %s' % sorted(_CODEC))
want = 33 if kind == 'node' else 32
if len(raw) != want:
raise ValueError('%s key is %d bytes' % (kind, want))
return 'did:key:z' + b58encode(_CODEC[kind] + raw)
[docs]def parse_did_key(did: str) -> tuple[str, bytes]:
"""(kind, raw bytes) of a did:key this profile emits; refuses other codecs."""
if not did.startswith('did:key:z'):
raise ValueError('did:key is base58btc (z) here')
body = b58decode(did[len('did:key:z'):])
for kind, codec in _CODEC.items():
if body.startswith(codec):
raw = body[len(codec):]
if len(raw) != (33 if kind == 'node' else 32):
raise ValueError('%s did:key has the wrong length' % kind)
if kind == 'node' and raw[0] != 0x02:
raise ValueError('node did:key must be the even-y compressed point')
return kind, raw
raise ValueError('a different curve is a different network: codec %s' % body[:2].hex())
[docs]def node_did_key(x_only_hex: str) -> str:
return did_key('node', compressed_node_key(x_only_hex))
def _b64url(obj: Any) -> str:
return base64.urlsafe_b64encode(json.dumps(obj, separators=(',', ':'), sort_keys=True, ensure_ascii=False).encode()).decode().rstrip('=')
def _abbr_value(v: Any, table: Mapping[str, str], drop_id: bool) -> Any:
"""One value of a did:peer:2 service, abbreviated or expanded. Strings
are looked up, objects and lists are walked (numalgo 2 says the whole
document, so a list of objects is abbreviated too). `id` is dropped only
at the top level - that is the one did:peer:2 assigns - and never from a
nested object, which is somebody else's id."""
if isinstance(v, str):
return table.get(v, v)
if isinstance(v, Mapping):
out: MutableMapping[str, Any] = {}
for k, vv in v.items():
if drop_id and k == 'id':
continue
out[table.get(k, k)] = _abbr_value(vv, table, False)
return out
if isinstance(v, list):
return [_abbr_value(x, table, False) for x in v]
return v
def _abbreviate(service: Json) -> Mapping[str, Any]:
return cast(Mapping[str, Any], _abbr_value(service, _ABBREV, True))
def _expand(service: Json) -> Mapping[str, Any]:
return cast(Mapping[str, Any], _abbr_value(service, _UNABBREV, False))
_B64URL = frozenset('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_')
def _b64url_decode(body: str) -> bytes:
"""Strict base64url without padding: the alphabet only, and canonical
(no trailing bits). urlsafe_b64decode silently accepted '+', '/', '=',
and bits that re-encode differently, so two DIDs that were not the same
string parsed to the same service."""
if not body or any(c not in _B64URL for c in body) or len(body) % 4 == 1:
raise ValueError('S element is not base64url')
raw = base64.urlsafe_b64decode(body + '=' * (-len(body) % 4))
if base64.urlsafe_b64encode(raw).decode().rstrip('=') != body:
raise ValueError('S element is not canonical base64url')
return raw
[docs]def did_peer(node_pk_hex: str, agreement_raw: Optional[bytes], service: Optional[Json]) -> str:
"""did:peer:2 of a node: V = the node key, E = the agreement key, S = the DIDComm service."""
parts = ['.V' + node_did_key(node_pk_hex)[len('did:key:'):]]
if agreement_raw is not None:
parts.append('.E' + did_key('agreement', agreement_raw)[len('did:key:'):])
if service is not None:
parts.append('.S' + _b64url(_abbreviate(service)))
return 'did:peer:2' + ''.join(parts)
[docs]def parse_did_peer(did: str) -> PeerParts:
"""{node: x-only hex, agreement: hex or None, service: expanded or None}."""
if not did.startswith('did:peer:2.'):
raise ValueError('only did:peer numalgo 2 is spoken here')
out: PeerParts = {'node': None, 'agreement': None, 'service': None}
for el in did[len('did:peer:2.'):].split('.'):
if not el:
raise ValueError('empty did:peer:2 element')
purpose, body = el[0], el[1:]
if purpose == 'V':
kind, raw = parse_did_key('did:key:' + body)
if kind != 'node':
raise ValueError('V must be the node key')
out['node'] = raw[1:].hex()
elif purpose == 'E':
kind, raw = parse_did_key('did:key:' + body)
if kind != 'agreement':
raise ValueError('E must be the agreement key')
out['agreement'] = raw.hex()
elif purpose == 'S':
try:
doc = json.loads(_b64url_decode(body).decode('utf-8'))
except (UnicodeDecodeError, json.JSONDecodeError) as e:
raise ValueError('S element is not JSON: %s' % e)
if not isinstance(doc, dict):
raise ValueError('S element must be a JSON object')
svc = dict(_expand(doc))
svc['id'] = '#didcomm'
out['service'] = cast(Service, svc)
else:
raise ValueError('unknown did:peer:2 purpose %r' % purpose)
if out['node'] is None:
raise ValueError('did:peer:2 without a V element names no node')
return out
[docs]def parse(did: str) -> Parsed:
"""{method, node} for any DID this profile speaks; node is the x-only hex when it names one."""
if did.startswith('did:nostr:'):
pk = did[len('did:nostr:'):]
compressed_node_key(pk)
return {'method': 'nostr', 'node': pk}
if did.startswith('did:key:'):
kind, raw = parse_did_key(did)
return {'method': 'key', 'kind': kind, 'node': raw[1:].hex() if kind == 'node' else None}
if did.startswith('did:peer:'):
p = parse_did_peer(did)
return {'method': 'peer', 'node': p['node']}
raise ValueError('did methods here are nostr, key and peer')
[docs]def did_nostr(pubkey: str) -> str:
"""Format an x-only hex pubkey as did:nostr:<pubkey>."""
return 'did:nostr:' + pubkey.lower()
[docs]def node_of_did(did_or_kid: str) -> str:
"""Extract canonical 64-hex node pubkey from did:nostr, did:key, or did:peer identifier/KID."""
body = did_or_kid.split('#', 1)[0]
if body.startswith('did:nostr:'):
pk = body[len('did:nostr:'):].lower()
if spelling.is_hex(pk, 64):
try:
compressed_node_key(pk)
except ValueError:
raise ValueError('DID %r names no secp256k1 public key' % (did_or_kid,)) from None
return pk
p = parse(body)
node = p.get('node')
if not node:
raise ValueError('DID %r names no node pubkey' % (did_or_kid,))
return node
def _tags(desc: Json, name: str) -> list[list[str]]:
tags = cast(list[list[str]], desc['tags'])
return [t for t in tags if t and t[0] == name]
[docs]def didcomm_service(desc: Json) -> Optional[Service]:
eps = sorted(_tags(desc, 'endpoint'), key=lambda e: int(e[3]) if len(e) > 3 else 50)
wss = [e for e in eps if e[1] in ('wss', 'https')]
if not wss:
return None
se: ServiceEndpoint = {'uri': wss[0][2], 'accept': ['didcomm/v2']}
med = _tags(desc, 'mediator')
if med:
se['routingKeys'] = [med[0][1] + '#agree']
return {'id': '#didcomm', 'type': 'DIDCommMessaging', 'serviceEndpoint': se}
[docs]def document(desc: Json) -> Document:
"""The node profile a did:nostr resolver emits for a kind 11801, with its aliases."""
from ..crypto import keys
pubkey = cast(str, desc['pubkey'])
did = 'did:nostr:' + pubkey
vm: list[VerificationMethod] = [{'id': '#nostr', 'type': 'Multikey', 'controller': did,
'publicKeyMultibase': keys.multikey('node', bytes.fromhex(pubkey))}]
agreement_name = None
agreement_raw = None
key_ids = {'agreement': '#agree', 'transport': '#wire', 'fips': '#fips'}
for k in _tags(desc, 'key'):
if len(k) < 3:
continue
name = key_ids.get(k[1])
if name is None:
continue
vm.append({'id': name, 'type': 'Multikey', 'controller': did, 'publicKeyMultibase': k[2]})
if k[1] == 'agreement':
agreement_name = name
agreement_raw = keys.parse_multikey(k[2])[1]
service = didcomm_service(desc)
services: list[Service] = [service] if service else []
doc: Document = {
'@context': list(CONSTANTS['descriptor']['did_contexts']),
'id': did,
'alsoKnownAs': [node_did_key(pubkey), did_peer(pubkey, agreement_raw, service)],
'verificationMethod': vm,
'authentication': ['#nostr'], 'assertionMethod': ['#nostr'],
'keyAgreement': [agreement_name] if agreement_name else [], 'service': services,
}
caps = {t[1] for t in _tags(desc, 'c')}
eps = sorted(_tags(desc, 'endpoint'), key=lambda e: int(e[3]) if len(e) > 3 else 50)
for e in eps:
if e[1] == 'wss' and 'relay' in caps:
services.append(cast(Service, {'id': '#relay', 'type': 'NostrRelay', 'serviceEndpoint': e[2]}))
elif e[1] == 'iroh':
services.append(cast(Service, {'id': '#iroh', 'type': 'IrohNode', 'serviceEndpoint': e[2]}))
return doc
# --- verifying a signature by the DID that made it ---------------------------
#
# `parse` says who a DID names; this says whether they signed something. It is
# separate because it is the audit path: `node/config/change.py` records WHO
# changed a setting, and a claim is not a record until a signature is checked
# against the identifier that claimed it.
#
# Every method this profile speaks - nostr, key, peer - is SELF-CERTIFYING:
# the key is in the identifier, so the check happens in this process with no
# resolver, no network and no third party. That is not a convenience. A
# resolvable method (did:web, did:plc, did:ion) would break two things at
# once: `test_unplug.py` exists to prove this implementation reaches no host
# to do its work, and a rotated key makes yesterday's signature unverifiable,
# so an audit record built on one is not evidence. `parse` already refuses
# them; `refusal` below says why in a sentence an operator reads.
# Methods that would need a document fetched. Named so they are refused BY
# NAME rather than as an unknown method, which reads like a typo.
RESOLVABLE: tuple[str, ...] = ('web', 'plc', 'ion', 'ethr', 'pkh')
[docs]def signing_key(did: str) -> Optional[tuple[str, bytes]]:
"""(curve, raw public key) a DID can verify a signature with, or None.
An x25519 agreement key is not a signing key and comes back None rather
than being checked against the wrong algorithm.
"""
try:
parsed = parse(did.split('#', 1)[0])
except ValueError:
return None
if parsed.get('node'):
return 'secp256k1', bytes.fromhex(cast(str, parsed['node']))
if parsed.get('method') == 'key' and parsed.get('kind') == 'transport':
_kind, raw = parse_did_key(did.split('#', 1)[0])
return 'ed25519', raw
return None
[docs]def verify(did: str, msg32: bytes, sig_hex: str) -> bool:
"""Whether `sig_hex` is this DID's signature over `msg32`.
False rather than raising, for every reason: a malformed DID, a method
this profile does not speak, an agreement key offered as a signing key, a
bad signature. A verifier on an audit path that can raise is a verifier
that can be made to fail closed by a malformed input, and the caller
needs an answer, not an exception.
"""
k = signing_key(did)
if k is None:
return False
curve, raw = k
try:
if curve == 'secp256k1':
from ..crypto import crypto# noqa: PLC0415
return bool(crypto.schnorr_verify(msg32, raw.hex(), sig_hex))
if curve == 'ed25519':
from cryptography.exceptions import InvalidSignature # noqa: PLC0415
from cryptography.hazmat.primitives.asymmetric import ed25519 # noqa: PLC0415
try:
ed25519.Ed25519PublicKey.from_public_bytes(raw).verify(
bytes.fromhex(sig_hex), msg32)
return True
except (InvalidSignature, ValueError):
return False
except Exception:
return False
return False
[docs]def self_certifying(did: str) -> bool:
"""Whether this DID can be verified from the identifier alone."""
return signing_key(did) is not None
[docs]def resolvable(did: str) -> bool:
"""Whether verifying this DID would need a document fetched."""
parts = did.split(':', 2)
return len(parts) >= 3 and parts[0] == 'did' and parts[1] in RESOLVABLE
[docs]def refusal(did: str) -> str:
"""Why this DID cannot verify a signature, in a sentence."""
if self_certifying(did):
return ''
if resolvable(did):
return ('did:%s needs its document fetched to verify, which this node will not do '
'on an audit path: the network may be unplugged, and a rotated key makes an '
'old signature unverifiable. Pin the key instead.' % did.split(':')[1])
try:
parsed = parse(did.split('#', 1)[0])
except ValueError as e:
return str(e)
if parsed.get('method') == 'key' and parsed.get('kind') == 'agreement':
return 'an x25519 agreement key signs nothing; offer the node or transport key'
return 'that DID names no key this node can verify a signature with'
# ------------------------------------------------------------- operator DIDs
# `constants.json#operator_did`: the operator tag of a kind 11801 and the d of
# a kind 30831. A person is did:nostr (or the bare hex that means the same), a
# circle is did:group:<slug>. A group resolves through its kind 30834 controller
# document, which is P2 work: it parses here so a node can file it, compare it
# and refuse it BY NAME, never pass it by accident.
GROUP_REFUSAL: str = 'did:group controller resolution is P2: no signature verifies under a group DID yet'
_GROUP_SLUG_MIN, _GROUP_SLUG_MAX = 3, 48
_SLUG_CHARS = frozenset('abcdefghijklmnopqrstuvwxyz0123456789-')
[docs]class Operator(TypedDict):
method: str # 'nostr' | 'group'
did: str # the normalised DID
pubkey: Optional[str] # x-only hex for nostr, None for group
slug: Optional[str] # the group slug, None for nostr
refusal: str # '' when the DID can verify a signature on its own
[docs]def is_group_slug(slug: str) -> bool:
return (_GROUP_SLUG_MIN <= len(slug) <= _GROUP_SLUG_MAX and all(c in _SLUG_CHARS for c in slug))
[docs]def parse_operator(value: str) -> Operator:
"""The operator an operator tag names. Bare 64-hex and did:nostr:<hex> are
the same operator and compare equal here because both come back as the
parsed pubkey; did:group:<slug> parses with a refusal that says why nothing
verifies under it yet. Anything else is a ValueError."""
if not isinstance(value, str) or not value:
raise ValueError('operator must be a non-empty string')
s = value.strip()
if s.startswith('did:group:'):
slug = s[len('did:group:'):]
if not is_group_slug(slug):
raise ValueError('did:group slug is [a-z0-9-]{%d,%d}' % (_GROUP_SLUG_MIN, _GROUP_SLUG_MAX))
return {'method': 'group', 'did': 'did:group:' + slug, 'pubkey': None, 'slug': slug, 'refusal': GROUP_REFUSAL}
pk = s[len('did:nostr:'):] if s.startswith('did:nostr:') else s
if not spelling.is_hex(pk, 64, upper=True):
raise ValueError('an operator is did:nostr:<64 hex>, a bare 64-hex pubkey, or did:group:<slug>')
pk = pk.lower()
compressed_node_key(pk)
return {'method': 'nostr', 'did': did_nostr(pk), 'pubkey': pk, 'slug': None, 'refusal': ''}
[docs]def same_operator(a: str, b: str) -> bool:
"""Whether two operator spellings name one operator: the parsed pubkey or
slug is compared, never the string (constants.json operator_did.bare_hex)."""
try:
pa, pb = parse_operator(a), parse_operator(b)
except ValueError:
return False
return pa['method'] == pb['method'] and pa['pubkey'] == pb['pubkey'] and pa['slug'] == pb['slug']