"""The three keys a node holds, and their Multikey encodings::
node secp256k1, x-only; the nostr identity and the did:nostr subject.
BIP-340 signatures come from fleetmesh_core/crypto/crypto.py. multicodec 0xe7.
agreement X25519; every DIDComm v2 envelope. multicodec 0xec.
transport Ed25519; iroh NodeId, libp2p PeerId, gossipsub StrictSign. 0xed.
A Multikey here is multibase 'f' (lowercase hex) over the multicodec varint and
the public key, which is why a descriptor's key tags read fec01<x25519> and
fed01<ed25519>: 0xec and 0xed each encode as two varint bytes, ec 01 and ed 01.
The node key is a compressed secp256k1 point, fe70102<x>. constants.json crypto
names all three; nothing here is a choice.
"""
from __future__ import annotations
import os
from typing import Literal, Optional, Union
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import ed25519, x25519
from cryptography.exceptions import InvalidSignature
KeyKind = Literal['node', 'agreement', 'transport']
CODEC: dict[KeyKind, bytes] = {'node': b'\xe7\x01', 'agreement': b'\xec\x01', 'transport': b'\xed\x01'}
# The node key is secp256k1 and its Multikey carries the compressed point, so
# the x-only nostr key gains the 0x02 prefix BIP-340 implies (even y). The
# other two are raw 32-byte keys. Hence fe70102<x>, fec01<x25519>, fed01<ed25519>,
# which is the pattern schemas/identity/did-nostr-node.schema.json enforces.
PREFIX: dict[KeyKind, str] = {'node': 'fe70102', 'agreement': 'fec01', 'transport': 'fed01'}
_RAW = serialization.Encoding.Raw
_PUB = serialization.PublicFormat.Raw
[docs]def multikey(kind: KeyKind | str, raw_pubkey: bytes) -> str:
if kind not in CODEC or len(raw_pubkey) != 32:
raise ValueError('a Multikey here is one of %s over 32 bytes' % sorted(CODEC))
return PREFIX[kind] + raw_pubkey.hex()
[docs]def parse_multikey(s: str) -> tuple[KeyKind, bytes]:
"""(kind, raw 32 bytes). Rejects anything that is not one of the three."""
for kind, prefix in PREFIX.items():
if s.startswith(prefix) and len(s) == len(prefix) + 64:
return kind, bytes.fromhex(s[len(prefix):])
raise ValueError('not a fleetmesh Multikey: %r' % s[:12])
# ------------------------------------------------------------- X25519 ----
[docs]def agreement_keypair(seed: Optional[bytes] = None) -> tuple[x25519.X25519PrivateKey, x25519.X25519PublicKey]:
priv = (x25519.X25519PrivateKey.from_private_bytes(seed) if seed
else x25519.X25519PrivateKey.generate())
return priv, priv.public_key()
[docs]def agreement_public(raw: bytes) -> x25519.X25519PublicKey:
return x25519.X25519PublicKey.from_public_bytes(raw)
[docs]def raw_public(key: Union[x25519.X25519PublicKey, ed25519.Ed25519PublicKey]) -> bytes:
return key.public_bytes(_RAW, _PUB)
[docs]def x25519_shared(priv: x25519.X25519PrivateKey, their_pub: x25519.X25519PublicKey) -> bytes:
return priv.exchange(their_pub)
# ------------------------------------------------------------ Ed25519 ----
[docs]def transport_keypair(seed: Optional[bytes] = None) -> tuple[ed25519.Ed25519PrivateKey, ed25519.Ed25519PublicKey]:
priv = (ed25519.Ed25519PrivateKey.from_private_bytes(seed) if seed
else ed25519.Ed25519PrivateKey.generate())
return priv, priv.public_key()
[docs]def ed25519_sign(priv: ed25519.Ed25519PrivateKey, message: bytes) -> bytes:
return priv.sign(message)
[docs]def ed25519_verify(pub: ed25519.Ed25519PublicKey, message: bytes, signature: bytes) -> bool:
try:
pub.verify(signature, message)
return True
except InvalidSignature:
return False
[docs]def fresh_seed() -> bytes:
return os.urandom(32)