2016-10-06 13:04:38 +00:00
|
|
|
from trezor import wire
|
2018-02-27 15:35:21 +00:00
|
|
|
from trezor.crypto import bip32, bip39
|
2018-07-03 14:20:26 +00:00
|
|
|
|
2018-02-27 15:35:21 +00:00
|
|
|
from apps.common import cache, storage
|
|
|
|
from apps.common.request_passphrase import protect_by_passphrase
|
2016-10-06 13:04:38 +00:00
|
|
|
|
2018-07-03 14:20:58 +00:00
|
|
|
_DEFAULT_CURVE = "secp256k1"
|
2016-10-06 13:04:38 +00:00
|
|
|
|
|
|
|
|
2018-07-03 14:20:58 +00:00
|
|
|
async def derive_node(
|
|
|
|
ctx: wire.Context, path: list, curve_name: str = _DEFAULT_CURVE
|
|
|
|
) -> bip32.HDNode:
|
2018-05-28 13:20:31 +00:00
|
|
|
seed = await _get_cached_seed(ctx)
|
2018-02-06 13:28:22 +00:00
|
|
|
node = bip32.from_seed(seed, curve_name)
|
2018-06-21 12:00:02 +00:00
|
|
|
node.derive_path(path)
|
2018-02-06 13:28:22 +00:00
|
|
|
return node
|
2016-10-06 13:04:38 +00:00
|
|
|
|
|
|
|
|
2018-05-28 13:20:31 +00:00
|
|
|
async def _get_cached_seed(ctx: wire.Context) -> bytes:
|
|
|
|
if not storage.is_initialized():
|
2018-07-03 14:20:58 +00:00
|
|
|
raise wire.ProcessError("Device is not initialized")
|
2018-02-09 17:59:26 +00:00
|
|
|
if cache.get_seed() is None:
|
2018-05-28 13:20:31 +00:00
|
|
|
passphrase = await _get_cached_passphrase(ctx)
|
|
|
|
seed = bip39.seed(storage.get_mnemonic(), passphrase)
|
|
|
|
cache.set_seed(seed)
|
2018-02-09 17:59:26 +00:00
|
|
|
return cache.get_seed()
|
2016-10-06 13:04:38 +00:00
|
|
|
|
|
|
|
|
2018-05-28 13:20:31 +00:00
|
|
|
async def _get_cached_passphrase(ctx: wire.Context) -> str:
|
|
|
|
if cache.get_passphrase() is None:
|
|
|
|
passphrase = await protect_by_passphrase(ctx)
|
|
|
|
cache.set_passphrase(passphrase)
|
|
|
|
return cache.get_passphrase()
|
2017-05-23 10:44:36 +00:00
|
|
|
|
|
|
|
|
2018-07-03 14:20:58 +00:00
|
|
|
def derive_node_without_passphrase(
|
|
|
|
path: list, curve_name: str = _DEFAULT_CURVE
|
|
|
|
) -> bip32.HDNode:
|
2017-05-23 10:44:36 +00:00
|
|
|
if not storage.is_initialized():
|
2018-07-03 14:20:58 +00:00
|
|
|
raise Exception("Device is not initialized")
|
2018-02-27 15:35:21 +00:00
|
|
|
|
2018-07-03 14:20:58 +00:00
|
|
|
seed = bip39.seed(storage.get_mnemonic(), "")
|
2018-02-06 13:28:22 +00:00
|
|
|
node = bip32.from_seed(seed, curve_name)
|
|
|
|
node.derive_path(path)
|
|
|
|
return node
|
2018-05-11 13:31:53 +00:00
|
|
|
|
|
|
|
|
|
|
|
def remove_ed25519_public_key_prefix(pubkey: bytes) -> bytes:
|
|
|
|
# 0x01 prefix is not part of the actual public key, hence removed
|
|
|
|
return pubkey[1:]
|