rust: move async helper functions to the util crate
What changed, and why it matters
This commit simply moves existing helper code for running asynchronous tasks from one internal Rust crate to another shared utility crate. It does not change how the code works, does not fix any bug, and does not introduce any new behavior that could be exploited. It is a routine code organization change to make the helpers usable in more places.
No security action needed. Review as normal code refactor if desired.
Security signals we found
No strong security signals were identified.
Evidence from the diff
The change relocates Task, spin, option, and block_on helpers, plus the waker_fn module, from bitbox02-rust to the util crate. bitbox02-rust now re-exports these from util, and bitbox02 enables the util/testing feature when its own testing feature is on. The moved code is identical to the original, so this is a pure refactor with no functional or security impact.
Changed components
src/rust/bitbox02-rust/src/bb02_async.rssrc/rust/util/src/bb02_async.rssrc/rust/util/src/waker_fn.rsCargo.toml feature flags for testingInspect captured patch +118 / −96
diff --git a/src/rust/bitbox02-rust/Cargo.toml b/src/rust/bitbox02-rust/Cargo.toml
index 9a84d9d..eeafb8c 100644
--- a/src/rust/bitbox02-rust/Cargo.toml
+++ b/src/rust/bitbox02-rust/Cargo.toml
@@ -101,7 +101,8 @@ app-cardano = [
]
testing = [
- "bitbox02/testing"
+ "bitbox02/testing",
+ "util/testing"
]
c-unit-testing = []
diff --git a/src/rust/bitbox02-rust/src/bb02_async.rs b/src/rust/bitbox02-rust/src/bb02_async.rs
index 7c3060c..2a602e4 100644
--- a/src/rust/bitbox02-rust/src/bb02_async.rs
+++ b/src/rust/bitbox02-rust/src/bb02_async.rs
@@ -12,37 +12,11 @@
// See the License for the specific language governing permissions and
// limitations under the License.
-use alloc::boxed::Box;
use core::cell::RefCell;
-use core::pin::Pin;
-use core::task::{Context, Poll};
-/// Task is the top-level future which can be polled by an executor.
-/// Note that other futures awaited inside do not have to be pinned.
-/// The 'a lifetime allows to spin a boxed/pinned future that is not
-/// 'static, or a future with non-'static input param references.
-pub type Task<'a, O> = Pin<Box<dyn core::future::Future<Output = O> + 'a>>;
-
-/// A primitive poll invocation for a task, with no waking functionality.
-pub fn spin<O>(task: &mut Task<O>) -> Poll<O> {
- // TODO: statically allocate the context.
- let waker = crate::waker_fn::waker_fn(|| {});
- let context = &mut Context::from_waker(&waker);
- task.as_mut().poll(context)
-}
-
-/// Implements the Option future, see `option()`.
-pub struct AsyncOption<'a, O>(&'a RefCell<Option<O>>);
-
-impl<O> core::future::Future for AsyncOption<'_, O> {
- type Output = O;
- fn poll(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<Self::Output> {
- match self.0.borrow_mut().take() {
- None => Poll::Pending,
- Some(output) => Poll::Ready(output),
- }
- }
-}
+#[cfg(feature = "testing")]
+pub use util::bb02_async::block_on;
+pub use util::bb02_async::{Task, option, spin};
/// Disables the screensaver while waiting for an option to contain a value. Afterwards, it returns that value
pub async fn option_no_screensaver<O>(opt: &RefCell<Option<O>>) -> O {
@@ -51,20 +25,3 @@ pub async fn option_no_screensaver<O>(opt: &RefCell<Option<O>>) -> O {
bitbox02::screen_saver::screen_saver_enable();
result
}
-
-/// Waits for an option to contain a value and returns that value, leaving `None` in its place.
-/// E.g. `assert_eq!(option(&Some(42)).await, 42)`.
-pub fn option<O>(option: &RefCell<Option<O>>) -> AsyncOption<'_, O> {
- AsyncOption(option)
-}
-
-/// Polls a future until the result is available.
-#[cfg(feature = "testing")]
-pub fn block_on<O>(task: impl core::future::Future<Output = O>) -> O {
- let mut task: crate::bb02_async::Task<O> = alloc::boxed::Box::pin(task);
- loop {
- if let Poll::Ready(result) = spin(&mut task) {
- return result;
- }
- }
-}
diff --git a/src/rust/bitbox02-rust/src/lib.rs b/src/rust/bitbox02-rust/src/lib.rs
index 811090a..479d0af 100644
--- a/src/rust/bitbox02-rust/src/lib.rs
+++ b/src/rust/bitbox02-rust/src/lib.rs
@@ -40,7 +40,6 @@ pub mod secp256k1;
#[cfg(feature = "app-u2f")]
mod u2f;
mod version;
-mod waker_fn;
pub mod workflow;
#[cfg(any(feature = "app-bitcoin", feature = "app-litecoin"))]
mod xpubcache;
diff --git a/src/rust/bitbox02-rust/src/waker_fn.rs b/src/rust/bitbox02-rust/src/waker_fn.rs
deleted file mode 100644
index 16a94b4..0000000
--- a/src/rust/bitbox02-rust/src/waker_fn.rs
+++ /dev/null
@@ -1,47 +0,0 @@
-// This file was taken from here:
-// https://github.com/async-rs/async-task/blob/b7a249680490991f92cc2144d4eff65e4effb3b7/src/waker_fn.rs
-// https://github.com/async-rs/async-task/blob/b7a249680490991f92cc2144d4eff65e4effb3b7/LICENSE-APACHE
-
-use alloc::sync::Arc;
-use core::mem::{self, ManuallyDrop};
-use core::task::{RawWaker, RawWakerVTable, Waker};
-
-/// Creates a waker from a wake function.
-///
-/// The function gets called every time the waker is woken.
-pub fn waker_fn<F: Fn() + Send + Sync + 'static>(f: F) -> Waker {
- let raw = Arc::into_raw(Arc::new(f)) as *const ();
- let vtable = &Helper::<F>::VTABLE;
- unsafe { Waker::from_raw(RawWaker::new(raw, vtable)) }
-}
-
-struct Helper<F>(F);
-
-impl<F: Fn() + Send + Sync + 'static> Helper<F> {
- const VTABLE: RawWakerVTable = RawWakerVTable::new(
- Self::clone_waker,
- Self::wake,
- Self::wake_by_ref,
- Self::drop_waker,
- );
-
- unsafe fn clone_waker(ptr: *const ()) -> RawWaker {
- let arc = ManuallyDrop::new(unsafe { Arc::from_raw(ptr as *const F) });
- mem::forget(arc.clone());
- RawWaker::new(ptr, &Self::VTABLE)
- }
-
- unsafe fn wake(ptr: *const ()) {
- let arc = unsafe { Arc::from_raw(ptr as *const F) };
- (arc)();
- }
-
- unsafe fn wake_by_ref(ptr: *const ()) {
- let arc = ManuallyDrop::new(unsafe { Arc::from_raw(ptr as *const F) });
- (arc)();
- }
-
- unsafe fn drop_waker(ptr: *const ()) {
- drop(unsafe { Arc::from_raw(ptr as *const F) });
- }
-}
diff --git a/src/rust/bitbox02/Cargo.toml b/src/rust/bitbox02/Cargo.toml
index e0c8b38..b99296f 100644
--- a/src/rust/bitbox02/Cargo.toml
+++ b/src/rust/bitbox02/Cargo.toml
@@ -36,7 +36,7 @@ bitbox02-rust = { path = "../bitbox02-rust" }
[features]
# Only to be enabled in unit tests and simulators
-testing = []
+testing = ["util/testing"]
# Enables UI stubs for rust unit tests
unit-testing = []
# Active when the Rust code is compiled to be linked into the C unit tests and simulator.
diff --git a/src/rust/util/Cargo.toml b/src/rust/util/Cargo.toml
index 808988b..f27b99d 100644
--- a/src/rust/util/Cargo.toml
+++ b/src/rust/util/Cargo.toml
@@ -31,5 +31,6 @@ bitcoin = {workspace = true}
[features]
rtt = ["dep:rtt-target", "dep:cortex-m"]
+testing = []
c-unit-testing = []
firmware = []
diff --git a/src/rust/util/src/bb02_async.rs b/src/rust/util/src/bb02_async.rs
new file mode 100644
index 0000000..1b6a252
--- /dev/null
+++ b/src/rust/util/src/bb02_async.rs
@@ -0,0 +1,62 @@
+// Copyright 2025 Shift Crypto AG
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+use alloc::boxed::Box;
+use core::cell::RefCell;
+use core::pin::Pin;
+use core::task::{Context, Poll};
+
+/// Task is the top-level future which can be polled by an executor.
+/// Note that other futures awaited inside do not have to be pinned.
+/// The 'a lifetime allows to spin a boxed/pinned future that is not
+/// 'static, or a future with non-'static input param references.
+pub type Task<'a, O> = Pin<Box<dyn core::future::Future<Output = O> + 'a>>;
+
+/// A primitive poll invocation for a task, with no waking functionality.
+pub fn spin<O>(task: &mut Task<O>) -> Poll<O> {
+ // TODO: statically allocate the context.
+ let waker = crate::waker_fn::waker_fn(|| {});
+ let context = &mut Context::from_waker(&waker);
+ task.as_mut().poll(context)
+}
+
+/// Implements the Option future, see `option()`.
+pub struct AsyncOption<'a, O>(&'a RefCell<Option<O>>);
+
+impl<O> core::future::Future for AsyncOption<'_, O> {
+ type Output = O;
+ fn poll(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<Self::Output> {
+ match self.0.borrow_mut().take() {
+ None => Poll::Pending,
+ Some(output) => Poll::Ready(output),
+ }
+ }
+}
+
+/// Waits for an option to contain a value and returns that value, leaving `None` in its place.
+/// E.g. `assert_eq!(option(&Some(42)).await, 42)`.
+pub fn option<O>(option: &RefCell<Option<O>>) -> AsyncOption<'_, O> {
+ AsyncOption(option)
+}
+
+/// Polls a future until the result is available.
+#[cfg(feature = "testing")]
+pub fn block_on<O>(task: impl core::future::Future<Output = O>) -> O {
+ let mut task: crate::bb02_async::Task<O> = alloc::boxed::Box::pin(task);
+ loop {
+ if let Poll::Ready(result) = spin(&mut task) {
+ return result;
+ }
+ }
+}
diff --git a/src/rust/util/src/lib.rs b/src/rust/util/src/lib.rs
index 1c90970..22ffecf 100644
--- a/src/rust/util/src/lib.rs
+++ b/src/rust/util/src/lib.rs
@@ -14,12 +14,14 @@
#![cfg_attr(not(test), no_std)]
pub mod ascii;
+pub mod bb02_async;
pub mod bip32;
pub mod bytes;
pub mod cell;
pub mod decimal;
pub mod log;
pub mod name;
+mod waker_fn;
mod base58;
#[cfg(feature = "p256")]
diff --git a/src/rust/util/src/waker_fn.rs b/src/rust/util/src/waker_fn.rs
new file mode 100644
index 0000000..16a94b4
--- /dev/null
+++ b/src/rust/util/src/waker_fn.rs
@@ -0,0 +1,47 @@
+// This file was taken from here:
+// https://github.com/async-rs/async-task/blob/b7a249680490991f92cc2144d4eff65e4effb3b7/src/waker_fn.rs
+// https://github.com/async-rs/async-task/blob/b7a249680490991f92cc2144d4eff65e4effb3b7/LICENSE-APACHE
+
+use alloc::sync::Arc;
+use core::mem::{self, ManuallyDrop};
+use core::task::{RawWaker, RawWakerVTable, Waker};
+
+/// Creates a waker from a wake function.
+///
+/// The function gets called every time the waker is woken.
+pub fn waker_fn<F: Fn() + Send + Sync + 'static>(f: F) -> Waker {
+ let raw = Arc::into_raw(Arc::new(f)) as *const ();
+ let vtable = &Helper::<F>::VTABLE;
+ unsafe { Waker::from_raw(RawWaker::new(raw, vtable)) }
+}
+
+struct Helper<F>(F);
+
+impl<F: Fn() + Send + Sync + 'static> Helper<F> {
+ const VTABLE: RawWakerVTable = RawWakerVTable::new(
+ Self::clone_waker,
+ Self::wake,
+ Self::wake_by_ref,
+ Self::drop_waker,
+ );
+
+ unsafe fn clone_waker(ptr: *const ()) -> RawWaker {
+ let arc = ManuallyDrop::new(unsafe { Arc::from_raw(ptr as *const F) });
+ mem::forget(arc.clone());
+ RawWaker::new(ptr, &Self::VTABLE)
+ }
+
+ unsafe fn wake(ptr: *const ()) {
+ let arc = unsafe { Arc::from_raw(ptr as *const F) };
+ (arc)();
+ }
+
+ unsafe fn wake_by_ref(ptr: *const ()) {
+ let arc = ManuallyDrop::new(unsafe { Arc::from_raw(ptr as *const F) });
+ (arc)();
+ }
+
+ unsafe fn drop_waker(ptr: *const ()) {
+ drop(unsafe { Arc::from_raw(ptr as *const F) });
+ }
+}
Why this scored 15/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.