core: add final mypy fixes!

pull/645/head
Tomas Susanka 5 years ago
parent 4bae47ea6d
commit 0511cc8b8c

@ -63,7 +63,8 @@ class ProtoField:
if field.type == field.TYPE_MESSAGE: if field.type == field.TYPE_MESSAGE:
proto_type = py_type = type_name proto_type = py_type = type_name
elif field.type == field.TYPE_ENUM: elif field.type == field.TYPE_ENUM:
valuestr = ", ".join(str(v) for v in descriptor.enum_types[type_name]) value_dict = descriptor.enum_types[type_name]
valuestr = ", ".join(str(v) for v in value_dict.values())
proto_type = 'p.EnumType("{}", ({}))'.format(type_name, valuestr) proto_type = 'p.EnumType("{}", ({}))'.format(type_name, valuestr)
py_type = "EnumType" + type_name py_type = "EnumType" + type_name
else: else:
@ -162,7 +163,7 @@ class Descriptor:
# find messages and enums # find messages and enums
self.messages = [] self.messages = []
self.enums = [] self.enums = []
self.enum_types = defaultdict(set) self.enum_types = defaultdict(dict)
for file in self.files: for file in self.files:
self.messages += file.message_type self.messages += file.message_type
self.enums += file.enum_type self.enums += file.enum_type
@ -218,17 +219,17 @@ class Descriptor:
# please keep the yields aligned # please keep the yields aligned
# fmt: off # fmt: off
... # https://github.com/ambv/black/issues/385 ... # https://github.com/ambv/black/issues/385
yield " def __init__(" yield " def __init__("
yield " self," yield " self,"
for field in fields: for field in fields:
yield " {}: {} = None,".format(field.name, field.py_type) yield f" {field.name}: {field.py_type} = None,"
yield " ) -> None:" yield " ) -> None:"
for field in fields: for field in fields:
if field.repeated: if field.repeated:
yield " self.{0} = {0} if {0} is not None else []".format(field.name) yield f" self.{field.name} = {field.name} if {field.name} is not None else []"
else: else:
yield " self.{0} = {0}".format(field.name) yield f" self.{field.name} = {field.name}"
# fmt: on # fmt: on
def create_fields_method(self, fields): def create_fields_method(self, fields):
@ -278,19 +279,17 @@ class Descriptor:
yield "" yield ""
yield "if __debug__:" yield "if __debug__:"
yield " try:" yield " try:"
yield " from typing import Dict, List, Optional" yield " from typing import Dict, List # noqa: F401"
yield " from typing_extensions import Literal # noqa: F401" yield " from typing_extensions import Literal # noqa: F401"
all_enums = [field for field in fields if field.type_name in self.enum_types] all_enums = [field for field in fields if field.type_name in self.enum_types]
for field in all_enums: for field in all_enums:
allowed_values = self.enum_types[field.type_name] allowed_values = self.enum_types[field.type_name].values()
valuestr = ", ".join(str(v) for v in sorted(allowed_values)) valuestr = ", ".join(str(v) for v in sorted(allowed_values))
yield " {} = Literal[{}]".format(field.py_inner_type, valuestr) yield " {} = Literal[{}]".format(field.py_inner_type, valuestr)
yield " except ImportError:" yield " except ImportError:"
yield " Dict, List, Optional = None, None, None # type: ignore" yield " pass"
for field in all_enums:
yield " {} = None # type: ignore".format(field.py_inner_type)
yield "" yield ""
yield "" yield ""
@ -311,6 +310,11 @@ class Descriptor:
def process_enum(self, enum): def process_enum(self, enum):
logging.debug("Processing enum {}".format(enum.name)) logging.debug("Processing enum {}".format(enum.name))
# file header
yield "if False:"
yield " from typing_extensions import Literal"
yield ""
for value in enum.value: for value in enum.value:
# Remove type name from the beginning of the constant # Remove type name from the beginning of the constant
# For example "PinMatrixRequestType_Current" -> "Current" # For example "PinMatrixRequestType_Current" -> "Current"
@ -324,8 +328,8 @@ class Descriptor:
enum_prefix, _ = enum_prefix.rsplit("Type", 1) enum_prefix, _ = enum_prefix.rsplit("Type", 1)
name = strip_leader(name, enum_prefix) name = strip_leader(name, enum_prefix)
self.enum_types[enum.name].add(value.number) self.enum_types[enum.name][value.name] = value.number
yield "{} = {}".format(name, value.number) yield f"{name} = {value.number} # type: Literal[{value.number}]"
def process_messages(self, messages): def process_messages(self, messages):
for message in sorted(messages, key=lambda m: m.name): for message in sorted(messages, key=lambda m: m.name):

@ -274,7 +274,7 @@ STATIC const mp_obj_type_t mod_trezorio_FatFSFile_type = {
.locals_dict = (void *)&mod_trezorio_FatFSFile_locals_dict, .locals_dict = (void *)&mod_trezorio_FatFSFile_locals_dict,
}; };
/// class FatFSDir(Iterable[Tuple[int, str, str]]): /// class FatFSDir(Iterator[Tuple[int, str, str]]):
/// """ /// """
/// Class encapsulating directory /// Class encapsulating directory
/// """ /// """

@ -54,7 +54,7 @@ class FatFSFile:
# extmod/modtrezorio/modtrezorio-fatfs.h # extmod/modtrezorio/modtrezorio-fatfs.h
class FatFSDir(Iterable[Tuple[int, str, str]]): class FatFSDir(Iterator[Tuple[int, str, str]]):
""" """
Class encapsulating directory Class encapsulating directory
""" """

