Files
plm-lottery/apps/lottery/keys.py
T

67 lines
3.1 KiB
Python

"""Who may hold which key (ARC-78, roadmap B4).
The web process knows only the **public** account key (`PLM_ACCOUNT_XPUB`): it is enough to derive every deposit
and pool address. The private side — the master xprv, encrypted, and the key that encrypts it, two separate files —
is loaded only by the worker (`PROCESS_ROLE=worker`) and only when both files are there. Anywhere else the loader
refuses, whatever the files, so a bug in a view cannot reach the signing key.
"""
import os
from pathlib import Path
from cryptography.fernet import Fernet, InvalidToken
from django.conf import settings
from embit.bip32 import HDKey
from plm_engine.network import Profile
class SigningKeyUnavailable(Exception):
pass
def public_account_key() -> HDKey:
"""The account's public key, from configuration: derives addresses, signs nothing."""
xpub = settings.PLM_ACCOUNT_XPUB
if not xpub:
raise SigningKeyUnavailable("PLM_ACCOUNT_XPUB is not set: run `manage.py init_keys` and put the public key in .env")
return HDKey.from_base58(xpub)
def signing_account_key() -> HDKey:
"""The private account key. Only the worker can have it."""
if settings.PROCESS_ROLE != "worker":
raise SigningKeyUnavailable("the signing key is only available to the worker process")
master_file, key_file = settings.PLM_MASTER_KEY_FILE, settings.PLM_KEY_ENCRYPTION_KEY_FILE
if not (master_file and key_file):
raise SigningKeyUnavailable("PLM_MASTER_KEY_FILE and PLM_KEY_ENCRYPTION_KEY_FILE are not set")
try:
token = Path(master_file).read_bytes()
fernet = Fernet(Path(key_file).read_bytes().strip())
master = HDKey.from_base58(fernet.decrypt(token).decode())
except (OSError, InvalidToken, ValueError) as exc:
raise SigningKeyUnavailable(f"the signing key cannot be loaded: {exc.__class__.__name__}") from exc
return master.derive(settings.PLM_PROFILE.account_path)
def _write_private(path: Path, data: bytes) -> None:
"""`0600` from the start, never through a wider mode (SEC-50)."""
fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
with os.fdopen(fd, "wb") as handle:
os.fchmod(handle.fileno(), 0o600)
handle.write(data)
def generate_keys(directory: Path, profile: Profile) -> str:
"""Create a master key and its encryption key under `directory` (refuses to overwrite) and return the
account's public key, to be put in `PLM_ACCOUNT_XPUB`."""
directory.mkdir(parents=True, exist_ok=True, mode=0o700)
master_path, key_path = directory / "master.key", directory / "master.encryption.key"
if master_path.exists() or key_path.exists():
raise FileExistsError(f"{directory} already holds keys: refusing to overwrite them")
master = HDKey.from_seed(os.urandom(32), version=profile.embit["xprv"])
encryption_key = Fernet.generate_key()
_write_private(key_path, encryption_key)
_write_private(master_path, Fernet(encryption_key).encrypt(master.to_base58(version=profile.embit["xprv"]).encode()))
account = master.derive(profile.account_path).to_public()
return account.to_base58(version=profile.embit["xpub"])