From 05f452688aae0f6f5433488a19a07c650046c443 Mon Sep 17 00:00:00 2001 From: Trevor Arjeski Date: Thu, 26 Nov 2026 08:43:00 +0000 Subject: [PATCH 01/23] feat: make the BitBox client stack optional - Keep existing clients, persistence, and clock APIs enabled by default. - Allow consumers to build the protocol without transport, runtime, or OS entropy. --- Cargo.toml | 31 ++++++++++++++++++++----------- src/antiklepto.rs | 2 ++ src/btc.rs | 7 ++++++- src/communication.rs | 13 +++++++++++++ src/error.rs | 3 +++ src/eth.rs | 23 ++++++++++++++++++++--- src/lib.rs | 41 ++++++++++++++++++++++++++++++++++++++--- src/noise.rs | 21 +++++++++++++++++---- tests/test_btc.rs | 5 +---- tests/test_btc_psbt.rs | 5 +---- tests/test_cardano.rs | 5 +---- tests/test_device.rs | 12 +++++++----- tests/test_eth.rs | 11 +++++++---- tests/util/mod.rs | 4 ++++ 14 files changed, 140 insertions(+), 43 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 5d6ba52..ef7c017 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -12,28 +12,28 @@ keywords = ["bitbox", "api", "bitcoin"] categories = ["api-bindings", "cryptography"] [dependencies] -async-trait = "0.1.68" +async-trait = { version = "0.1.68", optional = true } base32 = "0.5" bitcoin = "0.32" byteorder = "1.3.2" -getrandom = { version = "0.2" } -futures-util = { version = "0.3", default-features = false, features = ["std"] } +getrandom = { version = "0.2", optional = true } +futures-util = { version = "0.3", default-features = false, features = ["std"], optional = true } hex = { version = "0.4" } noise-protocol = "0.2" -noise-rust-crypto = "0.6" -num-bigint = "0.4" +noise-rust-crypto = { version = "0.6", optional = true } +num-bigint = { version = "0.4", optional = true } # If you change this, also change the version of prost-build in scripts/build-protos.rs # and run `make build-protos`. prost = "0.14" semver = "1.0.17" -serde_json = { version = "1.0" } +serde_json = { version = "1.0", optional = true } thiserror = "2.0" zeroize = "1" -chrono = { version = "0.4.38", default-features = false, features = ["clock"] } +chrono = { version = "0.4.38", default-features = false, features = ["clock"], optional = true } hidapi = { version = "2.3", optional = true } rlp = { version = "0.6", optional = true } -serde = { version = "1.0", features = ["derive"] } +serde = { version = "1.0", features = ["derive"], optional = true } tokio = { version = "1", optional = true, features = ["time"] } [dev-dependencies] @@ -45,6 +45,8 @@ reqwest = "0.12" url = "2.5" tiny-keccak = { version = "2.0", features = ["keccak"] } rlp = "0.6" +serde = { version = "1.0", features = ["derive"] } +serde_json = "1.0" # Enable this to be able to get coverage using `cargo tarpaulin --features=simulator,tokio --out=Html` without compilation error. # See https://github.com/rust-bitcoin/rust-bitcoinconsensus/pull/94 # bitcoinconsensus = { git = "https://github.com/rust-bitcoin/rust-bitcoinconsensus.git", rev = "788ce4d210f7fe6fae4414f5be80968216ba0fd8", default-features = false } @@ -81,7 +83,7 @@ required-features = ["usb", "tokio/rt", "tokio/macros"] [[example]] name = "eth" -required-features = ["usb", "tokio/rt", "tokio/macros", "rlp"] +required-features = ["usb", "tokio/rt", "tokio/macros", "rlp", "persistence"] [[example]] name = "cardano" @@ -92,8 +94,15 @@ name = "simulator" required-features = ["simulator", "tokio/rt", "tokio/macros", "tokio/rt-multi-thread", "multithreaded"] [features] +default = ["client", "persistence", "clock"] +runtime = ["dep:async-trait"] +read-write = ["dep:async-trait"] +client = ["runtime", "read-write", "dep:futures-util", "dep:getrandom", "dep:noise-rust-crypto", "dep:num-bigint"] +persistence = ["dep:serde", "dep:serde_json"] +clock = ["client", "dep:chrono"] +usb = ["client", "dep:hidapi"] +simulator = ["client"] +tokio = ["runtime", "dep:tokio"] # Implement Sync+Send for PairedBitBox and PairingBitBox. # This may or may not cause trouble on macOS, see: https://github.com/libusb/hidapi/issues/503 multithreaded = [] -usb = ["dep:hidapi"] -simulator = [] diff --git a/src/antiklepto.rs b/src/antiklepto.rs index 4ff0adb..c241b40 100644 --- a/src/antiklepto.rs +++ b/src/antiklepto.rs @@ -10,6 +10,7 @@ use std::io::Write; #[derive(Error, Debug)] pub enum Error { + #[cfg(feature = "client")] #[error("Failed generating antiklepto host nonce")] GenNonce, #[error("{0}")] @@ -35,6 +36,7 @@ fn tagged_sha256(tag: &[u8], msg: &[u8]) -> [u8; 32] { sha256::Hash::from_engine(engine).to_byte_array() } +#[cfg(feature = "client")] pub fn gen_host_nonce() -> Result<[u8; 32], Error> { let mut result = [0u8; 32]; getrandom::getrandom(&mut result).map_err(|_| Error::GenNonce)?; diff --git a/src/btc.rs b/src/btc.rs index 8280d43..fb2f5ec 100644 --- a/src/btc.rs +++ b/src/btc.rs @@ -2,11 +2,15 @@ //! Functions and methods related to Bitcoin. +#[cfg(feature = "client")] use crate::runtime::Runtime; use crate::error::Error; -use crate::pb::{self, request::Request, response::Response}; +use crate::pb; +#[cfg(feature = "client")] +use crate::pb::{request::Request, response::Response}; use crate::Keypath; +#[cfg(feature = "client")] use crate::PairedBitBox; pub use bitcoin::{ @@ -678,6 +682,7 @@ fn find_or_add_script_config( } } +#[cfg(feature = "client")] impl PairedBitBox { /// Retrieves an xpub. For non-standard keypaths, a warning is displayed on the BitBox even if /// `display` is false. diff --git a/src/communication.rs b/src/communication.rs index 8a29f30..68474ee 100644 --- a/src/communication.rs +++ b/src/communication.rs @@ -1,8 +1,12 @@ // SPDX-License-Identifier: Apache-2.0 +#[cfg(feature = "client")] use super::u2fframing; +#[cfg(feature = "client")] use crate::runtime::Runtime; +#[cfg(feature = "read-write")] use crate::util::Threading; +#[cfg(feature = "read-write")] use async_trait::async_trait; use thiserror::Error; @@ -24,6 +28,7 @@ pub enum Error { Version(&'static str), } +#[cfg(feature = "read-write")] #[cfg_attr(feature = "multithreaded", async_trait)] #[cfg_attr(not(feature="multithreaded"), async_trait(?Send))] pub trait ReadWrite: Threading { @@ -36,13 +41,16 @@ pub trait ReadWrite: Threading { } } +#[cfg(feature = "client")] pub struct U2fHidCommunication { read_write: Box, u2fhid: u2fframing::U2fHid, } +#[cfg(feature = "client")] impl crate::util::Threading for U2fHidCommunication {} +#[cfg(feature = "client")] impl U2fHidCommunication { pub fn from(read_write: Box, cmd: u8) -> Self { U2fHidCommunication { @@ -52,6 +60,7 @@ impl U2fHidCommunication { } } +#[cfg(feature = "client")] #[cfg_attr(feature = "multithreaded", async_trait)] #[cfg_attr(not(feature="multithreaded"),async_trait(?Send))] impl ReadWrite for U2fHidCommunication { @@ -125,12 +134,14 @@ pub struct Info { pub initialized: Option, } +#[cfg(feature = "client")] pub struct HwwCommunication { communication: Box, pub info: Info, marker: std::marker::PhantomData, } +#[cfg(feature = "client")] async fn get_info(communication: &dyn ReadWrite) -> Result { let response = communication.query(&[HWW_INFO]).await?; let (version_str_len, response) = ( @@ -178,6 +189,7 @@ async fn get_info(communication: &dyn ReadWrite) -> Result { }) } +#[cfg(feature = "client")] async fn reset_session( communication: &dyn ReadWrite, version: &semver::Version, @@ -195,6 +207,7 @@ async fn reset_session( } } +#[cfg(feature = "client")] impl HwwCommunication { pub async fn from(communication: Box) -> Result { let info = get_info(communication.as_ref()).await?; diff --git a/src/error.rs b/src/error.rs index 574dbd2..4c4417d 100644 --- a/src/error.rs +++ b/src/error.rs @@ -44,8 +44,10 @@ pub enum Error { Communication(communication::Error), #[error("noise channel error")] Noise, + #[cfg(any(feature = "client", feature = "persistence"))] #[error("noise config error: {0}")] NoiseConfig(#[from] crate::noise::ConfigError), + #[cfg(feature = "client")] #[error("pairing code rejected by user")] NoisePairingRejected, #[error("BitBox returned an unexpected response")] @@ -62,6 +64,7 @@ pub enum Error { InvalidSignature, #[error("Antiklepto verification failed: {0}")] AntiKlepto(#[from] crate::antiklepto::Error), + #[cfg(all(feature = "client", feature = "persistence"))] #[error("EIP-712 typed message processing error: {0}")] EthTypedMessage(String), #[error("Bitcoin transaction signing error: {0}")] diff --git a/src/eth.rs b/src/eth.rs index a17c4e2..3f6b6ae 100644 --- a/src/eth.rs +++ b/src/eth.rs @@ -3,21 +3,24 @@ use crate::runtime::Runtime; use crate::error::Error; +#[cfg(feature = "persistence")] use crate::pb::{ - self, eth_sign_typed_message_request::{DataType, Member, MemberType, StructType}, eth_typed_message_value_response::RootObject, - request::Request, - response::Response, }; +use crate::pb::{self, request::Request, response::Response}; use crate::Keypath; use crate::PairedBitBox; +#[cfg(feature = "persistence")] use std::collections::HashMap; +#[cfg(feature = "persistence")] use std::str::FromStr; +#[cfg(feature = "persistence")] use num_bigint::{BigInt, BigUint}; //use num_traits::ToPrimitive; +#[cfg(feature = "persistence")] use serde_json::Value; /// Threshold above which transaction data is streamed in chunks. @@ -181,12 +184,14 @@ impl TryFrom<&[u8]> for EIP1559Transaction { } } +#[cfg(feature = "persistence")] #[derive(Debug, PartialEq, serde::Deserialize)] struct Eip712TypeMember { name: String, r#type: String, } +#[cfg(feature = "persistence")] #[derive(Debug, PartialEq, serde::Deserialize)] #[serde(rename_all = "camelCase")] struct Eip712Message { @@ -196,6 +201,7 @@ struct Eip712Message { message: HashMap, } +#[cfg(feature = "persistence")] fn parse_type( typ: &str, types: &HashMap>, @@ -284,6 +290,7 @@ fn parse_type( } } +#[cfg(feature = "persistence")] fn encode_value(typ: &MemberType, value: &Value) -> Result, String> { match DataType::try_from(typ.r#type).unwrap() { DataType::Bytes => { @@ -367,6 +374,7 @@ fn encode_value(typ: &MemberType, value: &Value) -> Result, String> { } } +#[cfg(feature = "persistence")] fn get_value( what: &pb::EthTypedMessageValueResponse, msg: &Eip712Message, @@ -639,6 +647,7 @@ impl PairedBitBox { /// Signs an Ethereum EIP-712 typed message. It returns a 65 byte signature (R, S, and 1 byte /// recID). 27 is added to the recID to denote an uncompressed pubkey. /// If `use_antiklepto` is false, signing is deterministic and requires firmware >=9.26.0. + #[cfg(feature = "persistence")] pub async fn eth_sign_typed_message( &self, chain_id: u64, @@ -744,6 +753,7 @@ impl PairedBitBox { mod tests { use super::*; + #[cfg(feature = "persistence")] const EIP712_MSG: &str = r#" { "types": { @@ -792,6 +802,7 @@ mod tests { } "#; + #[cfg(feature = "persistence")] fn map_from(elements: &[(&str, Value)]) -> Value { let mut m = serde_json::Map::::new(); for (k, v) in elements.iter().cloned() { @@ -800,6 +811,7 @@ mod tests { m.into() } + #[cfg(feature = "persistence")] #[test] fn test_deserialize_eip713_message() { let msg: Eip712Message = serde_json::from_str(EIP712_MSG).unwrap(); @@ -920,10 +932,12 @@ mod tests { ); } + #[cfg(feature = "persistence")] fn parse_type_no_err(typ: &str, types: &HashMap>) -> MemberType { parse_type(typ, types).unwrap() } + #[cfg(feature = "persistence")] #[test] fn test_parse_type() { assert_eq!( @@ -1110,6 +1124,7 @@ mod tests { ); } + #[cfg(feature = "persistence")] #[test] fn test_encode_value() { let encoded = @@ -1213,6 +1228,7 @@ mod tests { assert_eq!(b"\x00\x00\x03\xe8".to_vec(), encoded); } + #[cfg(feature = "persistence")] #[test] fn test_encode_value_signed_integers() { let typ = parse_type_no_err("int64", &HashMap::new()); @@ -1247,6 +1263,7 @@ mod tests { } } + #[cfg(feature = "persistence")] #[test] fn test_get_value() { let msg: Eip712Message = serde_json::from_str(EIP712_MSG).unwrap(); diff --git a/src/lib.rs b/src/lib.rs index dbd7855..02aeec1 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -3,10 +3,13 @@ //! Rust BitBox hardware wallet client library. pub mod btc; +#[cfg(feature = "client")] pub mod cardano; pub mod error; +#[cfg(feature = "client")] pub mod eth; mod noise; +#[cfg(feature = "runtime")] pub mod runtime; #[cfg(feature = "simulator")] pub mod simulator; @@ -26,51 +29,78 @@ pub mod pb { include!("./shiftcrypto.bitbox02.rs"); } +#[cfg(feature = "client")] use crate::error::{BitBoxError, Error}; +#[cfg(feature = "client")] use pb::request::Request; +#[cfg(feature = "client")] use pb::response::Response; +#[cfg(feature = "client")] use runtime::Runtime; +#[cfg(feature = "client")] use noise_protocol::DH; +#[cfg(feature = "client")] use prost::Message; +#[cfg(feature = "client")] use futures_util::lock::{Mutex as AsyncMutex, MutexGuard as ApiMutexGuard}; +#[cfg(feature = "client")] use std::sync::Mutex; pub use keypath::Keypath; +#[cfg(feature = "persistence")] pub use noise::PersistedNoiseConfig; -pub use noise::{ConfigError, NoiseConfig, NoiseConfigData, NoiseConfigNoCache}; +#[cfg(any(feature = "client", feature = "persistence"))] +pub use noise::{ConfigError, NoiseConfig, NoiseConfigNoCache}; +pub use noise::NoiseConfigData; pub use util::Threading; +#[cfg(feature = "client")] use communication::HwwCommunication; pub use communication::Product; -pub use communication::{Error as CommunicationError, ReadWrite}; +pub use communication::Error as CommunicationError; +#[cfg(feature = "read-write")] +pub use communication::ReadWrite; +#[cfg(feature = "client")] const OP_I_CAN_HAS_HANDSHAEK: u8 = b'h'; +#[cfg(feature = "client")] const OP_HER_COMEZ_TEH_HANDSHAEK: u8 = b'H'; +#[cfg(feature = "client")] const OP_I_CAN_HAS_PAIRIN_VERIFICASHUN: u8 = b'v'; +#[cfg(feature = "client")] const OP_NOISE_MSG: u8 = b'n'; +#[cfg(feature = "client")] const _OP_ATTESTATION: u8 = b'a'; +#[cfg(feature = "client")] const OP_UNLOCK: u8 = b'u'; +#[cfg(feature = "client")] const RESPONSE_SUCCESS: u8 = 0x00; +#[cfg(feature = "client")] type Cipher = noise_rust_crypto::ChaCha20Poly1305; +#[cfg(feature = "client")] type HandshakeState = noise_protocol::HandshakeState; +#[cfg(feature = "client")] type CipherState = noise_protocol::CipherState; +#[cfg(feature = "client")] /// BitBox client. See `from_hid_device()`. pub struct BitBox { communication: communication::HwwCommunication, noise_config: Box, } +#[cfg(feature = "client")] pub type PairingCode = String; +#[cfg(feature = "client")] impl BitBox { /// Creates a new BitBox instance from a custom transport. /// @@ -214,6 +244,7 @@ impl BitBox { } } +#[cfg(feature = "client")] /// BitBox in the pairing state. Use `get_pairing_code()` to display the pairing code to the user /// and `wait_confirm()` to proceed to the paired state. pub struct PairingBitBox { @@ -223,6 +254,7 @@ pub struct PairingBitBox { pairing_code: Option, } +#[cfg(feature = "client")] impl PairingBitBox { fn from( communication: communication::HwwCommunication, @@ -269,6 +301,7 @@ impl PairingBitBox { } } +#[cfg(feature = "client")] /// Paired BitBox. This is where you can invoke most API functions like getting xpubs, displaying /// receive addresses, etc. pub struct PairedBitBox { @@ -278,6 +311,7 @@ pub struct PairedBitBox { noise_recv: Mutex, } +#[cfg(feature = "client")] impl PairedBitBox { fn from(communication: communication::HwwCommunication, host: HandshakeState) -> Self { let (send, recv) = host.get_ciphers(); @@ -406,6 +440,7 @@ impl PairedBitBox { } } + #[cfg(feature = "clock")] /// Restore from recovery words on the Bitbox. pub async fn restore_from_mnemonic(&self) -> Result<(), Error> { let _api_call = self.begin_api_call().await; @@ -458,7 +493,7 @@ impl PairedBitBox { } } -#[cfg(all(test, not(feature = "multithreaded")))] +#[cfg(all(test, feature = "client", not(feature = "multithreaded")))] mod tests { use super::*; use crate::communication::{Error as CommunicationError, ReadWrite}; diff --git a/src/noise.rs b/src/noise.rs index 7956b90..22f26b6 100644 --- a/src/noise.rs +++ b/src/noise.rs @@ -1,20 +1,25 @@ // SPDX-License-Identifier: Apache-2.0 +#[cfg(any(feature = "client", feature = "persistence"))] use crate::util::Threading; -#[cfg(unix)] +#[cfg(all(feature = "persistence", unix))] use std::os::unix::fs::{OpenOptionsExt, PermissionsExt}; +#[cfg(any(feature = "client", feature = "persistence"))] use thiserror::Error; +#[cfg(any(feature = "client", feature = "persistence"))] #[derive(Error, Debug)] #[error("{0}")] pub struct ConfigError(pub String); -#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)] +#[derive(Default, Clone, Debug)] +#[cfg_attr(feature = "persistence", derive(serde::Serialize, serde::Deserialize))] pub struct NoiseConfigData { pub app_static_privkey: Option<[u8; 32]>, pub device_static_pubkeys: Vec>, } +#[cfg(feature = "client")] impl NoiseConfigData { pub(crate) fn contains_device_static_pubkey(&self, pubkey: &[u8]) -> bool { self.device_static_pubkeys @@ -44,6 +49,7 @@ impl NoiseConfigData { } } +#[cfg(any(feature = "client", feature = "persistence"))] pub trait NoiseConfig: Threading { fn read_config(&self) -> Result { Ok(NoiseConfigData::default()) @@ -53,11 +59,14 @@ pub trait NoiseConfig: Threading { } } +#[cfg(any(feature = "client", feature = "persistence"))] pub struct NoiseConfigNoCache; +#[cfg(any(feature = "client", feature = "persistence"))] impl NoiseConfig for NoiseConfigNoCache {} +#[cfg(any(feature = "client", feature = "persistence"))] impl Threading for NoiseConfigNoCache {} -#[cfg(unix)] +#[cfg(all(feature = "persistence", unix))] fn ensure_private_file_permissions(path: &std::path::Path) -> Result<(), ConfigError> { let metadata = std::fs::symlink_metadata(path).map_err(|e| ConfigError(e.to_string()))?; @@ -70,12 +79,15 @@ fn ensure_private_file_permissions(path: &std::path::Path) -> Result<(), ConfigE .map_err(|e| ConfigError(e.to_string())) } +#[cfg(feature = "persistence")] pub struct PersistedNoiseConfig { config_dir: String, } +#[cfg(feature = "persistence")] impl Threading for PersistedNoiseConfig {} +#[cfg(feature = "persistence")] impl PersistedNoiseConfig { /// Creates a new persisting noise config, which stores the pairing information in "bitbox.json" /// in the provided directory. The directory must already exist and should be created with @@ -87,6 +99,7 @@ impl PersistedNoiseConfig { } } +#[cfg(feature = "persistence")] impl NoiseConfig for PersistedNoiseConfig { fn read_config(&self) -> Result { use std::io::Read; @@ -135,7 +148,7 @@ impl NoiseConfig for PersistedNoiseConfig { } } -#[cfg(all(test, unix))] +#[cfg(all(test, feature = "persistence", unix))] mod tests { use super::*; use std::os::unix::fs::PermissionsExt; diff --git a/tests/test_btc.rs b/tests/test_btc.rs index 1b3bda0..6a01870 100644 --- a/tests/test_btc.rs +++ b/tests/test_btc.rs @@ -1,12 +1,9 @@ // SPDX-License-Identifier: Apache-2.0 -#![cfg(feature = "simulator")] +#![cfg(all(feature = "simulator", feature = "tokio", feature = "clock"))] // Simulators only run on linux/amd64. #![cfg(all(target_os = "linux", target_arch = "x86_64"))] -#[cfg(not(feature = "tokio"))] -compile_error!("Enable the tokio feature to run simulator tests"); - mod util; use util::test_initialized_simulators; diff --git a/tests/test_btc_psbt.rs b/tests/test_btc_psbt.rs index b121c95..1f48721 100644 --- a/tests/test_btc_psbt.rs +++ b/tests/test_btc_psbt.rs @@ -1,12 +1,9 @@ // SPDX-License-Identifier: Apache-2.0 -#![cfg(feature = "simulator")] +#![cfg(all(feature = "simulator", feature = "tokio", feature = "clock"))] // Simulators only run on linux/amd64. #![cfg(all(target_os = "linux", target_arch = "x86_64"))] -#[cfg(not(feature = "tokio"))] -compile_error!("Enable the tokio feature to run simulator tests"); - mod util; use std::collections::{BTreeMap, BTreeSet}; diff --git a/tests/test_cardano.rs b/tests/test_cardano.rs index eac36e6..d8cf9d2 100644 --- a/tests/test_cardano.rs +++ b/tests/test_cardano.rs @@ -1,12 +1,9 @@ // SPDX-License-Identifier: Apache-2.0 -#![cfg(feature = "simulator")] +#![cfg(all(feature = "simulator", feature = "tokio", feature = "clock"))] // Simulators only run on linux/amd64. #![cfg(all(target_os = "linux", target_arch = "x86_64"))] -#[cfg(not(feature = "tokio"))] -compile_error!("Enable the tokio feature to run simulator tests"); - mod util; use util::test_initialized_simulators; diff --git a/tests/test_device.rs b/tests/test_device.rs index a37854b..f9cffc7 100644 --- a/tests/test_device.rs +++ b/tests/test_device.rs @@ -1,16 +1,16 @@ // SPDX-License-Identifier: Apache-2.0 -#![cfg(feature = "simulator")] +#![cfg(all(feature = "simulator", feature = "tokio"))] // Simulators only run on linux/amd64. #![cfg(all(target_os = "linux", target_arch = "x86_64"))] -#[cfg(not(feature = "tokio"))] -compile_error!("Enable the tokio feature to run simulator tests"); - mod util; -use util::{test_initialized_simulators, test_simulators_after_pairing}; +#[cfg(feature = "clock")] +use util::test_initialized_simulators; +use util::test_simulators_after_pairing; +#[cfg(feature = "clock")] #[tokio::test] async fn test_reconnect() { use bitbox_api::{btc, pb, runtime::TokioRuntime, BitBox, NoiseConfigNoCache, PairedBitBox}; @@ -148,6 +148,7 @@ async fn test_device_info() { .await } +#[cfg(feature = "clock")] #[tokio::test] async fn test_root_fingerprint() { test_initialized_simulators(async |paired_bitbox| { @@ -159,6 +160,7 @@ async fn test_root_fingerprint() { .await } +#[cfg(feature = "clock")] #[tokio::test] async fn test_change_password() { test_initialized_simulators(async |bitbox| { diff --git a/tests/test_eth.rs b/tests/test_eth.rs index d6c5f8b..f6e6709 100644 --- a/tests/test_eth.rs +++ b/tests/test_eth.rs @@ -1,12 +1,9 @@ // SPDX-License-Identifier: Apache-2.0 -#![cfg(feature = "simulator")] +#![cfg(all(feature = "simulator", feature = "tokio", feature = "clock"))] // Simulators only run on linux/amd64. #![cfg(all(target_os = "linux", target_arch = "x86_64"))] -#[cfg(not(feature = "tokio"))] -compile_error!("Enable the tokio feature to run simulator tests"); - mod util; use bitbox_api::eth::{EIP1559Transaction, Transaction}; @@ -14,6 +11,7 @@ use bitcoin::secp256k1; use tiny_keccak::{Hasher, Keccak}; use util::test_initialized_simulators; +#[cfg(feature = "persistence")] const EIP712_MSG: &str = r#" { "types": { @@ -103,6 +101,7 @@ fn eip1559_sighash(tx: &EIP1559Transaction) -> [u8; 32] { keccak256(&prefixed) } +#[cfg(feature = "persistence")] fn eip712_sighash(primary_type: &str, data_type: &str, data: &[u8]) -> [u8; 32] { let domain_type_hash = keccak256(b"EIP712Domain(string name)"); let name_hash = keccak256(b"Test"); @@ -272,6 +271,7 @@ async fn test_eth_sign_1559_transaction_streaming() { .await } +#[cfg(feature = "persistence")] #[tokio::test] async fn test_eth_sign_typed_message_antiklepto_enabled() { test_initialized_simulators(async |paired_bitbox| { @@ -290,6 +290,7 @@ async fn test_eth_sign_typed_message_antiklepto_enabled() { .await } +#[cfg(feature = "persistence")] #[tokio::test] async fn test_eth_sign_typed_message_signed_integers() { test_initialized_simulators(async |paired_bitbox| { @@ -340,6 +341,7 @@ async fn test_eth_sign_typed_message_signed_integers() { .await } +#[cfg(feature = "persistence")] #[tokio::test] async fn test_eth_sign_typed_message_antiklepto_disabled() { test_initialized_simulators(async |paired_bitbox| { @@ -385,6 +387,7 @@ async fn test_eth_sign_typed_message_antiklepto_disabled() { .await } +#[cfg(feature = "persistence")] #[tokio::test] async fn test_eth_sign_typed_message_streaming_bytes() { test_initialized_simulators(async |paired_bitbox| { diff --git a/tests/util/mod.rs b/tests/util/mod.rs index 0fb2549..59087ed 100644 --- a/tests/util/mod.rs +++ b/tests/util/mod.rs @@ -565,6 +565,7 @@ pub async fn test_simulators(run: impl AsyncFn(&SimulatorStdout)) { } /// Tests on an initialized device, which is not yet seeded. +#[cfg(feature = "tokio")] pub async fn test_simulators_after_pairing_with_stdout( run: impl AsyncFn(&bitbox_api::PairedBitBox, &SimulatorStdout), ) { @@ -584,6 +585,7 @@ pub async fn test_simulators_after_pairing_with_stdout( } /// Tests on an initialized device, which is not yet seeded. +#[cfg(feature = "tokio")] pub async fn test_simulators_after_pairing( run: impl AsyncFn(&bitbox_api::PairedBitBox), ) { @@ -596,6 +598,7 @@ pub async fn test_simulators_after_pairing( /// Tests on an initialized/seeded device. /// The simulator is initialized with the following mnemonic: /// boring mistake dish oyster truth pigeon viable emerge sort crash wire portion cannon couple enact box walk height pull today solid off enable tide +#[cfg(all(feature = "clock", feature = "tokio"))] pub async fn test_initialized_simulators_with_stdout( run: impl AsyncFn(&bitbox_api::PairedBitBox, &SimulatorStdout), ) { @@ -607,6 +610,7 @@ pub async fn test_initialized_simulators_with_stdout( } /// Tests on an initialized/seeded device. +#[cfg(all(feature = "clock", feature = "tokio"))] pub async fn test_initialized_simulators( run: impl AsyncFn(&bitbox_api::PairedBitBox), ) { From 0c020ad7ce1f1077bbb1049b19475992ec50d001 Mon Sep 17 00:00:00 2001 From: Trevor Arjeski Date: Thu, 26 Nov 2026 08:43:30 +0000 Subject: [PATCH 02/23] feat: expose signature and Anti-Klepto validation --- src/antiklepto.rs | 2 +- src/lib.rs | 8 ++++---- src/secp256k1.rs | 4 ++-- 3 files changed, 7 insertions(+), 7 deletions(-) diff --git a/src/antiklepto.rs b/src/antiklepto.rs index c241b40..97c1b8c 100644 --- a/src/antiklepto.rs +++ b/src/antiklepto.rs @@ -37,7 +37,7 @@ fn tagged_sha256(tag: &[u8], msg: &[u8]) -> [u8; 32] { } #[cfg(feature = "client")] -pub fn gen_host_nonce() -> Result<[u8; 32], Error> { +pub(crate) fn gen_host_nonce() -> Result<[u8; 32], Error> { let mut result = [0u8; 32]; getrandom::getrandom(&mut result).map_err(|_| Error::GenNonce)?; Ok(result) diff --git a/src/lib.rs b/src/lib.rs index 02aeec1..4b5556f 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -16,10 +16,10 @@ pub mod simulator; #[cfg(feature = "usb")] pub mod usb; -mod antiklepto; +pub mod antiklepto; mod communication; mod keypath; -mod secp256k1; +pub mod secp256k1; mod u2fframing; mod util; @@ -50,18 +50,18 @@ use futures_util::lock::{Mutex as AsyncMutex, MutexGuard as ApiMutexGuard}; use std::sync::Mutex; pub use keypath::Keypath; +pub use noise::NoiseConfigData; #[cfg(feature = "persistence")] pub use noise::PersistedNoiseConfig; #[cfg(any(feature = "client", feature = "persistence"))] pub use noise::{ConfigError, NoiseConfig, NoiseConfigNoCache}; -pub use noise::NoiseConfigData; pub use util::Threading; #[cfg(feature = "client")] use communication::HwwCommunication; -pub use communication::Product; pub use communication::Error as CommunicationError; +pub use communication::Product; #[cfg(feature = "read-write")] pub use communication::ReadWrite; diff --git a/src/secp256k1.rs b/src/secp256k1.rs index ee77d81..a7ff5f2 100644 --- a/src/secp256k1.rs +++ b/src/secp256k1.rs @@ -11,7 +11,7 @@ pub struct ValidationError(&'static str); /// Validates a 64-byte compact ECDSA signature encoded as `r || s`. /// /// Both scalars must be nonzero and in range, and `s` must use its low-S encoding. -pub(crate) fn validate_signature_compact(signature: &[u8]) -> Result<(), ValidationError> { +pub fn validate_signature_compact(signature: &[u8]) -> Result<(), ValidationError> { if signature.len() != 64 { return Err(ValidationError("Signature must be 64 bytes")); } @@ -34,7 +34,7 @@ pub(crate) fn validate_signature_compact(signature: &[u8]) -> Result<(), Validat /// Validates a 65-byte recoverable ECDSA signature encoded as `r || s || recovery_id`. /// /// The compact signature must be valid and the recovery ID must be in the range 0..=3. -pub(crate) fn validate_signature_recoverable(signature: &[u8]) -> Result<(), ValidationError> { +pub fn validate_signature_recoverable(signature: &[u8]) -> Result<(), ValidationError> { if signature.len() != 65 { return Err(ValidationError("Signature must be 65 bytes")); } From dfa50dfebd524f2e2cf4455323e78f5322637bf9 Mon Sep 17 00:00:00 2001 From: Trevor Arjeski Date: Thu, 26 Nov 2026 08:43:57 +0000 Subject: [PATCH 03/23] feat: expose the protobuf envelope codec - Share encoding and decoding with the convenience client. - Preserve raw device error codes and messages before client error mapping. --- src/api.rs | 43 +++++++++++++++++++++++++++++++++++++++++++ src/error.rs | 17 +++++++++++++++++ src/lib.rs | 31 ++++++------------------------- 3 files changed, 66 insertions(+), 25 deletions(-) create mode 100644 src/api.rs diff --git a/src/api.rs b/src/api.rs new file mode 100644 index 0000000..f45c446 --- /dev/null +++ b/src/api.rs @@ -0,0 +1,43 @@ +// SPDX-License-Identifier: Apache-2.0 + +use prost::Message; + +use crate::error::Error; +use crate::pb::{self, request::Request, response::Response}; + +pub fn encode_request(request: Request) -> Vec { + pb::Request { + request: Some(request), + } + .encode_to_vec() +} + +pub fn decode_response(bytes: &[u8]) -> Result { + pb::Response::decode(bytes) +} + +pub fn response_body(response: pb::Response) -> Result { + response.response.ok_or(Error::ProtobufDecode) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn decodes_error_without_losing_code_or_message() { + let wire = b"\x12\x08\x08\xe7\x07\x12\x03new"; + assert_eq!( + response_body(decode_response(wire).unwrap()).unwrap(), + Response::Error(pb::Error { + code: 999, + message: "new".into(), + }), + ); + assert!(matches!( + response_body(decode_response(&[]).unwrap()), + Err(Error::ProtobufDecode), + )); + assert!(decode_response(&wire[..wire.len() - 1]).is_err()); + } +} diff --git a/src/error.rs b/src/error.rs index 4c4417d..6d544ec 100644 --- a/src/error.rs +++ b/src/error.rs @@ -28,6 +28,23 @@ pub enum BitBoxError { NoiseDecrypt, } +impl BitBoxError { + pub fn from_code(code: i32) -> Self { + match code { + 101 => Self::InvalidInput, + 102 => Self::Memory, + 103 => Self::Generic, + 104 => Self::UserAbort, + 105 => Self::InvalidState, + 106 => Self::Disabled, + 107 => Self::Duplicate, + 108 => Self::NoiseEncrypt, + 109 => Self::NoiseDecrypt, + _ => Self::Unknown, + } + } +} + #[derive(Error, Debug)] pub enum Error { #[error("unknown error")] diff --git a/src/lib.rs b/src/lib.rs index 4b5556f..caa9c36 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -2,6 +2,7 @@ //! Rust BitBox hardware wallet client library. +pub mod api; pub mod btc; #[cfg(feature = "client")] pub mod cardano; @@ -41,8 +42,6 @@ use runtime::Runtime; #[cfg(feature = "client")] use noise_protocol::DH; -#[cfg(feature = "client")] -use prost::Message; #[cfg(feature = "client")] use futures_util::lock::{Mutex as AsyncMutex, MutexGuard as ApiMutexGuard}; @@ -348,10 +347,7 @@ impl PairedBitBox { let mut encrypted = vec![OP_NOISE_MSG]; encrypted.extend_from_slice({ let mut send = self.noise_send.lock().unwrap(); - let proto_msg = pb::Request { - request: Some(request), - }; - &send.encrypt_vec(&proto_msg.encode_to_vec()) + &send.encrypt_vec(&api::encode_request(request)) }); let response = self.communication.query(&encrypted).await?; @@ -362,25 +358,10 @@ impl PairedBitBox { let mut recv = self.noise_recv.lock().unwrap(); recv.decrypt_vec(&response[1..]).or(Err(Error::Noise))? }; - match pb::Response::decode(&decrypted[..]) { - Ok(pb::Response { - response: Some(Response::Error(pb::Error { code, .. })), - }) => match code { - 101 => Err(BitBoxError::InvalidInput.into()), - 102 => Err(BitBoxError::Memory.into()), - 103 => Err(BitBoxError::Generic.into()), - 104 => Err(BitBoxError::UserAbort.into()), - 105 => Err(BitBoxError::InvalidState.into()), - 106 => Err(BitBoxError::Disabled.into()), - 107 => Err(BitBoxError::Duplicate.into()), - 108 => Err(BitBoxError::NoiseEncrypt.into()), - 109 => Err(BitBoxError::NoiseDecrypt.into()), - _ => Err(BitBoxError::Unknown.into()), - }, - Ok(pb::Response { - response: Some(response), - }) => Ok(response), - _ => Err(Error::ProtobufDecode), + let response = api::decode_response(&decrypted).map_err(|_| Error::ProtobufDecode)?; + match api::response_body(response)? { + Response::Error(pb::Error { code, .. }) => Err(BitBoxError::from_code(code).into()), + response => Ok(response), } } From 807eaf2c853ec357b3890e716112f427abbc0ea3 Mon Sep 17 00:00:00 2001 From: Trevor Arjeski Date: Thu, 26 Nov 2026 08:45:14 +0000 Subject: [PATCH 04/23] feat: share management request and response primitives - Expose explicit entropy, timestamp, and timezone payloads without client I/O. - Reject malformed root fingerprints instead of returning arbitrary-length hex. --- src/api.rs | 160 +++++++++++++++++++++++++++++++++++++++++++++++++++++ src/lib.rs | 55 +++++------------- 2 files changed, 175 insertions(+), 40 deletions(-) diff --git a/src/api.rs b/src/api.rs index f45c446..f16f49f 100644 --- a/src/api.rs +++ b/src/api.rs @@ -1,5 +1,6 @@ // SPDX-License-Identifier: Apache-2.0 +use bitcoin::bip32::Fingerprint; use prost::Message; use crate::error::Error; @@ -20,6 +21,84 @@ pub fn response_body(response: pb::Response) -> Result { response.response.ok_or(Error::ProtobufDecode) } +pub fn root_fingerprint_request() -> Request { + Request::Fingerprint(pb::RootFingerprintRequest {}) +} + +pub fn device_info_request() -> Request { + Request::DeviceInfo(pb::DeviceInfoRequest {}) +} + +pub fn show_mnemonic_request() -> Request { + Request::ShowMnemonic(pb::ShowMnemonicRequest {}) +} + +pub fn set_device_name_request(name: String) -> Request { + Request::DeviceName(pb::SetDeviceNameRequest { name }) +} + +pub fn set_password_request(entropy: &[u8; 32]) -> Request { + Request::SetPassword(pb::SetPasswordRequest { + entropy: entropy.to_vec(), + }) +} + +pub fn create_backup_request(timestamp: u32, timezone_offset: i32) -> Request { + Request::CreateBackup(pb::CreateBackupRequest { + timestamp, + timezone_offset, + }) +} + +pub fn restore_from_mnemonic_request(timestamp: u32, timezone_offset: i32) -> Request { + Request::RestoreFromMnemonic(pb::RestoreFromMnemonicRequest { + timestamp, + timezone_offset, + }) +} + +pub fn reset_request() -> Request { + Request::Reset(pb::ResetRequest {}) +} + +pub fn set_mnemonic_passphrase_enabled_request(enabled: bool) -> Request { + Request::SetMnemonicPassphraseEnabled(pb::SetMnemonicPassphraseEnabledRequest { enabled }) +} + +pub fn parse_device_info(response: Response) -> Result { + match response { + Response::DeviceInfo(info) => Ok(info), + _ => Err(Error::UnexpectedResponse), + } +} + +pub fn parse_root_fingerprint(response: Response) -> Result { + match response { + Response::Fingerprint(info) => { + let bytes: [u8; 4] = info + .fingerprint + .try_into() + .map_err(|_| Error::UnexpectedResponse)?; + Ok(Fingerprint::from(bytes)) + } + _ => Err(Error::UnexpectedResponse), + } +} + +pub fn parse_pub(response: Response) -> Result { + match response { + Response::Pub(value) => Ok(value.r#pub), + _ => Err(Error::UnexpectedResponse), + } +} + +pub fn parse_success(response: Response) -> Result<(), Error> { + match response { + Response::Success(_) => Ok(()), + _ => Err(Error::UnexpectedResponse), + } +} + #[cfg(test)] mod tests { use super::*; @@ -40,4 +119,85 @@ mod tests { )); assert!(decode_response(&wire[..wire.len() - 1]).is_err()); } + + #[test] + fn encodes_management_requests() { + let entropy_wire = [&[0x2a, 34, 0x0a, 32][..], &[0x42; 32]].concat(); + for (request, wire) in [ + (root_fingerprint_request(), &b"\xc2\x01\x00"[..]), + (device_info_request(), &b"\x22\x00"[..]), + (show_mnemonic_request(), &b"\x3a\x00"[..]), + ( + set_device_name_request("unit".into()), + &b"\x12\x06\x0a\x04unit"[..], + ), + (set_password_request(&[0x42; 32]), &entropy_wire[..]), + ( + create_backup_request(123, 60), + &b"\x32\x04\x08\x7b\x10\x3c"[..], + ), + ( + restore_from_mnemonic_request(123, 60), + &b"\xb2\x01\x04\x08\x7b\x10\x3c"[..], + ), + (reset_request(), &b"\xaa\x01\x00"[..]), + ( + set_mnemonic_passphrase_enabled_request(true), + &b"\x72\x02\x08\x01"[..], + ), + ( + set_mnemonic_passphrase_enabled_request(false), + &b"\x72\x00"[..], + ), + ] { + assert_eq!(encode_request(request), wire); + } + } + + #[test] + fn fingerprint_requires_exactly_four_bytes() { + let parse = |bytes: &[u8]| { + parse_root_fingerprint(Response::Fingerprint(pb::RootFingerprintResponse { + fingerprint: bytes.to_vec(), + })) + }; + assert_eq!(parse(&[1, 2, 3, 4]).unwrap().to_bytes(), [1, 2, 3, 4]); + for bytes in [&[1, 2, 3][..], &[1, 2, 3, 4, 5]] { + assert!(matches!(parse(bytes), Err(Error::UnexpectedResponse))); + } + assert!(matches!( + parse_root_fingerprint(Response::Success(pb::Success {})), + Err(Error::UnexpectedResponse), + )); + } + + #[test] + fn checks_response_variants() { + let info = pb::DeviceInfoResponse { + version: "9.29.0".into(), + ..Default::default() + }; + assert_eq!( + parse_device_info(Response::DeviceInfo(info.clone())).unwrap(), + info + ); + let public = Response::Pub(pb::PubResponse { + r#pub: "address".into(), + }); + let success = Response::Success(pb::Success {}); + assert_eq!(parse_pub(public.clone()).unwrap(), "address"); + assert!(parse_success(success.clone()).is_ok()); + assert!(matches!( + parse_success(public), + Err(Error::UnexpectedResponse) + )); + assert!(matches!( + parse_pub(success.clone()), + Err(Error::UnexpectedResponse) + )); + assert!(matches!( + parse_device_info(success), + Err(Error::UnexpectedResponse) + )); + } } diff --git a/src/lib.rs b/src/lib.rs index caa9c36..e02b4f2 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -367,13 +367,7 @@ impl PairedBitBox { pub async fn device_info(&self) -> Result { let _api_call = self.begin_api_call().await; - match self - .query_proto(Request::DeviceInfo(pb::DeviceInfoRequest {})) - .await? - { - Response::DeviceInfo(di) => Ok(di), - _ => Err(Error::UnexpectedResponse), - } + api::parse_device_info(self.query_proto(api::device_info_request()).await?) } /// Returns which product we are connected to. @@ -399,26 +393,15 @@ impl PairedBitBox { self.root_fingerprint_inner().await.map(hex::encode) } - pub(crate) async fn root_fingerprint_inner(&self) -> Result, Error> { - match self - .query_proto(Request::Fingerprint(pb::RootFingerprintRequest {})) - .await? - { - Response::Fingerprint(pb::RootFingerprintResponse { fingerprint }) => Ok(fingerprint), - _ => Err(Error::UnexpectedResponse), - } + pub(crate) async fn root_fingerprint_inner(&self) -> Result<[u8; 4], Error> { + let response = self.query_proto(api::root_fingerprint_request()).await?; + api::parse_root_fingerprint(response).map(|fingerprint| fingerprint.to_bytes()) } /// Show recovery words on the Bitbox. pub async fn show_mnemonic(&self) -> Result<(), Error> { let _api_call = self.begin_api_call().await; - match self - .query_proto(Request::ShowMnemonic(pb::ShowMnemonicRequest {})) - .await? - { - Response::Success(_) => Ok(()), - _ => Err(Error::UnexpectedResponse), - } + api::parse_success(self.query_proto(api::show_mnemonic_request()).await?) } #[cfg(feature = "clock")] @@ -427,18 +410,13 @@ impl PairedBitBox { let _api_call = self.begin_api_call().await; let now = std::time::SystemTime::now(); let duration_since_epoch = now.duration_since(std::time::UNIX_EPOCH).unwrap(); - match self - .query_proto(Request::RestoreFromMnemonic( - pb::RestoreFromMnemonicRequest { - timestamp: duration_since_epoch.as_secs() as u32, - timezone_offset: chrono::Local::now().offset().local_minus_utc(), - }, + api::parse_success( + self.query_proto(api::restore_from_mnemonic_request( + duration_since_epoch.as_secs() as u32, + chrono::Local::now().offset().local_minus_utc(), )) - .await? - { - Response::Success(_) => Ok(()), - _ => Err(Error::UnexpectedResponse), - } + .await?, + ) } /// Invokes the password change workflow on the device. @@ -446,13 +424,10 @@ impl PairedBitBox { pub async fn change_password(&self) -> Result<(), Error> { let _api_call = self.begin_api_call().await; self.validate_version(">=9.25.0")?; - match self - .query_proto(Request::ChangePassword(pb::ChangePasswordRequest {})) - .await? - { - Response::Success(_) => Ok(()), - _ => Err(Error::UnexpectedResponse), - } + api::parse_success( + self.query_proto(Request::ChangePassword(pb::ChangePasswordRequest {})) + .await?, + ) } /// Invokes the BIP85-BIP39 workflow on the device, letting the user select the number of words From eb28bc6d88417bb1f038b9cf2721f6ace66ba867 Mon Sep 17 00:00:00 2001 From: Trevor Arjeski Date: Thu, 26 Nov 2026 08:45:23 +0000 Subject: [PATCH 05/23] feat(btc): share one-shot request and response primitives - Reuse shared xpub, address, and script-registration codecs in the client. - Preserve protobuf field presence for paths, names, and nested responses. --- src/btc.rs | 307 +++++++++++++++++++++++++++++++++++++++++------------ 1 file changed, 237 insertions(+), 70 deletions(-) diff --git a/src/btc.rs b/src/btc.rs index fb2f5ec..13f8aae 100644 --- a/src/btc.rs +++ b/src/btc.rs @@ -7,7 +7,6 @@ use crate::runtime::Runtime; use crate::error::Error; use crate::pb; -#[cfg(feature = "client")] use crate::pb::{request::Request, response::Response}; use crate::Keypath; #[cfg(feature = "client")] @@ -682,6 +681,120 @@ fn find_or_add_script_config( } } +fn btc_request(request: pb::btc_request::Request) -> Request { + Request::Btc(pb::BtcRequest { + request: Some(request), + }) +} + +/// Builds a request for a single extended public key. +pub fn xpub_request( + coin: pb::BtcCoin, + keypath: &Keypath, + xpub_type: pb::btc_pub_request::XPubType, + display: bool, +) -> Request { + Request::BtcPub(pb::BtcPubRequest { + coin: coin as _, + keypath: keypath.to_vec(), + display, + output: Some(pb::btc_pub_request::Output::XpubType(xpub_type as _)), + }) +} + +/// Builds a request for a Bitcoin address. +pub fn address_request( + coin: pb::BtcCoin, + keypath: &Keypath, + script_config: pb::BtcScriptConfig, + display: bool, +) -> Request { + Request::BtcPub(pb::BtcPubRequest { + coin: coin as _, + keypath: keypath.to_vec(), + display, + output: Some(pb::btc_pub_request::Output::ScriptConfig(script_config)), + }) +} + +fn script_config_registration( + coin: pb::BtcCoin, + script_config: pb::BtcScriptConfig, + keypath_account: Option<&Keypath>, +) -> pb::BtcScriptConfigRegistration { + pb::BtcScriptConfigRegistration { + coin: coin as _, + script_config: Some(script_config), + keypath: keypath_account.map_or_else(Vec::new, Keypath::to_vec), + } +} + +/// Builds a request to check whether a wallet configuration is registered. +pub fn is_script_config_registered_request( + coin: pb::BtcCoin, + script_config: pb::BtcScriptConfig, + keypath_account: Option<&Keypath>, +) -> Request { + btc_request(pb::btc_request::Request::IsScriptConfigRegistered( + pb::BtcIsScriptConfigRegisteredRequest { + registration: Some(script_config_registration( + coin, + script_config, + keypath_account, + )), + }, + )) +} + +/// Builds a wallet registration request. An absent name prompts on the device. +pub fn register_script_config_request( + coin: pb::BtcCoin, + script_config: pb::BtcScriptConfig, + keypath_account: Option<&Keypath>, + xpub_type: pb::btc_register_script_config_request::XPubType, + name: Option<&str>, +) -> Request { + btc_request(pb::btc_request::Request::RegisterScriptConfig( + pb::BtcRegisterScriptConfigRequest { + registration: Some(script_config_registration( + coin, + script_config, + keypath_account, + )), + name: name.unwrap_or_default().into(), + xpub_type: xpub_type as _, + }, + )) +} + +/// Extracts the body of a Bitcoin-specific response. +pub fn btc_response(response: Response) -> Result { + match response { + Response::Btc(pb::BtcResponse { + response: Some(response), + }) => Ok(response), + _ => Err(Error::UnexpectedResponse), + } +} + +/// Parses the result of a wallet registration check. +pub fn parse_is_registered(response: Response) -> Result { + match btc_response(response)? { + pb::btc_response::Response::IsScriptConfigRegistered(response) => { + Ok(response.is_registered) + } + _ => Err(Error::UnexpectedResponse), + } +} + +/// Parses the acknowledgement of a wallet registration. +pub fn parse_registered(response: Response) -> Result<(), Error> { + match btc_response(response)? { + pb::btc_response::Response::Success(_) => Ok(()), + _ => Err(Error::UnexpectedResponse), + } +} + #[cfg(feature = "client")] impl PairedBitBox { /// Retrieves an xpub. For non-standard keypaths, a warning is displayed on the BitBox even if @@ -704,18 +817,10 @@ impl PairedBitBox { xpub_type: pb::btc_pub_request::XPubType, display: bool, ) -> Result { - match self - .query_proto(Request::BtcPub(pb::BtcPubRequest { - coin: coin as _, - keypath: keypath.to_vec(), - display, - output: Some(pb::btc_pub_request::Output::XpubType(xpub_type as _)), - })) - .await? - { - Response::Pub(pb::PubResponse { r#pub }) => Ok(r#pub), - _ => Err(Error::UnexpectedResponse), - } + crate::api::parse_pub( + self.query_proto(xpub_request(coin, keypath, xpub_type, display)) + .await?, + ) } /// Retrieves multiple xpubs at once. Only standard keypaths are allowed. @@ -768,37 +873,17 @@ impl PairedBitBox { display: bool, ) -> Result { let _api_call = self.begin_api_call().await; - match self - .query_proto(Request::BtcPub(pb::BtcPubRequest { - coin: coin as _, - keypath: keypath.to_vec(), - display, - output: Some(pb::btc_pub_request::Output::ScriptConfig( - script_config.clone(), - )), - })) - .await? - { - Response::Pub(pb::PubResponse { r#pub }) => Ok(r#pub), - _ => Err(Error::UnexpectedResponse), - } + crate::api::parse_pub( + self.query_proto(address_request(coin, keypath, script_config.clone(), display)) + .await?, + ) } async fn query_proto_btc( &self, request: pb::btc_request::Request, ) -> Result { - match self - .query_proto(Request::Btc(pb::BtcRequest { - request: Some(request), - })) - .await? - { - Response::Btc(pb::BtcResponse { - response: Some(response), - }) => Ok(response), - _ => Err(Error::UnexpectedResponse), - } + btc_response(self.query_proto(btc_request(request)).await?) } async fn get_next_response(&self, request: Request) -> Result { @@ -1182,23 +1267,14 @@ impl PairedBitBox { keypath_account: Option<&Keypath>, ) -> Result { let _api_call = self.begin_api_call().await; - match self - .query_proto_btc(pb::btc_request::Request::IsScriptConfigRegistered( - pb::BtcIsScriptConfigRegisteredRequest { - registration: Some(pb::BtcScriptConfigRegistration { - coin: coin as _, - script_config: Some(script_config.clone()), - keypath: keypath_account.map_or(vec![], |kp| kp.to_vec()), - }), - }, + parse_is_registered( + self.query_proto(is_script_config_registered_request( + coin, + script_config.clone(), + keypath_account, )) - .await? - { - pb::btc_response::Response::IsScriptConfigRegistered(response) => { - Ok(response.is_registered) - } - _ => Err(Error::UnexpectedResponse), - } + .await?, + ) } /// Before a multisig or policy script config can be used to display receive addresses or sign @@ -1220,23 +1296,16 @@ impl PairedBitBox { name: Option<&str>, ) -> Result<(), Error> { let _api_call = self.begin_api_call().await; - match self - .query_proto_btc(pb::btc_request::Request::RegisterScriptConfig( - pb::BtcRegisterScriptConfigRequest { - registration: Some(pb::BtcScriptConfigRegistration { - coin: coin as _, - script_config: Some(script_config.clone()), - keypath: keypath_account.map_or(vec![], |kp| kp.to_vec()), - }), - name: name.unwrap_or("").into(), - xpub_type: xpub_type as _, - }, + parse_registered( + self.query_proto(register_script_config_request( + coin, + script_config.clone(), + keypath_account, + xpub_type, + name, )) - .await? - { - pb::btc_response::Response::Success(_) => Ok(()), - _ => Err(Error::UnexpectedResponse), - } + .await?, + ) } } @@ -1244,6 +1313,104 @@ impl PairedBitBox { mod tests { use super::*; + fn nested_response(response: pb::btc_response::Response) -> Response { + Response::Btc(pb::BtcResponse { + response: Some(response), + }) + } + + #[test] + fn one_shot_requests_preserve_variants_and_optional_fields() { + use pb::btc_pub_request::{Output, XPubType}; + use pb::btc_register_script_config_request::XPubType as RegistrationXpub; + use pb::btc_request::Request as BtcRequest; + + let coin = pb::BtcCoin::Tbtc; + let keypath = Keypath::try_from("m/1").unwrap(); + let config = make_script_config_simple(pb::btc_script_config::SimpleType::P2wpkh); + // The zero-valued Tpub must still be present in the oneof. + assert_eq!( + xpub_request(coin, &keypath, XPubType::Tpub, false), + Request::BtcPub(pb::BtcPubRequest { + coin: coin as _, + keypath: vec![1], + display: false, + output: Some(Output::XpubType(0)), + }), + ); + assert_eq!( + address_request(coin, &keypath, config.clone(), true), + Request::BtcPub(pb::BtcPubRequest { + coin: coin as _, + keypath: vec![1], + display: true, + output: Some(Output::ScriptConfig(config.clone())), + }), + ); + assert_eq!( + is_script_config_registered_request(coin, config.clone(), None), + Request::Btc(pb::BtcRequest { + request: Some(BtcRequest::IsScriptConfigRegistered( + pb::BtcIsScriptConfigRegisteredRequest { + registration: Some(pb::BtcScriptConfigRegistration { + coin: coin as _, + keypath: vec![], + script_config: Some(config.clone()), + }), + }, + )), + }), + ); + for (name, expected) in [(None, ""), (Some("wallet"), "wallet")] { + assert_eq!( + register_script_config_request( + coin, + config.clone(), + Some(&keypath), + RegistrationXpub::AutoXpubTpub, + name, + ), + Request::Btc(pb::BtcRequest { + request: Some(BtcRequest::RegisterScriptConfig( + pb::BtcRegisterScriptConfigRequest { + registration: Some(pb::BtcScriptConfigRegistration { + coin: coin as _, + keypath: vec![1], + script_config: Some(config.clone()), + }), + name: expected.into(), + xpub_type: RegistrationXpub::AutoXpubTpub as _, + }, + )), + }), + ); + } + } + + #[test] + fn registration_parsers_require_btc_reply_variants() { + use pb::btc_response::Response as BtcResponse; + + for is_registered in [false, true] { + let response = nested_response(BtcResponse::IsScriptConfigRegistered( + pb::BtcIsScriptConfigRegisteredResponse { is_registered }, + )); + assert_eq!(parse_is_registered(response.clone()).unwrap(), is_registered); + assert!(matches!(parse_registered(response), Err(Error::UnexpectedResponse))); + } + let response = nested_response(BtcResponse::Success(pb::BtcSuccess {})); + assert!(parse_registered(response.clone()).is_ok()); + assert!(matches!(parse_is_registered(response), Err(Error::UnexpectedResponse))); + assert!(matches!( + btc_response(Response::Btc(pb::BtcResponse { response: None })), + Err(Error::UnexpectedResponse) + )); + assert!(matches!( + parse_registered(Response::Success(pb::Success {})), + Err(Error::UnexpectedResponse) + )); + } + #[test] fn test_payload_from_pkscript() { use std::str::FromStr; From 4e33be82f7d5367a99e3a705f482014593b00b3b Mon Sep 17 00:00:00 2001 From: Trevor Arjeski Date: Thu, 26 Nov 2026 08:47:26 +0000 Subject: [PATCH 06/23] feat(noise): expose caller-keyed handshake primitives - Keep ephemeral generation and pairing state in the client. - Verify caller-supplied keys, pairing-code formatting, and encrypted exchanges with deterministic vectors. --- Cargo.toml | 1 + src/lib.rs | 33 +++--------- src/noise.rs | 138 +++++++++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 146 insertions(+), 26 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index ef7c017..c9d916e 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -40,6 +40,7 @@ tokio = { version = "1", optional = true, features = ["time"] } # For the base64 PSBT input/output in examples/btc_sign_psbt.rs. bitcoin = { version = "0.32", features = ["base64"] } futures-channel = "0.3" +noise-rust-crypto = "0.6" tokio = { version = "1", features = ["time", "macros", "rt", "fs"] } reqwest = "0.12" url = "2.5" diff --git a/src/lib.rs b/src/lib.rs index e02b4f2..b2ebf17 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -9,7 +9,7 @@ pub mod cardano; pub mod error; #[cfg(feature = "client")] pub mod eth; -mod noise; +pub mod noise; #[cfg(feature = "runtime")] pub mod runtime; #[cfg(feature = "simulator")] @@ -178,15 +178,8 @@ impl BitBox { k } }; - let mut host = HandshakeState::new( - noise_protocol::patterns::noise_xx(), - true, - b"Noise_XX_25519_ChaChaPoly_SHA256", - Some(host_static_key), - None, - None, - None, - ); + let mut host: HandshakeState = + noise::new_handshake(host_static_key, noise_rust_crypto::X25519::genkey())?; if self .communication @@ -201,30 +194,18 @@ impl BitBox { let host_handshake_1 = host.write_message_vec(b"").or(Err(Error::Noise))?; let bb02_handshake_1 = self.handshake_query(&host_handshake_1).await?; - host.read_message_vec(&bb02_handshake_1) - .or(Err(Error::Noise))?; - let host_handshake_2 = host.write_message_vec(b"").or(Err(Error::Noise))?; + let host_handshake_2 = noise::handshake_read_write(&mut host, &bb02_handshake_1)?; let bb02_handshake_2 = self.handshake_query(&host_handshake_2).await?; - let remote_static_pubkey = host.get_rs().ok_or(Error::Noise)?; + let (pairing_verification_required_by_device, remote_static_pubkey) = + noise::handshake_finalize(&host, &bb02_handshake_2)?; let pairing_verfication_required_by_app = !self .noise_config .read_config()? .contains_device_static_pubkey(&remote_static_pubkey); - let pairing_verification_required_by_device = bb02_handshake_2.as_slice() == [0x01]; if pairing_verfication_required_by_app || pairing_verification_required_by_device { - let format_hash = |h| { - let encoded = base32::encode(base32::Alphabet::Rfc4648 { padding: true }, h); - format!( - "{} {}\n{} {}", - &encoded[0..5], - &encoded[5..10], - &encoded[10..15], - &encoded[15..20] - ) - }; let handshake_hash: [u8; 32] = host.get_hash().try_into().or(Err(Error::Noise))?; - let pairing_code = format_hash(&handshake_hash); + let pairing_code = noise::pairing_code_from_hash(&handshake_hash); Ok(PairingBitBox::from( self.communication, diff --git a/src/noise.rs b/src/noise.rs index 22f26b6..bada9c9 100644 --- a/src/noise.rs +++ b/src/noise.rs @@ -1,5 +1,8 @@ // SPDX-License-Identifier: Apache-2.0 +use noise_protocol::{Cipher, HandshakeState, Hash, DH}; + +use crate::error::Error as ProtocolError; #[cfg(any(feature = "client", feature = "persistence"))] use crate::util::Threading; #[cfg(all(feature = "persistence", unix))] @@ -7,6 +10,65 @@ use std::os::unix::fs::{OpenOptionsExt, PermissionsExt}; #[cfg(any(feature = "client", feature = "persistence"))] use thiserror::Error; +const PROLOGUE: &[u8] = b"Noise_XX_25519_ChaChaPoly_SHA256"; + +pub fn new_handshake( + host_static_key: D::Key, + fresh_ephemeral_key: D::Key, +) -> Result, ProtocolError> { + if (D::name(), C::name(), H::name()) != ("25519", "ChaChaPoly", "SHA256") { + return Err(ProtocolError::Noise); + } + Ok(HandshakeState::new( + noise_protocol::patterns::noise_xx(), + true, + PROLOGUE, + Some(host_static_key), + Some(fresh_ephemeral_key), + None, + None, + )) +} + +pub fn handshake_read_write( + host: &mut HandshakeState, + device_message: &[u8], +) -> Result, ProtocolError> { + if host.completed() || host.is_write_turn() { + return Err(ProtocolError::Noise); + } + host.read_message_vec(device_message) + .map_err(|_| ProtocolError::Noise)?; + if host.completed() || !host.is_write_turn() { + return Err(ProtocolError::Noise); + } + host.write_message_vec(b"").map_err(|_| ProtocolError::Noise) +} + +pub fn handshake_finalize( + host: &HandshakeState, + device_ack: &[u8], +) -> Result<(bool, D::Pubkey), ProtocolError> { + if !host.completed() { + return Err(ProtocolError::Noise); + } + Ok(( + device_ack == [0x01], + host.get_rs().ok_or(ProtocolError::Noise)?, + )) +} + +pub fn pairing_code_from_hash(hash: &[u8; 32]) -> String { + let encoded = base32::encode(base32::Alphabet::Rfc4648 { padding: true }, hash); + format!( + "{} {}\n{} {}", + &encoded[0..5], + &encoded[5..10], + &encoded[10..15], + &encoded[15..20] + ) +} + #[cfg(any(feature = "client", feature = "persistence"))] #[derive(Error, Debug)] #[error("{0}")] @@ -262,3 +324,79 @@ mod tests { assert_eq!(mode(&target), 0o644); } } + +#[cfg(test)] +mod handshake_tests { + use super::*; + use noise_protocol::U8Array; + use noise_rust_crypto::{ChaCha20Poly1305, Sha256, Sha512, X25519}; + + #[test] + fn uses_supplied_keys_and_authenticates_device_message() { + let key = |byte| ::Key::new_with(byte); + let start = || new_handshake::(key(1), key(2)).unwrap(); + let mut device = HandshakeState::::new( + noise_protocol::patterns::noise_xx(), + false, + PROLOGUE, + Some(key(3)), + Some(key(4)), + None, + None, + ); + let mut host = start(); + assert!(matches!( + handshake_finalize(&host, &[]), + Err(ProtocolError::Noise) + )); + let first = host.write_message_vec(b"").unwrap(); + assert_eq!(first, X25519::pubkey(&key(2))); + device.read_message_vec(&first).unwrap(); + let reply = device.write_message_vec(b"").unwrap(); + + let mut bad_host = start(); + bad_host.write_message_vec(b"").unwrap(); + let mut tampered = reply.clone(); + *tampered.last_mut().unwrap() ^= 1; + assert!(matches!( + handshake_read_write(&mut bad_host, &tampered), + Err(ProtocolError::Noise) + )); + assert!(matches!( + handshake_finalize(&bad_host, &[1]), + Err(ProtocolError::Noise) + )); + + let last = handshake_read_write(&mut host, &reply).unwrap(); + device.read_message_vec(&last).unwrap(); + assert_eq!( + handshake_finalize(&host, &[1]).unwrap(), + (true, X25519::pubkey(&key(3))) + ); + assert!(!handshake_finalize(&host, &[0]).unwrap().0); + assert_eq!(host.get_hash(), device.get_hash()); + let (mut send, mut recv) = host.get_ciphers(); + let (mut device_recv, mut device_send) = device.get_ciphers(); + assert_eq!( + device_recv.decrypt_vec(&send.encrypt_vec(b"request")).unwrap(), + b"request" + ); + assert_eq!( + recv.decrypt_vec(&device_send.encrypt_vec(b"reply")).unwrap(), + b"reply" + ); + } + + #[test] + fn checks_protocol_suite_and_pairing_code() { + let key = || ::Key::new_with(1); + assert!(matches!( + new_handshake::(key(), key()), + Err(ProtocolError::Noise), + )); + assert_eq!( + pairing_code_from_hash(b"0123456789abcdef0123456789abcdef"), + "GAYTE MZUGU\n3DOOB ZMFRG" + ); + } +} From 03610121f8a7da18ac2a47d14f53043a8e4aff22 Mon Sep 17 00:00:00 2001 From: Trevor Arjeski Date: Thu, 26 Nov 2026 08:48:06 +0000 Subject: [PATCH 07/23] fix(u2f): expose framing and validate report boundaries - Port the final-sequence, payload-length, and error-propagation fixes from BitBoxSwiss/bitbox-api-rs#137. - Validate incoming continuation headers and preserve incremental whole-report decoding. - Read and write complete simulator reports over TCP. --- src/communication.rs | 4 +- src/lib.rs | 2 +- src/simulator.rs | 8 +-- src/u2fframing.rs | 165 +++++++++++++++++++++++++++++++++---------- 4 files changed, 137 insertions(+), 42 deletions(-) diff --git a/src/communication.rs b/src/communication.rs index 68474ee..1d1fbd3 100644 --- a/src/communication.rs +++ b/src/communication.rs @@ -22,6 +22,8 @@ pub enum Error { Read, #[error("u2f framing decoding error")] U2fDecode, + #[error("u2f framing encoding error")] + U2fEncode, #[error("error querying device info")] Info, #[error("firmware version {0} required")] @@ -66,7 +68,7 @@ impl U2fHidCommunication { impl ReadWrite for U2fHidCommunication { fn write(&self, msg: &[u8]) -> Result { let mut buf = [0u8; u2fframing::MAX_LEN]; - let size = self.u2fhid.encode(msg, &mut buf).unwrap(); + let size = self.u2fhid.encode(msg, &mut buf).or(Err(Error::U2fEncode))?; for chunk in buf[..size].chunks(64) { self.read_write.write(chunk)?; } diff --git a/src/lib.rs b/src/lib.rs index b2ebf17..2412497 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -21,7 +21,7 @@ pub mod antiklepto; mod communication; mod keypath; pub mod secp256k1; -mod u2fframing; +pub mod u2fframing; mod util; /// BitBox protobuf messages. diff --git a/src/simulator.rs b/src/simulator.rs index e53d304..3d85dc1 100644 --- a/src/simulator.rs +++ b/src/simulator.rs @@ -49,17 +49,17 @@ impl crate::util::Threading for TcpClient {} impl ReadWrite for TcpClient { fn write(&self, msg: &[u8]) -> Result { let mut stream = self.stream.lock().unwrap(); - stream.write(msg).map_err(|_| CommunicationError::Write) + stream.write_all(msg).map_err(|_| CommunicationError::Write)?; + Ok(msg.len()) } async fn read(&self) -> Result, CommunicationError> { let mut stream = self.stream.lock().unwrap(); let mut buffer = vec![0; 64]; - let n = stream - .read(&mut buffer) + stream + .read_exact(&mut buffer) .map_err(|_| CommunicationError::Read)?; - buffer.truncate(n); Ok(buffer) } } diff --git a/src/u2fframing.rs b/src/u2fframing.rs index a28aa2e..995152d 100644 --- a/src/u2fframing.rs +++ b/src/u2fframing.rs @@ -6,15 +6,18 @@ use byteorder::WriteBytesExt; use std::io; use std::io::Cursor; +const REPORT_LEN: usize = 64; const HEADER_INIT_LEN: usize = 7; const HEADER_CONT_LEN: usize = 5; +const PAYLOAD_INIT_LEN: usize = REPORT_LEN - HEADER_INIT_LEN; +const PAYLOAD_CONT_LEN: usize = REPORT_LEN - HEADER_CONT_LEN; // U2F specs: // With this approach, a message with a payload less or equal to (s - 7) may be sent as one packet. // A larger message is then divided into one or more continuation packets, starting with sequence // number 0, which then increments by one to a maximum of 127. // With a packet size of 64 bytes (max for full-speed devices), this means that the maximum message // payload length is 64 - 7 + 128 * (64 - 5) = 7609 bytes. -//pub const MAX_PAYLOAD_LEN: usize = 64 - HEADER_INIT_LEN + 128 * (64 - HEADER_CONT_LEN); +const MAX_PAYLOAD_LEN: usize = PAYLOAD_INIT_LEN + 128 * PAYLOAD_CONT_LEN; // This is the buffer size needed to fit the largest possible u2f package with headers pub const MAX_LEN: usize = 129 * 64; @@ -81,18 +84,22 @@ impl U2fHid { U2fHid { cid, cmd } } - fn get_encoded_len(len: u16) -> usize { - if len < 57 { - 64 - } else { - let len = len - 57; - 64 + 64 * ((59 + len - 1) / 59) as usize - } + fn get_encoded_len(len: usize) -> usize { + REPORT_LEN + * (1 + len + .saturating_sub(PAYLOAD_INIT_LEN) + .div_ceil(PAYLOAD_CONT_LEN)) } /// Encode function. pub fn encode(&self, mut message: &[u8], mut buf: &mut [u8]) -> io::Result { - let enc_len = Self::get_encoded_len(message.len() as u16); + if message.len() > MAX_PAYLOAD_LEN { + return Err(io::Error::new( + io::ErrorKind::InvalidInput, + "Message too long", + )); + } + let enc_len = Self::get_encoded_len(message.len()); if buf.len() < enc_len { return Err(std::io::Error::new( std::io::ErrorKind::InvalidInput, @@ -102,38 +109,39 @@ impl U2fHid { let len = encode_header_init(self.cid, self.cmd, message.len() as u16, buf)?; buf = &mut buf[len..]; - let len = usize::min(64 - len, message.len()); + let len = PAYLOAD_INIT_LEN.min(message.len()); let buf_slice = &mut buf[..len]; buf_slice.copy_from_slice(&message[..len]); message = &message[len..]; buf = &mut buf[len..]; - let mut seq = 0; + let mut seq = 0u8; while !message.is_empty() { - let len = encode_header_cont(self.cid, seq as u8, buf)?; + let len = encode_header_cont(self.cid, seq, buf)?; buf = &mut buf[len..]; - let len = usize::min(64 - len, message.len()); + let len = PAYLOAD_CONT_LEN.min(message.len()); let buf_slice = &mut buf[..len]; buf_slice.copy_from_slice(&message[..len]); buf = &mut buf[len..]; message = &message[len..]; seq += 1; - if seq > 127 { - return Err(std::io::Error::new( - std::io::ErrorKind::InvalidInput, - "More frames than allowed", - )); - } } Ok(enc_len) } - /// Decode function. Will fail in case CID and CMD doesn't match stored values. - pub fn decode(&self, mut buf: &[u8]) -> io::Result>> { + /// Decode a message from whole reports, ignoring extra reports after the message. + /// Returns `Ok(None)` if more whole reports are needed. + pub fn decode(&self, buf: &[u8]) -> io::Result>> { + if buf.is_empty() || !buf.chunks_exact(REPORT_LEN).remainder().is_empty() { + return Err(io::Error::new( + io::ErrorKind::UnexpectedEof, + "Incomplete U2F report", + )); + } let (cid, cmd, len) = parse_header(buf)?; if cid != self.cid { return Err(std::io::Error::new( @@ -147,24 +155,33 @@ impl U2fHid { "Wrong CMD", )); } - if buf.len() < Self::get_encoded_len(len) { - // Need more bytes. - return Ok(None); + let len = usize::from(len); + if len > MAX_PAYLOAD_LEN { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + "Message too long", + )); } - let mut res = Vec::with_capacity(len as usize); - let mut left = len as usize; - - let len = usize::min(57, len as usize); - res.extend_from_slice(&buf[HEADER_INIT_LEN..HEADER_INIT_LEN + len]); - buf = &buf[HEADER_INIT_LEN + len..]; - left -= len; + let enc_len = Self::get_encoded_len(len); + if buf.len() < enc_len { + return Ok(None); + } - while left > 0 { - let len = usize::min(59, left); - res.extend_from_slice(&buf[HEADER_CONT_LEN..HEADER_CONT_LEN + len]); - buf = &buf[HEADER_CONT_LEN + len..]; - left -= len; + let mut res = Vec::with_capacity(len); + res.extend_from_slice(&buf[HEADER_INIT_LEN..HEADER_INIT_LEN + PAYLOAD_INIT_LEN.min(len)]); + for (seq, report) in buf[..enc_len].chunks_exact(REPORT_LEN).skip(1).enumerate() { + if report[..4] != buf[..4] { + return Err(io::Error::new(io::ErrorKind::InvalidData, "Wrong CID")); + } + if report[4] != seq as u8 { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + "Wrong continuation sequence", + )); + } + let take = PAYLOAD_CONT_LEN.min(len - res.len()); + res.extend_from_slice(&report[HEADER_CONT_LEN..HEADER_CONT_LEN + take]); } Ok(Some(res)) } @@ -173,6 +190,24 @@ impl U2fHid { #[cfg(test)] mod tests { use super::*; + + #[test] + fn test_u2fhid_payload_length_limit() { + let codec = U2fHid::with_cid(0xEEEEEEEE, 0x55); + let mut buf = [0xAA; MAX_LEN]; + for len in [7610, 65536] { + assert_eq!( + codec.encode(&vec![0; len], &mut buf).unwrap_err().kind(), + io::ErrorKind::InvalidInput, + ); + assert!(buf.iter().all(|&byte| byte == 0xAA)); + } + assert_eq!( + codec.encode(&[0; 58], &mut buf[..64]).unwrap_err().kind(), + io::ErrorKind::InvalidInput, + ); + } + #[test] fn test_u2fhid_encode_single() { let codec = U2fHid::with_cid(0xEEEEEEEE, 0x55); @@ -199,6 +234,18 @@ mod tests { assert_eq!(&data[..len], &expect[..]); } + #[test] + fn test_u2fhid_encode_last_continuation_frame() { + let codec = U2fHid::with_cid(0xEEEEEEEE, 0x55); + for len in [7551, 7609] { + let payload = vec![0x42; len]; + let mut buf = [0; MAX_LEN]; + assert_eq!(codec.encode(&payload, &mut buf).unwrap(), MAX_LEN); + assert_eq!(buf[128 * 64 + 4], 127); + assert_eq!(codec.decode(&buf).unwrap().unwrap(), payload); + } + } + #[test] fn test_u2fhid_decode_single() { let codec = U2fHid::with_cid(0xEEEEEEEE, 0x55); @@ -220,4 +267,50 @@ mod tests { let data = codec.decode(&raw[..]).unwrap().unwrap(); assert_eq!(&data[..], &payload[..]); } + + #[test] + fn test_u2fhid_decode_incomplete_reports() { + let codec = U2fHid::with_cid(0xEEEEEEEE, 0x55); + let mut raw = [0u8; 128]; + raw[..7].copy_from_slice(b"\xEE\xEE\xEE\xEE\x55\x00\x3A"); + raw[64..69].copy_from_slice(b"\xEE\xEE\xEE\xEE\x00"); + assert_eq!(codec.decode(&raw[..64]).unwrap(), None); + for len in [0, 6, 63, 64 + 4, 127] { + assert_eq!( + codec.decode(&raw[..len]).unwrap_err().kind(), + io::ErrorKind::UnexpectedEof, + ); + } + } + + #[test] + fn test_u2fhid_decode_invalid_continuations() { + let codec = U2fHid::with_cid(0xEEEEEEEE, 0x55); + let mut raw = [0u8; 256]; + raw[..7].copy_from_slice(b"\xEE\xEE\xEE\xEE\x55\x00\x75"); + raw[64..69].copy_from_slice(b"\xEE\xEE\xEE\xEE\x00"); + raw[128..133].copy_from_slice(b"\xEE\xEE\xEE\xEE\x01"); + assert_eq!(codec.decode(&raw[..128]).unwrap(), None); + assert_eq!(codec.decode(&raw).unwrap(), Some(vec![0; 117])); + + for (offset, bad_byte) in [(64, 0xFF), (68, 1), (128, 0xFF), (132, 0), (132, 128)] { + let mut malformed = raw; + malformed[offset] = bad_byte; + assert_eq!( + codec.decode(&malformed).unwrap_err().kind(), + io::ErrorKind::InvalidData, + ); + } + } + + #[test] + fn test_u2fhid_decode_oversized_announcement() { + let codec = U2fHid::with_cid(0xEEEEEEEE, 0x55); + let mut raw = [0u8; 64]; + raw[..7].copy_from_slice(b"\xEE\xEE\xEE\xEE\x55\x1D\xBA"); + assert_eq!( + codec.decode(&raw).unwrap_err().kind(), + io::ErrorKind::InvalidData, + ); + } } From fe4b05c0c2e26fb504d6d8a1f87f5102bbad5497 Mon Sep 17 00:00:00 2001 From: Trevor Arjeski Date: Thu, 26 Nov 2026 08:48:34 +0000 Subject: [PATCH 08/23] feat(btc): expose signing primitives and payloads - Share signing requests, reply parsers, and firmware gates without moving the client loop. - Expose borrowed paths and reusable PSBT payloads; return an error for unsupported unforced scripts. --- src/btc.rs | 781 +++++++++++++++++++++++++++++++++++-------------- src/keypath.rs | 17 +- src/lib.rs | 9 +- 3 files changed, 572 insertions(+), 235 deletions(-) diff --git a/src/btc.rs b/src/btc.rs index 13f8aae..14517df 100644 --- a/src/btc.rs +++ b/src/btc.rs @@ -85,10 +85,11 @@ pub struct TxInput { } impl TxInput { - fn get_prev_tx(&self) -> Result<&PrevTx, Error> { - self.prev_tx.as_ref().ok_or(Error::BtcSign( - "input's previous transaction required but missing".into(), - )) + /// Returns the previous transaction when it is available. + pub fn get_prev_tx(&self) -> Result<&PrevTx, Error> { + self.prev_tx.as_ref().ok_or_else(|| { + Error::BtcSign("input's previous transaction required but missing".into()) + }) } } @@ -250,7 +251,9 @@ impl From for PsbtError { } } -enum OurKey { +/// The wallet's signing key and derivation path for a PSBT input or output. +#[derive(Debug)] +pub enum OurKey { Segwit(bitcoin::secp256k1::PublicKey, Keypath), TaprootInternal(Keypath), TaprootScript( @@ -261,11 +264,9 @@ enum OurKey { } impl OurKey { - fn keypath(&self) -> Keypath { + fn keypath(&self) -> &Keypath { match self { - OurKey::Segwit(_, kp) => kp.clone(), - OurKey::TaprootInternal(kp) => kp.clone(), - OurKey::TaprootScript(_, _, kp) => kp.clone(), + OurKey::Segwit(_, kp) | OurKey::TaprootInternal(kp) | OurKey::TaprootScript(_, _, kp) => kp, } } } @@ -379,50 +380,33 @@ fn find_our_key( fn script_config_from_utxo( output: &bitcoin::TxOut, - keypath: Keypath, + keypath: &Keypath, redeem_script: Option<&bitcoin::ScriptBuf>, - _witness_script: Option<&bitcoin::ScriptBuf>, ) -> Result { - let keypath = keypath.hardened_prefix(); - if output.script_pubkey.is_p2wpkh() { - return Ok(pb::BtcScriptConfigWithKeypath { - script_config: Some(make_script_config_simple( - pb::btc_script_config::SimpleType::P2wpkh, - )), - keypath: keypath.to_vec(), - }); - } - let redeem_script_is_p2wpkh = redeem_script.map(|s| s.is_p2wpkh()).unwrap_or(false); - if output.script_pubkey.is_p2sh() && redeem_script_is_p2wpkh { - return Ok(pb::BtcScriptConfigWithKeypath { - script_config: Some(make_script_config_simple( - pb::btc_script_config::SimpleType::P2wpkhP2sh, - )), - keypath: keypath.to_vec(), - }); - } - if output.script_pubkey.is_p2tr() { - return Ok(pb::BtcScriptConfigWithKeypath { - script_config: Some(make_script_config_simple( - pb::btc_script_config::SimpleType::P2tr, - )), - keypath: keypath.to_vec(), - }); - } - // Check for segwit multisig (p2wsh or p2wsh-p2sh). - let redeem_script_is_p2wsh = redeem_script.map(|s| s.is_p2wsh()).unwrap_or(false); - let is_p2wsh_p2sh = output.script_pubkey.is_p2sh() && redeem_script_is_p2wsh; - if output.script_pubkey.is_p2wsh() || is_p2wsh_p2sh { - todo!(); - } - Err(PsbtError::UnknownOutputType) + use pb::btc_script_config::SimpleType; + let script = &output.script_pubkey; + let simple_type = if script.is_p2wpkh() { + SimpleType::P2wpkh + } else if script.is_p2sh() && redeem_script.is_some_and(|script| script.is_p2wpkh()) { + SimpleType::P2wpkhP2sh + } else if script.is_p2tr() { + SimpleType::P2tr + } else { + return Err(PsbtError::UnknownOutputType); + }; + Ok(pb::BtcScriptConfigWithKeypath { + script_config: Some(make_script_config_simple(simple_type)), + keypath: keypath.hardened_prefix().to_vec(), + }) } -struct PsbtTransaction { - transaction: Transaction, - our_keys: Vec, - output_script_configs: Vec, - output_script_config_indices: Vec>, +/// A transaction lowered for signing, with keys in input order and config indices in output order. +#[derive(Debug)] +pub struct PsbtTransaction { + pub transaction: Transaction, + pub our_keys: Vec, + pub output_script_configs: Vec, + pub output_script_config_indices: Vec>, } impl Transaction { @@ -453,7 +437,6 @@ impl Transaction { utxo, our_key.keypath(), psbt_input.redeem_script.as_ref(), - psbt_input.witness_script.as_ref(), )?, ) }; @@ -463,7 +446,7 @@ impl Transaction { prev_out_index: tx_input.previous_output.vout, prev_out_value: utxo.value.to_sat(), sequence: tx_input.sequence.to_consensus_u32(), - keypath: our_key.keypath(), + keypath: our_key.keypath().clone(), script_config_index: script_config_index as _, prev_tx: psbt_input.non_witness_utxo.as_ref().map(PrevTx::from), }); @@ -484,7 +467,6 @@ impl Transaction { tx_output, our_key.keypath(), psbt_output.redeem_script.as_ref(), - psbt_output.witness_script.as_ref(), )? }; let same_account = is_same_account(&script_configs, &script_config)?; @@ -494,7 +476,7 @@ impl Transaction { let script_config_index = find_or_add_script_config(&mut script_configs, script_config); outputs.push(TxOutput::Internal(TxInternalOutput { - keypath: our_key.keypath(), + keypath: our_key.keypath().clone(), value: tx_output.value.to_sat(), script_config_index: script_config_index as _, })); @@ -503,7 +485,7 @@ impl Transaction { let output_script_config_index = find_or_add_script_config(&mut output_script_configs, script_config); outputs.push(TxOutput::Internal(TxInternalOutput { - keypath: our_key.keypath(), + keypath: our_key.keypath().clone(), value: tx_output.value.to_sat(), // Ignored when output_script_config_index is present. script_config_index: 0, @@ -554,7 +536,8 @@ pub struct KeyOriginInfo { pub xpub: bitcoin::bip32::Xpub, } -fn convert_xpub(xpub: &bitcoin::bip32::Xpub) -> pb::XPub { +/// Converts an extended public key to the device's protobuf representation. +pub fn convert_xpub(xpub: &bitcoin::bip32::Xpub) -> pb::XPub { pb::XPub { depth: vec![xpub.depth], parent_fingerprint: xpub.parent_fingerprint[..].to_vec(), @@ -629,7 +612,8 @@ fn is_taproot_policy(script_config: &pb::BtcScriptConfigWithKeypath) -> bool { ) } -fn is_schnorr(script_config: &pb::BtcScriptConfigWithKeypath) -> bool { +/// Returns whether the script config uses Schnorr signatures. +pub fn is_schnorr(script_config: &pb::BtcScriptConfigWithKeypath) -> bool { is_taproot_simple(script_config) | is_taproot_policy(script_config) } @@ -795,6 +779,222 @@ pub fn parse_registered(response: Response) -> Result<(), Error> { } } +/// Builds the first request of a transaction signing exchange. +pub fn sign_init_request( + coin: pb::BtcCoin, + tx: &Transaction, + output_script_configs: &[pb::BtcScriptConfigWithKeypath], + format_unit: pb::btc_sign_init_request::FormatUnit, +) -> Request { + Request::BtcSignInit(pb::BtcSignInitRequest { + coin: coin as _, + script_configs: tx.script_configs.clone(), + output_script_configs: output_script_configs.to_vec(), + version: tx.version, + num_inputs: tx.inputs.len() as _, + num_outputs: tx.outputs.len() as _, + locktime: tx.locktime, + format_unit: format_unit as _, + contains_silent_payment_outputs: false, + }) +} + +/// Builds a transaction input request, with a host commitment when using Anti-Klepto. +pub fn sign_input_request(input: &TxInput, host_nonce_commitment: Option<[u8; 32]>) -> Request { + Request::BtcSignInput(pb::BtcSignInputRequest { + prev_out_hash: input.prev_out_hash.clone(), + prev_out_index: input.prev_out_index, + prev_out_value: input.prev_out_value, + sequence: input.sequence, + keypath: input.keypath.to_vec(), + script_config_index: input.script_config_index, + host_nonce_commitment: host_nonce_commitment.map(|commitment| { + pb::AntiKleptoHostNonceCommitment { + commitment: commitment.to_vec(), + } + }), + }) +} + +/// Builds a transaction output request. The separate config index applies only to internal outputs. +pub fn sign_output_request(output: &TxOutput, output_script_config_index: Option) -> Request { + Request::BtcSignOutput(match output { + TxOutput::Internal(output) => pb::BtcSignOutputRequest { + ours: true, + value: output.value, + keypath: output.keypath.to_vec(), + script_config_index: output.script_config_index, + output_script_config_index, + ..Default::default() + }, + TxOutput::External(output) => pb::BtcSignOutputRequest { + ours: false, + value: output.value, + r#type: output.payload.output_type as _, + payload: output.payload.data.clone(), + ..Default::default() + }, + }) +} + +/// Builds a request describing a previous transaction. +pub fn prevtx_init_request(tx: &PrevTx) -> Request { + btc_request(pb::btc_request::Request::PrevtxInit(pb::BtcPrevTxInitRequest { + version: tx.version, + num_inputs: tx.inputs.len() as _, + num_outputs: tx.outputs.len() as _, + locktime: tx.locktime, + })) +} + +/// Builds a request carrying a previous transaction's input. +pub fn prevtx_input_request(input: &PrevTxInput) -> Request { + btc_request(pb::btc_request::Request::PrevtxInput(pb::BtcPrevTxInputRequest { + prev_out_hash: input.prev_out_hash.clone(), + prev_out_index: input.prev_out_index, + signature_script: input.signature_script.clone(), + sequence: input.sequence, + })) +} + +/// Builds a request carrying a previous transaction's output. +pub fn prevtx_output_request(output: &PrevTxOutput) -> Request { + btc_request(pb::btc_request::Request::PrevtxOutput(pb::BtcPrevTxOutputRequest { + value: output.value, + pubkey_script: output.pubkey_script.clone(), + })) +} + +/// Reveals the host nonce to request an Anti-Klepto signature. +pub fn antiklepto_signature_request(host_nonce: &[u8; 32]) -> Request { + btc_request(pb::btc_request::Request::AntikleptoSignature( + pb::AntiKleptoSignatureRequest { + host_nonce: host_nonce.to_vec(), + }, + )) +} + +/// Starts a message signing exchange with an Anti-Klepto host commitment. +pub fn sign_message_request( + coin: pb::BtcCoin, + script_config: pb::BtcScriptConfigWithKeypath, + message: &[u8], + host_nonce_commitment: [u8; 32], +) -> Request { + btc_request(pb::btc_request::Request::SignMessage( + pb::BtcSignMessageRequest { + coin: coin as _, + script_config: Some(script_config), + msg: message.to_vec(), + host_nonce_commitment: Some(pb::AntiKleptoHostNonceCommitment { + commitment: host_nonce_commitment.to_vec(), + }), + }, + )) +} + +/// Parses either a top-level or BTC-nested signing reply without interpreting its phase. +pub fn parse_sign_next(response: Response) -> Result { + match response { + Response::BtcSignNext(next) => Ok(next), + Response::Btc(pb::BtcResponse { + response: Some(pb::btc_response::Response::SignNext(next)), + }) => Ok(next), + _ => Err(Error::UnexpectedResponse), + } +} + +/// Extracts the device's Anti-Klepto commitment in a message signing exchange. +pub fn parse_signer_commitment(response: Response) -> Result, Error> { + match btc_response(response)? { + pb::btc_response::Response::AntikleptoSignerCommitment(response) => Ok(response.commitment), + _ => Err(Error::UnexpectedResponse), + } +} + +fn message_signature_bytes(response: Response) -> Result, Error> { + match btc_response(response)? { + pb::btc_response::Response::SignMessage(response) => Ok(response.signature), + _ => Err(Error::UnexpectedResponse), + } +} + +fn format_validated_message_signature(mut signature: Vec) -> SignMessageSignature { + let recid = signature[64]; + signature.truncate(64); + let mut electrum_sig65 = Vec::with_capacity(65); + // Electrum uses 27 plus the recovery ID, plus 4 for compressed pubkeys. + electrum_sig65.push(27 + 4 + recid); + electrum_sig65.extend_from_slice(&signature); + SignMessageSignature { + sig: signature, + recid, + electrum_sig65, + } +} + +/// Parses and validates a recoverable message signature's encoding. +/// +/// This does not verify the Anti-Klepto nonce contribution. +pub fn parse_message_signature(response: Response) -> Result { + let signature = message_signature_bytes(response)?; + crate::secp256k1::validate_signature_recoverable(&signature) + .map_err(crate::antiklepto::Error::from)?; + Ok(format_validated_message_signature(signature)) +} + +/// Checks that the firmware matches the specified semver requirement. +pub fn validate_version( + firmware_version: &semver::Version, + comparison: &'static str, +) -> Result<(), Error> { + if semver::VersionReq::parse(comparison) + .map_err(|_| Error::Unknown)? + .matches(firmware_version) + { + Ok(()) + } else { + Err(Error::Version(comparison)) + } +} + +/// Checks output index cardinality and the firmware requirements for raw transaction signing. +/// +/// An empty `output_script_config_indices` slice means no output has a separate config index. +pub fn validate_signing( + firmware_version: &semver::Version, + transaction: &Transaction, + output_script_configs: &[pb::BtcScriptConfigWithKeypath], + output_script_config_indices: &[Option], +) -> Result<(), Error> { + if !output_script_config_indices.is_empty() + && output_script_config_indices.len() != transaction.outputs.len() + { + return Err(Error::BtcSign( + "output script config indices must match transaction outputs".into(), + )); + } + validate_version(firmware_version, ">=9.4.0")?; // Anti-Klepto + if transaction + .script_configs + .iter() + .chain(output_script_configs) + .any(is_taproot_simple) + { + validate_version(firmware_version, ">=9.10.0")?; + } + if transaction.outputs.iter().any(|output| { + matches!( + output, + TxOutput::External(tx_output) + if tx_output.payload.output_type == pb::BtcOutputType::OpReturn + ) + }) { + validate_version(firmware_version, ">=9.24.0")?; + } + Ok(()) +} + #[cfg(feature = "client")] impl PairedBitBox { /// Retrieves an xpub. For non-standard keypaths, a warning is displayed on the BitBox even if @@ -887,20 +1087,7 @@ impl PairedBitBox { } async fn get_next_response(&self, request: Request) -> Result { - match self.query_proto(request).await? { - Response::BtcSignNext(next_response) => Ok(next_response), - _ => Err(Error::UnexpectedResponse), - } - } - - async fn get_next_response_nested( - &self, - request: pb::btc_request::Request, - ) -> Result { - match self.query_proto_btc(request).await? { - pb::btc_response::Response::SignNext(next_response) => Ok(next_response), - _ => Err(Error::UnexpectedResponse), - } + parse_sign_next(self.query_proto(request).await?) } /// Sign a Bitcoin transaction. Returns one 64 byte signature (compact serlization of the R and @@ -924,46 +1111,22 @@ impl PairedBitBox { output_script_config_indices: &[Option], format_unit: pb::btc_sign_init_request::FormatUnit, ) -> Result>, Error> { - if !output_script_config_indices.is_empty() - && output_script_config_indices.len() != transaction.outputs.len() - { - return Err(Error::BtcSign( - "output script config indices must match transaction outputs".into(), - )); - } - self.validate_version(">=9.4.0")?; // anti-klepto since 9.4.0 - if transaction - .script_configs - .iter() - .chain(output_script_configs) - .any(is_taproot_simple) - { - self.validate_version(">=9.10.0")?; // taproot since 9.10.0 - } - if transaction.outputs.iter().any(|output| { - matches!( - output, - TxOutput::External(tx_output) - if tx_output.payload.output_type == pb::BtcOutputType::OpReturn - ) - }) { - self.validate_version(">=9.24.0")?; - } + validate_signing( + self.version(), + transaction, + output_script_configs, + output_script_config_indices, + )?; - let mut sigs: Vec> = Vec::new(); + let mut sigs = Vec::with_capacity(transaction.inputs.len()); let mut next_response = self - .get_next_response(Request::BtcSignInit(pb::BtcSignInitRequest { - coin: coin as _, - script_configs: transaction.script_configs.clone(), - output_script_configs: output_script_configs.to_vec(), - version: transaction.version, - num_inputs: transaction.inputs.len() as _, - num_outputs: transaction.outputs.len() as _, - locktime: transaction.locktime, - format_unit: format_unit as _, - contains_silent_payment_outputs: false, - })) + .get_next_response(sign_init_request( + coin, + transaction, + output_script_configs, + format_unit, + )) .await?; let mut is_inputs_pass2 = false; @@ -985,19 +1148,10 @@ impl PairedBitBox { None }; next_response = self - .get_next_response(Request::BtcSignInput(pb::BtcSignInputRequest { - prev_out_hash: tx_input.prev_out_hash.clone(), - prev_out_index: tx_input.prev_out_index, - prev_out_value: tx_input.prev_out_value, - sequence: tx_input.sequence, - keypath: tx_input.keypath.to_vec(), - script_config_index: tx_input.script_config_index, - host_nonce_commitment: host_nonce.as_ref().map(|host_nonce| { - pb::AntiKleptoHostNonceCommitment { - commitment: crate::antiklepto::host_commit(host_nonce).to_vec(), - } - }), - })) + .get_next_response(sign_input_request( + tx_input, + host_nonce.as_ref().map(|nonce| crate::antiklepto::host_commit(nonce)), + )) .await?; if let Some(host_nonce) = host_nonce { @@ -1010,13 +1164,7 @@ impl PairedBitBox { next_response.anti_klepto_signer_commitment { next_response = self - .get_next_response_nested( - pb::btc_request::Request::AntikleptoSignature( - pb::AntiKleptoSignatureRequest { - host_nonce: host_nonce.to_vec(), - }, - ), - ) + .get_next_response(antiklepto_signature_request(&host_nonce)) .await?; if !next_response.has_signature { return Err(Error::UnexpectedResponse); @@ -1035,7 +1183,7 @@ impl PairedBitBox { if !next_response.has_signature { return Err(Error::UnexpectedResponse); } - sigs.push(next_response.signature.clone()); + sigs.push(std::mem::take(&mut next_response.signature)); } if input_index == transaction.inputs.len() - 1 { is_inputs_pass2 = true @@ -1044,16 +1192,7 @@ impl PairedBitBox { pb::btc_sign_next_response::Type::PrevtxInit => { let prevtx: &PrevTx = transaction.inputs[next_response.index as usize].get_prev_tx()?; - next_response = self - .get_next_response_nested(pb::btc_request::Request::PrevtxInit( - pb::BtcPrevTxInitRequest { - version: prevtx.version, - num_inputs: prevtx.inputs.len() as _, - num_outputs: prevtx.outputs.len() as _, - locktime: prevtx.locktime, - }, - )) - .await?; + next_response = self.get_next_response(prevtx_init_request(prevtx)).await?; } pb::btc_sign_next_response::Type::PrevtxInput => { let prevtx: &PrevTx = @@ -1061,14 +1200,7 @@ impl PairedBitBox { let prevtx_input: &PrevTxInput = &prevtx.inputs[next_response.prev_index as usize]; next_response = self - .get_next_response_nested(pb::btc_request::Request::PrevtxInput( - pb::BtcPrevTxInputRequest { - prev_out_hash: prevtx_input.prev_out_hash.clone(), - prev_out_index: prevtx_input.prev_out_index, - signature_script: prevtx_input.signature_script.clone(), - sequence: prevtx_input.sequence, - }, - )) + .get_next_response(prevtx_input_request(prevtx_input)) .await?; } pb::btc_sign_next_response::Type::PrevtxOutput => { @@ -1077,12 +1209,7 @@ impl PairedBitBox { let prevtx_output: &PrevTxOutput = &prevtx.outputs[next_response.prev_index as usize]; next_response = self - .get_next_response_nested(pb::btc_request::Request::PrevtxOutput( - pb::BtcPrevTxOutputRequest { - value: prevtx_output.value, - pubkey_script: prevtx_output.pubkey_script.clone(), - }, - )) + .get_next_response(prevtx_output_request(prevtx_output)) .await?; } pb::btc_sign_next_response::Type::Output => { @@ -1092,28 +1219,9 @@ impl PairedBitBox { .get(output_index) .copied() .flatten(); - let request: Request = match tx_output { - TxOutput::Internal(output) => { - Request::BtcSignOutput(pb::BtcSignOutputRequest { - ours: true, - value: output.value, - keypath: output.keypath.to_vec(), - script_config_index: output.script_config_index, - output_script_config_index, - ..Default::default() - }) - } - TxOutput::External(output) => { - Request::BtcSignOutput(pb::BtcSignOutputRequest { - ours: false, - value: output.value, - r#type: output.payload.output_type as _, - payload: output.payload.data.clone(), - ..Default::default() - }) - } - }; - next_response = self.get_next_response(request).await?; + next_response = self + .get_next_response(sign_output_request(tx_output, output_script_config_index)) + .await?; } pb::btc_sign_next_response::Type::Done => break, pb::btc_sign_next_response::Type::HostNonce => { @@ -1207,51 +1315,22 @@ impl PairedBitBox { self.validate_version(">=9.5.0")?; let host_nonce = crate::antiklepto::gen_host_nonce()?; - let request = pb::BtcSignMessageRequest { - coin: coin as _, - script_config: Some(script_config), - msg: msg.to_vec(), - host_nonce_commitment: Some(pb::AntiKleptoHostNonceCommitment { - commitment: crate::antiklepto::host_commit(&host_nonce).to_vec(), - }), - }; - - let response = self - .query_proto_btc(pb::btc_request::Request::SignMessage(request)) - .await?; - let signer_commitment = match response { - pb::btc_response::Response::AntikleptoSignerCommitment( - pb::AntiKleptoSignerCommitment { commitment }, - ) => commitment, - _ => return Err(Error::UnexpectedResponse), - }; - - let request = pb::AntiKleptoSignatureRequest { - host_nonce: host_nonce.to_vec(), - }; - - let response = self - .query_proto_btc(pb::btc_request::Request::AntikleptoSignature(request)) - .await?; - let signature = match response { - pb::btc_response::Response::SignMessage(pb::BtcSignMessageResponse { signature }) => { - signature - } - _ => return Err(Error::UnexpectedResponse), - }; + let signer_commitment = parse_signer_commitment( + self.query_proto(sign_message_request( + coin, + script_config, + msg, + crate::antiklepto::host_commit(&host_nonce), + )) + .await?, + )?; + let signature = message_signature_bytes( + self.query_proto(antiklepto_signature_request(&host_nonce)) + .await?, + )?; + // The nonce verifier also validates the encoding before formatting. crate::antiklepto::verify_recoverable_ecdsa(&host_nonce, &signer_commitment, &signature)?; - - let sig = signature[..64].to_vec(); - let recid = signature[64]; - let compressed: u8 = 4; // BitBox02 uses only compressed pubkeys - let sig65: u8 = 27 + compressed + recid; - let mut electrum_sig65 = vec![sig65]; - electrum_sig65.extend_from_slice(&sig); - Ok(SignMessageSignature { - sig, - recid, - electrum_sig65, - }) + Ok(format_validated_message_signature(signature)) } /// Before a multisig or policy script config can be used to display receive addresses or sign @@ -1411,6 +1490,272 @@ mod tests { )); } + #[test] + fn signing_requests_preserve_payloads_and_presence() { + use pb::btc_request::Request as BtcRequest; + use pb::btc_sign_init_request::FormatUnit; + + let coin = pb::BtcCoin::Tbtc; + let config = pb::BtcScriptConfigWithKeypath { + script_config: Some(make_script_config_simple(pb::btc_script_config::SimpleType::P2wpkh)), + keypath: vec![1, 2, 3], + }; + let keypath = Keypath::try_from("m/7").unwrap(); + let prevtx = PrevTx { + version: 1, + locktime: 9, + inputs: vec![PrevTxInput { + prev_out_hash: vec![1; 32], + prev_out_index: 2, + sequence: 3, + signature_script: vec![4], + }], + outputs: vec![PrevTxOutput { + value: 500, + pubkey_script: vec![6], + }], + }; + let tx = Transaction { + version: 2, + locktime: 42, + script_configs: vec![config.clone()], + inputs: vec![TxInput { + prev_out_hash: vec![7; 32], + prev_out_index: 8, + prev_out_value: 900, + sequence: 10, + keypath: keypath.clone(), + script_config_index: 11, + prev_tx: Some(prevtx), + }], + outputs: vec![ + TxOutput::Internal(TxInternalOutput { + keypath, + value: 100, + script_config_index: 12, + }), + TxOutput::External(TxExternalOutput { + payload: Payload { + output_type: pb::BtcOutputType::P2wpkh, + data: vec![13; 20], + }, + value: 200, + }), + ], + }; + let output_config = pb::BtcScriptConfigWithKeypath { + keypath: vec![1, 2, 4], + ..config.clone() + }; + assert_eq!( + sign_init_request(coin, &tx, std::slice::from_ref(&output_config), FormatUnit::Sat), + Request::BtcSignInit(pb::BtcSignInitRequest { + coin: coin as _, + script_configs: vec![config.clone()], + output_script_configs: vec![output_config], + version: 2, + num_inputs: 1, + num_outputs: 2, + locktime: 42, + format_unit: FormatUnit::Sat as _, + contains_silent_payment_outputs: false, + }), + ); + let commitment = [14; 32]; + for host_commitment in [None, Some(commitment)] { + assert_eq!( + sign_input_request(&tx.inputs[0], host_commitment), + Request::BtcSignInput(pb::BtcSignInputRequest { + prev_out_hash: vec![7; 32], + prev_out_index: 8, + prev_out_value: 900, + sequence: 10, + keypath: vec![7], + script_config_index: 11, + host_nonce_commitment: host_commitment.map(|_| { + pb::AntiKleptoHostNonceCommitment { commitment: vec![14; 32] } + }), + }), + ); + } + for index in [None, Some(0)] { + assert_eq!( + sign_output_request(&tx.outputs[0], index), + Request::BtcSignOutput(pb::BtcSignOutputRequest { + ours: true, + value: 100, + keypath: vec![7], + script_config_index: 12, + output_script_config_index: index, + ..Default::default() + }), + ); + } + assert_eq!( + sign_output_request(&tx.outputs[1], Some(0)), + Request::BtcSignOutput(pb::BtcSignOutputRequest { + r#type: pb::BtcOutputType::P2wpkh as _, + payload: vec![13; 20], + value: 200, + ..Default::default() + }), + ); + + let nested = |request| Request::Btc(pb::BtcRequest { request: Some(request) }); + let prevtx = tx.inputs[0].get_prev_tx().unwrap(); + assert_eq!( + prevtx_init_request(prevtx), + nested(BtcRequest::PrevtxInit(pb::BtcPrevTxInitRequest { + version: 1, + num_inputs: 1, + num_outputs: 1, + locktime: 9, + })), + ); + assert_eq!( + prevtx_input_request(&prevtx.inputs[0]), + nested(BtcRequest::PrevtxInput(pb::BtcPrevTxInputRequest { + prev_out_hash: vec![1; 32], + prev_out_index: 2, + sequence: 3, + signature_script: vec![4], + })), + ); + assert_eq!( + prevtx_output_request(&prevtx.outputs[0]), + nested(BtcRequest::PrevtxOutput(pb::BtcPrevTxOutputRequest { + value: 500, + pubkey_script: vec![6], + })), + ); + assert_eq!( + sign_message_request(coin, config.clone(), b"test", commitment), + nested(BtcRequest::SignMessage(pb::BtcSignMessageRequest { + coin: coin as _, + script_config: Some(config), + msg: b"test".to_vec(), + host_nonce_commitment: Some(pb::AntiKleptoHostNonceCommitment { + commitment: vec![14; 32], + }), + })), + ); + assert_eq!( + antiklepto_signature_request(&[15; 32]), + nested(BtcRequest::AntikleptoSignature(pb::AntiKleptoSignatureRequest { + host_nonce: vec![15; 32], + })), + ); + } + + #[test] + fn sign_next_accepts_both_response_nestings() { + use pb::btc_response::Response as BtcResponse; + let next = pb::BtcSignNextResponse { + r#type: pb::btc_sign_next_response::Type::PrevtxOutput as _, + index: 2, + prev_index: 3, + ..Default::default() + }; + assert_eq!(parse_sign_next(Response::BtcSignNext(next.clone())).unwrap(), next); + assert_eq!( + parse_sign_next(nested_response(BtcResponse::SignNext(next.clone()))).unwrap(), + next, + ); + assert!(matches!( + parse_sign_next(nested_response(BtcResponse::Success(pb::BtcSuccess {}))), + Err(Error::UnexpectedResponse) + )); + } + + #[test] + fn message_reply_parsing_validates_encoding_but_not_nonce() { + use pb::btc_response::Response as BtcResponse; + + let commitment = nested_response(BtcResponse::AntikleptoSignerCommitment( + pb::AntiKleptoSignerCommitment { commitment: vec![42; 33] }, + )); + assert_eq!(parse_signer_commitment(commitment.clone()).unwrap(), vec![42; 33]); + assert!(matches!(parse_message_signature(commitment), Err(Error::UnexpectedResponse))); + let message = |signature| { + nested_response(BtcResponse::SignMessage(pb::BtcSignMessageResponse { signature })) + }; + // Compact r = 1, s = 1: valid scalars irrespective of any message or nonce. + let mut compact = vec![0; 64]; + compact[31] = 1; + compact[63] = 1; + assert!(matches!( + parse_signer_commitment(message(compact.clone())), + Err(Error::UnexpectedResponse) + )); + for recid in [0, 3] { + let mut recoverable = compact.clone(); + recoverable.push(recid); + let parsed = parse_message_signature(message(recoverable)).unwrap(); + assert_eq!(parsed.sig, compact); + assert_eq!(parsed.recid, recid); + assert_eq!(parsed.electrum_sig65[0], 31 + recid); + assert_eq!(&parsed.electrum_sig65[1..], compact.as_slice()); + } + let mut bad_recid = compact.clone(); + bad_recid.push(4); + for malformed in [compact, bad_recid, vec![0; 65]] { + assert!(matches!( + parse_message_signature(message(malformed)), + Err(Error::AntiKlepto(crate::antiklepto::Error::InvalidSignature(_))) + )); + } + } + + #[test] + fn raw_signing_checks_versions_and_output_index_count() { + use pb::btc_script_config::SimpleType; + use semver::Version; + + let mut tx = Transaction { + version: 2, + locktime: 0, + inputs: vec![], + script_configs: vec![], + outputs: vec![], + }; + let old = Version::new(9, 3, 0); + assert!(matches!(validate_version(&old, "not semver"), Err(Error::Unknown))); + assert!(matches!(validate_signing(&old, &tx, &[], &[]), Err(Error::Version(">=9.4.0")))); + assert!(validate_signing(&Version::new(9, 4, 0), &tx, &[], &[]).is_ok()); + + let taproot = pb::BtcScriptConfigWithKeypath { + script_config: Some(make_script_config_simple(SimpleType::P2tr)), + keypath: vec![], + }; + assert!(is_schnorr(&taproot)); + assert!(matches!( + validate_signing(&Version::new(9, 9, 0), &tx, std::slice::from_ref(&taproot), &[]), + Err(Error::Version(">=9.10.0")) + )); + tx.script_configs.push(taproot); + assert!(matches!( + validate_signing(&Version::new(9, 9, 0), &tx, &[], &[]), + Err(Error::Version(">=9.10.0")) + )); + assert!(validate_signing(&Version::new(9, 10, 0), &tx, &[], &[]).is_ok()); + + tx.outputs.push(TxOutput::External(TxExternalOutput { + value: 0, + payload: Payload::from_pkscript(&[0x6a, 1, 42]).unwrap(), + })); + assert!(matches!( + validate_signing(&Version::new(9, 23, 0), &tx, &[], &[]), + Err(Error::Version(">=9.24.0")) + )); + let op_return_version = Version::new(9, 24, 0); + assert!(validate_signing(&op_return_version, &tx, &[], &[None]).is_ok()); + assert!(matches!( + validate_signing(&op_return_version, &tx, &[], &[None, None]), + Err(Error::BtcSign(message)) + if message == "output script config indices must match transaction outputs" + )); + } + #[test] fn test_payload_from_pkscript() { use std::str::FromStr; diff --git a/src/keypath.rs b/src/keypath.rs index 76b92f4..24e3ec5 100644 --- a/src/keypath.rs +++ b/src/keypath.rs @@ -12,14 +12,13 @@ impl Keypath { self.0.clone() } - pub(crate) fn hardened_prefix(&self) -> Keypath { - Keypath( - self.0 - .iter() - .cloned() - .take_while(|&el| el >= HARDENED) - .collect(), - ) + /// Returns the path components without copying them. + pub fn as_slice(&self) -> &[u32] { + &self.0 + } + + pub(crate) fn hardened_prefix(&self) -> &[u32] { + self.0.split(|&child| child < HARDENED).next().unwrap_or_default() } } @@ -132,7 +131,7 @@ mod tests { std::str::FromStr::from_str("m/84'/0'/0'/0/1").unwrap(); let keypath = Keypath::from(&derivation_path); assert_eq!( - keypath.to_vec().as_slice(), + keypath.as_slice(), &[84 + HARDENED, HARDENED, HARDENED, 0, 1] ); } diff --git a/src/lib.rs b/src/lib.rs index 2412497..3df5e19 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -314,14 +314,7 @@ impl PairedBitBox { } fn validate_version(&self, comparison: &'static str) -> Result<(), Error> { - if semver::VersionReq::parse(comparison) - .or(Err(Error::Unknown))? - .matches(&self.communication.info.version) - { - Ok(()) - } else { - Err(Error::Version(comparison)) - } + btc::validate_version(self.version(), comparison) } async fn query_proto(&self, request: Request) -> Result { From 6a324b7e16c73cbc051603f1921847bc9950d062 Mon Sep 17 00:00:00 2001 From: Trevor Arjeski Date: Thu, 26 Nov 2026 08:51:05 +0000 Subject: [PATCH 09/23] feat(btc): lower PSBTs with caller-resolved keys MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Retain the convenience client’s fingerprint lookup and use one lowering path. - Validate metadata cardinality and preserve firmware-aware output configuration. --- src/btc.rs | 317 +++++++++++++++++++++++++++++++++++++++++++---------- 1 file changed, 259 insertions(+), 58 deletions(-) diff --git a/src/btc.rs b/src/btc.rs index 14517df..f43d1c9 100644 --- a/src/btc.rs +++ b/src/btc.rs @@ -409,25 +409,78 @@ pub struct PsbtTransaction { pub output_script_config_indices: Vec>, } +fn validate_psbt_key_counts( + psbt: &bitcoin::psbt::Psbt, + input_keys: usize, + output_keys: usize, +) -> Result<(), Error> { + if psbt.inputs.len() != psbt.unsigned_tx.input.len() || input_keys != psbt.inputs.len() { + return Err(Error::BtcSign( + "input signing keys must match PSBT inputs".into(), + )); + } + if psbt.outputs.len() != psbt.unsigned_tx.output.len() || output_keys != psbt.outputs.len() { + return Err(Error::BtcSign( + "output signing keys must match PSBT outputs".into(), + )); + } + Ok(()) +} + impl Transaction { - fn from_psbt( + /// Lowers a PSBT using the device fingerprint to look up owned keys. + pub fn from_psbt( firmware_version: &semver::Version, our_root_fingerprint: &[u8], psbt: &bitcoin::psbt::Psbt, force_script_config: Option, - ) -> Result { - let is_script_config_forced = force_script_config.is_some(); - let mut script_configs = force_script_config.into_iter().collect::>(); - let mut output_script_configs: Vec = Vec::new(); + ) -> Result { + validate_psbt_key_counts(psbt, psbt.inputs.len(), psbt.outputs.len())?; + let input_keys = psbt + .inputs + .iter() + .map(|input| find_our_key(our_root_fingerprint, input)) + .collect::, _>>()?; + let output_keys = psbt + .outputs + .iter() + .map(|output| find_our_key(our_root_fingerprint, output).ok()) + .collect(); + Self::from_psbt_with_keys( + firmware_version, + psbt, + force_script_config, + input_keys, + output_keys, + ) + } - let mut our_keys: Vec = Vec::new(); - let mut inputs: Vec = Vec::new(); + /// Lowers a PSBT given caller-resolved keys in PSBT input and output order. + /// + /// An output key of `None` marks an external output. This does not verify key ownership. + pub fn from_psbt_with_keys( + firmware_version: &semver::Version, + psbt: &bitcoin::psbt::Psbt, + force_script_config: Option, + input_keys: Vec, + output_keys: Vec>, + ) -> Result { + validate_psbt_key_counts(psbt, input_keys.len(), output_keys.len())?; - for (input_index, (tx_input, psbt_input)) in - psbt.unsigned_tx.input.iter().zip(&psbt.inputs).enumerate() + let is_script_config_forced = force_script_config.is_some(); + let mut script_configs = force_script_config.into_iter().collect::>(); + let mut output_script_configs = Vec::new(); + let mut inputs = Vec::with_capacity(input_keys.len()); + + for (input_index, ((tx_input, psbt_input), our_key)) in psbt + .unsigned_tx + .input + .iter() + .zip(&psbt.inputs) + .zip(&input_keys) + .enumerate() { - let utxo = psbt.spend_utxo(input_index)?; - let our_key = find_our_key(our_root_fingerprint, psbt_input)?; + let utxo = psbt.spend_utxo(input_index).map_err(PsbtError::from)?; let script_config_index = if is_script_config_forced { 0 } else { @@ -450,57 +503,57 @@ impl Transaction { script_config_index: script_config_index as _, prev_tx: psbt_input.non_witness_utxo.as_ref().map(PrevTx::from), }); - our_keys.push(our_key); } - let mut outputs: Vec = Vec::new(); - let mut output_script_config_indices: Vec> = Vec::new(); - for (tx_output, psbt_output) in psbt.unsigned_tx.output.iter().zip(&psbt.outputs) { - let our_key = find_our_key(our_root_fingerprint, psbt_output); - // Either change output or a non-change output owned by the BitBox. - match our_key { - Ok(our_key) => { - let script_config = if is_script_config_forced { - script_configs[0].clone() - } else { - script_config_from_utxo( - tx_output, - our_key.keypath(), - psbt_output.redeem_script.as_ref(), - )? - }; - let same_account = is_same_account(&script_configs, &script_config)?; - // Firmware 9.22 added separate output configs for device-owned outputs that - // belong to another account. Older firmware must display them as external. - if same_account { - let script_config_index = - find_or_add_script_config(&mut script_configs, script_config); - outputs.push(TxOutput::Internal(TxInternalOutput { - keypath: our_key.keypath().clone(), - value: tx_output.value.to_sat(), - script_config_index: script_config_index as _, - })); - output_script_config_indices.push(None); - } else if firmware_version >= &semver::Version::new(9, 22, 0) { - let output_script_config_index = - find_or_add_script_config(&mut output_script_configs, script_config); - outputs.push(TxOutput::Internal(TxInternalOutput { - keypath: our_key.keypath().clone(), - value: tx_output.value.to_sat(), - // Ignored when output_script_config_index is present. - script_config_index: 0, - })); - output_script_config_indices.push(Some(output_script_config_index as _)); - } else { - outputs.push(TxOutput::External(tx_output.try_into()?)); - output_script_config_indices.push(None); - } - } - Err(_) => { + let mut outputs = Vec::with_capacity(output_keys.len()); + let mut output_script_config_indices = Vec::with_capacity(output_keys.len()); + for ((tx_output, psbt_output), output_key) in psbt + .unsigned_tx + .output + .iter() + .zip(&psbt.outputs) + .zip(output_keys) + { + let Some( + OurKey::Segwit(_, keypath) + | OurKey::TaprootInternal(keypath) + | OurKey::TaprootScript(_, _, keypath), + ) = output_key else { + outputs.push(TxOutput::External(tx_output.try_into()?)); + output_script_config_indices.push(None); + continue; + }; + let (script_config_index, output_script_config_index) = if is_script_config_forced { + // The forced config is used for all owned inputs and outputs, but still check + // that a forced simple config has an account keypath. + is_same_account(&script_configs, &script_configs[0])?; + (0, None) + } else { + let script_config = script_config_from_utxo( + tx_output, + &keypath, + psbt_output.redeem_script.as_ref(), + )?; + if is_same_account(&script_configs, &script_config)? { + (find_or_add_script_config(&mut script_configs, script_config) as u32, None) + } else if firmware_version >= &semver::Version::new(9, 22, 0) { + let index = + find_or_add_script_config(&mut output_script_configs, script_config); + // The input config index is ignored when the output config index is present. + (0, Some(index as u32)) + } else { + // Older firmware displays device-owned outputs of other accounts as external. outputs.push(TxOutput::External(tx_output.try_into()?)); output_script_config_indices.push(None); + continue; } - } + }; + outputs.push(TxOutput::Internal(TxInternalOutput { + keypath, + value: tx_output.value.to_sat(), + script_config_index, + })); + output_script_config_indices.push(output_script_config_index); } Ok(PsbtTransaction { @@ -511,7 +564,7 @@ impl Transaction { outputs, locktime: psbt.unsigned_tx.lock_time.to_consensus_u32(), }, - our_keys, + our_keys: input_keys, output_script_configs, output_script_config_indices, }) @@ -1756,6 +1809,154 @@ mod tests { )); } + fn psbt_fixture() -> (bitcoin::psbt::Psbt, Fingerprint, bitcoin::secp256k1::PublicKey) { + use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey}; + use bitcoin::{absolute, psbt::Psbt, transaction, Amount, CompressedPublicKey, ScriptBuf}; + + let key = PublicKey::from_secret_key( + &Secp256k1::new(), + &SecretKey::from_slice(&[1; 32]).unwrap(), + ); + let fingerprint = Fingerprint::from([1, 2, 3, 4]); + let output = bitcoin::TxOut { + value: Amount::from_sat(1000), + script_pubkey: ScriptBuf::new_p2wpkh(&CompressedPublicKey(key).wpubkey_hash()), + }; + let mut psbt = Psbt::from_unsigned_tx(bitcoin::Transaction { + version: transaction::Version::TWO, + lock_time: absolute::LockTime::ZERO, + input: vec![bitcoin::TxIn::default()], + output: vec![output.clone()], + }) + .unwrap(); + psbt.inputs[0].witness_utxo = Some(output); + psbt.inputs[0] + .bip32_derivation + .insert(key, (fingerprint, "m/84'/0'/0'/0/0".parse().unwrap())); + psbt.outputs[0] + .bip32_derivation + .insert(key, (fingerprint, "m/84'/0'/1'/1/3".parse().unwrap())); + (psbt, fingerprint, key) + } + + #[test] + fn psbt_lowering_uses_firmware_aware_cross_account_outputs() { + let (psbt, fingerprint, key) = psbt_fixture(); + let output_keypath = Keypath::try_from("m/84'/0'/1'/1/3").unwrap(); + for minor in [21, 22] { + let version = semver::Version::new(9, minor, 0); + let ordinary = Transaction::from_psbt(&version, &fingerprint[..], &psbt, None).unwrap(); + let resolved = Transaction::from_psbt_with_keys( + &version, + &psbt, + None, + vec![OurKey::Segwit(key, Keypath::try_from("m/84'/0'/0'/0/0").unwrap())], + vec![Some(OurKey::Segwit(key, output_keypath.clone()))], + ) + .unwrap(); + assert_eq!(ordinary.transaction, resolved.transaction); + assert_eq!(ordinary.output_script_configs, resolved.output_script_configs); + assert_eq!(ordinary.output_script_config_indices, resolved.output_script_config_indices); + assert_eq!(resolved.transaction.script_configs.len(), 1); + if minor == 21 { + assert_eq!(resolved.output_script_config_indices, [None]); + assert!(resolved.output_script_configs.is_empty()); + assert_eq!( + resolved.transaction.outputs[0], + TxOutput::External(TxExternalOutput::try_from(&psbt.unsigned_tx.output[0]).unwrap()), + ); + } else { + assert_eq!(resolved.output_script_config_indices, [Some(0)]); + assert_eq!(resolved.output_script_configs.len(), 1); + assert_eq!( + resolved.output_script_configs[0].keypath, + Keypath::try_from("m/84'/0'/1'").unwrap().as_slice(), + ); + assert_eq!( + resolved.transaction.outputs[0], + TxOutput::Internal(TxInternalOutput { + keypath: output_keypath.clone(), + value: 1000, + script_config_index: 0, + }), + ); + } + } + } + + #[test] + fn psbt_lowering_checks_psbt_and_key_cardinalities() { + let (mut psbt, fingerprint, key) = psbt_fixture(); + let version = semver::Version::new(9, 24, 0); + let input_keys = || vec![OurKey::Segwit(key, Keypath::try_from("m/84'/0'/0'/0/0").unwrap())]; + let input_error = "input signing keys must match PSBT inputs"; + let output_error = "output signing keys must match PSBT outputs"; + let expect_error = |result, expected: &str| { + assert!(matches!(result, Err(Error::BtcSign(message)) if message == expected)); + }; + expect_error( + Transaction::from_psbt_with_keys(&version, &psbt, None, vec![], vec![None]), + input_error, + ); + expect_error( + Transaction::from_psbt_with_keys(&version, &psbt, None, input_keys(), vec![]), + output_error, + ); + // Even if key and metadata counts agree, the unsigned transaction must agree as well. + psbt.unsigned_tx.input.push(bitcoin::TxIn::default()); + expect_error( + Transaction::from_psbt_with_keys(&version, &psbt, None, input_keys(), vec![None]), + input_error, + ); + expect_error(Transaction::from_psbt(&version, &fingerprint[..], &psbt, None), input_error); + psbt.unsigned_tx.input.pop(); + psbt.unsigned_tx.output.clear(); + expect_error( + Transaction::from_psbt_with_keys(&version, &psbt, None, input_keys(), vec![None]), + output_error, + ); + expect_error(Transaction::from_psbt(&version, &fingerprint[..], &psbt, None), output_error); + } + + #[test] + fn psbt_lowering_requires_explicit_config_for_p2wsh() { + use bitcoin::bip32::Xpriv; + use bitcoin::hashes::Hash; + use bitcoin::secp256k1::Secp256k1; + + let (mut psbt, fingerprint, _) = psbt_fixture(); + let version = semver::Version::new(9, 22, 0); + let script = bitcoin::ScriptBuf::new_p2wsh(&bitcoin::WScriptHash::from_byte_array([5; 32])); + psbt.inputs[0].witness_utxo.as_mut().unwrap().script_pubkey = script.clone(); + psbt.unsigned_tx.output[0].script_pubkey = script; + assert!(matches!( + Transaction::from_psbt(&version, &fingerprint[..], &psbt, None), + Err(Error::Psbt(PsbtError::UnknownOutputType)) + )); + let xpriv = Xpriv::new_master(bitcoin::Network::Bitcoin, &[7; 32]).unwrap(); + let forced = pb::BtcScriptConfigWithKeypath { + script_config: Some(make_script_config_policy( + "wsh(pk(@0/**))", + &[KeyOriginInfo { + root_fingerprint: Some(fingerprint), + keypath: None, + xpub: Xpub::from_priv(&Secp256k1::new(), &xpriv), + }], + )), + keypath: vec![], + }; + let lowered = Transaction::from_psbt(&version, &fingerprint[..], &psbt, Some(forced.clone())) + .unwrap(); + assert_eq!(lowered.transaction.script_configs, [forced]); + assert_eq!(lowered.transaction.inputs[0].script_config_index, 0); + assert!(matches!( + lowered.transaction.outputs[0], + TxOutput::Internal(TxInternalOutput { script_config_index: 0, .. }) + )); + assert!(lowered.output_script_configs.is_empty()); + assert_eq!(lowered.output_script_config_indices, [None]); + } + #[test] fn test_payload_from_pkscript() { use std::str::FromStr; From 7ab0be47e21b72baff48a4cf92c275d41703538d Mon Sep 17 00:00:00 2001 From: Trevor Arjeski Date: Thu, 26 Nov 2026 08:54:05 +0000 Subject: [PATCH 10/23] feat(btc): share PSBT signature application - Reject mismatched input and signature counts before mutating the PSBT. - Apply ECDSA and Taproot signatures without dropping unrelated entries. --- src/btc.rs | 374 ++++++++++++++++++++++++++++++++++++++----------- src/keypath.rs | 5 +- 2 files changed, 293 insertions(+), 86 deletions(-) diff --git a/src/btc.rs b/src/btc.rs index f43d1c9..2cc951a 100644 --- a/src/btc.rs +++ b/src/btc.rs @@ -266,7 +266,9 @@ pub enum OurKey { impl OurKey { fn keypath(&self) -> &Keypath { match self { - OurKey::Segwit(_, kp) | OurKey::TaprootInternal(kp) | OurKey::TaprootScript(_, _, kp) => kp, + OurKey::Segwit(_, kp) + | OurKey::TaprootInternal(kp) + | OurKey::TaprootScript(_, _, kp) => kp, } } } @@ -518,7 +520,8 @@ impl Transaction { OurKey::Segwit(_, keypath) | OurKey::TaprootInternal(keypath) | OurKey::TaprootScript(_, _, keypath), - ) = output_key else { + ) = output_key + else { outputs.push(TxOutput::External(tx_output.try_into()?)); output_script_config_indices.push(None); continue; @@ -535,7 +538,10 @@ impl Transaction { psbt_output.redeem_script.as_ref(), )?; if is_same_account(&script_configs, &script_config)? { - (find_or_add_script_config(&mut script_configs, script_config) as u32, None) + ( + find_or_add_script_config(&mut script_configs, script_config) as u32, + None, + ) } else if firmware_version >= &semver::Version::new(9, 22, 0) { let index = find_or_add_script_config(&mut output_script_configs, script_config); @@ -571,6 +577,53 @@ impl Transaction { } } +/// Applies device signatures to their PSBT inputs in input order, preserving other signatures. +/// +/// A count mismatch is rejected before mutation. If a later signature is malformed, earlier +/// signatures may already have been applied. +pub fn apply_signatures( + psbt: &mut bitcoin::psbt::Psbt, + signatures: &[Vec], + our_keys: &[OurKey], +) -> Result<(), Error> { + let num_inputs = psbt.unsigned_tx.input.len(); + if psbt.inputs.len() != num_inputs + || signatures.len() != num_inputs + || our_keys.len() != num_inputs + { + return Err(Error::BtcSign( + "signatures and signing keys must match PSBT inputs".into(), + )); + } + + for ((input, signature), key) in psbt.inputs.iter_mut().zip(signatures).zip(our_keys) { + match key { + OurKey::Segwit(pubkey, _) => { + let signature = bitcoin::secp256k1::ecdsa::Signature::from_compact(signature) + .map_err(|_| Error::InvalidSignature)?; + input.partial_sigs.insert( + bitcoin::PublicKey::new(*pubkey), + bitcoin::ecdsa::Signature::sighash_all(signature), + ); + } + OurKey::TaprootInternal(_) => { + input.tap_key_sig = Some( + bitcoin::taproot::Signature::from_slice(signature) + .map_err(|_| Error::InvalidSignature)?, + ); + } + OurKey::TaprootScript(xonly, leaf_hash, _) => { + let signature = bitcoin::taproot::Signature::from_slice(signature) + .map_err(|_| Error::InvalidSignature)?; + input + .tap_script_sigs + .insert((*xonly, *leaf_hash), signature); + } + } + } + Ok(()) +} + /// Create a single-sig script config. pub fn make_script_config_simple( simple_type: pb::btc_script_config::SimpleType, @@ -892,30 +945,36 @@ pub fn sign_output_request(output: &TxOutput, output_script_config_index: Option /// Builds a request describing a previous transaction. pub fn prevtx_init_request(tx: &PrevTx) -> Request { - btc_request(pb::btc_request::Request::PrevtxInit(pb::BtcPrevTxInitRequest { - version: tx.version, - num_inputs: tx.inputs.len() as _, - num_outputs: tx.outputs.len() as _, - locktime: tx.locktime, - })) + btc_request(pb::btc_request::Request::PrevtxInit( + pb::BtcPrevTxInitRequest { + version: tx.version, + num_inputs: tx.inputs.len() as _, + num_outputs: tx.outputs.len() as _, + locktime: tx.locktime, + }, + )) } /// Builds a request carrying a previous transaction's input. pub fn prevtx_input_request(input: &PrevTxInput) -> Request { - btc_request(pb::btc_request::Request::PrevtxInput(pb::BtcPrevTxInputRequest { - prev_out_hash: input.prev_out_hash.clone(), - prev_out_index: input.prev_out_index, - signature_script: input.signature_script.clone(), - sequence: input.sequence, - })) + btc_request(pb::btc_request::Request::PrevtxInput( + pb::BtcPrevTxInputRequest { + prev_out_hash: input.prev_out_hash.clone(), + prev_out_index: input.prev_out_index, + signature_script: input.signature_script.clone(), + sequence: input.sequence, + }, + )) } /// Builds a request carrying a previous transaction's output. pub fn prevtx_output_request(output: &PrevTxOutput) -> Request { - btc_request(pb::btc_request::Request::PrevtxOutput(pb::BtcPrevTxOutputRequest { - value: output.value, - pubkey_script: output.pubkey_script.clone(), - })) + btc_request(pb::btc_request::Request::PrevtxOutput( + pb::BtcPrevTxOutputRequest { + value: output.value, + pubkey_script: output.pubkey_script.clone(), + }, + )) } /// Reveals the host nonce to request an Anti-Klepto signature. @@ -1127,8 +1186,13 @@ impl PairedBitBox { ) -> Result { let _api_call = self.begin_api_call().await; crate::api::parse_pub( - self.query_proto(address_request(coin, keypath, script_config.clone(), display)) - .await?, + self.query_proto(address_request( + coin, + keypath, + script_config.clone(), + display, + )) + .await?, ) } @@ -1203,7 +1267,9 @@ impl PairedBitBox { next_response = self .get_next_response(sign_input_request( tx_input, - host_nonce.as_ref().map(|nonce| crate::antiklepto::host_commit(nonce)), + host_nonce + .as_ref() + .map(|nonce| crate::antiklepto::host_commit(nonce)), )) .await?; @@ -1273,7 +1339,10 @@ impl PairedBitBox { .copied() .flatten(); next_response = self - .get_next_response(sign_output_request(tx_output, output_script_config_index)) + .get_next_response(sign_output_request( + tx_output, + output_script_config_index, + )) .await?; } pb::btc_sign_next_response::Type::Done => break, @@ -1323,38 +1392,7 @@ impl PairedBitBox { format_unit, ) .await?; - for (psbt_input, (signature, our_key)) in psbt - .inputs - .iter_mut() - .zip(signatures.iter().zip(psbt_transaction.our_keys)) - { - match our_key { - OurKey::Segwit(pubkey, _) => { - psbt_input.partial_sigs.insert( - bitcoin::PublicKey::new(pubkey), - bitcoin::ecdsa::Signature { - signature: bitcoin::secp256k1::ecdsa::Signature::from_compact( - signature, - ) - .map_err(|_| Error::InvalidSignature)?, - sighash_type: bitcoin::sighash::EcdsaSighashType::All, - }, - ); - } - OurKey::TaprootInternal(_) => { - psbt_input.tap_key_sig = Some( - bitcoin::taproot::Signature::from_slice(signature) - .map_err(|_| Error::InvalidSignature)?, - ); - } - OurKey::TaprootScript(xonly, leaf_hash, _) => { - let sig = bitcoin::taproot::Signature::from_slice(signature) - .map_err(|_| Error::InvalidSignature)?; - psbt_input.tap_script_sigs.insert((xonly, leaf_hash), sig); - } - } - } - Ok(()) + apply_signatures(psbt, &signatures, &psbt_transaction.our_keys) } /// Sign a message. @@ -1527,12 +1565,21 @@ mod tests { let response = nested_response(BtcResponse::IsScriptConfigRegistered( pb::BtcIsScriptConfigRegisteredResponse { is_registered }, )); - assert_eq!(parse_is_registered(response.clone()).unwrap(), is_registered); - assert!(matches!(parse_registered(response), Err(Error::UnexpectedResponse))); + assert_eq!( + parse_is_registered(response.clone()).unwrap(), + is_registered + ); + assert!(matches!( + parse_registered(response), + Err(Error::UnexpectedResponse) + )); } let response = nested_response(BtcResponse::Success(pb::BtcSuccess {})); assert!(parse_registered(response.clone()).is_ok()); - assert!(matches!(parse_is_registered(response), Err(Error::UnexpectedResponse))); + assert!(matches!( + parse_is_registered(response), + Err(Error::UnexpectedResponse) + )); assert!(matches!( btc_response(Response::Btc(pb::BtcResponse { response: None })), Err(Error::UnexpectedResponse) @@ -1550,7 +1597,9 @@ mod tests { let coin = pb::BtcCoin::Tbtc; let config = pb::BtcScriptConfigWithKeypath { - script_config: Some(make_script_config_simple(pb::btc_script_config::SimpleType::P2wpkh)), + script_config: Some(make_script_config_simple( + pb::btc_script_config::SimpleType::P2wpkh, + )), keypath: vec![1, 2, 3], }; let keypath = Keypath::try_from("m/7").unwrap(); @@ -1601,7 +1650,12 @@ mod tests { ..config.clone() }; assert_eq!( - sign_init_request(coin, &tx, std::slice::from_ref(&output_config), FormatUnit::Sat), + sign_init_request( + coin, + &tx, + std::slice::from_ref(&output_config), + FormatUnit::Sat + ), Request::BtcSignInit(pb::BtcSignInitRequest { coin: coin as _, script_configs: vec![config.clone()], @@ -1626,7 +1680,9 @@ mod tests { keypath: vec![7], script_config_index: 11, host_nonce_commitment: host_commitment.map(|_| { - pb::AntiKleptoHostNonceCommitment { commitment: vec![14; 32] } + pb::AntiKleptoHostNonceCommitment { + commitment: vec![14; 32], + } }), }), ); @@ -1654,7 +1710,11 @@ mod tests { }), ); - let nested = |request| Request::Btc(pb::BtcRequest { request: Some(request) }); + let nested = |request| { + Request::Btc(pb::BtcRequest { + request: Some(request), + }) + }; let prevtx = tx.inputs[0].get_prev_tx().unwrap(); assert_eq!( prevtx_init_request(prevtx), @@ -1694,9 +1754,11 @@ mod tests { ); assert_eq!( antiklepto_signature_request(&[15; 32]), - nested(BtcRequest::AntikleptoSignature(pb::AntiKleptoSignatureRequest { - host_nonce: vec![15; 32], - })), + nested(BtcRequest::AntikleptoSignature( + pb::AntiKleptoSignatureRequest { + host_nonce: vec![15; 32], + } + )), ); } @@ -1709,7 +1771,10 @@ mod tests { prev_index: 3, ..Default::default() }; - assert_eq!(parse_sign_next(Response::BtcSignNext(next.clone())).unwrap(), next); + assert_eq!( + parse_sign_next(Response::BtcSignNext(next.clone())).unwrap(), + next + ); assert_eq!( parse_sign_next(nested_response(BtcResponse::SignNext(next.clone()))).unwrap(), next, @@ -1725,12 +1790,22 @@ mod tests { use pb::btc_response::Response as BtcResponse; let commitment = nested_response(BtcResponse::AntikleptoSignerCommitment( - pb::AntiKleptoSignerCommitment { commitment: vec![42; 33] }, + pb::AntiKleptoSignerCommitment { + commitment: vec![42; 33], + }, + )); + assert_eq!( + parse_signer_commitment(commitment.clone()).unwrap(), + vec![42; 33] + ); + assert!(matches!( + parse_message_signature(commitment), + Err(Error::UnexpectedResponse) )); - assert_eq!(parse_signer_commitment(commitment.clone()).unwrap(), vec![42; 33]); - assert!(matches!(parse_message_signature(commitment), Err(Error::UnexpectedResponse))); let message = |signature| { - nested_response(BtcResponse::SignMessage(pb::BtcSignMessageResponse { signature })) + nested_response(BtcResponse::SignMessage(pb::BtcSignMessageResponse { + signature, + })) }; // Compact r = 1, s = 1: valid scalars irrespective of any message or nonce. let mut compact = vec![0; 64]; @@ -1754,7 +1829,9 @@ mod tests { for malformed in [compact, bad_recid, vec![0; 65]] { assert!(matches!( parse_message_signature(message(malformed)), - Err(Error::AntiKlepto(crate::antiklepto::Error::InvalidSignature(_))) + Err(Error::AntiKlepto( + crate::antiklepto::Error::InvalidSignature(_) + )) )); } } @@ -1772,8 +1849,14 @@ mod tests { outputs: vec![], }; let old = Version::new(9, 3, 0); - assert!(matches!(validate_version(&old, "not semver"), Err(Error::Unknown))); - assert!(matches!(validate_signing(&old, &tx, &[], &[]), Err(Error::Version(">=9.4.0")))); + assert!(matches!( + validate_version(&old, "not semver"), + Err(Error::Unknown) + )); + assert!(matches!( + validate_signing(&old, &tx, &[], &[]), + Err(Error::Version(">=9.4.0")) + )); assert!(validate_signing(&Version::new(9, 4, 0), &tx, &[], &[]).is_ok()); let taproot = pb::BtcScriptConfigWithKeypath { @@ -1782,7 +1865,12 @@ mod tests { }; assert!(is_schnorr(&taproot)); assert!(matches!( - validate_signing(&Version::new(9, 9, 0), &tx, std::slice::from_ref(&taproot), &[]), + validate_signing( + &Version::new(9, 9, 0), + &tx, + std::slice::from_ref(&taproot), + &[] + ), Err(Error::Version(">=9.10.0")) )); tx.script_configs.push(taproot); @@ -1809,7 +1897,11 @@ mod tests { )); } - fn psbt_fixture() -> (bitcoin::psbt::Psbt, Fingerprint, bitcoin::secp256k1::PublicKey) { + fn psbt_fixture() -> ( + bitcoin::psbt::Psbt, + Fingerprint, + bitcoin::secp256k1::PublicKey, + ) { use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey}; use bitcoin::{absolute, psbt::Psbt, transaction, Amount, CompressedPublicKey, ScriptBuf}; @@ -1850,20 +1942,31 @@ mod tests { &version, &psbt, None, - vec![OurKey::Segwit(key, Keypath::try_from("m/84'/0'/0'/0/0").unwrap())], + vec![OurKey::Segwit( + key, + Keypath::try_from("m/84'/0'/0'/0/0").unwrap(), + )], vec![Some(OurKey::Segwit(key, output_keypath.clone()))], ) .unwrap(); assert_eq!(ordinary.transaction, resolved.transaction); - assert_eq!(ordinary.output_script_configs, resolved.output_script_configs); - assert_eq!(ordinary.output_script_config_indices, resolved.output_script_config_indices); + assert_eq!( + ordinary.output_script_configs, + resolved.output_script_configs + ); + assert_eq!( + ordinary.output_script_config_indices, + resolved.output_script_config_indices + ); assert_eq!(resolved.transaction.script_configs.len(), 1); if minor == 21 { assert_eq!(resolved.output_script_config_indices, [None]); assert!(resolved.output_script_configs.is_empty()); assert_eq!( resolved.transaction.outputs[0], - TxOutput::External(TxExternalOutput::try_from(&psbt.unsigned_tx.output[0]).unwrap()), + TxOutput::External( + TxExternalOutput::try_from(&psbt.unsigned_tx.output[0]).unwrap() + ), ); } else { assert_eq!(resolved.output_script_config_indices, [Some(0)]); @@ -1888,7 +1991,12 @@ mod tests { fn psbt_lowering_checks_psbt_and_key_cardinalities() { let (mut psbt, fingerprint, key) = psbt_fixture(); let version = semver::Version::new(9, 24, 0); - let input_keys = || vec![OurKey::Segwit(key, Keypath::try_from("m/84'/0'/0'/0/0").unwrap())]; + let input_keys = || { + vec![OurKey::Segwit( + key, + Keypath::try_from("m/84'/0'/0'/0/0").unwrap(), + )] + }; let input_error = "input signing keys must match PSBT inputs"; let output_error = "output signing keys must match PSBT outputs"; let expect_error = |result, expected: &str| { @@ -1908,14 +2016,20 @@ mod tests { Transaction::from_psbt_with_keys(&version, &psbt, None, input_keys(), vec![None]), input_error, ); - expect_error(Transaction::from_psbt(&version, &fingerprint[..], &psbt, None), input_error); + expect_error( + Transaction::from_psbt(&version, &fingerprint[..], &psbt, None), + input_error, + ); psbt.unsigned_tx.input.pop(); psbt.unsigned_tx.output.clear(); expect_error( Transaction::from_psbt_with_keys(&version, &psbt, None, input_keys(), vec![None]), output_error, ); - expect_error(Transaction::from_psbt(&version, &fingerprint[..], &psbt, None), output_error); + expect_error( + Transaction::from_psbt(&version, &fingerprint[..], &psbt, None), + output_error, + ); } #[test] @@ -1945,18 +2059,108 @@ mod tests { )), keypath: vec![], }; - let lowered = Transaction::from_psbt(&version, &fingerprint[..], &psbt, Some(forced.clone())) - .unwrap(); + let lowered = + Transaction::from_psbt(&version, &fingerprint[..], &psbt, Some(forced.clone())) + .unwrap(); assert_eq!(lowered.transaction.script_configs, [forced]); assert_eq!(lowered.transaction.inputs[0].script_config_index, 0); assert!(matches!( lowered.transaction.outputs[0], - TxOutput::Internal(TxInternalOutput { script_config_index: 0, .. }) + TxOutput::Internal(TxInternalOutput { + script_config_index: 0, + .. + }) )); assert!(lowered.output_script_configs.is_empty()); assert_eq!(lowered.output_script_config_indices, [None]); } + #[test] + fn signature_application_checks_counts_before_mutating() { + let (mut psbt, _, key) = psbt_fixture(); + let keys = [OurKey::Segwit(key, Keypath::try_from("m/").unwrap())]; + let mut compact = vec![0; 64]; + compact[31] = 1; + compact[63] = 1; + let signatures = [compact]; + let mut expect_error = |signatures: &[Vec], keys: &[OurKey]| { + assert!(matches!( + apply_signatures(&mut psbt, signatures, keys), + Err(Error::BtcSign(message)) + if message == "signatures and signing keys must match PSBT inputs" + )); + assert!(psbt.inputs[0].partial_sigs.is_empty()); + }; + expect_error(&[], &keys); + expect_error(&signatures, &[]); + + // Matching signatures, keys, and PSBT metadata are still insufficient when the + // underlying unsigned transaction has a different input count. + psbt.unsigned_tx.input.push(bitcoin::TxIn::default()); + assert!(matches!( + apply_signatures(&mut psbt, &signatures, &keys), + Err(Error::BtcSign(message)) + if message == "signatures and signing keys must match PSBT inputs" + )); + assert!(psbt.inputs[0].partial_sigs.is_empty()); + } + + #[test] + fn signature_application_preserves_partial_signatures_and_applies_in_order() { + use bitcoin::secp256k1::{Keypair, Message, PublicKey, Secp256k1, SecretKey}; + use bitcoin::taproot::{LeafVersion, TapLeafHash}; + + let (mut psbt, _, key) = psbt_fixture(); + psbt.unsigned_tx + .input + .resize_with(3, bitcoin::TxIn::default); + psbt.inputs.resize_with(3, Default::default); + + let secp = Secp256k1::new(); + let secret = SecretKey::from_slice(&[1; 32]).unwrap(); + let cosigner = SecretKey::from_slice(&[2; 32]).unwrap(); + let cosigner_key = bitcoin::PublicKey::new(PublicKey::from_secret_key(&secp, &cosigner)); + let digest = Message::from_digest([3; 32]); + let existing = bitcoin::ecdsa::Signature::sighash_all(secp.sign_ecdsa(&digest, &cosigner)); + psbt.inputs[0].partial_sigs.insert(cosigner_key, existing); + + let ecdsa = secp.sign_ecdsa(&digest, &secret); + let schnorr = + secp.sign_schnorr_no_aux_rand(&digest, &Keypair::from_secret_key(&secp, &secret)); + let taproot = bitcoin::taproot::Signature { + signature: schnorr, + sighash_type: bitcoin::sighash::TapSighashType::Default, + }; + let xonly = key.x_only_public_key().0; + let leaf = TapLeafHash::from_script(bitcoin::Script::new(), LeafVersion::TapScript); + let path = Keypath::try_from("m/").unwrap(); + let keys = [ + OurKey::Segwit(key, path.clone()), + OurKey::TaprootInternal(path.clone()), + OurKey::TaprootScript(xonly, leaf, path), + ]; + let mut signatures = [ecdsa.serialize_compact().to_vec(), vec![], taproot.to_vec()]; + + assert!(matches!( + apply_signatures(&mut psbt, &signatures, &keys), + Err(Error::InvalidSignature) + )); + let our_pubkey = bitcoin::PublicKey::new(key); + assert_eq!( + psbt.inputs[0].partial_sigs[&our_pubkey], + bitcoin::ecdsa::Signature::sighash_all(ecdsa), + ); + assert!(psbt.inputs[1].tap_key_sig.is_none()); + assert!(psbt.inputs[2].tap_script_sigs.is_empty()); + + signatures[1] = taproot.to_vec(); + apply_signatures(&mut psbt, &signatures, &keys).unwrap(); + assert_eq!(psbt.inputs[0].partial_sigs[&cosigner_key], existing); + assert_eq!(psbt.inputs[0].partial_sigs.len(), 2); + assert_eq!(psbt.inputs[1].tap_key_sig, Some(taproot)); + assert_eq!(psbt.inputs[2].tap_script_sigs[&(xonly, leaf)], taproot); + } + #[test] fn test_payload_from_pkscript() { use std::str::FromStr; diff --git a/src/keypath.rs b/src/keypath.rs index 24e3ec5..6c4946c 100644 --- a/src/keypath.rs +++ b/src/keypath.rs @@ -18,7 +18,10 @@ impl Keypath { } pub(crate) fn hardened_prefix(&self) -> &[u32] { - self.0.split(|&child| child < HARDENED).next().unwrap_or_default() + self.0 + .split(|&child| child < HARDENED) + .next() + .unwrap_or_default() } } From 5da735930601a186e939b84f1c2cd8335e019d16 Mon Sep 17 00:00:00 2001 From: Trevor Arjeski Date: Thu, 26 Nov 2026 08:54:05 +0000 Subject: [PATCH 11/23] feat: expose HWW and INFO framing primitives - Parse acknowledgements without copying their payloads. - Preserve client retry and reconnect behavior around the shared codecs. --- src/communication.rs | 157 ++++++++++++++++++++++++++++++++----------- src/lib.rs | 2 +- src/simulator.rs | 4 +- 3 files changed, 122 insertions(+), 41 deletions(-) diff --git a/src/communication.rs b/src/communication.rs index 1d1fbd3..3055833 100644 --- a/src/communication.rs +++ b/src/communication.rs @@ -68,7 +68,10 @@ impl U2fHidCommunication { impl ReadWrite for U2fHidCommunication { fn write(&self, msg: &[u8]) -> Result { let mut buf = [0u8; u2fframing::MAX_LEN]; - let size = self.u2fhid.encode(msg, &mut buf).or(Err(Error::U2fEncode))?; + let size = self + .u2fhid + .encode(msg, &mut buf) + .or(Err(Error::U2fEncode))?; for chunk in buf[..size].chunks(64) { self.read_write.write(chunk)?; } @@ -94,27 +97,56 @@ impl ReadWrite for U2fHidCommunication { // sinve v7.0.0, requets and responses are framed with hww* codes. // hwwReq* are HWW-level framing opcodes of requests. // New request. -const HWW_REQ_NEW: u8 = 0x00; +pub const HWW_REQ_NEW: u8 = 0x00; // Poll an outstanding request for completion. -const HWW_REQ_RETRY: u8 = 0x01; +pub const HWW_REQ_RETRY: u8 = 0x01; // Cancel any outstanding request. // const HWW_REQ_CANCEL: u8 = 0x02; // Reset the previous session before starting a new one (since v9.28.0). -const HWW_REQ_RESET: u8 = 0x03; +pub const HWW_REQ_RESET: u8 = 0x03; // INFO api call (used to be OP_INFO api call), graduated to the toplevel framing so it works // the same way for all firmware versions. -const HWW_INFO: u8 = b'i'; +pub const HWW_INFO: u8 = b'i'; // hwwRsp* are HWW-level framing pocodes of responses. // Request finished, payload is valid. -const HWW_RSP_ACK: u8 = 0x00; +pub const HWW_RSP_ACK: u8 = 0x00; // Request is outstanding, retry later with hwwOpRetry. -const HWW_RSP_NOTREADY: u8 = 0x01; +pub const HWW_RSP_NOTREADY: u8 = 0x01; // Device is busy, request was dropped. Client should retry the exact same msg. -const HWW_RSP_BUSY: u8 = 0x02; +pub const HWW_RSP_BUSY: u8 = 0x02; // Bad request. -const HWW_RSP_NACK: u8 = 0x03; +pub const HWW_RSP_NACK: u8 = 0x03; + +#[derive(Debug, PartialEq, Eq)] +pub enum HwwStatus<'a> { + Ack(&'a [u8]), + NotReady, + Busy, + Nack, +} + +pub fn parse_hww_response(bytes: &[u8]) -> Result, Error> { + match bytes { + [HWW_RSP_ACK, payload @ ..] => Ok(HwwStatus::Ack(payload)), + [HWW_RSP_NOTREADY, ..] => Ok(HwwStatus::NotReady), + [HWW_RSP_BUSY, ..] => Ok(HwwStatus::Busy), + [HWW_RSP_NACK, ..] => Ok(HwwStatus::Nack), + _ => Err(Error::Info), + } +} + +pub fn encode_hww_request(payload: &[u8], out: &mut [u8]) -> Result { + let out = out.get_mut(..=payload.len()).ok_or(Error::Write)?; + out[0] = HWW_REQ_NEW; + out[1..].copy_from_slice(payload); + Ok(out.len()) +} + +pub fn needs_session_reset(version: &semver::Version) -> bool { + *version >= semver::Version::new(9, 28, 0) +} #[derive(PartialEq, Debug, Copy, Clone)] pub enum Product { @@ -129,31 +161,23 @@ pub enum Product { pub struct Info { pub version: semver::Version, pub product: Product, - #[allow(dead_code)] pub unlocked: bool, // Is None before firmware version 9.20.0. - #[allow(dead_code)] pub initialized: Option, } #[cfg(feature = "client")] -pub struct HwwCommunication { +pub(crate) struct HwwCommunication { communication: Box, pub info: Info, marker: std::marker::PhantomData, } -#[cfg(feature = "client")] -async fn get_info(communication: &dyn ReadWrite) -> Result { - let response = communication.query(&[HWW_INFO]).await?; - let (version_str_len, response) = ( - *response.first().ok_or(Error::Info)? as usize, - response.get(1..).ok_or(Error::Info)?, - ); - let (version_bytes, response) = ( - response.get(..version_str_len).ok_or(Error::Info)?, - response.get(version_str_len..).ok_or(Error::Info)?, - ); +pub fn parse_info(response: &[u8]) -> Result { + let (&version_len, response) = response.split_first().ok_or(Error::Info)?; + let (version_bytes, response) = response + .split_at_checked(usize::from(version_len)) + .ok_or(Error::Info)?; let version_str = std::str::from_utf8(version_bytes) .or(Err(Error::Info))? .strip_prefix('v') @@ -196,7 +220,7 @@ async fn reset_session( communication: &dyn ReadWrite, version: &semver::Version, ) -> Result<(), Error> { - if *version < semver::Version::new(9, 28, 0) { + if !needs_session_reset(version) { return Ok(()); } // Send at the framing layer so an unfinished workflow cannot consume the request. @@ -212,7 +236,7 @@ async fn reset_session( #[cfg(feature = "client")] impl HwwCommunication { pub async fn from(communication: Box) -> Result { - let info = get_info(communication.as_ref()).await?; + let info = parse_info(&communication.query(&[HWW_INFO]).await?)?; // communication message framing since 7.0.0 if !semver::VersionReq::parse(">=7.0.0") .or(Err(Error::Unknown))? @@ -240,34 +264,89 @@ impl HwwCommunication { } pub async fn query(&self, msg: &[u8]) -> Result, Error> { - let mut framed_msg = Vec::from([HWW_REQ_NEW]); - framed_msg.extend_from_slice(msg); + let mut framed_msg = vec![0; msg.len() + 1]; + encode_hww_request(msg, &mut framed_msg)?; let mut response = loop { let response = self.communication.query(&framed_msg).await?; - if let Some(&HWW_RSP_BUSY) = response.first() { + if matches!(parse_hww_response(&response)?, HwwStatus::Busy) { R::sleep(std::time::Duration::from_millis(1000)).await; continue; } break response; }; loop { - match response.first() { - Some(&HWW_RSP_ACK) => { - return Ok(response.split_off(1)); - } - Some(&HWW_RSP_BUSY) => { - return Err(Error::Info); - } - Some(&HWW_RSP_NACK) => { - return Err(Error::Info); + match parse_hww_response(&response)? { + HwwStatus::Ack(_) => { + response.remove(0); + return Ok(response); } - Some(&HWW_RSP_NOTREADY) => { + HwwStatus::Busy | HwwStatus::Nack => return Err(Error::Info), + HwwStatus::NotReady => { R::sleep(std::time::Duration::from_millis(200)).await; response = self.communication.query(&[HWW_REQ_RETRY]).await?; } - _ => return Err(Error::Info), } } } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn hww_request_uses_caller_buffer() { + let mut out = [0xFF; 4]; + assert_eq!(encode_hww_request(&[0x61, 0x62], &mut out).unwrap(), 3); + assert_eq!(out, [0, 0x61, 0x62, 0xFF]); + assert!(matches!( + encode_hww_request(&[0x61; 4], &mut out), + Err(Error::Write), + )); + assert_eq!(out, [0, 0x61, 0x62, 0xFF]); + } + + #[test] + fn hww_ack_borrows_payload_and_statuses_are_distinct() { + let data = [0, 0x61, 0x62]; + let HwwStatus::Ack(payload) = parse_hww_response(&data).unwrap() else { + panic!("expected acknowledgement"); + }; + assert_eq!(payload, b"ab"); + assert!(std::ptr::eq(payload, &data[1..])); + assert_eq!(parse_hww_response(&[1]).unwrap(), HwwStatus::NotReady); + assert_eq!(parse_hww_response(&[2]).unwrap(), HwwStatus::Busy); + assert_eq!(parse_hww_response(&[3]).unwrap(), HwwStatus::Nack); + for invalid in [&[][..], &[4]] { + assert!(matches!(parse_hww_response(invalid), Err(Error::Info))); + } + } + + #[test] + fn info_preserves_product_and_optional_initialized_state() { + let old = parse_info(b"\x07v9.19.0\x00\x00\x01").unwrap(); + assert_eq!(old.version, semver::Version::new(9, 19, 0)); + assert_eq!(old.product, Product::BitBox02Multi); + assert!(old.unlocked); + assert_eq!(old.initialized, None); + assert!(!needs_session_reset(&old.version)); + + let new = parse_info(b"\x07v9.28.0\x02\x01\x00\x01").unwrap(); + assert_eq!(new.product, Product::BitBox02NovaBtcOnly); + assert!(!new.unlocked); + assert_eq!(new.initialized, Some(true)); + assert!(needs_session_reset(&new.version)); + assert!(!needs_session_reset(&semver::Version::new(9, 27, 1))); + + for invalid in [ + &b"\x08v9.28.0"[..], + &b"\x079.28.00\x02\x01\x00"[..], + &b"\x07v9.28.0\x02\x01"[..], + &b"\x07v9.28.0\x02\x01\x02"[..], + &b"\x07v9.28.0\x02\x01\x00\x02"[..], + ] { + assert!(matches!(parse_info(invalid), Err(Error::Info))); + } + } +} diff --git a/src/lib.rs b/src/lib.rs index 3df5e19..2d2bb0b 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -18,7 +18,7 @@ pub mod simulator; pub mod usb; pub mod antiklepto; -mod communication; +pub mod communication; mod keypath; pub mod secp256k1; pub mod u2fframing; diff --git a/src/simulator.rs b/src/simulator.rs index 3d85dc1..9f0f611 100644 --- a/src/simulator.rs +++ b/src/simulator.rs @@ -49,7 +49,9 @@ impl crate::util::Threading for TcpClient {} impl ReadWrite for TcpClient { fn write(&self, msg: &[u8]) -> Result { let mut stream = self.stream.lock().unwrap(); - stream.write_all(msg).map_err(|_| CommunicationError::Write)?; + stream + .write_all(msg) + .map_err(|_| CommunicationError::Write)?; Ok(msg.len()) } From 6d026f841c885e8805cde8b8e8e7474aee96a947 Mon Sep 17 00:00:00 2001 From: Trevor Arjeski Date: Thu, 26 Nov 2026 08:55:04 +0000 Subject: [PATCH 12/23] style: finish feature-gated protocol cleanup - Apply rustfmt to the extracted client paths. - Compile the ETH utility only for the client and its tests. --- src/eth.rs | 2 +- src/noise.rs | 10 +++++++--- src/util.rs | 1 + 3 files changed, 9 insertions(+), 4 deletions(-) diff --git a/src/eth.rs b/src/eth.rs index 3f6b6ae..9aca6c1 100644 --- a/src/eth.rs +++ b/src/eth.rs @@ -3,12 +3,12 @@ use crate::runtime::Runtime; use crate::error::Error; +use crate::pb::{self, request::Request, response::Response}; #[cfg(feature = "persistence")] use crate::pb::{ eth_sign_typed_message_request::{DataType, Member, MemberType, StructType}, eth_typed_message_value_response::RootObject, }; -use crate::pb::{self, request::Request, response::Response}; use crate::Keypath; use crate::PairedBitBox; diff --git a/src/noise.rs b/src/noise.rs index bada9c9..78c1ae9 100644 --- a/src/noise.rs +++ b/src/noise.rs @@ -42,7 +42,8 @@ pub fn handshake_read_write( if host.completed() || !host.is_write_turn() { return Err(ProtocolError::Noise); } - host.write_message_vec(b"").map_err(|_| ProtocolError::Noise) + host.write_message_vec(b"") + .map_err(|_| ProtocolError::Noise) } pub fn handshake_finalize( @@ -378,11 +379,14 @@ mod handshake_tests { let (mut send, mut recv) = host.get_ciphers(); let (mut device_recv, mut device_send) = device.get_ciphers(); assert_eq!( - device_recv.decrypt_vec(&send.encrypt_vec(b"request")).unwrap(), + device_recv + .decrypt_vec(&send.encrypt_vec(b"request")) + .unwrap(), b"request" ); assert_eq!( - recv.decrypt_vec(&device_send.encrypt_vec(b"reply")).unwrap(), + recv.decrypt_vec(&device_send.encrypt_vec(b"reply")) + .unwrap(), b"reply" ); } diff --git a/src/util.rs b/src/util.rs index 5c8f32c..3c7902e 100644 --- a/src/util.rs +++ b/src/util.rs @@ -1,5 +1,6 @@ // SPDX-License-Identifier: Apache-2.0 +#[cfg(any(feature = "client", test))] pub fn remove_leading_zeroes(list: &[u8]) -> Vec { if let Some(first_non_zero) = list.iter().position(|&x| x != 0) { list[first_non_zero..].to_vec() From 5f43a4fdfbb18331c76658c321161809cce4a7df Mon Sep 17 00:00:00 2001 From: Trevor Arjeski Date: Thu, 26 Nov 2026 08:55:04 +0000 Subject: [PATCH 13/23] docs: describe the transport-free protocol feature MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Document the feature boundary and the caller’s fresh-ephemeral-key requirement. --- CHANGELOG.md | 3 +++ README.md | 13 +++++++++++++ 2 files changed, 16 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 8df68d6..9d1c848 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,9 @@ # Changelog ## [Unreleased] +- Expose transport-free protobuf, Bitcoin, signature validation, Noise, and framing primitives + with `default-features = false`. Defaults retain the async convenience clients. +- Reject malformed root fingerprints, oversized U2F messages, and invalid continuation headers. - Preserve the sign of positive EIP-712 signed integers supplied as JSON numbers. - Reset unfinished sessions when connecting to firmware v9.28.0 or newer, allowing host reconnects while the device remains powered on. diff --git a/README.md b/README.md index 3e5f1c4..45905a7 100644 --- a/README.md +++ b/README.md @@ -13,6 +13,19 @@ To run the example: See [Cargo.toml](Cargo.toml) for further examples. +## Protocol-only use + +Set `default-features = false` on `bitbox-api` to use the protobuf, Bitcoin, Noise, +signature validation, and framing primitives without the async client or its I/O +dependencies. The protocol-only library also builds for `wasm32-unknown-unknown`. +When initiating Noise yourself, supply a new cryptographically random ephemeral +key for each handshake. The caller owns pairing confirmation and transport. + +The default features are `client`, `persistence`, and `clock`. With defaults +disabled, enable `client` for the async API, `persistence` for JSON Noise config +and typed Ethereum message signing, and `clock` for system-time mnemonic restore. +`runtime` and `read-write` can be enabled separately for custom implementations. + ## Simulator tests The integration tests in [tests/](tests/) run against BitBox02 simulators. The simulators are From ee49e1b0c00ca2a24381de2bc285223fe8ba066a Mon Sep 17 00:00:00 2001 From: Trevor Arjeski Date: Thu, 26 Nov 2026 08:55:51 +0000 Subject: [PATCH 14/23] ci: verify the isolated native and WASM protocol surface - Check individual feature builds and guard the normal dependency closure. - Keep the existing client, simulator, USB, and example matrix. --- .github/workflows/rust.yml | 2 ++ ci.sh | 15 +++++++++++++++ 2 files changed, 17 insertions(+) diff --git a/.github/workflows/rust.yml b/.github/workflows/rust.yml index 89b44a6..bba4c2c 100644 --- a/.github/workflows/rust.yml +++ b/.github/workflows/rust.yml @@ -13,6 +13,7 @@ jobs: - uses: dtolnay/rust-toolchain@stable with: components: clippy, rustfmt + targets: wasm32-unknown-unknown - name: Enable simulators caching uses: actions/cache@v4 with: @@ -34,6 +35,7 @@ jobs: - uses: dtolnay/rust-toolchain@beta with: components: clippy, rustfmt + targets: wasm32-unknown-unknown - name: Enable simulators caching uses: actions/cache@v4 with: diff --git a/ci.sh b/ci.sh index a964906..99653a6 100755 --- a/ci.sh +++ b/ci.sh @@ -22,6 +22,21 @@ examples=( cargo fmt --check +cargo test --locked --lib --no-default-features +cargo check --locked --lib --no-default-features --target wasm32-unknown-unknown +for target in "$(rustc -vV | awk '$1 == "host:" { print $2 }')" wasm32-unknown-unknown; do + dependencies=$(cargo tree --locked --no-default-features --target "$target" \ + -e normal,build --prefix none --format '{p}') + if grep -E '^(async-trait|chrono|futures-util|getrandom|hidapi|js-sys|noise-rust-crypto|serde|serde_json|tokio|wasm-bindgen|web-sys) ' <<< "$dependencies"; then + echo "Unexpected transport, platform, or client dependency for $target" + exit 1 + fi +done + +for feature in runtime read-write client persistence clock; do + cargo check --locked --lib --no-default-features --features "$feature" +done + for feature_set in "${features[@]}"; do echo $feature_set cargo test --tests --locked --features="$feature_set" -- --nocapture --test-threads 1 From e4ad051d61421cf7a1c87e01e0dd7272a4f1f7a7 Mon Sep 17 00:00:00 2001 From: Trevor Arjeski Date: Thu, 26 Nov 2026 09:05:57 +0000 Subject: [PATCH 15/23] fix(btc): reject out-of-range PSBT previous outputs - Check the non-witness output index and preserve witness UTXO precedence. --- src/btc.rs | 57 +++++++++++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 54 insertions(+), 3 deletions(-) diff --git a/src/btc.rs b/src/btc.rs index 2cc951a..2d9227e 100644 --- a/src/btc.rs +++ b/src/btc.rs @@ -19,6 +19,7 @@ pub use bitcoin::{ }; use bitcoin::blockdata::{opcodes, script::Instruction}; +use bitcoin::psbt::SignError; #[derive(Clone, Debug, PartialEq)] pub struct PrevTxInput { @@ -474,15 +475,25 @@ impl Transaction { let mut output_script_configs = Vec::new(); let mut inputs = Vec::with_capacity(input_keys.len()); - for (input_index, ((tx_input, psbt_input), our_key)) in psbt + for ((tx_input, psbt_input), our_key) in psbt .unsigned_tx .input .iter() .zip(&psbt.inputs) .zip(&input_keys) - .enumerate() { - let utxo = psbt.spend_utxo(input_index).map_err(PsbtError::from)?; + // Unlike Psbt::spend_utxo, check that the non-witness output exists. + let utxo = psbt_input + .witness_utxo + .as_ref() + .or_else(|| { + psbt_input + .non_witness_utxo + .as_ref()? + .output + .get(tx_input.previous_output.vout as usize) + }) + .ok_or(PsbtError::SignError(SignError::MissingSpendUtxo))?; let script_config_index = if is_script_config_forced { 0 } else { @@ -2032,6 +2043,46 @@ mod tests { ); } + #[test] + fn psbt_lowering_checks_previous_output_index_without_a_witness_utxo() { + let (mut psbt, fingerprint, key) = psbt_fixture(); + let version = semver::Version::new(9, 24, 0); + let prev_tx = psbt.unsigned_tx.clone(); + psbt.unsigned_tx.input[0].previous_output = + bitcoin::OutPoint::new(prev_tx.compute_txid(), 1); + psbt.inputs[0].non_witness_utxo = Some(prev_tx); + + let lower = |psbt: &bitcoin::psbt::Psbt| { + [ + Transaction::from_psbt(&version, &fingerprint[..], psbt, None), + Transaction::from_psbt_with_keys( + &version, + psbt, + None, + vec![OurKey::Segwit( + key, + Keypath::try_from("m/84'/0'/0'/0/0").unwrap(), + )], + vec![None], + ), + ] + }; + + for result in lower(&psbt) { + assert_eq!(result.unwrap().transaction.inputs[0].prev_out_value, 1000); + } + + psbt.inputs[0].witness_utxo = None; + for result in lower(&psbt) { + assert!(matches!( + result, + Err(Error::Psbt(PsbtError::SignError( + SignError::MissingSpendUtxo + ))) + )); + } + } + #[test] fn psbt_lowering_requires_explicit_config_for_p2wsh() { use bitcoin::bip32::Xpriv; From 5147879d48a185d640e6e70f3973a4f8d88aed9c Mon Sep 17 00:00:00 2001 From: Trevor Arjeski Date: Thu, 26 Nov 2026 09:05:57 +0000 Subject: [PATCH 16/23] fix(btc): require firmware 9.22 for separate output configs --- src/btc.rs | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/src/btc.rs b/src/btc.rs index 2d9227e..75819ca 100644 --- a/src/btc.rs +++ b/src/btc.rs @@ -1106,6 +1106,10 @@ pub fn validate_signing( { validate_version(firmware_version, ">=9.10.0")?; } + if !output_script_configs.is_empty() || output_script_config_indices.iter().any(Option::is_some) + { + validate_version(firmware_version, ">=9.22.0")?; + } if transaction.outputs.iter().any(|output| { matches!( output, @@ -1970,6 +1974,15 @@ mod tests { resolved.output_script_config_indices ); assert_eq!(resolved.transaction.script_configs.len(), 1); + let validate = |version| { + validate_signing( + &version, + &resolved.transaction, + &resolved.output_script_configs, + &resolved.output_script_config_indices, + ) + }; + assert!(validate(version).is_ok()); if minor == 21 { assert_eq!(resolved.output_script_config_indices, [None]); assert!(resolved.output_script_configs.is_empty()); @@ -1982,6 +1995,10 @@ mod tests { } else { assert_eq!(resolved.output_script_config_indices, [Some(0)]); assert_eq!(resolved.output_script_configs.len(), 1); + assert!(matches!( + validate(semver::Version::new(9, 21, 0)), + Err(Error::Version(">=9.22.0")) + )); assert_eq!( resolved.output_script_configs[0].keypath, Keypath::try_from("m/84'/0'/1'").unwrap().as_slice(), From 55a1699e7593a584f72c8c149ced9c0e602576fa Mon Sep 17 00:00:00 2001 From: Trevor Arjeski Date: Thu, 26 Nov 2026 09:05:57 +0000 Subject: [PATCH 17/23] fix(noise): reject malformed pairing acknowledgements --- src/noise.rs | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/src/noise.rs b/src/noise.rs index 78c1ae9..1167c17 100644 --- a/src/noise.rs +++ b/src/noise.rs @@ -53,8 +53,13 @@ pub fn handshake_finalize( if !host.completed() { return Err(ProtocolError::Noise); } + let requires_verification = match device_ack { + [0] => false, + [1] => true, + _ => return Err(ProtocolError::Noise), + }; Ok(( - device_ack == [0x01], + requires_verification, host.get_rs().ok_or(ProtocolError::Noise)?, )) } @@ -375,6 +380,12 @@ mod handshake_tests { (true, X25519::pubkey(&key(3))) ); assert!(!handshake_finalize(&host, &[0]).unwrap().0); + for malformed in [&[][..], &[2], &[1, 0]] { + assert!(matches!( + handshake_finalize(&host, malformed), + Err(ProtocolError::Noise) + )); + } assert_eq!(host.get_hash(), device.get_hash()); let (mut send, mut recv) = host.get_ciphers(); let (mut device_recv, mut device_send) = device.get_ciphers(); From 5e21a191888ce0084f1febb477a547979fc01ea9 Mon Sep 17 00:00:00 2001 From: Trevor Arjeski Date: Thu, 26 Nov 2026 09:06:11 +0000 Subject: [PATCH 18/23] fix: reject malformed or incomplete BitBox reports - Zero U2F report padding and reject bad continuation headers as reports arrive. - Reject empty reads, short writes, and missing initialized flags in modern INFO replies. --- CHANGELOG.md | 3 +- src/communication.rs | 84 +++++++++++++++++++++++++++++++++++++------- src/u2fframing.rs | 43 ++++++++++++++++++----- 3 files changed, 108 insertions(+), 22 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 9d1c848..fe07f6b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,7 +3,8 @@ ## [Unreleased] - Expose transport-free protobuf, Bitcoin, signature validation, Noise, and framing primitives with `default-features = false`. Defaults retain the async convenience clients. -- Reject malformed root fingerprints, oversized U2F messages, and invalid continuation headers. +- Reject malformed fingerprint, pairing, and framing replies, and return an error for an + out-of-range previous output when lowering a PSBT. - Preserve the sign of positive EIP-712 signed integers supplied as JSON numbers. - Reset unfinished sessions when connecting to firmware v9.28.0 or newer, allowing host reconnects while the device remains powered on. diff --git a/src/communication.rs b/src/communication.rs index 3055833..eeb666d 100644 --- a/src/communication.rs +++ b/src/communication.rs @@ -44,7 +44,7 @@ pub trait ReadWrite: Threading { } #[cfg(feature = "client")] -pub struct U2fHidCommunication { +pub(crate) struct U2fHidCommunication { read_write: Box, u2fhid: u2fframing::U2fHid, } @@ -54,7 +54,7 @@ impl crate::util::Threading for U2fHidCommunication {} #[cfg(feature = "client")] impl U2fHidCommunication { - pub fn from(read_write: Box, cmd: u8) -> Self { + pub(crate) fn from(read_write: Box, cmd: u8) -> Self { U2fHidCommunication { read_write, u2fhid: u2fframing::U2fHid::new(cmd), @@ -73,23 +73,30 @@ impl ReadWrite for U2fHidCommunication { .encode(msg, &mut buf) .or(Err(Error::U2fEncode))?; for chunk in buf[..size].chunks(64) { - self.read_write.write(chunk)?; + // HID may include the extra report ID byte in its count. + if self.read_write.write(chunk)? < chunk.len() { + return Err(Error::Write); + } } Ok(size) } async fn read(&self) -> Result, Error> { let mut readbuf = self.read_write.read().await?; + let mut validated_continuations = 0; loop { - match self.u2fhid.decode(&readbuf).or(Err(Error::U2fDecode))? { - Some(d) => { - return Ok(d); - } - None => { - let more = self.read_write.read().await?; - readbuf.extend_from_slice(&more); - } + if let Some(payload) = self + .u2fhid + .decode_appended(&readbuf, &mut validated_continuations) + .or(Err(Error::U2fDecode))? + { + return Ok(payload); } + let more = self.read_write.read().await?; + if more.is_empty() { + return Err(Error::Read); + } + readbuf.extend_from_slice(&more); } } } @@ -192,6 +199,9 @@ pub fn parse_info(response: &[u8]) -> Result { let edition_byte = *response.get(1).ok_or(Error::Info)?; let unlocked_byte = *response.get(2).ok_or(Error::Info)?; let initialized_byte = response.get(3); + if initialized_byte.is_none() && version >= semver::Version::new(9, 20, 0) { + return Err(Error::Info); + } Ok(Info { version, product: match (platform_byte, edition_byte) { @@ -332,7 +342,10 @@ mod tests { assert_eq!(old.initialized, None); assert!(!needs_session_reset(&old.version)); - let new = parse_info(b"\x07v9.28.0\x02\x01\x00\x01").unwrap(); + let first = parse_info(b"\x07v9.20.0\x00\x00\x01\x00").unwrap(); + assert_eq!(first.initialized, Some(false)); + + let new = parse_info(b"\x07v9.28.0\x02\x01\x00\x01\xFF").unwrap(); assert_eq!(new.product, Product::BitBox02NovaBtcOnly); assert!(!new.unlocked); assert_eq!(new.initialized, Some(true)); @@ -341,12 +354,59 @@ mod tests { for invalid in [ &b"\x08v9.28.0"[..], + &b"\x07v9.20.0\x00\x00\x01"[..], &b"\x079.28.00\x02\x01\x00"[..], &b"\x07v9.28.0\x02\x01"[..], + &b"\x07v9.28.0\x02\x01\x00"[..], &b"\x07v9.28.0\x02\x01\x02"[..], &b"\x07v9.28.0\x02\x01\x00\x02"[..], ] { assert!(matches!(parse_info(invalid), Err(Error::Info))); } } + + #[cfg(feature = "client")] + #[tokio::test] + async fn u2f_transport_checks_report_io() { + struct Transport { + reads: std::sync::Mutex>>, + write_len: usize, + } + + impl Threading for Transport {} + + #[cfg_attr(feature = "multithreaded", async_trait)] + #[cfg_attr(not(feature = "multithreaded"), async_trait(?Send))] + impl ReadWrite for Transport { + fn write(&self, _msg: &[u8]) -> Result { + Ok(self.write_len) + } + + async fn read(&self) -> Result, Error> { + Ok(self.reads.lock().unwrap().next().expect("unexpected read")) + } + } + + let codec = u2fframing::U2fHid::new(FIRMWARE_CMD); + let payload = [0xA5; 117]; + let mut encoded = [0; 192]; + assert_eq!(codec.encode(&payload, &mut encoded).unwrap(), encoded.len()); + let transport = |reads: Vec>, write_len| { + U2fHidCommunication::from( + Box::new(Transport { + reads: std::sync::Mutex::new(reads.into_iter()), + write_len, + }), + FIRMWARE_CMD, + ) + }; + + let short = transport(vec![encoded[..64].to_vec(), vec![]], 63); + assert!(matches!(short.write(&payload), Err(Error::Write))); + assert!(matches!(short.read().await, Err(Error::Read))); + + let hid = transport(encoded.chunks(64).map(<[u8]>::to_vec).collect(), 65); + assert_eq!(hid.write(&payload).unwrap(), encoded.len()); + assert_eq!(hid.read().await.unwrap(), payload); + } } diff --git a/src/u2fframing.rs b/src/u2fframing.rs index 995152d..6759a19 100644 --- a/src/u2fframing.rs +++ b/src/u2fframing.rs @@ -106,6 +106,7 @@ impl U2fHid { "Message won't fit in buffer", )); } + buf = &mut buf[..enc_len]; let len = encode_header_init(self.cid, self.cmd, message.len() as u16, buf)?; buf = &mut buf[len..]; @@ -130,12 +131,22 @@ impl U2fHid { seq += 1; } + buf.fill(0); Ok(enc_len) } /// Decode a message from whole reports, ignoring extra reports after the message. /// Returns `Ok(None)` if more whole reports are needed. pub fn decode(&self, buf: &[u8]) -> io::Result>> { + self.decode_appended(buf, &mut 0) + } + + // `validated_continuations` counts reports already checked in an unchanged prefix of `buf`. + pub(crate) fn decode_appended( + &self, + buf: &[u8], + validated_continuations: &mut usize, + ) -> io::Result>> { if buf.is_empty() || !buf.chunks_exact(REPORT_LEN).remainder().is_empty() { return Err(io::Error::new( io::ErrorKind::UnexpectedEof, @@ -164,13 +175,10 @@ impl U2fHid { } let enc_len = Self::get_encoded_len(len); - if buf.len() < enc_len { - return Ok(None); - } - - let mut res = Vec::with_capacity(len); - res.extend_from_slice(&buf[HEADER_INIT_LEN..HEADER_INIT_LEN + PAYLOAD_INIT_LEN.min(len)]); - for (seq, report) in buf[..enc_len].chunks_exact(REPORT_LEN).skip(1).enumerate() { + let available_len = buf.len().min(enc_len); + let next_report = (1 + *validated_continuations) * REPORT_LEN; + let new_reports = buf[next_report..available_len].chunks_exact(REPORT_LEN); + for (seq, report) in (*validated_continuations..).zip(new_reports) { if report[..4] != buf[..4] { return Err(io::Error::new(io::ErrorKind::InvalidData, "Wrong CID")); } @@ -180,6 +188,15 @@ impl U2fHid { "Wrong continuation sequence", )); } + } + if buf.len() < enc_len { + *validated_continuations = available_len / REPORT_LEN - 1; + return Ok(None); + } + + let mut res = Vec::with_capacity(len); + res.extend_from_slice(&buf[HEADER_INIT_LEN..HEADER_INIT_LEN + PAYLOAD_INIT_LEN.min(len)]); + for report in buf[REPORT_LEN..enc_len].chunks_exact(REPORT_LEN) { let take = PAYLOAD_CONT_LEN.min(len - res.len()); res.extend_from_slice(&report[HEADER_CONT_LEN..HEADER_CONT_LEN + take]); } @@ -211,19 +228,20 @@ mod tests { #[test] fn test_u2fhid_encode_single() { let codec = U2fHid::with_cid(0xEEEEEEEE, 0x55); - let mut data = [0u8; 8000]; + let mut data = [0xAA; 128]; let len = codec.encode(b"\x01\x02\x03\x04", &mut data[..]).unwrap(); assert_eq!(len, 64); let mut expect = [0u8; 64]; expect[..11].copy_from_slice(b"\xEE\xEE\xEE\xEE\x55\x00\x04\x01\x02\x03\x04"); assert_eq!(&data[..len], &expect[..]); + assert!(data[len..].iter().all(|&byte| byte == 0xAA)); } #[test] fn test_u2fhid_encode_multi() { let payload: Vec = (0..65u8).collect(); let codec = U2fHid::with_cid(0xEEEEEEEE, 0x55); - let mut data = [0u8; 8000]; + let mut data = [0xAA; 192]; let len = codec.encode(&payload[..], &mut data[..]).unwrap(); assert_eq!(len, 128); let mut expect = [0u8; 128]; @@ -232,6 +250,7 @@ mod tests { expect[64..69].copy_from_slice(b"\xEE\xEE\xEE\xEE\x00"); expect[69..77].copy_from_slice(&payload[57..]); assert_eq!(&data[..len], &expect[..]); + assert!(data[len..].iter().all(|&byte| byte == 0xAA)); } #[test] @@ -300,6 +319,12 @@ mod tests { codec.decode(&malformed).unwrap_err().kind(), io::ErrorKind::InvalidData, ); + if offset < 128 { + assert_eq!( + codec.decode(&malformed[..128]).unwrap_err().kind(), + io::ErrorKind::InvalidData, + ); + } } } From ac450446c1572cfcb31493135615ba61231dae15 Mon Sep 17 00:00:00 2001 From: Trevor Arjeski Date: Thu, 26 Nov 2026 09:06:11 +0000 Subject: [PATCH 19/23] build: gate client-only hex and zeroize dependencies --- Cargo.toml | 16 +++++++++++++--- 1 file changed, 13 insertions(+), 3 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index c9d916e..11098cb 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -18,7 +18,7 @@ bitcoin = "0.32" byteorder = "1.3.2" getrandom = { version = "0.2", optional = true } futures-util = { version = "0.3", default-features = false, features = ["std"], optional = true } -hex = { version = "0.4" } +hex = { version = "0.4", optional = true } noise-protocol = "0.2" noise-rust-crypto = { version = "0.6", optional = true } num-bigint = { version = "0.4", optional = true } @@ -28,7 +28,7 @@ prost = "0.14" semver = "1.0.17" serde_json = { version = "1.0", optional = true } thiserror = "2.0" -zeroize = "1" +zeroize = { version = "1", optional = true } chrono = { version = "0.4.38", default-features = false, features = ["clock"], optional = true } hidapi = { version = "2.3", optional = true } @@ -40,6 +40,7 @@ tokio = { version = "1", optional = true, features = ["time"] } # For the base64 PSBT input/output in examples/btc_sign_psbt.rs. bitcoin = { version = "0.32", features = ["base64"] } futures-channel = "0.3" +hex = "0.4" noise-rust-crypto = "0.6" tokio = { version = "1", features = ["time", "macros", "rt", "fs"] } reqwest = "0.12" @@ -98,7 +99,16 @@ required-features = ["simulator", "tokio/rt", "tokio/macros", "tokio/rt-multi-th default = ["client", "persistence", "clock"] runtime = ["dep:async-trait"] read-write = ["dep:async-trait"] -client = ["runtime", "read-write", "dep:futures-util", "dep:getrandom", "dep:noise-rust-crypto", "dep:num-bigint"] +client = [ + "runtime", + "read-write", + "dep:futures-util", + "dep:getrandom", + "dep:hex", + "dep:noise-rust-crypto", + "dep:num-bigint", + "dep:zeroize", +] persistence = ["dep:serde", "dep:serde_json"] clock = ["client", "dep:chrono"] usb = ["client", "dep:hidapi"] From 0006cffdfd8958a54b8432efdd5409fc3e8d269d Mon Sep 17 00:00:00 2001 From: Trevor Arjeski Date: Thu, 26 Nov 2026 10:58:40 +0000 Subject: [PATCH 20/23] fix(btc): validate compact PSBT signatures - Reject invalid compact scalars and high-S signatures without parsing twice. - Document caller-owned signature verification and cover rejection before insertion. --- CHANGELOG.md | 1 + src/btc.rs | 25 ++++++++++++++++++++++++- src/secp256k1.rs | 6 +++++- 3 files changed, 30 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index fe07f6b..affdd60 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,7 @@ with `default-features = false`. Defaults retain the async convenience clients. - Reject malformed fingerprint, pairing, and framing replies, and return an error for an out-of-range previous output when lowering a PSBT. +- Reject malformed compact ECDSA signatures when applying signatures to a PSBT. - Preserve the sign of positive EIP-712 signed integers supplied as JSON numbers. - Reset unfinished sessions when connecting to firmware v9.28.0 or newer, allowing host reconnects while the device remains powered on. diff --git a/src/btc.rs b/src/btc.rs index 75819ca..79e2a75 100644 --- a/src/btc.rs +++ b/src/btc.rs @@ -592,6 +592,8 @@ impl Transaction { /// /// A count mismatch is rejected before mutation. If a later signature is malformed, earlier /// signatures may already have been applied. +/// +/// Callers must verify the transaction signatures and any required Anti-Klepto proofs. pub fn apply_signatures( psbt: &mut bitcoin::psbt::Psbt, signatures: &[Vec], @@ -610,7 +612,7 @@ pub fn apply_signatures( for ((input, signature), key) in psbt.inputs.iter_mut().zip(signatures).zip(our_keys) { match key { OurKey::Segwit(pubkey, _) => { - let signature = bitcoin::secp256k1::ecdsa::Signature::from_compact(signature) + let signature = crate::secp256k1::parse_signature_compact(signature) .map_err(|_| Error::InvalidSignature)?; input.partial_sigs.insert( bitcoin::PublicKey::new(*pubkey), @@ -2173,6 +2175,27 @@ mod tests { assert!(psbt.inputs[0].partial_sigs.is_empty()); } + #[test] + fn signature_application_rejects_invalid_ecdsa_scalars() { + let (mut psbt, _, key) = psbt_fixture(); + let keys = [OurKey::Segwit(key, Keypath::try_from("m/").unwrap())]; + let mut zero_r = [0; 64]; + zero_r[63] = 1; + let mut zero_s = [0; 64]; + zero_s[31] = 1; + let mut high_s = zero_s; + high_s[32..].copy_from_slice(&bitcoin::secp256k1::constants::CURVE_ORDER); + high_s[63] -= 1; + + for invalid in [zero_r, zero_s, high_s] { + assert!(matches!( + apply_signatures(&mut psbt, &[invalid.to_vec()], &keys), + Err(Error::InvalidSignature) + )); + assert!(psbt.inputs[0].partial_sigs.is_empty()); + } + } + #[test] fn signature_application_preserves_partial_signatures_and_applies_in_order() { use bitcoin::secp256k1::{Keypair, Message, PublicKey, Secp256k1, SecretKey}; diff --git a/src/secp256k1.rs b/src/secp256k1.rs index a7ff5f2..117b383 100644 --- a/src/secp256k1.rs +++ b/src/secp256k1.rs @@ -12,6 +12,10 @@ pub struct ValidationError(&'static str); /// /// Both scalars must be nonzero and in range, and `s` must use its low-S encoding. pub fn validate_signature_compact(signature: &[u8]) -> Result<(), ValidationError> { + parse_signature_compact(signature).map(|_| ()) +} + +pub(crate) fn parse_signature_compact(signature: &[u8]) -> Result { if signature.len() != 64 { return Err(ValidationError("Signature must be 64 bytes")); } @@ -28,7 +32,7 @@ pub fn validate_signature_compact(signature: &[u8]) -> Result<(), ValidationErro if normalized_signature != parsed_signature { return Err(ValidationError("ECDSA signature has high S")); } - Ok(()) + Ok(parsed_signature) } /// Validates a 65-byte recoverable ECDSA signature encoded as `r || s || recovery_id`. From a07113f4dcd017516b8aa062173963bb233c239b Mon Sep 17 00:00:00 2001 From: Trevor Arjeski Date: Thu, 26 Nov 2026 10:58:46 +0000 Subject: [PATCH 21/23] fix(btc): preserve client signing reply envelopes - Reject nested replies to top-level requests and top-level replies to nested requests. - Keep both envelopes supported by the standalone parser. --- src/btc.rs | 33 ++++++++++++++++++++++++++++++++- 1 file changed, 32 insertions(+), 1 deletion(-) diff --git a/src/btc.rs b/src/btc.rs index 79e2a75..7f65098 100644 --- a/src/btc.rs +++ b/src/btc.rs @@ -1029,6 +1029,17 @@ pub fn parse_sign_next(response: Response) -> Result Result { + if nested != matches!(response, Response::Btc(_)) { + return Err(Error::UnexpectedResponse); + } + parse_sign_next(response) +} + /// Extracts the device's Anti-Klepto commitment in a message signing exchange. pub fn parse_signer_commitment(response: Response) -> Result, Error> { match btc_response(response)? { @@ -1221,7 +1232,8 @@ impl PairedBitBox { } async fn get_next_response(&self, request: Request) -> Result { - parse_sign_next(self.query_proto(request).await?) + let nested = matches!(request, Request::Btc(_)); + parse_client_sign_next(self.query_proto(request).await?, nested) } /// Sign a Bitcoin transaction. Returns one 64 byte signature (compact serlization of the R and @@ -1802,6 +1814,25 @@ mod tests { )); } + #[cfg(feature = "client")] + #[test] + fn client_sign_next_rejects_the_wrong_response_envelope() { + let next = pb::BtcSignNextResponse::default(); + for (response, nested) in [ + (Response::BtcSignNext(next.clone()), false), + ( + nested_response(pb::btc_response::Response::SignNext(next.clone())), + true, + ), + ] { + assert!(matches!( + parse_client_sign_next(response.clone(), !nested), + Err(Error::UnexpectedResponse) + )); + assert_eq!(parse_client_sign_next(response, nested).unwrap(), next); + } + } + #[test] fn message_reply_parsing_validates_encoding_but_not_nonce() { use pb::btc_response::Response as BtcResponse; From 1f28df76acae5bcb89ede573c4503126d46424d7 Mon Sep 17 00:00:00 2001 From: Trevor Arjeski Date: Thu, 26 Nov 2026 10:58:46 +0000 Subject: [PATCH 22/23] fix(u2f): preserve the public communication error enum - Report adapter encoding errors as Write and retain detailed codec errors. --- src/communication.rs | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/src/communication.rs b/src/communication.rs index eeb666d..f474df2 100644 --- a/src/communication.rs +++ b/src/communication.rs @@ -22,8 +22,6 @@ pub enum Error { Read, #[error("u2f framing decoding error")] U2fDecode, - #[error("u2f framing encoding error")] - U2fEncode, #[error("error querying device info")] Info, #[error("firmware version {0} required")] @@ -68,10 +66,7 @@ impl U2fHidCommunication { impl ReadWrite for U2fHidCommunication { fn write(&self, msg: &[u8]) -> Result { let mut buf = [0u8; u2fframing::MAX_LEN]; - let size = self - .u2fhid - .encode(msg, &mut buf) - .or(Err(Error::U2fEncode))?; + let size = self.u2fhid.encode(msg, &mut buf).or(Err(Error::Write))?; for chunk in buf[..size].chunks(64) { // HID may include the extra report ID byte in its count. if self.read_write.write(chunk)? < chunk.len() { @@ -406,6 +401,10 @@ mod tests { assert!(matches!(short.read().await, Err(Error::Read))); let hid = transport(encoded.chunks(64).map(<[u8]>::to_vec).collect(), 65); + assert!(matches!( + hid.write(&[0; u2fframing::MAX_LEN]), + Err(Error::Write) + )); assert_eq!(hid.write(&payload).unwrap(), encoded.len()); assert_eq!(hid.read().await.unwrap(), payload); } From 99a9718793547ad8969dd720e23d92e415129c4e Mon Sep 17 00:00:00 2001 From: Trevor Arjeski Date: Thu, 26 Nov 2026 10:58:46 +0000 Subject: [PATCH 23/23] docs(antiklepto): define the caller nonce contract - Specify per-signature entropy, commitment ordering, and the verification boundary. --- src/antiklepto.rs | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/src/antiklepto.rs b/src/antiklepto.rs index 97c1b8c..3c8cadd 100644 --- a/src/antiklepto.rs +++ b/src/antiklepto.rs @@ -43,6 +43,11 @@ pub(crate) fn gen_host_nonce() -> Result<[u8; 32], Error> { Ok(result) } +/// Commits to a host nonce for one Anti-Klepto signature. +/// +/// Generate a fresh, secret 32-byte nonce with a cryptographically secure RNG for each +/// signature. Send only the commitment until the signer returns its commitment, then +/// reveal the nonce and verify its contribution before accepting the signature. pub fn host_commit(host_nonce: &[u8]) -> [u8; 32] { tagged_sha256(b"s2c/ecdsa/data", host_nonce) } @@ -50,6 +55,8 @@ pub fn host_commit(host_nonce: &[u8]) -> [u8; 32] { /// Verifies that `host_nonce` was used to tweak the nonce during signature generation according /// to k' = k + H(signer_commitment, host_nonce) by checking that /// k'*G = signer_commitment + H(signer_commitment, host_nonce)*G. +/// +/// This does not verify the signature against the message and signing key. pub fn verify_ecdsa( host_nonce: &[u8], signer_commitment: &[u8], @@ -60,6 +67,8 @@ pub fn verify_ecdsa( } /// Validates a recoverable ECDSA signature and verifies its Anti-Klepto nonce contribution. +/// +/// This does not verify the signature against the message and signing key. pub fn verify_recoverable_ecdsa( host_nonce: &[u8], signer_commitment: &[u8],