Skip to content

Commit

Permalink
SFT-3908: Switch to faster-hex from hex crate.
Browse files Browse the repository at this point in the history
  • Loading branch information
jeandudey committed Aug 1, 2024
1 parent 8a5d9eb commit 1b777cf
Show file tree
Hide file tree
Showing 14 changed files with 70 additions and 99 deletions.
2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,8 @@ bs58 = "0.5"
clap = { version = "4", features = ["cargo"] }
crc = "3"
criterion = { version = "0.4" }
faster-hex = { version = "0.9", default-features = false }
heapless = { version = "0.8", default-features = false }
hex = { version = "0.4.2", default-features = false }
itertools = { version = "0.10", default-features = false }
libfuzzer-sys = "0.4"
minicbor = { version = "0.24", features = ["derive"] }
Expand Down
8 changes: 6 additions & 2 deletions codecs/src/nostr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,9 @@ pub mod tests {
let vectors = NIP19Vector::new();

for vector in vectors.iter().filter(|t| t.kind == NPUB) {
let encoded = encode_npub(&vector.bytes);
let mut public_key = [0; 32];
public_key.copy_from_slice(&vector.bytes);
let encoded = encode_npub(&public_key);
assert_eq!(&encoded, &*vector.encoded);
}
}
Expand All @@ -108,7 +110,9 @@ pub mod tests {
let vectors = NIP19Vector::new();

for vector in vectors.iter().filter(|t| t.kind == NSEC) {
let encoded = encode_nsec(&vector.bytes);
let mut private_key = [0; 32];
private_key.copy_from_slice(&vector.bytes);
let encoded = encode_nsec(&private_key);
assert_eq!(&encoded, &*vector.encoded);
}
}
Expand Down
6 changes: 3 additions & 3 deletions firmware/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -18,14 +18,14 @@ required-features = ["binary"]

[features]
default = ["std", "binary"]
std = ["anyhow/std", "hex?/std", "nom/std", "secp256k1/std"]
binary = ["anyhow", "clap", "hex", "secp256k1/global-context", "std"]
std = ["anyhow/std", "faster-hex?/std", "nom/std", "secp256k1/std"]
binary = ["anyhow", "clap", "faster-hex", "secp256k1/global-context", "std"]

[dependencies]
bitcoin_hashes = { workspace = true }
clap = { workspace = true, optional = true }
heapless = { workspace = true }
hex = { workspace = true, optional = true }
faster-hex = { workspace = true, optional = true }
nom = { workspace = true }
secp256k1 = { workspace = true }
anyhow = { workspace = true, optional = true }
Expand Down
11 changes: 6 additions & 5 deletions firmware/src/bin/foundation-firmware.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
use anyhow::{anyhow, bail, Context, Result};
use bitcoin_hashes::{sha256, sha256d, Hash, HashEngine};
use clap::{command, value_parser, Arg, ArgAction};
use faster_hex::hex_string;
use foundation_firmware::{header, Header, Information, HEADER_LEN};
use nom::Finish;
use secp256k1::{global::SECP256K1, PublicKey};
Expand Down Expand Up @@ -56,7 +57,7 @@ fn main() -> Result<()> {
println!(
"{:>17}: {}",
"User Public Key",
hex::encode(public_key.serialize_uncompressed())
hex_string(&public_key.serialize_uncompressed())
);
}

Expand Down Expand Up @@ -86,9 +87,9 @@ fn print_header(header: &Header) {
println!("{:>17}: {}", "Version", header.information.version);
println!("{:>17}: {} bytes", "Length", header.information.length);
println!("{:>17}: {}", "Key", header.signature.public_key1);
println!("{:>17}: {}", "Signature", hex::encode(signature1));
println!("{:>17}: {}", "Signature", hex_string(&signature1));
println!("{:>17}: {}", "Key", header.signature.public_key2);
println!("{:>17}: {}", "Signature", hex::encode(signature2));
println!("{:>17}: {}", "Signature", hex_string(&signature2));
}

