hal: make SD functions async and yielding
What changed, and why it matters
This commit changes how the BitBox02 hardware wallet talks to its SD card. The operations themselves stay the same, but each SD card call now briefly pauses (yields) so the device can keep answering USB/app messages while a long backup or restore runs. The goal is to prevent the app from giving up (timing out) during backups that touch the SD card many times in a row. It is a reliability/usability fix, not a patch for a memory-corruption or cryptographic bug.
Treat as a normal reliability improvement. No urgent security action required. If reviewing further, verify that the async executor is not re-entrant in a way that could allow the same backup/restore request to be processed twice concurrently, and confirm that host timeout behavior is improved by the added yield points.
Security signals we found
No change to cryptographic operations, seed handling, or authorization checks
No change to SD card data parsing or buffer handling
No new untrusted input surfaces introduced
Async/await conversion is purely cooperative scheduling; underlying SD operations remain blocking
Potential minor concern: yield points can affect timing and ordering assumptions, but no race condition is evident in the diff
Evidence from the diff
The patch converts the Sd trait and its implementations (BitBox02Sd, TestingSd) from synchronous functions to async functions. Each real SD operation still calls the same underlying bitbox02::sd::* blocking C functions, but after the call it awaits futures_lite::future::yield_now(). Callers in backup, restore, sdcard, and list-backup API paths are updated to .await these calls. This gives the executor a chance to process the USB communication task between repeated SD mount/list/read/write/unmount cycles, mitigating host-side timeouts during operations like backup creation that previously performed 10+ SD operations back-to-back.
Changed components
src/rust/bitbox02-rust/src/hal.rs (Sd trait and BitBox02Sd/TestingSd implementations)src/rust/bitbox02-rust/src/backup.rs (backup load/create)src/rust/bitbox02-rust/src/hww/api.rs (API dispatch for ListBackups, CheckSdcard)src/rust/bitbox02-rust/src/hww/api/backup.rs (check/list/create backup handlers)src/rust/bitbox02-rust/src/hww/api/restore.rs (restore from backup handler)src/rust/bitbox02-rust/src/hww/api/sdcard.rs (insert/remove SD card handler)Inspect captured patch +146 / −79
diff --git a/src/rust/bitbox02-rust/src/backup.rs b/src/rust/bitbox02-rust/src/backup.rs
index 5c366f8..6f209be 100644
--- a/src/rust/bitbox02-rust/src/backup.rs
+++ b/src/rust/bitbox02-rust/src/backup.rs
@@ -158,18 +158,18 @@ fn bitwise_recovery(buf1: &[u8], buf2: &[u8], buf3: &[u8]) -> Result<Zeroizing<V
Ok(recovered_contents)
}
-pub fn load(
+pub async fn load(
hal: &mut impl crate::hal::Hal,
dir: &str,
) -> Result<(Zeroizing<BackupData>, pb_backup::BackupMetaData), ()> {
- let files = hal.sd().list_subdir(Some(dir))?;
+ let files = hal.sd().list_subdir(Some(dir)).await?;
if files.len() != 3 {
return Err(());
}
let file_contents: [Zeroizing<Vec<u8>>; 3] = [
- hal.sd().load_bin(&files[0], dir)?,
- hal.sd().load_bin(&files[1], dir)?,
- hal.sd().load_bin(&files[2], dir)?,
+ hal.sd().load_bin(&files[0], dir).await?,
+ hal.sd().load_bin(&files[1], dir).await?,
+ hal.sd().load_bin(&files[2], dir).await?,
];
for contents in file_contents.iter() {
if let o @ Ok(_) = load_from_buffer(contents) {
@@ -186,7 +186,7 @@ pub fn load(
)?)
}
-pub fn create(
+pub async fn create(
hal: &mut impl crate::hal::Hal,
seed: &[u8],
name: &str,
@@ -232,7 +232,11 @@ pub fn create(
};
let backup_encoded = backup.encode_to_vec();
let dir = id(seed);
- let files = hal.sd().list_subdir(Some(&dir)).or(Err(Error::SdList))?;
+ let files = hal
+ .sd()
+ .list_subdir(Some(&dir))
+ .await
+ .or(Err(Error::SdList))?;
let filename_datetime = {
let tm = bitbox02::get_datetime(backup_create_timestamp).map_err(|_| Error::Generic)?;
@@ -255,10 +259,12 @@ pub fn create(
}
hal.sd()
.write_bin(&filename, &dir, &backup_encoded)
+ .await
.or(Err(Error::SdWrite))?;
if hal
.sd()
.load_bin(&filename, &dir)
+ .await
.or(Err(Error::SdRead))?
.as_slice()
!= backup_encoded.as_slice()
@@ -268,7 +274,7 @@ pub fn create(
}
let mut stale = false;
for file in files {
- if hal.sd().erase_file_in_subdir(&file, &dir).is_err() {
+ if hal.sd().erase_file_in_subdir(&file, &dir).await.is_err() {
stale = true
}
}
@@ -285,6 +291,8 @@ mod tests {
use crate::hal::testing::TestingHal;
use core::convert::TryInto;
+ use util::bb02_async::block_on;
+
#[test]
fn test_id() {
// Seeds of different lengths (16, 24, 32 bytes)
@@ -307,11 +315,23 @@ mod tests {
let mut mock_hal = TestingHal::new();
let timestamp = 1601281809;
let birthdate = timestamp - 32400;
- assert!(create(&mut mock_hal, seed, "test name", timestamp, birthdate).is_ok());
+ assert!(
+ block_on(create(
+ &mut mock_hal,
+ seed,
+ "test name",
+ timestamp,
+ birthdate
+ ))
+ .is_ok()
+ );
let dir = id(seed);
- assert_eq!(mock_hal.sd.list_subdir(None), Ok(vec![dir.clone()]));
assert_eq!(
- mock_hal.sd.list_subdir(Some(&dir)),
+ block_on(mock_hal.sd.list_subdir(None)),
+ Ok(vec![dir.clone()])
+ );
+ assert_eq!(
+ block_on(mock_hal.sd.list_subdir(Some(&dir))),
Ok(vec![
"backup_Mon_2020-09-28T08-30-09Z_0.bin".into(),
"backup_Mon_2020-09-28T08-30-09Z_1.bin".into(),
@@ -320,9 +340,18 @@ mod tests {
);
// Recreating using same timestamp is not allowed and doesn't change the backups.
- assert!(create(&mut mock_hal, seed, "new name", timestamp, birthdate).is_err());
+ assert!(
+ block_on(create(
+ &mut mock_hal,
+ seed,
+ "new name",
+ timestamp,
+ birthdate
+ ))
+ .is_err()
+ );
assert_eq!(
- mock_hal.sd.list_subdir(Some(&dir)),
+ block_on(mock_hal.sd.list_subdir(Some(&dir))),
Ok(vec![
"backup_Mon_2020-09-28T08-30-09Z_0.bin".into(),
"backup_Mon_2020-09-28T08-30-09Z_1.bin".into(),
@@ -330,24 +359,32 @@ mod tests {
])
);
- let contents: [zeroize::Zeroizing<Vec<u8>>; 3] = mock_hal
- .sd
- .list_subdir(Some(&dir))
- .unwrap()
- .iter()
- .map(|file| mock_hal.sd.load_bin(file, &dir).unwrap())
- .collect::<Vec<_>>()
- .try_into()
- .unwrap();
+ let contents: [zeroize::Zeroizing<Vec<u8>>; 3] =
+ block_on(mock_hal.sd.list_subdir(Some(&dir)))
+ .unwrap()
+ .iter()
+ .map(|file| block_on(mock_hal.sd.load_bin(file, &dir)).unwrap())
+ .collect::<Vec<_>>()
+ .try_into()
+ .unwrap();
assert!(
contents[0].as_slice() == contents[1].as_slice()
&& contents[0].as_slice() == contents[2].as_slice()
);
// Recreating the backup removes the previous files.
- assert!(create(&mut mock_hal, seed, "new name", timestamp + 1, birthdate).is_ok());
+ assert!(
+ block_on(create(
+ &mut mock_hal,
+ seed,
+ "new name",
+ timestamp + 1,
+ birthdate
+ ))
+ .is_ok()
+ );
assert_eq!(
- mock_hal.sd.list_subdir(Some(&dir)),
+ block_on(mock_hal.sd.list_subdir(Some(&dir))),
Ok(vec![
"backup_Mon_2020-09-28T08-30-10Z_0.bin".into(),
"backup_Mon_2020-09-28T08-30-10Z_1.bin".into(),
@@ -355,7 +392,7 @@ mod tests {
])
);
- let (backup_data, metadata) = load(&mut mock_hal, &dir).unwrap();
+ let (backup_data, metadata) = block_on(load(&mut mock_hal, &dir)).unwrap();
assert_eq!(backup_data.get_seed(), seed);
assert_eq!(backup_data.0.birthdate, birthdate);
assert_eq!(metadata.name.as_str(), "new name");
diff --git a/src/rust/bitbox02-rust/src/hal.rs b/src/rust/bitbox02-rust/src/hal.rs
index 489489b..953c8e0 100644
--- a/src/rust/bitbox02-rust/src/hal.rs
+++ b/src/rust/bitbox02-rust/src/hal.rs
@@ -18,12 +18,19 @@ pub use crate::workflow::Workflows as Ui;
use alloc::string::String;
use alloc::vec::Vec;
+use futures_lite::future::yield_now;
+
+#[allow(async_fn_in_trait)]
pub trait Sd {
- fn sdcard_inserted(&mut self) -> bool;
- fn list_subdir(&mut self, subdir: Option<&str>) -> Result<Vec<String>, ()>;
- fn erase_file_in_subdir(&mut self, filename: &str, dir: &str) -> Result<(), ()>;
- fn load_bin(&mut self, filename: &str, dir: &str) -> Result<zeroize::Zeroizing<Vec<u8>>, ()>;
- fn write_bin(&mut self, filename: &str, dir: &str, data: &[u8]) -> Result<(), ()>;
+ async fn sdcard_inserted(&mut self) -> bool;
+ async fn list_subdir(&mut self, subdir: Option<&str>) -> Result<Vec<String>, ()>;
+ async fn erase_file_in_subdir(&mut self, filename: &str, dir: &str) -> Result<(), ()>;
+ async fn load_bin(
+ &mut self,
+ filename: &str,
+ dir: &str,
+ ) -> Result<zeroize::Zeroizing<Vec<u8>>, ()>;
+ async fn write_bin(&mut self, filename: &str, dir: &str, data: &[u8]) -> Result<(), ()>;
}
/// Hardware abstraction layer for BitBox devices.
@@ -36,28 +43,42 @@ pub struct BitBox02Sd;
impl Sd for BitBox02Sd {
#[inline(always)]
- fn sdcard_inserted(&mut self) -> bool {
- bitbox02::sd::sdcard_inserted()
+ async fn sdcard_inserted(&mut self) -> bool {
+ let result = bitbox02::sd::sdcard_inserted();
+ yield_now().await;
+ result
}
#[inline(always)]
- fn list_subdir(&mut self, subdir: Option<&str>) -> Result<Vec<String>, ()> {
- bitbox02::sd::list_subdir(subdir)
+ async fn list_subdir(&mut self, subdir: Option<&str>) -> Result<Vec<String>, ()> {
+ let result = bitbox02::sd::list_subdir(subdir);
+ yield_now().await;
+ result
}
#[inline(always)]
- fn erase_file_in_subdir(&mut self, filename: &str, dir: &str) -> Result<(), ()> {
- bitbox02::sd::erase_file_in_subdir(filename, dir)
+ async fn erase_file_in_subdir(&mut self, filename: &str, dir: &str) -> Result<(), ()> {
+ let result = bitbox02::sd::erase_file_in_subdir(filename, dir);
+ yield_now().await;
+ result
}
#[inline(always)]
- fn load_bin(&mut self, filename: &str, dir: &str) -> Result<zeroize::Zeroizing<Vec<u8>>, ()> {
- bitbox02::sd::load_bin(filename, dir)
+ async fn load_bin(
+ &mut self,
+ filename: &str,
+ dir: &str,
+ ) -> Result<zeroize::Zeroizing<Vec<u8>>, ()> {
+ let result = bitbox02::sd::load_bin(filename, dir);
+ yield_now().await;
+ result
}
#[inline(always)]
- fn write_bin(&mut self, filename: &str, dir: &str, data: &[u8]) -> Result<(), ()> {
- bitbox02::sd::write_bin(filename, dir, data)
+ async fn write_bin(&mut self, filename: &str, dir: &str, data: &[u8]) -> Result<(), ()> {
+ let result = bitbox02::sd::write_bin(filename, dir, data);
+ yield_now().await;
+ result
}
}
@@ -105,11 +126,11 @@ pub mod testing {
}
impl super::Sd for TestingSd {
- fn sdcard_inserted(&mut self) -> bool {
+ async fn sdcard_inserted(&mut self) -> bool {
self.inserted.unwrap()
}
- fn list_subdir(&mut self, subdir: Option<&str>) -> Result<Vec<String>, ()> {
+ async fn list_subdir(&mut self, subdir: Option<&str>) -> Result<Vec<String>, ()> {
match subdir {
Some(key) => Ok(self
.files
@@ -120,14 +141,14 @@ pub mod testing {
}
}
- fn erase_file_in_subdir(&mut self, filename: &str, dir: &str) -> Result<(), ()> {
+ async fn erase_file_in_subdir(&mut self, filename: &str, dir: &str) -> Result<(), ()> {
self.files
.get_mut(dir)
.and_then(|files| files.remove(filename).map(|_| ()))
.ok_or(())
}
- fn load_bin(
+ async fn load_bin(
&mut self,
filename: &str,
dir: &str,
@@ -139,7 +160,7 @@ pub mod testing {
.ok_or(())
}
- fn write_bin(&mut self, filename: &str, dir: &str, data: &[u8]) -> Result<(), ()> {
+ async fn write_bin(&mut self, filename: &str, dir: &str, data: &[u8]) -> Result<(), ()> {
self.files
.entry(dir.into())
.or_default()
@@ -176,29 +197,38 @@ pub mod testing {
use super::*;
use crate::hal::Sd;
+ use util::bb02_async::block_on;
+
// Quick check if our mock TestingSd implementation makes sense.
#[test]
fn test_sd_list_write_read_erase() {
let mut sd = TestingSd::new();
- assert_eq!(sd.list_subdir(None), Ok(vec![]));
- assert_eq!(sd.list_subdir(Some("dir1")), Ok(vec![]));
+ assert_eq!(block_on(sd.list_subdir(None)), Ok(vec![]));
+ assert_eq!(block_on(sd.list_subdir(Some("dir1"))), Ok(vec![]));
- assert!(sd.load_bin("file1.txt", "dir1").is_err());
- assert!(sd.write_bin("file1.txt", "dir1", b"data").is_ok());
- assert_eq!(sd.list_subdir(None), Ok(vec!["dir1".into()]));
- assert_eq!(sd.list_subdir(Some("dir1")), Ok(vec!["file1.txt".into()]));
+ assert!(block_on(sd.load_bin("file1.txt", "dir1")).is_err());
+ assert!(block_on(sd.write_bin("file1.txt", "dir1", b"data")).is_ok());
+ assert_eq!(block_on(sd.list_subdir(None)), Ok(vec!["dir1".into()]));
+ assert_eq!(
+ block_on(sd.list_subdir(Some("dir1"))),
+ Ok(vec!["file1.txt".into()])
+ );
assert_eq!(
- sd.load_bin("file1.txt", "dir1").unwrap().as_slice(),
+ block_on(sd.load_bin("file1.txt", "dir1"))
+ .unwrap()
+ .as_slice(),
b"data"
);
- assert!(sd.write_bin("file1.txt", "dir1", b"replaced data").is_ok());
+ assert!(block_on(sd.write_bin("file1.txt", "dir1", b"replaced data")).is_ok());
assert_eq!(
- sd.load_bin("file1.txt", "dir1").unwrap().as_slice(),
+ block_on(sd.load_bin("file1.txt", "dir1"))
+ .unwrap()
+ .as_slice(),
b"replaced data"
);
- assert!(sd.erase_file_in_subdir("doesnt-exist.txt", "dir1").is_err());
- assert!(sd.erase_file_in_subdir("file1.txt", "dir1").is_ok());
- assert_eq!(sd.list_subdir(Some("dir1")), Ok(vec![]));
+ assert!(block_on(sd.erase_file_in_subdir("doesnt-exist.txt", "dir1")).is_err());
+ assert!(block_on(sd.erase_file_in_subdir("file1.txt", "dir1")).is_ok());
+ assert_eq!(block_on(sd.list_subdir(Some("dir1"))), Ok(vec![]));
}
}
}
diff --git a/src/rust/bitbox02-rust/src/hww/api.rs b/src/rust/bitbox02-rust/src/hww/api.rs
index d5f159d..025ad60 100644
--- a/src/rust/bitbox02-rust/src/hww/api.rs
+++ b/src/rust/bitbox02-rust/src/hww/api.rs
@@ -172,9 +172,9 @@ async fn process_api(hal: &mut impl crate::hal::Hal, request: &Request) -> Resul
set_mnemonic_passphrase_enabled::process(hal, request).await
}
Request::InsertRemoveSdcard(request) => sdcard::process(hal, request).await,
- Request::ListBackups(_) => backup::list(hal),
+ Request::ListBackups(_) => backup::list(hal).await,
Request::CheckSdcard(_) => Ok(Response::CheckSdcard(pb::CheckSdCardResponse {
- inserted: hal.sd().sdcard_inserted(),
+ inserted: hal.sd().sdcard_inserted().await,
})),
Request::CheckBackup(request) => backup::check(hal, request).await,
Request::CreateBackup(request) => backup::create(hal, request).await,
diff --git a/src/rust/bitbox02-rust/src/hww/api/backup.rs b/src/rust/bitbox02-rust/src/hww/api/backup.rs
index d4b9954..c48038c 100644
--- a/src/rust/bitbox02-rust/src/hww/api/backup.rs
+++ b/src/rust/bitbox02-rust/src/hww/api/backup.rs
@@ -26,13 +26,13 @@ pub async fn check(
hal: &mut impl crate::hal::Hal,
&pb::CheckBackupRequest { silent }: &pb::CheckBackupRequest,
) -> Result<Response, Error> {
- if !hal.sd().sdcard_inserted() {
+ if !hal.sd().sdcard_inserted().await {
return Err(Error::InvalidInput);
}
let seed = bitbox02::keystore::copy_seed()?;
let id = backup::id(&seed);
- let (backup_data, metadata) = backup::load(hal, &id)?;
+ 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;
@@ -109,7 +109,7 @@ pub async fn create(
return Err(Error::Memory);
}
timestamp
- } else if let Ok((data, _)) = backup::load(hal, &backup::id(&seed)) {
+ } else if let Ok((data, _)) = backup::load(hal, &backup::id(&seed)).await {
// If adding new backup after initialized, we do not know the seed birthdate.
// If re-creating it, we use the already existing one.
data.0.birthdate
@@ -122,7 +122,9 @@ pub async fn create(
&bitbox02::memory::get_device_name(),
timestamp,
seed_birthdate,
- ) {
+ )
+ .await
+ {
Ok(()) => {
// The backup was created, so reporting an error here
// could have bad consequences like replacing the sd card,
@@ -142,10 +144,10 @@ pub async fn create(
}
}
-pub fn list(hal: &mut impl crate::hal::Hal) -> Result<Response, Error> {
+pub async fn list(hal: &mut impl crate::hal::Hal) -> Result<Response, Error> {
let mut info: Vec<pb::BackupInfo> = Vec::new();
- for dir in hal.sd().list_subdir(None)? {
- let (_, metadata) = match backup::load(hal, &dir) {
+ for dir in hal.sd().list_subdir(None).await? {
+ let (_, metadata) = match backup::load(hal, &dir).await {
Ok(d) => d,
Err(_) => continue,
};
@@ -235,14 +237,12 @@ mod tests {
// above seed.
let backup_fixture_v9_12_0: Vec<u8> = hex::decode("0a6c0a6a0a2017834e53e17370800c0bc49b49ef3f1309df104d7239db5bbd093c90eefc995112110891bec6fb0512094d7920426974426f782233081012208af64d31126a39b98f59708a3a463e5b000000000000000000000000000000001891bec6fb05220776392e31332e30").unwrap();
for i in 0..3 {
- mock_hal
- .sd
- .write_bin(
- &format!("backup_Mon_2020-09-28T08-30-09Z_{}.bin", i),
- EXPECTED_ID,
- &backup_fixture_v9_12_0,
- )
- .unwrap();
+ block_on(mock_hal.sd.write_bin(
+ &format!("backup_Mon_2020-09-28T08-30-09Z_{}.bin", i),
+ EXPECTED_ID,
+ &backup_fixture_v9_12_0,
+ ))
+ .unwrap();
}
// Check that the loaded seed matches the backup.
assert_eq!(
@@ -287,7 +287,7 @@ mod tests {
// No backups yet.
assert_eq!(
- list(&mut mock_hal),
+ block_on(list(&mut mock_hal)),
Ok(Response::ListBackups(pb::ListBackupsResponse {
info: vec![]
}))
@@ -313,7 +313,7 @@ mod tests {
);
assert_eq!(
- list(&mut mock_hal,),
+ block_on(list(&mut mock_hal)),
Ok(Response::ListBackups(pb::ListBackupsResponse {
info: vec![pb::BackupInfo {
id: "41233dfbad010723dbbb93514b7b81016b73f8aa35c5148e1b478f60d5750dce".into(),
@@ -342,7 +342,7 @@ mod tests {
);
assert_eq!(
- list(&mut mock_hal),
+ block_on(list(&mut mock_hal)),
Ok(Response::ListBackups(pb::ListBackupsResponse {
info: vec![
pb::BackupInfo {
diff --git a/src/rust/bitbox02-rust/src/hww/api/restore.rs b/src/rust/bitbox02-rust/src/hww/api/restore.rs
index d3c706b..9362015 100644
--- a/src/rust/bitbox02-rust/src/hww/api/restore.rs
+++ b/src/rust/bitbox02-rust/src/hww/api/restore.rs
@@ -33,7 +33,7 @@ pub async fn from_file(
})
.await?;
- let (data, metadata) = match crate::backup::load(hal, &request.id) {
+ let (data, metadata) = match crate::backup::load(hal, &request.id).await {
Ok(d) => d,
Err(_) => {
hal.ui().status("Could not\nrestore backup", false).await;
diff --git a/src/rust/bitbox02-rust/src/hww/api/sdcard.rs b/src/rust/bitbox02-rust/src/hww/api/sdcard.rs
index 65d471b..9e251a9 100644
--- a/src/rust/bitbox02-rust/src/hww/api/sdcard.rs
+++ b/src/rust/bitbox02-rust/src/hww/api/sdcard.rs
@@ -25,7 +25,7 @@ pub async fn process(
hal: &mut impl crate::hal::Hal,
&pb::InsertRemoveSdCardRequest { action }: &pb::InsertRemoveSdCardRequest,
) -> Result<Response, Error> {
- let inserted = hal.sd().sdcard_inserted();
+ let inserted = hal.sd().sdcard_inserted().await;
match SdCardAction::try_from(action) {
Ok(SdCardAction::InsertCard) => {}
_ => return Ok(Response::Success(pb::Success {})),
Why this scored 23/100
Community notes
Notes can correct, qualify, or add evidence to the AI analysis. Every note shown here has been validated by a human moderator.
The AI analysis stands alone for now. Submit a note if you can add evidence or important context.