i18n: persist and expose device language
What changed, and why it matters
This commit adds the ability to choose a device language (English or German) and remember it after reboot. It also lets a connected computer read the current language and list supported languages. The change requires the user to confirm on the device before switching languages, and it rejects unknown language codes. There is no direct evidence in the commit of a security vulnerability, but any new command that writes to device memory deserves a careful look for input validation and memory-safety issues.
Review the new `set_device_language` handler for TOCTOU and confirmation-bypass paths, verify that the C memory chunk write cannot corrupt adjacent fields, and audit `rust_i18n_translate_copy` callers for correct output buffer sizing. Treat as a normal feature commit unless additional context links it to a security issue.
Security signals we found
New host-facing command writes persistent device settings
Input validation rejects unsupported language codes with InvalidInput
User confirmation is required before persisting language change
Memory write uses a single reserved byte with enumerated values
New unsafe FFI copy helper handles null pointers and UTF-8 truncation
No security relevance, CVE, or researcher attribution in commit or references
Evidence from the diff
The patch introduces a new SetDeviceLanguage protobuf request, persists the selected language in a previously reserved settings byte, exposes it via DeviceInfoResponse, and adds Rust/C bridges and translation macros. The firmware validates the requested language code against a compile-time supported list, shows a device confirmation prompt in the current language, and only writes after user approval. The C memory layer restricts values to MEMORY_DEVICE_LANGUAGE_EN/DE and defaults to English. A new C-exported rust_i18n_translate_copy routine copies translated UTF-8 strings to a caller buffer, truncating only at character boundaries.
Changed components
BitBox02 firmware device settings / memory subsystemHost-wallet protobuf API (bitbox02_system.proto)Python bitbox02 client libraryRust i18n/translation core (bitbox-i18n, bitbox02-rust, bitbox02)C memory module (src/memory/memory.c)Inspect captured patch +525 / −33
### 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/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
@@ -356,6 +356,7 @@ dependencies = [
"bitbox-bytequeue",
"bitbox-framed-serial-link",
"bitbox-hal",
+ "bitbox-i18n",
"bitbox-noise",
"bitbox-securechip",
"bitbox-securechip-sys",
@@ -385,6 +386,7 @@ dependencies = [
"bitbox-da14531",
"bitbox-executor",
"bitbox-hal",
+ "bitbox-i18n",
"bitbox-noise",
"bitbox-platform-host",
"bitbox-proto",
### src/rust/bitbox-hal/src/memory.rs
@@ -88,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/build.rs
@@ -7,21 +7,31 @@ 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("en/firmware.json");
- let de_path = locales_dir.join("de/firmware.json");
+ let en_path = locales_dir.join(SOURCE_LOCALE).join("firmware.json");
println!("cargo::rerun-if-changed={}", en_path.display());
- println!("cargo::rerun-if-changed={}", de_path.display());
let english = read_flattened_json(&en_path);
- let german = read_flattened_json(&de_path);
- let german_entries = locale_entries(&english, &german, &de_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);
+ }
- let mut generated = generated_table(&german_entries);
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");
@@ -128,9 +138,11 @@ fn placeholder_count(value: &str) -> usize {
value.matches("{}").count() + value.matches("{:?}").count()
}
-fn generated_table(entries: &[(String, String)]) -> String {
- let mut out = String::from("// @generated by build.rs\n\n");
- out.push_str("pub(crate) const DE_TRANSLATIONS: &[(u64, &str)] = &[\n");
+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);
### src/rust/bitbox-i18n/src/lib.rs
@@ -118,6 +118,14 @@ fn next_placeholder(value: &str) -> Option<(usize, usize)> {
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));
### 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/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/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/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/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/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-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/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/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!()
}
### 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",Why this scored 23/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.