fn verify_signature(
Expand Down Expand Up @@ -127,12 +128,12 @@ fn verify_signature(
println!(
"{:>17}: {}",
"Validation Hash",
hex::encode(validation_hash.to_byte_array())
hex_string(validation_hash.as_byte_array())
);
println!(
"{:>17}: {}",
"Single Hash",
hex::encode(single_hash.to_byte_array())
hex_string(single_hash.as_byte_array())
);
println!();

Expand Down
14 changes: 7 additions & 7 deletions test-vectors/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -12,18 +12,18 @@ edition = "2021"

[features]
default = ["std"]
std = ["hex/std", "serde/std"]
bip32 = ["bs58", "hex/serde"]
std = ["faster-hex/std", "serde/std"]
bip32 = ["bs58", "faster-hex/serde"]
firmware = []
nostr = ["hex/serde"]
psbt = ["hex/serde"]
seedqr = ["bip39/serde", "hex/serde"]
blockchain-commons = ["bitcoin/serde", "hex/serde"]
nostr = ["faster-hex/serde"]
psbt = ["faster-hex/serde"]
seedqr = ["bip39/serde", "faster-hex/serde"]
blockchain-commons = ["bitcoin/serde", "faster-hex/serde"]

[dependencies]
bip39 = { workspace = true, optional = true }
bitcoin = { workspace = true, optional = true, features = ["std"] }
bs58 = { workspace = true, optional = true }
hex = { workspace = true, optional = true }
faster-hex = { workspace = true, optional = true }
serde = { workspace = true }
serde_json = { workspace = true }
2 changes: 1 addition & 1 deletion test-vectors/src/bip32.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ impl TestVectors {
#[serde(rename_all = "kebab-case")]
pub struct TestVector {
pub name: String,
#[serde(rename = "seed-hex", with = "hex")]
#[serde(rename = "seed-hex", with = "faster_hex::nopfx_ignorecase")]
pub seed: Vec<u8>,
pub chains: Vec<Chain>,
}
Expand Down
68 changes: 9 additions & 59 deletions test-vectors/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@
pub struct NIP19Vector {
pub name: String,
pub kind: String,
#[serde(with = "hex")]
pub bytes: [u8; 32],
#[serde(with = "faster_hex::nopfx_ignorecase")]
pub bytes: Vec<u8>,
pub encoded: String,
}

Expand All @@ -26,7 +26,7 @@ pub struct SeedQRVector {
pub seed: bip39::Mnemonic,
pub as_digits: String,
pub as_compact_bits: String,
#[serde(with = "hex")]
#[serde(with = "faster_hex::nopfx_ignorecase")]
pub as_compact_bytes: Vec<u8>,
}

Expand All @@ -51,15 +51,15 @@ mod blockchain_commons {

#[derive(Debug, Clone, Deserialize)]
pub enum UR {
#[serde(rename = "bytes", with = "hex")]
#[serde(rename = "bytes", with = "faster_hex::nopfx_ignorecase")]
Bytes(Vec<u8>),
#[serde(rename = "address")]
Address(AddressVector),
#[serde(rename = "eckey")]
ECKey(ECKeyVector),
#[serde(rename = "hdkey")]
HDKey(HDKeyVector),
#[serde(rename = "psbt", with = "hex")]
#[serde(rename = "psbt", with = "faster_hex::nopfx_ignorecase")]
Psbt(Vec<u8>),
#[serde(rename = "seed")]
Seed(SeedVector),
Expand Down Expand Up @@ -92,15 +92,15 @@ mod blockchain_commons {
#[serde(rename_all = "kebab-case")]
pub enum AddressVector {
Bitcoin(bitcoin::Address<bitcoin::address::NetworkUnchecked>),
#[serde(with = "prefix_hex")]
#[serde(with = "faster_hex::withpfx_ignorecase")]
Ethereum(Vec<u8>),
}

#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub struct ECKeyVector {
pub is_private: bool,
#[serde(with = "hex")]
#[serde(with = "faster_hex::nopfx_ignorecase")]
pub data: Vec<u8>,
}

Expand All @@ -119,7 +119,7 @@ mod blockchain_commons {
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub struct SeedVector {
#[serde(with = "hex")]
#[serde(with = "faster_hex::nopfx_ignorecase")]
pub payload: Vec<u8>,
pub creation_date: u64,
}
Expand All @@ -128,7 +128,7 @@ mod blockchain_commons {
#[serde(rename_all = "kebab-case")]
pub struct URVector {
pub name: String,
#[serde(with = "hex")]
#[serde(with = "faster_hex::nopfx_ignorecase")]
pub as_cbor: Vec<u8>,
pub as_ur: String,
pub ur: UR,
Expand All @@ -152,56 +152,6 @@ mod blockchain_commons {
vectors
}
}

mod prefix_hex {
use std::{fmt::Display, fmt::Formatter, marker::PhantomData};

use hex::FromHex;
use serde::{
de::{Error, Visitor},
Deserializer,
};

pub fn deserialize<'de, D, T>(deserializer: D) -> Result<T, D::Error>
where
D: Deserializer<'de>,
T: FromHex,
<T as FromHex>::Error: Display,
{
struct HexStrVisitor<T>(PhantomData<T>);
impl<'de, T> Visitor<'de> for HexStrVisitor<T>
where
T: FromHex,
<T as FromHex>::Error: Display,
{
type Value = T;

fn expecting(&self, f: &mut Formatter) -> std::fmt::Result {
f.write_str("hex encoded string with 0x prefix")
}

fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
where
E: Error,
{
let v = v
.strip_prefix("0x")
.ok_or_else(|| Error::custom("invalid prefix"))?;

FromHex::from_hex(v).map_err(Error::custom)
}

fn visit_string<E>(self, v: String) -> Result<Self::Value, E>
where
E: Error,
{
self.visit_str(&v)
}
}

deserializer.deserialize_str(HexStrVisitor(PhantomData))
}
}
}

#[cfg(feature = "blockchain-commons")]
Expand Down
2 changes: 1 addition & 1 deletion test-vectors/src/psbt.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ impl TestVectors {
#[derive(Debug, serde::Deserialize)]
pub struct TestVector {
pub description: String,
#[serde(with = "hex", rename = "as-hex")]
#[serde(with = "faster_hex::nopfx_ignorecase", rename = "as-hex")]
pub data: Vec<u8>,
}

Expand Down
2 changes: 1 addition & 1 deletion ur/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -33,4 +33,4 @@ phf = { workspace = true }
rand_xoshiro = { workspace = true }

[dev-dependencies]
hex = { workspace = true, features = ["alloc"] }
faster-hex = { workspace = true, features = ["alloc"] }
13 changes: 10 additions & 3 deletions ur/src/fountain/encoder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -235,7 +235,7 @@ pub mod tests {
);
for &expected_fragment in EXPECTED_FRAGMENTS.iter() {
let part = encoder.next_part();
assert_eq!(hex::encode(part.data), expected_fragment);
assert_eq!(faster_hex::hex_string(part.data), expected_fragment);
}
}

Expand Down Expand Up @@ -270,7 +270,11 @@ pub mod tests {

for (i, data) in EXPECTED_DATA
.iter()
.map(|v| hex::decode(v).unwrap())
.map(|v| {
let mut tmp = vec![0; v.len() / 2];
faster_hex::hex_decode(v.as_bytes(), &mut tmp).unwrap();
tmp
})
.enumerate()
{
let sequence = u32::try_from(i).unwrap();
Expand Down Expand Up @@ -334,7 +338,10 @@ pub mod tests {
u32::try_from(SEQUENCE_COUNT).unwrap()
);

for expected_cbor in EXPECTED_PARTS_CBOR.iter().map(|v| hex::decode(v).unwrap()) {
for expected_cbor_hex in EXPECTED_PARTS_CBOR.iter() {
let mut expected_cbor = vec![0; expected_cbor_hex.len() / 2];
faster_hex::hex_decode(expected_cbor_hex.as_bytes(), &mut expected_cbor).unwrap();

let mut cbor = alloc::vec::Vec::new();
minicbor::encode(encoder.next_part(), &mut cbor).unwrap();

Expand Down
2 changes: 1 addition & 1 deletion urtypes/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ alloc = ["minicbor/alloc"]
bitcoin = { workspace = true, optional = true }
foundation-arena = { workspace = true }
heapless = { workspace = true }
hex = { workspace = true }
faster-hex = { workspace = true }
minicbor = { workspace = true }
uuid = { workspace = true }

Expand Down
23 changes: 16 additions & 7 deletions urtypes/src/registry/passport.rs
Original file line number Diff line number Diff line change
Expand Up @@ -268,19 +268,24 @@ impl<'a, C> Encode<C> for PassportResponse<'a> {

#[cfg(test)]
mod tests {
use faster_hex::hex_decode;

use super::*;

#[test]
fn test_roundtrip_passport_request() {
let mut id = [0; 32];
let mut signature = [0; 64];

hex::decode_to_slice(
"2e99758548972a8e8822ad47fa1017ff72f06f3ff6a016851f45c398732bc50c",
hex_decode(
"2e99758548972a8e8822ad47fa1017ff72f06f3ff6a016851f45c398732bc50c".as_bytes(),
&mut id,
)
.unwrap();
hex::decode_to_slice("7d0a8468ed220400c0b8e6f335baa7e070ce880a37e2ac5995b9a97b809026de626da636ac7365249bb974c719edf543b52ed286646f437dc7f810cc2068375c", &mut signature).unwrap();
hex_decode(
"7d0a8468ed220400c0b8e6f335baa7e070ce880a37e2ac5995b9a97b809026de626da636ac7365249bb974c719edf543b52ed286646f437dc7f810cc2068375c".as_bytes(),
&mut signature,
).unwrap();

let request = PassportRequest {
transaction_id: Default::default(),
Expand All @@ -300,12 +305,15 @@ mod tests {
let mut id = [0; 32];
let mut signature = [0; 64];

hex::decode_to_slice(
"2e99758548972a8e8822ad47fa1017ff72f06f3ff6a016851f45c398732bc50c",
hex_decode(
"2e99758548972a8e8822ad47fa1017ff72f06f3ff6a016851f45c398732bc50c".as_bytes(),
&mut id,
)
.unwrap();
hex::decode_to_slice("7d0a8468ed220400c0b8e6f335baa7e070ce880a37e2ac5995b9a97b809026de626da636ac7365249bb974c719edf543b52ed286646f437dc7f810cc2068375c", &mut signature).unwrap();
hex_decode(
"7d0a8468ed220400c0b8e6f335baa7e070ce880a37e2ac5995b9a97b809026de626da636ac7365249bb974c719edf543b52ed286646f437dc7f810cc2068375c".as_bytes(),
&mut signature,
).unwrap();

let response = PassportResponse {
transaction_id: Default::default(),
Expand All @@ -328,7 +336,8 @@ mod tests {
#[test]
fn test_request_decode() {
const TEST_VECTOR: &str = "a201d8255083816f6064ff4046b93a85687f8f608202d902c6a30178403338633663303561633639613166623737626366333736333330383835326364336530383066653165343630346361613831623534383236653264613062643202788037393035306564663562386636343937663936626661633031333363396365663561303764613363343835613432373466646666396433616637346632393833636566386432303337663164626636613435356431356530666236346162313665333664643336353062363533323265333239303138313639633631356636610378603045022079050ec39f5bc28f64c297c3b96bc3bac380133cc29cc3af5a07c39a3c485a4274c3bdc3bfc29d3ac3b74f29c283022100c38ec3b8c392037f1dc2bf6a455d15c3a0c3bb64c2ab16c3a36dc393650b65322e32c2901816c29c615f6a";
let cbor = hex::decode(TEST_VECTOR).unwrap();
let mut cbor = vec![0; TEST_VECTOR.len() / 2];
hex_decode(TEST_VECTOR.as_bytes(), &mut cbor).unwrap();
minicbor::decode::<'_, PassportRequest>(&cbor).unwrap();
}
}
Loading

0 comments on commit 1b777cf

Please sign in to comment.