Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(rust/catalyst-types): Convert UUID types to cbor #148

Merged
merged 12 commits into from
Jan 17, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 1 addition & 2 deletions rust/catalyst-types/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@ name = "catalyst_types"

[dependencies]
blake2b_simd = "1.0.2"
coset = "0.3.8"
displaydoc = "0.2.5"
ed25519-dalek = "2.1.1"
fluent-uri = "0.3.2"
Expand All @@ -33,4 +32,4 @@ uuid = { version = "1.11.0", features = ["v4", "v7", "serde"] }

[dev-dependencies]
ed25519-dalek = { version = "2.1.1", features = ["rand_core"] }
rand = "0.8.5"
rand = "0.8.5"
163 changes: 132 additions & 31 deletions rust/catalyst-types/src/uuid/mod.rs
Original file line number Diff line number Diff line change
@@ -1,47 +1,148 @@
//! `UUID` types.

use displaydoc::Display;
use thiserror::Error;
use uuid::Uuid;

mod uuid_v4;
mod uuid_v7;

use minicbor::data::Tag;
pub use uuid_v4::UuidV4 as V4;
pub use uuid_v7::UuidV7 as V7;

/// Invalid Doc Type UUID
pub const INVALID_UUID: uuid::Uuid = uuid::Uuid::from_bytes([0x00; 16]);

/// CBOR tag for UUID content.
pub const UUID_CBOR_TAG: u64 = 37;

