Merge remote-tracking branch 'agent/benma-agent/compact-biguint'
What changed, and why it matters
This commit is a code-size optimization, not a security fix. It replaces generic num-bigint decimal formatting and multiplication/division routines in the Ethereum signing code with smaller, hand-written scalar versions. The goal is to reduce the firmware binary size by avoiding large arithmetic helpers. A new CI check was added to prevent these heavy symbols from creeping back in. There is no evidence in the commit of a vulnerability, exploit, or security incident.
No security action required. Treat as a normal optimization/refactoring commit. Reviewers may want to confirm the new scalar arithmetic is correct for all inputs and that the CI symbol regexes match intended num-bigint symbols without false positives.
Security signals we found
No security-relevant signals present in the diff
Change is framed by the author as binary-size reduction, not as a vulnerability fix
No bounds-checking, memory-safety, or cryptographic changes observed
Evidence from the diff
The change refactors BigUint/BigInt usage in the BitBox02 firmware to avoid pulling in num-bigint’s general multiplication, division, and radix-conversion routines. In ethereum/sign.rs, parse_fee() now computes gas_limit * gas_price by iterating over bytes and using scalar u32 operations instead of BigUint multiplication. In ethereum/sign_typed_msg.rs, BigUint/BigInt to_string() calls are replaced with util::decimal helpers that perform scalar division by 10. A new util::decimal module provides biguint_to_string and bigint_to_string. The CI script check-unwanted-symbols is extended to flag these num-bigint symbols. The commit includes unit tests verifying equivalence with the original BigUint behavior.
Changed components
Ethereum transaction fee parsing (src/rust/bitbox02-rust/src/hww/api/ethereum/sign.rs)EIP-712 typed message value formatting (src/rust/bitbox02-rust/src/hww/api/ethereum/sign_typed_msg.rs)Decimal formatting utility (src/rust/util/src/decimal.rs)CI firmware symbol check (.ci/check-unwanted-symbols)Inspect captured patch +138 / −11
### .ci/check-unwanted-symbols
@@ -68,6 +68,20 @@ check_firmware() {
"(__aeabi_f(add|sub|mul|div)|__(add|sub|mul|div|neg)sf3|compiler_builtins::float::(add|sub|mul|div)::.*f32)" \
"Software f32 arithmetic helpers add significant binary bloat." \
"Use integer arithmetic in firmware code instead."
+
+ check_symbols \
+ "$elf" \
+ "num-bigint decimal formatting" \
+ "num_bigint::(biguint::BigUint|bigint::BigInt).*(to_str_radix|as core::fmt::Display)" \
+ "Generic BigUint/BigInt decimal formatting pulls in large-number arithmetic." \
+ "Use the util::decimal helpers instead."
+
+ check_symbols \
+ "$elf" \
+ "num-bigint general multiplication and division" \
+ "num_bigint::biguint::(multiplication::(mac3|mul3)|division::div_rem_core)" \
+ "General BigUint multiplication and division add significant binary bloat." \
+ "Use scalar arithmetic where possible, as in Ethereum's parse_fee()."
}
check_bootloader() {
### src/rust/bitbox02-rust/src/hww/api/ethereum/sign.rs
@@ -20,7 +20,7 @@ use alloc::vec::Vec;
use hex_lit::hex;
use pb::eth_response::Response;
-use core::ops::{Add, Mul};
+use core::ops::Add;
use num_bigint::BigUint;
// 1 ETH = 1e18 wei.
@@ -202,22 +202,31 @@ async fn verify_payment_request_recipient(
// 1) actual gas used will often be lower than gas limit (in the case of contract interactions, not simple ETH transfers)
// 2) in the case of 1559 base fee at execution time might also be lower so that `base fee + priority fee < max fee per gas`
fn parse_fee<'a>(request: &Transaction<'_>, params: &'a Params) -> Amount<'a> {
- let gas_limit = BigUint::from_bytes_be(request.gas_limit());
+ let gas_limit = request.gas_limit();
+ fn multiply_by_be_bytes(value: &BigUint, bytes: &[u8]) -> BigUint {
+ // Scalar products avoid pulling in num-bigint's large-number multiplication routines.
+ let mut result = BigUint::ZERO;
+ for &byte in bytes {
+ result <<= 8;
+ result += value * u32::from(byte);
+ }
+ result
+ }
match request {
Transaction::Legacy(legacy) => {
let gas_price = BigUint::from_bytes_be(&legacy.gas_price);
Amount {
unit: params.unit,
decimals: WEI_DECIMALS,
- value: gas_price.mul(gas_limit),
+ value: multiply_by_be_bytes(&gas_price, gas_limit),
}
}
Transaction::Eip1559(eip1559) => {
let max_fee_per_gas = BigUint::from_bytes_be(&eip1559.max_fee_per_gas);
Amount {
unit: params.unit,
decimals: WEI_DECIMALS,
- value: max_fee_per_gas.mul(gas_limit),
+ value: multiply_by_be_bytes(&max_fee_per_gas, gas_limit),
}
}
}
@@ -735,6 +744,49 @@ mod tests {
}
}
+ #[test]
+ fn test_parse_fee_matches_biguint_multiplication() {
+ let params = Params {
+ coin: Some(pb::EthCoin::Eth),
+ chain_id: 1,
+ bip44_coin: 60 + HARDENED,
+ name: "Ethereum",
+ unit: "ETH",
+ };
+ // Pair zero, one, mixed-byte values, and the largest allowed 128-bit value
+ // to exercise byte order, zero bytes, and carries in both operands.
+ let operands: &[&[u8]] = &[
+ &[],
+ &hex!("01"),
+ &hex!("010002"),
+ &hex!("0123456789abcdef0123456789abcdef"),
+ &[0xff; 16],
+ ];
+ for price in operands {
+ for limit in operands {
+ let expected = BigUint::from_bytes_be(price) * BigUint::from_bytes_be(limit);
+ let legacy = pb::EthSignRequest {
+ gas_price: price.to_vec(),
+ gas_limit: limit.to_vec(),
+ ..Default::default()
+ };
+ let eip1559 = pb::EthSignEip1559Request {
+ max_fee_per_gas: price.to_vec(),
+ max_priority_fee_per_gas: vec![1],
+ gas_limit: limit.to_vec(),
+ ..Default::default()
+ };
+ for request in [Transaction::Legacy(&legacy), Transaction::Eip1559(&eip1559)] {
+ assert_eq!(
+ parse_fee(&request, ¶ms).value,
+ expected,
+ "price={price:02x?}, limit={limit:02x?}"
+ );
+ }
+ }
+ }
+ }
+
#[test]
pub fn test_parse_recipient() {
assert_eq!(
### src/rust/bitbox02-rust/src/hww/api/ethereum/sign_typed_msg.rs
@@ -321,7 +321,7 @@ fn encode_value(
}
(
leftpad32(&value, false)?,
- BigUint::from_bytes_be(&value).to_string(),
+ util::decimal::biguint_to_string(&BigUint::from_bytes_be(&value)),
)
}
DataType::Int => {
@@ -330,7 +330,7 @@ fn encode_value(
}
(
leftpad32(&value, true)?,
- BigInt::from_signed_bytes_be(&value).to_string(),
+ util::decimal::bigint_to_string(&BigInt::from_signed_bytes_be(&value)),
)
}
DataType::Bool => {
### src/rust/util/src/decimal.rs
@@ -3,20 +3,51 @@
extern crate alloc;
use alloc::string::{String, ToString};
-use num_bigint::BigUint;
+use num_bigint::{BigInt, BigUint};
-pub trait Format: ToString {}
+pub trait Format: ToString {
+ fn decimal_string(&self) -> String {
+ self.to_string()
+ }
+}
impl Format for u64 {}
-impl Format for &BigUint {}
+impl Format for &BigUint {
+ fn decimal_string(&self) -> String {
+ biguint_to_string(self)
+ }
+}
+
+pub fn biguint_to_string(value: &BigUint) -> String {
+ // Scalar division avoids pulling in num-bigint's large-number radix conversion routines.
+ if value == &BigUint::ZERO {
+ return "0".into();
+ }
+ let mut value = value.clone();
+ let mut digits = alloc::vec::Vec::new();
+ while value != BigUint::ZERO {
+ digits.push(b'0' + u8::try_from(&value % 10u32).unwrap());
+ value /= 10u32;
+ }
+ digits.reverse();
+ String::from_utf8(digits).unwrap()
+}
+
+pub fn bigint_to_string(value: &BigInt) -> String {
+ let mut text = biguint_to_string(value.magnitude());
+ if value.sign() == num_bigint::Sign::Minus {
+ text.insert(0, '-');
+ }
+ text
+}
/// Formats integer `value` as `value / 10^decimals`, with up to `decimals` decimal places,
/// trimming traling zeroes.
/// E.g. "123450" with decimals=3: "123.45".
/// Value must consists only of '0'-'9' digits.
pub fn format<F: Format>(value: F, decimals: usize) -> String {
- let mut v: String = format!("{:0>width$}", value.to_string(), width = decimals + 1);
+ let mut v: String = format!("{:0>width$}", value.decimal_string(), width = decimals + 1);
v.insert(v.len() - decimals, '.');
v.trim_end_matches('0').trim_end_matches('.').into()
}
@@ -26,7 +57,7 @@ pub fn format<F: Format>(value: F, decimals: usize) -> String {
/// E.g. "123450" with decimals=3: "123.450".
/// Value must consists only of '0'-'9' digits.
pub fn format_no_trim<F: Format>(value: F, decimals: usize) -> String {
- let mut v: String = format!("{:0>width$}", value.to_string(), width = decimals + 1);
+ let mut v: String = format!("{:0>width$}", value.decimal_string(), width = decimals + 1);
if decimals > 0 {
v.insert(v.len() - decimals, '.');
}
@@ -37,6 +68,36 @@ pub fn format_no_trim<F: Format>(value: F, decimals: usize) -> String {
mod tests {
use super::*;
+ #[test]
+ fn test_biguint_to_string() {
+ let two_to_256 = BigUint::from(1u32) << 256usize;
+ for value in [
+ BigUint::ZERO,
+ BigUint::from(1u32),
+ BigUint::from(9u32),
+ BigUint::from(10u32),
+ BigUint::from(1_020_030u32),
+ BigUint::from(u64::MAX),
+ &two_to_256 - 1u32,
+ two_to_256,
+ ] {
+ assert_eq!(biguint_to_string(&value), value.to_string());
+ }
+ }
+
+ #[test]
+ fn test_bigint_to_string() {
+ for value in [
+ BigInt::from(0),
+ BigInt::from(1),
+ BigInt::from(-1),
+ BigInt::from(i64::MIN),
+ -(BigInt::from(1u32) << 255usize),
+ ] {
+ assert_eq!(bigint_to_string(&value), value.to_string());
+ }
+ }
+
#[test]
fn test_format_int() {
assert_eq!(format(0u64, 0), "0");Why this scored 19/100
Community notes
Notes can correct, qualify, or add evidence to the AI analysis. Every note shown here has been validated by a human moderator.
The AI analysis stands alone for now. Submit a note if you can add evidence or important context.