Merge remote-tracking branch 'agent/benma-agent/translations'
What changed, and why it matters
This commit adds German-language translations to the BitBox02 hardware wallet firmware. It introduces a new internationalization (i18n) system, stores the chosen UI language in device memory, exposes it via the device-info API, and lets the host change it. The change is large but mostly mechanical: replacing hard-coded English strings with translated equivalents. There is no direct evidence in the diff of a security vulnerability, but any broad UI-text change carries a small risk that a safety-critical warning could be rendered incorrectly or bypassed due to a translation/lookup bug.
Treat as a normal feature merge, not a security patch. Review the set_device_language handler to confirm it validates the language code and requires user confirmation on the device. Verify that safety-critical strings (e.g., warnings, recovery-word instructions, high-fee alerts) are present and correctly translated in both locales, and that the FNV-1a hash lookup cannot be confused by near-collision strings. Run the existing unit tests and consider adding tests that safety strings render identically in meaning across languages.
Security signals we found
Large surface-area string-replacement refactor across security-sensitive workflows (seed backup, transaction signing, password change, factory reset, U2F, Bluetooth firmware upgrade)
New device-language memory byte reuses previously reserved chunk field; bounds/enum validation present but any memory-layout change warrants scrutiny
Translation lookup is by 64-bit FNV-1a hash of source English string; collisions across safety warnings could theoretically cause wrong text to be shown
New host-controllable SetDeviceLanguage API increases attack surface, though the implementation requires on-device user confirmation
Async recursion in async_usb is boxed, which is a hardening change rather than a vulnerability
Evidence from the diff
The merge commit implements firmware UI translations. Key changes: (1) new bitbox-i18n Rust crate with compile-time JSON locale tables (en/de) keyed by FNV-1a hash of the English source string; (2) memory.c reserves a byte for device_language (0=en, 1=de, 0xFF defaults to English) and adds get/set accessors; (3) DeviceInfoResponse protobuf gains language and supported_languages fields; (4) a new set_device_language API request is wired through the Rust hww layer; (5) dozens of UI call sites switch from hard-coded English to crate::tr!(hal, …) / crate::tr_format!(hal, …). The build.rs validates placeholder counts and translation completeness. A few unrelated fixes ride along: async_usb.rs boxes a recursive future to avoid stack overflow, and bitbox-lvgl-sys/build.rs adds -Wno-psabi.
Changed components
src/rust/bitbox-i18nsrc/memory/memory.c / memory.hsrc/rust/bitbox02-rust/src/hww/apimessages/bitbox02_system.protopy/bitbox02src/ui/componentssrc/rust/bitbox02-rust/src/workflowInspect captured patch +2798 / −594
### CHANGELOG.md
@@ -12,6 +12,7 @@ recorded separately.
- Hold the screen reset pin low until firmware is ready initalize it.
- Cardano: limit xpub requests to 20 keypaths per batch
- API: add a session reset command for clean host reconnects after interrupted operations
+- Add German firmware translations
### v9.27.1
- API: include the installed bootloader version in the device info response
### messages/bitbox02_system.proto
@@ -36,6 +36,10 @@ message DeviceInfoResponse {
string password_stretching_algo = 8;
// Marketing version of the installed stage1 bootloader. Not present on legacy bootloaders.
optional string bootloader_version = 9;
+ // Current UI language code, e.g. "en" or "de". Empty on firmware without language support.
+ string language = 10;
+ // Empty on firmware without supported-language reporting.
+ repeated string supported_languages = 11;
}
message InsertRemoveSDCardRequest {
### py/bitbox02/bitbox02/bitbox02/bitbox02.py
@@ -179,6 +179,8 @@ def device_info(self) -> Dict[str, Any]:
response = self._msg_query(request, expected_response="device_info")
result: Dict[str, Any] = {
"name": response.device_info.name,
+ "language": response.device_info.language,
+ "supported_languages": list(response.device_info.supported_languages),
"version": response.device_info.version,
"bootloader_version": (
response.device_info.bootloader_version
@@ -210,6 +212,12 @@ def set_device_name(self, device_name: str) -> None:
request.device_name.name = device_name
self._msg_query(request, expected_response="success")
+ def set_device_language(self, language: str) -> None:
+ # pylint: disable=no-member
+ request = hww.Request()
+ request.device_language.language = language
+ self._msg_query(request, expected_response="success")
+
def set_password(self, entropy_size: int = 32) -> bool:
"""
Returns True if the user entered the password correctly (passwords match).
### py/bitbox02/bitbox02/communication/generated/bitbox02_system_pb2.py
@@ -13,7 +13,7 @@
-DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\x15\x62itbox02_system.proto\x12\x14shiftcrypto.bitbox02\"\x14\n\x12\x43heckSDCardRequest\"\'\n\x13\x43heckSDCardResponse\x12\x10\n\x08inserted\x18\x01 \x01(\x08\"\x13\n\x11\x44\x65viceInfoRequest\"\xb2\x03\n\x12\x44\x65viceInfoResponse\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x13\n\x0binitialized\x18\x02 \x01(\x08\x12\x0f\n\x07version\x18\x03 \x01(\t\x12#\n\x1bmnemonic_passphrase_enabled\x18\x04 \x01(\x08\x12&\n\x1emonotonic_increments_remaining\x18\x05 \x01(\r\x12\x18\n\x10securechip_model\x18\x06 \x01(\t\x12J\n\tbluetooth\x18\x07 \x01(\x0b\x32\x32.shiftcrypto.bitbox02.DeviceInfoResponse.BluetoothH\x00\x88\x01\x01\x12 \n\x18password_stretching_algo\x18\x08 \x01(\t\x12\x1f\n\x12\x62ootloader_version\x18\t \x01(\tH\x01\x88\x01\x01\x1aM\n\tBluetooth\x12\x15\n\rfirmware_hash\x18\x01 \x01(\x0c\x12\x18\n\x10\x66irmware_version\x18\x02 \x01(\t\x12\x0f\n\x07\x65nabled\x18\x03 \x01(\x08\x42\x0c\n\n_bluetoothB\x15\n\x13_bootloader_version\"\x9b\x01\n\x19InsertRemoveSDCardRequest\x12L\n\x06\x61\x63tion\x18\x01 \x01(\x0e\x32<.shiftcrypto.bitbox02.InsertRemoveSDCardRequest.SDCardAction\"0\n\x0cSDCardAction\x12\x0f\n\x0bREMOVE_CARD\x10\x00\x12\x0f\n\x0bINSERT_CARD\x10\x01\"\x0e\n\x0cResetRequest\",\n\x18SetDeviceLanguageRequest\x12\x10\n\x08language\x18\x01 \x01(\t\"$\n\x14SetDeviceNameRequest\x12\x0c\n\x04name\x18\x01 \x01(\t\"%\n\x12SetPasswordRequest\x12\x0f\n\x07\x65ntropy\x18\x01 \x01(\x0c\"\x17\n\x15\x43hangePasswordRequestb\x06proto3')
+DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\x15\x62itbox02_system.proto\x12\x14shiftcrypto.bitbox02\"\x14\n\x12\x43heckSDCardRequest\"\'\n\x13\x43heckSDCardResponse\x12\x10\n\x08inserted\x18\x01 \x01(\x08\"\x13\n\x11\x44\x65viceInfoRequest\"\xe1\x03\n\x12\x44\x65viceInfoResponse\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x13\n\x0binitialized\x18\x02 \x01(\x08\x12\x0f\n\x07version\x18\x03 \x01(\t\x12#\n\x1bmnemonic_passphrase_enabled\x18\x04 \x01(\x08\x12&\n\x1emonotonic_increments_remaining\x18\x05 \x01(\r\x12\x18\n\x10securechip_model\x18\x06 \x01(\t\x12J\n\tbluetooth\x18\x07 \x01(\x0b\x32\x32.shiftcrypto.bitbox02.DeviceInfoResponse.BluetoothH\x00\x88\x01\x01\x12 \n\x18password_stretching_algo\x18\x08 \x01(\t\x12\x1f\n\x12\x62ootloader_version\x18\t \x01(\tH\x01\x88\x01\x01\x12\x10\n\x08language\x18\n \x01(\t\x12\x1b\n\x13supported_languages\x18\x0b \x03(\t\x1aM\n\tBluetooth\x12\x15\n\rfirmware_hash\x18\x01 \x01(\x0c\x12\x18\n\x10\x66irmware_version\x18\x02 \x01(\t\x12\x0f\n\x07\x65nabled\x18\x03 \x01(\x08\x42\x0c\n\n_bluetoothB\x15\n\x13_bootloader_version\"\x9b\x01\n\x19InsertRemoveSDCardRequest\x12L\n\x06\x61\x63tion\x18\x01 \x01(\x0e\x32<.shiftcrypto.bitbox02.InsertRemoveSDCardRequest.SDCardAction\"0\n\x0cSDCardAction\x12\x0f\n\x0bREMOVE_CARD\x10\x00\x12\x0f\n\x0bINSERT_CARD\x10\x01\"\x0e\n\x0cResetRequest\",\n\x18SetDeviceLanguageRequest\x12\x10\n\x08language\x18\x01 \x01(\t\"$\n\x14SetDeviceNameRequest\x12\x0c\n\x04name\x18\x01 \x01(\t\"%\n\x12SetPasswordRequest\x12\x0f\n\x07\x65ntropy\x18\x01 \x01(\x0c\"\x17\n\x15\x43hangePasswordRequestb\x06proto3')
_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, globals())
_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'bitbox02_system_pb2', globals())
@@ -27,21 +27,21 @@
_DEVICEINFOREQUEST._serialized_start=110
_DEVICEINFOREQUEST._serialized_end=129
_DEVICEINFORESPONSE._serialized_start=132
- _DEVICEINFORESPONSE._serialized_end=566
- _DEVICEINFORESPONSE_BLUETOOTH._serialized_start=452
- _DEVICEINFORESPONSE_BLUETOOTH._serialized_end=529
- _INSERTREMOVESDCARDREQUEST._serialized_start=569
- _INSERTREMOVESDCARDREQUEST._serialized_end=724
- _INSERTREMOVESDCARDREQUEST_SDCARDACTION._serialized_start=676
- _INSERTREMOVESDCARDREQUEST_SDCARDACTION._serialized_end=724
- _RESETREQUEST._serialized_start=726
- _RESETREQUEST._serialized_end=740
- _SETDEVICELANGUAGEREQUEST._serialized_start=742
- _SETDEVICELANGUAGEREQUEST._serialized_end=786
- _SETDEVICENAMEREQUEST._serialized_start=788
- _SETDEVICENAMEREQUEST._serialized_end=824
- _SETPASSWORDREQUEST._serialized_start=826
- _SETPASSWORDREQUEST._serialized_end=863
- _CHANGEPASSWORDREQUEST._serialized_start=865
- _CHANGEPASSWORDREQUEST._serialized_end=888
+ _DEVICEINFORESPONSE._serialized_end=613
+ _DEVICEINFORESPONSE_BLUETOOTH._serialized_start=499
+ _DEVICEINFORESPONSE_BLUETOOTH._serialized_end=576
+ _INSERTREMOVESDCARDREQUEST._serialized_start=616
+ _INSERTREMOVESDCARDREQUEST._serialized_end=771
+ _INSERTREMOVESDCARDREQUEST_SDCARDACTION._serialized_start=723
+ _INSERTREMOVESDCARDREQUEST_SDCARDACTION._serialized_end=771
+ _RESETREQUEST._serialized_start=773
+ _RESETREQUEST._serialized_end=787
+ _SETDEVICELANGUAGEREQUEST._serialized_start=789
+ _SETDEVICELANGUAGEREQUEST._serialized_end=833
+ _SETDEVICENAMEREQUEST._serialized_start=835
+ _SETDEVICENAMEREQUEST._serialized_end=871
+ _SETPASSWORDREQUEST._serialized_start=873
+ _SETPASSWORDREQUEST._serialized_end=910
+ _CHANGEPASSWORDREQUEST._serialized_start=912
+ _CHANGEPASSWORDREQUEST._serialized_end=935
# @@protoc_insertion_point(module_scope)
### py/bitbox02/bitbox02/communication/generated/bitbox02_system_pb2.pyi
@@ -4,7 +4,9 @@ isort:skip_file
SPDX-License-Identifier: Apache-2.0"""
import builtins
+import collections.abc
import google.protobuf.descriptor
+import google.protobuf.internal.containers
import google.protobuf.internal.enum_type_wrapper
import google.protobuf.message
import sys
@@ -87,6 +89,8 @@ class DeviceInfoResponse(google.protobuf.message.Message):
BLUETOOTH_FIELD_NUMBER: builtins.int
PASSWORD_STRETCHING_ALGO_FIELD_NUMBER: builtins.int
BOOTLOADER_VERSION_FIELD_NUMBER: builtins.int
+ LANGUAGE_FIELD_NUMBER: builtins.int
+ SUPPORTED_LANGUAGES_FIELD_NUMBER: builtins.int
name: builtins.str
initialized: builtins.bool
version: builtins.str
@@ -100,10 +104,16 @@ class DeviceInfoResponse(google.protobuf.message.Message):
"""
bootloader_version: builtins.str
"""Marketing version of the installed stage1 bootloader. Not present on legacy bootloaders."""
+ language: builtins.str
+ """Current UI language code, e.g. "en" or "de". Empty on firmware without language support."""
@property
def bluetooth(self) -> global___DeviceInfoResponse.Bluetooth:
"""Only present in Bluetooth-enabled devices."""
+ @property
+ def supported_languages(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.str]:
+ """Empty on firmware without supported-language reporting."""
+
def __init__(
self,
*,
@@ -116,9 +126,11 @@ class DeviceInfoResponse(google.protobuf.message.Message):
bluetooth: global___DeviceInfoResponse.Bluetooth | None = ...,
password_stretching_algo: builtins.str = ...,
bootloader_version: builtins.str | None = ...,
+ language: builtins.str = ...,
+ supported_languages: collections.abc.Iterable[builtins.str] | None = ...,
) -> None: ...
def HasField(self, field_name: typing.Literal["_bluetooth", b"_bluetooth", "_bootloader_version", b"_bootloader_version", "bluetooth", b"bluetooth", "bootloader_version", b"bootloader_version"]) -> builtins.bool: ...
- def ClearField(self, field_name: typing.Literal["_bluetooth", b"_bluetooth", "_bootloader_version", b"_bootloader_version", "bluetooth", b"bluetooth", "bootloader_version", b"bootloader_version", "initialized", b"initialized", "mnemonic_passphrase_enabled", b"mnemonic_passphrase_enabled", "monotonic_increments_remaining", b"monotonic_increments_remaining", "name", b"name", "password_stretching_algo", b"password_stretching_algo", "securechip_model", b"securechip_model", "version", b"version"]) -> None: ...
+ def ClearField(self, field_name: typing.Literal["_bluetooth", b"_bluetooth", "_bootloader_version", b"_bootloader_version", "bluetooth", b"bluetooth", "bootloader_version", b"bootloader_version", "initialized", b"initialized", "language", b"language", "mnemonic_passphrase_enabled", b"mnemonic_passphrase_enabled", "monotonic_increments_remaining", b"monotonic_increments_remaining", "name", b"name", "password_stretching_algo", b"password_stretching_algo", "securechip_model", b"securechip_model", "supported_languages", b"supported_languages", "version", b"version"]) -> None: ...
@typing.overload
def WhichOneof(self, oneof_group: typing.Literal["_bluetooth", b"_bluetooth"]) -> typing.Literal["bluetooth"] | None: ...
@typing.overload
### py/send_message.py
@@ -318,6 +318,21 @@ def _change_name_workflow(self, name: Optional[str] = None) -> None:
info = self._device.device_info()
print(f"New device name: {info['name']}")
+ def _change_language_workflow(self) -> None:
+ choice = ask_user(
+ (
+ ("English", lambda: self._device.set_device_language("en")),
+ ("German", lambda: self._device.set_device_language("de")),
+ )
+ )
+ if callable(choice):
+ try:
+ choice()
+ except UserAbortException:
+ eprint("Aborted by user")
+ else:
+ print("Device language changed.")
+
def _setup_workflow(self) -> None:
"""TODO: Document"""
self._change_name_workflow()
@@ -1871,6 +1886,7 @@ def _menu_notinit(self) -> None:
("Restore from backup", self._restore_backup_workflow),
("Restore from mnemonic", self._restore_from_mnemonic),
("List device info", self._list_device_info),
+ ("Change device language", self._change_language_workflow),
("Reboot into bootloader", self._reboot),
("Check if SD card inserted", self._check_sd_presence),
("Upgrade Bluetooth firmware", self._bluetooth_upgrade),
@@ -1888,6 +1904,7 @@ def _menu_init(self) -> None:
choices = (
("List device info", self._list_device_info),
("Change device name", self._change_name_workflow),
+ ("Change device language", self._change_language_workflow),
("Get root fingerprint", self._get_root_fingerprint),
("Retrieve zpub of first account", self._display_zpub),
("Retrieve multiple xpubs", self._btc_xpubs),
### src/da14531/da14531_handler.c
@@ -186,8 +186,10 @@ static void _ctrl_handler(const struct da14531_ctrl_frame* frame, struct RustByt
pairing_code_int /= 10;
}
// util_log("da14531: show/confirm pairing code: %s", pairing_code);
+ char pairing_title[32] = {0};
+ rust_i18n_translate_copy("Pairing code", pairing_title, sizeof(pairing_title));
const confirm_params_t confirm_params = {
- .title = "Pairing code",
+ .title = pairing_title,
.body = pairing_code,
.font = &font_monogram_16,
};
### src/i18n/locales/de/firmware.json
@@ -0,0 +1,344 @@
+{
+ "cancel": {
+ "confirmCancel": "Wirklich\nabbrechen?"
+ },
+ "confirm": {
+ "size": "Größe"
+ },
+ "hww": {
+ "backup": {
+ "check": {
+ "id": "ID?",
+ "invalid": "Backup fehlt\noder ungültig",
+ "name": "Name?",
+ "valid": "Backup gültig"
+ },
+ "create": {
+ "confirm": "Backup erstellen?",
+ "fail": "Backup nicht\nerstellt ({})\nSupport kontaktieren",
+ "isToday": "Ist heute?",
+ "success": "Backup erstellt",
+ "unlock": "Gerät entsperren"
+ }
+ },
+ "bip85": {
+ "confirmAdvanced": {
+ "body": "Dies ist eine Funktion für Fortgeschrittene. Nur fortfahren, wenn du dich gut auskennst.",
+ "title": "BIP-85"
+ },
+ "confirmDerivation": {
+ "body": "BIP-39\nMnemonic ableiten?",
+ "title": "BIP-85"
+ },
+ "createLightning": "Lightning-Wallet\nauf Endgerät\nerstellen?",
+ "finished": "Fertig",
+ "howManyWords": "Wie viele Wörter?",
+ "index": {
+ "enter": "Index eingeben",
+ "invalid": "Ungültiger Index",
+ "more": "Mehr",
+ "select": "Index wählen",
+ "status": "Index: {}"
+ },
+ "keypath": "Pfad",
+ "wordCount": "{} Wörter"
+ },
+ "bitcoin": {
+ "atAccount": "{}\nKonto #{}",
+ "atPath": "{}\nauf\n{}",
+ "multisig": {
+ "cosigner": {
+ "other": "Cosigner {}/{}: {}",
+ "self": "Cosigner {}/{} (dieses Gerät): {}"
+ },
+ "scriptAtPath": "{}\nauf\n{}",
+ "threshold": "{}-von-{}\n{} Multisig"
+ },
+ "paymentRequest": {
+ "memo": "Memo",
+ "memoFrom": "Memo von: {}"
+ },
+ "policies": {
+ "info": "{}\nPolicy mit\n{} Schlüsseln",
+ "key": "Schlüssel {}/{}",
+ "name": "Name",
+ "provablyUnspendable": "Nachweislich nicht ausgebbar: {}",
+ "showDetails": "Policy-Details\nanzeigen?",
+ "thisDevice": "Dieses Gerät: {}",
+ "title": "Policy"
+ },
+ "receiveTo": "Empfangen an",
+ "registration": {
+ "enterAccountName": "Kontonamen eingeben",
+ "multisigRegistered": "Multisig-Setup\nregistriert",
+ "policyRegistered": "Policy\nregistriert",
+ "registerAccount": {
+ "body": "Bitte dieses\nKonto benennen",
+ "title": "Registrieren"
+ },
+ "title": "Registrieren"
+ },
+ "scriptConfigs": {
+ "thisBitBox": "Diese BitBox - {}",
+ "thisBitBoxAccount": "Diese BitBox (Konto #{})"
+ },
+ "signMessage": {
+ "address": "Adresse",
+ "coin": "Coin: {}",
+ "externalServiceKey": "Coin: {}\nSchlüssel für\nexternen Dienst",
+ "sign": "Signieren",
+ "signMessage": "Nachricht\nsignieren"
+ },
+ "signTx": {
+ "invalidPaymentRequest": "Ungültige\nZahlungsanfrage",
+ "loadingTx": "Transaktion lädt...",
+ "locktime": "Locktime bei Block:\n{}",
+ "locktimeUtc": "Locktime (UTC):\n{}\n{}:{}:{}",
+ "multipleChangeWarning": {
+ "body": "{} Outputs mit\nWechselgeld.\nFortfahren?",
+ "title": "Warnung"
+ },
+ "signingTx": "Transaktion\nwird signiert...",
+ "spendFrom": "Ausgeben von",
+ "thisBitBoxSame": "Diese BitBox (gleiches Konto)",
+ "txCanceled": "Transaktion\nabgebrochen",
+ "txConfirmed": "Transaktion\nbestätigt"
+ },
+ "unusualKeypathWarning": {
+ "body": "Warnung: ungewöhnlicher Keypath {}. Nur fortfahren, wenn du dich gut auskennst.",
+ "title": "xpub-Export"
+ }
+ },
+ "bluetooth": {
+ "confirmUpgrade": {
+ "body": "Firmware\naktualisieren?",
+ "title": "Bluetooth"
+ },
+ "disabled": "Bluetooth\ndeaktiviert",
+ "enabled": "Bluetooth\naktiviert",
+ "setDisable": "Bluetooth\ndeaktivieren?",
+ "setEnable": "Bluetooth aktivieren?",
+ "upgrade": {
+ "fail": "Aktualisierung\nfehlgeschlagen",
+ "progress": "Aktualisierung...",
+ "success": "Aktualisierung\nerfolgreich"
+ }
+ },
+ "changePassword": {
+ "confirm": "Passwort ändern\nfortsetzen?",
+ "error": "Fehler\n{}"
+ },
+ "cardano": {
+ "signTransaction": {
+ "alwaysAbstain": "Immer Enthaltung",
+ "alwaysNoConfidence": "Nie Vertrauen",
+ "amountAsset": "Betrag: {}. Asset: {}",
+ "canBeMinedFrom": "Gültig ab",
+ "canBeMinedUntil": "Gültig bis",
+ "cannotBeMined": "Transaktion\nkann nicht\ngemined werden",
+ "delegateStaking": "Staking für Konto #{} an Pool {} delegieren?",
+ "delegateVoting": "Voting für Konto #{} an Typ {} delegieren?",
+ "delegateVotingDrep": "Voting für Konto #{} an Typ {} und DRep {} delegieren?",
+ "fee": "Gebühr\n{}",
+ "keyHash": "Schlüssel-Hash",
+ "networkWarning": "Diese Transaktion enthält keine Angabe zum Cardano-Netzwerk und kann auch in einem anderen Cardano-Netzwerk gültig sein.",
+ "registerStakingKey": "Staking-Schlüssel für Konto #{} registrieren?",
+ "scriptHash": "Skript-Hash",
+ "sendToken": "Token senden",
+ "slotInEpoch": "{}\nSlot {} in\nEpoche {}",
+ "stopStakeDelegation": "Stake-Delegation für Konto #{} stoppen?",
+ "txCanceled": "Transaktion\nabgebrochen",
+ "txConfirmed": "Transaktion\nbestätigt",
+ "withdrawInStakingRewards": "{} Staking-Rewards für Konto #{} abheben?"
+ }
+ },
+ "ethereum": {
+ "loadingData": "Daten laden...",
+ "keypath": {
+ "unusualKeypath": "Warnung: ungewöhnlicher Keypath {}. Nur fortfahren, wenn du dich gut auskennst."
+ },
+ "network": {
+ "recognizeChainId": "Nur fortfahren, wenn\ndu diese Chain-ID\nerkennst.",
+ "unknownChainId": "Unbekanntes\nNetzwerk\nmit Chain-ID:\n{}"
+ },
+ "sign": {
+ "signOn": "Transaktion\nsignieren auf\n\n{}",
+ "tokenContract": "Token-\nContract",
+ "txCanceled": "Transaktion\nabgebrochen",
+ "txConfirmed": "Transaktion\nbestätigt",
+ "unknownAmount": "Unbekannter Betrag",
+ "unknownContract": {
+ "confirm": {
+ "body": "Die rohen\nTransaktionsdaten\nwerden angezeigt.",
+ "title": "Unbekannter\nContract"
+ },
+ "confirmAdvancedStreaming": "Nur fortfahren, wenn\ndu die Risiken ganz\nverstehst.",
+ "confirmAdvanced": "Nur fortfahren, wenn\ndu die Daten genau\nverstehst.",
+ "confirmStreaming": "Du signierst eine\nContract-Interaktion\nmit vielen Daten.",
+ "tooLarge": "Der nächste Wert ist\nzu gross für die\nvollständige Anzeige",
+ "transactionData": "Transaktions-\ndaten"
+ },
+ "unknownToken": "Unbekannter Token"
+ },
+ "signMsg": {
+ "sign": "Signieren",
+ "signMessage": "Nachricht\nsignieren"
+ },
+ "signTypedMsg": {
+ "Message": "Nachricht",
+ "domain": "Domain",
+ "empyList": "(leere Liste)",
+ "line": ", Zeile {}/{}",
+ "listWithElements": "Liste mit {} Elementen",
+ "messageType": "Nachrichtentyp",
+ "noChainIdWarning": "Die typisierten Daten enthalten keine Chain-ID. Die Nachricht ist auf jeder Chain gültig.",
+ "signData": "Daten signieren?",
+ "unknown": "Unbekannt"
+ }
+ },
+ "reset": {
+ "body": "In Werkszustand\nzurücksetzen?",
+ "status": "Zurückgesetzt",
+ "title": "Zurücksetzen"
+ },
+ "restore": {
+ "backupName": "Name: {}. ID: {}",
+ "confirmRestore": "Backup\nwiederherstellen?",
+ "error": "Backup nicht\nwiederhergestellt",
+ "invalidWords": "Recovery-Wörter\nungültig",
+ "isNow": "Ist jetzt?",
+ "passwordMismatch": "Passwörter\nnicht gleich.\nErneut versuchen?",
+ "validWords": "Recovery-Wörter\ngültig"
+ },
+ "setMnemonicPassphrase": {
+ "disable": "Deaktivieren",
+ "enable": "Aktivieren",
+ "optionalPassphrase": "Optionale\nPassphrase"
+ },
+ "setDeviceName": {
+ "title": "Name"
+ },
+ "setDeviceLanguage": {
+ "confirm": "Sprache ändern\nauf {}?",
+ "english": "Englisch",
+ "german": "Deutsch"
+ },
+ "setPassword": {
+ "repeat": "Erneut eingeben",
+ "set": "Passwort setzen"
+ },
+ "showMnemonic": {
+ "backupCreated": "Backup erstellt",
+ "doNotShareWarning": {
+ "body": "Teile deine\nRecovery-Wörter\nNIEMALS mit anderen!",
+ "title": "Warnung"
+ },
+ "unlockDevice": "Gerät entsperren",
+ "writeDown": {
+ "body": "Bitte schreibe die\nfolgenden Wörter auf",
+ "title": "Recovery-\nWörter"
+ }
+ },
+ "system": {
+ "reboot": "Neustart?",
+ "rebootToBootloader": "Gehe zu den\nStarteinstellungen?",
+ "upgrade": "Upgrade fortsetzen?"
+ }
+ },
+ "infoCentered": {
+ "skip": "Überspringen"
+ },
+ "lockscreen": "Siehe BitBoxApp",
+ "menu": {
+ "continue": "Weiter",
+ "select": "Wählen"
+ },
+ "mnemonic": {
+ "backToWords": "Zurück zu\nRecovery-Wörtern",
+ "cancelRestore": "Wiederherstellung\nabbrechen",
+ "choose": "Wählen",
+ "confirmCancel": {
+ "body": "Wiederherstellung\nabbrechen?",
+ "title": "Wieder-\nherstellen"
+ },
+ "confirmEachWord": "Bestätige\njedes Wort",
+ "editPrevious": "Letztes Wort\nbearbeiten",
+ "enterWords": "{} Wörter\neingeben",
+ "howManyWords": "Wie viele Wörter?",
+ "incorrectWord": "Falsches Wort\nErneut versuchen",
+ "invalidWord": "Ungültiges Wort\nErneut versuchen",
+ "invalidCheckRestart": "Ungültig. Recovery-\nWörter prüfen.\nNeu starten?",
+ "noneOfThem": "Keines davon",
+ "wordIndex": "{} von {}",
+ "wordsFollow": "{} Wörter folgen"
+ },
+ "orientation": "Seite antippen",
+ "pairing": {
+ "pairingCode": "Kopplungscode"
+ },
+ "password": {
+ "characterWarning": {
+ "body": "Dein Passwort\nhat weniger als\n4 Zeichen.\nFortfahren?",
+ "title": "Warnung"
+ },
+ "confirmCancel": "Wirklich\nabbrechen?",
+ "mismatch": "Passwörter\nnicht identisch",
+ "repeat": "Erneut eingeben",
+ "set": "Passwort setzen",
+ "success": "Erfolgreich"
+ },
+ "sdcard": {
+ "insertToContinue": "SD einstecken\nzum Fortfahren"
+ },
+ "transaction": {
+ "confirmSwap": {
+ "from": "{} von",
+ "to": "{} zu"
+ },
+ "confirmTransaction": {
+ "amount": "Betrag",
+ "fee": "Gebühr",
+ "recipient": "Empfänger",
+ "total": "Total"
+ },
+ "highFeeWarning": {
+ "body": "Gebühr: {}%\ndes Sendebetrags.\nFortfahren?",
+ "bodyTotalInputs": "Gebühr: {}%\naller Inputs.\nFortfahren?",
+ "title": "Hohe Gebühr"
+ }
+ },
+ "u2f": {
+ "auth": "U2F-Auth",
+ "initializeWithBitBoxApp": "Mit BitBoxApp\neinrichten, um U2F\nzu nutzen",
+ "refreshWebpage": "Webseite neu laden",
+ "register": "U2F einrichten",
+ "unknownSite": "Unbekannte Seite:",
+ "use": "U2F nutzen?"
+ },
+ "paymentRequest": {
+ "swap": "Swap"
+ },
+ "verifyMessage": {
+ "dataHex": "{}\nDaten (Hex)",
+ "pageTitle": "{}\n{}/{}"
+ },
+ "unlock": {
+ "enterPassword": "Passwort eingeben",
+ "keystoreUnlockFailed": "Entsperren fehlgeschlagen\n{}",
+ "passphrase": {
+ "confirm": "Bestätigen",
+ "confirmEmpty": "Leere Passphrase\nverwenden?",
+ "doubleCheck": "Bitte prüfe gleich\ndie angezeigte\nPassphrase erneut.",
+ "title": "Optionale Passphrase",
+ "tryAgain": "Bitte erneut\nversuchen"
+ },
+ "remainingAttempts": {
+ "last": "LETZTER Versuch.\nBei falschem\nPasswort wird das\nGerät zurückgesetzt.",
+ "other": "Du hast noch {}\nEingabeversuche.",
+ "title": "Warnung"
+ },
+ "wrongPassword": {
+ "base": "Passwort falsch"
+ }
+ }
+}
### src/i18n/locales/en/firmware.json
@@ -0,0 +1,344 @@
+{
+ "cancel": {
+ "confirmCancel": "Do you really\nwant to cancel?"
+ },
+ "confirm": {
+ "size": "Size"
+ },
+ "hww": {
+ "backup": {
+ "check": {
+ "id": "ID?",
+ "invalid": "Backup missing\nor invalid",
+ "name": "Name?",
+ "valid": "Backup valid"
+ },
+ "create": {
+ "confirm": "Create backup?",
+ "fail": "Backup not created\nPlease contact\nsupport ({})",
+ "isToday": "Is today?",
+ "success": "Backup created",
+ "unlock": "Unlock device"
+ }
+ },
+ "bip85": {
+ "confirmAdvanced": {
+ "body": "This is an advanced feature. Proceed only if you know what you are doing.",
+ "title": "BIP-85"
+ },
+ "confirmDerivation": {
+ "body": "Derive BIP-39\nmnemonic?",
+ "title": "BIP-85"
+ },
+ "createLightning": "Create\nLightning wallet\non host device?",
+ "finished": "Finished",
+ "howManyWords": "How many words?",
+ "index": {
+ "enter": "Enter index",
+ "invalid": "Invalid index",
+ "more": "More",
+ "select": "Select index",
+ "status": "Index: {}"
+ },
+ "keypath": "Keypath",
+ "wordCount": "{} words"
+ },
+ "bitcoin": {
+ "atAccount": "{}\naccount #{}",
+ "atPath": "{}\nat\n{}",
+ "multisig": {
+ "cosigner": {
+ "other": "Cosigner {}/{}: {}",
+ "self": "Cosigner {}/{} (this device): {}"
+ },
+ "scriptAtPath": "{}\nat\n{}",
+ "threshold": "{}-of-{}\n{} multisig"
+ },
+ "paymentRequest": {
+ "memo": "Memo",
+ "memoFrom": "Memo from: {}"
+ },
+ "policies": {
+ "info": "{}\npolicy with\n{} keys",
+ "key": "Key {}/{}",
+ "name": "Name",
+ "provablyUnspendable": "Provably unspendable: {}",
+ "showDetails": "Show policy\ndetails?",
+ "thisDevice": "This device: {}",
+ "title": "Policy"
+ },
+ "receiveTo": "Receive to",
+ "registration": {
+ "enterAccountName": "Enter account name",
+ "multisigRegistered": "Multisig account\nregistered",
+ "policyRegistered": "Policy\nregistered",
+ "registerAccount": {
+ "body": "Please name this\naccount",
+ "title": "Register"
+ },
+ "title": "Register"
+ },
+ "scriptConfigs": {
+ "thisBitBox": "This BitBox - {}",
+ "thisBitBoxAccount": "This BitBox (account #{})"
+ },
+ "signMessage": {
+ "address": "Address",
+ "coin": "Coin: {}",
+ "externalServiceKey": "Coin: {}\nExternal service key",
+ "sign": "Sign",
+ "signMessage": "Sign message"
+ },
+ "signTx": {
+ "invalidPaymentRequest": "Invalid\npayment request",
+ "loadingTx": "Loading transaction...",
+ "locktime": "Locktime on block:\n{}",
+ "locktimeUtc": "Locktime (UTC):\n{}\n{}:{}:{}",
+ "multipleChangeWarning": {
+ "body": "There are {}\nchange outputs.\nProceed?",
+ "title": "Warning"
+ },
+ "signingTx": "Signing transaction...",
+ "spendFrom": "Spend from",
+ "thisBitBoxSame": "This BitBox (same account)",
+ "txCanceled": "Transaction\ncanceled",
+ "txConfirmed": "Transaction\nconfirmed"
+ },
+ "unusualKeypathWarning": {
+ "body": "Warning: unusual keypath {}. Proceed only if you know what you are doing.",
+ "title": "Export xpub"
+ }
+ },
+ "bluetooth": {
+ "confirmUpgrade": {
+ "body": "Upgrade\nfirmware?",
+ "title": "Bluetooth"
+ },
+ "disabled": "Bluetooth\ndisabled",
+ "enabled": "Bluetooth\nenabled",
+ "setDisable": "Disable Bluetooth?",
+ "setEnable": "Enable Bluetooth?",
+ "upgrade": {
+ "fail": "Upgrade failed",
+ "progress": "Upgrading...",
+ "success": "Upgrade\nsuccessful"
+ }
+ },
+ "changePassword": {
+ "confirm": "Proceed to\nchange password?",
+ "error": "Error\n{}"
+ },
+ "cardano": {
+ "signTransaction": {
+ "alwaysAbstain": "Always Abstain",
+ "alwaysNoConfidence": "Always No Confidence",
+ "amountAsset": "Amount: {}. Asset: {}",
+ "canBeMinedFrom": "Can be mined from",
+ "canBeMinedUntil": "Can be mined until",
+ "cannotBeMined": "Transaction\ncannot be\nmined",
+ "delegateStaking": "Delegate staking for account #{} to pool {}?",
+ "delegateVoting": "Delegate voting for account #{} to type {}?",
+ "delegateVotingDrep": "Delegate voting for account #{} to type {} and drep {}?",
+ "fee": "Fee\n{}",
+ "keyHash": "Key Hash",
+ "networkWarning": "This transaction does not encode a Cardano network and may be valid on another Cardano network.",
+ "registerStakingKey": "Register staking key for account #{}?",
+ "scriptHash": "Script Hash",
+ "sendToken": "Send token",
+ "slotInEpoch": "{}\nslot {} in\nepoch {}",
+ "stopStakeDelegation": "Stop stake delegation for account #{}?",
+ "txCanceled": "Transaction\ncanceled",
+ "txConfirmed": "Transaction\nconfirmed",
+ "withdrawInStakingRewards": "Withdraw {} in staking rewards for account #{}?"
+ }
+ },
+ "ethereum": {
+ "loadingData": "Loading data...",
+ "keypath": {
+ "unusualKeypath": "Warning: unusual keypath {}. Proceed only if you know what you are doing."
+ },
+ "network": {
+ "recognizeChainId": "Only proceed if\nyou recognize\nthis chain ID.",
+ "unknownChainId": "Unknown network\nwith chain ID:\n{}"
+ },
+ "sign": {
+ "signOn": "Sign transaction on\n\n{}",
+ "tokenContract": "Token\ncontract",
+ "txCanceled": "Transaction\ncanceled",
+ "txConfirmed": "Transaction\nconfirmed",
+ "unknownAmount": "Unknown amount",
+ "unknownContract": {
+ "confirm": {
+ "body": "You will be shown\nthe raw\ntransaction data.",
+ "title": "Unknown\ncontract"
+ },
+ "confirmAdvancedStreaming": "Only proceed if you\nfully understand\nthe risks involved.",
+ "confirmAdvanced": "Only proceed if you\nunderstand exactly\nwhat the data means.",
+ "confirmStreaming": "You are signing a\ncontract interaction\nwith large data.",
+ "tooLarge": "The next value is\ntoo large to display\nin full",
+ "transactionData": "Transaction\ndata"
+ },
+ "unknownToken": "Unknown token"
+ },
+ "signMsg": {
+ "sign": "Sign",
+ "signMessage": "Sign message"
+ },
+ "signTypedMsg": {
+ "Message": "Message",
+ "domain": "Domain",
+ "empyList": "(empty list)",
+ "line": ", line {}/{}",
+ "listWithElements": "list with {} elements",
+ "messageType": "Message type",
+ "noChainIdWarning": "Typed data has no chain ID. Message is valid for every chain.",
+ "signData": "Sign data?",
+ "unknown": "Unknown"
+ }
+ },
+ "reset": {
+ "body": "Proceed to\nfactory reset?",
+ "status": "Device reset",
+ "title": "RESET"
+ },
+ "restore": {
+ "backupName": "Name: {}. ID: {}",
+ "confirmRestore": "Restore backup?",
+ "error": "Could not\nrestore backup",
+ "invalidWords": "Recovery words\ninvalid",
+ "isNow": "Is now?",
+ "passwordMismatch": "Passwords\ndo not match.\nTry again?",
+ "validWords": "Recovery words\nvalid"
+ },
+ "setMnemonicPassphrase": {
+ "disable": "Disable",
+ "enable": "Enable",
+ "optionalPassphrase": "Optional\npassphrase"
+ },
+ "setDeviceName": {
+ "title": "Name"
+ },
+ "setDeviceLanguage": {
+ "confirm": "Change language\nto {}?",
+ "english": "English",
+ "german": "German"
+ },
+ "setPassword": {
+ "repeat": "Repeat password",
+ "set": "Set password"
+ },
+ "showMnemonic": {
+ "backupCreated": "Backup created",
+ "doNotShareWarning": {
+ "body": "DO NOT share your\nrecovery words with\nanyone!",
+ "title": "Warning"
+ },
+ "unlockDevice": "Unlock device",
+ "writeDown": {
+ "body": "Please write down\nthe following words",
+ "title": "Recovery\nwords"
+ }
+ },
+ "system": {
+ "reboot": "Reboot?",
+ "rebootToBootloader": "Go to\nstartup settings?",
+ "upgrade": "Proceed to upgrade?"
+ }
+ },
+ "infoCentered": {
+ "skip": "Skip"
+ },
+ "lockscreen": "See the BitBoxApp",
+ "menu": {
+ "continue": "Continue",
+ "select": "Select"
+ },
+ "mnemonic": {
+ "backToWords": "Back to\nrecovery words",
+ "cancelRestore": "Cancel restore",
+ "choose": "Choose",
+ "confirmCancel": {
+ "body": "Cancel restore?",
+ "title": "Restore"
+ },
+ "confirmEachWord": "Please confirm\neach word",
+ "editPrevious": "Edit previous word",
+ "enterWords": "Enter {} words",
+ "howManyWords": "How many words?",
+ "incorrectWord": "Incorrect word\nTry again",
+ "invalidWord": "Invalid word\nTry again",
+ "invalidCheckRestart": "Invalid. Check\nrecovery words.\nRestart?",
+ "noneOfThem": "None of them",
+ "wordIndex": "{} of {}",
+ "wordsFollow": "{} words follow"
+ },
+ "orientation": "Tap this side",
+ "pairing": {
+ "pairingCode": "Pairing code"
+ },
+ "password": {
+ "characterWarning": {
+ "body": "Your password\n has fewer than\n 4 characters.\nContinue?",
+ "title": "WARNING"
+ },
+ "confirmCancel": "Do you really\nwant to cancel?",
+ "mismatch": "Passwords\ndo not match",
+ "repeat": "Repeat password",
+ "set": "Set password",
+ "success": "Success"
+ },
+ "sdcard": {
+ "insertToContinue": "Insert SD card\nto continue"
+ },
+ "transaction": {
+ "confirmSwap": {
+ "from": "{} from",
+ "to": "{} to"
+ },
+ "confirmTransaction": {
+ "amount": "Amount",
+ "fee": "Fee",
+ "recipient": "Recipient",
+ "total": "Total"
+ },
+ "highFeeWarning": {
+ "body": "Fee is {}%\nof the send amount.\nProceed?",
+ "bodyTotalInputs": "Fee is {}%\nof all inputs.\nProceed?",
+ "title": "High fee"
+ }
+ },
+ "u2f": {
+ "auth": "U2F auth",
+ "initializeWithBitBoxApp": "Initialize with BitBoxApp\nto use U2F",
+ "refreshWebpage": "Refresh webpage",
+ "register": "U2F register",
+ "unknownSite": "Unknown site:",
+ "use": "Use U2F?"
+ },
+ "paymentRequest": {
+ "swap": "Swap"
+ },
+ "verifyMessage": {
+ "dataHex": "{}\ndata (hex)",
+ "pageTitle": "{} {}/{}"
+ },
+ "unlock": {
+ "enterPassword": "Enter password",
+ "keystoreUnlockFailed": "keystore unlock failed\n{}",
+ "passphrase": {
+ "confirm": "Confirm",
+ "confirmEmpty": "Use empty\npassphrase?",
+ "doubleCheck": "You will be asked to\nvisually confirm your\npassphrase now.",
+ "title": "Optional passphrase",
+ "tryAgain": "Please try again"
+ },
+ "remainingAttempts": {
+ "last": "This is your LAST\npassword attempt.\nDevice will reset\nif password is wrong.",
+ "other": "You have {}\npassword attempts\nleft.",
+ "title": "WARNING"
+ },
+ "wrongPassword": {
+ "base": "Wrong password"
+ }
+ }
+}
### src/memory/memory.c
@@ -99,7 +99,7 @@ typedef union {
uint8_t bitmask; // inverse bitmask, BITMASK_* bits
uint8_t failed_unlock_attempts; // starts at 0xFF (0 failed attempts), counting downwards
uint8_t password_stretch_algo; // see `memory_password_stretch_algo_t`.
- uint8_t reserved[1];
+ uint8_t device_language; // see `memory_device_language_t`. 0xFF defaults to English.
uint8_t noise_static_private_key[32]; // CURVE25519
uint8_t noise_remote_static_pubkeys[5][NOISE_PUBKEY_SIZE]; // 5 pubkey slots
uint8_t salt_root[32];
@@ -355,6 +355,30 @@ void memory_get_device_name(char* name_out)
}
}
+bool memory_set_device_language(memory_device_language_t language)
+{
+ if (language != MEMORY_DEVICE_LANGUAGE_EN && language != MEMORY_DEVICE_LANGUAGE_DE) {
+ return false;
+ }
+ chunk_1_t chunk = {0};
+ CLEANUP_CHUNK(chunk);
+ _read_chunk(CHUNK_1, chunk_bytes);
+ chunk.fields.device_language = (uint8_t)language;
+ return _write_chunk(CHUNK_1, chunk.bytes);
+}
+
+memory_device_language_t memory_get_device_language(void)
+{
+ const chunk_1_t* chunk = _chunk_1();
+ switch (chunk->fields.device_language) {
+ case MEMORY_DEVICE_LANGUAGE_DE:
+ return MEMORY_DEVICE_LANGUAGE_DE;
+ case MEMORY_DEVICE_LANGUAGE_EN:
+ default:
+ return MEMORY_DEVICE_LANGUAGE_EN;
+ }
+}
+
bool memory_set_seed_birthdate(uint32_t timestamp)
{
chunk_1_t chunk = {0};
### src/memory/memory.h
@@ -34,6 +34,11 @@ typedef enum {
MEMORY_PASSWORD_STRETCH_ALGO_V1,
} memory_password_stretch_algo_t;
+typedef enum {
+ MEMORY_DEVICE_LANGUAGE_EN = 0,
+ MEMORY_DEVICE_LANGUAGE_DE = 1,
+} memory_device_language_t;
+
typedef struct {
void (*const random_32_bytes)(uint8_t* buf_out);
} memory_interface_functions_t;
@@ -81,6 +86,9 @@ USE_RESULT bool memory_set_device_name(const char* name, size_t name_len);
// The name is cached in RAM, so the same random name is returned until reboot.
void memory_get_device_name(char* name_out);
+USE_RESULT bool memory_set_device_language(memory_device_language_t language);
+memory_device_language_t memory_get_device_language(void);
+
/**
* Sets the seed's birthdate to a unix timestamp.
* @param[in] timestamp The seed birthdate.
### src/rust/Cargo.lock
@@ -210,6 +210,14 @@ dependencies = [
"zeroize",
]
+[[package]]
+name = "bitbox-i18n"
+version = "0.1.0"
+dependencies = [
+ "bitbox-hal",
+ "serde_json",
+]
+
[[package]]
name = "bitbox-lvgl"
version = "0.1.0"
@@ -348,6 +356,7 @@ dependencies = [
"bitbox-bytequeue",
"bitbox-framed-serial-link",
"bitbox-hal",
+ "bitbox-i18n",
"bitbox-noise",
"bitbox-securechip",
"bitbox-securechip-sys",
@@ -377,6 +386,7 @@ dependencies = [
"bitbox-da14531",
"bitbox-executor",
"bitbox-hal",
+ "bitbox-i18n",
"bitbox-noise",
"bitbox-platform-host",
"bitbox-proto",
### src/rust/Cargo.toml
@@ -20,6 +20,7 @@ members = [
"bitbox-executor",
"bitbox-framed-serial-link",
"bitbox-hal",
+ "bitbox-i18n",
"bitbox-lvgl",
"bitbox-lvgl-sys",
"bitbox-mcu-stm32u5",
### src/rust/bitbox-hal/src/memory.rs
@@ -36,6 +36,12 @@ pub enum Platform {
BitBox03,
}
+#[derive(Copy, Clone, Debug, Eq, PartialEq)]
+pub enum Language {
+ English,
+ German,
+}
+
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub enum Error {
InvalidInput,
@@ -82,6 +88,8 @@ pub trait Memory {
fn get_device_name(&mut self) -> String;
/// `name` must be non-empty and at most [`DEVICE_NAME_MAX_LEN`] bytes long.
fn set_device_name(&mut self, name: &str) -> Result<(), Error>;
+ fn get_device_language(&mut self) -> Language;
+ fn set_device_language(&mut self, language: Language) -> Result<(), Error>;
fn is_mnemonic_passphrase_enabled(&mut self) -> bool;
fn set_mnemonic_passphrase_enabled(&mut self, enabled: bool) -> Result<(), ()>;
fn set_seed_birthdate(&mut self, timestamp: u32) -> Result<(), ()>;
### src/rust/bitbox-i18n/Cargo.toml
@@ -0,0 +1,14 @@
+# SPDX-License-Identifier: Apache-2.0
+
+[package]
+name = "bitbox-i18n"
+version = "0.1.0"
+authors = ["Shift Crypto AG <support@bitbox.swiss>"]
+edition = "2024"
+license = "Apache-2.0"
+
+[dependencies]
+bitbox-hal = { path = "../bitbox-hal" }
+
+[build-dependencies]
+serde_json = { workspace = true }
### src/rust/bitbox-i18n/build.rs
@@ -0,0 +1,183 @@
+// SPDX-License-Identifier: Apache-2.0
+
+use std::collections::BTreeMap;
+use std::env;
+use std::fs;
+use std::path::{Path, PathBuf};
+
+const FNV1A64_OFFSET: u64 = 0xcbf29ce484222325;
+const FNV1A64_PRIME: u64 = 0x100000001b3;
+const SOURCE_LOCALE: &str = "en";
+const TRANSLATION_LOCALES: &[&str] = &["de"];
+
+fn main() {
+ let locales_dir = locales_dir();
+ let en_path = locales_dir.join(SOURCE_LOCALE).join("firmware.json");
+
+ println!("cargo::rerun-if-changed={}", en_path.display());
+
+ let english = read_flattened_json(&en_path);
+ let mut generated = String::from("// @generated by build.rs\n\n");
+ let mut supported_languages = vec![SOURCE_LOCALE];
+ for &locale in TRANSLATION_LOCALES {
+ let path = locales_dir.join(locale).join("firmware.json");
+ println!("cargo::rerun-if-changed={}", path.display());
+ let translations = read_flattened_json(&path);
+ let entries = locale_entries(&english, &translations, &path);
+ generated.push_str(&generated_table(locale, &entries));
+ supported_languages.push(locale);
+ }
+
+ generated.push_str(&generated_valid_en_hashes(&english));
+ generated.push_str(&format!(
+ "\npub const SUPPORTED_LANGUAGES: &[&str] = &{supported_languages:?};\n"
+ ));
+
+ let out = PathBuf::from(env::var("OUT_DIR").expect("OUT_DIR not set")).join("i18n.rs");
+ fs::write(out, generated).expect("failed to write generated i18n table");
+}
+
+fn locales_dir() -> PathBuf {
+ Path::new(&env::var("CARGO_MANIFEST_DIR").expect("CARGO_MANIFEST_DIR not set"))
+ .join("../../i18n/locales")
+}
+
+fn read_flattened_json(path: &Path) -> BTreeMap<String, String> {
+ let data = fs::read_to_string(path)
+ .unwrap_or_else(|err| panic!("failed to read locale file {}: {err}", path.display()));
+ let value: serde_json::Value = serde_json::from_str(&data)
+ .unwrap_or_else(|err| panic!("failed to parse locale file {}: {err}", path.display()));
+
+ let mut flattened = BTreeMap::new();
+ flatten_json("", &value, &mut flattened, path);
+ flattened
+}
+
+fn flatten_json(
+ prefix: &str,
+ value: &serde_json::Value,
+ out: &mut BTreeMap<String, String>,
+ path: &Path,
+) {
+ match value {
+ serde_json::Value::Object(map) => {
+ for (key, value) in map {
+ let key = if prefix.is_empty() {
+ key.to_owned()
+ } else {
+ format!("{prefix}.{key}")
+ };
+ flatten_json(&key, value, out, path);
+ }
+ }
+ serde_json::Value::String(value) => {
+ if out.insert(prefix.to_owned(), value.to_owned()).is_some() {
+ panic!("duplicate flattened key '{}' in {}", prefix, path.display());
+ }
+ }
+ _ => panic!(
+ "locale file {} contains a non-string leaf at key '{}'",
+ path.display(),
+ prefix
+ ),
+ }
+}
+
+fn locale_entries(
+ english: &BTreeMap<String, String>,
+ locale: &BTreeMap<String, String>,
+ locale_path: &Path,
+) -> Vec<(String, String)> {
+ let mut by_english = BTreeMap::<String, String>::new();
+ for key in locale.keys() {
+ if !english.contains_key(key) {
+ panic!(
+ "locale file {} contains key '{}' which does not exist in English",
+ locale_path.display(),
+ key
+ );
+ }
+ }
+ for (key, english) in english {
+ let translated = locale.get(key).unwrap_or_else(|| {
+ panic!(
+ "locale file {} is missing English key '{}'",
+ locale_path.display(),
+ key
+ )
+ });
+ if placeholder_count(english) != placeholder_count(translated) {
+ panic!(
+ "placeholder mismatch in {} at key '{}': {:?} vs {:?}",
+ locale_path.display(),
+ key,
+ english,
+ translated
+ );
+ }
+ match by_english.get(english) {
+ Some(existing) if existing != translated => {
+ panic!(
+ "locale file {} has conflicting translations for {:?}: {:?} and {:?}",
+ locale_path.display(),
+ english,
+ existing,
+ translated
+ );
+ }
+ Some(_) => {}
+ None => {
+ by_english.insert(english.to_owned(), translated.to_owned());
+ }
+ }
+ }
+ by_english.into_iter().collect()
+}
+
+fn placeholder_count(value: &str) -> usize {
+ value.matches("{}").count() + value.matches("{:?}").count()
+}
+
+fn generated_table(locale: &str, entries: &[(String, String)]) -> String {
+ let mut out = format!(
+ "pub(crate) const {}_TRANSLATIONS: &[(u64, &str)] = &[\n",
+ locale.to_ascii_uppercase()
+ );
+ let mut by_key = BTreeMap::<u64, (&str, &str)>::new();
+ for (english, translated) in entries {
+ let key = translation_key(english);
+ if let Some((existing, _)) = by_key.insert(key, (english.as_str(), translated.as_str())) {
+ panic!("translation key collision between {existing:?} and {english:?}");
+ }
+ }
+ for (key, (_, translated)) in by_key {
+ out.push_str(&format!(" (0x{key:016x}, {translated:?}),\n"));
+ }
+ out.push_str("];\n");
+ out
+}
+
+fn generated_valid_en_hashes(english: &BTreeMap<String, String>) -> String {
+ let mut hashes: Vec<u64> = english
+ .values()
+ .map(|value| translation_key(value))
+ .collect();
+ hashes.sort_unstable();
+ hashes.dedup();
+
+ let mut out = String::from("\npub(crate) const VALID_EN_HASHES: &[u64] = &[\n");
+ for hash in hashes {
+ out.push_str(&format!(" 0x{hash:016x},\n"));
+ }
+ out.push_str("];\n");
+ out
+}
+
+fn translation_key(value: &str) -> u64 {
+ let mut hash = FNV1A64_OFFSET;
+ for byte in value.as_bytes() {
+ hash ^= u64::from(*byte);
+ hash = hash.wrapping_mul(FNV1A64_PRIME);
+ }
+ hash
+}
### src/rust/bitbox-i18n/src/lib.rs
@@ -0,0 +1,199 @@
+// SPDX-License-Identifier: Apache-2.0
+
+#![no_std]
+
+extern crate alloc;
+
+use alloc::borrow::Cow;
+use alloc::string::String;
+use bitbox_hal::memory::Language;
+
+include!(concat!(env!("OUT_DIR"), "/i18n.rs"));
+
+const FNV1A64_OFFSET: u64 = 0xcbf29ce484222325;
+const FNV1A64_PRIME: u64 = 0x100000001b3;
+
+pub fn language_from_code(code: &str) -> Option<Language> {
+ let code = code.as_bytes();
+ if code.len() < 2 {
+ return None;
+ }
+ if code.len() > 2 && code[2] != b'-' && code[2] != b'_' {
+ return None;
+ }
+
+ match (code[0].to_ascii_lowercase(), code[1].to_ascii_lowercase()) {
+ (b'e', b'n') => Some(Language::English),
+ (b'd', b'e') => Some(Language::German),
+ _ => None,
+ }
+}
+
+pub fn language_code(language: Language) -> &'static str {
+ match language {
+ Language::English => "en",
+ Language::German => "de",
+ }
+}
+
+pub fn translate<'a>(language: Language, english: &'a str) -> Cow<'a, str> {
+ match language {
+ Language::English => Cow::Borrowed(english),
+ Language::German => translate_from_table(english, DE_TRANSLATIONS)
+ .map(Cow::Borrowed)
+ .unwrap_or(Cow::Borrowed(english)),
+ }
+}
+
+pub fn format(language: Language, english: &'static str, args: &[&str]) -> String {
+ let translated = translate(language, english);
+ format_pattern(&translated, args)
+}
+
+pub const fn is_translatable(english: &str) -> bool {
+ let key = translation_key(english);
+ let mut lo = 0;
+ let mut hi = VALID_EN_HASHES.len();
+ while lo < hi {
+ let mid = lo + (hi - lo) / 2;
+ let value = VALID_EN_HASHES[mid];
+ if value == key {
+ return true;
+ } else if value < key {
+ lo = mid + 1;
+ } else {
+ hi = mid;
+ }
+ }
+ false
+}
+
+fn translate_from_table<'a>(english: &str, table: &'a [(u64, &str)]) -> Option<&'a str> {
+ let key = translation_key(english);
+ table
+ .binary_search_by_key(&key, |(source_key, _)| *source_key)
+ .ok()
+ .map(|index| table[index].1)
+}
+
+const fn translation_key(value: &str) -> u64 {
+ let bytes = value.as_bytes();
+ let mut hash = FNV1A64_OFFSET;
+ let mut i = 0;
+ while i < bytes.len() {
+ hash ^= bytes[i] as u64;
+ hash = hash.wrapping_mul(FNV1A64_PRIME);
+ i += 1;
+ }
+ hash
+}
+
+fn format_pattern(pattern: &str, args: &[&str]) -> String {
+ let mut out =
+ String::with_capacity(pattern.len() + args.iter().map(|arg| arg.len()).sum::<usize>());
+ let mut rest = pattern;
+ let mut args = args.iter();
+
+ while let Some((start, len)) = next_placeholder(rest) {
+ out.push_str(&rest[..start]);
+ out.push_str(args.next().expect("not enough format arguments"));
+ rest = &rest[start + len..];
+ }
+ assert!(args.next().is_none(), "too many format arguments");
+ out.push_str(rest);
+ out
+}
+
+fn next_placeholder(value: &str) -> Option<(usize, usize)> {
+ match (value.find("{}"), value.find("{:?}")) {
+ (Some(a), Some(b)) if a <= b => Some((a, 2)),
+ (Some(_), Some(b)) => Some((b, 4)),
+ (Some(a), None) => Some((a, 2)),
+ (None, Some(b)) => Some((b, 4)),
+ (None, None) => None,
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn test_supported_languages() {
+ for (index, &code) in SUPPORTED_LANGUAGES.iter().enumerate() {
+ assert!(!SUPPORTED_LANGUAGES[..index].contains(&code));
+ assert_eq!(language_code(language_from_code(code).unwrap()), code);
+ }
+ }
+
+ #[test]
+ fn test_language_from_code() {
+ assert_eq!(language_from_code("en"), Some(Language::English));
+ assert_eq!(language_from_code("EN-us"), Some(Language::English));
+ assert_eq!(language_from_code("de"), Some(Language::German));
+ assert_eq!(language_from_code("de_CH"), Some(Language::German));
+ assert_eq!(language_from_code("dex"), None);
+ assert_eq!(language_from_code("it"), None);
+ }
+
+ #[test]
+ fn test_translate() {
+ assert_eq!(
+ translate(Language::English, "Proceed to upgrade?").as_ref(),
+ "Proceed to upgrade?"
+ );
+ assert_eq!(
+ translate(Language::German, "Proceed to upgrade?").as_ref(),
+ "Upgrade fortsetzen?"
+ );
+ assert_eq!(
+ translate(Language::German, "Not translated").as_ref(),
+ "Not translated"
+ );
+ }
+
+ #[test]
+ fn test_generated_table_sorted() {
+ assert!(DE_TRANSLATIONS.windows(2).all(|pair| pair[0].0 < pair[1].0));
+ }
+
+ #[test]
+ fn test_is_translatable() {
+ assert!(is_translatable("Proceed to upgrade?"));
+ assert!(!is_translatable("Proceed to upgrade"));
+ assert!(!is_translatable("definitely not a source string"));
+ }
+
+ #[test]
+ fn test_format() {
+ assert_eq!(
+ format(
+ Language::German,
+ "Fee is {}%\nof the send amount.\nProceed?",
+ &["17.0"],
+ ),
+ "Gebühr: 17.0%\ndes Sendebetrags.\nFortfahren?"
+ );
+ }
+
+ #[test]
+ fn test_format_pattern() {
+ assert_eq!(format_pattern("No arguments", &[]), "No arguments");
+ assert_eq!(
+ format_pattern("{} / {:?} / {}", &["first", "second", "third"]),
+ "first / second / third"
+ );
+ }
+
+ #[test]
+ #[should_panic(expected = "not enough format arguments")]
+ fn test_format_pattern_too_few_arguments() {
+ format_pattern("Fee is {}%", &[]);
+ }
+
+ #[test]
+ #[should_panic(expected = "too many format arguments")]
+ fn test_format_pattern_too_many_arguments() {
+ format_pattern("Fee is {}%", &["17.0", "unexpected"]);
+ }
+}
### src/rust/bitbox-lvgl-sys/build.rs
@@ -258,6 +258,7 @@ fn main() -> Result<(), &'static str> {
}
lvgl_build.warnings(false);
lvgl_build.extra_warnings(false);
+ lvgl_build.flag_if_supported("-Wno-psabi");
lvgl_build.debug(debug);
lvgl_build.compile("lvgl");
### src/rust/bitbox-platform-host/src/memory.rs
@@ -4,8 +4,8 @@ use alloc::string::String;
use alloc::vec::Vec;
use bitbox_hal::memory::{
- BleFirmwareSlot, BleMetadata, Error, OptigaConfigVersion, PasswordStretchAlgo, Platform,
- SecurechipType,
+ BleFirmwareSlot, BleMetadata, Error, Language, OptigaConfigVersion, PasswordStretchAlgo,
+ Platform, SecurechipType,
};
pub struct FakeMemory {
@@ -26,6 +26,7 @@ pub struct FakeMemory {
noise_static_private_key: [u8; 32],
noise_remote_static_pubkeys: Vec<[u8; 32]>,
device_name: Option<String>,
+ device_language: Language,
salt_root: [u8; 32],
attestation_device_pubkey: Option<[u8; 64]>,
attestation_certificate: Option<[u8; 64]>,
@@ -74,6 +75,7 @@ impl FakeMemory {
noise_static_private_key: make_noise_static_private_key(0),
noise_remote_static_pubkeys: Vec::new(),
device_name: None,
+ device_language: Language::English,
salt_root: *b"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
attestation_device_pubkey: None,
attestation_certificate: None,
@@ -207,6 +209,15 @@ impl bitbox_hal::Memory for FakeMemory {
Ok(())
}
+ fn get_device_language(&mut self) -> Language {
+ self.device_language
+ }
+
+ fn set_device_language(&mut self, language: Language) -> Result<(), Error> {
+ self.device_language = language;
+ Ok(())
+ }
+
fn is_mnemonic_passphrase_enabled(&mut self) -> bool {
self.mnemonic_passphrase_enabled
}
@@ -268,6 +279,7 @@ impl bitbox_hal::Memory for FakeMemory {
make_noise_static_private_key(self.noise_static_private_key_generation);
self.noise_remote_static_pubkeys = Vec::new();
self.device_name = None;
+ self.device_language = Language::English;
self.multisig_entries = Vec::new();
Ok(())
}
### src/rust/bitbox-proto/src/generated/shiftcrypto.bitbox02.rs
@@ -124,6 +124,12 @@ pub struct DeviceInfoResponse {
/// Marketing version of the installed stage1 bootloader. Not present on legacy bootloaders.
#[prost(string, optional, tag = "9")]
pub bootloader_version: ::core::option::Option<::prost::alloc::string::String>,
+ /// Current UI language code, e.g. "en" or "de". Empty on firmware without language support.
+ #[prost(string, tag = "10")]
+ pub language: ::prost::alloc::string::String,
+ /// Empty on firmware without supported-language reporting.
+ #[prost(string, repeated, tag = "11")]
+ pub supported_languages: ::prost::alloc::vec::Vec<::prost::alloc::string::String>,
}
/// Nested message and enum types in `DeviceInfoResponse`.
pub mod device_info_response {
### src/rust/bitbox02-rust-c/src/async_usb.rs
@@ -5,12 +5,13 @@
extern crate alloc;
use crate::HalImpl;
+use alloc::boxed::Box;
use alloc::vec::Vec;
use bitbox02_rust::async_usb::{on_next_request, spawn, waiting_for_next_request};
async fn process_packet_with_hal(usb_in: Vec<u8>) -> Vec<u8> {
let mut hal = HalImpl::new();
- bitbox02_rust::hww::process_packet(&mut hal, usb_in).await
+ Box::pin(bitbox02_rust::hww::process_packet(&mut hal, usb_in)).await
}
#[unsafe(no_mangle)]
### src/rust/bitbox02-rust/Cargo.toml
@@ -17,6 +17,7 @@ doctest = false
bitbox-proto = { path = "../bitbox-proto" }
bitbox-hal = { path = "../bitbox-hal" }
bitbox-core-utils = { path = "../bitbox-core-utils" }
+bitbox-i18n = { path = "../bitbox-i18n" }
bitbox-da14531 = { path = "../bitbox-da14531" }
bitbox02 = { path = "../bitbox02" }
bitbox-platform-host = { path = "../bitbox-platform-host", optional = true }
### src/rust/bitbox02-rust/src/hww.rs
@@ -256,7 +256,7 @@ mod tests {
#[async_test::test]
async fn test_cant_unlock() {
assert_eq!(
- process_packet(&mut TestingHal::new(), vec![OP_UNLOCK]).await,
+ Box::pin(process_packet(&mut TestingHal::new(), vec![OP_UNLOCK])).await,
[OP_STATUS_FAILURE_UNINITIALIZED].to_vec()
);
}
@@ -476,7 +476,7 @@ mod tests {
.ui
.set_enter_string(Box::new(|_params| Ok("password".into())));
assert_eq!(
- process_packet(&mut mock_hal, vec![OP_UNLOCK]).await,
+ Box::pin(process_packet(&mut mock_hal, vec![OP_UNLOCK])).await,
[OP_STATUS_SUCCESS].to_vec()
);
assert!(!crate::keystore::is_locked());
### src/rust/bitbox02-rust/src/hww/api.rs
@@ -27,6 +27,7 @@ mod reset;
mod restore;
mod rootfingerprint;
mod sdcard;
+mod set_device_language;
mod set_device_name;
mod set_mnemonic_passphrase_enabled;
mod set_password;
@@ -165,6 +166,7 @@ async fn process_api(hal: &mut impl crate::hal::Hal, request: &Request) -> Resul
Request::Reboot(request) => system::reboot_to_bootloader(hal, request).await,
Request::DeviceInfo(_) => device_info::process(hal).await,
Request::DeviceName(request) => set_device_name::process(hal, request).await,
+ Request::DeviceLanguage(request) => set_device_language::process(hal, request).await,
Request::SetPassword(request) => set_password::process(hal, request).await,
Request::ChangePassword(_) => change_password::process(hal).await,
Request::Reset(_) => reset::process(hal).await,
### src/rust/bitbox02-rust/src/hww/api/backup.rs
@@ -9,6 +9,7 @@ use pb::response::Response;
use crate::backup;
use crate::hal::{Memory, Sd, Ui};
+use crate::i18n::I18n as _;
use crate::workflow::unlock;
pub async fn check(
@@ -24,7 +25,8 @@ pub async fn check(
let (backup_data, metadata) = backup::load(hal, &id).await?;
if seed.as_slice() != backup_data.get_seed() {
if !silent {
- hal.ui().status("Backup missing\nor invalid", false).await;
+ let status = crate::tr!(hal, "Backup missing\nor invalid");
+ hal.ui().status(&status, false).await;
}
return Err(Error::Generic);
}
@@ -33,26 +35,29 @@ pub async fn check(
let ui = hal.ui();
backup::sanitize_name(&metadata.name, |c| ui.has_glyph(Font::Regular11, c))
};
+ let title = crate::tr!(hal, "Name?");
hal.ui()
.confirm(&ConfirmParams {
- title: "Name?",
+ title: &title,
body: &name,
scrollable: true,
accept_is_nextarrow: true,
..Default::default()
})
.await?;
+ let title = crate::tr!(hal, "ID?");
hal.ui()
.confirm(&ConfirmParams {
- title: "ID?",
+ title: &title,
body: &id,
scrollable: true,
..Default::default()
})
.await?;
- hal.ui().status("Backup valid", true).await;
+ let status = crate::tr!(hal, "Backup valid");
+ hal.ui().status(&status, true).await;
}
Ok(Response::CheckBackup(pb::CheckBackupResponse { id }))
}
@@ -72,19 +77,23 @@ pub async fn create(
timezone_offset,
}: &pb::CreateBackupRequest,
) -> Result<Response, Error> {
+ let title = crate::tr!(hal, "Is today?");
+ let body = hal
+ .tr_datetime(timestamp, timezone_offset, true)
+ .map_err(|_| Error::InvalidInput)?;
hal.ui()
.confirm(&ConfirmParams {
- title: "Is today?",
- body: &util::datetime::format_datetime(timestamp, timezone_offset, true)
- .map_err(|_| Error::InvalidInput)?,
+ title: &title,
+ body: &body,
..Default::default()
})
.await?;
+ let body = crate::tr!(hal, "Create backup?");
hal.ui()
.confirm(&ConfirmParams {
title: "",
- body: "Create backup?",
+ body: &body,
longtouch: true,
..Default::default()
})
@@ -102,7 +111,8 @@ pub async fn create(
let is_initialized = hal.memory().is_initialized();
let seed = if is_initialized {
- unlock::unlock_keystore(hal, "Unlock device", CanCancel::Yes).await?
+ let title = crate::tr!(hal, "Unlock device");
+ unlock::unlock_keystore(hal, &title, CanCancel::Yes).await?
} else {
let seed = crate::keystore::copy_seed(hal).await?;
// Yield now to give executor a chance to process USB/BLE communication, as copy_seed() causes
@@ -133,13 +143,15 @@ pub async fn create(
// process again.
let _ = hal.memory().set_initialized();
- hal.ui().status("Backup created", true).await;
+ let status = crate::tr!(hal, "Backup created");
+ hal.ui().status(&status, true).await;
Ok(Response::Success(pb::Success {}))
}
Err(err) => {
- let msg = format!(
+ let msg = crate::tr_format!(
+ hal,
"Backup not created\nPlease contact\nsupport ({})",
- backup::format_error(&err)
+ &[backup::format_error(&err)],
);
hal.ui().status(&msg, false).await;
Err(Error::Generic)
@@ -224,6 +236,50 @@ mod tests {
);
}
+ #[async_test::test]
+ pub async fn test_create_german_date() {
+ const TIMESTAMP: u32 = 1779964200;
+
+ mock_unlocked();
+
+ let mut mock_hal = TestingHal::new();
+ mock_hal
+ .memory
+ .set_device_language(bitbox_hal::memory::Language::German)
+ .unwrap();
+ mock_hal.sd.inserted = Some(true);
+ assert_eq!(
+ create(
+ &mut mock_hal,
+ &pb::CreateBackupRequest {
+ timestamp: TIMESTAMP,
+ timezone_offset: 0,
+ }
+ )
+ .await,
+ Ok(Response::Success(pb::Success {}))
+ );
+ assert_eq!(
+ mock_hal.ui.screens,
+ vec![
+ Screen::Confirm {
+ title: "Ist heute?".into(),
+ body: "Do 28.05.2026".into(),
+ longtouch: false
+ },
+ Screen::Confirm {
+ title: "".into(),
+ body: "Backup erstellen?".into(),
+ longtouch: true
+ },
+ Screen::Status {
+ title: "Backup erstellt".into(),
+ success: true
+ }
+ ]
+ );
+ }
+
/// Test backup creation on a initialized keystore. The sdcard does not contain the backup yet.
#[async_test::test]
pub async fn test_create_initialized_new() {
### src/rust/bitbox02-rust/src/hww/api/bip85.rs
@@ -3,13 +3,16 @@
use super::Error;
use super::pb;
use crate::hal::ui::ConfirmParams;
+use crate::i18n::I18n as _;
use pb::response::Response;
+use crate::hal::Memory;
use crate::hal::Ui;
use crate::keystore;
+use alloc::string::ToString;
use alloc::vec::Vec;
/// Processes a BIP-85 API call.
@@ -33,50 +36,59 @@ pub async fn process(
async fn process_bip39(hal: &mut impl crate::hal::Hal) -> Result<(), Error> {
use crate::hal::ui::{CanCancel, TrinaryChoice};
+ let title = crate::tr!(hal, "BIP-85");
+ let body = crate::tr!(hal, "Derive BIP-39\nmnemonic?");
hal.ui()
.confirm(&ConfirmParams {
- title: "BIP-85",
- body: "Derive BIP-39\nmnemonic?",
+ title: &title,
+ body: &body,
accept_is_nextarrow: true,
..Default::default()
})
.await?;
+ let title = crate::tr!(hal, "BIP-85");
+ let body = crate::tr!(
+ hal,
+ "This is an advanced feature. Proceed only if you know what you are doing."
+ );
hal.ui()
.confirm(&ConfirmParams {
- title: "BIP-85",
- body: "This is an advanced feature. Proceed only if you know what you are doing.",
+ title: &title,
+ body: &body,
scrollable: true,
accept_is_nextarrow: true,
..Default::default()
})
.await?;
+ let how_many_words = crate::tr!(hal, "How many words?");
let num_words: u32 = match hal
.ui()
- .trinary_choice("How many words?", Some("12"), None, Some("24"))
+ .trinary_choice(&how_many_words, Some("12"), None, Some("24"))
.await
{
TrinaryChoice::Left => 12,
TrinaryChoice::Middle => unreachable!(),
TrinaryChoice::Right => 24,
};
- hal.ui().status(&format!("{} words", num_words), true).await;
+ let status = crate::tr_format!(hal, "{} words", &[&num_words.to_string()]);
+ hal.ui().status(&status, true).await;
// Pick index. The first few are quick-access. "More" leads to a full number input keyboard.
- let index: u32 = match hal
- .ui()
- .menu(&["0", "1", "2", "3", "4", "More"], Some("Select index"))
- .await?
- {
+ let more = crate::tr!(hal, "More");
+ let select_index = crate::tr!(hal, "Select index");
+ let words = ["0", "1", "2", "3", "4", more.as_ref()];
+ let index: u32 = match hal.ui().menu(&words, Some(&select_index)).await? {
i @ 0..=4 => i.into(),
5 => {
+ let title = crate::tr!(hal, "Enter index");
let number_string = hal
.ui()
.enter_string(
&crate::hal::ui::EnterStringParams {
- title: "Enter index",
+ title: &title,
number_input: true,
longtouch: true,
..Default::default()
@@ -88,19 +100,22 @@ async fn process_bip39(hal: &mut impl crate::hal::Hal) -> Result<(), Error> {
match number_string.as_str().parse::<u32>() {
Ok(i) if i < util::bip32::HARDENED => i,
_ => {
- hal.ui().status("Invalid index", false).await;
+ let status = crate::tr!(hal, "Invalid index");
+ hal.ui().status(&status, false).await;
return Err(Error::InvalidInput);
}
}
}
6.. => panic!("bip85 error"),
};
- hal.ui().status(&format!("Index: {}", index), true).await;
+ let status = crate::tr_format!(hal, "Index: {}", &[&index.to_string()]);
+ hal.ui().status(&status, true).await;
+ let title = crate::tr!(hal, "Keypath");
hal.ui()
.confirm(&ConfirmParams {
- title: "Keypath",
+ title: &title,
body: &format!("m/83696968'/39'/0'/{}'/{}'", num_words, index),
scrollable: true,
longtouch: true,
@@ -111,11 +126,13 @@ async fn process_bip39(hal: &mut impl crate::hal::Hal) -> Result<(), Error> {
let mnemonic = keystore::bip85_bip39(hal, num_words, index).await?;
let words: Vec<&str> = mnemonic.split(' ').collect();
{
+ let language = hal.memory().get_device_language();
let crate::hal::HalSubsystems { ui, random, .. } = hal.as_mut();
- crate::workflow::mnemonic::show_and_confirm_mnemonic(ui, random, &words).await?;
+ crate::workflow::mnemonic::show_and_confirm_mnemonic(ui, random, &words, language).await?;
}
- hal.ui().status("Finished", true).await;
+ let status = crate::tr!(hal, "Finished");
+ hal.ui().status(&status, true).await;
Ok(())
}
@@ -132,10 +149,11 @@ async fn process_ln(
if account_number != 0 {
return Err(Error::InvalidInput);
}
+ let body = crate::tr!(hal, "Create\nLightning wallet\non host device?");
hal.ui()
.confirm(&ConfirmParams {
title: "",
- body: "Create\nLightning wallet\non host device?",
+ body: &body,
longtouch: true,
..Default::default()
})
### src/rust/bitbox02-rust/src/hww/api/bitcoin.rs
@@ -1,6 +1,7 @@
// SPDX-License-Identifier: Apache-2.0
use crate::hal::ui::ConfirmParams;
+use crate::i18n::I18n as _;
#[cfg(not(feature = "app-bitcoin"))]
compile_error!("Bitcoin code is being compiled even though the app-bitcoin feature is not enabled");
@@ -22,6 +23,8 @@ use super::pb;
use crate::hal::Ui;
+use alloc::string::ToString;
+
use util::bip32::HARDENED;
use crate::keystore;
@@ -99,13 +102,20 @@ async fn xpub(
keypath::validate_xpub(keypath, params.bip44_coin, params.taproot_support).is_err();
if is_unusual {
// For unusual keypaths, we allow export after a confirmation.
+ let title = if display {
+ "xpub".into()
+ } else {
+ crate::tr!(hal, "Export xpub")
+ };
+ let body = crate::tr_format!(
+ hal,
+ "Warning: unusual keypath {}. Proceed only if you know what you are doing.",
+ &[&util::bip32::to_string(keypath)],
+ );
hal.ui()
.confirm(&ConfirmParams {
- title: if display { "xpub" } else { "Export xpub" },
- body: &format!(
- "Warning: unusual keypath {}. Proceed only if you know what you are doing.",
- util::bip32::to_string(keypath)
- ),
+ title: &title,
+ body: &body,
scrollable: true,
longtouch: true,
..Default::default()
@@ -120,9 +130,17 @@ async fn xpub(
let title = if is_unusual {
"".into()
} else if keypath == [45 + HARDENED] {
- format!("{}\nat\n{}", params.name, util::bip32::to_string(keypath))
+ crate::tr_format!(
+ hal,
+ "{}\nat\n{}",
+ &[params.name, &util::bip32::to_string(keypath)],
+ )
} else {
- format!("{}\naccount #{}", params.name, keypath[2] - HARDENED + 1)
+ crate::tr_format!(
+ hal,
+ "{}\naccount #{}",
+ &[params.name, &(keypath[2] - HARDENED + 1).to_string()],
+ )
};
let confirm_params = ConfirmParams {
@@ -222,9 +240,9 @@ pub async fn address_multisig(
Some(name) => name,
None => return Err(Error::InvalidInput),
};
- let title = "Receive to";
+ let title = crate::tr!(hal, "Receive to");
if display {
- multisig::confirm(hal, title, coin_params, &name, multisig).await?;
+ multisig::confirm(hal, &title, coin_params, &name, multisig).await?;
}
let address = common::Payload::from_multisig(
coin_params,
@@ -237,7 +255,7 @@ pub async fn address_multisig(
let address_formatted = util::strings::format_address(&address);
hal.ui()
.confirm(&ConfirmParams {
- title,
+ title: &title,
body: &address_formatted,
scrollable: true,
..Default::default()
@@ -264,11 +282,11 @@ async fn address_policy(
let name = parsed.name(hal, coin_params)?.ok_or(Error::InvalidInput)?;
- let title = "Receive to";
+ let title = crate::tr!(hal, "Receive to");
if display {
parsed
- .confirm(hal, title, coin_params, &name, policies::Mode::Basic)
+ .confirm(hal, &title, coin_params, &name, policies::Mode::Basic)
.await?;
}
@@ -278,7 +296,7 @@ async fn address_policy(
let address_formatted = util::strings::format_address(&address);
hal.ui()
.confirm(&ConfirmParams {
- title,
+ title: &title,
body: &address_formatted,
scrollable: true,
..Default::default()
### src/rust/bitbox02-rust/src/hww/api/bitcoin/multisig.rs
@@ -4,6 +4,7 @@ use super::Error;
use super::params::Params;
use super::pb;
use crate::hal::ui::ConfirmParams;
+use crate::i18n::I18n as _;
use pb::BtcCoin;
use pb::btc_register_script_config_request::XPubType;
@@ -13,7 +14,7 @@ use crate::bip32;
use crate::hal::{Memory, Ui};
-use alloc::string::String;
+use alloc::string::{String, ToString};
use alloc::vec::Vec;
use sha2::{Digest, Sha256};
@@ -127,15 +128,19 @@ pub async fn confirm(
name: &str,
multisig: &Multisig,
) -> Result<(), Error> {
+ let body = crate::tr_format!(
+ hal,
+ "{}-of-{}\n{} multisig",
+ &[
+ &multisig.threshold.to_string(),
+ &multisig.xpubs.len().to_string(),
+ params.name,
+ ],
+ );
hal.ui()
.confirm(&ConfirmParams {
title,
- body: &format!(
- "{}-of-{}\n{} multisig",
- multisig.threshold,
- multisig.xpubs.len(),
- params.name
- ),
+ body: &body,
accept_is_nextarrow: true,
..Default::default()
})
@@ -176,17 +181,21 @@ pub async fn confirm_extended(
let script_type = ScriptType::try_from(multisig.script_type)?;
confirm(hal, title, params, name, multisig).await?;
+ let body = crate::tr_format!(
+ hal,
+ "{}\nat\n{}",
+ &[
+ match ScriptType::try_from(multisig.script_type)? {
+ ScriptType::P2wsh => "p2wsh",
+ ScriptType::P2wshP2sh => "p2wsh-p2sh",
+ },
+ &util::bip32::to_string(keypath),
+ ],
+ );
hal.ui()
.confirm(&ConfirmParams {
title,
- body: &format!(
- "{}\nat\n{}",
- match ScriptType::try_from(multisig.script_type)? {
- ScriptType::P2wsh => "p2wsh",
- ScriptType::P2wshP2sh => "p2wsh-p2sh",
- },
- util::bip32::to_string(keypath)
- ),
+ body: &body,
accept_is_nextarrow: true,
..Default::default()
})
@@ -214,20 +223,23 @@ pub async fn confirm_extended(
let xpub_str = bip32::Xpub::from(xpub)
.serialize_str(output_xpub_type)
.or(Err(Error::InvalidInput))?;
+ let body = if i == multisig.our_xpub_index as usize {
+ crate::tr_format!(
+ hal,
+ "Cosigner {}/{} (this device): {}",
+ &[&(i + 1).to_string(), &num_cosigners.to_string(), &xpub_str],
+ )
+ } else {
+ crate::tr_format!(
+ hal,
+ "Cosigner {}/{}: {}",
+ &[&(i + 1).to_string(), &num_cosigners.to_string(), &xpub_str],
+ )
+ };
hal.ui()
.confirm(&ConfirmParams {
title,
- body: (if i == multisig.our_xpub_index as usize {
- format!(
- "Cosigner {}/{} (this device): {}",
- i + 1,
- num_cosigners,
- xpub_str
- )
- } else {
- format!("Cosigner {}/{}: {}", i + 1, num_cosigners, xpub_str)
- })
- .as_str(),
+ body: &body,
scrollable: true,
longtouch: i == num_cosigners - 1,
accept_is_nextarrow: true,
### src/rust/bitbox02-rust/src/hww/api/bitcoin/policies.rs
@@ -4,11 +4,12 @@ use super::Error;
use super::params::Params;
use super::pb;
use crate::hal::ui::ConfirmParams;
+use crate::i18n::I18n as _;
use pb::BtcCoin;
use pb::btc_script_config::Policy;
-use alloc::string::String;
+use alloc::string::{String, ToString};
use alloc::vec::Vec;
use core::str::FromStr;
@@ -439,19 +440,25 @@ impl ParsedPolicy<'_> {
mode: Mode,
) -> Result<(), Error> {
let policy = self.policy;
+ let body = crate::tr_format!(
+ hal,
+ "{}\npolicy with\n{} keys",
+ &[params.name, &policy.keys.len().to_string()],
+ );
hal.ui()
.confirm(&ConfirmParams {
title,
- body: &format!("{}\npolicy with\n{} keys", params.name, policy.keys.len(),),
+ body: &body,
accept_is_nextarrow: true,
..Default::default()
})
.await?;
+ let name_title = crate::tr!(hal, "Name");
confirm::confirm_value(
hal,
&ConfirmParams {
- title: "Name",
+ title: &name_title,
body: name,
scrollable: true,
accept_is_nextarrow: true,
@@ -461,10 +468,11 @@ impl ParsedPolicy<'_> {
.await?;
if matches!(mode, Mode::Basic) {
+ let body = crate::tr!(hal, "Show policy\ndetails?");
if let Err(crate::hal::ui::UserAbort) = hal
.ui()
.confirm(&ConfirmParams {
- body: "Show policy\ndetails?",
+ body: &body,
accept_is_nextarrow: true,
..Default::default()
})
@@ -474,10 +482,11 @@ impl ParsedPolicy<'_> {
}
}
+ let policy_title = crate::tr!(hal, "Policy");
confirm::confirm_value(
hal,
&ConfirmParams {
- title: "Policy",
+ title: &policy_title,
body: &policy.policy,
scrollable: true,
accept_is_nextarrow: true,
@@ -520,16 +529,21 @@ impl ParsedPolicy<'_> {
_ => return Err(Error::InvalidInput),
};
if self.is_our_key[i] {
- key_str = format!("This device: {}", key_str)
+ key_str = crate::tr_format!(hal, "This device: {}", &[&key_str])
} else if Some(i) == taproot_unspendable_internal_key_index {
- key_str = format!("Provably unspendable: {}", key_str)
+ key_str = crate::tr_format!(hal, "Provably unspendable: {}", &[&key_str])
}
if key_str.len() > confirm::MAX_CONFIRM_BODY_SIZE {
return Err(Error::InvalidInput);
}
+ let key_title = crate::tr_format!(
+ hal,
+ "Key {}/{}",
+ &[&(i + 1).to_string(), &num_keys.to_string()]
+ );
hal.ui()
.confirm(&ConfirmParams {
- title: &format!("Key {}/{}", i + 1, num_keys),
+ title: &key_title,
body: key_str.as_str(),
scrollable: true,
longtouch: i == num_keys - 1 && matches!(mode, Mode::Advanced),
### src/rust/bitbox02-rust/src/hww/api/bitcoin/registration.rs
@@ -4,6 +4,7 @@ use super::Error;
use super::params;
use super::pb;
use crate::hal::ui::{ConfirmParams, Font};
+use crate::i18n::I18n as _;
use alloc::string::String;
@@ -65,20 +66,23 @@ async fn get_name(
request: &pb::BtcRegisterScriptConfigRequest,
) -> Result<String, Error> {
let name = if request.name.is_empty() {
+ let title = crate::tr!(hal, "Register");
+ let body = crate::tr!(hal, "Please name this\naccount");
hal.ui()
.confirm(&ConfirmParams {
- title: "Register",
- body: "Please name this\naccount",
+ title: &title,
+ body: &body,
accept_is_nextarrow: true,
..Default::default()
})
.await?;
+ let title = crate::tr!(hal, "Enter account name");
let name = hal
.ui()
.enter_string(
&crate::hal::ui::EnterStringParams {
- title: "Enter account name",
+ title: &title,
longtouch: true,
..Default::default()
},
@@ -107,7 +111,7 @@ pub async fn process_register_script_config(
hal: &mut impl crate::hal::Hal,
request: &pb::BtcRegisterScriptConfigRequest,
) -> Result<Response, Error> {
- let title = "Register";
+ let title = crate::tr!(hal, "Register");
match request.registration.as_ref() {
Some(pb::BtcScriptConfigRegistration {
coin,
@@ -124,7 +128,7 @@ pub async fn process_register_script_config(
let xpub_type = XPubType::try_from(request.xpub_type)?;
super::multisig::confirm_extended(
hal,
- title,
+ &title,
coin_params,
&name,
multisig,
@@ -134,7 +138,8 @@ pub async fn process_register_script_config(
.await?;
let hash = super::multisig::get_hash(coin, multisig, SortXpubs::Yes, keypath)?;
hal.memory().multisig_set_by_hash(&hash, &name)?;
- hal.ui().status("Multisig account\nregistered", true).await;
+ let status = crate::tr!(hal, "Multisig account\nregistered");
+ hal.ui().status(&status, true).await;
Ok(Response::Success(pb::BtcSuccess {}))
}
Some(pb::BtcScriptConfigRegistration {
@@ -152,15 +157,16 @@ pub async fn process_register_script_config(
parsed
.confirm(
hal,
- title,
+ &title,
coin_params,
&name,
super::policies::Mode::Advanced,
)
.await?;
let hash = super::policies::get_hash(coin, policy)?;
hal.memory().multisig_set_by_hash(&hash, &name)?;
- hal.ui().status("Policy\nregistered", true).await;
+ let status = crate::tr!(hal, "Policy\nregistered");
+ hal.ui().status(&status, true).await;
Ok(Response::Success(pb::BtcSuccess {}))
}
// Only multisig and policy registration supported for now.
### src/rust/bitbox02-rust/src/hww/api/bitcoin/script_configs.rs
@@ -1,12 +1,13 @@
// SPDX-License-Identifier: Apache-2.0
-use alloc::string::String;
+use alloc::string::{String, ToString};
use super::Error;
use super::pb;
use pb::btc_script_config::{Multisig, SimpleType};
use super::policies::ParsedPolicy;
+use crate::hal::memory::Language;
use util::bip32::HARDENED;
@@ -32,19 +33,21 @@ pub struct ValidatedScriptConfigWithKeypath<'a> {
impl ValidatedScriptConfigWithKeypath<'_> {
/// Get a string representation of the account script config to show to the user when they send
/// coins to an address belonging to the same keystore.
- pub fn self_transfer_representation(&self) -> Result<String, Error> {
+ pub fn self_transfer_representation(&self, language: Language) -> Result<String, Error> {
match self {
ValidatedScriptConfigWithKeypath {
keypath,
config: ValidatedScriptConfig::SimpleType(_),
} => {
let keypath_account_element = keypath.get(2).ok_or(Error::Generic)?;
- Ok(format!(
+ Ok(crate::i18n::format(
+ language,
"This BitBox (account #{})",
- keypath_account_element
+ &[&(keypath_account_element
.checked_sub(HARDENED)
.ok_or(Error::Generic)?
- + 1
+ + 1)
+ .to_string()],
))
}
ValidatedScriptConfigWithKeypath {
@@ -54,7 +57,7 @@ impl ValidatedScriptConfigWithKeypath<'_> {
| ValidatedScriptConfigWithKeypath {
config: ValidatedScriptConfig::Policy { name, .. },
..
- } => Ok(format!("This BitBox - {}", name)),
+ } => Ok(crate::i18n::format(language, "This BitBox - {}", &[name])),
}
}
}
@@ -74,7 +77,9 @@ mod tests {
config: ValidatedScriptConfig::SimpleType(simple_type),
};
assert_eq!(
- config.self_transfer_representation().unwrap(),
+ config
+ .self_transfer_representation(Language::English)
+ .unwrap(),
"This BitBox (account #11)"
)
}
@@ -100,7 +105,10 @@ mod tests {
};
assert_eq!(
- config.self_transfer_representation().unwrap().as_str(),
+ config
+ .self_transfer_representation(Language::English)
+ .unwrap()
+ .as_str(),
"This BitBox - test multisig account name",
)
}
@@ -146,7 +154,10 @@ mod tests {
};
assert_eq!(
- config.self_transfer_representation().unwrap().as_str(),
+ config
+ .self_transfer_representation(Language::English)
+ .unwrap()
+ .as_str(),
"This BitBox - test policy account name",
)
}
### src/rust/bitbox02-rust/src/hww/api/bitcoin/signmsg.rs
@@ -1,6 +1,7 @@
// SPDX-License-Identifier: Apache-2.0
use crate::hal::ui::ConfirmParams;
+use crate::i18n::I18n as _;
use alloc::vec::Vec;
use sha2::{Digest, Sha256};
@@ -94,28 +95,32 @@ pub async fn process(
let address_formatted = util::strings::format_address(&address);
let basic_info = if is_standard_keypath {
- format!("Coin: {}", coin_params.name)
+ crate::tr_format!(hal, "Coin: {}", &[coin_params.name])
} else {
- format!("Coin: {}\nExternal service key", coin_params.name)
+ crate::tr_format!(hal, "Coin: {}\nExternal service key", &[coin_params.name])
};
+ let title = crate::tr!(hal, "Sign message");
let confirm_params = ConfirmParams {
- title: "Sign message",
+ title: &title,
body: &basic_info,
accept_is_nextarrow: true,
..Default::default()
};
hal.ui().confirm(&confirm_params).await?;
+ let title = crate::tr!(hal, "Address");
let confirm_params = ConfirmParams {
- title: "Address",
+ title: &title,
body: &address_formatted,
scrollable: true,
accept_is_nextarrow: true,
..Default::default()
};
hal.ui().confirm(&confirm_params).await?;
- verify_message::verify(hal, "Sign message", "Sign", &request.msg, true).await?;
+ let title_long = crate::tr!(hal, "Sign message");
+ let title_short = crate::tr!(hal, "Sign");
+ verify_message::verify(hal, &title_long, &title_short, &request.msg, true).await?;
// See
// https://github.com/spesmilo/electrum/blob/84dc181b6e7bb20e88ef6b98fb8925c5f645a765/electrum/ecc.py#L355-L358.
### src/rust/bitbox02-rust/src/hww/api/bitcoin/signtx.rs
@@ -3,20 +3,21 @@
use super::Error;
use super::pb;
use crate::hal::ui::{ConfirmParams, Progress};
+use crate::i18n::I18n as _;
use super::super::payment_request;
use super::common::format_amount;
use super::policies::TaprootSpendInfo;
use super::script_configs::{ValidatedScriptConfig, ValidatedScriptConfigWithKeypath};
use super::{bip143, bip341, common, keypath};
-use crate::hal::Ui;
+use crate::hal::{Memory, Ui};
use crate::keystore::Compute;
use crate::secp256k1::SECP256K1;
use crate::workflow::transaction;
use crate::xpubcache::Bip32XpubCache;
-use alloc::string::String;
+use alloc::string::{String, ToString};
use alloc::vec::Vec;
use pb::request::Request;
@@ -530,7 +531,8 @@ async fn validate_input_script_configs<'a>(
},
] = script_configs.as_slice()
{
- super::multisig::confirm(hal, "Spend from", coin_params, name, multisig).await?;
+ let title = crate::tr!(hal, "Spend from");
+ super::multisig::confirm(hal, &title, coin_params, name, multisig).await?;
return Ok(script_configs);
}
@@ -553,14 +555,9 @@ async fn validate_input_script_configs<'a>(
// the input keypath, and the computation of the pk_script checks that full keypath is
// valid.
+ let title = crate::tr!(hal, "Spend from");
parsed_policy
- .confirm(
- hal,
- "Spend from",
- coin_params,
- name,
- super::policies::Mode::Basic,
- )
+ .confirm(hal, &title, coin_params, name, super::policies::Mode::Basic)
.await?;
return Ok(script_configs);
@@ -667,23 +664,22 @@ impl<'a> TryFrom<&'a ValidatedScriptConfigWithKeypath<'a>>
///
/// Timestamp locktimes are shown in UTC. Whether a locktime has passed is determined using chain
/// state, which the device does not have, so only the exact signed value is displayed.
-fn format_locktime(locktime: u32) -> Result<String, Error> {
+fn format_locktime(hal: &mut impl crate::hal::Hal, locktime: u32) -> Result<String, Error> {
let locktime = bitcoin::absolute::LockTime::from_consensus(locktime);
if locktime.is_block_height() {
- return Ok(format!(
+ return Ok(crate::tr_format!(
+ hal,
"Locktime on block:\n{}",
- locktime.to_consensus_u32()
+ &[&locktime.to_consensus_u32().to_string()]
));
}
let tm = util::datetime::get_datetime(locktime.to_consensus_u32())
.map_err(|_| Error::InvalidInput)?;
- Ok(format!(
+ Ok(crate::tr_format!(
+ hal,
"Locktime (UTC):\n{}\n{}:{}:{}",
- tm.date(),
- tm.hour(),
- tm.minute(),
- tm.second(),
+ &[&tm.date(), &tm.hour(), &tm.minute(), &tm.second()],
))
}
@@ -764,7 +760,8 @@ async fn _process(
// transaction.
let mut payment_request_seen = false;
- let mut progress_component = Some(hal.ui().progress_create("Loading transaction..."));
+ let progress_title = crate::tr!(hal, "Loading transaction...");
+ let mut progress_component = Some(hal.ui().progress_create(&progress_title));
let mut next_response = NextResponse {
next: Default::default(),
@@ -1064,7 +1061,8 @@ async fn _process(
return Err(Error::Disabled);
}
Err(_) => {
- hal.ui().status("Invalid\npayment request", false).await;
+ let status = crate::tr!(hal, "Invalid\npayment request");
+ hal.ui().status(&status, false).await;
return Err(Error::InvalidInput);
}
}
@@ -1089,10 +1087,13 @@ async fn _process(
let output_script_config = validated_output_script_configs
.get(output_script_config_index as usize)
.ok_or(Error::InvalidInput)?;
- Some(output_script_config.self_transfer_representation()?)
+ Some(
+ output_script_config
+ .self_transfer_representation(hal.memory().get_device_language())?,
+ )
} else {
// Non-change output of the same account.
- Some("This BitBox (same account)".into())
+ Some(crate::tr!(hal, "This BitBox (same account)").into_owned())
}
} else {
// Regular outgoing payment, no prefix.
@@ -1135,10 +1136,16 @@ async fn _process(
}
if num_changes > 1 {
+ let title = crate::tr!(hal, "Warning");
+ let body = crate::tr_format!(
+ hal,
+ "There are {}\nchange outputs.\nProceed?",
+ &[&num_changes.to_string()],
+ );
hal.ui()
.confirm(&ConfirmParams {
- title: "Warning",
- body: &format!("There are {}\nchange outputs.\nProceed?", num_changes),
+ title: &title,
+ body: &body,
accept_is_nextarrow: true,
..Default::default()
})
@@ -1148,7 +1155,7 @@ async fn _process(
// Confirm an effective non-zero nLockTime because it can defer when the signed transaction
// becomes valid. nLockTime is ignored if every input uses the final sequence number.
if request.locktime > 0 && locktime_applies {
- let body = format_locktime(request.locktime)?;
+ let body = format_locktime(hal, request.locktime)?;
hal.ui()
.confirm(&ConfirmParams {
body: &body,
@@ -1189,7 +1196,8 @@ async fn _process(
fee_percentage_basis,
)
.await?;
- hal.ui().status("Transaction\nconfirmed", true).await;
+ let status = crate::tr!(hal, "Transaction\nconfirmed");
+ hal.ui().status(&status, true).await;
let hash_outputs = hasher_outputs.finalize();
@@ -1199,7 +1207,8 @@ async fn _process(
// Show progress of signing inputs if there are more than 2 inputs. This is an arbitrary cutoff;
// less or equal to 2 inputs is fast enough so it does not need a progress bar.
let mut progress_component = if request.num_inputs > 2 {
- Some(hal.ui().progress_create("Signing transaction..."))
+ let title = crate::tr!(hal, "Signing transaction...");
+ Some(hal.ui().progress_create(&title))
} else {
None
};
@@ -1367,7 +1376,8 @@ pub async fn process(
) -> Result<Response, Error> {
let result = _process(hal, request).await;
if let Err(Error::UserAbort) = result {
- hal.ui().status("Transaction\ncanceled", false).await;
+ let status = crate::tr!(hal, "Transaction\ncanceled");
+ hal.ui().status(&status, false).await;
}
result
}
@@ -1389,20 +1399,21 @@ mod tests {
#[test]
fn test_format_locktime() {
+ let mut hal = TestingHal::new();
assert_eq!(
- format_locktime(499_999_999).unwrap(),
+ format_locktime(&mut hal, 499_999_999).unwrap(),
"Locktime on block:\n499999999"
);
assert_eq!(
- format_locktime(500_000_000).unwrap(),
+ format_locktime(&mut hal, 500_000_000).unwrap(),
"Locktime (UTC):\n1985-11-05\n00:53:20"
);
assert_eq!(
- format_locktime(1_800_000_000).unwrap(),
+ format_locktime(&mut hal, 1_800_000_000).unwrap(),
"Locktime (UTC):\n2027-01-15\n08:00:00"
);
assert_eq!(
- format_locktime(u32::MAX).unwrap(),
+ format_locktime(&mut hal, u32::MAX).unwrap(),
"Locktime (UTC):\n2106-02-07\n06:28:15"
);
}
### src/rust/bitbox02-rust/src/hww/api/bluetooth.rs
@@ -3,6 +3,7 @@
use super::Error;
use super::pb;
use crate::hal::ui::{ConfirmParams, Progress};
+use crate::i18n::I18n as _;
use hex_lit::hex;
@@ -132,16 +133,19 @@ async fn process_upgrade(
}
}
+ let title = crate::tr!(hal, "Bluetooth");
+ let body = crate::tr!(hal, "Upgrade\nfirmware?");
hal.ui()
.confirm(&ConfirmParams {
- title: "Bluetooth",
- body: "Upgrade\nfirmware?",
+ title: &title,
+ body: &body,
longtouch: true,
..Default::default()
})
.await?;
- let mut progress = hal.ui().progress_create("Upgrading...");
+ let progress_title = crate::tr!(hal, "Upgrading...");
+ let mut progress = hal.ui().progress_create(&progress_title);
let response = process_upgrade_helper(
hal.memory(),
&mut RealFuncs,
@@ -153,7 +157,8 @@ async fn process_upgrade(
drop(progress);
if response.is_ok() {
- hal.ui().status("Upgrade\nsuccessful", true).await;
+ let status = crate::tr!(hal, "Upgrade\nsuccessful");
+ hal.ui().status(&status, true).await;
hal.system().reset_ble();
if crate::communication_mode::ble_enabled(hal) {
// Since the Bluetooth host will not be there anymore to read this response, this task
@@ -162,22 +167,23 @@ async fn process_upgrade(
crate::async_usb::cancel();
}
} else {
- hal.ui().status("Upgrade failed", false).await;
+ let status = crate::tr!(hal, "Upgrade failed");
+ hal.ui().status(&status, false).await;
}
response
}
async fn process_toggle_enabled(hal: &mut impl crate::hal::Hal) -> Result<Response, Error> {
let enabled = hal.memory().ble_enabled();
let body = if enabled {
- "Disable Bluetooth?"
+ crate::tr!(hal, "Disable Bluetooth?")
} else {
- "Enable Bluetooth?"
+ crate::tr!(hal, "Enable Bluetooth?")
};
hal.ui()
.confirm(&ConfirmParams {
- body,
+ body: &body,
longtouch: true,
..Default::default()
})
@@ -188,11 +194,11 @@ async fn process_toggle_enabled(hal: &mut impl crate::hal::Hal) -> Result<Respon
.map_err(|_| Error::Memory)?;
let status_text = if enabled {
- "Bluetooth\ndisabled"
+ crate::tr!(hal, "Bluetooth\ndisabled")
} else {
- "Bluetooth\nenabled"
+ crate::tr!(hal, "Bluetooth\nenabled")
};
- hal.ui().status(status_text, true).await;
+ hal.ui().status(&status_text, true).await;
Ok(pb::bluetooth_response::Response::Success(
pb::BluetoothSuccess {},
### src/rust/bitbox02-rust/src/hww/api/cardano/sign_transaction.rs
@@ -7,7 +7,7 @@ mod certificates;
use super::Error;
use super::pb;
-use alloc::string::String;
+use alloc::string::{String, ToString};
use alloc::vec::Vec;
use bitcoin::bech32;
@@ -18,6 +18,7 @@ use blake2::{
};
use crate::hal::Ui;
+use crate::i18n::I18n as _;
use crate::workflow::transaction;
use pb::cardano_response::Response;
@@ -73,10 +74,20 @@ async fn verify_slot(
}
let epoch = SHELLEY_START_EPOCH + (slot - SHELLEY_START_SLOT) / SHELLEY_SLOTS_IN_EPOCH;
let slot_in_epoch = (slot - SHELLEY_START_SLOT) % SHELLEY_SLOTS_IN_EPOCH;
+ let title = hal.tr(title);
+ let body = crate::tr_format!(
+ hal,
+ "{}\nslot {} in\nepoch {}",
+ &[
+ title.as_ref(),
+ &slot_in_epoch.to_string(),
+ &epoch.to_string(),
+ ],
+ );
hal.ui()
.confirm(&ConfirmParams {
title: params.name,
- body: &format!("{}\nslot {} in\nepoch {}", title, slot_in_epoch, epoch),
+ body: &body,
accept_is_nextarrow: true,
..Default::default()
})
@@ -164,10 +175,11 @@ async fn _process(
&& (request.validity_interval_start > request.ttl))
|| (ttl_present && request.ttl < SHELLEY_START_SLOT);
if cannot_be_mined {
+ let body = crate::tr!(hal, "Transaction\ncannot be\nmined");
hal.ui()
.confirm(&ConfirmParams {
title: params.name,
- body: "Transaction\ncannot be\nmined",
+ body: &body,
accept_is_nextarrow: true,
..Default::default()
})
@@ -188,10 +200,15 @@ async fn _process(
}
}
if !commits_to_network(request) {
+ let title = crate::tr!(hal, "Warning");
+ let body = crate::tr!(
+ hal,
+ "This transaction does not encode a Cardano network and may be valid on another Cardano network."
+ );
hal.ui()
.confirm(&ConfirmParams {
- title: "Warning",
- body: "This transaction does not encode a Cardano network and may be valid on another Cardano network.",
+ title: &title,
+ body: &body,
accept_is_nextarrow: true,
scrollable: true,
..Default::default()
@@ -213,14 +230,17 @@ async fn _process(
return Err(Error::InvalidInput);
}
+ let account = (withdrawal.keypath[2] + 1 - HARDENED).to_string();
+ let value = format_value(params, withdrawal.value);
+ let body = crate::tr_format!(
+ hal,
+ "Withdraw {} in staking rewards for account #{}?",
+ &[&value, &account],
+ );
hal.ui()
.confirm(&ConfirmParams {
title: params.name,
- body: &format!(
- "Withdraw {} in staking rewards for account #{}?",
- format_value(params, withdrawal.value),
- withdrawal.keypath[2] + 1 - HARDENED,
- ),
+ body: &body,
scrollable: true,
accept_is_nextarrow: true,
..Default::default()
@@ -266,14 +286,19 @@ async fn _process(
for asset_group in output.asset_groups.iter() {
for token in asset_group.tokens.iter() {
+ let title = crate::tr!(hal, "Send token");
+ let body = crate::tr_format!(
+ hal,
+ "Amount: {}. Asset: {}",
+ &[
+ &util::decimal::format(token.value, 0),
+ &format_asset(&asset_group.policy_id, &token.asset_name),
+ ],
+ );
hal.ui()
.confirm(&ConfirmParams {
- title: "Send token",
- body: &format!(
- "Amount: {}. Asset: {}",
- util::decimal::format(token.value, 0),
- format_asset(&asset_group.policy_id, &token.asset_name),
- ),
+ title: &title,
+ body: &body,
accept_is_nextarrow: true,
scrollable: true,
..Default::default()
@@ -286,10 +311,11 @@ async fn _process(
}
if total == 0 {
+ let body = crate::tr_format!(hal, "Fee\n{}", &[&format_value(params, request.fee)]);
hal.ui()
.confirm(&ConfirmParams {
title: params.name,
- body: &format!("Fee\n{}", format_value(params, request.fee)),
+ body: &body,
longtouch: true,
..Default::default()
})
@@ -306,7 +332,8 @@ async fn _process(
.await?;
}
- hal.ui().status("Transaction\nconfirmed", true).await;
+ let status = crate::tr!(hal, "Transaction\nconfirmed");
+ hal.ui().status(&status, true).await;
let tx_body_hash: [u8; 32] = {
let mut hasher = Blake2bVar::new(32).unwrap();
@@ -337,7 +364,8 @@ pub async fn process(
) -> Result<Response, Error> {
let result = _process(hal, request).await;
if let Err(Error::UserAbort) = result {
- hal.ui().status("Transaction\ncanceled", false).await;
+ let status = crate::tr!(hal, "Transaction\ncanceled");
+ hal.ui().status(&status, false).await;
}
result
}
### src/rust/bitbox02-rust/src/hww/api/cardano/sign_transaction/certificates.rs
@@ -5,7 +5,9 @@ use super::super::keypath::validate_address_shelley_stake;
use super::super::params;
use super::super::pb;
use crate::hal::ui::ConfirmParams;
+use crate::i18n::I18n as _;
+use alloc::string::ToString;
use alloc::vec::Vec;
use pb::cardano_sign_transaction_request::{
@@ -30,13 +32,13 @@ pub async fn verify<'a>(
validate_address_shelley_stake(keypath, Some(bip44_account))?;
signing_keypaths.push(keypath);
// 2 ADA will be deposited and refunded once delegation stops, independent of the staking rewards.
+ let account = (keypath[2] + 1 - HARDENED).to_string();
+ let body =
+ crate::tr_format!(hal, "Register staking key for account #{}?", &[&account]);
hal.ui()
.confirm(&ConfirmParams {
title: params.name,
- body: &format!(
- "Register staking key for account #{}?",
- keypath[2] + 1 - HARDENED
- ),
+ body: &body,
scrollable: true,
accept_is_nextarrow: true,
..Default::default()
@@ -47,13 +49,13 @@ pub async fn verify<'a>(
validate_address_shelley_stake(keypath, Some(bip44_account))?;
signing_keypaths.push(keypath);
// 2 ADA will be refunded back, independent of the staking rewards.
+ let account = (keypath[2] + 1 - HARDENED).to_string();
+ let body =
+ crate::tr_format!(hal, "Stop stake delegation for account #{}?", &[&account]);
hal.ui()
.confirm(&ConfirmParams {
title: params.name,
- body: &format!(
- "Stop stake delegation for account #{}?",
- keypath[2] + 1 - HARDENED
- ),
+ body: &body,
scrollable: true,
accept_is_nextarrow: true,
..Default::default()
@@ -66,14 +68,17 @@ pub async fn verify<'a>(
}) => {
validate_address_shelley_stake(keypath, Some(bip44_account))?;
signing_keypaths.push(keypath);
+ let account = (keypath[2] + 1 - HARDENED).to_string();
+ let pool = hex::encode(pool_keyhash);
+ let body = crate::tr_format!(
+ hal,
+ "Delegate staking for account #{} to pool {}?",
+ &[&account, &pool],
+ );
hal.ui()
.confirm(&ConfirmParams {
title: params.name,
- body: &format!(
- "Delegate staking for account #{} to pool {}?",
- keypath[2] + 1 - HARDENED,
- hex::encode(pool_keyhash),
- ),
+ body: &body,
scrollable: true,
accept_is_nextarrow: true,
..Default::default()
@@ -89,41 +94,48 @@ pub async fn verify<'a>(
signing_keypaths.push(keypath);
let drep_type_name =
match certificate::vote_delegation::CardanoDRepType::try_from(*r#type)? {
- certificate::vote_delegation::CardanoDRepType::KeyHash => "Key Hash",
- certificate::vote_delegation::CardanoDRepType::ScriptHash => "Script Hash",
+ certificate::vote_delegation::CardanoDRepType::KeyHash => {
+ crate::tr!(hal, "Key Hash")
+ }
+ certificate::vote_delegation::CardanoDRepType::ScriptHash => {
+ crate::tr!(hal, "Script Hash")
+ }
certificate::vote_delegation::CardanoDRepType::AlwaysAbstain => {
- "Always Abstain"
+ crate::tr!(hal, "Always Abstain")
}
certificate::vote_delegation::CardanoDRepType::AlwaysNoConfidence => {
- "Always No Confidence"
+ crate::tr!(hal, "Always No Confidence")
}
};
+ let account = (keypath[2] + 1 - HARDENED).to_string();
match drep_credhash {
Some(hash) => {
+ let hash = hex::encode(hash);
+ let body = crate::tr_format!(
+ hal,
+ "Delegate voting for account #{} to type {} and drep {}?",
+ &[&account, drep_type_name.as_ref(), &hash],
+ );
hal.ui()
.confirm(&ConfirmParams {
title: params.name,
- body: &format!(
- "Delegate voting for account #{} to type {} and drep {}?",
- keypath[2] + 1 - HARDENED,
- drep_type_name,
- hex::encode(hash),
- ),
+ body: &body,
scrollable: true,
accept_is_nextarrow: true,
..Default::default()
})
.await?;
}
None => {
+ let body = crate::tr_format!(
+ hal,
+ "Delegate voting for account #{} to type {}?",
+ &[&account, drep_type_name.as_ref()],
+ );
hal.ui()
.confirm(&ConfirmParams {
title: params.name,
- body: &format!(
- "Delegate voting for account #{} to type {}?",
- keypath[2] + 1 - HARDENED,
- drep_type_name,
- ),
+ body: &body,
scrollable: true,
accept_is_nextarrow: true,
..Default::default()
### src/rust/bitbox02-rust/src/hww/api/change_password.rs
@@ -2,6 +2,7 @@
use super::Error;
use crate::hal::ui::{CanCancel, ConfirmParams};
+use crate::i18n::I18n as _;
use crate::pb;
use pb::response::Response;
@@ -12,24 +13,25 @@ use crate::workflow::{password, unlock};
pub async fn process(hal: &mut impl crate::hal::Hal) -> Result<Response, Error> {
// Process confirmation and instruction for user
+ let body = crate::tr!(hal, "Proceed to\nchange password?");
hal.ui()
.confirm(&ConfirmParams {
title: "",
- body: "Proceed to\nchange password?",
+ body: &body,
accept_is_nextarrow: true,
..Default::default()
})
.await?;
// Unlock with old password
- let seed = unlock::unlock_keystore(hal, "Unlock device", CanCancel::Yes).await?;
+ let title = crate::tr!(hal, "Unlock device");
+ let seed = unlock::unlock_keystore(hal, &title, CanCancel::Yes).await?;
// Enter and confirm new password
let new_password = password::enter_twice(hal).await?;
// Re-encrypt seed with new password
if let Err(err) = keystore::re_encrypt_seed(hal, &seed, &new_password).await {
- hal.ui()
- .status(&format!("Error\n{}", keystore::format_error(&err)), false)
- .await;
+ let status = crate::tr_format!(hal, "Error\n{}", &[&keystore::format_error(&err)]);
+ hal.ui().status(&status, false).await;
return Err(Error::Generic);
}
### src/rust/bitbox02-rust/src/hww/api/device_info.rs
@@ -34,6 +34,11 @@ pub async fn process(hal: &mut impl crate::hal::Hal) -> Result<Response, Error>
};
Ok(Response::DeviceInfo(pb::DeviceInfoResponse {
name: hal.memory().get_device_name(),
+ language: crate::i18n::language_code(hal.memory().get_device_language()).into(),
+ supported_languages: crate::i18n::SUPPORTED_LANGUAGES
+ .iter()
+ .map(|&code| code.into())
+ .collect(),
initialized: hal.memory().is_initialized(),
version: crate::version::FIRMWARE_VERSION_SHORT.into(),
mnemonic_passphrase_enabled: hal.memory().is_mnemonic_passphrase_enabled(),
@@ -65,6 +70,26 @@ mod tests {
}
}
+ #[async_test::test]
+ async fn test_process_language() {
+ let mut hal = TestingHal::new();
+ let info = _device_info(&mut hal).await;
+ assert_eq!(info.language, "en");
+ assert_eq!(info.supported_languages, ["en", "de"]);
+
+ hal.memory
+ .set_device_language(hal_memory::Language::German)
+ .unwrap();
+ let info = _device_info(&mut hal).await;
+ assert_eq!(info.language, "de");
+ assert_eq!(info.supported_languages, ["en", "de"]);
+
+ hal.memory
+ .set_device_language(hal_memory::Language::English)
+ .unwrap();
+ assert_eq!(_device_info(&mut hal).await.language, "en");
+ }
+
#[async_test::test]
async fn test_process_bootloader_version() {
let mut hal = TestingHal::new();
### src/rust/bitbox02-rust/src/hww/api/ethereum/keypath.rs
@@ -4,6 +4,7 @@ use super::Error;
use super::params::Params;
use crate::hal::Ui;
use crate::hal::ui::ConfirmParams;
+use crate::i18n::I18n as _;
use util::bip32::HARDENED;
const ACCOUNT_MAX: u32 = 99; // 100 accounts
@@ -27,9 +28,10 @@ pub async fn warn_unusual_keypath(
return Err(Error::InvalidInput);
}
if keypath[1] != params.bip44_coin {
- let body = format!(
+ let body = crate::tr_format!(
+ hal,
"Warning: unusual keypath {}. Proceed only if you know what you are doing.",
- util::bip32::to_string(keypath)
+ &[&util::bip32::to_string(keypath)],
);
return Ok(hal
.ui()
### src/rust/bitbox02-rust/src/hww/api/ethereum/params.rs
@@ -3,10 +3,13 @@
use super::Error;
use super::pb;
use crate::hal::ui::ConfirmParams;
+use crate::i18n::I18n as _;
use pb::EthCoin;
use crate::hal::Ui;
+use alloc::string::ToString;
+
use util::bip32::HARDENED;
#[derive(Copy, Clone)]
@@ -153,18 +156,26 @@ pub async fn get_and_warn_unknown(
if chain_id == 0 {
Err(Error::InvalidInput)
} else {
+ let title = crate::tr!(hal, "Warning");
+ let body = crate::tr_format!(
+ hal,
+ "Unknown network\nwith chain ID:\n{}",
+ &[&chain_id.to_string()],
+ );
hal.ui()
.confirm(&ConfirmParams {
- title: "Warning",
- body: &format!("Unknown network\nwith chain ID:\n{}", chain_id),
+ title: &title,
+ body: &body,
accept_is_nextarrow: true,
..Default::default()
})
.await?;
+ let title = crate::tr!(hal, "Warning");
+ let body = crate::tr!(hal, "Only proceed if\nyou recognize\nthis chain ID.");
hal.ui()
.confirm(&ConfirmParams {
- title: "Warning",
- body: "Only proceed if\nyou recognize\nthis chain ID.",
+ title: &title,
+ body: &body,
accept_is_nextarrow: true,
..Default::default()
})
### src/rust/bitbox02-rust/src/hww/api/ethereum/sign.rs
@@ -9,9 +9,9 @@ use super::sighash::DataProducer;
use super::truncating_hex_preview_byte_cap;
use crate::hal::ui::ConfirmParams;
-use crate::keystore;
-
use crate::hal::Ui;
+use crate::i18n::I18n as _;
+use crate::keystore;
use crate::workflow::confirm;
use crate::workflow::transaction;
@@ -189,7 +189,8 @@ async fn verify_payment_request_recipient(
{
Ok(()) => Ok(()),
Err(_) => {
- hal.ui().status("Invalid\npayment request", false).await;
+ let status = crate::tr!(hal, "Invalid\npayment request");
+ hal.ui().status(&status, false).await;
Err(Error::InvalidInput)
}
}
@@ -304,7 +305,8 @@ async fn prepare_streaming_standard_data(
let mut producer = super::sighash::ChunkingProducer::from_host(request.data_length())
.with_preview(display_cap);
let hash = {
- let mut progress = hal.ui().progress_create("Loading data...");
+ let title = crate::tr!(hal, "Loading data...");
+ let mut progress = hal.ui().progress_create(&title);
let mut producer = super::sighash::ProgressProducer::new(&mut producer, &mut progress);
match request {
Transaction::Legacy(legacy) => {
@@ -355,9 +357,10 @@ async fn verify_erc20_transaction(
{
let contract_address = super::address::from_pubkey_hash(&contract, request.case()?);
let contract_address_display = super::address::format_display_address(&contract_address);
+ let title = crate::tr!(hal, "Token\ncontract");
hal.ui()
.confirm(&ConfirmParams {
- title: "Token\ncontract",
+ title: &title,
body: &contract_address_display,
scrollable: true,
accept_is_nextarrow: true,
@@ -403,7 +406,10 @@ async fn verify_erc20_transaction(
// ERC20 token: fee has a different unit (ETH), so the total is just the value again.
(value.clone(), value.clone())
}
- None => ("Unknown token".into(), "Unknown amount".into()),
+ None => (
+ crate::tr!(hal, "Unknown token").into_owned(),
+ crate::tr!(hal, "Unknown amount").into_owned(),
+ ),
};
hal.ui()
.verify_recipient(&recipient_address_display, &formatted_value)
@@ -460,26 +466,39 @@ async fn verify_standard_transaction(
let mut prepared_streaming_data = None;
if !request.data().is_empty() || data_length > 0 {
+ let title = crate::tr!(hal, "Unknown\ncontract");
+ let body = if data_length > 0 {
+ crate::tr!(
+ hal,
+ "You are signing a\ncontract interaction\nwith large data."
+ )
+ } else {
+ crate::tr!(hal, "You will be shown\nthe raw\ntransaction data.")
+ };
hal.ui()
.confirm(&ConfirmParams {
- title: "Unknown\ncontract",
- body: if data_length > 0 {
- "You are signing a\ncontract interaction\nwith large data."
- } else {
- "You will be shown\nthe raw\ntransaction data."
- },
+ title: &title,
+ body: &body,
accept_is_nextarrow: true,
..Default::default()
})
.await?;
+ let title = crate::tr!(hal, "Unknown\ncontract");
+ let body = if data_length > 0 {
+ crate::tr!(
+ hal,
+ "Only proceed if you\nfully understand\nthe risks involved."
+ )
+ } else {
+ crate::tr!(
+ hal,
+ "Only proceed if you\nunderstand exactly\nwhat the data means."
+ )
+ };
hal.ui()
.confirm(&ConfirmParams {
- title: "Unknown\ncontract",
- body: if data_length > 0 {
- "Only proceed if you\nfully understand\nthe risks involved."
- } else {
- "Only proceed if you\nunderstand exactly\nwhat the data means."
- },
+ title: &title,
+ body: &body,
accept_is_nextarrow: true,
..Default::default()
})
@@ -494,10 +513,11 @@ async fn verify_standard_transaction(
} else {
(request.data().len(), hex::encode(request.data()))
};
+ let title = crate::tr!(hal, "Transaction\ndata");
confirm::confirm_value(
hal,
&ConfirmParams {
- title: "Transaction\ndata",
+ title: &title,
body: &body,
scrollable: true,
display_size,
@@ -537,9 +557,10 @@ pub async fn _process(
// Show chain confirmation only for known networks
if super::params::is_known_network(request.coin()?, request.chain_id()) {
+ let body = crate::tr_format!(hal, "Sign transaction on\n\n{}", &[params.name]);
hal.ui()
.confirm(&ConfirmParams {
- body: &format!("Sign transaction on\n\n{}", params.name),
+ body: &body,
accept_is_nextarrow: true,
..Default::default()
})
@@ -626,7 +647,8 @@ pub async fn _process(
precomputed_standard_hash =
verify_standard_transaction(hal, request, ¶ms, payment_request).await?;
}
- hal.ui().status("Transaction\nconfirmed", true).await;
+ let status = crate::tr!(hal, "Transaction\nconfirmed");
+ hal.ui().status(&status, true).await;
let hash: [u8; 32] = match precomputed_standard_hash {
Some(hash) => hash,
@@ -683,7 +705,8 @@ pub async fn process(
) -> Result<Response, Error> {
let result = _process(hal, request).await;
if let Err(Error::UserAbort) = result {
- hal.ui().status("Transaction\ncanceled", false).await;
+ let status = crate::tr!(hal, "Transaction\ncanceled");
+ hal.ui().status(&status, false).await;
}
result
}
### src/rust/bitbox02-rust/src/hww/api/ethereum/sign_typed_msg.rs
@@ -14,6 +14,7 @@ use super::truncating_hex_preview_byte_cap;
use crate::hal::Ui;
use crate::hal::ui::{ConfirmParams, Font};
+use crate::i18n::I18n as _;
use crate::keystore;
use crate::workflow::confirm;
@@ -389,9 +390,17 @@ fn confirm_title(root_object: RootObject) -> &'static str {
}
}
-fn format_display_line_prefix(display_path: &str, line_num: usize, num_lines: usize) -> String {
+fn format_display_line_prefix(
+ display_path: &str,
+ line_num: usize,
+ num_lines: usize,
+ line_suffix: Option<&str>,
+) -> String {
if num_lines > 1 {
- format!("{display_path}, line {}/{}", line_num + 1, num_lines)
+ match line_suffix {
+ Some(line_suffix) => format!("{display_path}{line_suffix}"),
+ None => format!("{display_path}, line {}/{}", line_num + 1, num_lines),
+ }
} else {
display_path.to_string()
}
@@ -402,10 +411,11 @@ fn format_display_line_body(
line_num: usize,
num_lines: usize,
line: &str,
+ line_suffix: Option<&str>,
) -> String {
format!(
"{}: {}",
- format_display_line_prefix(display_path, line_num, num_lines),
+ format_display_line_prefix(display_path, line_num, num_lines, line_suffix),
line
)
}
@@ -464,14 +474,19 @@ async fn encode_member<U: sha3::digest::Update>(
display_size = req.data_length as usize;
let display_cap = truncating_hex_preview_byte_cap(
- format!("{}: 0x", format_display_line_prefix(&display_path, 0, 1)).len(),
+ format!(
+ "{}: 0x",
+ format_display_line_prefix(&display_path, 0, 1, None)
+ )
+ .len(),
display_size,
);
let mut producer = super::sighash::ChunkingProducer::from_host(req.data_length)
.with_preview(display_cap);
let mut keccak = sha3::Keccak256::new();
{
- let mut progress = hal.ui().progress_create("Loading data...");
+ let title = crate::tr!(hal, "Loading data...");
+ let mut progress = hal.ui().progress_create(&title);
let mut producer =
super::sighash::ProgressProducer::new(&mut producer, &mut progress);
while let Some(chunk) = producer.next().await? {
@@ -494,15 +509,29 @@ async fn encode_member<U: sha3::digest::Update>(
// Display value, splitting multi-line strings into separate screens.
let lines: Vec<&str> = value_formatted.split('\n').collect();
for (i, &line) in lines.iter().enumerate() {
- let body = format_display_line_body(&display_path, i, lines.len(), line);
+ let line_suffix = (lines.len() > 1).then(|| {
+ crate::tr_format!(
+ hal,
+ ", line {}/{}",
+ &[&(i + 1).to_string(), &lines.len().to_string()],
+ )
+ });
+ let body = format_display_line_body(
+ &display_path,
+ i,
+ lines.len(),
+ line,
+ line_suffix.as_deref(),
+ );
+ let title = format!(
+ "{}{}",
+ hal.tr(confirm_title(context.root_object)),
+ context.title_suffix.as_deref().unwrap_or("")
+ );
confirm::confirm_value(
hal,
&ConfirmParams {
- title: &format!(
- "{}{}",
- confirm_title(context.root_object),
- context.title_suffix.as_deref().unwrap_or("")
- ),
+ title: &title,
body: &body,
scrollable: true,
display_size,
@@ -536,29 +565,31 @@ async fn hash_array(
let array_type = member_type.array_type.as_ref().ok_or(Error::InvalidInput)?;
- confirm::confirm_value(
- hal,
- &ConfirmParams {
- title: &format!(
- "{}{}",
- confirm_title(context.root_object),
- context.title_suffix.as_deref().unwrap_or("")
- ),
- body: &format!(
- "{}: {}",
- context.formatted_path.join("."),
- if array_size == 0 {
- "(empty list)".into()
- } else {
- format!("list with {} elements", array_size)
- }
- ),
- scrollable: true,
- accept_is_nextarrow: true,
- ..Default::default()
- },
- )
- .await?;
+ // Free the labels before recursion to avoid accumulating them for nested arrays.
+ {
+ let title = format!(
+ "{}{}",
+ hal.tr(confirm_title(context.root_object)),
+ context.title_suffix.as_deref().unwrap_or("")
+ );
+ let list_description = if array_size == 0 {
+ crate::tr!(hal, "(empty list)").into_owned()
+ } else {
+ crate::tr_format!(hal, "list with {} elements", &[&array_size.to_string()])
+ };
+ let body = format!("{}: {}", context.formatted_path.join("."), list_description);
+ confirm::confirm_value(
+ hal,
+ &ConfirmParams {
+ title: &title,
+ body: &body,
+ scrollable: true,
+ accept_is_nextarrow: true,
+ ..Default::default()
+ },
+ )
+ .await?;
+ }
let mut hasher = sha3::Keccak256::new();
let mut child_path = context.path.to_vec();
@@ -614,7 +645,7 @@ async fn hash_struct(
title_suffix: if context.title_suffix.is_some() {
context.title_suffix.clone()
} else {
- Some(format!(" ({}/{})", index + 1, typ.members.len()))
+ Some(format!("\n({}/{})", index + 1, typ.members.len()))
},
cached_chain_id: context.cached_chain_id,
};
@@ -718,10 +749,15 @@ pub async fn process(
let cached_chain_id = validate_chain_id(request).await?;
if cached_chain_id.is_none() {
+ let title = crate::tr!(hal, "Warning");
+ let body = crate::tr!(
+ hal,
+ "Typed data has no chain ID. Message is valid for every chain."
+ );
hal.ui()
.confirm(&ConfirmParams {
- title: "Warning",
- body: "Typed data has no chain ID. Message is valid for every chain.",
+ title: &title,
+ body: &body,
scrollable: true,
accept_is_nextarrow: true,
..Default::default()
@@ -749,10 +785,11 @@ pub async fn process(
)
.await?;
+ let title = crate::tr!(hal, "Message type");
confirm::confirm_value(
hal,
&ConfirmParams {
- title: "Message type",
+ title: &title,
body: &request.primary_type,
scrollable: true,
accept_is_nextarrow: true,
@@ -769,9 +806,10 @@ pub async fn process(
)
.await?;
+ let body = crate::tr!(hal, "Sign data?");
hal.ui()
.confirm(&ConfirmParams {
- body: "Sign data?",
+ body: &body,
longtouch: true,
..Default::default()
})
@@ -1493,6 +1531,7 @@ mod tests {
0,
1,
&format!("0x{}", hex::encode(vec![0u8; exact_fit])),
+ None,
);
assert_eq!(exact_fit_body.len(), MAX_CONFIRM_BODY_SIZE);
@@ -1503,6 +1542,7 @@ mod tests {
0,
1,
&format!("0x{}", hex::encode(vec![0u8; truncated])),
+ None,
);
assert!(truncated_body.len() > MAX_CONFIRM_BODY_SIZE);
}
@@ -1517,17 +1557,17 @@ mod tests {
mock_hal.ui.screens,
vec![
Screen::Confirm {
- title: "Domain (1/1)".into(),
+ title: "Domain\n(1/1)".into(),
body: "name: test".into(),
longtouch: false,
},
Screen::Confirm {
- title: "Message (1/1)".into(),
+ title: "Message\n(1/1)".into(),
body: format!("data, line 1/2: {line1}"),
longtouch: false,
},
Screen::Confirm {
- title: "Message (1/1)".into(),
+ title: "Message\n(1/1)".into(),
body: format!("data, line 2/2: {line2}"),
longtouch: false,
},
@@ -1545,12 +1585,12 @@ mod tests {
mock_hal.ui.screens,
vec![
Screen::Confirm {
- title: "Domain (1/1)".into(),
+ title: "Domain\n(1/1)".into(),
body: "name: test".into(),
longtouch: false,
},
Screen::Confirm {
- title: "Message (1/1)".into(),
+ title: "Message\n(1/1)".into(),
body: "data, line 1/2: ok".into(),
longtouch: false,
},
@@ -1560,7 +1600,7 @@ mod tests {
longtouch: false,
},
Screen::Confirm {
- title: "Message (1/1)".into(),
+ title: "Message\n(1/1)".into(),
body: format!("data, line 2/2: {line2}"),
longtouch: false,
},
@@ -1590,7 +1630,7 @@ mod tests {
assert_eq!(
mock_hal.ui.screens[2],
Screen::Confirm {
- title: "Message (1/1)".into(),
+ title: "Message\n(1/1)".into(),
body: format!("{member_name}: (empty list)"),
longtouch: false,
}
@@ -1617,7 +1657,7 @@ mod tests {
);
match &mock_hal.ui.screens[2] {
Screen::Confirm { title, body, .. } => {
- assert_eq!(title, "Message (1/1)");
+ assert_eq!(title, "Message\n(1/1)");
assert!(body.len() > MAX_CONFIRM_BODY_SIZE);
}
_ => panic!("unexpected screen"),
@@ -1934,22 +1974,22 @@ mod tests {
mock_hal.ui.screens,
vec![
Screen::Confirm {
- title: "Domain (1/4)".into(),
+ title: "Domain\n(1/4)".into(),
body: "name: Ether Mail".into(),
longtouch: false,
},
Screen::Confirm {
- title: "Domain (2/4)".into(),
+ title: "Domain\n(2/4)".into(),
body: "version: 1".into(),
longtouch: false,
},
Screen::Confirm {
- title: "Domain (3/4)".into(),
+ title: "Domain\n(3/4)".into(),
body: "chainId: 1".into(),
longtouch: false,
},
Screen::Confirm {
- title: "Domain (4/4)".into(),
+ title: "Domain\n(4/4)".into(),
body: "verifyingContract: 0x CcCC cccc CCCC cCCC CCCc CcCc cCcC CCcC cccc cccC"
.into(),
longtouch: false,
@@ -2151,169 +2191,172 @@ mod tests {
#[async_test::test]
async fn test_exhaustive_data() {
const EXPECTED_DIALOGS: &[(&str, &str)] = &[
- ("Domain (1/4)", "name: Ether Mail"),
- ("Domain (2/4)", "version: 1"),
- ("Domain (3/4)", "chainId: 1"),
+ ("Domain\n(1/4)", "name: Ether Mail"),
+ ("Domain\n(2/4)", "version: 1"),
+ ("Domain\n(3/4)", "chainId: 1"),
(
- "Domain (4/4)",
+ "Domain\n(4/4)",
"verifyingContract: 0x CcCC cccc CCCC cCCC CCCc CcCc cCcC CCcC cccc cccC",
),
- ("Message (1/23)", "str: str"),
- ("Message (2/23)", "emptyArray: (empty list)"),
+ ("Message\n(1/23)", "str: str"),
+ ("Message\n(2/23)", "emptyArray: (empty list)"),
(
- "Message (3/23)",
+ "Message\n(3/23)",
"name_address: 0x a21A 16EC 22a9 4099 0922 220E 4ab5 bF4C 2310 F556",
),
- ("Message (4/23)", "name_string: list with 6 elements"),
- ("Message (4/23)", "name_string[1/6]: "),
- ("Message (4/23)", "name_string[2/6]: a"),
- ("Message (4/23)", "name_string[3/6]: aa"),
- ("Message (4/23)", "name_string[4/6]: |@#!$"),
+ ("Message\n(4/23)", "name_string: list with 6 elements"),
+ ("Message\n(4/23)", "name_string[1/6]: "),
+ ("Message\n(4/23)", "name_string[2/6]: a"),
+ ("Message\n(4/23)", "name_string[3/6]: aa"),
+ ("Message\n(4/23)", "name_string[4/6]: |@#!$"),
(
- "Message (4/23)",
+ "Message\n(4/23)",
"name_string[5/6]: long long long long long long long long",
),
- ("Message (4/23)", "name_string[6/6], line 1/3: multi"),
- ("Message (4/23)", "name_string[6/6], line 2/3: "),
- ("Message (4/23)", "name_string[6/6], line 3/3: line"),
- ("Message (5/23)", "name_bytes: list with 2 elements"),
- ("Message (5/23)", "name_bytes[1/2]: 0x"),
- ("Message (5/23)", "name_bytes[2/2]: 0xaabbcc"),
- ("Message (6/23)", "name_bytes1: 0xaa"),
- ("Message (7/23)", "name_bytes10: 0x112233445566778899aa"),
+ ("Message\n(4/23)", "name_string[6/6], line 1/3: multi"),
+ ("Message\n(4/23)", "name_string[6/6], line 2/3: "),
+ ("Message\n(4/23)", "name_string[6/6], line 3/3: line"),
+ ("Message\n(5/23)", "name_bytes: list with 2 elements"),
+ ("Message\n(5/23)", "name_bytes[1/2]: 0x"),
+ ("Message\n(5/23)", "name_bytes[2/2]: 0xaabbcc"),
+ ("Message\n(6/23)", "name_bytes1: 0xaa"),
+ ("Message\n(7/23)", "name_bytes10: 0x112233445566778899aa"),
(
- "Message (8/23)",
+ "Message\n(8/23)",
"name_bytes32: 0xd0f02988fd881565e927c7473c287322db166901bac03bef55d7a52a5c750ab4",
),
- ("Message (9/23)", "name_uint8: list with 4 elements"),
- ("Message (9/23)", "name_uint8[1/4]: 0"),
- ("Message (9/23)", "name_uint8[2/4]: 1"),
- ("Message (9/23)", "name_uint8[3/4]: 10"),
- ("Message (9/23)", "name_uint8[4/4]: 255"),
- ("Message (10/23)", "name_uint32: list with 4 elements"),
- ("Message (10/23)", "name_uint32[1/4]: 0"),
- ("Message (10/23)", "name_uint32[2/4]: 256"),
- ("Message (10/23)", "name_uint32[3/4]: 65536"),
- ("Message (10/23)", "name_uint32[4/4]: 4294967295"),
- ("Message (11/23)", "name_uint64: 18446744073709551615"),
+ ("Message\n(9/23)", "name_uint8: list with 4 elements"),
+ ("Message\n(9/23)", "name_uint8[1/4]: 0"),
+ ("Message\n(9/23)", "name_uint8[2/4]: 1"),
+ ("Message\n(9/23)", "name_uint8[3/4]: 10"),
+ ("Message\n(9/23)", "name_uint8[4/4]: 255"),
+ ("Message\n(10/23)", "name_uint32: list with 4 elements"),
+ ("Message\n(10/23)", "name_uint32[1/4]: 0"),
+ ("Message\n(10/23)", "name_uint32[2/4]: 256"),
+ ("Message\n(10/23)", "name_uint32[3/4]: 65536"),
+ ("Message\n(10/23)", "name_uint32[4/4]: 4294967295"),
+ ("Message\n(11/23)", "name_uint64: 18446744073709551615"),
(
- "Message (12/23)",
+ "Message\n(12/23)",
"name_uint128: 340282366920938463463374607431768211455",
),
(
- "Message (13/23)",
+ "Message\n(13/23)",
"name_uint256: 115792089237316195423570985008687907853269984665640564039457584007913129639935",
),
- ("Message (14/23)", "name_int8: list with 5 elements"),
- ("Message (14/23)", "name_int8[1/5]: 0"),
- ("Message (14/23)", "name_int8[2/5]: 10"),
- ("Message (14/23)", "name_int8[3/5]: -10"),
- ("Message (14/23)", "name_int8[4/5]: 127"),
- ("Message (14/23)", "name_int8[5/5]: -128"),
- ("Message (15/23)", "name_int32: list with 2 elements"),
- ("Message (15/23)", "name_int32[1/2]: 2147483647"),
- ("Message (15/23)", "name_int32[2/2]: -2147483648"),
- ("Message (16/23)", "name_int64: list with 4 elements"),
- ("Message (16/23)", "name_int64[1/4]: 500"),
- ("Message (16/23)", "name_int64[2/4]: -500"),
- ("Message (16/23)", "name_int64[3/4]: 9223372036854775807"),
- ("Message (16/23)", "name_int64[4/4]: -9223372036854775808"),
- ("Message (17/23)", "name_int128: list with 2 elements"),
+ ("Message\n(14/23)", "name_int8: list with 5 elements"),
+ ("Message\n(14/23)", "name_int8[1/5]: 0"),
+ ("Message\n(14/23)", "name_int8[2/5]: 10"),
+ ("Message\n(14/23)", "name_int8[3/5]: -10"),
+ ("Message\n(14/23)", "name_int8[4/5]: 127"),
+ ("Message\n(14/23)", "name_int8[5/5]: -128"),
+ ("Message\n(15/23)", "name_int32: list with 2 elements"),
+ ("Message\n(15/23)", "name_int32[1/2]: 2147483647"),
+ ("Message\n(15/23)", "name_int32[2/2]: -2147483648"),
+ ("Message\n(16/23)", "name_int64: list with 4 elements"),
+ ("Message\n(16/23)", "name_int64[1/4]: 500"),
+ ("Message\n(16/23)", "name_int64[2/4]: -500"),
+ ("Message\n(16/23)", "name_int64[3/4]: 9223372036854775807"),
+ ("Message\n(16/23)", "name_int64[4/4]: -9223372036854775808"),
+ ("Message\n(17/23)", "name_int128: list with 2 elements"),
(
- "Message (17/23)",
+ "Message\n(17/23)",
"name_int128[1/2]: 170141183460469231731687303715884105727",
),
(
- "Message (17/23)",
+ "Message\n(17/23)",
"name_int128[2/2]: -170141183460469231731687303715884105728",
),
- ("Message (18/23)", "name_int256: list with 2 elements"),
+ ("Message\n(18/23)", "name_int256: list with 2 elements"),
(
- "Message (18/23)",
+ "Message\n(18/23)",
"name_int256[1/2]: 57896044618658097711785492504343953926634992332820282019728792003956564819967",
),
(
- "Message (18/23)",
+ "Message\n(18/23)",
"name_int256[2/2]: -57896044618658097711785492504343953926634992332820282019728792003956564819968",
),
- ("Message (19/23)", "name_bool: list with 2 elements"),
- ("Message (19/23)", "name_bool[1/2]: false"),
- ("Message (19/23)", "name_bool[2/2]: true"),
- ("Message (20/23)", "name_struct.name: struct name"),
- ("Message (20/23)", "name_struct.arr: (empty list)"),
- ("Message (21/23)", "arrayOfStructs: list with 3 elements"),
- ("Message (21/23)", "arrayOfStructs[1/3].name: name 1"),
- ("Message (21/23)", "arrayOfStructs[1/3].arr: (empty list)"),
- ("Message (21/23)", "arrayOfStructs[2/3].name: name 2"),
+ ("Message\n(19/23)", "name_bool: list with 2 elements"),
+ ("Message\n(19/23)", "name_bool[1/2]: false"),
+ ("Message\n(19/23)", "name_bool[2/2]: true"),
+ ("Message\n(20/23)", "name_struct.name: struct name"),
+ ("Message\n(20/23)", "name_struct.arr: (empty list)"),
+ ("Message\n(21/23)", "arrayOfStructs: list with 3 elements"),
+ ("Message\n(21/23)", "arrayOfStructs[1/3].name: name 1"),
+ ("Message\n(21/23)", "arrayOfStructs[1/3].arr: (empty list)"),
+ ("Message\n(21/23)", "arrayOfStructs[2/3].name: name 2"),
(
- "Message (21/23)",
+ "Message\n(21/23)",
"arrayOfStructs[2/3].arr: list with 1 elements",
),
- ("Message (21/23)", "arrayOfStructs[2/3].arr[1/1]: false"),
- ("Message (21/23)", "arrayOfStructs[3/3].name: name 3"),
+ ("Message\n(21/23)", "arrayOfStructs[2/3].arr[1/1]: false"),
+ ("Message\n(21/23)", "arrayOfStructs[3/3].name: name 3"),
(
- "Message (21/23)",
+ "Message\n(21/23)",
"arrayOfStructs[3/3].arr: list with 2 elements",
),
- ("Message (21/23)", "arrayOfStructs[3/3].arr[1/2]: false"),
- ("Message (21/23)", "arrayOfStructs[3/3].arr[2/2]: true"),
+ ("Message\n(21/23)", "arrayOfStructs[3/3].arr[1/2]: false"),
+ ("Message\n(21/23)", "arrayOfStructs[3/3].arr[2/2]: true"),
(
- "Message (22/23)",
+ "Message\n(22/23)",
"fixedArrayOfStructs: list with 2 elements",
),
- ("Message (22/23)", "fixedArrayOfStructs[1/2].name: name 1"),
+ ("Message\n(22/23)", "fixedArrayOfStructs[1/2].name: name 1"),
(
- "Message (22/23)",
+ "Message\n(22/23)",
"fixedArrayOfStructs[1/2].arr: (empty list)",
),
- ("Message (22/23)", "fixedArrayOfStructs[2/2].name: name 2"),
+ ("Message\n(22/23)", "fixedArrayOfStructs[2/2].name: name 2"),
(
- "Message (22/23)",
+ "Message\n(22/23)",
"fixedArrayOfStructs[2/2].arr: list with 3 elements",
),
(
- "Message (22/23)",
+ "Message\n(22/23)",
"fixedArrayOfStructs[2/2].arr[1/3]: false",
),
(
- "Message (22/23)",
+ "Message\n(22/23)",
"fixedArrayOfStructs[2/2].arr[2/3]: false",
),
- ("Message (22/23)", "fixedArrayOfStructs[2/2].arr[3/3]: true"),
- ("Message (23/23)", "nestedArray: list with 3 elements"),
- ("Message (23/23)", "nestedArray[1/3]: list with 2 elements"),
(
- "Message (23/23)",
+ "Message\n(22/23)",
+ "fixedArrayOfStructs[2/2].arr[3/3]: true",
+ ),
+ ("Message\n(23/23)", "nestedArray: list with 3 elements"),
+ ("Message\n(23/23)", "nestedArray[1/3]: list with 2 elements"),
+ (
+ "Message\n(23/23)",
"nestedArray[1/3][1/2]: list with 2 elements",
),
- ("Message (23/23)", "nestedArray[1/3][1/2][1/2]: 1"),
- ("Message (23/23)", "nestedArray[1/3][1/2][2/2]: 2"),
+ ("Message\n(23/23)", "nestedArray[1/3][1/2][1/2]: 1"),
+ ("Message\n(23/23)", "nestedArray[1/3][1/2][2/2]: 2"),
(
- "Message (23/23)",
+ "Message\n(23/23)",
"nestedArray[1/3][2/2]: list with 3 elements",
),
- ("Message (23/23)", "nestedArray[1/3][2/2][1/3]: 3"),
- ("Message (23/23)", "nestedArray[1/3][2/2][2/3]: 4"),
- ("Message (23/23)", "nestedArray[1/3][2/2][3/3]: 5"),
- ("Message (23/23)", "nestedArray[2/3]: list with 2 elements"),
+ ("Message\n(23/23)", "nestedArray[1/3][2/2][1/3]: 3"),
+ ("Message\n(23/23)", "nestedArray[1/3][2/2][2/3]: 4"),
+ ("Message\n(23/23)", "nestedArray[1/3][2/2][3/3]: 5"),
+ ("Message\n(23/23)", "nestedArray[2/3]: list with 2 elements"),
(
- "Message (23/23)",
+ "Message\n(23/23)",
"nestedArray[2/3][1/2]: list with 2 elements",
),
- ("Message (23/23)", "nestedArray[2/3][1/2][1/2]: 6"),
- ("Message (23/23)", "nestedArray[2/3][1/2][2/2]: 7"),
+ ("Message\n(23/23)", "nestedArray[2/3][1/2][1/2]: 6"),
+ ("Message\n(23/23)", "nestedArray[2/3][1/2][2/2]: 7"),
(
- "Message (23/23)",
+ "Message\n(23/23)",
"nestedArray[2/3][2/2]: list with 1 elements",
),
- ("Message (23/23)", "nestedArray[2/3][2/2][1/1]: 8"),
- ("Message (23/23)", "nestedArray[3/3]: list with 2 elements"),
- ("Message (23/23)", "nestedArray[3/3][1/2]: (empty list)"),
+ ("Message\n(23/23)", "nestedArray[2/3][2/2][1/1]: 8"),
+ ("Message\n(23/23)", "nestedArray[3/3]: list with 2 elements"),
+ ("Message\n(23/23)", "nestedArray[3/3][1/2]: (empty list)"),
(
- "Message (23/23)",
+ "Message\n(23/23)",
"nestedArray[3/3][2/2]: list with 1 elements",
),
- ("Message (23/23)", "nestedArray[3/3][2/2][1/1]: 9"),
+ ("Message\n(23/23)", "nestedArray[3/3][2/2][1/1]: 9"),
];
let bytes32 = b"\xd0\xf0\x29\x88\xfd\x88\x15\x65\xe9\x27\xc7\x47\x3c\x28\x73\x22\xdb\x16\x69\x01\xba\xc0\x3b\xef\x55\xd7\xa5\x2a\x5c\x75\x0a\xb4";
### src/rust/bitbox02-rust/src/hww/api/ethereum/signmsg.rs
@@ -3,6 +3,7 @@
use super::Error;
use super::pb;
+use crate::i18n::I18n as _;
use crate::keystore;
use crate::workflow::verify_message;
@@ -39,7 +40,9 @@ pub async fn process(
// abort errors.
super::pubrequest::process(hal, &pub_request).await?;
- verify_message::verify(hal, "Sign message", "Sign", &request.msg, true).await?;
+ let title = crate::tr!(hal, "Sign message");
+ let accept = crate::tr!(hal, "Sign");
+ verify_message::verify(hal, &title, &accept, &request.msg, true).await?;
// Construct message to be signed. There is no standard for this. We match what MyEtherWallet,
// Trezor, etc. do, e.g.:
### src/rust/bitbox02-rust/src/hww/api/ethereum/testdata/typed_msg_streaming_tests.json
@@ -24,15 +24,15 @@
"expected_sighash": "8b791f4fc1a7fe8c2adc89877cee75b14aa23c896943c414b394a9e0cc3d0696",
"expected_screens": [
[
- "Domain (1/1)",
+ "Domain\n(1/1)",
"name: test"
],
[
"Warning",
"The next value is\ntoo large to display\nin full"
],
[
- "Message (1/1)",
+ "Message\n(1/1)",
"data: 0x000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f202122232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f404142434445464748494a4b4c4d4e4f505152535455565758595a5b5c5d5e5f606162636465666768696a6b6c6d6e6f707172737475767778797a7b7c7d7e7f808182838485868788898a8b8c8d8e8f909192939495969798999a9b9c9d9e9fa0a1a2a3a4a5a6a7a8a9aaabacadaeafb0b1b2b3b4b5b6b7b8b9babbbcbdbebfc0c1c2c3c4c5c6c7c8c9cacbcccdcecfd0d1d2d3d4d5d6d7d8d9dadbdcdddedfe0e1e2e3e4e5e6e7e8e9eaebecedeeeff0f1f2f3f4f5f6f7f8f9fafbfcfdfeff000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f202122232425262728292a2b2c2d2e2f303132333435363738393a3b3c"
]
],
@@ -64,19 +64,19 @@
"expected_sighash": "7599e2ee5cceee1de599875d5d71af1c09db0b03552a9673b205bf2e49b02066",
"expected_screens": [
[
- "Domain (1/1)",
+ "Domain\n(1/1)",
"name: test"
],
[
- "Message (1/1)",
+ "Message\n(1/1)",
"data, line 1/2: ok"
],
[
"Warning",
"The next value is\ntoo large to display\nin full"
],
[
- "Message (1/1)",
+ "Message\n(1/1)",
"data, line 2/2: bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"
]
]
### src/rust/bitbox02-rust/src/hww/api/payment_request.rs
@@ -11,6 +11,7 @@ use num_bigint::BigUint;
use pb::btc_payment_request_request::{Memo, memo};
use crate::hal::Ui;
+use crate::i18n::I18n as _;
use crate::secp256k1::SECP256K1;
use crate::workflow::verify_message;
@@ -158,24 +159,29 @@ pub async fn user_verify(
if !has_all_glyphs {
return Err(Error::InvalidInput);
}
+ let body =
+ crate::tr_format!(hal, "Memo from: {}", &[&payment_request.recipient_name]);
hal.ui()
.confirm(&ConfirmParams {
title: "",
- body: &format!("Memo from: {}", payment_request.recipient_name),
+ body: &body,
scrollable: true,
accept_is_nextarrow: true,
..Default::default()
})
.await?;
- verify_message::verify(hal, "Memo", "Memo", text_memo.note.as_bytes(), false)
+ let title = crate::tr!(hal, "Memo");
+ let accept = crate::tr!(hal, "Memo");
+ verify_message::verify(hal, &title, &accept, text_memo.note.as_bytes(), false)
.await?;
}
Memo {
memo: Some(memo::Memo::CoinPurchaseMemo(coin_purchase_memo)),
} => {
parse_coin_purchase_amount(&coin_purchase_memo.amount)?;
+ let title = crate::tr!(hal, "Swap");
hal.ui()
- .confirm_swap("Swap", displayed_source_amount, &coin_purchase_memo.amount)
+ .confirm_swap(&title, displayed_source_amount, &coin_purchase_memo.amount)
.await?;
}
_ => return Err(Error::InvalidInput),
### src/rust/bitbox02-rust/src/hww/api/reset.rs
@@ -2,16 +2,19 @@
use super::Error;
use crate::hal::ui::ConfirmParams;
+use crate::i18n::I18n as _;
use crate::pb;
use pb::response::Response;
use crate::hal::Ui;
pub async fn process(hal: &mut impl crate::hal::Hal) -> Result<Response, Error> {
+ let title = crate::tr!(hal, "RESET");
+ let body = crate::tr!(hal, "Proceed to\nfactory reset?");
let params = ConfirmParams {
- title: "RESET",
- body: "Proceed to\nfactory reset?",
+ title: &title,
+ body: &body,
longtouch: true,
..Default::default()
};
### src/rust/bitbox02-rust/src/hww/api/restore.rs
@@ -2,6 +2,7 @@
use super::Error;
use crate::hal::ui::{ConfirmParams, Font};
+use crate::i18n::I18n as _;
use crate::pb;
use pb::response::Response;
@@ -16,9 +17,10 @@ pub async fn from_file(
request: &pb::RestoreBackupRequest,
) -> Result<Response, Error> {
// This is a separate screen because 'Restore backup?' does not fit in the title field.
+ let body = crate::tr!(hal, "Restore backup?");
hal.ui()
.confirm(&ConfirmParams {
- body: "Restore backup?",
+ body: &body,
accept_is_nextarrow: true,
..Default::default()
})
@@ -27,7 +29,8 @@ pub async fn from_file(
let (data, metadata) = match crate::backup::load(hal, &request.id).await {
Ok(d) => d,
Err(_) => {
- hal.ui().status("Could not\nrestore backup", false).await;
+ let status = crate::tr!(hal, "Could not\nrestore backup");
+ hal.ui().status(&status, false).await;
return Err(Error::Generic);
}
};
@@ -36,9 +39,10 @@ pub async fn from_file(
let ui = hal.ui();
crate::backup::sanitize_name(&metadata.name, |c| ui.has_glyph(Font::Regular11, c))
};
+ let body = crate::tr_format!(hal, "Name: {}. ID: {}", &[&device_name, &request.id]);
hal.ui()
.confirm(&ConfirmParams {
- body: &format!("Name: {}. ID: {}", &device_name, &request.id),
+ body: &body,
scrollable: true,
accept_is_nextarrow: true,
..Default::default()
@@ -47,11 +51,12 @@ pub async fn from_file(
#[cfg(feature = "app-u2f")]
{
- let datetime_string =
- util::datetime::format_datetime(request.timestamp, request.timezone_offset, false)
- .map_err(|_| Error::InvalidInput)?;
+ let datetime_string = hal
+ .tr_datetime(request.timestamp, request.timezone_offset, false)
+ .map_err(|_| Error::InvalidInput)?;
+ let title = crate::tr!(hal, "Is now?");
let params = ConfirmParams {
- title: "Is now?",
+ title: &title,
body: &datetime_string,
accept_is_nextarrow: true,
..Default::default()
@@ -64,15 +69,10 @@ pub async fn from_file(
let seed = data.get_seed();
if let Err(err) = crate::keystore::encrypt_and_store_seed(hal, seed, &password).await {
drop(unlock_animation);
- hal.ui()
- .status(
- &format!(
- "Could not\nrestore backup\n{}",
- crate::keystore::format_error(&err)
- ),
- false,
- )
- .await;
+ let mut status = crate::tr!(hal, "Could not\nrestore backup").into_owned();
+ status.push('\n');
+ status.push_str(&crate::keystore::format_error(&err));
+ hal.ui().status(&status, false).await;
return Err(Error::Generic);
}
@@ -105,37 +105,43 @@ pub async fn from_mnemonic(
) -> Result<Response, Error> {
#[cfg(feature = "app-u2f")]
{
- let datetime_string = util::datetime::format_datetime(timestamp, timezone_offset, false)
+ let datetime_string = hal
+ .tr_datetime(timestamp, timezone_offset, false)
.map_err(|_| Error::InvalidInput)?;
+ let title = crate::tr!(hal, "Is now?");
hal.ui()
.confirm(&ConfirmParams {
- title: "Is now?",
+ title: &title,
body: &datetime_string,
accept_is_nextarrow: true,
..Default::default()
})
.await?;
}
- let mnemonic = crate::workflow::mnemonic::get(hal.ui()).await?;
+ let language = hal.memory().get_device_language();
+ let mnemonic = crate::workflow::mnemonic::get_with_language(hal.ui(), language).await?;
let seed = match crate::bip39::mnemonic_to_seed(&mnemonic) {
Ok(seed) => seed,
Err(()) => {
- hal.ui().status("Recovery words\ninvalid", false).await;
+ let status = crate::tr!(hal, "Recovery words\ninvalid");
+ hal.ui().status(&status, false).await;
return Err(Error::Generic);
}
};
- hal.ui().status("Recovery words\nvalid", true).await;
+ let status = crate::tr!(hal, "Recovery words\nvalid");
+ hal.ui().status(&status, true).await;
// If entering password fails (repeat password does not match the first), we don't want to abort
// the process immediately. We break out only if the user confirms.
let password = loop {
match password::enter_twice(hal).await {
Err(password::EnterTwiceError::DoNotMatch) => {
+ let body = crate::tr!(hal, "Passwords\ndo not match.\nTry again?");
hal.ui()
.confirm(&ConfirmParams {
title: "",
- body: "Passwords\ndo not match.\nTry again?",
+ body: &body,
..Default::default()
})
.await?;
@@ -148,15 +154,10 @@ pub async fn from_mnemonic(
if let Err(err) = crate::keystore::encrypt_and_store_seed(hal, &seed, &password).await {
drop(unlock_animation);
- hal.ui()
- .status(
- &format!(
- "Could not\nrestore backup\n{}",
- crate::keystore::format_error(&err)
- ),
- false,
- )
- .await;
+ let mut status = crate::tr!(hal, "Could not\nrestore backup").into_owned();
+ status.push('\n');
+ status.push_str(&crate::keystore::format_error(&err));
+ hal.ui().status(&status, false).await;
return Err(Error::Generic);
};
### src/rust/bitbox02-rust/src/hww/api/set_device_language.rs
@@ -0,0 +1,133 @@
+// SPDX-License-Identifier: Apache-2.0
+
+use super::Error;
+use crate::hal::ui::ConfirmParams;
+use crate::hal::{Memory, Ui};
+use crate::pb;
+
+use bitbox_hal::memory::Language;
+use pb::response::Response;
+
+pub async fn process(
+ hal: &mut impl crate::hal::Hal,
+ pb::SetDeviceLanguageRequest { language }: &pb::SetDeviceLanguageRequest,
+) -> Result<Response, Error> {
+ let language = crate::i18n::language_from_code(language).ok_or(Error::InvalidInput)?;
+ let current_language = hal.memory().get_device_language();
+ let language_name = language_name(current_language, language);
+ let body = crate::i18n::format(
+ current_language,
+ "Change language\nto {}?",
+ &[language_name.as_ref()],
+ );
+ hal.ui()
+ .confirm(&ConfirmParams {
+ body: &body,
+ ..Default::default()
+ })
+ .await?;
+ hal.memory().set_device_language(language)?;
+ Ok(Response::Success(pb::Success {}))
+}
+
+fn language_name(
+ current_language: Language,
+ language: Language,
+) -> alloc::borrow::Cow<'static, str> {
+ match language {
+ Language::English => crate::i18n::translate(current_language, "English"),
+ Language::German => crate::i18n::translate(current_language, "German"),
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ use crate::hal::testing::TestingHal;
+ use crate::hal::testing::ui::Screen;
+
+ #[async_test::test]
+ async fn test_set_device_language() {
+ let mut mock_hal = TestingHal::new();
+ assert_eq!(
+ process(
+ &mut mock_hal,
+ &pb::SetDeviceLanguageRequest {
+ language: "de".into()
+ }
+ )
+ .await,
+ Ok(Response::Success(pb::Success {}))
+ );
+ assert_eq!(
+ mock_hal.ui.screens,
+ vec![Screen::Confirm {
+ title: "".into(),
+ body: "Change language\nto German?".into(),
+ longtouch: false,
+ }]
+ );
+ assert_eq!(
+ mock_hal.memory.get_device_language(),
+ bitbox_hal::memory::Language::German
+ );
+
+ assert_eq!(
+ process(
+ &mut mock_hal,
+ &pb::SetDeviceLanguageRequest {
+ language: "en-US".into()
+ }
+ )
+ .await,
+ Ok(Response::Success(pb::Success {}))
+ );
+ assert_eq!(
+ mock_hal.ui.screens,
+ vec![
+ Screen::Confirm {
+ title: "".into(),
+ body: "Change language\nto German?".into(),
+ longtouch: false,
+ },
+ Screen::Confirm {
+ title: "".into(),
+ body: "Sprache ändern\nauf Englisch?".into(),
+ longtouch: false,
+ },
+ ]
+ );
+ assert_eq!(
+ mock_hal.memory.get_device_language(),
+ bitbox_hal::memory::Language::English
+ );
+
+ mock_hal.ui.abort_nth(2);
+ assert_eq!(
+ process(
+ &mut mock_hal,
+ &pb::SetDeviceLanguageRequest {
+ language: "de".into()
+ }
+ )
+ .await,
+ Err(Error::UserAbort)
+ );
+ assert_eq!(
+ mock_hal.memory.get_device_language(),
+ bitbox_hal::memory::Language::English
+ );
+
+ assert_eq!(
+ process(
+ &mut mock_hal,
+ &pb::SetDeviceLanguageRequest {
+ language: "fr".into()
+ }
+ )
+ .await,
+ Err(Error::InvalidInput)
+ );
+ }
+}
### src/rust/bitbox02-rust/src/hww/api/set_device_name.rs
@@ -2,6 +2,7 @@
use super::Error;
use crate::hal::ui::{ConfirmParams, Font};
+use crate::i18n::I18n as _;
use crate::pb;
use pb::response::Response;
@@ -28,8 +29,9 @@ pub async fn process(
return Err(Error::InvalidInput);
}
+ let title = crate::tr!(hal, "Name");
let params = ConfirmParams {
- title: "Name",
+ title: &title,
body: name,
scrollable: true,
..Default::default()
### src/rust/bitbox02-rust/src/hww/api/set_mnemonic_passphrase_enabled.rs
@@ -2,6 +2,7 @@
use super::Error;
use crate::hal::ui::ConfirmParams;
+use crate::i18n::I18n as _;
use crate::pb;
use pb::response::Response;
@@ -12,9 +13,15 @@ pub async fn process(
hal: &mut impl crate::hal::Hal,
&pb::SetMnemonicPassphraseEnabledRequest { enabled }: &pb::SetMnemonicPassphraseEnabledRequest,
) -> Result<Response, Error> {
+ let title = if enabled {
+ crate::tr!(hal, "Enable")
+ } else {
+ crate::tr!(hal, "Disable")
+ };
+ let body = crate::tr!(hal, "Optional\npassphrase");
let params = ConfirmParams {
- title: if enabled { "Enable" } else { "Disable" },
- body: "Optional\npassphrase",
+ title: &title,
+ body: &body,
longtouch: true,
..Default::default()
};
### src/rust/bitbox02-rust/src/hww/api/show_mnemonic.rs
@@ -1,6 +1,7 @@
// SPDX-License-Identifier: Apache-2.0
use crate::hal::ui::{CanCancel, ConfirmParams};
+use crate::i18n::I18n as _;
use alloc::vec::Vec;
use super::Error;
@@ -18,27 +19,32 @@ use crate::workflow::unlock;
pub async fn process(hal: &mut impl crate::hal::Hal) -> Result<Response, Error> {
let mnemonic_sentence = {
let seed = if hal.memory().is_initialized() {
- unlock::unlock_keystore(hal, "Unlock device", CanCancel::Yes).await?
+ let title = crate::tr!(hal, "Unlock device");
+ unlock::unlock_keystore(hal, &title, CanCancel::Yes).await?
} else {
crate::keystore::copy_seed(hal).await?
};
crate::bip39::mnemonic_from_seed(&seed)?
};
+ let title = crate::tr!(hal, "Warning");
+ let body = crate::tr!(hal, "DO NOT share your\nrecovery words with\nanyone!");
hal.ui()
.confirm(&ConfirmParams {
- title: "Warning",
- body: "DO NOT share your\nrecovery words with\nanyone!",
+ title: &title,
+ body: &body,
accept_is_nextarrow: true,
..Default::default()
})
.await?;
+ let title = crate::tr!(hal, "Recovery\nwords");
+ let body = crate::tr!(hal, "Please write down\nthe following words");
hal.ui()
.confirm(&ConfirmParams {
- title: "Recovery\nwords",
- body: "Please write down\nthe following words",
+ title: &title,
+ body: &body,
accept_is_nextarrow: true,
..Default::default()
})
@@ -47,13 +53,15 @@ pub async fn process(hal: &mut impl crate::hal::Hal) -> Result<Response, Error>
let words: Vec<&str> = mnemonic_sentence.split(' ').collect();
{
+ let language = hal.memory().get_device_language();
let crate::hal::HalSubsystems { ui, random, .. } = hal.as_mut();
- crate::workflow::mnemonic::show_and_confirm_mnemonic(ui, random, &words).await?;
+ crate::workflow::mnemonic::show_and_confirm_mnemonic(ui, random, &words, language).await?;
}
hal.memory().set_initialized().or(Err(Error::Memory))?;
- hal.ui().status("Backup created", true).await;
+ let status = crate::tr!(hal, "Backup created");
+ hal.ui().status(&status, true).await;
Ok(Response::Success(pb::Success {}))
}
### src/rust/bitbox02-rust/src/hww/api/system.rs
@@ -2,6 +2,7 @@
use super::Error;
use crate::hal::ui::ConfirmParams;
+use crate::i18n::I18n as _;
use crate::pb;
use pb::reboot_request::Purpose;
@@ -13,16 +14,17 @@ pub async fn reboot_to_bootloader(
hal: &mut impl crate::hal::Hal,
&pb::RebootRequest { purpose }: &pb::RebootRequest,
) -> Result<Response, Error> {
+ let body = match Purpose::try_from(purpose) {
+ Ok(Purpose::Upgrade) => crate::tr!(hal, "Proceed to upgrade?"),
+ Ok(Purpose::Settings) => crate::tr!(hal, "Go to\nstartup settings?"),
+ // No error, if new client library sends a purpose that we don't understand,
+ // we reboot anyway.
+ Err(_) => crate::tr!(hal, "Reboot?"),
+ };
hal.ui()
.confirm(&ConfirmParams {
title: "",
- body: match Purpose::try_from(purpose) {
- Ok(Purpose::Upgrade) => "Proceed to upgrade?",
- Ok(Purpose::Settings) => "Go to\nstartup settings?",
- // No error, if new client library sends a purpose that we don't understand,
- // we reboot anyway.
- Err(_) => "Reboot?",
- },
+ body: &body,
..Default::default()
})
.await?;
### src/rust/bitbox02-rust/src/hww/api/unlock/tests.rs
@@ -21,7 +21,7 @@ const SEED: [u8; 32] = hex!("c7940c13479b8d9a6498f4e50d5a42e0d617bc8e8ac9f2b8cec
async fn task(packet: Vec<u8>) -> Vec<u8> {
let mut hal = HAL.0.borrow_mut().take().unwrap();
- let response = crate::hww::process_packet(&mut hal, packet).await;
+ let response = Box::pin(crate::hww::process_packet(&mut hal, packet)).await;
HAL.0.borrow_mut().replace(hal);
response
}
### src/rust/bitbox02-rust/src/i18n.rs
@@ -0,0 +1,73 @@
+// SPDX-License-Identifier: Apache-2.0
+
+extern crate alloc;
+
+use alloc::borrow::Cow;
+use alloc::string::String;
+use bitbox_hal::memory::Language;
+
+use crate::hal::{Hal, Memory};
+
+pub use bitbox_i18n::{
+ SUPPORTED_LANGUAGES, format, is_translatable, language_code, language_from_code, translate,
+};
+
+/// Verifying at compile time that the literal exists in the English source file.
+/// Prevents literals to drift from the locale file i.e. translations silently falling back to English.
+#[macro_export]
+macro_rules! tr {
+ ($hal:expr, $msg:literal $(,)?) => {{
+ const _: () = ::core::assert!(
+ $crate::i18n::is_translatable($msg),
+ "i18n: string literal is not a value in src/i18n/locales/en/firmware.json",
+ );
+ $hal.tr($msg)
+ }};
+}
+
+#[macro_export]
+macro_rules! tr_format {
+ ($hal:expr, $msg:literal, $args:expr $(,)?) => {{
+ const _: () = ::core::assert!(
+ $crate::i18n::is_translatable($msg),
+ "i18n: format pattern is not a value in src/i18n/locales/en/firmware.json",
+ );
+ $hal.tr_format($msg, $args)
+ }};
+}
+
+pub trait I18n {
+ fn tr<'a>(&mut self, english: &'a str) -> Cow<'a, str>;
+ fn tr_format(&mut self, english: &'static str, args: &[&str]) -> String;
+ fn tr_datetime(
+ &mut self,
+ timestamp: u32,
+ timezone_offset: i32,
+ date_only: bool,
+ ) -> Result<String, ()>;
+}
+
+impl<T: Hal> I18n for T {
+ fn tr<'a>(&mut self, english: &'a str) -> Cow<'a, str> {
+ let language = self.memory().get_device_language();
+ translate(language, english)
+ }
+
+ fn tr_format(&mut self, english: &'static str, args: &[&str]) -> String {
+ let language = self.memory().get_device_language();
+ format(language, english, args)
+ }
+
+ fn tr_datetime(
+ &mut self,
+ timestamp: u32,
+ timezone_offset: i32,
+ date_only: bool,
+ ) -> Result<String, ()> {
+ let locale = match self.memory().get_device_language() {
+ Language::English => util::datetime::DateLocale::English,
+ Language::German => util::datetime::DateLocale::German,
+ };
+ util::datetime::format_datetime_locale(timestamp, timezone_offset, date_only, locale)
+ }
+}
### src/rust/bitbox02-rust/src/lib.rs
@@ -17,6 +17,7 @@ pub mod general;
pub mod hal;
pub mod hash;
pub mod hww;
+pub mod i18n;
pub mod keystore;
#[cfg(all(
feature = "firmware",
### src/rust/bitbox02-rust/src/reset.rs
@@ -2,6 +2,7 @@
use crate::general::abort;
use crate::hal::{Eeprom, Memory, SecureChip, System, Ui, memory};
+use crate::i18n::I18n as _;
/// Resets the device:
/// - Updates secure chip KDF keys.
@@ -12,6 +13,7 @@ use crate::hal::{Eeprom, Memory, SecureChip, System, Ui, memory};
///
/// `status` selects whether the status message indicates success or failure (user invoked vs forced).
pub(crate) async fn reset(hal: &mut impl crate::hal::Hal, status: bool) {
+ let status_title = crate::tr!(hal, "Device reset");
crate::keystore::lock();
// Resetting takes longer than the default 500 ms watchdog. Bump the watchdog timeout to roughly
// 7 seconds (longer than needed) so we don't assume communication was lost and this task gets
@@ -60,8 +62,7 @@ pub(crate) async fn reset(hal: &mut impl crate::hal::Hal, status: bool) {
// Disable SmartEEPROM so it will be erased on next reboot.
hal.eeprom().disable();
- // Show "Device reset" status using the UI workflow.
- hal.ui().status("Device reset", status).await;
+ hal.ui().status(&status_title, status).await;
// The ble chip needs to be restarted to load the new secrets.
if matches!(
### src/rust/bitbox02-rust/src/u2f.rs
@@ -99,26 +99,33 @@ const APPS: &[App] = &[
];
/// Returns the site name/identifier to be displayed during U2F registration/auth.
-fn app_string(app_id: &[u8; 32]) -> String {
+fn app_string(app_id: &[u8; 32], unknown_site: &str) -> String {
if let Some(&App { name, .. }) = APPS.iter().find(|app| app.app_id == app_id) {
return name.into();
}
let m = bip39::Mnemonic::from_entropy_in(bip39::Language::English, app_id).unwrap();
let words: Vec<&'static str> = m.words().collect();
alloc::format!(
- "Unknown site:\n{} {}\n{} {}",
+ "{}\n{} {}\n{} {}",
+ unknown_site,
words[0],
words[1],
words[2],
words[3],
)
}
-// app_id must be of length 32, and out must be a least 60 bytes.
+// app_id must be of length 32, unknown_site must be valid UTF-8, and out must be large enough for
+// unknown_site and the four mnemonic words.
#[unsafe(no_mangle)]
-pub extern "C" fn rust_u2f_app_string(app_id: util::bytes::Bytes, mut out: util::bytes::BytesMut) {
- let app_str = app_string(app_id.as_ref().try_into().unwrap());
+pub extern "C" fn rust_u2f_app_string(
+ app_id: util::bytes::Bytes,
+ unknown_site: util::bytes::Bytes,
+ mut out: util::bytes::BytesMut,
+) {
+ let unknown_site = core::str::from_utf8(unknown_site.as_ref()).unwrap();
+ let app_str = app_string(app_id.as_ref().try_into().unwrap(), unknown_site);
let bytes = app_str.as_bytes();
let out = out.as_mut();
out[..bytes.len()].clone_from_slice(bytes);
@@ -135,6 +142,7 @@ mod tests {
let mut string = [0u8; 100];
rust_u2f_app_string(
unsafe { util::bytes::rust_util_bytes(app_id.as_ptr(), app_id.len()) },
+ unsafe { util::bytes::rust_util_bytes(core::ptr::null(), 0) },
unsafe { util::bytes::rust_util_bytes_mut(string.as_mut_ptr(), string.len()) },
);
assert_eq!(
@@ -152,6 +160,9 @@ mod tests {
let mut string = [0u8; 100];
rust_u2f_app_string(
unsafe { util::bytes::rust_util_bytes(app_id.as_ptr(), app_id.len()) },
+ unsafe {
+ util::bytes::rust_util_bytes("Unknown site:".as_ptr(), "Unknown site:".len())
+ },
unsafe { util::bytes::rust_util_bytes_mut(string.as_mut_ptr(), string.len()) },
);
assert_eq!(
@@ -162,4 +173,23 @@ mod tests {
"Unknown site:\ncatch turn\ntask hen"
);
}
+
+ #[test]
+ fn test_rust_u2f_app_string_unknown_custom_prefix() {
+ let app_id = b"\x24\x1d\x5b\x78\x35\x90\xc2\x1f\x79\x69\x8e\x7c\xe8\x92\xdd\x03\xfb\x2c\x8f\xad\xc2\x44\x0e\xc2\x3a\xa5\xde\x9e\x2d\x23\x81\xb0";
+ let unknown_site = "Unbekannte Seite:";
+ let mut string = [0u8; 100];
+ rust_u2f_app_string(
+ unsafe { util::bytes::rust_util_bytes(app_id.as_ptr(), app_id.len()) },
+ unsafe { util::bytes::rust_util_bytes(unknown_site.as_ptr(), unknown_site.len()) },
+ unsafe { util::bytes::rust_util_bytes_mut(string.as_mut_ptr(), string.len()) },
+ );
+ assert_eq!(
+ core::ffi::CStr::from_bytes_until_nul(&string)
+ .unwrap()
+ .to_str()
+ .unwrap(),
+ "Unbekannte Seite:\ncatch turn\ntask hen"
+ );
+ }
}
### src/rust/bitbox02-rust/src/workflow/confirm.rs
@@ -2,6 +2,7 @@
use crate::hal::Ui;
use crate::hal::ui::{ConfirmParams, UserAbort};
+use crate::i18n::I18n as _;
pub(crate) use crate::hal::ui::MAX_CONFIRM_BODY_SIZE;
@@ -15,10 +16,12 @@ pub(crate) async fn confirm_value(
params: &ConfirmParams<'_>,
) -> Result<(), UserAbort> {
if params.body.len() > MAX_CONFIRM_BODY_SIZE {
+ let title = crate::tr!(hal, "Warning");
+ let body = hal.tr(TRUNCATION_WARNING_BODY);
hal.ui()
.confirm(&ConfirmParams {
- title: "Warning",
- body: TRUNCATION_WARNING_BODY,
+ title: &title,
+ body: &body,
accept_is_nextarrow: true,
..Default::default()
})
### src/rust/bitbox02-rust/src/workflow/mnemonic.rs
@@ -1,9 +1,10 @@
// SPDX-License-Identifier: Apache-2.0
use crate::bip39::MAX_MNEMONIC_BYTES;
+use crate::hal::memory::Language;
use crate::hal::ui::{ConfirmParams, TrinaryChoice, UserAbort, WordlistEntryAbort};
-use alloc::string::String;
+use alloc::string::{String, ToString};
use alloc::vec::Vec;
use sha2::{Digest, Sha256};
@@ -65,11 +66,13 @@ pub async fn show_and_confirm_mnemonic(
hal_ui: &mut impl crate::hal::Ui,
hal_random: &mut impl crate::hal::Random,
words: &[&str],
+ language: Language,
) -> Result<(), UserAbort> {
+ let body = crate::i18n::format(language, "{} words follow", &[&words.len().to_string()]);
hal_ui
.confirm(&ConfirmParams {
title: "",
- body: &format!("{} words follow", words.len()),
+ body: &body,
accept_is_nextarrow: true,
..Default::default()
})
@@ -80,10 +83,11 @@ pub async fn show_and_confirm_mnemonic(
hal_ui.show_mnemonic(words).await?;
// Can only succeed due to `accept_only`.
+ let body = crate::i18n::translate(language, "Please confirm\neach word");
let _ = hal_ui
.confirm(&ConfirmParams {
title: "",
- body: "Please confirm\neach word",
+ body: &body,
accept_only: true,
accept_is_nextarrow: true,
..Default::default()
@@ -95,13 +99,17 @@ pub async fn show_and_confirm_mnemonic(
let title = format!("{:02}", word_idx + 1);
let (correct_idx, choices) = create_random_unique_words(hal_random, word, NUM_RANDOM_WORDS);
let mut choices: Vec<&str> = choices.iter().map(|c| c.as_ref()).collect();
- choices.push("Back to\nrecovery words");
+ let back_to_words = crate::i18n::translate(language, "Back to\nrecovery words");
+ choices.push(&back_to_words);
let back_idx = (choices.len() - 1) as u8;
loop {
match hal_ui.quiz_mnemonic_word(&choices, &title).await? {
selected_idx if selected_idx == correct_idx => break,
selected_idx if selected_idx == back_idx => hal_ui.show_mnemonic(words).await?,
- _ => hal_ui.status("Incorrect word\nTry again", false).await,
+ _ => {
+ let status = crate::i18n::translate(language, "Incorrect word\nTry again");
+ hal_ui.status(&status, false).await
+ }
}
}
}
@@ -191,20 +199,25 @@ async fn get_24th_word(
hal_ui: &mut impl crate::hal::Ui,
title: &str,
entered_words: &[&str],
+ language: Language,
) -> Result<Option<zeroize::Zeroizing<String>>, UserAbort> {
let mut choices = lastword_choices_strings(entered_words);
// Add one more menu entry.
let none_of_them_idx = {
- choices.push(zeroize::Zeroizing::new("None of them".into()));
+ choices.push(zeroize::Zeroizing::new(
+ crate::i18n::translate(language, "None of them").into_owned(),
+ ));
choices.len() - 1
};
loop {
match hal_ui.menu(&as_str_vec(&choices), Some(title)).await {
Err(UserAbort) => return Err(UserAbort),
Ok(choice_idx) if choice_idx as usize == none_of_them_idx => {
+ let body =
+ crate::i18n::translate(language, "Invalid. Check\nrecovery words.\nRestart?");
let params = ConfirmParams {
title: "",
- body: "Invalid. Check\nrecovery words.\nRestart?",
+ body: &body,
..Default::default()
};
if let Ok(()) = hal_ui.confirm(¶ms).await {
@@ -265,26 +278,38 @@ async fn get_12th_18th_word(
pub async fn get(
hal_ui: &mut impl crate::hal::Ui,
) -> Result<zeroize::Zeroizing<String>, UserAbort> {
+ get_with_language(hal_ui, Language::English).await
+}
+
+/// Retrieve a localized BIP39 mnemonic sentence of 12 or 24 words from the user.
+pub async fn get_with_language(
+ hal_ui: &mut impl crate::hal::Ui,
+ language: Language,
+) -> Result<zeroize::Zeroizing<String>, UserAbort> {
+ let how_many_words = crate::i18n::translate(language, "How many words?");
let num_words: usize = match hal_ui
- .trinary_choice("How many words?", Some("12"), None, Some("24"))
+ .trinary_choice(&how_many_words, Some("12"), None, Some("24"))
.await
{
TrinaryChoice::Left => 12,
TrinaryChoice::Middle => unreachable!(),
TrinaryChoice::Right => 24,
};
- hal_ui
- .status(&format!("Enter {} words", num_words), true)
- .await;
+ let body = crate::i18n::format(language, "Enter {} words", &[&num_words.to_string()]);
+ hal_ui.status(&body, true).await;
// Provide all bip39 words to restrict the keyboard entry.
let bip39_wordlist: Vec<u16> = (0..BIP39_WORDLIST_LEN).collect();
let mut word_idx: usize = 0;
let mut entered_words = vec![zeroize::Zeroizing::new(String::new()); num_words];
while word_idx < num_words {
- let title = format!("{} of {}", word_idx + 1, num_words);
+ let title = crate::i18n::format(
+ language,
+ "{} of {}",
+ &[&(word_idx + 1).to_string(), &num_words.to_string()],
+ );
// The already entered word will already be filled out (if not empty, i.e. not entered
// before). This happens when one goes back to edit previous words, and also when the user
@@ -300,7 +325,14 @@ pub async fn get(
// throws, for example.
if num_words == 24 {
// With 24 words there are only 8 valid candidates. We presnet them as a menu.
- match get_24th_word(hal_ui, &title, &as_str_vec(&entered_words[..word_idx])).await {
+ match get_24th_word(
+ hal_ui,
+ &title,
+ &as_str_vec(&entered_words[..word_idx]),
+ language,
+ )
+ .await
+ {
Ok(None) => return Err(UserAbort),
Ok(Some(r)) => Ok(r),
// The menu has a single abort control, so ask what the user meant.
@@ -333,10 +365,11 @@ pub async fn get(
// previous word and we go straight to the cancel action.
WordlistEntryAbort::Unspecified if word_idx == 0 => GetWordError::Cancel,
WordlistEntryAbort::Unspecified => {
- match hal_ui
- .menu(&["Edit previous word", "Cancel restore"], Some("Choose"))
- .await
- {
+ let edit_previous = crate::i18n::translate(language, "Edit previous word");
+ let cancel_restore = crate::i18n::translate(language, "Cancel restore");
+ let choose = crate::i18n::translate(language, "Choose");
+ let choices = [edit_previous.as_ref(), cancel_restore.as_ref()];
+ match hal_ui.menu(&choices, Some(choose.as_ref())).await {
Err(UserAbort) => {
// Cancel cancelled.
continue;
@@ -351,9 +384,11 @@ pub async fn get(
match cancel_choice {
GetWordError::EditPrevious => word_idx -= 1,
GetWordError::Cancel => {
+ let title = crate::i18n::translate(language, "Restore");
+ let body = crate::i18n::translate(language, "Cancel restore?");
let params = ConfirmParams {
- title: "Restore",
- body: "Cancel restore?",
+ title: &title,
+ body: &body,
..Default::default()
};
@@ -426,7 +461,8 @@ mod tests {
let mut random = TestingRandom::new();
ui.prepare_show_and_confirm_mnemonic(&mut random, words.len());
- let result = show_and_confirm_mnemonic(&mut ui, &mut random, &words).await;
+ let result =
+ show_and_confirm_mnemonic(&mut ui, &mut random, &words, Language::English).await;
assert!(result.is_ok());
TestingUi::assert_show_and_confirm_mnemonic_screens(&ui.screens, &words);
}
### src/rust/bitbox02-rust/src/workflow/mnemonic_c_unit_tests.rs
@@ -11,6 +11,7 @@ pub async fn show_and_confirm_mnemonic(
_ui: &mut impl crate::hal::Ui,
_random: &mut impl crate::hal::Random,
words: &[&str],
+ _language: crate::hal::memory::Language,
) -> Result<(), UserAbort> {
for word in words.iter() {
std::println!("{}", word);
@@ -20,7 +21,14 @@ pub async fn show_and_confirm_mnemonic(
Ok(())
}
-pub async fn get(_ui: &mut impl crate::hal::Ui) -> Result<zeroize::Zeroizing<String>, UserAbort> {
+pub async fn get(ui: &mut impl crate::hal::Ui) -> Result<zeroize::Zeroizing<String>, UserAbort> {
+ get_with_language(ui, crate::hal::memory::Language::English).await
+}
+
+pub async fn get_with_language(
+ _ui: &mut impl crate::hal::Ui,
+ _language: crate::hal::memory::Language,
+) -> Result<zeroize::Zeroizing<String>, UserAbort> {
let words = "boring mistake dish oyster truth pigeon viable emerge sort crash wire portion cannon couple enact box walk height pull today solid off enable tide";
std::println!("Restored from recovery words below:");
std::println!("{}", words);
### src/rust/bitbox02-rust/src/workflow/pairing.rs
@@ -2,6 +2,7 @@
use crate::hal::Ui;
use crate::hal::ui::{ConfirmParams, Font, UserAbort};
+use crate::i18n::I18n as _;
use alloc::string::String;
@@ -21,8 +22,9 @@ pub fn format_hash(hash: &[u8; 32]) -> String {
}
pub async fn confirm(hal: &mut impl crate::hal::Hal, hash: &[u8; 32]) -> Result<(), UserAbort> {
+ let title = crate::tr!(hal, "Pairing code");
let params = ConfirmParams {
- title: "Pairing code",
+ title: &title,
body: &format_hash(hash),
font: Font::Monogram16,
..Default::default()
### src/rust/bitbox02-rust/src/workflow/password.rs
@@ -2,15 +2,17 @@
use crate::hal::Ui;
use crate::hal::ui::{CanCancel, ConfirmParams, UserAbort};
+use crate::i18n::I18n as _;
use crate::hal::{Memory, memory::SecurechipType};
use alloc::string::String;
async fn prompt_cancel(hal: &mut impl crate::hal::Hal) -> Result<(), crate::hal::ui::UserAbort> {
+ let body = crate::tr!(hal, "Do you really\nwant to cancel?");
hal.ui()
.confirm(&ConfirmParams {
- body: "Do you really\nwant to cancel?",
+ body: &body,
..Default::default()
})
.await
@@ -108,31 +110,27 @@ impl core::convert::From<EnterError> for EnterTwiceError {
pub async fn enter_twice(
hal: &mut impl crate::hal::Hal,
) -> Result<zeroize::Zeroizing<String>, EnterTwiceError> {
- let password = enter(
- hal,
- "Set password",
- PasswordType::DevicePassword,
- CanCancel::Yes,
- )
- .await?;
- let password_repeat = enter(
- hal,
- "Repeat password",
- PasswordType::DevicePassword,
- CanCancel::Yes,
- )
- .await?;
+ let title = crate::tr!(hal, "Set password");
+ let password = enter(hal, &title, PasswordType::DevicePassword, CanCancel::Yes).await?;
+ let title = crate::tr!(hal, "Repeat password");
+ let password_repeat = enter(hal, &title, PasswordType::DevicePassword, CanCancel::Yes).await?;
if password.as_str() != password_repeat.as_str() {
- hal.ui().status("Passwords\ndo not match", false).await;
+ let status = crate::tr!(hal, "Passwords\ndo not match");
+ hal.ui().status(&status, false).await;
return Err(EnterTwiceError::DoNotMatch);
}
if password.as_str().len() < 4 {
+ let title = crate::tr!(hal, "WARNING");
+ let body = crate::tr!(
+ hal,
+ "Your password\n has fewer than\n 4 characters.\nContinue?"
+ );
loop {
match hal
.ui()
.confirm(&ConfirmParams {
- title: "WARNING",
- body: "Your password\n has fewer than\n 4 characters.\nContinue?",
+ title: &title,
+ body: &body,
longtouch: true,
..Default::default()
})
@@ -146,7 +144,8 @@ pub async fn enter_twice(
}
}
}
- hal.ui().status("Success", true).await;
+ let status = crate::tr!(hal, "Success");
+ hal.ui().status(&status, true).await;
Ok(password)
}
### src/rust/bitbox02-rust/src/workflow/transaction.rs
@@ -3,6 +3,7 @@
use crate::hal::Ui;
use crate::hal::ui::ConfirmParams;
use crate::hal::ui::UserAbort;
+use crate::i18n::I18n as _;
use alloc::string::String;
@@ -26,13 +27,21 @@ pub enum FeePercentageBasis {
}
impl FeePercentageBasis {
- fn warning_message(&self, fee_percentage: &str) -> String {
+ fn warning_message(&self, hal: &mut impl crate::hal::Hal, fee_percentage: &str) -> String {
match self {
FeePercentageBasis::SendAmount => {
- format!("Fee is {}%\nof the send amount.\nProceed?", fee_percentage)
+ crate::tr_format!(
+ hal,
+ "Fee is {}%\nof the send amount.\nProceed?",
+ &[fee_percentage]
+ )
}
FeePercentageBasis::TotalInputs => {
- format!("Fee is {}%\nof all inputs.\nProceed?", fee_percentage)
+ crate::tr_format!(
+ hal,
+ "Fee is {}%\nof all inputs.\nProceed?",
+ &[fee_percentage]
+ )
}
}
}
@@ -67,11 +76,12 @@ pub async fn verify_total_fee_maybe_warn_with_basis(
hal.ui().verify_total_fee(total, fee, longtouch).await?;
if let Some(fee_percentage) = fee_percentage {
+ let title = crate::tr!(hal, "High fee");
let warning_message =
- fee_percentage_basis.warning_message(&format_percentage(fee_percentage));
+ fee_percentage_basis.warning_message(hal, &format_percentage(fee_percentage));
hal.ui()
.confirm(&ConfirmParams {
- title: "High fee",
+ title: &title,
body: &warning_message,
longtouch: true,
..Default::default()
### src/rust/bitbox02-rust/src/workflow/unlock.rs
@@ -3,8 +3,10 @@
use crate::general::abort;
use crate::hal::ui::{CanCancel, ConfirmParams};
use crate::hal::{Memory, Ui};
+use crate::i18n::I18n as _;
use crate::workflow::password;
+use alloc::string::{String, ToString};
use alloc::vec::Vec;
/// Confirm the entered mnemonic passphrase with the user. Returns Ok if the user confirmed it,
@@ -18,11 +20,13 @@ pub(crate) async fn confirm_mnemonic_passphrase(
// must always be explicitly confirmed so the host cannot silently select another wallet.
if passphrase.is_empty() {
if from_host {
+ let title = crate::tr!(hal, "Confirm");
+ let body = crate::tr!(hal, "Use empty\npassphrase?");
return hal
.ui()
.confirm(&ConfirmParams {
- title: "Confirm",
- body: "Use empty\npassphrase?",
+ title: &title,
+ body: &body,
longtouch: true,
..Default::default()
})
@@ -31,18 +35,23 @@ pub(crate) async fn confirm_mnemonic_passphrase(
return Ok(());
}
+ let body = crate::tr!(
+ hal,
+ "You will be asked to\nvisually confirm your\npassphrase now."
+ );
let params = ConfirmParams {
title: "",
- body: "You will be asked to\nvisually confirm your\npassphrase now.",
+ body: &body,
accept_only: true,
accept_is_nextarrow: true,
..Default::default()
};
hal.ui().confirm(¶ms).await?;
+ let title = crate::tr!(hal, "Confirm");
let params = ConfirmParams {
- title: "Confirm",
+ title: &title,
body: passphrase,
font: crate::hal::ui::Font::Password12,
scrollable: true,
@@ -57,9 +66,10 @@ pub(crate) async fn confirm_mnemonic_passphrase(
pub(crate) async fn enter_mnemonic_passphrase(
hal: &mut impl crate::hal::Hal,
) -> zeroize::Zeroizing<alloc::string::String> {
+ let title = crate::tr!(hal, "Optional passphrase");
password::enter(
hal,
- "Optional passphrase",
+ &title,
password::PasswordType::Bip39Passphrase,
CanCancel::No,
)
@@ -78,7 +88,8 @@ async fn enter_and_confirm_mnemonic_passphrase(
if let Ok(()) = confirm_mnemonic_passphrase(hal, passphrase.as_str(), false).await {
return passphrase;
}
- hal.ui().status("Please try again", false).await;
+ let status = crate::tr!(hal, "Please try again");
+ hal.ui().status(&status, false).await;
}
}
@@ -115,15 +126,24 @@ async fn maybe_confirm_remaining_unlock_attempts(
// password is entered. This might be confusing UX if it happened, but it's an extreme edge
// case, so we purposefully don't deal with this here.
- let body: alloc::string::String = if remaining == 1 {
- "This is your LAST\npassword attempt.\nDevice will reset\nif password is wrong.".into()
+ let body: String = if remaining == 1 {
+ crate::tr!(
+ hal,
+ "This is your LAST\npassword attempt.\nDevice will reset\nif password is wrong."
+ )
+ .into_owned()
} else {
- format!("You have {}\npassword attempts\nleft.", remaining)
+ crate::tr_format!(
+ hal,
+ "You have {}\npassword attempts\nleft.",
+ &[&remaining.to_string()],
+ )
};
+ let title = crate::tr!(hal, "WARNING");
hal.ui()
.confirm(&ConfirmParams {
- title: "WARNING",
+ title: &title,
body: &body,
accept_is_nextarrow: true,
longtouch: remaining == 1,
@@ -161,13 +181,15 @@ pub async fn unlock_keystore(
match crate::keystore::unlock(hal, &password).await {
Ok(seed) => Ok(seed),
Err(crate::keystore::Error::IncorrectPassword) => {
- hal.ui().status("Wrong password", false).await;
+ let status = crate::tr!(hal, "Wrong password");
+ hal.ui().status(&status, false).await;
Err(UnlockError::IncorrectPassword)
}
Err(err) => {
- let msg = format!(
+ let msg = crate::tr_format!(
+ hal,
"keystore unlock failed\n{}",
- crate::keystore::format_error(&err)
+ &[&crate::keystore::format_error(&err)],
);
hal.ui().status(&msg, false).await;
Err(UnlockError::Generic)
@@ -286,7 +308,8 @@ pub(crate) async fn unlock_with_passphrase<H: crate::hal::Hal, E>(
// Loop unlock until the password is correct or the device resets.
let seed = loop {
- if let Ok(seed) = unlock_keystore(hal, "Enter password", CanCancel::No).await {
+ let title = crate::tr!(hal, "Enter password");
+ if let Ok(seed) = unlock_keystore(hal, &title, CanCancel::No).await {
break seed;
}
};
### src/rust/bitbox02-rust/src/workflow/verify_message.rs
@@ -1,6 +1,8 @@
// SPDX-License-Identifier: Apache-2.0
use crate::hal::ui::{ConfirmParams, Font};
+use crate::i18n::I18n as _;
+use alloc::string::ToString;
use alloc::vec::Vec;
use crate::hal::Ui;
@@ -62,7 +64,11 @@ pub async fn verify(
let title = if pages.len() == 1 {
title_long.into()
} else {
- format!("{} {}/{}", title_short, i + 1, pages.len())
+ crate::tr_format!(
+ hal,
+ "{} {}/{}",
+ &[title_short, &(i + 1).to_string(), &pages.len().to_string()],
+ )
};
let params = ConfirmParams {
title: &title,
@@ -77,8 +83,14 @@ pub async fn verify(
Ok(())
} else {
let body = hex::encode(msg);
+ let title_base = if title_long.contains('\n') {
+ title_short
+ } else {
+ title_long
+ };
+ let title = crate::tr_format!(hal, "{}\ndata (hex)", &[title_base]);
let params = ConfirmParams {
- title: &format!("{}\ndata (hex)", title_long),
+ title: &title,
body: &body,
scrollable: true,
display_size: msg.len(),
@@ -97,6 +109,7 @@ mod tests {
use alloc::boxed::Box;
+ use crate::hal::Memory as _;
use crate::hal::testing::TestingHal;
use crate::hal::testing::ui::Screen;
use crate::workflow::confirm::{MAX_CONFIRM_BODY_SIZE, TRUNCATION_WARNING_BODY};
@@ -127,6 +140,43 @@ mod tests {
);
}
+ #[async_test::test]
+ async fn test_verify_multiline_text_german() {
+ let mut hal = TestingHal::new();
+ hal.memory
+ .set_device_language(bitbox_hal::memory::Language::German)
+ .unwrap();
+ let msg = ["A"; 100].join("\n");
+ assert!(
+ verify(
+ &mut hal,
+ "Nachricht\nsignieren",
+ "Signieren",
+ msg.as_bytes(),
+ true,
+ )
+ .await
+ .is_ok()
+ );
+ assert_eq!(hal.ui.screens.len(), 100);
+ assert_eq!(
+ hal.ui.screens.first().unwrap(),
+ &Screen::Confirm {
+ title: "Signieren\n1/100".into(),
+ body: "A".into(),
+ longtouch: false,
+ }
+ );
+ assert_eq!(
+ hal.ui.screens.last().unwrap(),
+ &Screen::Confirm {
+ title: "Signieren\n100/100".into(),
+ body: "A".into(),
+ longtouch: true,
+ }
+ );
+ }
+
#[async_test::test]
async fn test_verify_blank_lines() {
let mut hal = TestingHal::new();
@@ -442,4 +492,32 @@ mod tests {
);
assert_eq!(mock_hal.ui.confirm_display_sizes, vec![3]);
}
+ #[async_test::test]
+ async fn test_verify_hex_german_uses_short_title() {
+ let mut mock_hal = TestingHal::new();
+ mock_hal
+ .memory
+ .set_device_language(bitbox_hal::memory::Language::German)
+ .unwrap();
+
+ assert!(
+ verify(
+ &mut mock_hal,
+ "Nachricht\nsignieren",
+ "Signieren",
+ &[0],
+ true
+ )
+ .await
+ .is_ok()
+ );
+ assert_eq!(
+ mock_hal.ui.screens,
+ vec![Screen::Confirm {
+ title: "Signieren\nDaten (Hex)".into(),
+ body: "00".into(),
+ longtouch: true,
+ }]
+ );
+ }
}
### src/rust/bitbox02-sys/build.rs
@@ -103,6 +103,7 @@ const ALLOWLIST_FNS: &[&str] = &[
"memory_get_ble_metadata",
"memory_get_bootloader_version",
"memory_get_device_name",
+ "memory_get_device_language",
"memory_get_encrypted_seed_and_hmac",
"memory_get_encryption_key",
"memory_get_io_protection_key",
@@ -123,6 +124,7 @@ const ALLOWLIST_FNS: &[&str] = &[
"memory_set_attestation_certificate",
"memory_set_attestation_device_pubkey",
"memory_set_device_name",
+ "memory_set_device_language",
"memory_set_encrypted_seed_and_hmac",
"memory_set_initialized",
"memory_set_mnemonic_passphrase_enabled",
### src/rust/bitbox02/Cargo.toml
@@ -16,6 +16,7 @@ bitbox-noise = { path = "../bitbox-noise" }
bitbox-hal = { path = "../bitbox-hal" }
bitbox-bytequeue = { path = "../bitbox-bytequeue" }
bitbox-framed-serial-link = { path = "../bitbox-framed-serial-link" }
+bitbox-i18n = { path = "../bitbox-i18n" }
bitbox-usb-report-queue = { path = "../bitbox-usb-report-queue" }
util = {path = "../util"}
zeroize = { workspace = true }
### src/rust/bitbox02/src/hal/memory.rs
@@ -5,8 +5,8 @@ use alloc::vec::Vec;
use bitbox_hal::Memory;
use bitbox_hal::memory::{
- BleFirmwareSlot, BleMetadata, Error, OptigaConfigVersion, PasswordStretchAlgo, Platform,
- SecurechipType,
+ BleFirmwareSlot, BleMetadata, Error, Language, OptigaConfigVersion, PasswordStretchAlgo,
+ Platform, SecurechipType,
};
pub struct BitBox02Memory;
@@ -171,6 +171,14 @@ impl Memory for BitBox02Memory {
crate::memory::set_device_name(name).map_err(to_hal_error)
}
+ fn get_device_language(&mut self) -> Language {
+ crate::memory::get_device_language()
+ }
+
+ fn set_device_language(&mut self, language: Language) -> Result<(), Error> {
+ crate::memory::set_device_language(language).map_err(to_hal_error)
+ }
+
fn is_mnemonic_passphrase_enabled(&mut self) -> bool {
crate::memory::is_mnemonic_passphrase_enabled()
}
### src/rust/bitbox02/src/hal/ui.rs
@@ -1,6 +1,5 @@
// SPDX-License-Identifier: Apache-2.0
-use alloc::format;
use alloc::string::String;
use core::marker::PhantomData;
use core::time::Duration;
@@ -152,9 +151,10 @@ impl<Timer: bitbox_hal::timer::Timer> Ui for BitBox02Ui<Timer> {
#[inline(always)]
async fn confirm_swap(&mut self, title: &str, from: &str, to: &str) -> Result<(), UserAbort> {
if !crate::ui::transaction_amount_fits(from) || !crate::ui::transaction_amount_fits(to) {
- let from_title = format!("{title} from");
+ let language = crate::memory::get_device_language();
+ let from_title = crate::i18n::format(language, "{} from", &[title]);
self.review_value(&from_title, from, false).await?;
- let to_title = format!("{title} to");
+ let to_title = crate::i18n::format(language, "{} to", &[title]);
return self.review_value(&to_title, to, false).await;
}
match crate::ui::confirm_swap(title, from, to).await {
@@ -166,8 +166,10 @@ impl<Timer: bitbox_hal::timer::Timer> Ui for BitBox02Ui<Timer> {
#[inline(always)]
async fn verify_recipient(&mut self, recipient: &str, amount: &str) -> Result<(), UserAbort> {
if !crate::ui::transaction_amount_fits(amount) {
- self.review_value("Amount", amount, false).await?;
- return self.review_value("Recipient", recipient, false).await;
+ let title = crate::i18n::translate_current("Amount");
+ self.review_value(&title, amount, false).await?;
+ let title = crate::i18n::translate_current("Recipient");
+ return self.review_value(&title, recipient, false).await;
}
match crate::ui::confirm_transaction_address(amount, recipient).await {
crate::ui::ConfirmResponse::Approved => Ok(()),
@@ -183,8 +185,10 @@ impl<Timer: bitbox_hal::timer::Timer> Ui for BitBox02Ui<Timer> {
longtouch: bool,
) -> Result<(), UserAbort> {
if !crate::ui::transaction_amount_fits(total) || !crate::ui::transaction_fee_fits(fee) {
- self.review_value("Total", total, false).await?;
- return self.review_value("Fee", fee, longtouch).await;
+ let title = crate::i18n::translate_current("Total");
+ self.review_value(&title, total, false).await?;
+ let title = crate::i18n::translate_current("Fee");
+ return self.review_value(&title, fee, longtouch).await;
}
match crate::ui::confirm_transaction_fee(total, fee, longtouch).await {
crate::ui::ConfirmResponse::Approved => Ok(()),
@@ -280,12 +284,13 @@ impl<Timer: bitbox_hal::timer::Timer> Ui for BitBox02Ui<Timer> {
}
async fn show_mnemonic(&mut self, words: &[&str]) -> Result<(), UserAbort> {
+ let cancel_confirm_title = crate::i18n::translate_current("Recovery\nwords");
match crate::ui::menu(crate::ui::MenuParams {
words,
title: None,
select_word: false,
continue_on_last: true,
- cancel_confirm_title: Some("Recovery\nwords"),
+ cancel_confirm_title: Some(&cancel_confirm_title),
})
.await
{
@@ -296,12 +301,13 @@ impl<Timer: bitbox_hal::timer::Timer> Ui for BitBox02Ui<Timer> {
}
async fn quiz_mnemonic_word(&mut self, choices: &[&str], title: &str) -> Result<u8, UserAbort> {
+ let cancel_confirm_title = crate::i18n::translate_current("Recovery\nwords");
match crate::ui::menu(crate::ui::MenuParams {
words: choices,
title: Some(title),
select_word: true,
continue_on_last: false,
- cancel_confirm_title: Some("Recovery\nwords"),
+ cancel_confirm_title: Some(&cancel_confirm_title),
})
.await
{
### src/rust/bitbox02/src/i18n.rs
@@ -0,0 +1,61 @@
+// SPDX-License-Identifier: Apache-2.0
+
+use core::ffi::{c_char, c_void};
+
+pub use bitbox_i18n::{format, language_code, language_from_code, translate};
+
+pub fn translate_current<'a>(english: &'a str) -> alloc::borrow::Cow<'a, str> {
+ translate(crate::memory::get_device_language(), english)
+}
+
+/// # Safety
+///
+/// `input` must be a valid, null-terminated string pointer. `output` must be a valid pointer to a
+/// buffer of at least `output_len` bytes.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn rust_i18n_translate_copy(
+ input: *const c_char,
+ output: *mut c_char,
+ output_len: usize,
+) -> bool {
+ if input.is_null() || output.is_null() || output_len == 0 {
+ return false;
+ }
+ let Ok(input) = (unsafe { util::strings::str_from_null_terminated_ptr(input) }) else {
+ unsafe { *output = 0 };
+ return false;
+ };
+ let translated = translate_current(input);
+ copy_to_cstr(&translated, output.cast::<c_void>(), output_len)
+}
+
+fn copy_to_cstr(input: &str, output: *mut c_void, output_len: usize) -> bool {
+ let mut len = input.len().min(output_len - 1);
+ while !input.is_char_boundary(len) {
+ len -= 1;
+ }
+ unsafe {
+ core::ptr::copy_nonoverlapping(input.as_ptr(), output.cast::<u8>(), len);
+ *output.cast::<u8>().add(len) = 0;
+ }
+ len == input.len()
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn test_copy_to_cstr_truncates_to_char_boundary() {
+ let input = core::str::from_utf8(b"Gr\xc3\xb6sse").unwrap();
+ let mut output = [0xff; 4];
+
+ assert!(!copy_to_cstr(
+ input,
+ output.as_mut_ptr().cast::<c_void>(),
+ output.len()
+ ));
+ assert_eq!(&output[..3], b"Gr\0");
+ assert_eq!(output[3], 0xff);
+ }
+}
### src/rust/bitbox02/src/lib.rs
@@ -28,6 +28,7 @@ pub mod hid_hww;
#[cfg(feature = "app-u2f")]
pub mod hid_u2f;
pub mod hww;
+pub mod i18n;
pub mod memory;
pub mod platform;
pub mod random;
### src/rust/bitbox02/src/memory.rs
@@ -7,6 +7,7 @@ use bitbox_hal::memory::{DEVICE_NAME_MAX_LEN, MULTISIG_NAME_MAX_LEN};
pub use bitbox02_sys::memory_ble_metadata_t as BleMetadata;
+pub use bitbox02_sys::memory_device_language_t as DeviceLanguage;
pub use bitbox02_sys::memory_optiga_config_version_t as OptigaConfigVersion;
pub use bitbox02_sys::memory_password_stretch_algo_t as PasswordStretchAlgo;
pub use bitbox02_sys::memory_result_t as MemoryError;
@@ -50,6 +51,30 @@ pub fn set_device_name(name: &str) -> Result<(), MemoryError> {
}
}
+pub fn get_device_language() -> bitbox_hal::memory::Language {
+ match unsafe { bitbox02_sys::memory_get_device_language() } {
+ bitbox02_sys::memory_device_language_t_MEMORY_DEVICE_LANGUAGE_DE => {
+ bitbox_hal::memory::Language::German
+ }
+ _ => bitbox_hal::memory::Language::English,
+ }
+}
+
+pub fn set_device_language(language: bitbox_hal::memory::Language) -> Result<(), MemoryError> {
+ let language = match language {
+ bitbox_hal::memory::Language::English => {
+ bitbox02_sys::memory_device_language_t_MEMORY_DEVICE_LANGUAGE_EN
+ }
+ bitbox_hal::memory::Language::German => {
+ bitbox02_sys::memory_device_language_t_MEMORY_DEVICE_LANGUAGE_DE
+ }
+ };
+ match unsafe { bitbox02_sys::memory_set_device_language(language) } {
+ true => Ok(()),
+ false => Err(MemoryError::MEMORY_ERR_UNKNOWN),
+ }
+}
+
pub fn is_initialized() -> bool {
unsafe { bitbox02_sys::memory_is_initialized() }
}
@@ -472,6 +497,19 @@ mod tests {
}
}
+ #[test]
+ fn test_get_set_device_language() {
+ mock_memory();
+
+ assert_eq!(get_device_language(), bitbox_hal::memory::Language::English);
+
+ set_device_language(bitbox_hal::memory::Language::German).unwrap();
+ assert_eq!(get_device_language(), bitbox_hal::memory::Language::German);
+
+ set_device_language(bitbox_hal::memory::Language::English).unwrap();
+ assert_eq!(get_device_language(), bitbox_hal::memory::Language::English);
+ }
+
#[test]
fn test_is_set_initialized() {
mock_memory();
### src/rust/bitbox02/src/platform.rs
@@ -3,7 +3,7 @@
pub fn product() -> &'static str {
unsafe {
let mut len = 0;
- let s = bitbox02_sys::platform_product(&mut len as *mut _) as *const u8;
+ let s = bitbox02_sys::platform_product(&mut len as *mut _).cast::<u8>();
let s = core::slice::from_raw_parts(s, len);
// SAFETY: `platform_product()` returns a compile-time ASCII JSON string literal.
core::str::from_utf8_unchecked(s)
### src/rust/bitbox02/src/ui/ui.rs
@@ -541,11 +541,12 @@ pub async fn menu(params: MenuParams<'_>) -> MenuResponse {
MenuResponse::Cancel => match cancel_confirm_title {
None => return MenuResponse::Cancel,
Some(title) => {
+ let body = crate::i18n::translate_current("Do you really\nwant to cancel?");
// `ConfirmResponse::Cancelled` means _do not cancel_,
// stay in the same menu component.
match confirm(&ConfirmParams {
title,
- body: "Do you really\nwant to cancel?",
+ body: &body,
..Default::default()
})
.await
### src/rust/bitbox03/src/memory.rs
@@ -59,6 +59,17 @@ impl hal::memory::Memory for BitBox03Memory {
todo!()
}
+ fn get_device_language(&mut self) -> bitbox_hal::memory::Language {
+ bitbox_hal::memory::Language::English
+ }
+
+ fn set_device_language(
+ &mut self,
+ _language: bitbox_hal::memory::Language,
+ ) -> Result<(), bitbox_hal::memory::Error> {
+ todo!()
+ }
+
fn is_mnemonic_passphrase_enabled(&mut self) -> bool {
todo!()
}
### src/rust/util/src/datetime.rs
@@ -3,34 +3,77 @@
use alloc::string::String;
use time::{OffsetDateTime, UtcOffset, Weekday};
+#[derive(Copy, Clone, Debug, Eq, PartialEq)]
+pub enum DateLocale {
+ English,
+ German,
+}
+
pub struct Tm {
datetime: OffsetDateTime,
}
impl Tm {
/// Returns the weekday, one of "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"
pub fn weekday(&self) -> String {
+ self.weekday_locale(DateLocale::English)
+ }
+
+ fn weekday_locale(&self, locale: DateLocale) -> String {
match self.datetime.weekday() {
- Weekday::Sunday => "Sun",
- Weekday::Monday => "Mon",
- Weekday::Tuesday => "Tue",
- Weekday::Wednesday => "Wed",
- Weekday::Thursday => "Thu",
- Weekday::Friday => "Fri",
- Weekday::Saturday => "Sat",
+ Weekday::Sunday => match locale {
+ DateLocale::English => "Sun",
+ DateLocale::German => "So",
+ },
+ Weekday::Monday => match locale {
+ DateLocale::English => "Mon",
+ DateLocale::German => "Mo",
+ },
+ Weekday::Tuesday => match locale {
+ DateLocale::English => "Tue",
+ DateLocale::German => "Di",
+ },
+ Weekday::Wednesday => match locale {
+ DateLocale::English => "Wed",
+ DateLocale::German => "Mi",
+ },
+ Weekday::Thursday => match locale {
+ DateLocale::English => "Thu",
+ DateLocale::German => "Do",
+ },
+ Weekday::Friday => match locale {
+ DateLocale::English => "Fri",
+ DateLocale::German => "Fr",
+ },
+ Weekday::Saturday => match locale {
+ DateLocale::English => "Sat",
+ DateLocale::German => "Sa",
+ },
}
.into()
}
/// Returns 'year-month-day', e.g. 2024-07-16, equivalent of '%Y-%m-%d' in strftime.
pub fn date(&self) -> String {
+ self.date_locale(DateLocale::English)
+ }
+
+ fn date_locale(&self, locale: DateLocale) -> String {
let date = self.datetime.date();
- format!(
- "{}-{:02}-{:02}",
- date.year(),
- date.month() as u8,
- date.day(),
- )
+ match locale {
+ DateLocale::English => format!(
+ "{}-{:02}-{:02}",
+ date.year(),
+ date.month() as u8,
+ date.day(),
+ ),
+ DateLocale::German => format!(
+ "{:02}.{:02}.{}",
+ date.day(),
+ date.month() as u8,
+ date.year(),
+ ),
+ }
}
/// Returns the zero-padded hour from 00-23, e.g. "07".
@@ -62,6 +105,15 @@ pub fn format_datetime(
timestamp: u32,
timezone_offset: i32,
date_only: bool,
+) -> Result<String, ()> {
+ format_datetime_locale(timestamp, timezone_offset, date_only, DateLocale::English)
+}
+
+pub fn format_datetime_locale(
+ timestamp: u32,
+ timezone_offset: i32,
+ date_only: bool,
+ locale: DateLocale,
) -> Result<String, ()> {
const MAX_EAST_UTC_OFFSET: i32 = 50400; // 14 hours in seconds
const MAX_WEST_UTC_OFFSET: i32 = -43200; // 12 hours in seconds
@@ -77,12 +129,12 @@ pub fn format_datetime(
.ok_or(())?;
let tm = Tm { datetime };
Ok(if date_only {
- format!("{} {}", tm.weekday(), tm.date())
+ format!("{} {}", tm.weekday_locale(locale), tm.date_locale(locale))
} else {
format!(
"{} {}\n{}:{}",
- tm.weekday(),
- tm.date(),
+ tm.weekday_locale(locale),
+ tm.date_locale(locale),
tm.hour(),
tm.minute()
)
@@ -115,4 +167,20 @@ mod tests {
assert!(format_datetime(1601281809, 50401, false).is_err());
assert!(format_datetime(1601281809, -43201, false).is_err());
}
+
+ #[test]
+ fn test_format_datetime_locale() {
+ assert_eq!(
+ format_datetime_locale(1779964200, 0, true, DateLocale::German),
+ Ok("Do 28.05.2026".into())
+ );
+ assert_eq!(
+ format_datetime_locale(1779964200, 0, false, DateLocale::German),
+ Ok("Do 28.05.2026\n10:30".into())
+ );
+ assert_eq!(
+ format_datetime_locale(1601281809, -32400, false, DateLocale::German),
+ Ok("So 27.09.2020\n23:30".into())
+ );
+ }
}
### src/u2f.c
@@ -126,7 +126,9 @@ static const component_functions_t _refresh_webpage_component_functions = {
static component_t* _create_refresh_webpage(void)
{
- component_t* component = info_centered_create("Refresh webpage", NULL);
+ char refresh_webpage[32] = {0};
+ rust_i18n_translate_copy("Refresh webpage", refresh_webpage, sizeof(refresh_webpage));
+ component_t* component = info_centered_create(refresh_webpage, NULL);
component->f = &_refresh_webpage_component_functions;
return component;
}
@@ -191,7 +193,12 @@ static void _create_nudge_label(void)
return;
}
- _nudge_label = info_centered_create("Initialize with BitBoxApp\nto use U2F", _nudge_label_cb);
+ char initialize_with_bitboxapp[64] = {0};
+ rust_i18n_translate_copy(
+ "Initialize with BitBoxApp\nto use U2F",
+ initialize_with_bitboxapp,
+ sizeof(initialize_with_bitboxapp));
+ _nudge_label = info_centered_create(initialize_with_bitboxapp, _nudge_label_cb);
_nudge_label->f = &_nudge_label_component_functions;
ui_screen_stack_push(_nudge_label);
}
### src/u2f/u2f_app.c
@@ -26,7 +26,12 @@ static struct {
static void _app_string(const uint8_t* app_id, char* out, size_t out_len)
{
memset(out, 0, out_len);
- rust_u2f_app_string(rust_util_bytes(app_id, 32), rust_util_bytes_mut((uint8_t*)out, out_len));
+ char unknown_site[32] = {0};
+ rust_i18n_translate_copy("Unknown site:", unknown_site, sizeof(unknown_site));
+ rust_u2f_app_string(
+ rust_util_bytes(app_id, 32),
+ rust_util_bytes((const uint8_t*)unknown_site, strlen(unknown_site)),
+ rust_util_bytes_mut((uint8_t*)out, out_len));
}
static bool _is_app_id_bogus(const uint8_t* app_id)
@@ -39,6 +44,7 @@ bool u2f_app_confirm_start(enum u2f_app_confirm_t type, const uint8_t* app_id)
{
char app_string[100] = {0};
const char* title;
+ bool translate_app_string = false;
switch (type) {
case U2F_APP_REGISTER:
if (!_is_app_id_bogus(app_id)) {
@@ -49,6 +55,7 @@ bool u2f_app_confirm_start(enum u2f_app_confirm_t type, const uint8_t* app_id)
// registrations to make the device blink.
title = "";
snprintf(app_string, sizeof(app_string), "%s", "Use U2F?");
+ translate_app_string = true;
}
break;
case U2F_APP_AUTHENTICATE:
@@ -58,6 +65,16 @@ bool u2f_app_confirm_start(enum u2f_app_confirm_t type, const uint8_t* app_id)
default:
Abort("u2f_app_confirm: Internal error");
}
+ char translated_title[64] = {0};
+ if (title[0] != '\0') {
+ rust_i18n_translate_copy(title, translated_title, sizeof(translated_title));
+ title = translated_title;
+ }
+ if (translate_app_string) {
+ char translated_app_string[sizeof(app_string)] = {0};
+ rust_i18n_translate_copy(app_string, translated_app_string, sizeof(translated_app_string));
+ memcpy(app_string, translated_app_string, sizeof(app_string));
+ }
if (!rust_workflow_spawn_confirm(title, app_string)) {
return false;
}
### src/ui/components/confirm.c
@@ -8,6 +8,7 @@
#include "label.h"
#include <hardfault.h>
+#include <rust/rust.h>
#include <screen.h>
#include <ui/fonts/regular_fonts.h>
#include <ui/ugui/ugui.h>
@@ -80,12 +81,14 @@ component_t* confirm_create(
confirm->dimension.height = SCREEN_HEIGHT;
if (params->display_size) {
- char size_label[20];
+ char size_label[24];
+ char size[10] = {0};
+ rust_i18n_translate_copy("Size", size, sizeof(size));
// Ignore warning, %u works for 32bit but not 64 bit (unit tests). %zu does not work with
// our compiler.
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wformat"
- snprintf(size_label, sizeof(size_label), "Size: %uB", params->display_size);
+ snprintf(size_label, sizeof(size_label), "%s: %uB", size, params->display_size);
#pragma GCC diagnostic pop
ui_util_add_sub_component(
confirm, label_create(size_label, params->font, LEFT_BOTTOM, confirm));
### src/ui/components/confirm_transaction.c
@@ -7,6 +7,7 @@
#include "ui_images.h"
#include <hardfault.h>
+#include <rust/rust.h>
#include <screen.h>
#include <stdbool.h>
#include <string.h>
@@ -116,17 +117,21 @@ static component_t* _confirm_transaction_create(
confirm, label_create_scrollable_offset(address, NULL, CENTER, 0, 20, confirm));
}
if (strlens(fee)) {
+ char fee_label[MAX_LABEL_SIZE + 1] = {0};
+ rust_i18n_translate_copy("Fee", fee_label, sizeof(fee_label));
ui_util_add_sub_component(
- confirm, label_create_offset("Fee", &font_regular_9, CENTER_TOP, 0, 38, confirm));
+ confirm, label_create_offset(fee_label, &font_regular_9, CENTER_TOP, 0, 38, confirm));
ui_util_add_sub_component(
confirm, label_create_offset(fee, &font_regular_9, CENTER_TOP, 0, 50, confirm));
}
const UG_FONT* amount_font =
label_fits_width(amount, NULL, SCREEN_WIDTH) ? NULL : &font_regular_9;
if (verify_total) {
+ char total_label[MAX_LABEL_SIZE + 1] = {0};
+ rust_i18n_translate_copy("Total", total_label, sizeof(total_label));
ui_util_add_sub_component(
- confirm, label_create_offset("Total", NULL, CENTER_TOP, 0, 8, confirm));
+ confirm, label_create_offset(total_label, NULL, CENTER_TOP, 0, 8, confirm));
ui_util_add_sub_component(
confirm, label_create_offset(amount, amount_font, CENTER_TOP, 0, 22, confirm));
} else {
### src/ui/components/info_centered.c
@@ -6,6 +6,7 @@
#include "label.h"
#include <hardfault.h>
+#include <rust/rust.h>
#include <screen.h>
#include <string.h>
@@ -44,8 +45,10 @@ component_t* info_centered_create(const char* text, void (*skip_callback)(compon
ui_util_add_sub_component(info_centered, label_create(text, NULL, CENTER, info_centered));
if (skip_callback != NULL) {
- component_t* skip_button =
- button_create("Skip", bottom_slider, SCREEN_WIDTH / 2, skip_callback, info_centered);
+ char skip_label[20] = {0};
+ rust_i18n_translate_copy("Skip", skip_label, sizeof(skip_label));
+ component_t* skip_button = button_create(
+ skip_label, bottom_slider, SCREEN_WIDTH / 2, skip_callback, info_centered);
ui_util_add_sub_component(info_centered, skip_button);
}
### src/ui/components/lockscreen.c
@@ -109,8 +109,9 @@ component_t* lockscreen_create(void)
sizeof(display_name),
device_name_font,
component->dimension.width);
- ui_util_add_sub_component(
- component, label_create("See the BitBoxApp", NULL, CENTER, component));
+ char lockscreen_text[MAX_LABEL_SIZE + 1] = {0};
+ rust_i18n_translate_copy("See the BitBoxApp", lockscreen_text, sizeof(lockscreen_text));
+ ui_util_add_sub_component(component, label_create(lockscreen_text, NULL, CENTER, component));
ui_util_add_sub_component(
component, label_create(display_name, device_name_font, CENTER_BOTTOM, component));
### src/ui/components/menu.c
@@ -9,6 +9,7 @@
#include "right_arrow.h"
#include <hardfault.h>
+#include <rust/rust.h>
#include <screen.h>
#include <touch/gestures.h>
@@ -96,8 +97,10 @@ static void _update_positions(component_t* menu, int32_t velocity)
if (data->index == data->length - 1 && data->continue_on_last_cb != NULL &&
data->continue_on_last_button == NULL) {
+ char continue_label[20] = {0};
+ rust_i18n_translate_copy("Continue", continue_label, sizeof(continue_label));
data->continue_on_last_button =
- button_create("Continue", top_slider, SCREEN_WIDTH - 23, _continue, menu);
+ button_create(continue_label, top_slider, SCREEN_WIDTH - 23, _continue, menu);
ui_util_add_sub_component(menu, data->continue_on_last_button);
}
}
@@ -268,8 +271,10 @@ component_t* menu_create(
}
if (select_word_cb != NULL) {
+ char select_label[20] = {0};
+ rust_i18n_translate_copy("Select", select_label, sizeof(select_label));
ui_util_add_sub_component(
- menu, button_create("Select", bottom_slider, SCREEN_WIDTH / 2, _select, menu));
+ menu, button_create(select_label, bottom_slider, SCREEN_WIDTH / 2, _select, menu));
}
if (cancel_cb != NULL) {
### src/ui/components/orientation_arrows.c
@@ -6,6 +6,7 @@
#include "ui_images.h"
#include <hardfault.h>
+#include <rust/rust.h>
#include <screen.h>
#include <ui/ui_util.h>
#include <util.h>
@@ -19,7 +20,6 @@
#endif
#define SCALE 2 // Divide `count` by scale to slow down motion
-#define TEXT "Tap this side"
#define COUNT_CHANGE_DIRECTION (SCREEN_WIDTH / 2 + IMAGE_DEFAULT_ARROW_HEIGHT - 2)
#define COUNT_SHOW_TEXT (COUNT_CHANGE_DIRECTION + SCREEN_HEIGHT / 2 + 24)
@@ -172,8 +172,10 @@ component_t* orientation_arrows_create(void (*done_callback)(bool, void*), void*
orientation->position.top = 0;
orientation->position.left = 0;
- component_t* button_bottom = button_create_wide(TEXT, bottom_slider, _stay, orientation);
- component_t* button_top = button_create_wide(TEXT, top_slider, _flip, orientation);
+ char text[32] = {0};
+ rust_i18n_translate_copy("Tap this side", text, sizeof(text));
+ component_t* button_bottom = button_create_wide(text, bottom_slider, _stay, orientation);
+ component_t* button_top = button_create_wide(text, top_slider, _flip, orientation);
component_t* rotate = image_create(
IMAGE_ROTATE, sizeof(IMAGE_ROTATE), IMAGE_ROTATE_W, IMAGE_ROTATE_H, CENTER, orientation);
### src/ui/components/sdcard.c
@@ -5,6 +5,7 @@
#include "label.h"
#include "ui_images.h"
#include <hardfault.h>
+#include <rust/rust.h>
#include <screen.h>
#include <sd.h>
#include <touch/gestures.h>
@@ -84,13 +85,12 @@ component_t* sdcard_create(void (*callback)(bool inserted, void* user_data), voi
component->dimension.width = SCREEN_WIDTH;
component->dimension.height = SCREEN_HEIGHT;
+ char insert_text[MAX_LABEL_SIZE + 1] = {0};
+ rust_i18n_translate_copy("Insert SD card\nto continue", insert_text, sizeof(insert_text));
ui_util_add_sub_component(
component,
label_create(
- "Insert SD card\nto continue",
- NULL,
- screen_is_upside_down() ? RIGHT_CENTER : LEFT_CENTER,
- component));
+ insert_text, NULL, screen_is_upside_down() ? RIGHT_CENTER : LEFT_CENTER, component));
ui_util_add_sub_component(
component, icon_button_create(top_slider, ICON_BUTTON_CROSS, _cancel_callback, component));
return component;
### src/ui/ugui/ugui.c
@@ -679,7 +679,7 @@ void UG_MeasureStringCentered(UG_S16 *xout, UG_S16 *yout, const char *str)
UG_S16 calc_width_line = 0;
UG_S16 calc_height_line = 0;
const char* c;
- const uint8_t max_line = 128;
+ enum { max_line = 128 };
char line[max_line];
const char* start = str;
for (c = str; *c != '\0'; c++) {
@@ -859,33 +859,28 @@ void UG_PutStringCentered( UG_S16 x, UG_S16 y, UG_S16 width, UG_S16 height, cons
if (*c == '\n') {
num_lines++;
}
- // Limit num_lines to avoid stack overflows
if (num_lines > UG_MAX_LINE_ROWS) {
break;
}
}
- uint8_t current_line = 0;
- const uint8_t max_line = UG_MAX_LINE_COLS;
- char lines[num_lines][max_line];
- const char* start = str;
- for (c = str; *c != '\0'; c++) {
- if (*c == '\n' && current_line < UG_MAX_LINE_ROWS) {
- _copy_slice(
- lines[current_line], sizeof(lines[current_line]), start, (size_t)(c - start));
- current_line++;
- start = c + 1;
- }
- }
- _copy_slice(lines[current_line], sizeof(lines[current_line]), start, (size_t)(c - start));
// calculate the height of each line
_UG_PutString(0, 0, NULL, &calc_height, "W", 0, 1);
y = y + (height - ((calc_height + gui->char_v_space) * num_lines)) / 2;
+ char line[UG_MAX_LINE_COLS];
+ const char* start = str;
for (uint16_t i = 0; i < num_lines; i++) {
+ for (c = start; *c != '\0'; c++) {
+ if (*c == '\n' && i < UG_MAX_LINE_ROWS) {
+ break;
+ }
+ }
+ _copy_slice(line, sizeof(line), start, (size_t)(c - start));
UG_S16 current_y = y + (i * (calc_height + gui->char_v_space));
- _UG_PutString(0, 0, &calc_width, NULL, lines[i], 0, 1);
+ _UG_PutString(0, 0, &calc_width, NULL, line, 0, 1);
UG_S16 pos_x = x + (width - calc_width) / 2;
- _UG_PutString(pos_x, current_y, NULL, NULL, lines[i], 0, 0);
+ _UG_PutString(pos_x, current_y, NULL, NULL, line, 0, 0);
+ start = *c == '\n' ? c + 1 : c;
}
}
### src/ui/ugui/ugui.h
@@ -74,7 +74,7 @@ typedef struct {
#define UG_MAX_LINE_COLS 128
#define UG_MAX_LINE_ROWS 16
-/* Max allocaiton will be sizeof(char) * UG_MAX_LINE_COLS * UG_MAX_LINE_ROWS */
+/* Maximum line buffer allocation is sizeof(char) * UG_MAX_LINE_COLS. */
/* -------------------------------------------------------------------------------- */
/* -- PROTOTYPES -- */
### test/simulator-graphical-bb03/Cargo.lock
@@ -378,6 +378,14 @@ dependencies = [
"zeroize",
]
+[[package]]
+name = "bitbox-i18n"
+version = "0.1.0"
+dependencies = [
+ "bitbox-hal",
+ "serde_json",
+]
+
[[package]]
name = "bitbox-lvgl"
version = "0.1.0"
@@ -471,6 +479,7 @@ dependencies = [
"bitbox-bytequeue",
"bitbox-framed-serial-link",
"bitbox-hal",
+ "bitbox-i18n",
"bitbox-noise",
"bitbox-securechip",
"bitbox-securechip-sys",
@@ -499,6 +508,7 @@ dependencies = [
"bitbox-da14531",
"bitbox-executor",
"bitbox-hal",
+ "bitbox-i18n",
"bitbox-noise",
"bitbox-proto",
"bitbox-secp256k1",
### test/simulator-graphical/Cargo.lock
@@ -340,6 +340,14 @@ dependencies = [
"zeroize",
]
+[[package]]
+name = "bitbox-i18n"
+version = "0.1.0"
+dependencies = [
+ "bitbox-hal",
+ "serde_json",
+]
+
[[package]]
name = "bitbox-noise"
version = "0.1.0"
@@ -416,6 +424,7 @@ dependencies = [
"bitbox-bytequeue",
"bitbox-framed-serial-link",
"bitbox-hal",
+ "bitbox-i18n",
"bitbox-noise",
"bitbox-securechip",
"bitbox-securechip-sys",
@@ -444,6 +453,7 @@ dependencies = [
"bitbox-da14531",
"bitbox-executor",
"bitbox-hal",
+ "bitbox-i18n",
"bitbox-noise",
"bitbox-proto",
"bitbox-secp256k1",
### test/unit-test/test_ugui.c
@@ -570,6 +570,20 @@ static void _test_ugui_lvgl_cmap_validation(void** state)
assert_int_equal(width, 1);
}
+static void _test_ugui_put_string_centered_max_lines(void** state)
+{
+ (void)state;
+ UG_Init(&gui, _set_pixel, &font_regular_11, 128, 64);
+
+ char text[UG_MAX_LINE_ROWS + 2];
+ memset(text, '\n', UG_MAX_LINE_ROWS);
+ text[UG_MAX_LINE_ROWS] = 'A';
+ text[UG_MAX_LINE_ROWS + 1] = '\0';
+ _reset_pixel_capture();
+ UG_PutStringCentered(0, 0, 128, 64, text);
+ assert_true(pixels_set > 0);
+}
+
int main(void)
{
const struct CMUnitTest tests[] = {
@@ -588,6 +602,7 @@ int main(void)
cmocka_unit_test(_test_ugui_overhanging_glyph),
cmocka_unit_test(_test_ugui_put_string_resolves_glyph_once),
cmocka_unit_test(_test_ugui_lvgl_cmap_validation),
+ cmocka_unit_test(_test_ugui_put_string_centered_max_lines),
};
return cmocka_run_group_tests(tests, NULL, NULL);
}Why this scored 24/100
Community notes
Notes can correct, qualify, or add evidence to the AI analysis. Every note shown here has been validated by a human moderator.
The AI analysis stands alone for now. Submit a note if you can add evidence or important context.