/// Errors that can occur when decoding CBOR-encoded UUIDs.
#[derive(Display, Debug, Error)]
pub enum CborUuidError {
/// Invalid CBOR encoded UUID type
InvalidCborType,
/// Invalid CBOR encoded UUID type: invalid bytes size
InvalidByteSize,
/// UUID {uuid} is not `v{expected_version}`
InvalidVersion {
/// The decoded UUID that was checked.
uuid: Uuid,
/// The expected version of the UUID, which did not match the decoded one.
expected_version: usize,
},
/// UUID CBOR tag <https://www.iana.org/assignments/cbor-tags/cbor-tags.xhtml/>.
#[allow(dead_code)]
const UUID_CBOR_TAG: u64 = 37;

/// Context for `CBOR` encoding and decoding
pub enum CborContext {
/// Untagged bytes
Untagged,
/// IANA CBOR tag and bytes
Tagged,
/// Optional tag
Optional,
}

/// Decode `CBOR` encoded `UUID`.
pub(crate) fn decode_cbor_uuid(val: &coset::cbor::Value) -> Result<uuid::Uuid, CborUuidError> {
let Some((UUID_CBOR_TAG, coset::cbor::Value::Bytes(bytes))) = val.as_tag() else {
return Err(CborUuidError::InvalidCborType);
/// Validate UUID CBOR Tag.
fn validate_uuid_tag(tag: u64) -> Result<(), minicbor::decode::Error> {
if UUID_CBOR_TAG != tag {
return Err(minicbor::decode::Error::message(format!(
"tag value must be: {UUID_CBOR_TAG}, provided: {tag}"
)));
}
Ok(())
}

/// Decode from `CBOR` into `UUID`
fn decode_cbor_uuid(
d: &mut minicbor::Decoder<'_>, ctx: &mut CborContext,
) -> Result<uuid::Uuid, minicbor::decode::Error> {
let bytes = match ctx {
CborContext::Untagged => d.bytes()?,
CborContext::Tagged => {
let tag = d.tag()?;
validate_uuid_tag(tag.as_u64())?;
d.bytes()?
},
CborContext::Optional => {
let pos = d.position();
if let Ok(tag) = d.tag() {
validate_uuid_tag(tag.as_u64())?;
d.bytes()?
} else {
d.set_position(pos);
d.bytes()?
}
},
};
let uuid = uuid::Uuid::from_bytes(
bytes
.clone()
.try_into()
.map_err(|_| CborUuidError::InvalidByteSize)?,
);
let decoded: [u8; 16] = bytes.try_into().map_err(|_| {
minicbor::decode::Error::message("Invalid CBOR encoded UUID type: invalid bytes size")
})?;
let uuid = uuid::Uuid::from_bytes(decoded);
Ok(uuid)
}

/// Encode `UUID` into `CBOR`
fn encode_cbor_uuid<W: minicbor::encode::Write>(
uuid: uuid::Uuid, e: &mut minicbor::Encoder<W>, ctx: &mut CborContext,
) -> Result<(), minicbor::encode::Error<W::Error>> {
if let CborContext::Tagged = ctx {
e.tag(Tag::new(UUID_CBOR_TAG))?;
}
e.bytes(uuid.as_bytes())?;
Ok(())
}

#[cfg(test)]
mod tests {

use super::{V4, V7};
use crate::uuid::CborContext;

#[test]
fn test_cbor_uuid_v4_roundtrip() {
let uuid: V4 = uuid::Uuid::new_v4().into();
let mut bytes = Vec::new();
minicbor::encode_with(uuid, &mut bytes, &mut CborContext::Untagged).unwrap();
let decoded = minicbor::decode_with(bytes.as_slice(), &mut CborContext::Untagged).unwrap();
assert_eq!(uuid, decoded);
}

#[test]
fn test_cbor_uuid_v7_roundtrip() {
let uuid: V7 = uuid::Uuid::now_v7().into();
let mut bytes = Vec::new();
minicbor::encode_with(uuid, &mut bytes, &mut CborContext::Untagged).unwrap();
let decoded = minicbor::decode_with(bytes.as_slice(), &mut CborContext::Untagged).unwrap();
assert_eq!(uuid, decoded);
}

#[test]
fn test_tagged_cbor_uuid_v4_roundtrip() {
let uuid: V4 = uuid::Uuid::new_v4().into();
let mut bytes = Vec::new();
minicbor::encode_with(uuid, &mut bytes, &mut CborContext::Tagged).unwrap();
let decoded = minicbor::decode_with(bytes.as_slice(), &mut CborContext::Tagged).unwrap();
assert_eq!(uuid, decoded);
}

#[test]
fn test_tagged_cbor_uuid_v7_roundtrip() {
let uuid: V7 = uuid::Uuid::now_v7().into();
let mut bytes = Vec::new();
minicbor::encode_with(uuid, &mut bytes, &mut CborContext::Tagged).unwrap();
let decoded = minicbor::decode_with(bytes.as_slice(), &mut CborContext::Tagged).unwrap();
assert_eq!(uuid, decoded);
}

#[test]
fn test_optional_cbor_uuid_v4_roundtrip() {
let uuid: V4 = uuid::Uuid::new_v4().into();

let mut bytes = Vec::new();
minicbor::encode_with(uuid, &mut bytes, &mut CborContext::Untagged).unwrap();
let decoded = minicbor::decode_with(bytes.as_slice(), &mut CborContext::Optional).unwrap();
assert_eq!(uuid, decoded);

let mut bytes = Vec::new();
minicbor::encode_with(uuid, &mut bytes, &mut CborContext::Tagged).unwrap();
let decoded = minicbor::decode_with(bytes.as_slice(), &mut CborContext::Optional).unwrap();
assert_eq!(uuid, decoded);
}

#[test]
fn test_optional_cbor_uuid_v7_roundtrip() {
let uuid: V7 = uuid::Uuid::now_v7().into();

let mut bytes = Vec::new();
stevenj marked this conversation as resolved.
Show resolved Hide resolved
minicbor::encode_with(uuid, &mut bytes, &mut CborContext::Untagged).unwrap();
let decoded = minicbor::decode_with(bytes.as_slice(), &mut CborContext::Optional).unwrap();
assert_eq!(uuid, decoded);

let mut bytes = Vec::new();
minicbor::encode_with(uuid, &mut bytes, &mut CborContext::Tagged).unwrap();
let decoded = minicbor::decode_with(bytes.as_slice(), &mut CborContext::Optional).unwrap();
assert_eq!(uuid, decoded);
}
}
68 changes: 15 additions & 53 deletions rust/catalyst-types/src/uuid/uuid_v4.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
//! `UUIDv4` Type.
use std::fmt::{Display, Formatter};

use super::{decode_cbor_uuid, INVALID_UUID};
use minicbor::{Decode, Decoder, Encode};

use super::{decode_cbor_uuid, encode_cbor_uuid, CborContext, INVALID_UUID};

/// Type representing a `UUIDv4`.
#[derive(Copy, Clone, Debug, PartialEq, PartialOrd, serde::Serialize, serde::Deserialize)]
Expand Down Expand Up @@ -41,23 +43,18 @@ impl Display for UuidV4 {
}
}

impl TryFrom<&coset::cbor::Value> for UuidV4 {
type Error = super::CborUuidError;

fn try_from(cbor_value: &coset::cbor::Value) -> Result<Self, Self::Error> {
match decode_cbor_uuid(cbor_value) {
Ok(uuid) => {
if uuid.get_version_num() == Self::UUID_VERSION_NUMBER {
Ok(Self { uuid })
} else {
Err(super::CborUuidError::InvalidVersion {
uuid,
expected_version: Self::UUID_VERSION_NUMBER,
})
}
},
Err(e) => Err(e),
}
impl Decode<'_, CborContext> for UuidV4 {
fn decode(d: &mut Decoder<'_>, ctx: &mut CborContext) -> Result<Self, minicbor::decode::Error> {
let uuid = decode_cbor_uuid(d, ctx)?;
stevenj marked this conversation as resolved.
Show resolved Hide resolved
Ok(Self { uuid })
}
}

impl Encode<CborContext> for UuidV4 {
fn encode<W: minicbor::encode::Write>(
&self, e: &mut minicbor::Encoder<W>, ctx: &mut CborContext,
) -> Result<(), minicbor::encode::Error<W::Error>> {
encode_cbor_uuid(self.uuid(), e, ctx)
stevenj marked this conversation as resolved.
Show resolved Hide resolved
}
}

Expand All @@ -81,11 +78,9 @@ impl From<UuidV4> for uuid::Uuid {

#[cfg(test)]
mod tests {
use coset::cbor::Value;
use uuid::Uuid;

use super::*;
use crate::uuid::UUID_CBOR_TAG;

#[test]
fn test_invalid_uuid() {
Expand All @@ -112,37 +107,4 @@ mod tests {
"Zero UUID should not be valid"
);
}

#[test]
fn test_try_from_cbor_valid_uuid() {
let uuid = Uuid::new_v4();
let cbor_value = Value::Tag(
UUID_CBOR_TAG,
Box::new(Value::Bytes(uuid.as_bytes().to_vec())),
);
let result = UuidV4::try_from(&cbor_value);

assert!(
result.is_ok(),
"Should successfully parse valid UUID from CBOR"
);
let uuid_v4 = result.unwrap();
assert!(uuid_v4.is_valid(), "Parsed UUIDv4 should be valid");
assert_eq!(
uuid_v4.uuid(),
uuid,
"Parsed UUID should match original UUID"
);
}

#[test]
fn test_try_from_cbor_invalid_uuid() {
let cbor_value = Value::Bytes(vec![0; 16]);
let result = UuidV4::try_from(&cbor_value);

assert!(
result.is_err(),
"Should fail to parse invalid UUID from CBOR"
);
}
}
68 changes: 15 additions & 53 deletions rust/catalyst-types/src/uuid/uuid_v7.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
//! `UUIDv7` Type.
use std::fmt::{Display, Formatter};

use super::{decode_cbor_uuid, INVALID_UUID};
use minicbor::{Decode, Decoder, Encode};

use super::{decode_cbor_uuid, encode_cbor_uuid, CborContext, INVALID_UUID};

/// Type representing a `UUIDv7`.
#[derive(Copy, Clone, Debug, PartialEq, PartialOrd, serde::Serialize, serde::Deserialize)]
Expand Down Expand Up @@ -41,23 +43,18 @@ impl Display for UuidV7 {
}
}

impl TryFrom<&coset::cbor::Value> for UuidV7 {
type Error = super::CborUuidError;

fn try_from(cbor_value: &coset::cbor::Value) -> Result<Self, Self::Error> {
match decode_cbor_uuid(cbor_value) {
Ok(uuid) => {
if uuid.get_version_num() == Self::UUID_VERSION_NUMBER {
Ok(Self { uuid })
} else {
Err(super::CborUuidError::InvalidVersion {
uuid,
expected_version: Self::UUID_VERSION_NUMBER,
})
}
},
Err(e) => Err(e),
}
impl Decode<'_, CborContext> for UuidV7 {
fn decode(d: &mut Decoder<'_>, ctx: &mut CborContext) -> Result<Self, minicbor::decode::Error> {
let uuid = decode_cbor_uuid(d, ctx)?;
stevenj marked this conversation as resolved.
Show resolved Hide resolved
Ok(Self { uuid })
}
}

impl Encode<CborContext> for UuidV7 {
fn encode<W: minicbor::encode::Write>(
stevenj marked this conversation as resolved.
Show resolved Hide resolved
&self, e: &mut minicbor::Encoder<W>, ctx: &mut CborContext,
) -> Result<(), minicbor::encode::Error<W::Error>> {
encode_cbor_uuid(self.uuid(), e, ctx)
}
}

Expand All @@ -81,11 +78,9 @@ impl From<UuidV7> for uuid::Uuid {

#[cfg(test)]
mod tests {
use coset::cbor::Value;
use uuid::Uuid;

use super::*;
use crate::uuid::UUID_CBOR_TAG;

#[test]
fn test_invalid_uuid() {
Expand Down Expand Up @@ -113,37 +108,4 @@ mod tests {
"Zero UUID should not be valid"
);
}

#[test]
fn test_try_from_cbor_valid_uuid() {
let uuid = Uuid::try_parse("017f22e3-79b0-7cc7-98cf-e0bbf8a1c5f1").unwrap();
let cbor_value = Value::Tag(
UUID_CBOR_TAG,
Box::new(Value::Bytes(uuid.as_bytes().to_vec())),
);
let result = UuidV7::try_from(&cbor_value);

assert!(
result.is_ok(),
"Should successfully parse valid UUID from CBOR"
);
let uuid_v7 = result.unwrap();
assert!(uuid_v7.is_valid(), "Parsed UUIDv7 should be valid");
assert_eq!(
uuid_v7.uuid(),
uuid,
"Parsed UUID should match original UUID"
);
}

#[test]
fn test_try_from_cbor_invalid_uuid() {
let cbor_value = Value::Bytes(vec![0; 16]);
let result = UuidV7::try_from(&cbor_value);

assert!(
result.is_err(),
"Should fail to parse invalid UUID from CBOR"
);
}
}
Loading