What changed, and why it matters
This commit adds German language translations to the BitBox02 hardware wallet's on-screen prompts and messages. Most changes simply replace hard-coded English text with calls to a translation system. There is one small functional improvement: when confirming nested arrays in Ethereum typed-data signing, the temporary labels are now freed before processing child arrays, which reduces memory use. A few build/test changes pin large async functions on the heap to keep the compiler happy. Overall, this is a localization feature patch, not a security fix or vulnerability.
No security action required. Treat as a normal feature/localization commit. Reviewers may optionally verify that the new `Box::pin` wrappers do not change task cancellation semantics and that the scoped EIP-712 labels still display correctly in deeply nested test cases.
Security signals we found
Memory-use hardening: scoped array confirmation labels in EIP-712 typed-message signing to free allocations before recursion
No changes to cryptographic primitives, key handling, or authorization checks
No input validation changes observed
Build-only flag added: -Wno-psabi in bitbox-lvgl-sys/build.rs
Evidence from the diff
The commit localizes firmware UI workflows by routing user-facing strings through the existing i18n/tr! translation stack. It touches backup, Bitcoin, Ethereum, Cardano, U2F, reset/restore, and workflow modules. Notable non-i18n changes: (1) EIP-712 array confirmation labels are scoped to a block so allocations are dropped before recursive child-array processing, mitigating stack/heap pressure for deeply nested typed messages. (2) Several process_packet and large async call sites are wrapped in Box::pin(...) to satisfy lint/clippy future-size limits. (3) rust_u2f_app_string now accepts a localized ‘unknown site’ prefix from C callers. No cryptographic, access-control, or parsing logic is altered.
Changed components
src/rust/bitbox02-rust/src/hww/api/ethereum/sign_typed_msg.rssrc/rust/bitbox02-rust-c/src/async_usb.rssrc/rust/bitbox02-rust/src/hww.rssrc/rust/bitbox02-rust/src/hww/api/unlock/tests.rssrc/rust/bitbox02-rust/src/u2f.rssrc/da14531/da14531_handler.csrc/u2f.csrc/u2f/u2f_app.cTranslation/i18n layer across Rust workflows and C UI componentsInspect captured patch +1091 / −536
### 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
### 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/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/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/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/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/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_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/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/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/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/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;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.