"""The node's keys on disk.
One JSON file, mode 0600, holding the three secrets constants.json names: the
secp256k1 node key (the nostr identity and did:nostr subject), the X25519
agreement key, and the Ed25519 transport key. Generated once, read every
start. Nothing else is stored here: grants, receipts and the event store have
their own files, and an operator who rotates the node key has a new node.
"""
from __future__ import annotations
import json
import os
import stat
from typing import Literal
from cryptography.hazmat.primitives.asymmetric import ed25519, x25519
from fleetmesh_core.crypto import crypto, keys # noqa: E402
FILE = 'keys.json'
[docs]class Keystore:
node_sk: str
node_pk: str
did: str
agreement_priv: x25519.X25519PrivateKey
agreement_pub: x25519.X25519PublicKey
transport_priv: ed25519.Ed25519PrivateKey
transport_pub: ed25519.Ed25519PublicKey
_seeds: tuple[bytes, bytes]
[docs] def __init__(self, node_sk: str, agreement_seed: bytes, transport_seed: bytes) -> None:
# A secret that is not a scalar in [1, N) is not a key. Below 1 the
# curve arithmetic returned None and the node died on a TypeError;
# at or above N it was silently reduced, so the node signed with a
# key that was not the one in its file. Refuse both by name.
try:
value = int(node_sk, 16)
except (TypeError, ValueError):
raise ValueError('node_sk is 64 hex characters')
if not isinstance(node_sk, str) or len(node_sk) != 64 or not (1 <= value < crypto.N):
raise ValueError('node_sk must be a 32-byte scalar in [1, N)')
if len(agreement_seed) != 32 or len(transport_seed) != 32:
raise ValueError('agreement and transport seeds are 32 bytes')
self.node_sk = node_sk # hex
self.node_pk = crypto.pubkey(node_sk) # hex, x-only
self.did = 'did:nostr:' + self.node_pk
self.agreement_priv, self.agreement_pub = keys.agreement_keypair(agreement_seed)
self.transport_priv, self.transport_pub = keys.transport_keypair(transport_seed)
self._seeds = (agreement_seed, transport_seed)
# ---- encodings the descriptor and DID document carry ----------------
[docs] def multikeys(self) -> dict[str, str]:
return {'node': keys.multikey('node', bytes.fromhex(self.node_pk)),
'agreement': keys.multikey('agreement', keys.raw_public(self.agreement_pub)),
'transport': keys.multikey('transport', keys.raw_public(self.transport_pub))}
[docs] def kid(self, which: Literal['agreement', 'transport', 'node'] = 'agreement') -> str:
return '%s#%s' % (self.did, {'agreement': 'agree', 'transport': 'wire', 'node': 'nostr'}[which])
# ---- persistence -----------------------------------------------------
[docs] @classmethod
def generate(cls) -> Keystore:
sk = os.urandom(32).hex()
while not (1 <= int(sk, 16) < crypto.N):
sk = os.urandom(32).hex()
return cls(sk, keys.fresh_seed(), keys.fresh_seed())
[docs] @classmethod
def load(cls, directory: str | os.PathLike[str]) -> Keystore:
path = os.path.join(directory, FILE)
mode = stat.S_IMODE(os.stat(path).st_mode)
if mode & 0o077:
raise PermissionError('%s is readable by others (mode %o); refusing to load' % (path, mode))
with open(path, encoding='utf-8') as _fh:
d = json.load(_fh)
if d.get('format') != 'meshnode-keys/1':
raise ValueError('not a meshnode key file')
return cls(d['node_sk'], bytes.fromhex(d['agreement_seed']), bytes.fromhex(d['transport_seed']))
[docs] def save(self, directory: str | os.PathLike[str]) -> str:
os.makedirs(directory, mode=0o700, exist_ok=True)
path = os.path.join(directory, FILE)
if os.path.exists(path):
raise FileExistsError('%s exists; a node does not overwrite its own keys' % path)
body = json.dumps({'format': 'meshnode-keys/1', 'node_sk': self.node_sk,
'agreement_seed': self._seeds[0].hex(),
'transport_seed': self._seeds[1].hex(),
'node_pk': self.node_pk, 'did': self.did}, indent=2)
fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
with os.fdopen(fd, 'w', encoding='utf-8') as f:
f.write(body + '\n')
return path
[docs] @classmethod
def load_or_generate(cls, directory: str | os.PathLike[str]) -> Keystore:
if os.path.exists(os.path.join(directory, FILE)):
return cls.load(directory)
ks = cls.generate()
ks.save(directory)
return ks