Files
plm-lottery/plm_engine/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

53 lines
2.0 KiB
Python

"""HD derivation from an account key, pure (ADR-59, roadmap B1): no settings, no files, no database.
The account key (`m/84'/746'/0'`) is handed in by whoever holds the master key; this module only
derives from it. Branch 0 is users, branch 1 the reserve pool key, branch 2 one pool key per round
(B-80, RND-35).
"""
from embit import script
from embit.bip32 import HDKey
from embit.ec import PrivateKey
from .network import PLM_MAINNET
def user_key(account: HDKey, derivation_index: int) -> HDKey:
return account.derive(f"0/{derivation_index}")
def address_of(key: HDKey) -> str:
return script.p2wpkh(key.to_public()).address(network=PLM_MAINNET)
def user_address(account: HDKey, derivation_index: int) -> str:
return address_of(user_key(account, derivation_index))
def user_wif(account: HDKey, derivation_index: int) -> str:
key = user_key(account, derivation_index)
return PrivateKey(key.secret, compressed=True, network=PLM_MAINNET).wif(network=PLM_MAINNET)
def pool_key(account: HDKey, round_id: int | None = None) -> HDKey:
"""A round's own key on branch 2, or the reserve key (branch 1, index 0) without a `round_id`."""
if round_id is None:
return account.derive("1/0")
if round_id < 1:
raise ValueError(f"invalid round id {round_id}")
return account.derive(f"2/{round_id}")
def pool_address(account: HDKey, round_id: int | None = None) -> str:
return address_of(pool_key(account, round_id))
def round_pool_key(account: HDKey, round_id: int, stored_address: str) -> HDKey:
"""The key that controls `stored_address`, the address stored on round `round_id`: the round's own, or
the reserve key for a round opened before B-80. A mismatch fails loudly instead of building a transaction
that spends someone else's coins."""
for key in (pool_key(account, round_id), pool_key(account)):
if address_of(key) == stored_address:
return key
raise ValueError(f"round {round_id}: no pool key controls the stored address {stored_address!r}")