Files
plm-lottery/app/wallet/hd.py
T
davideandClaude Sonnet 5.5 3ee60a23da B1: plm_engine takes the modules without a database (ADR-59)
HD derivation (pure part), PSBT builder, Electrum client/merkle/quorum/scripthash, network
profile, addresses and header checks move to plm_engine; the old stack imports them from
there. A test forbids framework imports in the package.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-16 15:31:47 +01:00

60 lines
2.4 KiB
Python

import os
from embit.bip32 import HDKey
from app.config import settings
from plm_engine import hd as engine
from app.wallet.keystore import decrypt_xprv, encrypt_xprv, write_secret_file
from plm_engine.network import ACCOUNT_PATH, PLM_MAINNET
_account_key: HDKey | None = None
def generate_master_key(overwrite: bool = False) -> None:
"""One-time ops bootstrap: create a random master seed, encrypt it, write it to
disk. Not exposed via any API endpoint — run manually before first launch."""
if os.path.exists(settings.master_key_path) and not overwrite:
raise FileExistsError(f"{settings.master_key_path} already exists")
root = HDKey.from_seed(os.urandom(32), version=PLM_MAINNET["xprv"])
write_secret_file(settings.master_key_path, encrypt_xprv(root.to_base58(version=PLM_MAINNET["xprv"])))
def _load_account_key() -> HDKey:
global _account_key
if _account_key is None:
with open(settings.master_key_path, "rb") as f:
token = f.read()
root = HDKey.from_base58(decrypt_xprv(token))
_account_key = root.derive(ACCOUNT_PATH)
return _account_key
def derive_user_key(derivation_index: int) -> HDKey:
return engine.user_key(_load_account_key(), derivation_index)
def derive_user_address(derivation_index: int) -> str:
return engine.user_address(_load_account_key(), derivation_index)
def derive_user_wif(derivation_index: int) -> str:
"""Exports a user's raw private key (WIF) for manual server-side intervention (e.g. sweeping funds back to a
user, or out, if something gets stuck). Callers must treat the result as a live secret: log access, never
persist it, never return it over an unauthenticated channel."""
return engine.user_wif(_load_account_key(), derivation_index)
def derive_pool_key(round_id: int | None = None) -> HDKey:
"""A pool key: a round's own (B-80, RND-35) or, without a `round_id`, the reserve key. See `plm_engine.hd`."""
return engine.pool_key(_load_account_key(), round_id)
def derive_pool_address(round_id: int | None = None) -> str:
"""The pool address of a round (B-80), or the reserve address without a `round_id`."""
return engine.pool_address(_load_account_key(), round_id)
def derive_round_pool_key(round_id: int, pool_address: str) -> HDKey:
"""The key that controls `pool_address`, the address stored on round `round_id` (see `plm_engine.hd`)."""
return engine.round_pool_key(_load_account_key(), round_id, pool_address)