Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(core/mercury): show remaining shares #4142

Merged
merged 1 commit into from
Sep 3, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions core/.changelog.d/4142.fixed
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
[T3T1] Added missing info about remaining shares in super-shamir recovery.
306 changes: 210 additions & 96 deletions core/embed/rust/src/ui/model_mercury/flow/continue_recovery.rs

Large diffs are not rendered by default.

33 changes: 1 addition & 32 deletions core/embed/rust/src/ui/model_mercury/layout.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1013,31 +1013,6 @@ extern "C" fn new_show_group_share_success(
unsafe { util::try_with_args_and_kwargs(n_args, args, kwargs, block) }
}

extern "C" fn new_show_remaining_shares(n_args: usize, args: *const Obj, kwargs: *mut Map) -> Obj {
let block = move |_args: &[Obj], kwargs: &Map| {
let pages_iterable: Obj = kwargs.get(Qstr::MP_QSTR_pages)?;

let mut paragraphs = ParagraphVecLong::new();
for page in IterBuf::new().try_iterate(pages_iterable)? {
let [title, description]: [TString; 2] = util::iter_into_array(page)?;
paragraphs
.add(Paragraph::new(&theme::TEXT_DEMIBOLD, title))
.add(Paragraph::new(&theme::TEXT_NORMAL, description).break_after());
}

let obj = LayoutObj::new(SwipeUpScreen::new(
Frame::left_aligned(
TR::recovery__title_remaining_shares.into(),
SwipeContent::new(paragraphs.into_paragraphs()),
)
.with_footer(TR::instructions__swipe_up.into(), None)
.with_swipe(SwipeDirection::Up, SwipeSettings::default()),
))?;
Ok(obj.into())
};
unsafe { util::try_with_args_and_kwargs(n_args, args, kwargs, block) }
}

