"""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 MAINNET, Profile def account_key(master: HDKey, profile: Profile = MAINNET) -> HDKey: """The account key of the profile's chain: `m/84'/'/0'` under the master key.""" return master.derive(profile.account_path) def user_key(account: HDKey, derivation_index: int) -> HDKey: return account.derive(f"0/{derivation_index}") def address_of(key: HDKey, profile: Profile = MAINNET) -> str: return script.p2wpkh(key.to_public()).address(network=profile.embit) def user_address(account: HDKey, derivation_index: int, profile: Profile = MAINNET) -> str: return address_of(user_key(account, derivation_index), profile) def user_wif(account: HDKey, derivation_index: int, profile: Profile = MAINNET) -> str: key = user_key(account, derivation_index) return PrivateKey(key.secret, compressed=True, network=profile.embit).wif(network=profile.embit) 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, profile: Profile = MAINNET) -> str: return address_of(pool_key(account, round_id), profile) def round_pool_key(account: HDKey, round_id: int, stored_address: str, profile: Profile = MAINNET) -> 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, profile) == stored_address: return key raise ValueError(f"round {round_id}: no pool key controls the stored address {stored_address!r}")