What changed, and why it matters
This commit upgrades the Rust code edition from 2021 to 2024 across the project and applies the matching rustfmt formatting. It is a routine toolchain/language-version migration: Cargo.toml files are updated, import order is re-sorted, unsafe blocks are wrapped in new unsafe extern/unsafe {} syntax required by the 2024 edition, and test code is reformatted. There are no functional security fixes or behavior changes visible in the diff.
No security action required. Treat as a normal dependency/language-edition upgrade; verify CI/tests pass and that the new unsafe-extern/unsafe-block syntax is applied consistently.
Security signals we found
No strong security signals were identified.
Evidence from the diff
The diff is a large, mechanical migration to Rust edition 2024. Concrete changes include: edition=‘2024’ in Cargo.toml files; rustfmt.toml aligned to 2024; #[no_mangle] replaced with #[unsafe(no_mangle)]; extern “C” blocks marked unsafe; unsafe operations inside unsafe fn now wrapped in unsafe { … }; match arms drop ref bindings (e.g., Request::BtcPub(request) instead of Request::BtcPub(ref request)); import re-ordering; and purely formatting changes (line breaks, trailing commas). No logic, bounds checks, cryptographic operations, or authorization checks are modified.
Changed components
Rust workspace edition configurationrustfmt configurationFFI C-bindings in bitbox02-rust-cRust API handlers (Bitcoin, Ethereum, Cardano, etc.)Inspect captured patch +1041 / −815
diff --git a/src/rust/bitbox-aes/src/lib.rs b/src/rust/bitbox-aes/src/lib.rs
index 1ed192a..8a3c1ef 100644
--- a/src/rust/bitbox-aes/src/lib.rs
+++ b/src/rust/bitbox-aes/src/lib.rs
@@ -19,7 +19,7 @@ extern crate alloc;
use alloc::vec::Vec;
-use bitcoin::hashes::{sha256, Hash, HashEngine, Hmac, HmacEngine};
+use bitcoin::hashes::{Hash, HashEngine, Hmac, HmacEngine, sha256};
// AES block size.
const BLOCK_SIZE: usize = 16;
diff --git a/src/rust/bitbox02-noise/Cargo.toml b/src/rust/bitbox02-noise/Cargo.toml
index 9d62bdb..d314968 100644
--- a/src/rust/bitbox02-noise/Cargo.toml
+++ b/src/rust/bitbox02-noise/Cargo.toml
@@ -17,7 +17,7 @@
name = "bitbox02-noise"
version = "0.1.0"
authors = ["Shift Crypto AG <support@bitbox.swiss>"]
-edition = "2021"
+edition = "2024"
description = "BitBox02 noise protocol primitives"
license = "Apache-2.0"
diff --git a/src/rust/bitbox02-noise/src/noise_xx.rs b/src/rust/bitbox02-noise/src/noise_xx.rs
index 0654940..b4acc44 100644
--- a/src/rust/bitbox02-noise/src/noise_xx.rs
+++ b/src/rust/bitbox02-noise/src/noise_xx.rs
@@ -16,7 +16,7 @@ extern crate alloc;
use alloc::vec::Vec;
use crate::x25519::{PrivateKey, PublicKey, Random32, X25519};
-use noise_rust_crypto::{sensitive::Sensitive, ChaCha20Poly1305, Sha256};
+use noise_rust_crypto::{ChaCha20Poly1305, Sha256, sensitive::Sensitive};
/// Specialization of noise_protocol::HandshakeState, picking the implementations for Diffie
/// Hellman, Cipher and Hash.
diff --git a/src/rust/bitbox02-rust-c/Cargo.toml b/src/rust/bitbox02-rust-c/Cargo.toml
index 9c5f841..b9c1e29 100644
--- a/src/rust/bitbox02-rust-c/Cargo.toml
+++ b/src/rust/bitbox02-rust-c/Cargo.toml
@@ -17,7 +17,7 @@
name = "bitbox02-rust-c"
version = "0.1.0"
authors = ["Shift Crypto AG <support@bitbox.swiss>"]
-edition = "2021"
+edition = "2024"
license = "Apache-2.0"
[lib]
diff --git a/src/rust/bitbox02-rust-c/src/alloc.rs b/src/rust/bitbox02-rust-c/src/alloc.rs
index 14d1b19..fac6694 100644
--- a/src/rust/bitbox02-rust-c/src/alloc.rs
+++ b/src/rust/bitbox02-rust-c/src/alloc.rs
@@ -14,17 +14,17 @@
struct BB02Allocator;
-extern "C" {
+unsafe extern "C" {
pub fn malloc(size: usize) -> *mut core::ffi::c_void;
pub fn free(p: *mut core::ffi::c_void);
}
unsafe impl core::alloc::GlobalAlloc for BB02Allocator {
unsafe fn alloc(&self, layout: core::alloc::Layout) -> *mut u8 {
- malloc(layout.size()) as _
+ unsafe { malloc(layout.size()) as _ }
}
unsafe fn dealloc(&self, ptr: *mut u8, _layout: core::alloc::Layout) {
- free(ptr as _)
+ unsafe { free(ptr as _) }
}
}
diff --git a/src/rust/bitbox02-rust-c/src/async_usb.rs b/src/rust/bitbox02-rust-c/src/async_usb.rs
index 70d4b13..7caaec2 100644
--- a/src/rust/bitbox02-rust-c/src/async_usb.rs
+++ b/src/rust/bitbox02-rust-c/src/async_usb.rs
@@ -15,7 +15,7 @@
use bitbox02_rust::async_usb::{on_next_request, spawn, waiting_for_next_request};
use bitbox02_rust::hww::process_packet;
-#[no_mangle]
+#[unsafe(no_mangle)]
pub extern "C" fn rust_async_usb_spin() {
bitbox02_rust::async_usb::spin();
}
@@ -33,13 +33,13 @@ pub enum UsbResponse {
/// `UsbResponseNack` if on ask is running.
/// `UsbResponseAck` if the result was copied.
/// `UsbResponseNotReady` if a task is running but not yet complete.
-#[no_mangle]
+#[unsafe(no_mangle)]
pub unsafe extern "C" fn rust_async_usb_copy_response(out: *mut bitbox02::buffer_t) -> UsbResponse {
- use bitbox02_rust::async_usb::{copy_response, CopyResponseErr};
- let dst = core::slice::from_raw_parts_mut((*out).data, (*out).max_len);
+ use bitbox02_rust::async_usb::{CopyResponseErr, copy_response};
+ let dst = unsafe { core::slice::from_raw_parts_mut((*out).data, (*out).max_len) };
match copy_response(dst) {
Ok(len) => {
- (*out).len = len as _;
+ unsafe { (*out).len = len as _ };
UsbResponse::UsbResponseAck
}
Err(CopyResponseErr::NotReady) => UsbResponse::UsbResponseNotReady,
@@ -51,7 +51,7 @@ pub unsafe extern "C" fn rust_async_usb_copy_response(out: *mut bitbox02::buffer
/// arbitration level should be taken care of before).
///
/// `usb_in` are the api request bytes.
-#[no_mangle]
+#[unsafe(no_mangle)]
pub extern "C" fn rust_async_usb_on_request_hww(usb_in: crate::util::Bytes) {
if waiting_for_next_request() {
on_next_request(usb_in.as_ref());
@@ -60,7 +60,7 @@ pub extern "C" fn rust_async_usb_on_request_hww(usb_in: crate::util::Bytes) {
}
}
-#[no_mangle]
+#[unsafe(no_mangle)]
pub extern "C" fn rust_async_usb_cancel() -> bool {
bitbox02_rust::async_usb::cancel()
}
diff --git a/src/rust/bitbox02-rust-c/src/bip39.rs b/src/rust/bitbox02-rust-c/src/bip39.rs
index f6e5db7..d00862c 100644
--- a/src/rust/bitbox02-rust-c/src/bip39.rs
+++ b/src/rust/bitbox02-rust-c/src/bip39.rs
@@ -18,7 +18,7 @@
///
/// `seed` must be 16, 24 or 32 bytes long.
/// `out` must be exactly 64 bytes long.
-#[no_mangle]
+#[unsafe(no_mangle)]
pub unsafe extern "C" fn rust_derive_bip39_seed(
seed: crate::util::Bytes,
passphrase: *const core::ffi::c_char,
@@ -26,13 +26,13 @@ pub unsafe extern "C" fn rust_derive_bip39_seed(
) {
let mnemonic =
bip39::Mnemonic::from_entropy_in(bip39::Language::English, seed.as_ref()).unwrap();
- let passphrase = core::ffi::CStr::from_ptr(passphrase);
+ let passphrase = unsafe { core::ffi::CStr::from_ptr(passphrase) };
let bip39_seed =
zeroize::Zeroizing::new(mnemonic.to_seed_normalized(passphrase.to_str().unwrap()));
out.as_mut().clone_from_slice(&bip39_seed[..]);
}
-#[no_mangle]
+#[unsafe(no_mangle)]
pub extern "C" fn rust_get_bip39_word(idx: u16, mut out: crate::util::BytesMut) -> bool {
let word = match bitbox02_rust::bip39::get_word(idx) {
Err(()) => return false,
diff --git a/src/rust/bitbox02-rust-c/src/der.rs b/src/rust/bitbox02-rust-c/src/der.rs
index ba8d745..a12caa6 100644
--- a/src/rust/bitbox02-rust-c/src/der.rs
+++ b/src/rust/bitbox02-rust-c/src/der.rs
@@ -42,7 +42,7 @@ fn parse_two_int256s(data: &[u8]) -> Result<([u8; 32], [u8; 32]), ()> {
/// The input is the DER encoding of the signature R/S values encoded as two DER "INGEGER".
/// It's the same encoding as a regular DER-signature, but without the 0x30 sequence header.
/// sig_compact_out must be 64 bytes and will contain the R/S values (each 32 bytes).
-#[no_mangle]
+#[unsafe(no_mangle)]
pub extern "C" fn rust_der_parse_optiga_signature(
sig_der: crate::util::Bytes,
mut sig_compact_out: crate::util::BytesMut,
diff --git a/src/rust/bitbox02-rust-c/src/lib.rs b/src/rust/bitbox02-rust-c/src/lib.rs
index 5883022..569c84d 100644
--- a/src/rust/bitbox02-rust-c/src/lib.rs
+++ b/src/rust/bitbox02-rust-c/src/lib.rs
@@ -56,12 +56,12 @@ fn panic(info: &core::panic::PanicInfo) -> ! {
loop {}
}
-#[no_mangle]
+#[unsafe(no_mangle)]
pub extern "C" fn rust_rtt_init() {
::util::log::rtt_init()
}
-#[no_mangle]
+#[unsafe(no_mangle)]
pub extern "C" fn rust_rtt_flush() {
::util::log::rtt_flush();
}
@@ -69,7 +69,7 @@ pub extern "C" fn rust_rtt_flush() {
/// # Safety
///
/// The pointer `ptr` must point to a null terminated string
-#[no_mangle]
+#[unsafe(no_mangle)]
#[cfg_attr(not(all(feature = "rtt", target_os = "none")), allow(unused))]
pub unsafe extern "C" fn rust_log(ptr: *const core::ffi::c_char) {
#[cfg(all(feature = "rtt", target_os = "none"))]
@@ -83,7 +83,7 @@ pub unsafe extern "C" fn rust_log(ptr: *const core::ffi::c_char) {
}
}
-#[no_mangle]
+#[unsafe(no_mangle)]
pub extern "C" fn rust_cipher_encrypt(
iv: crate::util::Bytes,
key: crate::util::Bytes,
@@ -100,7 +100,7 @@ pub extern "C" fn rust_cipher_encrypt(
*out_len = enc.len();
}
-#[no_mangle]
+#[unsafe(no_mangle)]
pub extern "C" fn rust_cipher_decrypt(
key: crate::util::Bytes,
cipher: crate::util::Bytes,
@@ -121,16 +121,18 @@ pub extern "C" fn rust_cipher_decrypt(
///
/// keypath pointer has point to a buffer of length `keypath_len` uint32 elements.
#[cfg(feature = "firmware")]
-#[no_mangle]
+#[unsafe(no_mangle)]
pub unsafe extern "C" fn rust_secp256k1_get_private_key(
keypath: *const u32,
keypath_len: usize,
mut out: crate::util::BytesMut,
) -> bool {
- match bitbox02_rust::keystore::secp256k1_get_private_key(core::slice::from_raw_parts(
- keypath,
- keypath_len,
- )) {
+ match unsafe {
+ bitbox02_rust::keystore::secp256k1_get_private_key(core::slice::from_raw_parts(
+ keypath,
+ keypath_len,
+ ))
+ } {
Ok(private_key) => {
out.as_mut().copy_from_slice(&private_key);
true
@@ -142,7 +144,7 @@ pub unsafe extern "C" fn rust_secp256k1_get_private_key(
/// # Safety
///
/// The pointer `data` must point to a buffer of length `len`.
-#[no_mangle]
+#[unsafe(no_mangle)]
#[allow(static_mut_refs)]
#[cfg_attr(not(all(feature = "rtt", target_os = "none")), allow(unused))]
pub unsafe extern "C" fn rust_rtt_ch1_write(data: *const u8, len: usize) {
@@ -160,7 +162,7 @@ pub unsafe extern "C" fn rust_rtt_ch1_write(data: *const u8, len: usize) {
/// # Safety
///
/// The pointer `data` must point to a buffer of length `len`.
-#[no_mangle]
+#[unsafe(no_mangle)]
#[allow(static_mut_refs)]
#[cfg_attr(not(all(feature = "rtt", target_os = "none")), allow(unused))]
pub unsafe extern "C" fn rust_rtt_ch0_read(data: *mut u8, len: usize) -> usize {
diff --git a/src/rust/bitbox02-rust-c/src/noise.rs b/src/rust/bitbox02-rust-c/src/noise.rs
index b72d62c..25e8125 100644
--- a/src/rust/bitbox02-rust-c/src/noise.rs
+++ b/src/rust/bitbox02-rust-c/src/noise.rs
@@ -14,7 +14,7 @@
// limitations under the License.
/// `private_key_out` must be 32 bytes.
-#[no_mangle]
+#[unsafe(no_mangle)]
pub extern "C" fn rust_noise_generate_static_private_key(
mut private_key_out: crate::util::BytesMut,
) {
diff --git a/src/rust/bitbox02-rust-c/src/p256.rs b/src/rust/bitbox02-rust-c/src/p256.rs
index 4e65661..0daa483 100644
--- a/src/rust/bitbox02-rust-c/src/p256.rs
+++ b/src/rust/bitbox02-rust-c/src/p256.rs
@@ -14,7 +14,7 @@
/// Derive the public key of a ECC NIST-P256 private key.
/// private_key must be 32 bytes, public_key_out must be 64 bytes.
-#[no_mangle]
+#[unsafe(no_mangle)]
pub extern "C" fn rust_p256_pubkey(
private_key: crate::util::Bytes,
mut public_key_out: crate::util::BytesMut,
@@ -31,13 +31,13 @@ pub extern "C" fn rust_p256_pubkey(
/// private_key must be 32 bytes.
/// msg must be 32 bytes digest and is signed directly without further hashing.
/// sig_out must be 64 bytes.
-#[no_mangle]
+#[unsafe(no_mangle)]
pub extern "C" fn rust_p256_sign(
private_key: crate::util::Bytes,
msg: crate::util::Bytes,
mut sig_out: crate::util::BytesMut,
) {
- use p256::ecdsa::{signature::hazmat::PrehashSigner, Signature, SigningKey};
+ use p256::ecdsa::{Signature, SigningKey, signature::hazmat::PrehashSigner};
let signing_key = SigningKey::from_slice(private_key.as_ref()).unwrap();
let (signature, _): (Signature, _) = signing_key.sign_prehash(msg.as_ref()).unwrap();
sig_out.as_mut().copy_from_slice(&signature.to_bytes());
diff --git a/src/rust/bitbox02-rust-c/src/sha2.rs b/src/rust/bitbox02-rust-c/src/sha2.rs
index 460dd03..953b571 100644
--- a/src/rust/bitbox02-rust-c/src/sha2.rs
+++ b/src/rust/bitbox02-rust-c/src/sha2.rs
@@ -20,7 +20,7 @@ use sha2::Digest;
use sha2::Sha256;
/// Result must be freed by calling `rust_sha256_finish()` or `rust_sha256_free()`.
-#[no_mangle]
+#[unsafe(no_mangle)]
pub extern "C" fn rust_sha256_new() -> *mut c_void {
Box::into_raw(Box::new(Sha256::new())) as *mut _
}
@@ -29,32 +29,32 @@ pub extern "C" fn rust_sha256_new() -> *mut c_void {
/// valid buffer for `len` bytes.
// NOTE: we specifically do not use util::Bytes, as it disallows NULL. Our data can be 0 though, as
// the booloader starts at 0 and is hashed.
-#[no_mangle]
+#[unsafe(no_mangle)]
pub unsafe extern "C" fn rust_sha256_update(ctx: *mut c_void, data: *const c_void, len: usize) {
- let data = core::slice::from_raw_parts(data as *const u8, len);
+ let data = unsafe { core::slice::from_raw_parts(data as *const u8, len) };
#[allow(clippy::cast_ptr_alignment)] // ctx is properly aligned, see `Box::into_raw`.
let ctx = ctx as *mut Sha256;
- (*ctx).update(data);
+ unsafe { (*ctx).update(data) };
}
/// Safety: ctx must be a pointer to a valid sha256 context produced by `rust_sha256_new()`.
/// `out` must be 32 bytes long.
/// After this, the hasher is dropped and `ctx` is set to NULL and must not be used anymore.
-#[no_mangle]
+#[unsafe(no_mangle)]
pub unsafe extern "C" fn rust_sha256_finish(ctx: *mut *mut c_void, out: *mut c_uchar) {
- let out = core::slice::from_raw_parts_mut(out, 32);
+ let out = unsafe { core::slice::from_raw_parts_mut(out, 32) };
#[allow(clippy::cast_ptr_alignment)] // ctx is properly aligned, see `Box::into_raw`.
- let hasher = Box::from_raw(*ctx as *mut Sha256); // dropped at the end
+ let hasher = unsafe { Box::from_raw(*ctx as *mut Sha256) }; // dropped at the end
let hash = hasher.finalize();
out.copy_from_slice(&hash[..]);
- *ctx = core::ptr::null_mut();
+ unsafe { *ctx = core::ptr::null_mut() };
}
/// Safety: data must be a valid buffer for `len` bytes. `out` must be 32 bytes long.
-#[no_mangle]
+#[unsafe(no_mangle)]
pub unsafe extern "C" fn rust_sha256(data: *const c_void, len: usize, out: *mut c_uchar) {
- let out = core::slice::from_raw_parts_mut(out, 32);
- let data = core::slice::from_raw_parts(data as *const u8, len);
+ let out = unsafe { core::slice::from_raw_parts_mut(out, 32) };
+ let data = unsafe { core::slice::from_raw_parts(data as *const u8, len) };
let hash = Sha256::digest(data);
out.copy_from_slice(&hash[..]);
}
@@ -62,7 +62,7 @@ pub unsafe extern "C" fn rust_sha256(data: *const c_void, len: usize, out: *mut
/// Safety: `key` and `data` must be a valid buffers of the corresponding sizes. `out` must be 32
/// bytes long.
#[cfg(feature = "firmware")]
-#[no_mangle]
+#[unsafe(no_mangle)]
pub unsafe extern "C" fn rust_hmac_sha256(
key: *const c_void,
key_len: usize,
@@ -70,11 +70,11 @@ pub unsafe extern "C" fn rust_hmac_sha256(
data_len: usize,
out: *mut c_uchar,
) {
- let out = core::slice::from_raw_parts_mut(out, 32);
- let key = core::slice::from_raw_parts(key as *const u8, key_len);
- let data = core::slice::from_raw_parts(data as *const u8, data_len);
+ let out = unsafe { core::slice::from_raw_parts_mut(out, 32) };
+ let key = unsafe { core::slice::from_raw_parts(key as *const u8, key_len) };
+ let data = unsafe { core::slice::from_raw_parts(data as *const u8, data_len) };
- use bitcoin::hashes::{sha256, Hash, HashEngine, Hmac, HmacEngine};
+ use bitcoin::hashes::{Hash, HashEngine, Hmac, HmacEngine, sha256};
let mut engine = HmacEngine::<sha256::Hash>::new(key);
engine.input(data);
let hmac_result: Hmac<sha256::Hash> = Hmac::from_engine(engine);
@@ -84,7 +84,7 @@ pub unsafe extern "C" fn rust_hmac_sha256(
/// Safety: `key` and `data` must be a valid buffers of the corresponding sizes. `out` must be 64
/// bytes long.
#[cfg(feature = "firmware")]
-#[no_mangle]
+#[unsafe(no_mangle)]
pub unsafe extern "C" fn rust_hmac_sha512(
key: *const c_void,
key_len: usize,
@@ -92,11 +92,11 @@ pub unsafe extern "C" fn rust_hmac_sha512(
data_len: usize,
out: *mut c_uchar,
) {
- let out = core::slice::from_raw_parts_mut(out, 64);
- let key = core::slice::from_raw_parts(key as *const u8, key_len);
- let data = core::slice::from_raw_parts(data as *const u8, data_len);
+ let out = unsafe { core::slice::from_raw_parts_mut(out, 64) };
+ let key = unsafe { core::slice::from_raw_parts(key as *const u8, key_len) };
+ let data = unsafe { core::slice::from_raw_parts(data as *const u8, data_len) };
- use bitcoin::hashes::{sha512, Hash, HashEngine, Hmac, HmacEngine};
+ use bitcoin::hashes::{Hash, HashEngine, Hmac, HmacEngine, sha512};
let mut engine = HmacEngine::<sha512::Hash>::new(key);
engine.input(data);
let hmac_result: Hmac<sha512::Hash> = Hmac::from_engine(engine);
diff --git a/src/rust/bitbox02-rust-c/src/u2f.rs b/src/rust/bitbox02-rust-c/src/u2f.rs
index bd82dab..6a50dcf 100644
--- a/src/rust/bitbox02-rust-c/src/u2f.rs
+++ b/src/rust/bitbox02-rust-c/src/u2f.rs
@@ -128,7 +128,7 @@ fn app_string(app_id: &[u8; 32]) -> String {
}
// app_id must be of length 32, and out must be a least 60 bytes.
-#[no_mangle]
+#[unsafe(no_mangle)]
pub extern "C" fn rust_u2f_app_string(app_id: crate::util::Bytes, mut out: crate::util::BytesMut) {
let app_str = app_string(app_id.as_ref().try_into().unwrap());
let bytes = app_str.as_bytes();
diff --git a/src/rust/bitbox02-rust-c/src/util.rs b/src/rust/bitbox02-rust-c/src/util.rs
index 5b3b3cc..1705012 100644
--- a/src/rust/bitbox02-rust-c/src/util.rs
+++ b/src/rust/bitbox02-rust-c/src/util.rs
@@ -17,7 +17,7 @@ use core::ffi::c_uchar;
/// Zero a buffer using volatile writes. Accepts null-ptr and 0-length buffers and does nothing.
///
/// * `dst` - Buffer to zero
-#[no_mangle]
+#[unsafe(no_mangle)]
pub extern "C" fn rust_util_zero(mut dst: BytesMut) {
if dst.buf.is_null() || dst.len == 0 {
return;
@@ -28,12 +28,12 @@ pub extern "C" fn rust_util_zero(mut dst: BytesMut) {
/// Calls `util::name::validate()` on the provided C string.
/// SAFETY:
/// `buf` must point to a valid buffer of size `max_len`.
-#[no_mangle]
+#[unsafe(no_mangle)]
pub unsafe extern "C" fn rust_util_is_name_valid(buf: *const u8, max_len: usize) -> bool {
if max_len == 0 {
return false;
}
- let slice = core::slice::from_raw_parts(buf, max_len);
+ let slice = unsafe { core::slice::from_raw_parts(buf, max_len) };
match core::ffi::CStr::from_bytes_until_nul(slice) {
Ok(cstr) => match cstr.to_str() {
Ok(s) => util::name::validate(s, max_len - 1),
@@ -47,7 +47,7 @@ pub unsafe extern "C" fn rust_util_is_name_valid(buf: *const u8, max_len: usize)
///
/// * `buf` - bytes to convert to hex.
/// * `out` - hex will be written here. out len must be at least 2*buf.len+1.
-#[no_mangle]
+#[unsafe(no_mangle)]
pub extern "C" fn rust_util_uint8_to_hex(buf: Bytes, mut out: BytesMut) {
let bytes = buf.as_ref();
let hexlen = bytes.len() * 2;
@@ -121,7 +121,7 @@ impl AsMut<[u8]> for BytesMut {
/// * `len` - Length of buffer, `buf[len-1]` must be a valid dereference
///
/// SAFTEY: buf must not be NULL and point to a valid memory area of size `len`.
-#[no_mangle]
+#[unsafe(no_mangle)]
pub unsafe extern "C" fn rust_util_bytes(buf: *const c_uchar, len: usize) -> Bytes {
Bytes { buf, len }
}
@@ -132,14 +132,14 @@ pub unsafe extern "C" fn rust_util_bytes(buf: *const c_uchar, len: usize) -> Byt
/// * `len` - Length of buffer, `buf[len-1]` must be a valid dereference
///
/// SAFTEY: buf must not be NULL and point to a valid memory area of size `len`.
-#[no_mangle]
+#[unsafe(no_mangle)]
pub unsafe extern "C" fn rust_util_bytes_mut(buf: *mut c_uchar, len: usize) -> BytesMut {
BytesMut { buf, len }
}
/// Base58Check-encode the input.
#[cfg(feature = "c-unit-testing")]
-#[no_mangle]
+#[unsafe(no_mangle)]
pub extern "C" fn rust_base58_encode_check(buf: Bytes, mut out: BytesMut) -> bool {
if buf.len == 0 {
return false;
diff --git a/src/rust/bitbox02-rust-c/src/workflow.rs b/src/rust/bitbox02-rust-c/src/workflow.rs
index fcf7887..ea5df50 100644
--- a/src/rust/bitbox02-rust-c/src/workflow.rs
+++ b/src/rust/bitbox02-rust-c/src/workflow.rs
@@ -24,7 +24,7 @@ extern crate alloc;
use alloc::boxed::Box;
use alloc::string::String;
-use bitbox02_rust::bb02_async::{spin, Task};
+use bitbox02_rust::bb02_async::{Task, spin};
use bitbox02_rust::workflow::confirm;
use core::task::Poll;
@@ -42,90 +42,102 @@ static mut CONFIRM_PARAMS: Option<confirm::Params> = None;
static mut CONFIRM_STATE: TaskState<'static, Result<(), confirm::UserAbort>> = TaskState::Nothing;
static mut BITBOX02_HAL: bitbox02_rust::hal::BitBox02Hal = bitbox02_rust::hal::BitBox02Hal::new();
-#[no_mangle]
+#[unsafe(no_mangle)]
pub unsafe extern "C" fn rust_workflow_spawn_unlock() {
- UNLOCK_STATE = TaskState::Running(Box::pin(bitbox02_rust::workflow::unlock::unlock(
- &mut BITBOX02_HAL,
- )));
+ unsafe {
+ UNLOCK_STATE = TaskState::Running(Box::pin(bitbox02_rust::workflow::unlock::unlock(
+ &mut BITBOX02_HAL,
+ )));
+ }
}
-#[no_mangle]
+#[unsafe(no_mangle)]
pub unsafe extern "C" fn rust_workflow_spawn_confirm(
title: *const core::ffi::c_char,
body: *const core::ffi::c_char,
) {
- CONFIRM_TITLE = Some(core::ffi::CStr::from_ptr(title).to_str().unwrap().into());
- CONFIRM_BODY = Some(core::ffi::CStr::from_ptr(body).to_str().unwrap().into());
- CONFIRM_PARAMS = Some(confirm::Params {
- title: CONFIRM_TITLE.as_ref().unwrap(),
- body: CONFIRM_BODY.as_ref().unwrap(),
- ..Default::default()
- });
+ unsafe {
+ CONFIRM_TITLE = Some(core::ffi::CStr::from_ptr(title).to_str().unwrap().into());
+ CONFIRM_BODY = Some(core::ffi::CStr::from_ptr(body).to_str().unwrap().into());
+ CONFIRM_PARAMS = Some(confirm::Params {
+ title: CONFIRM_TITLE.as_ref().unwrap(),
+ body: CONFIRM_BODY.as_ref().unwrap(),
+ ..Default::default()
+ });
- CONFIRM_STATE =
- TaskState::Running(Box::pin(confirm::confirm(CONFIRM_PARAMS.as_ref().unwrap())));
+ CONFIRM_STATE =
+ TaskState::Running(Box::pin(confirm::confirm(CONFIRM_PARAMS.as_ref().unwrap())));
+ }
}
-#[no_mangle]
+#[unsafe(no_mangle)]
pub unsafe extern "C" fn rust_workflow_spin() {
- match UNLOCK_STATE {
- TaskState::Running(ref mut task) => {
- let result = spin(task);
- if let Poll::Ready(result) = result {
- UNLOCK_STATE = TaskState::ResultAvailable(result);
+ unsafe {
+ match UNLOCK_STATE {
+ TaskState::Running(ref mut task) => {
+ let result = spin(task);
+ if let Poll::Ready(result) = result {
+ UNLOCK_STATE = TaskState::ResultAvailable(result);
+ }
}
+ _ => (),
}
- _ => (),
- }
- match CONFIRM_STATE {
- TaskState::Running(ref mut task) => {
- let result = spin(task);
- if let Poll::Ready(result) = result {
- CONFIRM_STATE = TaskState::ResultAvailable(result);
+ match CONFIRM_STATE {
+ TaskState::Running(ref mut task) => {
+ let result = spin(task);
+ if let Poll::Ready(result) = result {
+ CONFIRM_STATE = TaskState::ResultAvailable(result);
+ }
}
+ _ => (),
}
- _ => (),
}
}
/// Returns true if there was a result.
-#[no_mangle]
+#[unsafe(no_mangle)]
pub unsafe extern "C" fn rust_workflow_unlock_poll(result_out: &mut bool) -> bool {
- match UNLOCK_STATE {
- TaskState::ResultAvailable(result) => {
- UNLOCK_STATE = TaskState::Nothing;
- match result {
- Ok(()) => *result_out = true,
- Err(()) => *result_out = false,
+ unsafe {
+ match UNLOCK_STATE {
+ TaskState::ResultAvailable(result) => {
+ UNLOCK_STATE = TaskState::Nothing;
+ match result {
+ Ok(()) => *result_out = true,
+ Err(()) => *result_out = false,
+ }
+ true
}
- true
+ _ => false,
}
- _ => false,
}
}
/// Returns true if there was a result.
-#[no_mangle]
+#[unsafe(no_mangle)]
pub unsafe extern "C" fn rust_workflow_confirm_poll(result_out: &mut bool) -> bool {
- match CONFIRM_STATE {
- TaskState::ResultAvailable(ref result) => {
- CONFIRM_TITLE = None;
- CONFIRM_BODY = None;
- CONFIRM_PARAMS = None;
- CONFIRM_STATE = TaskState::Nothing;
- *result_out = result.is_ok();
- true
+ unsafe {
+ match CONFIRM_STATE {
+ TaskState::ResultAvailable(ref result) => {
+ CONFIRM_TITLE = None;
+ CONFIRM_BODY = None;
+ CONFIRM_PARAMS = None;
+ CONFIRM_STATE = TaskState::Nothing;
+ *result_out = result.is_ok();
+ true
+ }
+ _ => false,
}
- _ => false,
}
}
-#[no_mangle]
+#[unsafe(no_mangle)]
pub unsafe extern "C" fn rust_workflow_abort_current() {
- UNLOCK_STATE = TaskState::Nothing;
+ unsafe {
+ UNLOCK_STATE = TaskState::Nothing;
- CONFIRM_TITLE = None;
- CONFIRM_BODY = None;
- CONFIRM_PARAMS = None;
- CONFIRM_STATE = TaskState::Nothing;
+ CONFIRM_TITLE = None;
+ CONFIRM_BODY = None;
+ CONFIRM_PARAMS = None;
+ CONFIRM_STATE = TaskState::Nothing;
+ }
}
diff --git a/src/rust/bitbox02-rust/Cargo.toml b/src/rust/bitbox02-rust/Cargo.toml
index 1cca60d..19c9ac5 100644
--- a/src/rust/bitbox02-rust/Cargo.toml
+++ b/src/rust/bitbox02-rust/Cargo.toml
@@ -17,7 +17,7 @@
name = "bitbox02-rust"
version = "0.1.0"
authors = ["Shift Crypto AG <support@bitbox.swiss>"]
-edition = "2021"
+edition = "2024"
description = "BitBox02 functionality implemented in rust"
license = "Apache-2.0"
diff --git a/src/rust/bitbox02-rust/src/async_usb.rs b/src/rust/bitbox02-rust/src/async_usb.rs
index 31ac772..e21c62d 100644
--- a/src/rust/bitbox02-rust/src/async_usb.rs
+++ b/src/rust/bitbox02-rust/src/async_usb.rs
@@ -15,7 +15,7 @@
//! This module provides the executor for tasks that are spawned with an API request and deliver a
//! USB response. Terminology: host = computer, device = BitBox02.
-use crate::bb02_async::{option, spin as spin_task, Task};
+use crate::bb02_async::{Task, option, spin as spin_task};
use alloc::boxed::Box;
use alloc::vec::Vec;
use core::cell::RefCell;
@@ -196,7 +196,7 @@ pub fn copy_response(dst: &mut [u8]) -> Result<usize, CopyResponseErr> {
match *state {
UsbTaskState::Nothing => Err(CopyResponseErr::NotRunning),
UsbTaskState::Running(Some(_), ref mut next_request_state) => {
- if let WaitingForNextRequestState::SendingResponse(ref response) = next_request_state {
+ if let WaitingForNextRequestState::SendingResponse(response) = next_request_state {
let len = response.len();
dst[..len].copy_from_slice(response);
*next_request_state = WaitingForNextRequestState::AwaitingRequest;
diff --git a/src/rust/bitbox02-rust/src/backup.rs b/src/rust/bitbox02-rust/src/backup.rs
index e232247..5c366f8 100644
--- a/src/rust/bitbox02-rust/src/backup.rs
+++ b/src/rust/bitbox02-rust/src/backup.rs
@@ -382,13 +382,21 @@ mod tests {
assert_eq!(bitwise_recovery(&[], &[], &[]).unwrap().as_slice(), &[]);
assert_eq!(
bitwise_recovery(
- &[0b10101010, 0b00001111, 0b00001111, 0b10101010, 0b11111111, 0b11110000],
- &[0b10101010, 0b11110000, 0b10101010, 0b00001111, 0b11110101, 0b11110101],
- &[0b10101010, 0b10101010, 0b11110000, 0b11110000, 0b11111111, 0b11110000],
+ &[
+ 0b10101010, 0b00001111, 0b00001111, 0b10101010, 0b11111111, 0b11110000
+ ],
+ &[
+ 0b10101010, 0b11110000, 0b10101010, 0b00001111, 0b11110101, 0b11110101
+ ],
+ &[
+ 0b10101010, 0b10101010, 0b11110000, 0b11110000, 0b11111111, 0b11110000
+ ],
)
.unwrap()
.as_slice(),
- &[0b10101010, 0b10101010, 0b10101010, 0b10101010, 0b11111111, 0b11110000]
+ &[
+ 0b10101010, 0b10101010, 0b10101010, 0b10101010, 0b11111111, 0b11110000
+ ]
);
}
}
diff --git a/src/rust/bitbox02-rust/src/hww.rs b/src/rust/bitbox02-rust/src/hww.rs
index 8091e09..d86a7db 100644
--- a/src/rust/bitbox02-rust/src/hww.rs
+++ b/src/rust/bitbox02-rust/src/hww.rs
@@ -641,9 +641,11 @@ mod tests {
crate::pb::ListBackupsResponse { info },
)),
} => match info.as_slice() {
- &[crate::pb::BackupInfo {
- ref id, ref name, ..
- }] => {
+ &[
+ crate::pb::BackupInfo {
+ ref id, ref name, ..
+ },
+ ] => {
assert_eq!(name.as_str(), "test device name");
id.clone()
}
diff --git a/src/rust/bitbox02-rust/src/hww/api.rs b/src/rust/bitbox02-rust/src/hww/api.rs
index f8def6b..d5f159d 100644
--- a/src/rust/bitbox02-rust/src/hww/api.rs
+++ b/src/rust/bitbox02-rust/src/hww/api.rs
@@ -42,7 +42,7 @@ mod system;
use alloc::vec::Vec;
-use error::{make_error, Error};
+use error::{Error, make_error};
use pb::request::Request;
use pb::response::Response;
use prost::Message;
@@ -73,8 +73,8 @@ async fn process_api_btc(
request: &Request,
) -> Result<Response, Error> {
match request {
- Request::BtcPub(ref request) => bitcoin::process_pub(hal, request).await,
- Request::BtcSignInit(ref request) => bitcoin::signtx::process(hal, request).await,
+ Request::BtcPub(request) => bitcoin::process_pub(hal, request).await,
+ Request::BtcSignInit(request) => bitcoin::signtx::process(hal, request).await,
Request::Btc(pb::BtcRequest {
request: Some(request),
}) => bitcoin::process_api(hal, request)
@@ -163,29 +163,29 @@ fn can_call(request: &Request) -> bool {
/// Handle a protobuf api call.
async fn process_api(hal: &mut impl crate::hal::Hal, request: &Request) -> Result<Response, Error> {
match request {
- Request::Reboot(ref request) => system::reboot_to_bootloader(hal, request).await,
+ Request::Reboot(request) => system::reboot_to_bootloader(hal, request).await,
Request::DeviceInfo(_) => device_info::process(),
- Request::DeviceName(ref request) => set_device_name::process(hal, request).await,
- Request::SetPassword(ref request) => set_password::process(hal, request).await,
+ Request::DeviceName(request) => set_device_name::process(hal, request).await,
+ Request::SetPassword(request) => set_password::process(hal, request).await,
Request::Reset(_) => reset::process(hal).await,
- Request::SetMnemonicPassphraseEnabled(ref request) => {
+ Request::SetMnemonicPassphraseEnabled(request) => {
set_mnemonic_passphrase_enabled::process(hal, request).await
}
- Request::InsertRemoveSdcard(ref request) => sdcard::process(hal, request).await,
+ Request::InsertRemoveSdcard(request) => sdcard::process(hal, request).await,
Request::ListBackups(_) => backup::list(hal),
Request::CheckSdcard(_) => Ok(Response::CheckSdcard(pb::CheckSdCardResponse {
inserted: hal.sd().sdcard_inserted(),
})),
- Request::CheckBackup(ref request) => backup::check(hal, request).await,
- Request::CreateBackup(ref request) => backup::create(hal, request).await,
- Request::RestoreBackup(ref request) => restore::from_file(hal, request).await,
+ Request::CheckBackup(request) => backup::check(hal, request).await,
+ Request::CreateBackup(request) => backup::create(hal, request).await,
+ Request::RestoreBackup(request) => restore::from_file(hal, request).await,
Request::ShowMnemonic(_) => show_mnemonic::process(hal).await,
- Request::RestoreFromMnemonic(ref request) => restore::from_mnemonic(hal, request).await,
- Request::ElectrumEncryptionKey(ref request) => electrum::process(request).await,
+ Request::RestoreFromMnemonic(request) => restore::from_mnemonic(hal, request).await,
+ Request::ElectrumEncryptionKey(request) => electrum::process(request).await,
#[cfg(feature = "app-ethereum")]
Request::Eth(pb::EthRequest {
- request: Some(ref request),
+ request: Some(request),
}) => ethereum::process_api(hal, request)
.await
.map(|r| Response::Eth(pb::EthResponse { response: Some(r) })),
@@ -199,15 +199,15 @@ async fn process_api(hal: &mut impl crate::hal::Hal, request: &Request) -> Resul
#[cfg(feature = "app-cardano")]
Request::Cardano(pb::CardanoRequest {
- request: Some(ref request),
+ request: Some(request),
}) => cardano::process_api(hal, request)
.await
.map(|r| Response::Cardano(pb::CardanoResponse { response: Some(r) })),
#[cfg(not(feature = "app-cardano"))]
Request::Cardano(_) => Err(Error::Disabled),
- Request::Bip85(ref request) => bip85::process(hal, request).await,
+ Request::Bip85(request) => bip85::process(hal, request).await,
Request::Bluetooth(pb::BluetoothRequest {
- request: Some(ref request),
+ request: Some(request),
}) => bluetooth::process_api(hal, request)
.await
.map(|r| Response::Bluetooth(pb::BluetoothResponse { response: Some(r) })),
diff --git a/src/rust/bitbox02-rust/src/hww/api/backup.rs b/src/rust/bitbox02-rust/src/hww/api/backup.rs
index b8d0290..b06f498 100644
--- a/src/rust/bitbox02-rust/src/hww/api/backup.rs
+++ b/src/rust/bitbox02-rust/src/hww/api/backup.rs
@@ -295,17 +295,22 @@ mod tests {
// Create one backup.
mock_memory();
- mock_unlocked_using_mnemonic("purity concert above invest pigeon category peace tuition hazard vivid latin since legal speak nation session onion library travel spell region blast estate stay", "");
+ mock_unlocked_using_mnemonic(
+ "purity concert above invest pigeon category peace tuition hazard vivid latin since legal speak nation session onion library travel spell region blast estate stay",
+ "",
+ );
bitbox02::memory::set_device_name(DEVICE_NAME_1).unwrap();
- assert!(block_on(create(
- &mut mock_hal,
- &pb::CreateBackupRequest {
- timestamp: EXPECTED_TIMESTAMP,
- timezone_offset: 18000,
- }
- ))
- .is_ok());
+ assert!(
+ block_on(create(
+ &mut mock_hal,
+ &pb::CreateBackupRequest {
+ timestamp: EXPECTED_TIMESTAMP,
+ timezone_offset: 18000,
+ }
+ ))
+ .is_ok()
+ );
assert_eq!(
list(&mut mock_hal,),
@@ -320,16 +325,21 @@ mod tests {
// Create another backup.
mock_memory();
- mock_unlocked_using_mnemonic("goddess item rack improve shaft occur actress rib emerge salad rich blame model glare lounge stable electric height scrub scrub oyster now dinner oven", "");
+ mock_unlocked_using_mnemonic(
+ "goddess item rack improve shaft occur actress rib emerge salad rich blame model glare lounge stable electric height scrub scrub oyster now dinner oven",
+ "",
+ );
bitbox02::memory::set_device_name(DEVICE_NAME_2).unwrap();
- assert!(block_on(create(
- &mut mock_hal,
- &pb::CreateBackupRequest {
- timestamp: EXPECTED_TIMESTAMP,
- timezone_offset: 18000,
- }
- ))
- .is_ok());
+ assert!(
+ block_on(create(
+ &mut mock_hal,
+ &pb::CreateBackupRequest {
+ timestamp: EXPECTED_TIMESTAMP,
+ timezone_offset: 18000,
+ }
+ ))
+ .is_ok()
+ );
assert_eq!(
list(&mut mock_hal),
diff --git a/src/rust/bitbox02-rust/src/hww/api/bip85.rs b/src/rust/bitbox02-rust/src/hww/api/bip85.rs
index e8760ea..4cee89a 100644
--- a/src/rust/bitbox02-rust/src/hww/api/bip85.rs
+++ b/src/rust/bitbox02-rust/src/hww/api/bip85.rs
@@ -12,8 +12,8 @@
// See the License for the specific language governing permissions and
// limitations under the License.
-use super::pb;
use super::Error;
+use super::pb;
use pb::response::Response;
diff --git a/src/rust/bitbox02-rust/src/hww/api/bitcoin.rs b/src/rust/bitbox02-rust/src/hww/api/bitcoin.rs
index 7ff1b53..29c16c8 100644
--- a/src/rust/bitbox02-rust/src/hww/api/bitcoin.rs
+++ b/src/rust/bitbox02-rust/src/hww/api/bitcoin.rs
@@ -29,8 +29,8 @@ mod script_configs;
pub mod signmsg;
pub mod signtx;
-use super::pb;
use super::Error;
+use super::pb;
use crate::hal::Ui;
use crate::workflow::confirm;
@@ -39,13 +39,13 @@ use util::bip32::HARDENED;
use crate::keystore;
+use pb::BtcCoin;
+use pb::BtcScriptConfig;
use pb::btc_pub_request::{Output, XPubType};
use pb::btc_request::Request;
use pb::btc_script_config::{Config, SimpleType};
use pb::btc_script_config::{Multisig, Policy};
use pb::response::Response;
-use pb::BtcCoin;
-use pb::BtcScriptConfig;
use alloc::string::String;
@@ -308,13 +308,13 @@ pub async fn process_api(
request: &Request,
) -> Result<pb::btc_response::Response, Error> {
match request {
- Request::IsScriptConfigRegistered(ref request) => {
+ Request::IsScriptConfigRegistered(request) => {
registration::process_is_script_config_registered(request)
}
- Request::RegisterScriptConfig(ref request) => {
+ Request::RegisterScriptConfig(request) => {
registration::process_register_script_config(hal, request).await
}
- Request::SignMessage(ref request) => signmsg::process(hal, request).await,
+ Request::SignMessage(request) => signmsg::process(hal, request).await,
// These are streamed asynchronously using the `next_request()` primitive in
// bitcoin/signtx.rs and are not handled directly.
Request::PrevtxInit(_)
@@ -336,7 +336,7 @@ mod tests {
use alloc::boxed::Box;
use alloc::vec::Vec;
use bitbox02::testing::{
- mock_memory, mock_unlocked, mock_unlocked_using_mnemonic, TEST_MNEMONIC,
+ TEST_MNEMONIC, mock_memory, mock_unlocked, mock_unlocked_using_mnemonic,
};
use pb::btc_script_config::multisig::ScriptType as MultisigScriptType;
use util::bip32::HARDENED;
@@ -499,20 +499,19 @@ mod tests {
let mut mock_hal = TestingHal::new();
assert_eq!(
- block_on(process_pub(&mut mock_hal ,&req)),
+ block_on(process_pub(&mut mock_hal, &req)),
Ok(Response::Pub(pb::PubResponse {
r#pub: test.expected_xpub.into(),
})),
);
assert_eq!(
mock_hal.ui.screens,
- vec![
- Screen::Confirm {
- title: test.expected_display_title.into(),
- body: test.expected_xpub.into(),
- longtouch: false,
- },
- ]);
+ vec![Screen::Confirm {
+ title: test.expected_display_title.into(),
+ body: test.expected_xpub.into(),
+ longtouch: false,
+ },]
+ );
}
{
@@ -806,13 +805,12 @@ mod tests {
);
assert_eq!(
mock_hal.ui.screens,
- vec![
- Screen::Confirm {
- title: test.expected_display_title.into(),
- body: test.expected_address.into(),
- longtouch: false,
- },
- ]);
+ vec![Screen::Confirm {
+ title: test.expected_display_title.into(),
+ body: test.expected_address.into(),
+ longtouch: false,
+ },]
+ );
}
// --- Negative tests
@@ -840,18 +838,20 @@ mod tests {
req_invalid.keypath = [49 + HARDENED, 0 + HARDENED, 1 + HARDENED, 1, 10000].to_vec();
assert!(block_on(process_pub(&mut TestingHal::new(), &req_invalid)).is_err());
// -- No taproot in Litecoin
- assert!(block_on(process_pub(
- &mut TestingHal::new(),
- &pb::BtcPubRequest {
- coin: BtcCoin::Ltc as _,
- keypath: [86 + HARDENED, 0 + HARDENED, 0 + HARDENED, 0, 0].to_vec(),
- display: false,
- output: Some(Output::ScriptConfig(BtcScriptConfig {
- config: Some(Config::SimpleType(SimpleType::P2tr as _)),
- })),
- }
- ))
- .is_err());
+ assert!(
+ block_on(process_pub(
+ &mut TestingHal::new(),
+ &pb::BtcPubRequest {
+ coin: BtcCoin::Ltc as _,
+ keypath: [86 + HARDENED, 0 + HARDENED, 0 + HARDENED, 0, 0].to_vec(),
+ display: false,
+ output: Some(Output::ScriptConfig(BtcScriptConfig {
+ config: Some(Config::SimpleType(SimpleType::P2tr as _)),
+ })),
+ }
+ ))
+ .is_err()
+ );
}
#[test]
@@ -952,11 +952,7 @@ mod tests {
],
expected_info: "1-of-2\nBitcoin multisig",
our_xpub_index: 1,
- keypath: &[
- 45 + HARDENED,
- 1,
- 2
- ],
+ keypath: &[45 + HARDENED, 1, 2],
script_type: MultisigScriptType::P2wsh,
expected_address: "bc1qtsvlhzltl05etjjeqh00urwttu6ep4xn3c0ccndz77unttut9h0qvrcs04",
},
@@ -991,13 +987,7 @@ mod tests {
],
expected_info: "2-of-2\nBitcoin multisig",
our_xpub_index: 1,
- keypath: &[
- 48 + HARDENED,
- 0 + HARDENED,
- 0 + HARDENED,
- 1,
- 0,
- ],
+ keypath: &[48 + HARDENED, 0 + HARDENED, 0 + HARDENED, 1, 0],
script_type: MultisigScriptType::P2wshP2sh,
expected_address: "341hw7cuzpf2AtSuXupX5Pu3tkkXv24bvo",
},
diff --git a/src/rust/bitbox02-rust/src/hww/api/bitcoin/common.rs b/src/rust/bitbox02-rust/src/hww/api/bitcoin/common.rs
index 8822041..4872407 100644
--- a/src/rust/bitbox02-rust/src/hww/api/bitcoin/common.rs
+++ b/src/rust/bitbox02-rust/src/hww/api/bitcoin/common.rs
@@ -12,8 +12,8 @@
// See the License for the specific language governing permissions and
// limitations under the License.
-use super::pb;
use super::Error;
+use super::pb;
use crate::xpubcache::Bip32XpubCache;
diff --git a/src/rust/bitbox02-rust/src/hww/api/bitcoin/keypath.rs b/src/rust/bitbox02-rust/src/hww/api/bitcoin/keypath.rs
index 48862b6..aecd949 100644
--- a/src/rust/bitbox02-rust/src/hww/api/bitcoin/keypath.rs
+++ b/src/rust/bitbox02-rust/src/hww/api/bitcoin/keypath.rs
@@ -13,8 +13,8 @@
// limitations under the License.
use crate::pb;
-pub use pb::btc_script_config::multisig::ScriptType as MultisigScriptType;
pub use pb::btc_script_config::SimpleType;
+pub use pb::btc_script_config::multisig::ScriptType as MultisigScriptType;
const ALL_MULTISCRIPT_SCRIPT_TYPES: [MultisigScriptType; 2] =
[MultisigScriptType::P2wsh, MultisigScriptType::P2wshP2sh];
@@ -196,20 +196,24 @@ mod tests {
}
assert!(validate_account(&[0, 0, 100 + HARDENED], 0, 0).is_err());
- assert!(validate_account(
- &[84 + HARDENED, 1 + HARDENED, 1 + HARDENED],
- 84 + HARDENED,
- 1 + HARDENED,
- )
- .is_ok());
+ assert!(
+ validate_account(
+ &[84 + HARDENED, 1 + HARDENED, 1 + HARDENED],
+ 84 + HARDENED,
+ 1 + HARDENED,
+ )
+ .is_ok()
+ );
// Too many elements.
- assert!(validate_account(
- &[84 + HARDENED, 1 + HARDENED, 1 + HARDENED, 1 + HARDENED],
- 84 + HARDENED,
- 1 + HARDENED,
- )
- .is_err());
+ assert!(
+ validate_account(
+ &[84 + HARDENED, 1 + HARDENED, 1 + HARDENED, 1 + HARDENED],
+ 84 + HARDENED,
+ 1 + HARDENED,
+ )
+ .is_err()
+ );
}
#[test]
@@ -217,50 +221,62 @@ mod tests {
let coin = 1 + HARDENED;
// Valid p2wsh-p2sh.
- assert!(validate_account_multisig(
- &[48 + HARDENED, coin, 0 + HARDENED, 1 + HARDENED],
- coin,
- MultisigScriptType::P2wshP2sh
- )
- .is_ok());
+ assert!(
+ validate_account_multisig(
+ &[48 + HARDENED, coin, 0 + HARDENED, 1 + HARDENED],
+ coin,
+ MultisigScriptType::P2wshP2sh
+ )
+ .is_ok()
+ );
// Valid p2wsh.
- assert!(validate_account_multisig(
- &[48 + HARDENED, coin, 0 + HARDENED, 2 + HARDENED],
- coin,
- MultisigScriptType::P2wsh
- )
- .is_ok());
+ assert!(
+ validate_account_multisig(
+ &[48 + HARDENED, coin, 0 + HARDENED, 2 + HARDENED],
+ coin,
+ MultisigScriptType::P2wsh
+ )
+ .is_ok()
+ );
// Valid Nunchuk-style.
- assert!(validate_account_multisig(
- &[48 + HARDENED, coin, 0 + HARDENED],
- coin,
- MultisigScriptType::P2wsh
- )
- .is_ok());
- assert!(validate_account_multisig(
- &[48 + HARDENED, coin, 0 + HARDENED],
- coin,
- MultisigScriptType::P2wshP2sh
- )
- .is_ok());
+ assert!(
+ validate_account_multisig(
+ &[48 + HARDENED, coin, 0 + HARDENED],
+ coin,
+ MultisigScriptType::P2wsh
+ )
+ .is_ok()
+ );
+ assert!(
+ validate_account_multisig(
+ &[48 + HARDENED, coin, 0 + HARDENED],
+ coin,
+ MultisigScriptType::P2wshP2sh
+ )
+ .is_ok()
+ );
// Valid script (last element).
- assert!(validate_account_multisig(
- &[48 + HARDENED, coin, 0 + HARDENED, 1 + HARDENED],
- coin,
- MultisigScriptType::P2wsh
- )
- .is_err());
+ assert!(
+ validate_account_multisig(
+ &[48 + HARDENED, coin, 0 + HARDENED, 1 + HARDENED],
+ coin,
+ MultisigScriptType::P2wsh
+ )
+ .is_err()
+ );
// Wrong purpose.
- assert!(validate_account_multisig(
- &[49 + HARDENED, coin, 0 + HARDENED, 2 + HARDENED],
- coin,
- MultisigScriptType::P2wsh
- )
- .is_err());
+ assert!(
+ validate_account_multisig(
+ &[49 + HARDENED, coin, 0 + HARDENED, 2 + HARDENED],
+ coin,
+ MultisigScriptType::P2wsh
+ )
+ .is_err()
+ );
}
#[test]
@@ -270,24 +286,28 @@ mod tests {
let taproot_support = true;
for mode in [ReceiveSpend::Receive, ReceiveSpend::Spend] {
// valid p2wpkh-p2sh; receive
- assert!(validate_address_simple(
- &[49 + HARDENED, bip44_coin, bip44_account, 0, 0],
- bip44_coin,
- SimpleType::P2wpkhP2sh,
- taproot_support,
- mode,
- )
- .is_ok());
+ assert!(
+ validate_address_simple(
+ &[49 + HARDENED, bip44_coin, bip44_account, 0, 0],
+ bip44_coin,
+ SimpleType::P2wpkhP2sh,
+ taproot_support,
+ mode,
+ )
+ .is_ok()
+ );
// valid p2wpkh-p2sh; receive on high address
- assert!(validate_address_simple(
- &[49 + HARDENED, bip44_coin, bip44_account, 0, 9999],
- bip44_coin,
- SimpleType::P2wpkhP2sh,
- taproot_support,
- mode,
- )
- .is_ok());
+ assert!(
+ validate_address_simple(
+ &[49 + HARDENED, bip44_coin, bip44_account, 0, 9999],
+ bip44_coin,
+ SimpleType::P2wpkhP2sh,
+ taproot_support,
+ mode,
+ )
+ .is_ok()
+ );
// invalid p2wpkh-p2sh; receive on too high address - only allowed when spending
assert_eq!(
@@ -303,130 +323,156 @@ mod tests {
);
// valid p2wpkh-p2sh; change
- assert!(validate_address_simple(
- &[49 + HARDENED, bip44_coin, bip44_account, 1, 0],
- bip44_coin,
- SimpleType::P2wpkhP2sh,
- taproot_support,
- mode,
- )
- .is_ok());
+ assert!(
+ validate_address_simple(
+ &[49 + HARDENED, bip44_coin, bip44_account, 1, 0],
+ bip44_coin,
+ SimpleType::P2wpkhP2sh,
+ taproot_support,
+ mode,
+ )
+ .is_ok()
+ );
// valid p2wpkh-p2sh; invalid bip44 change values
- assert!(validate_address_simple(
- &[49 + HARDENED, bip44_coin, bip44_account, 2, 0],
- bip44_coin,
- SimpleType::P2wpkhP2sh,
- taproot_support,
- mode,
- )
- .is_err());
- assert!(validate_address_simple(
- &[49 + HARDENED, bip44_coin, bip44_account, 0 + HARDENED, 0],
- bip44_coin,
- SimpleType::P2wpkhP2sh,
- taproot_support,
- mode,
- )
- .is_err());
- assert!(validate_address_simple(
- &[49 + HARDENED, bip44_coin, bip44_account, 1 + HARDENED, 0],
- bip44_coin,
- SimpleType::P2wpkhP2sh,
- taproot_support,
- mode,
- )
- .is_err());
+ assert!(
+ validate_address_simple(
+ &[49 + HARDENED, bip44_coin, bip44_account, 2, 0],
+ bip44_coin,
+ SimpleType::P2wpkhP2sh,
+ taproot_support,
+ mode,
+ )
+ .is_err()
+ );
+ assert!(
+ validate_address_simple(
+ &[49 + HARDENED, bip44_coin, bip44_account, 0 + HARDENED, 0],
+ bip44_coin,
+ SimpleType::P2wpkhP2sh,
+ taproot_support,
+ mode,
+ )
+ .is_err()
+ );
+ assert!(
+ validate_address_simple(
+ &[49 + HARDENED, bip44_coin, bip44_account, 1 + HARDENED, 0],
+ bip44_coin,
+ SimpleType::P2wpkhP2sh,
+ taproot_support,
+ mode,
+ )
+ .is_err()
+ );
// invalid p2wpkh-p2sh; wrong purpose
- assert!(validate_address_simple(
- &[84 + HARDENED, bip44_coin, bip44_account, 0, 0],
- bip44_coin,
- SimpleType::P2wpkhP2sh,
- taproot_support,
- mode,
- )
- .is_err());
+ assert!(
+ validate_address_simple(
+ &[84 + HARDENED, bip44_coin, bip44_account, 0, 0],
+ bip44_coin,
+ SimpleType::P2wpkhP2sh,
+ taproot_support,
+ mode,
+ )
+ .is_err()
+ );
// invalid p2wpkh-p2sh; account too high
- assert!(validate_address_simple(
- &[49 + HARDENED, bip44_coin, 100 + HARDENED, 0, 0],
- bip44_coin,
- SimpleType::P2wpkhP2sh,
- taproot_support,
- mode,
- )
- .is_err());
+ assert!(
+ validate_address_simple(
+ &[49 + HARDENED, bip44_coin, 100 + HARDENED, 0, 0],
+ bip44_coin,
+ SimpleType::P2wpkhP2sh,
+ taproot_support,
+ mode,
+ )
+ .is_err()
+ );
// invalid p2wpkh-p2sh; account too low
- assert!(validate_address_simple(
- &[49 + HARDENED, bip44_coin, HARDENED - 1, 0, 0],
- bip44_coin,
- SimpleType::P2wpkhP2sh,
- taproot_support,
- mode,
- )
- .is_err());
+ assert!(
+ validate_address_simple(
+ &[49 + HARDENED, bip44_coin, HARDENED - 1, 0, 0],
+ bip44_coin,
+ SimpleType::P2wpkhP2sh,
+ taproot_support,
+ mode,
+ )
+ .is_err()
+ );
// invalid p2wpkh-p2sh; expected coin mismatch
- assert!(validate_address_simple(
- &[49 + HARDENED, bip44_coin, bip44_account, 0, 0],
- bip44_coin + 1,
- SimpleType::P2wpkhP2sh,
- taproot_support,
- mode,
- )
- .is_err());
+ assert!(
+ validate_address_simple(
+ &[49 + HARDENED, bip44_coin, bip44_account, 0, 0],
+ bip44_coin + 1,
+ SimpleType::P2wpkhP2sh,
+ taproot_support,
+ mode,
+ )
+ .is_err()
+ );
// valid p2wpkh
- assert!(validate_address_simple(
- &[84 + HARDENED, bip44_coin, bip44_account, 0, 0],
- bip44_coin,
- SimpleType::P2wpkh,
- taproot_support,
- mode,
- )
- .is_ok());
+ assert!(
+ validate_address_simple(
+ &[84 + HARDENED, bip44_coin, bip44_account, 0, 0],
+ bip44_coin,
+ SimpleType::P2wpkh,
+ taproot_support,
+ mode,
+ )
+ .is_ok()
+ );
// invalid p2wpkh; wrong purpose
- assert!(validate_address_simple(
- &[49 + HARDENED, bip44_coin, bip44_account, 0, 0],
- bip44_coin,
- SimpleType::P2wpkh,
- taproot_support,
- mode,
- )
- .is_err());
+ assert!(
+ validate_address_simple(
+ &[49 + HARDENED, bip44_coin, bip44_account, 0, 0],
+ bip44_coin,
+ SimpleType::P2wpkh,
+ taproot_support,
+ mode,
+ )
+ .is_err()
+ );
// valid p2tr
- assert!(validate_address_simple(
- &[86 + HARDENED, bip44_coin, bip44_account, 0, 0],
- bip44_coin,
- SimpleType::P2tr,
- taproot_support,
- mode,
- )
- .is_ok());
+ assert!(
+ validate_address_simple(
+ &[86 + HARDENED, bip44_coin, bip44_account, 0, 0],
+ bip44_coin,
+ SimpleType::P2tr,
+ taproot_support,
+ mode,
+ )
+ .is_ok()
+ );
// invalid p2tr, taproot not supported
- assert!(validate_address_simple(
- &[86 + HARDENED, bip44_coin, bip44_account, 0, 0],
- bip44_coin,
- SimpleType::P2tr,
- false,
- mode,
- )
- .is_err());
+ assert!(
+ validate_address_simple(
+ &[86 + HARDENED, bip44_coin, bip44_account, 0, 0],
+ bip44_coin,
+ SimpleType::P2tr,
+ false,
+ mode,
+ )
+ .is_err()
+ );
// invalid p2tr; wrong purpose
- assert!(validate_address_simple(
- &[49 + HARDENED, bip44_coin, bip44_account, 0, 0],
- bip44_coin,
- SimpleType::P2tr,
- taproot_support,
- mode,
- )
- .is_err());
+ assert!(
+ validate_address_simple(
+ &[49 + HARDENED, bip44_coin, bip44_account, 0, 0],
+ bip44_coin,
+ SimpleType::P2tr,
+ taproot_support,
+ mode,
+ )
+ .is_err()
+ );
}
}
@@ -450,95 +496,121 @@ mod tests {
let bip44_coin = 1 + HARDENED;
let taproot_support = true;
// Valid singlesig xpubs.
- assert!(validate_xpub(
- &[49 + HARDENED, bip44_coin, 0 + HARDENED],
- bip44_coin,
- taproot_support
- )
- .is_ok());
- assert!(validate_xpub(
- &[84 + HARDENED, bip44_coin, 0 + HARDENED],
- bip44_coin,
- taproot_support
- )
- .is_ok());
- assert!(validate_xpub(
- &[86 + HARDENED, bip44_coin, 0 + HARDENED],
- bip44_coin,
- taproot_support
- )
- .is_ok());
+ assert!(
+ validate_xpub(
+ &[49 + HARDENED, bip44_coin, 0 + HARDENED],
+ bip44_coin,
+ taproot_support
+ )
+ .is_ok()
+ );
+ assert!(
+ validate_xpub(
+ &[84 + HARDENED, bip44_coin, 0 + HARDENED],
+ bip44_coin,
+ taproot_support
+ )
+ .is_ok()
+ );
+ assert!(
+ validate_xpub(
+ &[86 + HARDENED, bip44_coin, 0 + HARDENED],
+ bip44_coin,
+ taproot_support
+ )
+ .is_ok()
+ );
// Valid multisig xpubs.
- assert!(validate_xpub(
- &[48 + HARDENED, bip44_coin, 0 + HARDENED],
- bip44_coin,
- taproot_support
- )
- .is_ok());
- assert!(validate_xpub(
- &[48 + HARDENED, bip44_coin, 0 + HARDENED, 1 + HARDENED],
- bip44_coin,
- taproot_support
- )
- .is_ok());
- assert!(validate_xpub(
- &[48 + HARDENED, bip44_coin, 0 + HARDENED, 2 + HARDENED],
- bip44_coin,
- taproot_support
- )
- .is_ok());
+ assert!(
+ validate_xpub(
+ &[48 + HARDENED, bip44_coin, 0 + HARDENED],
+ bip44_coin,
+ taproot_support
+ )
+ .is_ok()
+ );
+ assert!(
+ validate_xpub(
+ &[48 + HARDENED, bip44_coin, 0 + HARDENED, 1 + HARDENED],
+ bip44_coin,
+ taproot_support
+ )
+ .is_ok()
+ );
+ assert!(
+ validate_xpub(
+ &[48 + HARDENED, bip44_coin, 0 + HARDENED, 2 + HARDENED],
+ bip44_coin,
+ taproot_support
+ )
+ .is_ok()
+ );
// No taproot.
- assert!(validate_xpub(
- &[86 + HARDENED, bip44_coin, 0 + HARDENED],
- bip44_coin,
- false,
- )
- .is_err());
+ assert!(
+ validate_xpub(
+ &[86 + HARDENED, bip44_coin, 0 + HARDENED],
+ bip44_coin,
+ false,
+ )
+ .is_err()
+ );
// Invalid multisig script type.
- assert!(validate_xpub(
- &[48 + HARDENED, bip44_coin, 0 + HARDENED, 3 + HARDENED],
- bip44_coin,
- taproot_support
- )
- .is_err());
+ assert!(
+ validate_xpub(
+ &[48 + HARDENED, bip44_coin, 0 + HARDENED, 3 + HARDENED],
+ bip44_coin,
+ taproot_support
+ )
+ .is_err()
+ );
// Coin mismatch.
- assert!(validate_xpub(
- &[48 + HARDENED, bip44_coin, 0 + HARDENED, 2 + HARDENED],
- bip44_coin + 1,
- taproot_support
- )
- .is_err());
+ assert!(
+ validate_xpub(
+ &[48 + HARDENED, bip44_coin, 0 + HARDENED, 2 + HARDENED],
+ bip44_coin + 1,
+ taproot_support
+ )
+ .is_err()
+ );
// Invalid account.
- assert!(validate_xpub(
- &[48 + HARDENED, bip44_coin, HARDENED - 1, 2 + HARDENED],
- bip44_coin,
- taproot_support
- )
- .is_err());
- assert!(validate_xpub(
- &[48 + HARDENED, bip44_coin, HARDENED + 100, 2 + HARDENED],
- bip44_coin,
- taproot_support
- )
- .is_err());
+ assert!(
+ validate_xpub(
+ &[48 + HARDENED, bip44_coin, HARDENED - 1, 2 + HARDENED],
+ bip44_coin,
+ taproot_support
+ )
+ .is_err()
+ );
+ assert!(
+ validate_xpub(
+ &[48 + HARDENED, bip44_coin, HARDENED + 100, 2 + HARDENED],
+ bip44_coin,
+ taproot_support
+ )
+ .is_err()
+ );
// Invalid purpose.
- assert!(validate_xpub(
- &[44 + HARDENED, bip44_coin, 0 + HARDENED, 2 + HARDENED],
- bip44_coin,
- taproot_support
- )
- .is_err());
- assert!(validate_xpub(
- &[100 + HARDENED, bip44_coin, 0 + HARDENED, 2 + HARDENED],
- bip44_coin,
- taproot_support
- )
- .is_err());
+ assert!(
+ validate_xpub(
+ &[44 + HARDENED, bip44_coin, 0 + HARDENED, 2 + HARDENED],
+ bip44_coin,
+ taproot_support
+ )
+ .is_err()
+ );
+ assert!(
+ validate_xpub(
+ &[100 + HARDENED, bip44_coin, 0 + HARDENED, 2 + HARDENED],
+ bip44_coin,
+ taproot_support
+ )
+ .is_err()
+ );
}
}
diff --git a/src/rust/bitbox02-rust/src/hww/api/bitcoin/multisig.rs b/src/rust/bitbox02-rust/src/hww/api/bitcoin/multisig.rs
index 898c259..499c1c1 100644
--- a/src/rust/bitbox02-rust/src/hww/api/bitcoin/multisig.rs
+++ b/src/rust/bitbox02-rust/src/hww/api/bitcoin/multisig.rs
@@ -12,13 +12,13 @@
// See the License for the specific language governing permissions and
// limitations under the License.
+use super::Error;
use super::params::Params;
use super::pb;
-use super::Error;
-use pb::btc_register_script_config_request::XPubType;
-use pb::btc_script_config::{multisig::ScriptType, Multisig};
use pb::BtcCoin;
+use pb::btc_register_script_config_request::XPubType;
+use pb::btc_script_config::{Multisig, multisig::ScriptType};
use crate::bip32;
@@ -825,21 +825,23 @@ mod tests {
];
for test in tests {
- assert!(pkscript(
- &Multisig {
- threshold: test.threshold,
- xpubs: test
- .xpubs
- .iter()
- .map(|xpub| parse_xpub(xpub).unwrap())
- .collect(),
- our_xpub_index: 0,
- script_type: ScriptType::P2wsh as _
- },
- 1,
- 2,
- )
- .is_err());
+ assert!(
+ pkscript(
+ &Multisig {
+ threshold: test.threshold,
+ xpubs: test
+ .xpubs
+ .iter()
+ .map(|xpub| parse_xpub(xpub).unwrap())
+ .collect(),
+ our_xpub_index: 0,
+ script_type: ScriptType::P2wsh as _
+ },
+ 1,
+ 2,
+ )
+ .is_err()
+ );
}
}
}
diff --git a/src/rust/bitbox02-rust/src/hww/api/bitcoin/payment_request.rs b/src/rust/bitbox02-rust/src/hww/api/bitcoin/payment_request.rs
index 4cfb193..50f369a 100644
--- a/src/rust/bitbox02-rust/src/hww/api/bitcoin/payment_request.rs
+++ b/src/rust/bitbox02-rust/src/hww/api/bitcoin/payment_request.rs
@@ -12,8 +12,8 @@
// See the License for the specific language governing permissions and
// limitations under the License.
-use super::pb;
use super::Error;
+use super::pb;
use alloc::vec::Vec;
@@ -21,7 +21,7 @@ use super::common::format_amount;
use super::params;
use super::script::serialize_varint;
-use pb::btc_payment_request_request::{memo, Memo};
+use pb::btc_payment_request_request::{Memo, memo};
use pb::btc_sign_init_request::FormatUnit;
use crate::hal::Ui;
diff --git a/src/rust/bitbox02-rust/src/hww/api/bitcoin/policies.rs b/src/rust/bitbox02-rust/src/hww/api/bitcoin/policies.rs
index a9ac61e..4acc39d 100644
--- a/src/rust/bitbox02-rust/src/hww/api/bitcoin/policies.rs
+++ b/src/rust/bitbox02-rust/src/hww/api/bitcoin/policies.rs
@@ -12,9 +12,9 @@
// See the License for the specific language governing permissions and
// limitations under the License.
+use super::Error;
use super::params::Params;
use super::pb;
-use super::Error;
use pb::BtcCoin;
use pb::btc_script_config::Policy;
@@ -947,18 +947,20 @@ mod tests {
assert!(parse(&make_policy("wsh(pk(@0/**))", &[our_key.clone()]), coin).is_ok());
// All good, all keys are used across internal key & leaf scripts.
- assert!(parse(
- &make_policy(
- "tr(@0/**,{pk(@1/**),pk(@2/**)})",
- &[
- our_key.clone(),
- make_key(SOME_XPUB_1),
- make_key(SOME_XPUB_2)
- ],
- ),
- coin
- )
- .is_ok());
+ assert!(
+ parse(
+ &make_policy(
+ "tr(@0/**,{pk(@1/**),pk(@2/**)})",
+ &[
+ our_key.clone(),
+ make_key(SOME_XPUB_1),
+ make_key(SOME_XPUB_2)
+ ],
+ ),
+ coin
+ )
+ .is_ok()
+ );
// Unsupported coins
for coin in [BtcCoin::Ltc, BtcCoin::Tltc] {
@@ -1214,78 +1216,88 @@ mod tests {
);
// Account keypath does not match.
- assert!(get_change_and_address_index(
- ["@0/<10;11>/*", "@1/<20;21>/*"].iter(),
- &[our_key.clone(), some_key.clone()],
- &[true, false],
- &[
- 48 + HARDENED,
- 1 + HARDENED,
- 0 + HARDENED,
- 0 + HARDENED,
- 11,
- 5,
- ],
- )
- .is_err());
+ assert!(
+ get_change_and_address_index(
+ ["@0/<10;11>/*", "@1/<20;21>/*"].iter(),
+ &[our_key.clone(), some_key.clone()],
+ &[true, false],
+ &[
+ 48 + HARDENED,
+ 1 + HARDENED,
+ 0 + HARDENED,
+ 0 + HARDENED,
+ 11,
+ 5,
+ ],
+ )
+ .is_err()
+ );
// Keypath change/receive element does not match.
- assert!(get_change_and_address_index(
- ["@0/<10;11>/*", "@1/<20;21>/*"].iter(),
- &[our_key.clone(), some_key.clone()],
- &[true, false],
- &[
- 48 + HARDENED,
- 1 + HARDENED,
- 0 + HARDENED,
- 3 + HARDENED,
- 20,
- 5,
- ],
- )
- .is_err());
+ assert!(
+ get_change_and_address_index(
+ ["@0/<10;11>/*", "@1/<20;21>/*"].iter(),
+ &[our_key.clone(), some_key.clone()],
+ &[true, false],
+ &[
+ 48 + HARDENED,
+ 1 + HARDENED,
+ 0 + HARDENED,
+ 3 + HARDENED,
+ 20,
+ 5,
+ ],
+ )
+ .is_err()
+ );
// Keypath too long
- assert!(get_change_and_address_index(
- ["@0/<10;11>/*", "@1/<20;21>/*"].iter(),
- &[our_key.clone(), some_key.clone()],
- &[true, false],
- &[
- 48 + HARDENED,
- 1 + HARDENED,
- 0 + HARDENED,
- 3 + HARDENED,
- 10,
- 5,
- 0,
- ],
- )
- .is_err());
+ assert!(
+ get_change_and_address_index(
+ ["@0/<10;11>/*", "@1/<20;21>/*"].iter(),
+ &[our_key.clone(), some_key.clone()],
+ &[true, false],
+ &[
+ 48 + HARDENED,
+ 1 + HARDENED,
+ 0 + HARDENED,
+ 3 + HARDENED,
+ 10,
+ 5,
+ 0,
+ ],
+ )
+ .is_err()
+ );
// Keypath too short
- assert!(get_change_and_address_index(
- ["@0/<10;11>/*", "@1/<20;21>/*"].iter(),
- &[our_key.clone(), some_key.clone()],
- &[true, false],
- &[48 + HARDENED, 1 + HARDENED, 0 + HARDENED, 3 + HARDENED, 10,],
- )
- .is_err());
+ assert!(
+ get_change_and_address_index(
+ ["@0/<10;11>/*", "@1/<20;21>/*"].iter(),
+ &[our_key.clone(), some_key.clone()],
+ &[true, false],
+ &[48 + HARDENED, 1 + HARDENED, 0 + HARDENED, 3 + HARDENED, 10,],
+ )
+ .is_err()
+ );
// Keypath is valid but uses a key in the policy that is not ours.
- assert!(get_change_and_address_index(
- ["@0/<10;11>/*", "@1/<20;21>/*"].iter(),
- &[
- our_key.clone(),
- pb::KeyOriginInfo {
- root_fingerprint: b"aaaa".to_vec(),
- keypath: vec![99 + HARDENED],
- xpub: Some(parse_xpub(SOME_XPUB_1).unwrap()),
- }
- ],
- &[true, false],
- &[99 + HARDENED, 20, 0],
- )
- .is_err());
+ assert!(
+ get_change_and_address_index(
+ ["@0/<10;11>/*", "@1/<20;21>/*"].iter(),
+ &[
+ our_key.clone(),
+ pb::KeyOriginInfo {
+ root_fingerprint: b"aaaa".to_vec(),
+ keypath: vec![99 + HARDENED],
+ xpub: Some(parse_xpub(SOME_XPUB_1).unwrap()),
+ }
+ ],
+ &[true, false],
+ &[99 + HARDENED, 20, 0],
+ )
+ .is_err()
+ );
}
#[test]
diff --git a/src/rust/bitbox02-rust/src/hww/api/bitcoin/registration.rs b/src/rust/bitbox02-rust/src/hww/api/bitcoin/registration.rs
index c70fea3..c7bd227 100644
--- a/src/rust/bitbox02-rust/src/hww/api/bitcoin/registration.rs
+++ b/src/rust/bitbox02-rust/src/hww/api/bitcoin/registration.rs
@@ -12,16 +12,16 @@
// See the License for the specific language governing permissions and
// limitations under the License.
+use super::Error;
use super::params;
use super::pb;
-use super::Error;
use alloc::string::String;
+use pb::BtcCoin;
use pb::btc_register_script_config_request::XPubType;
use pb::btc_response::Response;
use pb::btc_script_config::Config;
-use pb::BtcCoin;
use super::multisig::SortXpubs;
@@ -193,7 +193,7 @@ mod tests {
use bitbox02::testing::{mock_memory, mock_unlocked_using_mnemonic};
use util::bip32::HARDENED;
- use pb::btc_script_config::{multisig::ScriptType, Multisig};
+ use pb::btc_script_config::{Multisig, multisig::ScriptType};
#[test]
fn test_process_is_script_config_registered() {
diff --git a/src/rust/bitbox02-rust/src/hww/api/bitcoin/script_configs.rs b/src/rust/bitbox02-rust/src/hww/api/bitcoin/script_configs.rs
index 8c1aed0..f89ba63 100644
--- a/src/rust/bitbox02-rust/src/hww/api/bitcoin/script_configs.rs
+++ b/src/rust/bitbox02-rust/src/hww/api/bitcoin/script_configs.rs
@@ -14,8 +14,8 @@
use alloc::string::String;
-use super::pb;
use super::Error;
+use super::pb;
use pb::btc_script_config::{Multisig, SimpleType};
use super::policies::ParsedPolicy;
diff --git a/src/rust/bitbox02-rust/src/hww/api/bitcoin/signmsg.rs b/src/rust/bitbox02-rust/src/hww/api/bitcoin/signmsg.rs
index 7806e09..22da8d0 100644
--- a/src/rust/bitbox02-rust/src/hww/api/bitcoin/signmsg.rs
+++ b/src/rust/bitbox02-rust/src/hww/api/bitcoin/signmsg.rs
@@ -16,11 +16,11 @@ use alloc::vec::Vec;
use sha2::{Digest, Sha256};
-use super::pb;
use super::Error;
+use super::pb;
-use pb::btc_script_config::{Config, SimpleType};
use pb::BtcCoin;
+use pb::btc_script_config::{Config, SimpleType};
use pb::btc_response::Response;
diff --git a/src/rust/bitbox02-rust/src/hww/api/bitcoin/signtx.rs b/src/rust/bitbox02-rust/src/hww/api/bitcoin/signtx.rs
index 919e212..73f21fd 100644
--- a/src/rust/bitbox02-rust/src/hww/api/bitcoin/signtx.rs
+++ b/src/rust/bitbox02-rust/src/hww/api/bitcoin/signtx.rs
@@ -12,8 +12,8 @@
// See the License for the specific language governing permissions and
// limitations under the License.
-use super::pb;
use super::Error;
+use super::pb;
use super::common::format_amount;
use super::payment_request;
@@ -471,10 +471,12 @@ async fn validate_input_script_configs<'a>(
// We get multisig out of the way first.
- if let [ValidatedScriptConfigWithKeypath {
- config: ValidatedScriptConfig::Multisig { name, multisig },
- ..
- }] = script_configs.as_slice()
+ if let [
+ ValidatedScriptConfigWithKeypath {
+ config: ValidatedScriptConfig::Multisig { name, multisig },
+ ..
+ },
+ ] = script_configs.as_slice()
{
super::multisig::confirm(hal, "Spend from", coin_params, name, multisig).await?;
return Ok(script_configs);
@@ -482,14 +484,16 @@ async fn validate_input_script_configs<'a>(
// Then we get policies out of the way.
- if let [ValidatedScriptConfigWithKeypath {
- config:
- ValidatedScriptConfig::Policy {
- name,
- parsed_policy,
- },
- ..
- }] = script_configs.as_slice()
+ if let [
+ ValidatedScriptConfigWithKeypath {
+ config:
+ ValidatedScriptConfig::Policy {
+ name,
+ parsed_policy,
+ },
+ ..
+ },
+ ] = script_configs.as_slice()
{
// We could check here that the account keypath matches one of our keys in the policy and
// abort early, but we don't have to - if the keypath does not match we will fail when
@@ -1276,7 +1280,7 @@ mod tests {
use crate::workflow::testing::Screen;
use alloc::boxed::Box;
use bitbox02::testing::{mock_memory, mock_unlocked, mock_unlocked_using_mnemonic};
- use pb::btc_payment_request_request::{memo, Memo};
+ use pb::btc_payment_request_request::{Memo, memo};
use util::bip32::HARDENED;
fn extract_next(response: &Response) -> &pb::BtcSignNextResponse {
@@ -2465,9 +2469,11 @@ mod tests {
fee: "2.05419010 BTC".into(),
longtouch: false
}));
- assert!(mock_hal
- .ui
- .contains_confirm("High fee", "The fee is 18.1%\nthe send amount.\nProceed?"));
+ assert!(
+ mock_hal
+ .ui
+ .contains_confirm("High fee", "The fee is 18.1%\nthe send amount.\nProceed?")
+ );
assert_eq!(
mock_hal.ui.screens.len() as u32,
tx.total_confirmations + 1 // plus status screen
@@ -3357,13 +3363,15 @@ mod tests {
bitbox02::memory::multisig_set_by_hash(&policy_hash, "test policy account name").unwrap();
let mut mock_hal = TestingHal::new();
- assert!(block_on(process(
- &mut mock_hal,
- &transaction
- .borrow()
- .init_request_policy(policy, keypath_account),
- ))
- .is_ok());
+ assert!(
+ block_on(process(
+ &mut mock_hal,
+ &transaction
+ .borrow()
+ .init_request_policy(policy, keypath_account),
+ ))
+ .is_ok()
+ );
assert_eq!(
mock_hal.ui.screens,
diff --git a/src/rust/bitbox02-rust/src/hww/api/bluetooth.rs b/src/rust/bitbox02-rust/src/hww/api/bluetooth.rs
index 96902bf..59acb9c 100644
--- a/src/rust/bitbox02-rust/src/hww/api/bluetooth.rs
+++ b/src/rust/bitbox02-rust/src/hww/api/bluetooth.rs
@@ -12,8 +12,8 @@
// See the License for the specific language governing permissions and
// limitations under the License.
-use super::pb;
use super::Error;
+use super::pb;
use pb::bluetooth_request::Request;
use pb::bluetooth_response::Response;
@@ -218,7 +218,7 @@ pub async fn process_api(
return Err(Error::Disabled);
}
match request {
- Request::UpgradeInit(ref request) => process_upgrade(hal, request).await,
+ Request::UpgradeInit(request) => process_upgrade(hal, request).await,
// These are streamed asynchronously using the `next_request()` primitive are not handled
// directly.
Request::Chunk(_) => Err(Error::InvalidInput),
@@ -299,14 +299,16 @@ mod tests {
};
let allowed_hash: [u8; 32] =
Sha256::digest(vec![0; test.firmware_length as usize]).into();
- assert!(block_on(_process_upgrade(
- &mut mock_funcs,
- &pb::BluetoothUpgradeInitRequest {
- firmware_length: test.firmware_length,
- },
- &allowed_hash,
- ))
- .is_ok());
+ assert!(
+ block_on(_process_upgrade(
+ &mut mock_funcs,
+ &pb::BluetoothUpgradeInitRequest {
+ firmware_length: test.firmware_length,
+ },
+ &allowed_hash,
+ ))
+ .is_ok()
+ );
assert_eq!(mock_funcs.chunk_requests, test.expected_chunk_requests);
}
}
diff --git a/src/rust/bitbox02-rust/src/hww/api/cardano.rs b/src/rust/bitbox02-rust/src/hww/api/cardano.rs
index 22bffcc..afacf84 100644
--- a/src/rust/bitbox02-rust/src/hww/api/cardano.rs
+++ b/src/rust/bitbox02-rust/src/hww/api/cardano.rs
@@ -21,8 +21,8 @@ mod params;
mod sign_transaction;
mod xpubs;
-use super::pb;
use super::Error;
+use super::pb;
use pb::cardano_request::Request;
use pb::cardano_response::Response;
@@ -33,8 +33,8 @@ pub async fn process_api(
request: &Request,
) -> Result<Response, Error> {
match request {
- Request::Xpubs(ref request) => xpubs::process(request),
- Request::Address(ref request) => address::process(hal, request).await,
- Request::SignTransaction(ref request) => sign_transaction::process(hal, request).await,
+ Request::Xpubs(request) => xpubs::process(request),
+ Request::Address(request) => address::process(hal, request).await,
+ Request::SignTransaction(request) => sign_transaction::process(hal, request).await,
}
}
diff --git a/src/rust/bitbox02-rust/src/hww/api/cardano/address.rs b/src/rust/bitbox02-rust/src/hww/api/cardano/address.rs
index bee89b5..dbbc085 100644
--- a/src/rust/bitbox02-rust/src/hww/api/cardano/address.rs
+++ b/src/rust/bitbox02-rust/src/hww/api/cardano/address.rs
@@ -12,8 +12,8 @@
// See the License for the specific language governing permissions and
// limitations under the License.
-use super::pb;
use super::Error;
+use super::pb;
use alloc::string::String;
use alloc::vec::Vec;
@@ -21,13 +21,13 @@ use alloc::vec::Vec;
use crate::hal::Ui;
use crate::workflow::confirm;
+use pb::CardanoNetwork;
use pb::cardano_response::Response;
use pb::cardano_script_config::Config;
-use pb::CardanoNetwork;
use blake2::{
- digest::{Update, VariableOutput},
Blake2bVar,
+ digest::{Update, VariableOutput},
};
use super::params;
@@ -423,7 +423,6 @@ mod tests {
"addr128phkx6acpnf78fuvxn0mkew3l0fd058hzquvz7w36x4gtupnz75xxcrtw79hu",
"addr1vx2fxv2umyhttkxyxp8x0dlpdt3k6cwng5pxj3jhsydzers66hrl8",
"addr1w8phkx6acpnf78fuvxn0mkew3l0fd058hzquvz7w36x4gtcyjy7wx",
-
// Byron addresses:
"Ae2tdPwUPEZFRbyhz3cpfC2CumGzNkFBN2L42rcUc2yjQpEkxDbkPodpMAi", // Yoroi style
"DdzFFzCqrhtC3C4UY8YFaEyDALJmFAwhx4Kggk3eae3BT9PhymMjzCVYhQE753BH1Rp3LXfVkVaD1FHT4joSBq7Y8rcXbbVWoxkqB7gy", // Daedalus style
@@ -449,10 +448,8 @@ mod tests {
"addr_test12rphkx6acpnf78fuvxn0mkew3l0fd058hzquvz7w36x4gtupnz75xxcryqrvmw",
"addr_test1vz2fxv2umyhttkxyxp8x0dlpdt3k6cwng5pxj3jhsydzerspjrlsz",
"addr_test1wrphkx6acpnf78fuvxn0mkew3l0fd058hzquvz7w36x4gtcl6szpr",
-
// Byron addresses:
"37btjrVyb4KEB2STADSsj3MYSAdj52X5FrFWpw2r7Wmj2GDzXjFRsHWuZqrw7zSkwopv8Ci3VWeg6bisU9dgJxW5hb2MZYeduNKbQJrqz3zVBsu9nT", // Daedalus style
-
];
for address in &valid_addresses_testnet {
@@ -606,22 +603,22 @@ mod tests {
Test {
keypath_payment: &[1852 + HARDENED, 1815 + HARDENED, HARDENED, 0, 0],
keypath_stake: &[1852 + HARDENED, 1815 + HARDENED, HARDENED, 2, 0],
- expected_address:"addr1q90tlskd4mh5kncmul7vx887j30tjtfgvap5n0g0rf9qqc7znmndrdhe7rwvqkw5c7mqnp4a3yflnvu6kff7l5dungvqmvu6hs",
+ expected_address: "addr1q90tlskd4mh5kncmul7vx887j30tjtfgvap5n0g0rf9qqc7znmndrdhe7rwvqkw5c7mqnp4a3yflnvu6kff7l5dungvqmvu6hs",
},
Test {
keypath_payment: &[1852 + HARDENED, 1815 + HARDENED, HARDENED, 0, 10],
keypath_stake: &[1852 + HARDENED, 1815 + HARDENED, HARDENED, 2, 0],
- expected_address:"addr1qxgr8vtpxq6tzghua0ye8tz869y8w5vs3xr6qk83vzmpy2xznmndrdhe7rwvqkw5c7mqnp4a3yflnvu6kff7l5dungvqatkd04",
+ expected_address: "addr1qxgr8vtpxq6tzghua0ye8tz869y8w5vs3xr6qk83vzmpy2xznmndrdhe7rwvqkw5c7mqnp4a3yflnvu6kff7l5dungvqatkd04",
},
Test {
keypath_payment: &[1852 + HARDENED, 1815 + HARDENED, HARDENED, 1, 10],
keypath_stake: &[1852 + HARDENED, 1815 + HARDENED, HARDENED, 2, 0],
- expected_address:"addr1qy6wl9mazd7w8s303a3t6hjx9k3qqjxzcyfrqjug8wu5uw7znmndrdhe7rwvqkw5c7mqnp4a3yflnvu6kff7l5dungvqvlsgvu",
+ expected_address: "addr1qy6wl9mazd7w8s303a3t6hjx9k3qqjxzcyfrqjug8wu5uw7znmndrdhe7rwvqkw5c7mqnp4a3yflnvu6kff7l5dungvqvlsgvu",
},
Test {
- keypath_payment: &[1852 + HARDENED, 1815 + HARDENED, HARDENED+50, 1, 10],
- keypath_stake: &[1852 + HARDENED, 1815 + HARDENED, HARDENED+50, 2, 0],
- expected_address:"addr1q9t8qctl2mg55fvxrlgnlctf70hww5gtj9cgzrane7nj0amdad2jzalmf2zvjnw9x4z8e5emcqklue3gz85vadsgfutq96mqmx",
+ keypath_payment: &[1852 + HARDENED, 1815 + HARDENED, HARDENED + 50, 1, 10],
+ keypath_stake: &[1852 + HARDENED, 1815 + HARDENED, HARDENED + 50, 2, 0],
+ expected_address: "addr1q9t8qctl2mg55fvxrlgnlctf70hww5gtj9cgzrane7nj0amdad2jzalmf2zvjnw9x4z8e5emcqklue3gz85vadsgfutq96mqmx",
},
];
diff --git a/src/rust/bitbox02-rust/src/hww/api/cardano/keypath.rs b/src/rust/bitbox02-rust/src/hww/api/cardano/keypath.rs
index 64bcb46..92da51f 100644
--- a/src/rust/bitbox02-rust/src/hww/api/cardano/keypath.rs
+++ b/src/rust/bitbox02-rust/src/hww/api/cardano/keypath.rs
@@ -85,8 +85,13 @@ pub fn validate_address_shelley_stake(
keypath: &[u32],
bip44_account: Option<u32>,
) -> Result<(), Error> {
- if let &[BIP44_PURPOSE_SHELLEY, BIP44_COIN, account, BIP44_STAKE_ROLE, BIP44_STAKE_ADDRESS] =
- keypath
+ if let &[
+ BIP44_PURPOSE_SHELLEY,
+ BIP44_COIN,
+ account,
+ BIP44_STAKE_ROLE,
+ BIP44_STAKE_ADDRESS,
+ ] = keypath
{
if bip44_account.is_some_and(|a| a != account) {
return Err(Error);
@@ -149,11 +154,10 @@ mod tests {
);
// force account, mismatch
- assert!(validate_address_shelley_payment(
- &[purpose, coin, account, 0, 0],
- Some(50 + HARDENED)
- )
- .is_err());
+ assert!(
+ validate_address_shelley_payment(&[purpose, coin, account, 0, 0], Some(50 + HARDENED))
+ .is_err()
+ );
// high address
assert!(validate_address_shelley_payment(&[purpose, coin, account, 0, 9999], None).is_ok());
@@ -205,11 +209,10 @@ mod tests {
);
// force account, mismatch
- assert!(validate_address_shelley_stake(
- &[purpose, coin, account, 2, 0],
- Some(50 + HARDENED)
- )
- .is_err());
+ assert!(
+ validate_address_shelley_stake(&[purpose, coin, account, 2, 0], Some(50 + HARDENED))
+ .is_err()
+ );
// invalid address
assert!(validate_address_shelley_stake(&[purpose, coin, account, 2, 1], None).is_err());
@@ -243,58 +246,72 @@ mod tests {
let coin = 1815 + HARDENED;
let account = 99 + HARDENED;
- assert!(validate_address_shelley(
- &[purpose, coin, account, 0, 0],
- &[purpose, coin, account, 2, 0],
- None
- )
- .is_ok());
+ assert!(
+ validate_address_shelley(
+ &[purpose, coin, account, 0, 0],
+ &[purpose, coin, account, 2, 0],
+ None
+ )
+ .is_ok()
+ );
- assert!(validate_address_shelley(
- &[purpose, coin, account, 0, 100],
- &[purpose, coin, account, 2, 0],
- None
- )
- .is_ok());
+ assert!(
+ validate_address_shelley(
+ &[purpose, coin, account, 0, 100],
+ &[purpose, coin, account, 2, 0],
+ None
+ )
+ .is_ok()
+ );
// payment key is a change key
- assert!(validate_address_shelley(
- &[purpose, coin, account, 1, 100],
- &[purpose, coin, account, 2, 0],
- None
- )
- .is_ok());
+ assert!(
+ validate_address_shelley(
+ &[purpose, coin, account, 1, 100],
+ &[purpose, coin, account, 2, 0],
+ None
+ )
+ .is_ok()
+ );
// force account
- assert!(validate_address_shelley(
- &[purpose, coin, account, 0, 0],
- &[purpose, coin, account, 2, 0],
- Some(account),
- )
- .is_ok());
+ assert!(
+ validate_address_shelley(
+ &[purpose, coin, account, 0, 0],
+ &[purpose, coin, account, 2, 0],
+ Some(account),
+ )
+ .is_ok()
+ );
// force account, mismatch
- assert!(validate_address_shelley(
- &[purpose, coin, account, 0, 0],
- &[purpose, coin, account, 2, 0],
- Some(50 + HARDENED),
- )
- .is_err());
+ assert!(
+ validate_address_shelley(
+ &[purpose, coin, account, 0, 0],
+ &[purpose, coin, account, 2, 0],
+ Some(50 + HARDENED),
+ )
+ .is_err()
+ );
// different accounts
- assert!(validate_address_shelley(
- &[purpose, coin, 98 + HARDENED, 0, 100],
- &[purpose, coin, 99 + HARDENED, 2, 0],
- None
- )
- .is_err());
+ assert!(
+ validate_address_shelley(
+ &[purpose, coin, 98 + HARDENED, 0, 100],
+ &[purpose, coin, 99 + HARDENED, 2, 0],
+ None
+ )
+ .is_err()
+ );
// stake address index is not 0
- assert!(validate_address_shelley(
- &[purpose, coin, account, 0, 100],
- &[purpose, coin, account, 2, 1],
- None
- )
- .is_err());
+ assert!(
+ validate_address_shelley(
+ &[purpose, coin, account, 0, 100],
+ &[purpose, coin, account, 2, 1],
+ None
+ )
+ .is_err()
+ );
}
}
diff --git a/src/rust/bitbox02-rust/src/hww/api/cardano/sign_transaction.rs b/src/rust/bitbox02-rust/src/hww/api/cardano/sign_transaction.rs
index 78f21de..6ccacaa 100644
--- a/src/rust/bitbox02-rust/src/hww/api/cardano/sign_transaction.rs
+++ b/src/rust/bitbox02-rust/src/hww/api/cardano/sign_transaction.rs
@@ -15,15 +15,15 @@
mod cbor;
mod certificates;
-use super::pb;
use super::Error;
+use super::pb;
use alloc::string::String;
use alloc::vec::Vec;
use blake2::{
- digest::{Update, VariableOutput},
Blake2bVar,
+ digest::{Update, VariableOutput},
};
use crate::hal::Ui;
@@ -228,7 +228,7 @@ async fn _process(
match output.script_config {
Some(ref script_config) => match script_config {
CardanoScriptConfig {
- config: Some(ref config),
+ config: Some(config),
} => {
let encoded_address = super::address::validate_and_encode_payment_address(
params,
@@ -335,7 +335,7 @@ mod tests {
use bitbox02::testing::mock_unlocked;
use util::bip32::HARDENED;
- use pb::cardano_sign_transaction_request::{certificate, certificate::Cert, Certificate};
+ use pb::cardano_sign_transaction_request::{Certificate, certificate, certificate::Cert};
#[test]
fn test_format_asset() {
@@ -1227,9 +1227,11 @@ mod tests {
let mut mock_hal = TestingHal::new();
assert!(block_on(process(&mut mock_hal, &tx)).is_ok());
- assert!(mock_hal
- .ui
- .contains_confirm("High fee", "The fee is 17.0%\nthe send amount.\nProceed?"));
+ assert!(
+ mock_hal
+ .ui
+ .contains_confirm("High fee", "The fee is 17.0%\nthe send amount.\nProceed?")
+ );
}
#[test]
diff --git a/src/rust/bitbox02-rust/src/hww/api/cardano/sign_transaction/cbor.rs b/src/rust/bitbox02-rust/src/hww/api/cardano/sign_transaction/cbor.rs
index bb08d10..639e05d 100644
--- a/src/rust/bitbox02-rust/src/hww/api/cardano/sign_transaction/cbor.rs
+++ b/src/rust/bitbox02-rust/src/hww/api/cardano/sign_transaction/cbor.rs
@@ -12,18 +12,18 @@
// See the License for the specific language governing permissions and
// limitations under the License.
+use super::super::Error;
use super::super::params;
use super::super::pb;
-use super::super::Error;
use alloc::vec::Vec;
use digest::Update;
use minicbor::encode::{Encoder, Write};
-use pb::cardano_sign_transaction_request::{certificate, Certificate, Withdrawal};
+use pb::cardano_sign_transaction_request::{Certificate, Withdrawal, certificate};
-use super::super::address::{decode_payment_address, pubkey_hash_at_keypath, ADDRESS_HASH_SIZE};
+use super::super::address::{ADDRESS_HASH_SIZE, decode_payment_address, pubkey_hash_at_keypath};
/// A newtype for hashers to implement the Write trait, enabling serializing cbor directly into the
/// hasher.
@@ -249,7 +249,7 @@ pub fn encode_transaction_body<W: Write>(
mod tests {
use super::*;
use alloc::vec::Vec;
- use blake2::{digest::VariableOutput, Blake2bVar};
+ use blake2::{Blake2bVar, digest::VariableOutput};
fn encode_something<W: Write>(
encoder: &mut Encoder<W>,
diff --git a/src/rust/bitbox02-rust/src/hww/api/cardano/sign_transaction/certificates.rs b/src/rust/bitbox02-rust/src/hww/api/cardano/sign_transaction/certificates.rs
index 1f2a517..ba7f4ae 100644
--- a/src/rust/bitbox02-rust/src/hww/api/cardano/sign_transaction/certificates.rs
+++ b/src/rust/bitbox02-rust/src/hww/api/cardano/sign_transaction/certificates.rs
@@ -12,17 +12,16 @@
// See the License for the specific language governing permissions and
// limitations under the License.
+use super::super::Error;
use super::super::keypath::validate_address_shelley_stake;
use super::super::params;
use super::super::pb;
-use super::super::Error;
use alloc::vec::Vec;
use pb::cardano_sign_transaction_request::{
- certificate,
+ Certificate, certificate,
certificate::Cert::{StakeDelegation, StakeDeregistration, StakeRegistration, VoteDelegation},
- Certificate,
};
use crate::hal::Ui;
diff --git a/src/rust/bitbox02-rust/src/hww/api/cardano/xpubs.rs b/src/rust/bitbox02-rust/src/hww/api/cardano/xpubs.rs
index 0564ac8..8601d8a 100644
--- a/src/rust/bitbox02-rust/src/hww/api/cardano/xpubs.rs
+++ b/src/rust/bitbox02-rust/src/hww/api/cardano/xpubs.rs
@@ -12,8 +12,8 @@
// See the License for the specific language governing permissions and
// limitations under the License.
-use super::pb;
use super::Error;
+use super::pb;
use alloc::vec::Vec;
diff --git a/src/rust/bitbox02-rust/src/hww/api/electrum.rs b/src/rust/bitbox02-rust/src/hww/api/electrum.rs
index e2caffb..1d54b55 100644
--- a/src/rust/bitbox02-rust/src/hww/api/electrum.rs
+++ b/src/rust/bitbox02-rust/src/hww/api/electrum.rs
@@ -12,8 +12,8 @@
// See the License for the specific language governing permissions and
// limitations under the License.
-use super::pb;
use super::Error;
+use super::pb;
use pb::response::Response;
diff --git a/src/rust/bitbox02-rust/src/hww/api/ethereum.rs b/src/rust/bitbox02-rust/src/hww/api/ethereum.rs
index 664d996..2895cc2 100644
--- a/src/rust/bitbox02-rust/src/hww/api/ethereum.rs
+++ b/src/rust/bitbox02-rust/src/hww/api/ethereum.rs
@@ -27,8 +27,8 @@ mod sign;
mod sign_typed_msg;
mod signmsg;
-use super::pb;
use super::Error;
+use super::pb;
use pb::eth_request::Request;
use pb::eth_response::Response;
@@ -80,14 +80,14 @@ pub async fn process_api(
request: &Request,
) -> Result<Response, Error> {
match request {
- Request::Pub(ref request) => pubrequest::process(hal, request).await,
- Request::SignMsg(ref request) => signmsg::process(hal, request).await,
- Request::Sign(ref request) => sign::process(hal, &sign::Transaction::Legacy(request)).await,
- Request::SignEip1559(ref request) => {
+ Request::Pub(request) => pubrequest::process(hal, request).await,
+ Request::SignMsg(request) => signmsg::process(hal, request).await,
+ Request::Sign(request) => sign::process(hal, &sign::Transaction::Legacy(request)).await,
+ Request::SignEip1559(request) => {
sign::process(hal, &sign::Transaction::Eip1559(request)).await
}
Request::AntikleptoSignature(_) => Err(Error::InvalidInput),
- Request::SignTypedMsg(ref request) => sign_typed_msg::process(hal, request).await,
+ Request::SignTypedMsg(request) => sign_typed_msg::process(hal, request).await,
Request::TypedMsgValue(_) => Err(Error::InvalidInput),
}
}
diff --git a/src/rust/bitbox02-rust/src/hww/api/ethereum/address.rs b/src/rust/bitbox02-rust/src/hww/api/ethereum/address.rs
index 4b9fe2a..c9fb977 100644
--- a/src/rust/bitbox02-rust/src/hww/api/ethereum/address.rs
+++ b/src/rust/bitbox02-rust/src/hww/api/ethereum/address.rs
@@ -30,11 +30,7 @@ pub fn from_pubkey_hash(recipient: &[u8; 20], address_case: pb::EthAddressCase)
for (i, e) in hex.iter_mut().enumerate() {
let hash_byte = {
let b = hash[i / 2];
- if i % 2 == 0 {
- b >> 4
- } else {
- b & 0xf
- }
+ if i % 2 == 0 { b >> 4 } else { b & 0xf }
};
if *e > b'9' && hash_byte > 7 {
*e -= 32; // convert to uppercase
diff --git a/src/rust/bitbox02-rust/src/hww/api/ethereum/keypath.rs b/src/rust/bitbox02-rust/src/hww/api/ethereum/keypath.rs
index 4d8abdc..c85d4d3 100644
--- a/src/rust/bitbox02-rust/src/hww/api/ethereum/keypath.rs
+++ b/src/rust/bitbox02-rust/src/hww/api/ethereum/keypath.rs
@@ -12,8 +12,8 @@
// See the License for the specific language governing permissions and
// limitations under the License.
-use super::params::Params;
use super::Error;
+use super::params::Params;
use crate::hal::Ui;
use crate::workflow::confirm;
use util::bip32::HARDENED;
diff --git a/src/rust/bitbox02-rust/src/hww/api/ethereum/params.rs b/src/rust/bitbox02-rust/src/hww/api/ethereum/params.rs
index b8f4ac5..970d741 100644
--- a/src/rust/bitbox02-rust/src/hww/api/ethereum/params.rs
+++ b/src/rust/bitbox02-rust/src/hww/api/ethereum/params.rs
@@ -12,8 +12,8 @@
// See the License for the specific language governing permissions and
// limitations under the License.
-use super::pb;
use super::Error;
+use super::pb;
use pb::EthCoin;
use crate::hal::Ui;
diff --git a/src/rust/bitbox02-rust/src/hww/api/ethereum/pubrequest.rs b/src/rust/bitbox02-rust/src/hww/api/ethereum/pubrequest.rs
index da8c7fa..666cff8 100644
--- a/src/rust/bitbox02-rust/src/hww/api/ethereum/pubrequest.rs
+++ b/src/rust/bitbox02-rust/src/hww/api/ethereum/pubrequest.rs
@@ -12,8 +12,8 @@
// See the License for the specific language governing permissions and
// limitations under the License.
-use super::pb;
use super::Error;
+use super::pb;
use pb::eth_pub_request::OutputType;
use pb::eth_response::Response;
diff --git a/src/rust/bitbox02-rust/src/hww/api/ethereum/sign.rs b/src/rust/bitbox02-rust/src/hww/api/ethereum/sign.rs
index 90673d2..6684279 100644
--- a/src/rust/bitbox02-rust/src/hww/api/ethereum/sign.rs
+++ b/src/rust/bitbox02-rust/src/hww/api/ethereum/sign.rs
@@ -12,10 +12,10 @@
// See the License for the specific language governing permissions and
// limitations under the License.
-use super::amount::{calculate_percentage, Amount};
+use super::Error;
+use super::amount::{Amount, calculate_percentage};
use super::params::Params;
use super::pb;
-use super::Error;
use bitbox02::keystore;
@@ -388,7 +388,7 @@ pub async fn _process(
let host_nonce = match request.host_nonce_commitment() {
// Engage in the anti-klepto protocol if the host sends a host nonce commitment.
- Some(pb::AntiKleptoHostNonceCommitment { ref commitment }) => {
+ Some(pb::AntiKleptoHostNonceCommitment { commitment }) => {
let signer_commitment = keystore::secp256k1_nonce_commit(
SECP256K1,
&crate::keystore::secp256k1_get_private_key(request.keypath())?
@@ -477,36 +477,44 @@ mod tests {
);
// ETH value must be 0 when transacting ERC20.
- assert!(parse_erc20(&Transaction::Legacy(&pb::EthSignRequest {
- value: vec![0],
- data: valid_data.to_vec(),
- ..Default::default()
- }))
- .is_none());
+ assert!(
+ parse_erc20(&Transaction::Legacy(&pb::EthSignRequest {
+ value: vec![0],
+ data: valid_data.to_vec(),
+ ..Default::default()
+ }))
+ .is_none()
+ );
// Invalid method (first byte)
let invalid_data = b"\xa8\x05\x9c\xbb\0\0\0\0\0\0\0\0\0\0\0\0abcdefghijklmnopqrst\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\xff";
- assert!(parse_erc20(&Transaction::Legacy(&pb::EthSignRequest {
- data: invalid_data.to_vec(),
- ..Default::default()
- }))
- .is_none());
+ assert!(
+ parse_erc20(&Transaction::Legacy(&pb::EthSignRequest {
+ data: invalid_data.to_vec(),
+ ..Default::default()
+ }))
+ .is_none()
+ );
// Recipient too long (not zero padded)
let invalid_data = b"\xa9\x05\x9c\xbb\0\0\0\0\0\0\0\0\0\0\0babcdefghijklmnopqrst\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\xff";
- assert!(parse_erc20(&Transaction::Legacy(&pb::EthSignRequest {
- data: invalid_data.to_vec(),
- ..Default::default()
- }))
- .is_none());
+ assert!(
+ parse_erc20(&Transaction::Legacy(&pb::EthSignRequest {
+ data: invalid_data.to_vec(),
+ ..Default::default()
+ }))
+ .is_none()
+ );
// Value can't be zero
let invalid_data = b"\xa9\x05\x9c\xbb\0\0\0\0\0\0\0\0\0\0\0\0abcdefghijklmnopqrst\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\x00";
- assert!(parse_erc20(&Transaction::Legacy(&pb::EthSignRequest {
- data: invalid_data.to_vec(),
- ..Default::default()
- }))
- .is_none());
+ assert!(
+ parse_erc20(&Transaction::Legacy(&pb::EthSignRequest {
+ data: invalid_data.to_vec(),
+ ..Default::default()
+ }))
+ .is_none()
+ );
}
/// Standard ETH transaction with no data field.
@@ -1046,11 +1054,13 @@ mod tests {
{
// Check that the above is valid before making invalid variants.
mock_unlocked();
- assert!(block_on(process(
- &mut TestingHal::new(),
- &Transaction::Legacy(&valid_request)
- ))
- .is_ok());
+ assert!(
+ block_on(process(
+ &mut TestingHal::new(),
+ &Transaction::Legacy(&valid_request)
+ ))
+ .is_ok()
+ );
}
{
@@ -1199,11 +1209,13 @@ mod tests {
{
// Check that the above is valid before making invalid variants.
mock_unlocked();
- assert!(block_on(process(
- &mut TestingHal::new(),
- &Transaction::Eip1559(&valid_request)
- ))
- .is_ok());
+ assert!(
+ block_on(process(
+ &mut TestingHal::new(),
+ &Transaction::Eip1559(&valid_request)
+ ))
+ .is_ok()
+ );
}
{
diff --git a/src/rust/bitbox02-rust/src/hww/api/ethereum/sign_typed_msg.rs b/src/rust/bitbox02-rust/src/hww/api/ethereum/sign_typed_msg.rs
index bf1818d..4c1772c 100644
--- a/src/rust/bitbox02-rust/src/hww/api/ethereum/sign_typed_msg.rs
+++ b/src/rust/bitbox02-rust/src/hww/api/ethereum/sign_typed_msg.rs
@@ -19,8 +19,8 @@
//! https://github.com/MetaMask/eth-sig-util/blob/v4.0.1/src/sign-typed-data.ts
//! using SignTypedDataVersion.V4.
-use super::pb;
use super::Error;
+use super::pb;
use crate::hal::Ui;
use crate::secp256k1::SECP256K1;
@@ -1126,13 +1126,19 @@ mod tests {
),
("Message (1/23)", "str: str"),
("Message (2/23)", "emptyArray: (empty list)"),
- ("Message (3/23)", "name_address: 0xa21A16EC22a940990922220E4ab5bF4C2310F556"),
+ (
+ "Message (3/23)",
+ "name_address: 0xa21A16EC22a940990922220E4ab5bF4C2310F556",
+ ),
("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 (4/23)", "name_string[5/6]: long long long long long long long long"),
+ (
+ "Message (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"),
@@ -1141,7 +1147,10 @@ mod tests {
("Message (5/23)", "name_bytes[2/2]: 0xaabbcc"),
("Message (6/23)", "name_bytes1: 0xaa"),
("Message (7/23)", "name_bytes10: 0x112233445566778899aa"),
- ("Message (8/23)", "name_bytes32: 0xd0f02988fd881565e927c7473c287322db166901bac03bef55d7a52a5c750ab4"),
+ (
+ "Message (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"),
@@ -1153,8 +1162,14 @@ mod tests {
("Message (10/23)", "name_uint32[3/4]: 65536"),
("Message (10/23)", "name_uint32[4/4]: 4294967295"),
("Message (11/23)", "name_uint64: 18446744073709551615"),
- ("Message (12/23)", "name_uint128: 340282366920938463463374607431768211455"),
- ("Message (13/23)", "name_uint256: 115792089237316195423570985008687907853269984665640564039457584007913129639935"),
+ (
+ "Message (12/23)",
+ "name_uint128: 340282366920938463463374607431768211455",
+ ),
+ (
+ "Message (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"),
@@ -1170,11 +1185,23 @@ mod tests {
("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 (17/23)", "name_int128[1/2]: 170141183460469231731687303715884105727"),
- ("Message (17/23)", "name_int128[2/2]: -170141183460469231731687303715884105728"),
+ (
+ "Message (17/23)",
+ "name_int128[1/2]: 170141183460469231731687303715884105727",
+ ),
+ (
+ "Message (17/23)",
+ "name_int128[2/2]: -170141183460469231731687303715884105728",
+ ),
("Message (18/23)", "name_int256: list with 2 elements"),
- ("Message (18/23)", "name_int256[1/2]: 57896044618658097711785492504343953926634992332820282019728792003956564819967"),
- ("Message (18/23)", "name_int256[2/2]: -57896044618658097711785492504343953926634992332820282019728792003956564819968"),
+ (
+ "Message (18/23)",
+ "name_int256[1/2]: 57896044618658097711785492504343953926634992332820282019728792003956564819967",
+ ),
+ (
+ "Message (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"),
@@ -1184,38 +1211,74 @@ mod tests {
("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 (21/23)", "arrayOfStructs[2/3].arr: list with 1 elements"),
+ (
+ "Message (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 (21/23)", "arrayOfStructs[3/3].arr: list with 2 elements"),
+ (
+ "Message (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 (22/23)", "fixedArrayOfStructs: list with 2 elements"),
+ (
+ "Message (22/23)",
+ "fixedArrayOfStructs: list with 2 elements",
+ ),
("Message (22/23)", "fixedArrayOfStructs[1/2].name: name 1"),
- ("Message (22/23)", "fixedArrayOfStructs[1/2].arr: (empty list)"),
+ (
+ "Message (22/23)",
+ "fixedArrayOfStructs[1/2].arr: (empty list)",
+ ),
("Message (22/23)", "fixedArrayOfStructs[2/2].name: name 2"),
- ("Message (22/23)", "fixedArrayOfStructs[2/2].arr: list with 3 elements"),
- ("Message (22/23)", "fixedArrayOfStructs[2/2].arr[1/3]: false"),
- ("Message (22/23)", "fixedArrayOfStructs[2/2].arr[2/3]: false"),
+ (
+ "Message (22/23)",
+ "fixedArrayOfStructs[2/2].arr: list with 3 elements",
+ ),
+ (
+ "Message (22/23)",
+ "fixedArrayOfStructs[2/2].arr[1/3]: false",
+ ),
+ (
+ "Message (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)", "nestedArray[1/3][1/2]: list with 2 elements"),
+ (
+ "Message (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 (23/23)", "nestedArray[1/3][2/2]: list with 3 elements"),
+ (
+ "Message (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 (23/23)", "nestedArray[2/3][1/2]: list with 2 elements"),
+ (
+ "Message (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 (23/23)", "nestedArray[2/3][2/2]: list with 1 elements"),
+ (
+ "Message (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 (23/23)", "nestedArray[3/3][2/2]: list with 1 elements"),
+ (
+ "Message (23/23)",
+ "nestedArray[3/3][2/2]: list with 1 elements",
+ ),
("Message (23/23)", "nestedArray[3/3][2/2][1/1]: 9"),
];
diff --git a/src/rust/bitbox02-rust/src/hww/api/ethereum/signmsg.rs b/src/rust/bitbox02-rust/src/hww/api/ethereum/signmsg.rs
index 9d47d83..6f861f9 100644
--- a/src/rust/bitbox02-rust/src/hww/api/ethereum/signmsg.rs
+++ b/src/rust/bitbox02-rust/src/hww/api/ethereum/signmsg.rs
@@ -12,8 +12,8 @@
// See the License for the specific language governing permissions and
// limitations under the License.
-use super::pb;
use super::Error;
+use super::pb;
use bitbox02::keystore;
diff --git a/src/rust/bitbox02-rust/src/hww/api/rootfingerprint.rs b/src/rust/bitbox02-rust/src/hww/api/rootfingerprint.rs
index 056f05d..ea48e65 100644
--- a/src/rust/bitbox02-rust/src/hww/api/rootfingerprint.rs
+++ b/src/rust/bitbox02-rust/src/hww/api/rootfingerprint.rs
@@ -12,8 +12,8 @@
// See the License for the specific language governing permissions and
// limitations under the License.
-use super::pb;
use super::Error;
+use super::pb;
use pb::response::Response;
diff --git a/src/rust/bitbox02-rust/src/keystore.rs b/src/rust/bitbox02-rust/src/keystore.rs
index a679913..1ec0b2a 100644
--- a/src/rust/bitbox02-rust/src/keystore.rs
+++ b/src/rust/bitbox02-rust/src/keystore.rs
@@ -26,7 +26,7 @@ use util::bip32::HARDENED;
use crate::hash::Sha512;
use crate::secp256k1::SECP256K1;
-use hmac::{digest::FixedOutput, Mac, SimpleHmac};
+use hmac::{Mac, SimpleHmac, digest::FixedOutput};
/// Returns the keystore's seed encoded as a BIP-39 mnemonic.
pub fn get_bip39_mnemonic() -> Result<zeroize::Zeroizing<String>, ()> {
@@ -161,7 +161,7 @@ mod tests {
use super::*;
use bitbox02::testing::{
- mock_memory, mock_unlocked, mock_unlocked_using_mnemonic, TEST_MNEMONIC,
+ TEST_MNEMONIC, mock_memory, mock_unlocked, mock_unlocked_using_mnemonic,
};
#[test]
@@ -223,15 +223,24 @@ mod tests {
"",
);
assert_eq!(
- get_xpub_twice(&[]).unwrap().serialize_str(bip32::XPubType::Xpub).unwrap(),
+ get_xpub_twice(&[])
+ .unwrap()
+ .serialize_str(bip32::XPubType::Xpub)
+ .unwrap(),
"xpub661MyMwAqRbcEhX8d9WJh78SZrxusAzWFoykz4n5CF75uYRzixw5FZPUSoWyhaaJ1bpiPFdzdHSQqJN38PcTkyrLmxT4J2JDYfoGJQ4ioE2",
);
assert_eq!(
- get_xpub_twice(keypath).unwrap().serialize_str(bip32::XPubType::Xpub).unwrap(),
+ get_xpub_twice(keypath)
+ .unwrap()
+ .serialize_str(bip32::XPubType::Xpub)
+ .unwrap(),
"xpub6Cj6NNCGj2CRPHvkuEG1rbW3nrNCAnLjaoTg1P67FCGoahSsbg9WQ7YaMEEP83QDxt2kZ3hTPAPpGdyEZcfAC1C75HfR66UbjpAb39f4PnG",
);
assert_eq!(
- get_xpub_twice(keypath_5).unwrap().serialize_str(bip32::XPubType::Xpub).unwrap(),
+ get_xpub_twice(keypath_5)
+ .unwrap()
+ .serialize_str(bip32::XPubType::Xpub)
+ .unwrap(),
"xpub6HHn1zdtf1RjePopiTV5nxf8jY2xwbJicTQ91jV4cUJZ5EnbvXyBGDhqWt8B9JxxBt9vExi4pdWzrbrM43qSFs747VCGmSy2DPWAhg9MkUg",
);
@@ -241,7 +250,10 @@ mod tests {
"",
);
assert_eq!(
- get_xpub_twice(keypath).unwrap().serialize_str(bip32::XPubType::Xpub).unwrap(),
+ get_xpub_twice(keypath)
+ .unwrap()
+ .serialize_str(bip32::XPubType::Xpub)
+ .unwrap(),
"xpub6C7fKxGtTzEVxCC22U2VHx4GpaVy77DzU6KdZ1CLuHgoUGviBMWDc62uoQVxqcRa5RQbMPnffjpwxve18BG81VJhJDXnSpRe5NGKwVpXiAb",
);
@@ -251,7 +263,10 @@ mod tests {
"",
);
assert_eq!(
- get_xpub_twice(keypath).unwrap().serialize_str(bip32::XPubType::Xpub).unwrap(),
+ get_xpub_twice(keypath)
+ .unwrap()
+ .serialize_str(bip32::XPubType::Xpub)
+ .unwrap(),
"xpub6DLvpzjKpJ8k4xYrWYPmZQkUe9dkG1eRig2v6Jz4iYgo8hcpHWx87gGoCGDaB2cHFZ3ExUfe1jDiMu7Ch6gA4ULCBhvwZj29mHCPYSux3YV",
)
}
diff --git a/src/rust/bitbox02-rust/src/keystore/ed25519.rs b/src/rust/bitbox02-rust/src/keystore/ed25519.rs
index 6efca0e..da6b49f 100644
--- a/src/rust/bitbox02-rust/src/keystore/ed25519.rs
+++ b/src/rust/bitbox02-rust/src/keystore/ed25519.rs
@@ -15,7 +15,7 @@
use alloc::vec::Vec;
use crate::hash::Sha512;
-use bip32_ed25519::{Xprv, Xpub, ED25519_EXPANDED_SECRET_KEY_SIZE};
+use bip32_ed25519::{ED25519_EXPANDED_SECRET_KEY_SIZE, Xprv, Xpub};
fn get_seed() -> Result<zeroize::Zeroizing<Vec<u8>>, ()> {
bitbox02::keystore::get_ed25519_seed()
diff --git a/src/rust/bitbox02-rust/src/waker_fn.rs b/src/rust/bitbox02-rust/src/waker_fn.rs
index d1c514a..16a94b4 100644
--- a/src/rust/bitbox02-rust/src/waker_fn.rs
+++ b/src/rust/bitbox02-rust/src/waker_fn.rs
@@ -26,22 +26,22 @@ impl<F: Fn() + Send + Sync + 'static> Helper<F> {
);
unsafe fn clone_waker(ptr: *const ()) -> RawWaker {
- let arc = ManuallyDrop::new(Arc::from_raw(ptr as *const F));
+ 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 = Arc::from_raw(ptr as *const F);
+ let arc = unsafe { Arc::from_raw(ptr as *const F) };
(arc)();
}
unsafe fn wake_by_ref(ptr: *const ()) {
- let arc = ManuallyDrop::new(Arc::from_raw(ptr as *const F));
+ let arc = ManuallyDrop::new(unsafe { Arc::from_raw(ptr as *const F) });
(arc)();
}
unsafe fn drop_waker(ptr: *const ()) {
- drop(Arc::from_raw(ptr as *const F));
+ drop(unsafe { Arc::from_raw(ptr as *const F) });
}
}
diff --git a/src/rust/bitbox02-rust/src/workflow/mnemonic.rs b/src/rust/bitbox02-rust/src/workflow/mnemonic.rs
index c815c67..d26cdef 100644
--- a/src/rust/bitbox02-rust/src/workflow/mnemonic.rs
+++ b/src/rust/bitbox02-rust/src/workflow/mnemonic.rs
@@ -12,13 +12,13 @@
// See the License for the specific language governing permissions and
// limitations under the License.
+use super::Workflows;
pub use super::cancel::Error as CancelError;
use super::cancel::{cancel, set_result, with_cancel};
use super::confirm;
use super::menu;
use super::trinary_choice::TrinaryChoice;
use super::trinary_input_string;
-use super::Workflows;
use alloc::boxed::Box;
use alloc::string::String;
@@ -426,7 +426,7 @@ mod tests {
use super::*;
use alloc::boxed::Box;
- use bitbox02::testing::{mock, Data};
+ use bitbox02::testing::{Data, mock};
fn bruteforce_lastword(mnemonic: &[&str]) -> Vec<zeroize::Zeroizing<String>> {
let mut result = Vec::new();
@@ -447,7 +447,9 @@ mod tests {
assert_eq!(
&as_str_vec(&bruteforce_lastword(&["violin"; 23])),
- &["boss", "coyote", "dry", "habit", "panel", "regular", "speed", "winter"]
+ &[
+ "boss", "coyote", "dry", "habit", "panel", "regular", "speed", "winter"
+ ]
);
assert_eq!(
diff --git a/src/rust/bitbox02-rust/src/workflow/password.rs b/src/rust/bitbox02-rust/src/workflow/password.rs
index 149ddfe..e84abab 100644
--- a/src/rust/bitbox02-rust/src/workflow/password.rs
+++ b/src/rust/bitbox02-rust/src/workflow/password.rs
@@ -12,7 +12,7 @@
// See the License for the specific language governing permissions and
// limitations under the License.
-use super::{confirm, trinary_input_string, Workflows};
+use super::{Workflows, confirm, trinary_input_string};
pub use trinary_input_string::{CanCancel, Error};
diff --git a/src/rust/bitbox02-rust/src/workflow/testing.rs b/src/rust/bitbox02-rust/src/workflow/testing.rs
index 7f0a2ae..13c5dc7 100644
--- a/src/rust/bitbox02-rust/src/workflow/testing.rs
+++ b/src/rust/bitbox02-rust/src/workflow/testing.rs
@@ -12,7 +12,7 @@
// See the License for the specific language governing permissions and
// limitations under the License.
-use super::{confirm, menu, sdcard, transaction, trinary_choice, trinary_input_string, Workflows};
+use super::{Workflows, confirm, menu, sdcard, transaction, trinary_choice, trinary_input_string};
use alloc::boxed::Box;
use alloc::string::String;
diff --git a/src/rust/bitbox02-rust/src/workflow/trinary_choice.rs b/src/rust/bitbox02-rust/src/workflow/trinary_choice.rs
index 26cc9e0..a19f533 100644
--- a/src/rust/bitbox02-rust/src/workflow/trinary_choice.rs
+++ b/src/rust/bitbox02-rust/src/workflow/trinary_choice.rs
@@ -17,8 +17,8 @@ use core::cell::RefCell;
use alloc::boxed::Box;
-use bitbox02::ui::trinary_choice_create;
pub use bitbox02::ui::TrinaryChoice;
+use bitbox02::ui::trinary_choice_create;
pub async fn choose(
message: &str,
diff --git a/src/rust/bitbox02-rust/src/workflow/trinary_input_string.rs b/src/rust/bitbox02-rust/src/workflow/trinary_input_string.rs
index 71061d7..ffbcc4c 100644
--- a/src/rust/bitbox02-rust/src/workflow/trinary_input_string.rs
+++ b/src/rust/bitbox02-rust/src/workflow/trinary_input_string.rs
@@ -12,7 +12,7 @@
// See the License for the specific language governing permissions and
// limitations under the License.
-pub use super::cancel::{cancel, set_result, Error};
+pub use super::cancel::{Error, cancel, set_result};
pub use bitbox02::ui::TrinaryInputStringParams as Params;
use crate::bb02_async::option;
diff --git a/src/rust/bitbox02-rust/src/workflow/verify_message.rs b/src/rust/bitbox02-rust/src/workflow/verify_message.rs
index 93940ba..982daeb 100644
--- a/src/rust/bitbox02-rust/src/workflow/verify_message.rs
+++ b/src/rust/bitbox02-rust/src/workflow/verify_message.rs
@@ -14,7 +14,7 @@
use alloc::vec::Vec;
-use super::{confirm, Workflows};
+use super::{Workflows, confirm};
use util::ascii;
diff --git a/src/rust/bitbox02-sys/Cargo.toml b/src/rust/bitbox02-sys/Cargo.toml
index 37aaea9..1ed623b 100644
--- a/src/rust/bitbox02-sys/Cargo.toml
+++ b/src/rust/bitbox02-sys/Cargo.toml
@@ -17,7 +17,7 @@
name = "bitbox02-sys"
version = "0.1.0"
authors = ["Shift Crypto AG <support@bitbox.swiss>"]
-edition = "2021"
+edition = "2024"
description = "Rust bindings for C code in bitbox02-firmware"
license = "Apache-2.0"
diff --git a/src/rust/bitbox02/Cargo.toml b/src/rust/bitbox02/Cargo.toml
index 806806f..f7c9cf0 100644
--- a/src/rust/bitbox02/Cargo.toml
+++ b/src/rust/bitbox02/Cargo.toml
@@ -17,7 +17,7 @@
name = "bitbox02"
version = "0.1.0"
authors = ["Shift Crypto AG <support@bitbox.swiss>"]
-edition = "2021"
+edition = "2024"
description = "Idiomatic rust bindings for C code in bitbox02-firmware"
license = "Apache-2.0"
diff --git a/src/rust/bitbox02/src/keystore.rs b/src/rust/bitbox02/src/keystore.rs
index 861edd0..ec107df 100644
--- a/src/rust/bitbox02/src/keystore.rs
+++ b/src/rust/bitbox02/src/keystore.rs
@@ -304,14 +304,18 @@ mod tests {
assert_eq!(recovered_pubkey, expected_pubkey);
// Verify signature.
- assert!(secp
- .verify_ecdsa(&msg, &recoverable_sig.to_standard(), &expected_pubkey)
- .is_ok());
+ assert!(
+ secp.verify_ecdsa(&msg, &recoverable_sig.to_standard(), &expected_pubkey)
+ .is_ok()
+ );
}
#[test]
fn test_secp256k1_schnorr_sign() {
- mock_unlocked_using_mnemonic("abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about", "");
+ mock_unlocked_using_mnemonic(
+ "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about",
+ "",
+ );
let keypath = [86 + HARDENED, 0 + HARDENED, 0 + HARDENED, 0, 0];
let msg = [0x88u8; 32];
@@ -326,13 +330,14 @@ mod tests {
crate::random::fake_reset();
let secp = secp256k1::Secp256k1::new();
let sig = secp256k1_schnorr_sign(&secp, &keypath, &msg, None).unwrap();
- assert!(secp
- .verify_schnorr(
+ assert!(
+ secp.verify_schnorr(
&secp256k1::schnorr::Signature::from_slice(&sig).unwrap(),
&secp256k1::Message::from_digest_slice(&msg).unwrap(),
&expected_pubkey
)
- .is_ok());
+ .is_ok()
+ );
// Test with tweak
crate::random::fake_reset();
@@ -345,13 +350,14 @@ mod tests {
let (tweaked_pubkey, _) = expected_pubkey.add_tweak(&secp, &tweak).unwrap();
let sig =
secp256k1_schnorr_sign(&secp, &keypath, &msg, Some(&tweak.to_be_bytes())).unwrap();
- assert!(secp
- .verify_schnorr(
+ assert!(
+ secp.verify_schnorr(
&secp256k1::schnorr::Signature::from_slice(&sig).unwrap(),
&secp256k1::Message::from_digest_slice(&msg).unwrap(),
&tweaked_pubkey
)
- .is_ok());
+ .is_ok()
+ );
}
#[test]
@@ -452,7 +458,10 @@ mod tests {
// https://github.com/cardano-foundation/CIPs/blob/6c249ef48f8f5b32efc0ec768fadf4321f3173f2/CIP-0003/Ledger.md#test-vectors
// See also: https://github.com/cardano-foundation/CIPs/pull/132
- mock_unlocked_using_mnemonic("recall grace sport punch exhibit mad harbor stand obey short width stem awkward used stairs wool ugly trap season stove worth toward congress jaguar", "");
+ mock_unlocked_using_mnemonic(
+ "recall grace sport punch exhibit mad harbor stand obey short width stem awkward used stairs wool ugly trap season stove worth toward congress jaguar",
+ "",
+ );
assert_eq!(
hex::encode(get_ed25519_seed().unwrap()),
"a08cf85b564ecf3b947d8d4321fb96d70ee7bb760877e371899b14e2ccf88658104b884682b57efd97decbb318a45c05a527b9cc5c2f64f7352935a049ceea60680d52308194ccef2a18e6812b452a5815fbd7f5babc083856919aaf668fe7e4",
@@ -460,13 +469,19 @@ mod tests {
// Multiple loop iterations.
- mock_unlocked_using_mnemonic("correct cherry mammal bubble want mandate polar hazard crater better craft exotic choice fun tourist census gap lottery neglect address glow carry old business", "");
+ mock_unlocked_using_mnemonic(
+ "correct cherry mammal bubble want mandate polar hazard crater better craft exotic choice fun tourist census gap lottery neglect address glow carry old business",
+ "",
+ );
assert_eq!(
hex::encode(get_ed25519_seed().unwrap()),
"587c6774357ecbf840d4db6404ff7af016dace0400769751ad2abfc77b9a3844cc71702520ef1a4d1b68b91187787a9b8faab0a9bb6b160de541b6ee62469901fc0beda0975fe4763beabd83b7051a5fd5cbce5b88e82c4bbaca265014e524bd",
);
- mock_unlocked_using_mnemonic("abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon art", "foo");
+ mock_unlocked_using_mnemonic(
+ "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon art",
+ "foo",
+ );
assert_eq!(
hex::encode(get_ed25519_seed().unwrap()),
"f053a1e752de5c26197b60f032a4809f08bb3e5d90484fe42024be31efcba7578d914d3ff992e21652fee6a4d99f6091006938fac2c0c0f9d2de0ba64b754e92a4f3723f23472077aa4cd4dd8a8a175dba07ea1852dad1cf268c61a2679c3890",
diff --git a/src/rust/bitbox02/src/memory.rs b/src/rust/bitbox02/src/memory.rs
index 1a0d3d7..e3b8ee1 100644
--- a/src/rust/bitbox02/src/memory.rs
+++ b/src/rust/bitbox02/src/memory.rs
@@ -229,11 +229,7 @@ pub fn ble_enabled() -> bool {
pub fn ble_enable(enable: bool) -> Result<(), ()> {
let res = unsafe { bitbox02_sys::memory_ble_enable(enable) };
- if res {
- Ok(())
- } else {
- Err(())
- }
+ if res { Ok(()) } else { Err(()) }
}
#[cfg(feature = "testing")]
diff --git a/src/rust/bitbox02/src/random.rs b/src/rust/bitbox02/src/random.rs
index 5c87b73..42d8b0b 100644
--- a/src/rust/bitbox02/src/random.rs
+++ b/src/rust/bitbox02/src/random.rs
@@ -19,7 +19,7 @@ pub fn mcu_32_bytes(out: &mut [u8; 32]) {
#[cfg(not(target_arch = "arm"))]
pub fn mcu_32_bytes(out: &mut [u8; 32]) {
- extern "C" {
+ unsafe extern "C" {
fn rand() -> core::ffi::c_int;
}
diff --git a/src/rust/bitbox02/src/secp256k1.rs b/src/rust/bitbox02/src/secp256k1.rs
index 50b4443..dde5d98 100644
--- a/src/rust/bitbox02/src/secp256k1.rs
+++ b/src/rust/bitbox02/src/secp256k1.rs
@@ -78,11 +78,7 @@ pub fn dleq_verify(
p2.as_c_ptr() as _,
)
};
- if result == 1 {
- Ok(())
- } else {
- Err(())
- }
+ if result == 1 { Ok(()) } else { Err(()) }
}
#[cfg(test)]
diff --git a/src/rust/bitbox02/src/testing.rs b/src/rust/bitbox02/src/testing.rs
index 7a7bc66..7fbbb97 100644
--- a/src/rust/bitbox02/src/testing.rs
+++ b/src/rust/bitbox02/src/testing.rs
@@ -34,7 +34,7 @@ pub fn mock_unlocked() {
}
unsafe extern "C" fn c_mock_random_32_bytes(buf_out: *mut u8) {
- let s = core::slice::from_raw_parts_mut(buf_out, 32);
+ let s = unsafe { core::slice::from_raw_parts_mut(buf_out, 32) };
s.copy_from_slice(b"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
}
diff --git a/src/rust/bitbox02/src/util.rs b/src/rust/bitbox02/src/util.rs
index f487e87..a621df7 100644
--- a/src/rust/bitbox02/src/util.rs
+++ b/src/rust/bitbox02/src/util.rs
@@ -30,17 +30,13 @@ pub fn str_from_null_terminated(input: &[u8]) -> Result<&str, ()> {
/// # Safety `ptr` must be not null and be a null terminated string. The resulting string is only
/// valid as long the memory pointed to by `ptr` is valid.
pub unsafe fn str_from_null_terminated_ptr<'a>(ptr: *const u8) -> Result<&'a str, ()> {
- core::ffi::CStr::from_ptr(ptr.cast()).to_str().or(Err(()))
+ unsafe { core::ffi::CStr::from_ptr(ptr.cast()).to_str().or(Err(())) }
}
/// truncate_str truncates string `s` to `len` chars. If `s` is
/// shorter than `len`, the string is returned unchanged (no panics).
pub fn truncate_str(s: &str, len: usize) -> &str {
- if s.len() > len {
- &s[..len]
- } else {
- s
- }
+ if s.len() > len { &s[..len] } else { s }
}
/// Converts a Rust string to a null terminated C string by appending a null
diff --git a/src/rust/erc20_params/Cargo.toml b/src/rust/erc20_params/Cargo.toml
index 3378146..20d7ce1 100644
--- a/src/rust/erc20_params/Cargo.toml
+++ b/src/rust/erc20_params/Cargo.toml
@@ -16,7 +16,7 @@
name = "erc20_params"
version = "0.1.0"
authors = ["Shift Crypto AG <support@bitbox.swiss>"]
-edition = "2021"
+edition = "2024"
license = "Apache-2.0"
[dev-dependencies]
diff --git a/src/rust/rustfmt.toml b/src/rust/rustfmt.toml
index 3a26366..f216078 100644
--- a/src/rust/rustfmt.toml
+++ b/src/rust/rustfmt.toml
@@ -1 +1 @@
-edition = "2021"
+edition = "2024"
diff --git a/src/rust/streaming-silent-payments/Cargo.toml b/src/rust/streaming-silent-payments/Cargo.toml
index 114c5a7..4e2885e 100644
--- a/src/rust/streaming-silent-payments/Cargo.toml
+++ b/src/rust/streaming-silent-payments/Cargo.toml
@@ -16,7 +16,7 @@
name = "streaming-silent-payments"
version = "0.1.0"
authors = ["Shift Crypto AG <support@bitbox.swiss>"]
-edition = "2021"
+edition = "2024"
license = "Apache-2.0"
[dependencies]
diff --git a/src/rust/streaming-silent-payments/src/hash.rs b/src/rust/streaming-silent-payments/src/hash.rs
index 689551b..37c9016 100644
--- a/src/rust/streaming-silent-payments/src/hash.rs
+++ b/src/rust/streaming-silent-payments/src/hash.rs
@@ -3,7 +3,7 @@
#![allow(non_snake_case)]
-use bitcoin::hashes::{sha256t_hash_newtype, Hash, HashEngine};
+use bitcoin::hashes::{Hash, HashEngine, sha256t_hash_newtype};
use bitcoin::secp256k1::{PublicKey, Scalar};
sha256t_hash_newtype! {
diff --git a/src/rust/streaming-silent-payments/src/lib.rs b/src/rust/streaming-silent-payments/src/lib.rs
index 574bcd5..2d921a8 100644
--- a/src/rust/streaming-silent-payments/src/lib.rs
+++ b/src/rust/streaming-silent-payments/src/lib.rs
@@ -396,8 +396,8 @@ mod tests {
.unwrap();
let _ = v.create_output("sp1qqgste7k9hx0qftg6qmwlkqtwuy6cycyavzmzj85c6qdfhjdpdjtdgqjuexzk6murw56suy3e0rd2cgqvycxttddwsvgxe2usfpxumr70xc9pkqwv").unwrap();
- assert!(v
- .add_input(
+ assert!(
+ v.add_input(
InputType::P2wpkh,
&SecretKey::from_str(
"93f5ed907ad5b2bdbbdcb5d9116ebc0a4e1f92f910d5260237fa45a9408aad16",
@@ -411,6 +411,7 @@ mod tests {
0,
),
)
- .is_err());
+ .is_err()
+ );
}
}
diff --git a/src/rust/streaming-silent-payments/tests/table_test.rs b/src/rust/streaming-silent-payments/tests/table_test.rs
index 90bbcec..a8b089f 100644
--- a/src/rust/streaming-silent-payments/tests/table_test.rs
+++ b/src/rust/streaming-silent-payments/tests/table_test.rs
@@ -20,9 +20,8 @@ use std::io::BufReader;
use std::str::FromStr;
use streaming_silent_payments::{
- bitcoin,
+ InputType, Network, SilentPayment, bitcoin,
bitcoin::secp256k1::{SecretKey, XOnlyPublicKey},
- InputType, Network, SilentPayment,
};
/// The following structs have been copied from:
diff --git a/src/rust/util/Cargo.toml b/src/rust/util/Cargo.toml
index 86568e8..8c42490 100644
--- a/src/rust/util/Cargo.toml
+++ b/src/rust/util/Cargo.toml
@@ -17,7 +17,7 @@
name = "util"
version = "0.1.0"
authors = ["Shift Crypto AG <support@bitbox.swiss>"]
-edition = "2021"
+edition = "2024"
license = "Apache-2.0"
[dependencies]
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.