extern "C" fn new_show_progress(n_args: usize, args: *const Obj, kwargs: *mut Map) -> Obj {
let block = move |_args: &[Obj], kwargs: &Map| {
let description: TString = kwargs.get(Qstr::MP_QSTR_description)?.try_into()?;
Expand Down Expand Up @@ -1594,6 +1569,7 @@ pub static mp_module_trezorui2: Module = obj_module! {
/// recovery_type: RecoveryType,
/// text: str,
/// subtext: str | None = None,
/// pages: Iterable[tuple[str, str]] | None = None,
/// ) -> LayoutObj[UiResult]:
/// """Device recovery homescreen."""
Qstr::MP_QSTR_flow_continue_recovery => obj_fn_kw!(0, flow::continue_recovery::new_continue_recovery).as_obj(),
Expand All @@ -1613,13 +1589,6 @@ pub static mp_module_trezorui2: Module = obj_module! {
/// """Shown after successfully finishing a group."""
Qstr::MP_QSTR_show_group_share_success => obj_fn_kw!(0, new_show_group_share_success).as_obj(),

/// def show_remaining_shares(
/// *,
/// pages: Iterable[tuple[str, str]],
/// ) -> LayoutObj[UiResult]:
/// """Shows SLIP39 state after info button is pressed on `confirm_recovery`."""
Qstr::MP_QSTR_show_remaining_shares => obj_fn_kw!(0, new_show_remaining_shares).as_obj(),

/// def show_progress(
/// *,
/// title: str,
Expand Down
9 changes: 1 addition & 8 deletions core/mocks/generated/trezorui2.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -452,6 +452,7 @@ def flow_continue_recovery(
recovery_type: RecoveryType,
text: str,
subtext: str | None = None,
pages: Iterable[tuple[str, str]] | None = None,
) -> LayoutObj[UiResult]:
"""Device recovery homescreen."""

Expand All @@ -473,14 +474,6 @@ def show_group_share_success(
"""Shown after successfully finishing a group."""


# rust/src/ui/model_mercury/layout.rs
def show_remaining_shares(
*,
pages: Iterable[tuple[str, str]],
) -> LayoutObj[UiResult]:
"""Shows SLIP39 state after info button is pressed on `confirm_recovery`."""


# rust/src/ui/model_mercury/layout.rs
def show_progress(
*,
Expand Down
30 changes: 16 additions & 14 deletions core/src/apps/management/recovery_device/homescreen.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@
if TYPE_CHECKING:
from trezor.enums import BackupType, RecoveryType

from .layout import RemainingSharesInfo


async def recovery_homescreen() -> None:
from trezor import workflow
Expand Down Expand Up @@ -297,7 +299,7 @@ async def _request_share_next_screen() -> None:
await layout.homescreen_dialog(
TR.buttons__enter,
TR.recovery__more_shares_needed,
info_func=_show_remaining_groups_and_shares,
remaining_shares_info=_get_remaining_groups_and_shares(),
)
else:
still_needed_shares = remaining[0]
Expand All @@ -315,37 +317,37 @@ async def _request_share_next_screen() -> None:
await layout.homescreen_dialog(TR.buttons__enter_share, entered, needed)


async def _show_remaining_groups_and_shares() -> None:
def _get_remaining_groups_and_shares() -> "RemainingSharesInfo":
"""
Show info dialog for Slip39 Advanced - what shares are to be entered.
Prepare data for Slip39 Advanced - what shares are to be entered.
"""
from trezor.crypto import slip39

shares_remaining = storage_recovery.fetch_slip39_remaining_shares()
# should be stored at this point
assert shares_remaining
assert shares_remaining # should be stored at this point

groups = set()
first_entered_index = -1
for i, group_count in enumerate(shares_remaining):
if group_count < slip39.MAX_SHARE_COUNT:
first_entered_index = i
break

share = None
for index, remaining in enumerate(shares_remaining):
if 0 <= remaining < slip39.MAX_SHARE_COUNT:
m = storage_recovery_shares.fetch_group(index)[0]
if not share:
share = slip39.decode_mnemonic(m)
identifier = m.split(" ")[0:3]
groups.add((remaining, tuple(identifier)))
identifier = tuple(m.split(" ")[0:3])
groups.add(identifier)
elif remaining == slip39.MAX_SHARE_COUNT: # no shares yet
identifier = storage_recovery_shares.fetch_group(first_entered_index)[
0
].split(" ")[0:2]
groups.add((remaining, tuple(identifier)))
identifier = tuple(
storage_recovery_shares.fetch_group(first_entered_index)[0].split(" ")[
0:2
]
)
groups.add(identifier)

assert share # share needs to be set
return await layout.show_remaining_shares(
groups, shares_remaining, share.group_threshold
)
return groups, shares_remaining, share.group_threshold
18 changes: 13 additions & 5 deletions core/src/apps/management/recovery_device/layout.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,16 +6,19 @@
request_word_count,
show_group_share_success,
show_recovery_warning,
show_remaining_shares,
)

from apps.common import backup_types

if TYPE_CHECKING:
from typing import Callable

from trezor.enums import BackupType

# RemainingSharesInfo represents the data structure for remaining shares in SLIP-39 recovery:
# - Set of tuples, each containing 2 or 3 words identifying a group
# - List of remaining share counts for each group
# - Group threshold (minimum number of groups required)
RemainingSharesInfo = tuple[set[tuple[str, ...]], list[int], int]


async def request_mnemonic(
word_count: int, backup_type: BackupType | None
Expand Down Expand Up @@ -123,8 +126,8 @@ async def homescreen_dialog(
button_label: str,
text: str,
subtext: str | None = None,
info_func: Callable | None = None,
show_info: bool = False,
remaining_shares_info: "RemainingSharesInfo | None" = None,
) -> None:
import storage.recovery as storage_recovery
from trezor.ui.layouts.recovery import continue_recovery
Expand All @@ -133,6 +136,11 @@ async def homescreen_dialog(

recovery_type = storage_recovery.get_type()
if not await continue_recovery(
button_label, text, subtext, info_func, recovery_type, show_info
button_label,
text,
subtext,
recovery_type,
show_info,
remaining_shares_info,
):
raise RecoveryAborted
48 changes: 22 additions & 26 deletions core/src/trezor/ui/layouts/mercury/recovery.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from typing import Callable, Iterable
from typing import TYPE_CHECKING

import trezorui2
from trezor import TR
Expand All @@ -11,6 +11,9 @@
CANCELLED = trezorui2.CANCELLED # global_import_cache
INFO = trezorui2.INFO # global_import_cache

if TYPE_CHECKING:
from apps.management.recovery_device.layout import RemainingSharesInfo


async def request_word_count(recovery_type: RecoveryType) -> int:
selector = RustLayout(trezorui2.select_word_count(recovery_type=recovery_type))
Expand Down Expand Up @@ -40,16 +43,18 @@ async def request_word(
return word


async def show_remaining_shares(
groups: Iterable[tuple[int, tuple[str, ...]]], # remaining + list 3 words
shares_remaining: list[int],
group_threshold: int,
) -> None:
def format_remaining_shares_info(
remaining_shares_info: "RemainingSharesInfo",
) -> list[tuple[str, str]]:
from trezor import strings
from trezor.crypto.slip39 import MAX_SHARE_COUNT

groups, shares_remaining, group_threshold = remaining_shares_info

pages: list[tuple[str, str]] = []
for remaining, group in groups:
completed_groups = shares_remaining.count(0)

for group, remaining in zip(groups, shares_remaining):
if 0 < remaining < MAX_SHARE_COUNT:
title = strings.format_plural(
TR.recovery__x_more_items_starting_template_plural,
Expand All @@ -58,10 +63,8 @@ async def show_remaining_shares(
)
words = "\n".join(group)
pages.append((title, words))
elif (
remaining == MAX_SHARE_COUNT and shares_remaining.count(0) < group_threshold
):
groups_remaining = group_threshold - shares_remaining.count(0)
elif remaining == MAX_SHARE_COUNT and completed_groups < group_threshold:
groups_remaining = group_threshold - completed_groups
title = strings.format_plural(
TR.recovery__x_more_items_starting_template_plural,
groups_remaining,
Expand All @@ -70,13 +73,7 @@ async def show_remaining_shares(
words = "\n".join(group)
pages.append((title, words))

await raise_if_not_confirmed(
interact(
RustLayout(trezorui2.show_remaining_shares(pages=pages)),
"show_shares",
ButtonRequestType.Other,
)
)
return pages


async def show_group_share_success(share_index: int, group_index: int) -> None:
Expand All @@ -102,26 +99,25 @@ async def continue_recovery(
button_label: str, # unused on mercury
text: str,
subtext: str | None,
info_func: Callable | None, # TODO: see below
recovery_type: RecoveryType,
show_info: bool = False,
remaining_shares_info: "RemainingSharesInfo | None" = None,
) -> bool:
# TODO: info_func should be changed to return data to be shown (and not show
# them) so that individual models can implement showing logic on their own.
# T3T1 should move the data to `flow_continue_recovery` and hide them
# in the context menu

# NOTE: show_info can be understood as first screen before any shares
# NOTE: button request sent from the flow
homepage = RustLayout(
result = await RustLayout(
trezorui2.flow_continue_recovery(
first_screen=show_info,
recovery_type=recovery_type,
text=text,
subtext=subtext,
pages=(
format_remaining_shares_info(remaining_shares_info)
if remaining_shares_info
else None
),
)
)
result = await homepage
return result is CONFIRMED


Expand Down
7 changes: 5 additions & 2 deletions core/src/trezor/ui/layouts/tr/recovery.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from typing import Callable, Iterable
from typing import TYPE_CHECKING, Iterable

import trezorui2
from trezor import TR
Expand All @@ -7,6 +7,9 @@
from ..common import interact
from . import RustLayout, raise_if_not_confirmed, show_warning

if TYPE_CHECKING:
from apps.management.recovery_device.layout import RemainingSharesInfo


async def request_word_count(recovery_type: RecoveryType) -> int:
count = await interact(
Expand Down Expand Up @@ -97,9 +100,9 @@ async def continue_recovery(
button_label: str,
text: str,
subtext: str | None,
info_func: Callable | None,
recovery_type: RecoveryType,
show_info: bool = False,
remaining_shares_info: "RemainingSharesInfo | None" = None, # unused on TR
) -> bool:
# TODO: implement info_func?
# There is very limited space on the screen
Expand Down
Loading
Loading