From 507cadba201701e15514e2dedd9003ef7df50c32 Mon Sep 17 00:00:00 2001 From: vnprc Date: Thu, 14 Nov 2024 17:18:57 -0500 Subject: [PATCH] fix: convert Id::TryFrom to Id::From --- crates/cdk/src/nuts/nut02.rs | 21 ++++++++++++++------- crates/cdk/src/nuts/nut13.rs | 2 +- 2 files changed, 15 insertions(+), 8 deletions(-) diff --git a/crates/cdk/src/nuts/nut02.rs b/crates/cdk/src/nuts/nut02.rs index 934be23ff..9f36a4a2d 100644 --- a/crates/cdk/src/nuts/nut02.rs +++ b/crates/cdk/src/nuts/nut02.rs @@ -112,17 +112,24 @@ impl Id { id: bytes[1..].try_into()?, }) } + + /// [`Id`] as bytes + pub fn as_bytes(&self) -> [u8; Self::BYTELEN + 1] { + let mut bytes = [0u8; Self::BYTELEN + 1]; + bytes[0] = self.version.to_byte(); + bytes[1..].copy_from_slice(&self.id); + bytes + } } -impl TryFrom for u32 { - type Error = Error; - fn try_from(value: Id) -> Result { - let hex_bytes: [u8; 8] = value.to_bytes().try_into().map_err(|_| Error::Length)?; +// Used to generate a compressed unique identifier as part of the NUT13 spec +impl From for u32 { + fn from(value: Id) -> Self { + let hex_bytes: [u8; 8] = value.as_bytes(); let int = u64::from_be_bytes(hex_bytes); - let result = (int % (2_u64.pow(31) - 1)) as u32; - Ok(result) + (int % (2_u64.pow(31) - 1)) as u32 } } @@ -491,7 +498,7 @@ mod test { fn test_to_int() { let id = Id::from_str("009a1f293253e41e").unwrap(); - let id_int = u32::try_from(id).unwrap(); + let id_int = u32::from(id); assert_eq!(864559728, id_int) } diff --git a/crates/cdk/src/nuts/nut13.rs b/crates/cdk/src/nuts/nut13.rs index df7706b79..849131974 100644 --- a/crates/cdk/src/nuts/nut13.rs +++ b/crates/cdk/src/nuts/nut13.rs @@ -170,7 +170,7 @@ impl PreMintSecrets { } fn derive_path_from_keyset_id(id: Id) -> Result { - let index = u32::try_from(id)?; + let index = u32::from(id); let keyset_child_number = ChildNumber::from_hardened_idx(index)?; Ok(DerivationPath::from(vec![