@ -1,6 +1,6 @@
from trezor.crypto import hashlib, hmac, random from trezor.crypto import hashlib, hmac, random
from apps.common import storage from apps.common.storage.device import get_device_id
if False: if False:
from typing import Optional from typing import Optional
@ -28,7 +28,7 @@ def get_state(prev_state: bytes = None, passphrase: str = None) -> Optional[byte
def _compute_state(salt: bytes, passphrase: str) -> bytes: def _compute_state(salt: bytes, passphrase: str) -> bytes:
# state = HMAC(passphrase, salt || device_id) # state = HMAC(passphrase, salt || device_id)
message = salt + storage.device.get_device_id().encode() message = salt + get_device_id().encode()
state = hmac.new(passphrase.encode(), message, hashlib.sha256).digest() state = hmac.new(passphrase.encode(), message, hashlib.sha256).digest()
return salt + state return salt + state

@ -6,18 +6,20 @@ from trezor.ui.confirm import CONFIRMED, INFO, Confirm, HoldToConfirm, InfoConfi
if __debug__: if __debug__:
from apps.debug import confirm_signal from apps.debug import confirm_signal
from trezor.ui.scroll import Paginated
if False: if False:
from typing import Any, Callable, Optional from typing import Any, Callable, Optional
from trezor import ui from trezor import ui
from trezor.ui.confirm import ButtonContent, ButtonStyleType from trezor.ui.confirm import ButtonContent, ButtonStyleType
from trezor.ui.loader import LoaderStyleType from trezor.ui.loader import LoaderStyleType
from trezor.messages.ButtonRequest import EnumTypeButtonRequestType
async def confirm( async def confirm(
ctx: wire.Context, ctx: wire.Context,
content: ui.Component, content: ui.Component,
code: int = ButtonRequestType.Other, code: EnumTypeButtonRequestType = ButtonRequestType.Other,
confirm: Optional[ButtonContent] = Confirm.DEFAULT_CONFIRM, confirm: Optional[ButtonContent] = Confirm.DEFAULT_CONFIRM,
confirm_style: ButtonStyleType = Confirm.DEFAULT_CONFIRM_STYLE, confirm_style: ButtonStyleType = Confirm.DEFAULT_CONFIRM_STYLE,
cancel: Optional[ButtonContent] = Confirm.DEFAULT_CANCEL, cancel: Optional[ButtonContent] = Confirm.DEFAULT_CANCEL,
@ -27,6 +29,10 @@ async def confirm(
await ctx.call(ButtonRequest(code=code), ButtonAck) await ctx.call(ButtonRequest(code=code), ButtonAck)
if content.__class__.__name__ == "Paginated": if content.__class__.__name__ == "Paginated":
# The following works because asserts are omitted in non-debug builds.
# IOW if the assert runs, that means __debug__ is True and Paginated is imported
assert isinstance(content, Paginated)
content.pages[-1] = Confirm( content.pages[-1] = Confirm(
content.pages[-1], content.pages[-1],
confirm, confirm,
@ -35,7 +41,7 @@ async def confirm(
cancel_style, cancel_style,
major_confirm, major_confirm,
) )
dialog = content dialog = content # type: ui.Layout
else: else:
dialog = Confirm( dialog = Confirm(
content, confirm, confirm_style, cancel, cancel_style, major_confirm content, confirm, confirm_style, cancel, cancel_style, major_confirm
@ -51,7 +57,7 @@ async def info_confirm(
ctx: wire.Context, ctx: wire.Context,
content: ui.Component, content: ui.Component,
info_func: Callable, info_func: Callable,
code: int = ButtonRequestType.Other, code: EnumTypeButtonRequestType = ButtonRequestType.Other,
confirm: ButtonContent = InfoConfirm.DEFAULT_CONFIRM, confirm: ButtonContent = InfoConfirm.DEFAULT_CONFIRM,
confirm_style: ButtonStyleType = InfoConfirm.DEFAULT_CONFIRM_STYLE, confirm_style: ButtonStyleType = InfoConfirm.DEFAULT_CONFIRM_STYLE,
cancel: ButtonContent = InfoConfirm.DEFAULT_CANCEL, cancel: ButtonContent = InfoConfirm.DEFAULT_CANCEL,
@ -80,19 +86,23 @@ async def info_confirm(
async def hold_to_confirm( async def hold_to_confirm(
ctx: wire.Context, ctx: wire.Context,
content: ui.Component, content: ui.Layout,
code: int = ButtonRequestType.Other, code: EnumTypeButtonRequestType = ButtonRequestType.Other,
confirm: ButtonContent = HoldToConfirm.DEFAULT_CONFIRM, confirm: str = HoldToConfirm.DEFAULT_CONFIRM,
confirm_style: ButtonStyleType = HoldToConfirm.DEFAULT_CONFIRM_STYLE, confirm_style: ButtonStyleType = HoldToConfirm.DEFAULT_CONFIRM_STYLE,
loader_style: LoaderStyleType = HoldToConfirm.DEFAULT_LOADER_STYLE, loader_style: LoaderStyleType = HoldToConfirm.DEFAULT_LOADER_STYLE,
) -> bool: ) -> bool:
await ctx.call(ButtonRequest(code=code), ButtonAck) await ctx.call(ButtonRequest(code=code), ButtonAck)
if content.__class__.__name__ == "Paginated": if content.__class__.__name__ == "Paginated":
# The following works because asserts are omitted in non-debug builds.
# IOW if the assert runs, that means __debug__ is True and Paginated is imported
assert isinstance(content, Paginated)
content.pages[-1] = HoldToConfirm( content.pages[-1] = HoldToConfirm(
content.pages[-1], confirm, confirm_style, loader_style content.pages[-1], confirm, confirm_style, loader_style
) )
dialog = content dialog = content # type: ui.Layout
else: else:
dialog = HoldToConfirm(content, confirm, confirm_style, loader_style) dialog = HoldToConfirm(content, confirm, confirm_style, loader_style)

@ -13,7 +13,7 @@ from apps.common import HARDENED
from apps.common.confirm import confirm, require_confirm from apps.common.confirm import confirm, require_confirm
if False: if False:
from typing import Iterable from typing import Iterable, Iterator
from trezor import wire from trezor import wire
@ -60,7 +60,7 @@ async def show_pubkey(ctx: wire.Context, pubkey: bytes) -> None:
await require_confirm(ctx, text, ButtonRequestType.PublicKey) await require_confirm(ctx, text, ButtonRequestType.PublicKey)
def split_address(address: str) -> Iterable[str]: def split_address(address: str) -> Iterator[str]:
return chunks(address, 17) return chunks(address, 17)

@ -2,7 +2,7 @@ from trezor import ui, workflow
from trezor.crypto import bip39, slip39 from trezor.crypto import bip39, slip39
from trezor.messages import BackupType from trezor.messages import BackupType
from apps.common import storage from apps.common.storage import device as storage_device
if False: if False:
from typing import Optional, Tuple from typing import Optional, Tuple
@ -14,11 +14,11 @@ def get() -> Tuple[Optional[bytes], int]:
def get_secret() -> Optional[bytes]: def get_secret() -> Optional[bytes]:
return storage.device.get_mnemonic_secret() return storage_device.get_mnemonic_secret()
def get_type() -> EnumTypeBackupType: def get_type() -> EnumTypeBackupType:
return storage.device.get_backup_type() return storage_device.get_backup_type()
def is_bip39() -> bool: def is_bip39() -> bool:
@ -43,8 +43,8 @@ def get_seed(passphrase: str = "", progress_bar: bool = True) -> bytes:
seed = bip39.seed(mnemonic_secret.decode(), passphrase, render_func) seed = bip39.seed(mnemonic_secret.decode(), passphrase, render_func)
else: # SLIP-39 else: # SLIP-39
identifier = storage.device.get_slip39_identifier() identifier = storage_device.get_slip39_identifier()
iteration_exponent = storage.device.get_slip39_iteration_exponent() iteration_exponent = storage_device.get_slip39_iteration_exponent()
if identifier is None or iteration_exponent is None: if identifier is None or iteration_exponent is None:
# Identifier or exponent expected but not found # Identifier or exponent expected but not found
raise RuntimeError raise RuntimeError

@ -12,7 +12,8 @@ from trezor.ui.passphrase import CANCELLED, PassphraseKeyboard, PassphraseSource
from trezor.ui.popup import Popup from trezor.ui.popup import Popup
from trezor.ui.text import Text from trezor.ui.text import Text
from apps.common import cache, storage from apps.common import cache
from apps.common.storage import device as storage_device
if __debug__: if __debug__:
from apps.debug import input_signal from apps.debug import input_signal
@ -21,14 +22,14 @@ _MAX_PASSPHRASE_LEN = const(50)
async def protect_by_passphrase(ctx: wire.Context) -> str: async def protect_by_passphrase(ctx: wire.Context) -> str:
if storage.device.has_passphrase(): if storage_device.has_passphrase():
return await request_passphrase(ctx) return await request_passphrase(ctx)
else: else:
return "" return ""
async def request_passphrase(ctx: wire.Context) -> str: async def request_passphrase(ctx: wire.Context) -> str:
source = storage.device.get_passphrase_source() source = storage_device.get_passphrase_source()
if source == PassphraseSourceType.ASK: if source == PassphraseSourceType.ASK:
source = await request_passphrase_source(ctx) source = await request_passphrase_source(ctx)
passphrase = await request_passphrase_ack( passphrase = await request_passphrase_ack(
@ -47,7 +48,9 @@ async def request_passphrase_source(ctx: wire.Context) -> int:
text.normal("Where do you want to", "enter your passphrase?") text.normal("Where do you want to", "enter your passphrase?")
source = PassphraseSource(text) source = PassphraseSource(text)
return await ctx.wait(source) response = await ctx.wait(source)
assert isinstance(response, int)
return response
async def request_passphrase_ack(ctx: wire.Context, on_device: bool) -> str: async def request_passphrase_ack(ctx: wire.Context, on_device: bool) -> str:
@ -56,8 +59,8 @@ async def request_passphrase_ack(ctx: wire.Context, on_device: bool) -> str:
text.normal("Please type your", "passphrase on the", "connected host.") text.normal("Please type your", "passphrase on the", "connected host.")
await Popup(text) await Popup(text)
req = PassphraseRequest(on_device=on_device) passphrase_request = PassphraseRequest(on_device=on_device)
ack = await ctx.call(req, PassphraseAck) ack = await ctx.call(passphrase_request, PassphraseAck)
if on_device: if on_device:
if ack.passphrase is not None: if ack.passphrase is not None:
@ -75,8 +78,10 @@ async def request_passphrase_ack(ctx: wire.Context, on_device: bool) -> str:
raise wire.ProcessError("Passphrase not provided") raise wire.ProcessError("Passphrase not provided")
passphrase = ack.passphrase passphrase = ack.passphrase
assert isinstance(passphrase, str)
state = cache.get_state(prev_state=ack.state, passphrase=passphrase) state = cache.get_state(prev_state=ack.state, passphrase=passphrase)
req = PassphraseStateRequest(state=state) state_request = PassphraseStateRequest(state=state)
ack = await ctx.call(req, PassphraseStateAck) await ctx.call(state_request, PassphraseStateAck)
return passphrase return passphrase

@ -41,18 +41,21 @@ async def request_pin(
while True: while True:
if __debug__: if __debug__:
result = await loop.race(dialog, input_signal()) pin = await loop.race(dialog, input_signal())
else: else:
result = await dialog pin = await dialog
if result is CANCELLED: if pin is CANCELLED:
raise PinCancelled raise PinCancelled
return result assert isinstance(pin, str)
return pin
async def request_pin_ack(ctx: wire.Context, *args: Any, **kwargs: Any) -> str: async def request_pin_ack(ctx: wire.Context, *args: Any, **kwargs: Any) -> str:
try: try:
await ctx.call(ButtonRequest(code=ButtonRequestType.Other), ButtonAck) await ctx.call(ButtonRequest(code=ButtonRequestType.Other), ButtonAck)
return await ctx.wait(request_pin(*args, **kwargs)) pin = await ctx.wait(request_pin(*args, **kwargs))
assert isinstance(pin, str)
return pin
except PinCancelled: except PinCancelled:
raise wire.ActionCancelled("Cancelled") raise wire.ActionCancelled("Cancelled")

@ -7,8 +7,8 @@ from trezor.ui.confirm import CONFIRMED, Confirm
from trezor.ui.text import Text from trezor.ui.text import Text
from trezor.utils import consteq from trezor.utils import consteq
from apps.common import storage
from apps.common.confirm import confirm from apps.common.confirm import confirm
from apps.common.storage.device import get_device_id
if False: if False:
from typing import Optional from typing import Optional
@ -78,7 +78,7 @@ async def _write_failed_dialog(ctx: Optional[wire.Context]) -> None:
def _get_device_dir() -> str: def _get_device_dir() -> str:
return "/trezor/device_%s" % storage.device.get_device_id().lower() return "/trezor/device_%s" % get_device_id().lower()
def _get_salt_path(new: bool = False) -> str: def _get_salt_path(new: bool = False) -> str:

@ -97,6 +97,7 @@ class Keychain:
def derive_slip77_blinding_private_key(self, script: bytes) -> bytes: def derive_slip77_blinding_private_key(self, script: bytes) -> bytes:
"""Following the derivation by Elements/Liquid.""" """Following the derivation by Elements/Liquid."""
master_node = self.derive(node_path=[b"SLIP-0077"], curve_name="slip21") master_node = self.derive(node_path=[b"SLIP-0077"], curve_name="slip21")
assert isinstance(master_node, Slip21Node)
return hmac.new( return hmac.new(
key=master_node.key(), msg=script, digestmod=hashlib.sha256 key=master_node.key(), msg=script, digestmod=hashlib.sha256
).digest() ).digest()

@ -96,7 +96,7 @@ def get_backup_type() -> EnumTypeBackupType:
): ):
# Invalid backup type # Invalid backup type
raise RuntimeError raise RuntimeError
return backup_type return backup_type # type: ignore
def has_passphrase() -> bool: def has_passphrase() -> bool:

@ -29,7 +29,7 @@ if False:
from typing import List, Optional from typing import List, Optional
def _require_progress(): def _require_progress() -> None:
if not is_in_progress(): if not is_in_progress():
raise RuntimeError raise RuntimeError
@ -77,7 +77,7 @@ def set_slip39_group_count(group_count: int) -> None:
common.set_uint8(_NAMESPACE, _SLIP39_GROUP_COUNT, group_count) common.set_uint8(_NAMESPACE, _SLIP39_GROUP_COUNT, group_count)
def get_slip39_group_count() -> Optional[int]: def get_slip39_group_count() -> int:
_require_progress() _require_progress()
return ( return (
common.get_uint8(_NAMESPACE, _SLIP39_GROUP_COUNT) or _DEFAULT_SLIP39_GROUP_COUNT common.get_uint8(_NAMESPACE, _SLIP39_GROUP_COUNT) or _DEFAULT_SLIP39_GROUP_COUNT

@ -28,7 +28,7 @@ if __debug__:
debuglink_decision_chan = loop.chan() debuglink_decision_chan = loop.chan()
async def debuglink_decision_dispatcher(): async def debuglink_decision_dispatcher() -> None:
from trezor.ui import confirm, swipe from trezor.ui import confirm, swipe
while True: while True:
@ -64,12 +64,13 @@ if __debug__:
ctx: wire.Context, msg: DebugLinkGetState ctx: wire.Context, msg: DebugLinkGetState
) -> DebugLinkState: ) -> DebugLinkState:
from trezor.messages.DebugLinkState import DebugLinkState from trezor.messages.DebugLinkState import DebugLinkState
from apps.common import storage, mnemonic from apps.common import mnemonic
from apps.common.storage.device import has_passphrase
m = DebugLinkState() m = DebugLinkState()
m.mnemonic_secret = mnemonic.get_secret() m.mnemonic_secret = mnemonic.get_secret()
m.mnemonic_type = mnemonic.get_type() m.mnemonic_type = mnemonic.get_type()
m.passphrase_protection = storage.device.has_passphrase() m.passphrase_protection = has_passphrase()
m.reset_entropy = reset_internal_entropy m.reset_entropy = reset_internal_entropy
if msg.wait_word_pos: if msg.wait_word_pos:

@ -5,6 +5,7 @@ from trezor.messages.Success import Success
from trezor.wire import register from trezor.wire import register
from apps.common import cache, mnemonic, storage from apps.common import cache, mnemonic, storage
from apps.common.storage import device as storage_device, recovery as storage_recovery
if False: if False:
from typing import NoReturn from typing import NoReturn
@ -22,20 +23,20 @@ def get_features() -> Features:
f.major_version = utils.VERSION_MAJOR f.major_version = utils.VERSION_MAJOR
f.minor_version = utils.VERSION_MINOR f.minor_version = utils.VERSION_MINOR
f.patch_version = utils.VERSION_PATCH f.patch_version = utils.VERSION_PATCH
f.revision = utils.GITREV f.revision = utils.GITREV.encode()
f.model = utils.MODEL f.model = utils.MODEL
f.device_id = storage.device.get_device_id() f.device_id = storage_device.get_device_id()
f.label = storage.device.get_label() f.label = storage_device.get_label()
f.initialized = storage.is_initialized() f.initialized = storage.is_initialized()
f.pin_protection = config.has_pin() f.pin_protection = config.has_pin()
f.pin_cached = config.has_pin() f.pin_cached = config.has_pin()
f.passphrase_protection = storage.device.has_passphrase() f.passphrase_protection = storage_device.has_passphrase()
f.passphrase_cached = cache.has_passphrase() f.passphrase_cached = cache.has_passphrase()
f.needs_backup = storage.device.needs_backup() f.needs_backup = storage_device.needs_backup()
f.unfinished_backup = storage.device.unfinished_backup() f.unfinished_backup = storage_device.unfinished_backup()
f.no_backup = storage.device.no_backup() f.no_backup = storage_device.no_backup()
f.flags = storage.device.get_flags() f.flags = storage_device.get_flags()
f.recovery_mode = storage.recovery.is_in_progress() f.recovery_mode = storage_recovery.is_in_progress()
f.backup_type = mnemonic.get_type() f.backup_type = mnemonic.get_type()
if utils.BITCOIN_ONLY: if utils.BITCOIN_ONLY:
f.capabilities = [ f.capabilities = [

@ -1,6 +1,7 @@
from trezor import config, res, ui from trezor import config, res, ui
from apps.common import storage from apps.common import storage
from apps.common.storage import device as storage_device
async def homescreen() -> None: async def homescreen() -> None:
@ -8,10 +9,10 @@ async def homescreen() -> None:
class Homescreen(ui.Layout): class Homescreen(ui.Layout):
def __init__(self): def __init__(self) -> None:
self.repaint = True self.repaint = True
def on_render(self): def on_render(self) -> None:
if not self.repaint: if not self.repaint:
return return
@ -19,17 +20,17 @@ class Homescreen(ui.Layout):
if not storage.is_initialized(): if not storage.is_initialized():
label = "Go to trezor.io/start" label = "Go to trezor.io/start"
else: else:
label = storage.device.get_label() or "My Trezor" label = storage_device.get_label() or "My Trezor"
image = storage.device.get_homescreen() image = storage_device.get_homescreen()
if not image: if not image:
image = res.load("apps/homescreen/res/bg.toif") image = res.load("apps/homescreen/res/bg.toif")
if storage.is_initialized() and storage.device.no_backup(): if storage.is_initialized() and storage_device.no_backup():
ui.header_error("SEEDLESS") ui.header_error("SEEDLESS")
elif storage.is_initialized() and storage.device.unfinished_backup(): elif storage.is_initialized() and storage_device.unfinished_backup():
ui.header_error("BACKUP FAILED!") ui.header_error("BACKUP FAILED!")
elif storage.is_initialized() and storage.device.needs_backup(): elif storage.is_initialized() and storage_device.needs_backup():
ui.header_warning("NEEDS BACKUP!") ui.header_warning("NEEDS BACKUP!")
elif storage.is_initialized() and not config.has_pin(): elif storage.is_initialized() and not config.has_pin():
ui.header_warning("PIN NOT SET!") ui.header_warning("PIN NOT SET!")

@ -1,8 +1,8 @@
from trezor.messages.Success import Success from trezor.messages.Success import Success
from apps.common import storage from apps.common.storage.device import set_flags
async def apply_flags(ctx, msg): async def apply_flags(ctx, msg):
storage.device.set_flags(msg.flags) set_flags(msg.flags)
return Success(message="Flags applied") return Success(message="Flags applied")

@ -3,8 +3,8 @@ from trezor.messages import ButtonRequestType, PassphraseSourceType
from trezor.messages.Success import Success from trezor.messages.Success import Success
from trezor.ui.text import Text from trezor.ui.text import Text
from apps.common import storage
from apps.common.confirm import require_confirm from apps.common.confirm import require_confirm
from apps.common.storage import device as storage_device
async def apply_settings(ctx, msg): async def apply_settings(ctx, msg):
@ -18,7 +18,7 @@ async def apply_settings(ctx, msg):
raise wire.ProcessError("No setting provided") raise wire.ProcessError("No setting provided")
if msg.homescreen is not None: if msg.homescreen is not None:
if len(msg.homescreen) > storage.device.HOMESCREEN_MAXSIZE: if len(msg.homescreen) > storage_device.HOMESCREEN_MAXSIZE:
raise wire.DataError("Homescreen is too complex") raise wire.DataError("Homescreen is too complex")
await require_confirm_change_homescreen(ctx) await require_confirm_change_homescreen(ctx)
@ -34,7 +34,7 @@ async def apply_settings(ctx, msg):
if msg.display_rotation is not None: if msg.display_rotation is not None:
await require_confirm_change_display_rotation(ctx, msg.display_rotation) await require_confirm_change_display_rotation(ctx, msg.display_rotation)
storage.device.load_settings( storage_device.load_settings(
label=msg.label, label=msg.label,
use_passphrase=msg.use_passphrase, use_passphrase=msg.use_passphrase,
homescreen=msg.homescreen, homescreen=msg.homescreen,
@ -43,7 +43,7 @@ async def apply_settings(ctx, msg):
) )
if msg.display_rotation is not None: if msg.display_rotation is not None:
ui.display.orientation(storage.device.get_rotation()) ui.display.orientation(storage_device.get_rotation())
return Success(message="Settings applied") return Success(message="Settings applied")

@ -2,23 +2,24 @@ from trezor import wire
from trezor.messages.Success import Success from trezor.messages.Success import Success
from apps.common import mnemonic, storage from apps.common import mnemonic, storage
from apps.common.storage import device as storage_device
from apps.management.reset_device import backup_seed, layout from apps.management.reset_device import backup_seed, layout
async def backup_device(ctx, msg): async def backup_device(ctx, msg):
if not storage.is_initialized(): if not storage.is_initialized():
raise wire.NotInitialized("Device is not initialized") raise wire.NotInitialized("Device is not initialized")
if not storage.device.needs_backup(): if not storage_device.needs_backup():
raise wire.ProcessError("Seed already backed up") raise wire.ProcessError("Seed already backed up")
mnemonic_secret, mnemonic_type = mnemonic.get() mnemonic_secret, mnemonic_type = mnemonic.get()
storage.device.set_unfinished_backup(True) storage_device.set_unfinished_backup(True)
storage.device.set_backed_up() storage_device.set_backed_up()
await backup_seed(ctx, mnemonic_type, mnemonic_secret) await backup_seed(ctx, mnemonic_type, mnemonic_secret)
storage.device.set_unfinished_backup(False) storage_device.set_unfinished_backup(False)
await layout.show_backup_success(ctx) await layout.show_backup_success(ctx)

@ -22,7 +22,7 @@ def is_slip39_word_count(word_count: int) -> bool:
raise RuntimeError raise RuntimeError
def is_slip39_backup_type(backup_type: EnumTypeBackupType): def is_slip39_backup_type(backup_type: EnumTypeBackupType) -> bool:
return backup_type in (BackupType.Slip39_Basic, BackupType.Slip39_Advanced) return backup_type in (BackupType.Slip39_Basic, BackupType.Slip39_Advanced)

@ -7,6 +7,7 @@ from trezor.ui.text import Text
from apps.common import storage from apps.common import storage
from apps.common.confirm import require_confirm from apps.common.confirm import require_confirm
from apps.common.storage import device as storage_device
from apps.management import backup_types from apps.management import backup_types
@ -32,13 +33,13 @@ async def load_device(ctx, msg):
backup_type = BackupType.Slip39_Advanced backup_type = BackupType.Slip39_Advanced
else: else:
raise RuntimeError("Invalid group count") raise RuntimeError("Invalid group count")
storage.device.set_slip39_identifier(identifier) storage_device.set_slip39_identifier(identifier)
storage.device.set_slip39_iteration_exponent(iteration_exponent) storage_device.set_slip39_iteration_exponent(iteration_exponent)
storage.device.store_mnemonic_secret( storage_device.store_mnemonic_secret(
secret, backup_type, needs_backup=True, no_backup=False secret, backup_type, needs_backup=True, no_backup=False
) )
storage.device.load_settings( storage_device.load_settings(
use_passphrase=msg.passphrase_protection, label=msg.label use_passphrase=msg.passphrase_protection, label=msg.label
) )
if msg.pin: if msg.pin:

@ -11,6 +11,7 @@ from apps.common.request_pin import (
request_pin_confirm, request_pin_confirm,
show_pin_invalid, show_pin_invalid,
) )
from apps.common.storage import device as storage_device, recovery as storage_recovery
from apps.management.recovery_device.homescreen import recovery_process from apps.management.recovery_device.homescreen import recovery_process
if False: if False:
@ -43,13 +44,13 @@ async def recovery_device(ctx: wire.Context, msg: RecoveryDevice) -> Success:
config.change_pin(pin_to_int(""), pin_to_int(newpin), None, None) config.change_pin(pin_to_int(""), pin_to_int(newpin), None, None)
if msg.u2f_counter: if msg.u2f_counter:
storage.device.set_u2f_counter(msg.u2f_counter) storage_device.set_u2f_counter(msg.u2f_counter)
storage.device.load_settings( storage_device.load_settings(
label=msg.label, use_passphrase=msg.passphrase_protection label=msg.label, use_passphrase=msg.passphrase_protection
) )
storage.recovery.set_in_progress(True) storage_recovery.set_in_progress(True)
if msg.dry_run: if msg.dry_run:
storage.recovery.set_dry_run(msg.dry_run) storage_recovery.set_dry_run(msg.dry_run)
result = await recovery_process(ctx) result = await recovery_process(ctx)
@ -62,7 +63,7 @@ def _check_state(msg: RecoveryDevice) -> None:
if msg.dry_run and not storage.is_initialized(): if msg.dry_run and not storage.is_initialized():
raise wire.NotInitialized("Device is not initialized") raise wire.NotInitialized("Device is not initialized")
if storage.recovery.is_in_progress(): if storage_recovery.is_in_progress():
raise RuntimeError( raise RuntimeError(
"Function recovery_device should not be invoked when recovery is already in progress" "Function recovery_device should not be invoked when recovery is already in progress"
) )
@ -73,7 +74,7 @@ def _check_state(msg: RecoveryDevice) -> None:
) )
async def _continue_dialog(ctx: wire.Context, msg: RecoveryDevice): async def _continue_dialog(ctx: wire.Context, msg: RecoveryDevice) -> None:
if not msg.dry_run: if not msg.dry_run:
text = Text("Recovery mode", ui.ICON_RECOVERY, new_lines=False) text = Text("Recovery mode", ui.ICON_RECOVERY, new_lines=False)
text.bold("Do you really want to") text.bold("Do you really want to")

@ -9,17 +9,22 @@ from . import recover
from apps.common import mnemonic, storage from apps.common import mnemonic, storage
from apps.common.layout import show_success from apps.common.layout import show_success
from apps.common.storage import (
device as storage_device,
recovery as storage_recovery,
recovery_shares as storage_recovery_shares,
)
from apps.management import backup_types from apps.management import backup_types
from apps.management.recovery_device import layout from apps.management.recovery_device import layout
if False: if False:
from typing import Optional, Tuple from typing import Optional, Tuple, cast
from trezor.messages.ResetDevice import EnumTypeBackupType from trezor.messages.ResetDevice import EnumTypeBackupType
async def recovery_homescreen() -> None: async def recovery_homescreen() -> None:
# recovery process does not communicate on the wire # recovery process does not communicate on the wire
ctx = wire.DummyContext() ctx = cast(wire.Context, wire.DummyContext()) # TODO
try: try:
await recovery_process(ctx) await recovery_process(ctx)
finally: finally:
@ -33,9 +38,9 @@ async def recovery_process(ctx: wire.Context) -> Success:
try: try:
result = await _continue_recovery_process(ctx) result = await _continue_recovery_process(ctx)
except recover.RecoveryAborted: except recover.RecoveryAborted:
dry_run = storage.recovery.is_dry_run() dry_run = storage_recovery.is_dry_run()
if dry_run: if dry_run:
storage.recovery.end_progress() storage_recovery.end_progress()
else: else:
storage.wipe() storage.wipe()
raise wire.ActionCancelled("Cancelled") raise wire.ActionCancelled("Cancelled")
@ -44,7 +49,7 @@ async def recovery_process(ctx: wire.Context) -> Success:
async def _continue_recovery_process(ctx: wire.Context) -> Success: async def _continue_recovery_process(ctx: wire.Context) -> Success:
# gather the current recovery state from storage # gather the current recovery state from storage
dry_run = storage.recovery.is_dry_run() dry_run = storage_recovery.is_dry_run()
word_count, backup_type = recover.load_slip39_state() word_count, backup_type = recover.load_slip39_state()
# Both word_count and backup_type are derived from the same data. Both will be # Both word_count and backup_type are derived from the same data. Both will be
@ -54,6 +59,7 @@ async def _continue_recovery_process(ctx: wire.Context) -> Success:
is_first_step = backup_type is None is_first_step = backup_type is None
if not is_first_step: if not is_first_step:
assert word_count is not None
# If we continue recovery, show starting screen with word count immediately. # If we continue recovery, show starting screen with word count immediately.
await _request_share_first_screen(ctx, word_count) await _request_share_first_screen(ctx, word_count)
@ -64,6 +70,7 @@ async def _continue_recovery_process(ctx: wire.Context) -> Success:
word_count = await _request_word_count(ctx, dry_run) word_count = await _request_word_count(ctx, dry_run)
# ...and only then show the starting screen with word count. # ...and only then show the starting screen with word count.
await _request_share_first_screen(ctx, word_count) await _request_share_first_screen(ctx, word_count)
assert word_count is not None
# ask for mnemonic words one by one # ask for mnemonic words one by one
words = await layout.request_mnemonic(ctx, word_count, backup_type) words = await layout.request_mnemonic(ctx, word_count, backup_type)
@ -81,6 +88,7 @@ async def _continue_recovery_process(ctx: wire.Context) -> Success:
except MnemonicError: except MnemonicError:
await layout.show_invalid_mnemonic(ctx, word_count) await layout.show_invalid_mnemonic(ctx, word_count)
assert backup_type is not None
if dry_run: if dry_run:
result = await _finish_recovery_dry_run(ctx, secret, backup_type) result = await _finish_recovery_dry_run(ctx, secret, backup_type)
else: else:
@ -104,17 +112,17 @@ async def _finish_recovery_dry_run(
# Check that the identifier and iteration exponent match as well # Check that the identifier and iteration exponent match as well
if is_slip39: if is_slip39:
result &= ( result &= (
storage.device.get_slip39_identifier() storage_device.get_slip39_identifier()
== storage.recovery.get_slip39_identifier() == storage_recovery.get_slip39_identifier()
) )
result &= ( result &= (
storage.device.get_slip39_iteration_exponent() storage_device.get_slip39_iteration_exponent()
== storage.recovery.get_slip39_iteration_exponent() == storage_recovery.get_slip39_iteration_exponent()
) )
await layout.show_dry_run_result(ctx, result, is_slip39) await layout.show_dry_run_result(ctx, result, is_slip39)
storage.recovery.end_progress() storage_recovery.end_progress()
if result: if result:
return Success("The seed is valid and matches the one in the device") return Success("The seed is valid and matches the one in the device")
@ -128,21 +136,21 @@ async def _finish_recovery(
if backup_type is None: if backup_type is None:
raise RuntimeError raise RuntimeError
storage.device.store_mnemonic_secret( storage_device.store_mnemonic_secret(
secret, backup_type, needs_backup=False, no_backup=False secret, backup_type, needs_backup=False, no_backup=False
) )
if backup_type in (BackupType.Slip39_Basic, BackupType.Slip39_Advanced): if backup_type in (BackupType.Slip39_Basic, BackupType.Slip39_Advanced):
identifier = storage.recovery.get_slip39_identifier() identifier = storage_recovery.get_slip39_identifier()
exponent = storage.recovery.get_slip39_iteration_exponent() exponent = storage_recovery.get_slip39_iteration_exponent()
if identifier is None or exponent is None: if identifier is None or exponent is None:
# Identifier and exponent need to be stored in storage at this point # Identifier and exponent need to be stored in storage at this point
raise RuntimeError raise RuntimeError
storage.device.set_slip39_identifier(identifier) storage_device.set_slip39_identifier(identifier)
storage.device.set_slip39_iteration_exponent(exponent) storage_device.set_slip39_iteration_exponent(exponent)
await show_success(ctx, ("You have successfully", "recovered your wallet.")) await show_success(ctx, ("You have successfully", "recovered your wallet."))
storage.recovery.end_progress() storage_recovery.end_progress()
return Success(message="Device recovered") return Success(message="Device recovered")
@ -162,12 +170,13 @@ async def _process_words(
share = None share = None
if not is_slip39: # BIP-39 if not is_slip39: # BIP-39
secret = recover.process_bip39(words) secret = recover.process_bip39(words) # type: Optional[bytes]
else: else:
secret, share = recover.process_slip39(words) secret, share = recover.process_slip39(words)
backup_type = backup_types.infer_backup_type(is_slip39, share) backup_type = backup_types.infer_backup_type(is_slip39, share)
if secret is None: if secret is None: # SLIP-39
assert share is not None
if share.group_count and share.group_count > 1: if share.group_count and share.group_count > 1:
await layout.show_group_share_success(ctx, share.index, share.group_index) await layout.show_group_share_success(ctx, share.index, share.group_index)
await _request_share_next_screen(ctx) await _request_share_next_screen(ctx)
@ -177,7 +186,7 @@ async def _process_words(
async def _request_share_first_screen(ctx: wire.Context, word_count: int) -> None: async def _request_share_first_screen(ctx: wire.Context, word_count: int) -> None:
if backup_types.is_slip39_word_count(word_count): if backup_types.is_slip39_word_count(word_count):
remaining = storage.recovery.fetch_slip39_remaining_shares() remaining = storage_recovery.fetch_slip39_remaining_shares()
if remaining: if remaining:
await _request_share_next_screen(ctx) await _request_share_next_screen(ctx)
else: else:
@ -193,8 +202,8 @@ async def _request_share_first_screen(ctx: wire.Context, word_count: int) -> Non
async def _request_share_next_screen(ctx: wire.Context) -> None: async def _request_share_next_screen(ctx: wire.Context) -> None:
remaining = storage.recovery.fetch_slip39_remaining_shares() remaining = storage_recovery.fetch_slip39_remaining_shares()
group_count = storage.recovery.get_slip39_group_count() group_count = storage_recovery.get_slip39_group_count()
if not remaining: if not remaining:
# 'remaining' should be stored at this point # 'remaining' should be stored at this point
raise RuntimeError raise RuntimeError
@ -217,7 +226,9 @@ async def _show_remaining_groups_and_shares(ctx: wire.Context) -> None:
""" """
Show info dialog for Slip39 Advanced - what shares are to be entered. Show info dialog for Slip39 Advanced - what shares are to be entered.
""" """
shares_remaining = storage.recovery.fetch_slip39_remaining_shares() shares_remaining = storage_recovery.fetch_slip39_remaining_shares()
# should be stored at this point
assert shares_remaining
groups = set() groups = set()
first_entered_index = -1 first_entered_index = -1
@ -228,17 +239,18 @@ async def _show_remaining_groups_and_shares(ctx: wire.Context) -> None:
share = None share = None
for index, remaining in enumerate(shares_remaining): for index, remaining in enumerate(shares_remaining):
if 0 <= remaining < slip39.MAX_SHARE_COUNT: if 0 <= remaining < slip39.MAX_SHARE_COUNT:
m = storage.recovery_shares.fetch_group(index)[0] m = storage_recovery_shares.fetch_group(index)[0]
if not share: if not share:
share = slip39.decode_mnemonic(m) share = slip39.decode_mnemonic(m)
identifier = m.split(" ")[0:3] identifier = m.split(" ")[0:3]
groups.add((remaining, tuple(identifier))) groups.add((remaining, tuple(identifier)))
elif remaining == slip39.MAX_SHARE_COUNT: # no shares yet elif remaining == slip39.MAX_SHARE_COUNT: # no shares yet
identifier = storage.recovery_shares.fetch_group(first_entered_index)[ identifier = storage_recovery_shares.fetch_group(first_entered_index)[
0 0
].split(" ")[0:2] ].split(" ")[0:2]
groups.add((remaining, tuple(identifier))) groups.add((remaining, tuple(identifier)))
assert share # share needs to be set
return await layout.show_remaining_shares( return await layout.show_remaining_shares(
ctx, groups, shares_remaining, share.group_threshold ctx, groups, shares_remaining, share.group_threshold
) )

@ -11,9 +11,9 @@ from .keyboard_bip39 import Bip39Keyboard
from .keyboard_slip39 import Slip39Keyboard from .keyboard_slip39 import Slip39Keyboard
from .recover import RecoveryAborted from .recover import RecoveryAborted
from apps.common import storage
from apps.common.confirm import confirm, info_confirm, require_confirm from apps.common.confirm import confirm, info_confirm, require_confirm
from apps.common.layout import show_success, show_warning from apps.common.layout import show_success, show_warning
from apps.common.storage import recovery as storage_recovery
from apps.management import backup_types from apps.management import backup_types
from apps.management.recovery_device import recover from apps.management.recovery_device import recover
@ -21,7 +21,7 @@ if __debug__:
from apps.debug import input_signal from apps.debug import input_signal
if False: if False:
from typing import List, Optional, Callable, Iterable, Tuple from typing import List, Optional, Callable, Iterable, Tuple, Union
from trezor.messages.ResetDevice import EnumTypeBackupType from trezor.messages.ResetDevice import EnumTypeBackupType
@ -51,7 +51,7 @@ async def request_word_count(ctx: wire.Context, dry_run: bool) -> int:
else: else:
count = await ctx.wait(WordSelector(text)) count = await ctx.wait(WordSelector(text))
return count return count # type: ignore
async def request_mnemonic( async def request_mnemonic(
@ -59,10 +59,12 @@ async def request_mnemonic(
) -> Optional[str]: ) -> Optional[str]:
await ctx.call(ButtonRequest(code=ButtonRequestType.MnemonicInput), ButtonAck) await ctx.call(ButtonRequest(code=ButtonRequestType.MnemonicInput), ButtonAck)
words = [] words = [] # type: List[str]
for i in range(word_count): for i in range(word_count):
if backup_types.is_slip39_word_count(word_count): if backup_types.is_slip39_word_count(word_count):
keyboard = Slip39Keyboard("Type word %s of %s:" % (i + 1, word_count)) keyboard = Slip39Keyboard(
"Type word %s of %s:" % (i + 1, word_count)
) # type: Union[Slip39Keyboard, Bip39Keyboard]
else: else:
keyboard = Bip39Keyboard("Type word %s of %s:" % (i + 1, word_count)) keyboard = Bip39Keyboard("Type word %s of %s:" % (i + 1, word_count))
if __debug__: if __debug__:
@ -125,8 +127,10 @@ async def check_word_validity(
if len(group) > 0: if len(group) > 0:
if current_word == group[0].split(" ")[current_index]: if current_word == group[0].split(" ")[current_index]:
remaining_shares = ( remaining_shares = (
storage.recovery.fetch_slip39_remaining_shares() storage_recovery.fetch_slip39_remaining_shares()
) )
# if backup_type is not None, some share was already entered -> remaining needs to be set
assert remaining_shares is not None
if remaining_shares[i] == 0: if remaining_shares[i] == 0:
await show_group_threshold_reached(ctx) await show_group_threshold_reached(ctx)
return False return False
@ -152,11 +156,11 @@ async def check_word_validity(
async def show_remaining_shares( async def show_remaining_shares(
ctx: wire.Context, ctx: wire.Context,
groups: Iterable[Tuple[int, Tuple[str]]], # remaining + list 3 words groups: Iterable[Tuple[int, Tuple[str, ...]]], # remaining + list 3 words
shares_remaining: List[int], shares_remaining: List[int],
group_threshold: int, group_threshold: int,
) -> None: ) -> None:
pages = [] pages = [] # type: List[ui.Component]
for remaining, group in groups: for remaining, group in groups:
if 0 < remaining < MAX_SHARE_COUNT: if 0 < remaining < MAX_SHARE_COUNT:
text = Text("Remaining Shares") text = Text("Remaining Shares")
@ -179,8 +183,7 @@ async def show_remaining_shares(
for word in group: for word in group:
text.normal(word) text.normal(word)
pages.append(text) pages.append(text)
await confirm(ctx, Paginated(pages), cancel=None)
return await confirm(ctx, Paginated(pages), cancel=None)
async def show_group_share_success( async def show_group_share_success(
@ -192,7 +195,7 @@ async def show_group_share_success(
text.normal("from") text.normal("from")
text.bold("Group %s" % (group_index + 1)) text.bold("Group %s" % (group_index + 1))
return await confirm(ctx, text, confirm="Continue", cancel=None) await confirm(ctx, text, confirm="Continue", cancel=None)
async def show_dry_run_result(ctx: wire.Context, result: bool, is_slip39: bool) -> None: async def show_dry_run_result(ctx: wire.Context, result: bool, is_slip39: bool) -> None:
@ -275,7 +278,7 @@ class RecoveryHomescreen(ui.Component):
def __init__(self, text: str, subtext: str = None): def __init__(self, text: str, subtext: str = None):
self.text = text self.text = text
self.subtext = subtext self.subtext = subtext
self.dry_run = storage.recovery.is_dry_run() self.dry_run = storage_recovery.is_dry_run()
self.repaint = True self.repaint = True
def on_render(self) -> None: def on_render(self) -> None:
@ -335,6 +338,6 @@ async def homescreen_dialog(
# go forward in the recovery process # go forward in the recovery process
break break
# user has chosen to abort, confirm the choice # user has chosen to abort, confirm the choice
dry_run = storage.recovery.is_dry_run() dry_run = storage_recovery.is_dry_run()
if await confirm_abort(ctx, dry_run): if await confirm_abort(ctx, dry_run):
raise RecoveryAborted raise RecoveryAborted

@ -1,12 +1,15 @@
from trezor.crypto import bip39, slip39 from trezor.crypto import bip39, slip39
from trezor.errors import MnemonicError from trezor.errors import MnemonicError
from apps.common import storage from apps.common.storage import (
recovery as storage_recovery,
recovery_shares as storage_recovery_shares,
)
from apps.management import backup_types from apps.management import backup_types
if False: if False:
from trezor.messages.ResetDevice import EnumTypeBackupType from trezor.messages.ResetDevice import EnumTypeBackupType
from typing import Optional, Tuple, List from typing import Optional, Tuple, List, Union
class RecoveryAborted(Exception): class RecoveryAborted(Exception):
@ -30,17 +33,17 @@ def process_slip39(words: str) -> Tuple[Optional[bytes], slip39.Share]:
""" """
share = slip39.decode_mnemonic(words) share = slip39.decode_mnemonic(words)
remaining = storage.recovery.fetch_slip39_remaining_shares() remaining = storage_recovery.fetch_slip39_remaining_shares()
# if this is the first share, parse and store metadata # if this is the first share, parse and store metadata
if not remaining: if not remaining:
storage.recovery.set_slip39_group_count(share.group_count) storage_recovery.set_slip39_group_count(share.group_count)
storage.recovery.set_slip39_iteration_exponent(share.iteration_exponent) storage_recovery.set_slip39_iteration_exponent(share.iteration_exponent)
storage.recovery.set_slip39_identifier(share.identifier) storage_recovery.set_slip39_identifier(share.identifier)
storage.recovery.set_slip39_remaining_shares( storage_recovery.set_slip39_remaining_shares(
share.threshold - 1, share.group_index share.threshold - 1, share.group_index
) )
storage.recovery_shares.set(share.index, share.group_index, words) storage_recovery_shares.set(share.index, share.group_index, words)
# if share threshold and group threshold are 1 # if share threshold and group threshold are 1
# we can calculate the secret right away # we can calculate the secret right away
@ -54,24 +57,24 @@ def process_slip39(words: str) -> Tuple[Optional[bytes], slip39.Share]:
return None, share return None, share
# These should be checked by UI before so it's a Runtime exception otherwise # These should be checked by UI before so it's a Runtime exception otherwise
if share.identifier != storage.recovery.get_slip39_identifier(): if share.identifier != storage_recovery.get_slip39_identifier():
raise RuntimeError("Slip39: Share identifiers do not match") raise RuntimeError("Slip39: Share identifiers do not match")
if share.iteration_exponent != storage.recovery.get_slip39_iteration_exponent(): if share.iteration_exponent != storage_recovery.get_slip39_iteration_exponent():
raise RuntimeError("Slip39: Share exponents do not match") raise RuntimeError("Slip39: Share exponents do not match")
if storage.recovery_shares.get(share.index, share.group_index): if storage_recovery_shares.get(share.index, share.group_index):
raise RuntimeError("Slip39: This mnemonic was already entered") raise RuntimeError("Slip39: This mnemonic was already entered")
if share.group_count != storage.recovery.get_slip39_group_count(): if share.group_count != storage_recovery.get_slip39_group_count():
raise RuntimeError("Slip39: Group count does not match") raise RuntimeError("Slip39: Group count does not match")
remaining_for_share = ( remaining_for_share = (
storage.recovery.get_slip39_remaining_shares(share.group_index) storage_recovery.get_slip39_remaining_shares(share.group_index)
or share.threshold or share.threshold
) )
storage.recovery.set_slip39_remaining_shares( storage_recovery.set_slip39_remaining_shares(
remaining_for_share - 1, share.group_index remaining_for_share - 1, share.group_index
) )
remaining[share.group_index] = remaining_for_share - 1 remaining[share.group_index] = remaining_for_share - 1
storage.recovery_shares.set(share.index, share.group_index, words) storage_recovery_shares.set(share.index, share.group_index, words)
if remaining.count(0) < share.group_threshold: if remaining.count(0) < share.group_threshold:
# we need more shares # we need more shares
@ -82,17 +85,21 @@ def process_slip39(words: str) -> Tuple[Optional[bytes], slip39.Share]:
for i, r in enumerate(remaining): for i, r in enumerate(remaining):
# if we have multiple groups pass only the ones with threshold reached # if we have multiple groups pass only the ones with threshold reached
if r == 0: if r == 0:
group = storage.recovery_shares.fetch_group(i) group = storage_recovery_shares.fetch_group(i)
mnemonics.extend(group) mnemonics.extend(group)
else: else:
# in case of slip39 basic we only need the first and only group # in case of slip39 basic we only need the first and only group
mnemonics = storage.recovery_shares.fetch_group(0) mnemonics = storage_recovery_shares.fetch_group(0)
identifier, iteration_exponent, secret, _ = slip39.combine_mnemonics(mnemonics) identifier, iteration_exponent, secret, _ = slip39.combine_mnemonics(mnemonics)
return secret, share return secret, share
def load_slip39_state() -> Tuple[Optional[int], Optional[EnumTypeBackupType]]: if False:
Slip39State = Union[Tuple[int, EnumTypeBackupType], Tuple[None, None]]
def load_slip39_state() -> Slip39State:
previous_mnemonics = fetch_previous_mnemonics() previous_mnemonics = fetch_previous_mnemonics()
if not previous_mnemonics: if not previous_mnemonics:
return None, None return None, None
@ -105,10 +112,10 @@ def load_slip39_state() -> Tuple[Optional[int], Optional[EnumTypeBackupType]]:
def fetch_previous_mnemonics() -> Optional[List[List[str]]]: def fetch_previous_mnemonics() -> Optional[List[List[str]]]:
mnemonics = [] mnemonics = []
if not storage.recovery.get_slip39_group_count(): if not storage_recovery.get_slip39_group_count():
return None return None
for i in range(storage.recovery.get_slip39_group_count()): for i in range(storage_recovery.get_slip39_group_count()):
mnemonics.append(storage.recovery_shares.fetch_group(i)) mnemonics.append(storage_recovery_shares.fetch_group(i))
if not any(p for p in mnemonics): if not any(p for p in mnemonics):
return None return None
return mnemonics return mnemonics

@ -7,6 +7,7 @@ from trezor.messages.Success import Success
from trezor.pin import pin_to_int from trezor.pin import pin_to_int
from apps.common import storage from apps.common import storage
from apps.common.storage import device as storage_device
from apps.management import backup_types from apps.management import backup_types
from apps.management.change_pin import request_pin_confirm from apps.management.change_pin import request_pin_confirm
from apps.management.reset_device import layout from apps.management.reset_device import layout
@ -52,8 +53,8 @@ async def reset_device(ctx: wire.Context, msg: ResetDevice) -> Success:
secret = bip39.from_data(secret).encode() secret = bip39.from_data(secret).encode()
elif msg.backup_type in (BackupType.Slip39_Basic, BackupType.Slip39_Advanced): elif msg.backup_type in (BackupType.Slip39_Basic, BackupType.Slip39_Advanced):
# generate and set SLIP39 parameters # generate and set SLIP39 parameters
storage.device.set_slip39_identifier(slip39.generate_random_identifier()) storage_device.set_slip39_identifier(slip39.generate_random_identifier())
storage.device.set_slip39_iteration_exponent(slip39.DEFAULT_ITERATION_EXPONENT) storage_device.set_slip39_iteration_exponent(slip39.DEFAULT_ITERATION_EXPONENT)
else: else:
# Unknown backup type. # Unknown backup type.
raise RuntimeError raise RuntimeError
@ -71,10 +72,10 @@ async def reset_device(ctx: wire.Context, msg: ResetDevice) -> Success:
await backup_seed(ctx, msg.backup_type, secret) await backup_seed(ctx, msg.backup_type, secret)
# write settings and master secret into storage # write settings and master secret into storage
storage.device.load_settings( storage_device.load_settings(
label=msg.label, use_passphrase=msg.passphrase_protection label=msg.label, use_passphrase=msg.passphrase_protection
) )
storage.device.store_mnemonic_secret( storage_device.store_mnemonic_secret(
secret, # for SLIP-39, this is the EMS secret, # for SLIP-39, this is the EMS
msg.backup_type, msg.backup_type,
needs_backup=not perform_backup, needs_backup=not perform_backup,
@ -102,10 +103,10 @@ async def backup_slip39_basic(
# generate the mnemonics # generate the mnemonics
mnemonics = slip39.generate_mnemonics_from_data( mnemonics = slip39.generate_mnemonics_from_data(
encrypted_master_secret, encrypted_master_secret,
storage.device.get_slip39_identifier(), storage_device.get_slip39_identifier(),
1, # Single Group threshold 1, # Single Group threshold
[(threshold, shares_count)], # Single Group threshold/count [(threshold, shares_count)], # Single Group threshold/count
storage.device.get_slip39_iteration_exponent(), storage_device.get_slip39_iteration_exponent(),
)[0] )[0]
# show and confirm individual shares # show and confirm individual shares
@ -137,10 +138,10 @@ async def backup_slip39_advanced(
# generate the mnemonics # generate the mnemonics
mnemonics = slip39.generate_mnemonics_from_data( mnemonics = slip39.generate_mnemonics_from_data(
encrypted_master_secret=encrypted_master_secret, encrypted_master_secret=encrypted_master_secret,
identifier=storage.device.get_slip39_identifier(), identifier=storage_device.get_slip39_identifier(),
group_threshold=group_threshold, group_threshold=group_threshold,
groups=groups, groups=groups,
iteration_exponent=storage.device.get_slip39_iteration_exponent(), iteration_exponent=storage_device.get_slip39_iteration_exponent(),
) )
# show and confirm individual shares # show and confirm individual shares

@ -3,8 +3,8 @@ from trezor.messages import ButtonRequestType
from trezor.messages.Success import Success from trezor.messages.Success import Success
from trezor.ui.text import Text from trezor.ui.text import Text
from apps.common import storage
from apps.common.confirm import require_confirm from apps.common.confirm import require_confirm
from apps.common.storage import device as storage_device
async def set_u2f_counter(ctx, msg): async def set_u2f_counter(ctx, msg):
@ -16,6 +16,6 @@ async def set_u2f_counter(ctx, msg):
text.bold("to %d?" % msg.u2f_counter) text.bold("to %d?" % msg.u2f_counter)
await require_confirm(ctx, text, code=ButtonRequestType.ProtectCall) await require_confirm(ctx, text, code=ButtonRequestType.ProtectCall)
storage.device.set_u2f_counter(msg.u2f_counter) storage_device.set_u2f_counter(msg.u2f_counter)
return Success(message="U2F counter set") return Success(message="U2F counter set")

@ -22,7 +22,7 @@ def boot() -> None:
wire.add(MessageType.DebugMoneroDiagRequest, __name__, "diag") wire.add(MessageType.DebugMoneroDiagRequest, __name__, "diag")
def live_refresh_token(token=None): def live_refresh_token(token: bytes = None) -> None:
global _LIVE_REFRESH_TOKEN global _LIVE_REFRESH_TOKEN
if token is None: if token is None:
return _LIVE_REFRESH_TOKEN return _LIVE_REFRESH_TOKEN

@ -5,7 +5,8 @@ from ubinascii import hexlify
from trezor import log, utils from trezor import log, utils
from trezor.crypto import bip32, chacha20poly1305, hashlib, hmac, random from trezor.crypto import bip32, chacha20poly1305, hashlib, hmac, random
from apps.common import HARDENED, cbor, seed, storage from apps.common import HARDENED, cbor, seed
from apps.common.storage import device as storage_device
if False: if False:
from typing import Optional from typing import Optional
@ -50,7 +51,7 @@ class Credential:
return None return None
def next_signature_counter(self) -> int: def next_signature_counter(self) -> int:
return storage.device.next_u2f_counter() or 0 return storage_device.next_u2f_counter() or 0
@staticmethod @staticmethod
def from_bytes(data: bytes, rp_id_hash: bytes) -> Optional["Credential"]: def from_bytes(data: bytes, rp_id_hash: bytes) -> Optional["Credential"]:
@ -82,7 +83,7 @@ class Fido2Credential(Credential):
return True return True
def generate_id(self) -> None: def generate_id(self) -> None:
self.creation_time = storage.device.next_u2f_counter() or 0 self.creation_time = storage_device.next_u2f_counter() or 0
data = cbor.encode( data = cbor.encode(
{ {

@ -4,15 +4,15 @@ from trezor.pin import pin_to_int, show_pin_timeout
from apps.common import storage from apps.common import storage
from apps.common.request_pin import PinCancelled, request_pin from apps.common.request_pin import PinCancelled, request_pin
from apps.common.sd_salt import SdProtectCancelled, request_sd_salt from apps.common.sd_salt import SdProtectCancelled, request_sd_salt
from apps.common.storage import device from apps.common.storage import device as storage_device
if False: if False:
from typing import Optional from typing import Optional
async def bootscreen() -> None: async def bootscreen() -> None:
ui.display.orientation(storage.device.get_rotation()) ui.display.orientation(storage_device.get_rotation())
salt_auth_key = device.get_sd_salt_auth_key() salt_auth_key = storage_device.get_sd_salt_auth_key()
while True: while True:
try: try:
@ -47,8 +47,8 @@ async def bootscreen() -> None:
async def lockscreen() -> None: async def lockscreen() -> None:
label = storage.device.get_label() label = storage_device.get_label()
image = storage.device.get_homescreen() image = storage_device.get_homescreen()
if not label: if not label:
label = "My Trezor" label = "My Trezor"
if not image: if not image:

@ -60,8 +60,15 @@ def critical(name: str, msg: str, *args: Any) -> None:
def exception(name: str, exc: BaseException) -> None: def exception(name: str, exc: BaseException) -> None:
# we are using `__class__.__name__` to avoid importing ui module # we are using `__class__.__name__` to avoid importing ui module
# we also need to instruct mypy to ignore the missing argument
# in ui.Result exception
if exc.__class__.__name__ == "Result": if exc.__class__.__name__ == "Result":
_log(name, DEBUG, "ui.Result: %s", exc.value) _log(
name,
DEBUG,
"ui.Result: %s",
exc.value, # type: ignore[attr-defined] # noqa: F821
)
elif exc.__class__.__name__ == "Cancelled": elif exc.__class__.__name__ == "Cancelled":
_log(name, DEBUG, "ui.Cancelled") _log(name, DEBUG, "ui.Cancelled")
else: else:

@ -375,15 +375,15 @@ class chan:
self.ch = ch self.ch = ch
self.task = None # type: Optional[Task] self.task = None # type: Optional[Task]
def handle(self, task) -> None: def handle(self, task: Task) -> None:
self.task = task self.task = task
self.ch._schedule_take(task) self.ch._schedule_take(task)
def __init__(self): def __init__(self) -> None:
self.putters = [] # type: List[Tuple[Optional[Task], Any]] self.putters = [] # type: List[Tuple[Optional[Task], Any]]
self.takers = [] # type: List[Task] self.takers = [] # type: List[Task]
def put(self, value: Any) -> None: def put(self, value: Any) -> Awaitable[None]: # type: ignore
put = chan.Put(self, value) put = chan.Put(self, value)
try: try:
return (yield put) return (yield put)
@ -393,7 +393,7 @@ class chan:
self.putters.remove(entry) self.putters.remove(entry)
raise raise
def take(self) -> None: def take(self) -> Awaitable[Any]: # type: ignore
take = chan.Take(self) take = chan.Take(self)
try: try:
return (yield take) return (yield take)
@ -409,7 +409,7 @@ class chan:
else: else:
self.putters.append((None, value)) self.putters.append((None, value))
def _schedule_put(self, putter: Task, value: Any) -> None: def _schedule_put(self, putter: Task, value: Any) -> bool:
if self.takers: if self.takers:
taker = self.takers.pop(0) taker = self.takers.pop(0)
schedule(taker, value) schedule(taker, value)

@ -4,10 +4,10 @@ import protobuf as p
if __debug__: if __debug__:
try: try:
from typing import Dict, List, Optional from typing import Dict, List # noqa: F401
from typing_extensions import Literal # noqa: F401 from typing_extensions import Literal # noqa: F401
except ImportError: except ImportError:
Dict, List, Optional = None, None, None # type: ignore pass
class Address(p.MessageType): class Address(p.MessageType):

@ -4,10 +4,10 @@ import protobuf as p
if __debug__: if __debug__:
try: try:
from typing import Dict, List, Optional from typing import Dict, List # noqa: F401
from typing_extensions import Literal # noqa: F401 from typing_extensions import Literal # noqa: F401
except ImportError: except ImportError:
Dict, List, Optional = None, None, None # type: ignore pass
class ApplyFlags(p.MessageType): class ApplyFlags(p.MessageType):

@ -4,12 +4,11 @@ import protobuf as p
if __debug__: if __debug__:
try: try:
from typing import Dict, List, Optional from typing import Dict, List # noqa: F401
from typing_extensions import Literal # noqa: F401 from typing_extensions import Literal # noqa: F401
EnumTypePassphraseSourceType = Literal[0, 1, 2] EnumTypePassphraseSourceType = Literal[0, 1, 2]
except ImportError: except ImportError:
Dict, List, Optional = None, None, None # type: ignore pass
EnumTypePassphraseSourceType = None # type: ignore
class ApplySettings(p.MessageType): class ApplySettings(p.MessageType):

@ -4,10 +4,10 @@ import protobuf as p
if __debug__: if __debug__:
try: try:
from typing import Dict, List, Optional from typing import Dict, List # noqa: F401
from typing_extensions import Literal # noqa: F401 from typing_extensions import Literal # noqa: F401
except ImportError: except ImportError:
Dict, List, Optional = None, None, None # type: ignore pass
class BackupDevice(p.MessageType): class BackupDevice(p.MessageType):

@ -1,5 +1,8 @@
# Automatically generated by pb2py # Automatically generated by pb2py
# fmt: off # fmt: off
Bip39 = 0 if False:
Slip39_Basic = 1 from typing_extensions import Literal
Slip39_Advanced = 2
Bip39 = 0 # type: Literal[0]
Slip39_Basic = 1 # type: Literal[1]
Slip39_Advanced = 2 # type: Literal[2]

@ -4,10 +4,10 @@ import protobuf as p
if __debug__: if __debug__:
try: try:
from typing import Dict, List, Optional from typing import Dict, List # noqa: F401
from typing_extensions import Literal # noqa: F401 from typing_extensions import Literal # noqa: F401
except ImportError: except ImportError:
Dict, List, Optional = None, None, None # type: ignore pass
class BinanceAddress(p.MessageType): class BinanceAddress(p.MessageType):

@ -4,10 +4,10 @@ import protobuf as p
if __debug__: if __debug__:
try: try:
from typing import Dict, List, Optional from typing import Dict, List # noqa: F401
from typing_extensions import Literal # noqa: F401 from typing_extensions import Literal # noqa: F401
except ImportError: except ImportError:
Dict, List, Optional = None, None, None # type: ignore pass
class BinanceCancelMsg(p.MessageType): class BinanceCancelMsg(p.MessageType):

@ -4,10 +4,10 @@ import protobuf as p
if __debug__: if __debug__:
try: try:
from typing import Dict, List, Optional from typing import Dict, List # noqa: F401
from typing_extensions import Literal # noqa: F401 from typing_extensions import Literal # noqa: F401
except ImportError: except ImportError:
Dict, List, Optional = None, None, None # type: ignore pass
class BinanceCoin(p.MessageType): class BinanceCoin(p.MessageType):

@ -4,10 +4,10 @@ import protobuf as p
if __debug__: if __debug__:
try: try:
from typing import Dict, List, Optional from typing import Dict, List # noqa: F401
from typing_extensions import Literal # noqa: F401 from typing_extensions import Literal # noqa: F401
except ImportError: except ImportError:
Dict, List, Optional = None, None, None # type: ignore pass
class BinanceGetAddress(p.MessageType): class BinanceGetAddress(p.MessageType):

@ -4,10 +4,10 @@ import protobuf as p
if __debug__: if __debug__:
try: try:
from typing import Dict, List, Optional from typing import Dict, List # noqa: F401
from typing_extensions import Literal # noqa: F401 from typing_extensions import Literal # noqa: F401
except ImportError: except ImportError:
Dict, List, Optional = None, None, None # type: ignore pass
class BinanceGetPublicKey(p.MessageType): class BinanceGetPublicKey(p.MessageType):

@ -6,10 +6,10 @@ from .BinanceCoin import BinanceCoin
if __debug__: if __debug__:
try: try:
from typing import Dict, List, Optional from typing import Dict, List # noqa: F401
from typing_extensions import Literal # noqa: F401 from typing_extensions import Literal # noqa: F401
except ImportError: except ImportError:
Dict, List, Optional = None, None, None # type: ignore pass
class BinanceInputOutput(p.MessageType): class BinanceInputOutput(p.MessageType):

@ -4,16 +4,13 @@ import protobuf as p
if __debug__: if __debug__:
try: try:
from typing import Dict, List, Optional from typing import Dict, List # noqa: F401
from typing_extensions import Literal # noqa: F401 from typing_extensions import Literal # noqa: F401
EnumTypeBinanceOrderType = Literal[0, 1, 2, 3] EnumTypeBinanceOrderType = Literal[0, 1, 2, 3]
EnumTypeBinanceOrderSide = Literal[0, 1, 2] EnumTypeBinanceOrderSide = Literal[0, 1, 2]
EnumTypeBinanceTimeInForce = Literal[0, 1, 2, 3] EnumTypeBinanceTimeInForce = Literal[0, 1, 2, 3]
except ImportError: except ImportError:
Dict, List, Optional = None, None, None # type: ignore pass
EnumTypeBinanceOrderType = None # type: ignore
EnumTypeBinanceOrderSide = None # type: ignore
EnumTypeBinanceTimeInForce = None # type: ignore
class BinanceOrderMsg(p.MessageType): class BinanceOrderMsg(p.MessageType):

@ -1,5 +1,8 @@
# Automatically generated by pb2py # Automatically generated by pb2py
# fmt: off # fmt: off
SIDE_UNKNOWN = 0 if False:
BUY = 1 from typing_extensions import Literal
SELL = 2
SIDE_UNKNOWN = 0 # type: Literal[0]
BUY = 1 # type: Literal[1]
SELL = 2 # type: Literal[2]

@ -1,6 +1,9 @@
# Automatically generated by pb2py # Automatically generated by pb2py
# fmt: off # fmt: off
OT_UNKNOWN = 0 if False:
MARKET = 1 from typing_extensions import Literal
LIMIT = 2
OT_RESERVED = 3 OT_UNKNOWN = 0 # type: Literal[0]
MARKET = 1 # type: Literal[1]
LIMIT = 2 # type: Literal[2]
OT_RESERVED = 3 # type: Literal[3]

@ -4,10 +4,10 @@ import protobuf as p
if __debug__: if __debug__:
try: try:
from typing import Dict, List, Optional from typing import Dict, List # noqa: F401
from typing_extensions import Literal # noqa: F401 from typing_extensions import Literal # noqa: F401
except ImportError: except ImportError:
Dict, List, Optional = None, None, None # type: ignore pass
class BinancePublicKey(p.MessageType): class BinancePublicKey(p.MessageType):

@ -4,10 +4,10 @@ import protobuf as p
if __debug__: if __debug__:
try: try:
from typing import Dict, List, Optional from typing import Dict, List # noqa: F401
from typing_extensions import Literal # noqa: F401 from typing_extensions import Literal # noqa: F401
except ImportError: except ImportError:
Dict, List, Optional = None, None, None # type: ignore pass
class BinanceSignTx(p.MessageType): class BinanceSignTx(p.MessageType):

@ -4,10 +4,10 @@ import protobuf as p
if __debug__: if __debug__:
try: try:
from typing import Dict, List, Optional from typing import Dict, List # noqa: F401
from typing_extensions import Literal # noqa: F401 from typing_extensions import Literal # noqa: F401
except ImportError: except ImportError:
Dict, List, Optional = None, None, None # type: ignore pass
class BinanceSignedTx(p.MessageType): class BinanceSignedTx(p.MessageType):

@ -1,6 +1,9 @@
# Automatically generated by pb2py # Automatically generated by pb2py
# fmt: off # fmt: off
TIF_UNKNOWN = 0 if False:
GTE = 1 from typing_extensions import Literal
TIF_RESERVED = 2
IOC = 3 TIF_UNKNOWN = 0 # type: Literal[0]
GTE = 1 # type: Literal[1]
TIF_RESERVED = 2 # type: Literal[2]
IOC = 3 # type: Literal[3]

@ -6,10 +6,10 @@ from .BinanceInputOutput import BinanceInputOutput
if __debug__: if __debug__:
try: try:
from typing import Dict, List, Optional from typing import Dict, List # noqa: F401
from typing_extensions import Literal # noqa: F401 from typing_extensions import Literal # noqa: F401
except ImportError: except ImportError:
Dict, List, Optional = None, None, None # type: ignore pass
class BinanceTransferMsg(p.MessageType): class BinanceTransferMsg(p.MessageType):

@ -4,10 +4,10 @@ import protobuf as p
if __debug__: if __debug__:
try: try:
from typing import Dict, List, Optional from typing import Dict, List # noqa: F401
from typing_extensions import Literal # noqa: F401 from typing_extensions import Literal # noqa: F401
except ImportError: except ImportError:
Dict, List, Optional = None, None, None # type: ignore pass
class BinanceTxRequest(p.MessageType): class BinanceTxRequest(p.MessageType):

@ -4,10 +4,10 @@ import protobuf as p
if __debug__: if __debug__:
try: try:
from typing import Dict, List, Optional from typing import Dict, List # noqa: F401
from typing_extensions import Literal # noqa: F401 from typing_extensions import Literal # noqa: F401
except ImportError: except ImportError:
Dict, List, Optional = None, None, None # type: ignore pass
class ButtonAck(p.MessageType): class ButtonAck(p.MessageType):

@ -4,12 +4,11 @@ import protobuf as p
if __debug__: if __debug__:
try: try:
from typing import Dict, List, Optional from typing import Dict, List # noqa: F401
from typing_extensions import Literal # noqa: F401 from typing_extensions import Literal # noqa: F401
EnumTypeButtonRequestType = Literal[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18] EnumTypeButtonRequestType = Literal[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18]
except ImportError: except ImportError:
Dict, List, Optional = None, None, None # type: ignore pass
EnumTypeButtonRequestType = None # type: ignore
class ButtonRequest(p.MessageType): class ButtonRequest(p.MessageType):

@ -1,20 +1,23 @@
# Automatically generated by pb2py # Automatically generated by pb2py
# fmt: off # fmt: off
Other = 1 if False:
FeeOverThreshold = 2 from typing_extensions import Literal
ConfirmOutput = 3
ResetDevice = 4 Other = 1 # type: Literal[1]
ConfirmWord = 5 FeeOverThreshold = 2 # type: Literal[2]
WipeDevice = 6 ConfirmOutput = 3 # type: Literal[3]
ProtectCall = 7 ResetDevice = 4 # type: Literal[4]
SignTx = 8 ConfirmWord = 5 # type: Literal[5]
FirmwareCheck = 9 WipeDevice = 6 # type: Literal[6]
Address = 10 ProtectCall = 7 # type: Literal[7]
PublicKey = 11 SignTx = 8 # type: Literal[8]
MnemonicWordCount = 12 FirmwareCheck = 9 # type: Literal[9]
MnemonicInput = 13 Address = 10 # type: Literal[10]
PassphraseType = 14 PublicKey = 11 # type: Literal[11]
UnknownDerivationPath = 15 MnemonicWordCount = 12 # type: Literal[12]
RecoveryHomepage = 16 MnemonicInput = 13 # type: Literal[13]
Success = 17 PassphraseType = 14 # type: Literal[14]
Warning = 18 UnknownDerivationPath = 15 # type: Literal[15]
RecoveryHomepage = 16 # type: Literal[16]
Success = 17 # type: Literal[17]
Warning = 18 # type: Literal[18]

@ -4,10 +4,10 @@ import protobuf as p
if __debug__: if __debug__:
try: try:
from typing import Dict, List, Optional from typing import Dict, List # noqa: F401
from typing_extensions import Literal # noqa: F401 from typing_extensions import Literal # noqa: F401
except ImportError: except ImportError:
Dict, List, Optional = None, None, None # type: ignore pass
class Cancel(p.MessageType): class Cancel(p.MessageType):

@ -2,21 +2,24 @@
# fmt: off # fmt: off
from trezor import utils from trezor import utils
Bitcoin = 1 if False:
from typing_extensions import Literal
Bitcoin = 1 # type: Literal[1]
if not utils.BITCOIN_ONLY: if not utils.BITCOIN_ONLY:
Bitcoin_like = 2 Bitcoin_like = 2 # type: Literal[2]
Binance = 3 Binance = 3 # type: Literal[3]
Cardano = 4 Cardano = 4 # type: Literal[4]
Crypto = 5 Crypto = 5 # type: Literal[5]
if not utils.BITCOIN_ONLY: if not utils.BITCOIN_ONLY:
EOS = 6 EOS = 6 # type: Literal[6]
Ethereum = 7 Ethereum = 7 # type: Literal[7]
Lisk = 8 Lisk = 8 # type: Literal[8]
Monero = 9 Monero = 9 # type: Literal[9]
NEM = 10 NEM = 10 # type: Literal[10]
Ripple = 11 Ripple = 11 # type: Literal[11]
Stellar = 12 Stellar = 12 # type: Literal[12]
Tezos = 13 Tezos = 13 # type: Literal[13]
U2F = 14 U2F = 14 # type: Literal[14]
Shamir = 15 Shamir = 15 # type: Literal[15]
ShamirGroups = 16 ShamirGroups = 16 # type: Literal[16]

@ -4,10 +4,10 @@ import protobuf as p
if __debug__: if __debug__:
try: try:
from typing import Dict, List, Optional from typing import Dict, List # noqa: F401
from typing_extensions import Literal # noqa: F401 from typing_extensions import Literal # noqa: F401
except ImportError: except ImportError:
Dict, List, Optional = None, None, None # type: ignore pass
class CardanoAddress(p.MessageType): class CardanoAddress(p.MessageType):

@ -4,10 +4,10 @@ import protobuf as p
if __debug__: if __debug__:
try: try:
from typing import Dict, List, Optional from typing import Dict, List # noqa: F401
from typing_extensions import Literal # noqa: F401 from typing_extensions import Literal # noqa: F401
except ImportError: except ImportError:
Dict, List, Optional = None, None, None # type: ignore pass
class CardanoGetAddress(p.MessageType): class CardanoGetAddress(p.MessageType):

@ -4,10 +4,10 @@ import protobuf as p
if __debug__: if __debug__:
try: try:
from typing import Dict, List, Optional from typing import Dict, List # noqa: F401
from typing_extensions import Literal # noqa: F401 from typing_extensions import Literal # noqa: F401
except ImportError: except ImportError:
Dict, List, Optional = None, None, None # type: ignore pass
class CardanoGetPublicKey(p.MessageType): class CardanoGetPublicKey(p.MessageType):

@ -6,10 +6,10 @@ from .HDNodeType import HDNodeType
if __debug__: if __debug__:
try: try:
from typing import Dict, List, Optional from typing import Dict, List # noqa: F401
from typing_extensions import Literal # noqa: F401 from typing_extensions import Literal # noqa: F401
except ImportError: except ImportError:
Dict, List, Optional = None, None, None # type: ignore pass
class CardanoPublicKey(p.MessageType): class CardanoPublicKey(p.MessageType):

@ -7,10 +7,10 @@ from .CardanoTxOutputType import CardanoTxOutputType
if __debug__: if __debug__:
try: try:
from typing import Dict, List, Optional from typing import Dict, List # noqa: F401
from typing_extensions import Literal # noqa: F401 from typing_extensions import Literal # noqa: F401
except ImportError: except ImportError:
Dict, List, Optional = None, None, None # type: ignore pass
class CardanoSignTx(p.MessageType): class CardanoSignTx(p.MessageType):

@ -4,10 +4,10 @@ import protobuf as p
if __debug__: if __debug__:
try: try:
from typing import Dict, List, Optional from typing import Dict, List # noqa: F401
from typing_extensions import Literal # noqa: F401 from typing_extensions import Literal # noqa: F401
except ImportError: except ImportError:
Dict, List, Optional = None, None, None # type: ignore pass
class CardanoSignedTx(p.MessageType): class CardanoSignedTx(p.MessageType):

@ -4,10 +4,10 @@ import protobuf as p
if __debug__: if __debug__:
try: try:
from typing import Dict, List, Optional from typing import Dict, List # noqa: F401
from typing_extensions import Literal # noqa: F401 from typing_extensions import Literal # noqa: F401
except ImportError: except ImportError:
Dict, List, Optional = None, None, None # type: ignore pass
class CardanoTxAck(p.MessageType): class CardanoTxAck(p.MessageType):

@ -4,10 +4,10 @@ import protobuf as p
if __debug__: if __debug__:
try: try:
from typing import Dict, List, Optional from typing import Dict, List # noqa: F401
from typing_extensions import Literal # noqa: F401 from typing_extensions import Literal # noqa: F401
except ImportError: except ImportError:
Dict, List, Optional = None, None, None # type: ignore pass
class CardanoTxInputType(p.MessageType): class CardanoTxInputType(p.MessageType):

@ -4,10 +4,10 @@ import protobuf as p
if __debug__: if __debug__:
try: try:
from typing import Dict, List, Optional from typing import Dict, List # noqa: F401
from typing_extensions import Literal # noqa: F401 from typing_extensions import Literal # noqa: F401
except ImportError: except ImportError:
Dict, List, Optional = None, None, None # type: ignore pass
class CardanoTxOutputType(p.MessageType): class CardanoTxOutputType(p.MessageType):

@ -4,10 +4,10 @@ import protobuf as p
if __debug__: if __debug__:
try: try:
from typing import Dict, List, Optional from typing import Dict, List # noqa: F401
from typing_extensions import Literal # noqa: F401 from typing_extensions import Literal # noqa: F401
except ImportError: except ImportError:
Dict, List, Optional = None, None, None # type: ignore pass
class CardanoTxRequest(p.MessageType): class CardanoTxRequest(p.MessageType):

@ -4,10 +4,10 @@ import protobuf as p
if __debug__: if __debug__:
try: try:
from typing import Dict, List, Optional from typing import Dict, List # noqa: F401
from typing_extensions import Literal # noqa: F401 from typing_extensions import Literal # noqa: F401
except ImportError: except ImportError:
Dict, List, Optional = None, None, None # type: ignore pass
class ChangePin(p.MessageType): class ChangePin(p.MessageType):

@ -4,10 +4,10 @@ import protobuf as p
if __debug__: if __debug__:
try: try:
from typing import Dict, List, Optional from typing import Dict, List # noqa: F401
from typing_extensions import Literal # noqa: F401 from typing_extensions import Literal # noqa: F401
except ImportError: except ImportError:
Dict, List, Optional = None, None, None # type: ignore pass
class CipherKeyValue(p.MessageType): class CipherKeyValue(p.MessageType):

@ -4,10 +4,10 @@ import protobuf as p
if __debug__: if __debug__:
try: try:
from typing import Dict, List, Optional from typing import Dict, List # noqa: F401
from typing_extensions import Literal # noqa: F401 from typing_extensions import Literal # noqa: F401
except ImportError: except ImportError:
Dict, List, Optional = None, None, None # type: ignore pass
class CipheredKeyValue(p.MessageType): class CipheredKeyValue(p.MessageType):

@ -4,10 +4,10 @@ import protobuf as p
if __debug__: if __debug__:
try: try:
from typing import Dict, List, Optional from typing import Dict, List # noqa: F401
from typing_extensions import Literal # noqa: F401 from typing_extensions import Literal # noqa: F401
except ImportError: except ImportError:
Dict, List, Optional = None, None, None # type: ignore pass
class ClearSession(p.MessageType): class ClearSession(p.MessageType):

@ -4,12 +4,11 @@ import protobuf as p
if __debug__: if __debug__:
try: try:
from typing import Dict, List, Optional from typing import Dict, List # noqa: F401
from typing_extensions import Literal # noqa: F401 from typing_extensions import Literal # noqa: F401
EnumTypeDebugSwipeDirection = Literal[0, 1, 2, 3] EnumTypeDebugSwipeDirection = Literal[0, 1, 2, 3]
except ImportError: except ImportError:
Dict, List, Optional = None, None, None # type: ignore pass
EnumTypeDebugSwipeDirection = None # type: ignore
class DebugLinkDecision(p.MessageType): class DebugLinkDecision(p.MessageType):

@ -4,10 +4,10 @@ import protobuf as p
if __debug__: if __debug__:
try: try:
from typing import Dict, List, Optional from typing import Dict, List # noqa: F401
from typing_extensions import Literal # noqa: F401 from typing_extensions import Literal # noqa: F401
except ImportError: except ImportError:
Dict, List, Optional = None, None, None # type: ignore pass
class DebugLinkGetState(p.MessageType): class DebugLinkGetState(p.MessageType):

@ -6,10 +6,10 @@ from .HDNodeType import HDNodeType
if __debug__: if __debug__:
try: try:
from typing import Dict, List, Optional from typing import Dict, List # noqa: F401
from typing_extensions import Literal # noqa: F401 from typing_extensions import Literal # noqa: F401
except ImportError: except ImportError:
Dict, List, Optional = None, None, None # type: ignore pass
class DebugLinkState(p.MessageType): class DebugLinkState(p.MessageType):

@ -4,10 +4,10 @@ import protobuf as p
if __debug__: if __debug__:
try: try:
from typing import Dict, List, Optional from typing import Dict, List # noqa: F401
from typing_extensions import Literal # noqa: F401 from typing_extensions import Literal # noqa: F401
except ImportError: except ImportError:
Dict, List, Optional = None, None, None # type: ignore pass
class DebugMoneroDiagAck(p.MessageType): class DebugMoneroDiagAck(p.MessageType):

@ -4,10 +4,10 @@ import protobuf as p
if __debug__: if __debug__:
try: try:
from typing import Dict, List, Optional from typing import Dict, List # noqa: F401
from typing_extensions import Literal # noqa: F401 from typing_extensions import Literal # noqa: F401
except ImportError: except ImportError:
Dict, List, Optional = None, None, None # type: ignore pass
class DebugMoneroDiagRequest(p.MessageType): class DebugMoneroDiagRequest(p.MessageType):

@ -1,6 +1,9 @@
# Automatically generated by pb2py # Automatically generated by pb2py
# fmt: off # fmt: off
UP = 0 if False:
DOWN = 1 from typing_extensions import Literal
LEFT = 2
RIGHT = 3 UP = 0 # type: Literal[0]
DOWN = 1 # type: Literal[1]
LEFT = 2 # type: Literal[2]
RIGHT = 3 # type: Literal[3]

@ -4,10 +4,10 @@ import protobuf as p
if __debug__: if __debug__:
try: try:
from typing import Dict, List, Optional from typing import Dict, List # noqa: F401
from typing_extensions import Literal # noqa: F401 from typing_extensions import Literal # noqa: F401
except ImportError: except ImportError:
Dict, List, Optional = None, None, None # type: ignore pass
class ECDHSessionKey(p.MessageType): class ECDHSessionKey(p.MessageType):

@ -4,10 +4,10 @@ import protobuf as p
if __debug__: if __debug__:
try: try:
from typing import Dict, List, Optional from typing import Dict, List # noqa: F401
from typing_extensions import Literal # noqa: F401 from typing_extensions import Literal # noqa: F401
except ImportError: except ImportError:
Dict, List, Optional = None, None, None # type: ignore pass
class Entropy(p.MessageType): class Entropy(p.MessageType):

@ -4,10 +4,10 @@ import protobuf as p
if __debug__: if __debug__:
try: try:
from typing import Dict, List, Optional from typing import Dict, List # noqa: F401
from typing_extensions import Literal # noqa: F401 from typing_extensions import Literal # noqa: F401
except ImportError: except ImportError:
Dict, List, Optional = None, None, None # type: ignore pass
class EntropyAck(p.MessageType): class EntropyAck(p.MessageType):

@ -4,10 +4,10 @@ import protobuf as p
if __debug__: if __debug__:
try: try:
from typing import Dict, List, Optional from typing import Dict, List # noqa: F401
from typing_extensions import Literal # noqa: F401 from typing_extensions import Literal # noqa: F401
except ImportError: except ImportError:
Dict, List, Optional = None, None, None # type: ignore pass
class EntropyRequest(p.MessageType): class EntropyRequest(p.MessageType):

@ -6,10 +6,10 @@ from .EosAsset import EosAsset
if __debug__: if __debug__:
try: try:
from typing import Dict, List, Optional from typing import Dict, List # noqa: F401
from typing_extensions import Literal # noqa: F401 from typing_extensions import Literal # noqa: F401
except ImportError: except ImportError:
Dict, List, Optional = None, None, None # type: ignore pass
class EosActionBuyRam(p.MessageType): class EosActionBuyRam(p.MessageType):

@ -4,10 +4,10 @@ import protobuf as p
if __debug__: if __debug__:
try: try:
from typing import Dict, List, Optional from typing import Dict, List # noqa: F401
from typing_extensions import Literal # noqa: F401 from typing_extensions import Literal # noqa: F401
except ImportError: except ImportError:
Dict, List, Optional = None, None, None # type: ignore pass
class EosActionBuyRamBytes(p.MessageType): class EosActionBuyRamBytes(p.MessageType):

@ -6,10 +6,10 @@ from .EosPermissionLevel import EosPermissionLevel
if __debug__: if __debug__:
try: try:
from typing import Dict, List, Optional from typing import Dict, List # noqa: F401
from typing_extensions import Literal # noqa: F401 from typing_extensions import Literal # noqa: F401
except ImportError: except ImportError:
Dict, List, Optional = None, None, None # type: ignore pass
class EosActionCommon(p.MessageType): class EosActionCommon(p.MessageType):

@ -6,10 +6,10 @@ from .EosAsset import EosAsset
if __debug__: if __debug__:
try: try:
from typing import Dict, List, Optional from typing import Dict, List # noqa: F401
from typing_extensions import Literal # noqa: F401 from typing_extensions import Literal # noqa: F401
except ImportError: except ImportError:
Dict, List, Optional = None, None, None # type: ignore pass
class EosActionDelegate(p.MessageType): class EosActionDelegate(p.MessageType):

@ -4,10 +4,10 @@ import protobuf as p
if __debug__: if __debug__:
try: try:
from typing import Dict, List, Optional from typing import Dict, List # noqa: F401
from typing_extensions import Literal # noqa: F401 from typing_extensions import Literal # noqa: F401
except ImportError: except ImportError:
Dict, List, Optional = None, None, None # type: ignore pass
class EosActionDeleteAuth(p.MessageType): class EosActionDeleteAuth(p.MessageType):

@ -4,10 +4,10 @@ import protobuf as p
if __debug__: if __debug__:
try: try:
from typing import Dict, List, Optional from typing import Dict, List # noqa: F401
from typing_extensions import Literal # noqa: F401 from typing_extensions import Literal # noqa: F401
except ImportError: except ImportError:
Dict, List, Optional = None, None, None # type: ignore pass
class EosActionLinkAuth(p.MessageType): class EosActionLinkAuth(p.MessageType):

@ -6,10 +6,10 @@ from .EosAuthorization import EosAuthorization
if __debug__: if __debug__:
try: try:
from typing import Dict, List, Optional from typing import Dict, List # noqa: F401
from typing_extensions import Literal # noqa: F401 from typing_extensions import Literal # noqa: F401
except ImportError: except ImportError:
Dict, List, Optional = None, None, None # type: ignore pass
class EosActionNewAccount(p.MessageType): class EosActionNewAccount(p.MessageType):

@ -4,10 +4,10 @@ import protobuf as p
if __debug__: if __debug__:
try: try:
from typing import Dict, List, Optional from typing import Dict, List # noqa: F401
from typing_extensions import Literal # noqa: F401 from typing_extensions import Literal # noqa: F401
except ImportError: except ImportError:
Dict, List, Optional = None, None, None # type: ignore pass
class EosActionRefund(p.MessageType): class EosActionRefund(p.MessageType):

@ -4,10 +4,10 @@ import protobuf as p
if __debug__: if __debug__:
try: try:
from typing import Dict, List, Optional from typing import Dict, List # noqa: F401
from typing_extensions import Literal # noqa: F401 from typing_extensions import Literal # noqa: F401
except ImportError: except ImportError:
Dict, List, Optional = None, None, None # type: ignore pass
class EosActionSellRam(p.MessageType): class EosActionSellRam(p.MessageType):

@ -6,10 +6,10 @@ from .EosAsset import EosAsset
if __debug__: if __debug__:
try: try:
from typing import Dict, List, Optional from typing import Dict, List # noqa: F401
from typing_extensions import Literal # noqa: F401 from typing_extensions import Literal # noqa: F401
except ImportError: except ImportError:
Dict, List, Optional = None, None, None # type: ignore pass
class EosActionTransfer(p.MessageType): class EosActionTransfer(p.MessageType):

@ -6,10 +6,10 @@ from .EosAsset import EosAsset
if __debug__: if __debug__:
try: try:
from typing import Dict, List, Optional from typing import Dict, List # noqa: F401
from typing_extensions import Literal # noqa: F401 from typing_extensions import Literal # noqa: F401
except ImportError: except ImportError:
Dict, List, Optional = None, None, None # type: ignore pass
class EosActionUndelegate(p.MessageType): class EosActionUndelegate(p.MessageType):

@ -4,10 +4,10 @@ import protobuf as p
if __debug__: if __debug__:
try: try:
from typing import Dict, List, Optional from typing import Dict, List # noqa: F401
from typing_extensions import Literal # noqa: F401 from typing_extensions import Literal # noqa: F401
except ImportError: except ImportError:
Dict, List, Optional = None, None, None # type: ignore pass
class EosActionUnknown(p.MessageType): class EosActionUnknown(p.MessageType):

@ -4,10 +4,10 @@ import protobuf as p
if __debug__: if __debug__:
try: try:
from typing import Dict, List, Optional from typing import Dict, List # noqa: F401
from typing_extensions import Literal # noqa: F401 from typing_extensions import Literal # noqa: F401
except ImportError: except ImportError:
Dict, List, Optional = None, None, None # type: ignore pass
class EosActionUnlinkAuth(p.MessageType): class EosActionUnlinkAuth(p.MessageType):

@ -6,10 +6,10 @@ from .EosAuthorization import EosAuthorization
if __debug__: if __debug__:
try: try:
from typing import Dict, List, Optional from typing import Dict, List # noqa: F401
from typing_extensions import Literal # noqa: F401 from typing_extensions import Literal # noqa: F401
except ImportError: except ImportError:
Dict, List, Optional = None, None, None # type: ignore pass
class EosActionUpdateAuth(p.MessageType): class EosActionUpdateAuth(p.MessageType):

@ -4,10 +4,10 @@ import protobuf as p
if __debug__: if __debug__:
try: try:
from typing import Dict, List, Optional from typing import Dict, List # noqa: F401
from typing_extensions import Literal # noqa: F401 from typing_extensions import Literal # noqa: F401
except ImportError: except ImportError:
Dict, List, Optional = None, None, None # type: ignore pass
class EosActionVoteProducer(p.MessageType): class EosActionVoteProducer(p.MessageType):

@ -4,10 +4,10 @@ import protobuf as p
if __debug__: if __debug__:
try: try:
from typing import Dict, List, Optional from typing import Dict, List # noqa: F401
from typing_extensions import Literal # noqa: F401 from typing_extensions import Literal # noqa: F401
except ImportError: except ImportError:
Dict, List, Optional = None, None, None # type: ignore pass
class EosAsset(p.MessageType): class EosAsset(p.MessageType):

@ -8,10 +8,10 @@ from .EosAuthorizationWait import EosAuthorizationWait
if __debug__: if __debug__:
try: try:
from typing import Dict, List, Optional from typing import Dict, List # noqa: F401
from typing_extensions import Literal # noqa: F401 from typing_extensions import Literal # noqa: F401
except ImportError: except ImportError:
Dict, List, Optional = None, None, None # type: ignore pass
class EosAuthorization(p.MessageType): class EosAuthorization(p.MessageType):

@ -6,10 +6,10 @@ from .EosPermissionLevel import EosPermissionLevel
if __debug__: if __debug__:
try: try:
from typing import Dict, List, Optional from typing import Dict, List # noqa: F401
from typing_extensions import Literal # noqa: F401 from typing_extensions import Literal # noqa: F401
except ImportError: except ImportError:
Dict, List, Optional = None, None, None # type: ignore pass
class EosAuthorizationAccount(p.MessageType): class EosAuthorizationAccount(p.MessageType):

@ -4,10 +4,10 @@ import protobuf as p
if __debug__: if __debug__:
try: try:
from typing import Dict, List, Optional from typing import Dict, List # noqa: F401
from typing_extensions import Literal # noqa: F401 from typing_extensions import Literal # noqa: F401
except ImportError: except ImportError:
Dict, List, Optional = None, None, None # type: ignore pass
class EosAuthorizationKey(p.MessageType): class EosAuthorizationKey(p.MessageType):

Some files were not shown because too many files have changed in this diff Show More

Loading…
Cancel
Save