Skip to content

feat(rust/signed-doc): add new type DocType #339

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

Merged
merged 6 commits into from
May 22, 2025
Merged
Show file tree
Hide file tree
Changes from 2 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
2 changes: 1 addition & 1 deletion rust/signed_doc/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ jsonschema = "0.28.3"
jsonpath-rust = "0.7.5"
futures = "0.3.31"
ed25519-bip32 = "0.4.1" # used by the `mk_signed_doc` cli tool

tracing = "0.1.40"

[dev-dependencies]
base64-url = "3.0.0"
Expand Down
22 changes: 22 additions & 0 deletions rust/signed_doc/src/decode_context.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
//! Context used to pass in decoder for additional information.

use catalyst_types::problem_report::ProblemReport;

/// Conversion policy
#[allow(dead_code)]
pub(crate) enum ConversionPolicy {
/// Allow conversion.
Accept,
/// Allow conversion but log warning.
Warn,
/// Fail when there is conversion.
Fail,
}

/// A context use to pass to decoder.
pub(crate) struct DecodeContext<'r> {
/// Conversion policy.
pub conversion_policy: ConversionPolicy,
/// Problem report.
pub report: &'r mut ProblemReport,
}
1 change: 1 addition & 0 deletions rust/signed_doc/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

mod builder;
mod content;
mod decode_context;
pub mod doc_types;
mod metadata;
pub mod providers;
Expand Down
225 changes: 225 additions & 0 deletions rust/signed_doc/src/metadata/doc_type.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,225 @@
//! Document Type.

use std::fmt::{Display, Formatter};

use catalyst_types::{
problem_report::ProblemReport,
uuid::{CborContext, Uuid, UuidV4},
};
use minicbor::{Decode, Decoder, Encode};
use tracing::warn;

use crate::decode_context::{ConversionPolicy, DecodeContext};

/// List of `UUIDv4` document type.
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct DocType(Vec<UuidV4>);

impl DocType {
/// Get a list of `UUIDv4` document types.
#[allow(dead_code)]
pub fn doc_types(&self) -> &Vec<UuidV4> {
&self.0
}
}

impl From<UuidV4> for DocType {
fn from(value: UuidV4) -> Self {
DocType(vec![value])
}
}

impl TryFrom<Uuid> for DocType {
type Error = anyhow::Error;

fn try_from(value: Uuid) -> Result<Self, Self::Error> {
let uuid_v4 = UuidV4::try_from(value)?;
Ok(DocType(vec![uuid_v4]))
}
}

impl From<Vec<UuidV4>> for DocType {
fn from(value: Vec<UuidV4>) -> Self {
DocType(value)
}
}

impl Display for DocType {
fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), std::fmt::Error> {
write!(
f,
"[{}]",
self.0
.iter()
.map(UuidV4::to_string)
.collect::<Vec<_>>()
.join(", ")
)
}
}

// ; Document Type
// document_type = [ 1* uuid_v4 ]
// ; UUIDv4
// uuid_v4 = #6.37(bytes .size 16)
impl Decode<'_, DecodeContext<'_>> for DocType {
fn decode(
d: &mut Decoder, decode_context: &mut DecodeContext,
) -> Result<Self, minicbor::decode::Error> {
const CONTEXT: &str = "DocType decoding";
let parse_uuid = |d: &mut Decoder| UuidV4::decode(d, &mut CborContext::Tagged);

match d.datatype()? {
minicbor::data::Type::Array => {
let len = d.array()?.ok_or_else(|| {
decode_context
.report
.other("Unable to decode array length", CONTEXT);
minicbor::decode::Error::message(format!(
"{CONTEXT}: Unable to decode array length"
))
})?;

if len == 0 {
decode_context.report.invalid_value(
"array length",
"0",
"must contain at least one UUIDv4",
CONTEXT,
);
return Err(minicbor::decode::Error::message(format!(
"{CONTEXT}: empty array"
)));
}

(0..len)
.map(|_| parse_uuid(d))
.collect::<Result<Vec<_>, _>>()
.map(Self)
.map_err(|e| {
decode_context
.report
.other(&format!("Invalid UUIDv4 in array: {e}"), CONTEXT);
minicbor::decode::Error::message(format!(
"{CONTEXT}: Invalid UUIDv4 in array: {e}"
))
})
},
minicbor::data::Type::Tag => {
// Handle single tagged UUID
match decode_context.conversion_policy {
ConversionPolicy::Accept | ConversionPolicy::Warn => {
if matches!(decode_context.conversion_policy, ConversionPolicy::Warn) {
warn!("{CONTEXT}: Conversion of document type single UUID to type DocType");
}

parse_uuid(d).map(|uuid| Self(vec![uuid])).map_err(|e| {
let msg = format!("Invalid single UUIDv4: {e}");
decode_context.report.other(&msg, CONTEXT);
minicbor::decode::Error::message(format!("{CONTEXT}: {msg}"))
})
},

ConversionPolicy::Fail => {
let msg = "Conversion of document type single UUID to type DocType is not allowed";
decode_context.report.other(msg, CONTEXT);
Err(minicbor::decode::Error::message(format!(
"{CONTEXT}: {msg}"
)))
},
}
},
other => {
decode_context.report.invalid_value(
"decoding type",
&format!("{other:?}"),
"array or tag cbor",
CONTEXT,
);
Err(minicbor::decode::Error::message(format!(
"{CONTEXT}: expected array of UUIDor tagged UUIDv4, got {other:?}",
)))
},
}
}
}

impl Encode<ProblemReport> for DocType {
fn encode<W: minicbor::encode::Write>(
&self, e: &mut minicbor::Encoder<W>, report: &mut ProblemReport,
) -> Result<(), minicbor::encode::Error<W::Error>> {
const CONTEXT: &str = "DocType encoding";
e.array(self.0.len().try_into().map_err(|_| {
report.other("Unable to encode array length", CONTEXT);
minicbor::encode::Error::message(format!("{CONTEXT}, unable to encode array length"))
})?)?;
for id in &self.0 {
UuidV4::encode(id, e, &mut CborContext::Tagged).map_err(|_| {
report.other("Failed to encode UUIDv4", CONTEXT);
minicbor::encode::Error::message(format!("{CONTEXT}: UUIDv4 encoding failed"))
})?;
}
Ok(())
}
}

#[cfg(test)]
mod tests {

use minicbor::Encoder;

use super::*;

#[test]
fn test_doc_type() {
let uuidv4 = UuidV4::new();
assert_eq!(DocType::from(uuidv4).0.len(), 1);

let mut report = ProblemReport::new("test doc type");
// ----- Multiple doc types -----
let doc_type_list: DocType = vec![uuidv4, uuidv4].into();
let mut buffer = Vec::new();
let mut encoder = Encoder::new(&mut buffer);
doc_type_list
.encode(&mut encoder, &mut report)
.expect("Failed to encode Doc Type");
let mut decoder = Decoder::new(&buffer);
let mut decoded_context = DecodeContext {
conversion_policy: ConversionPolicy::Accept,
report: &mut report.clone(),
};
let decoded_doc_type = DocType::decode(&mut decoder, &mut decoded_context).unwrap();
assert_eq!(decoded_doc_type, doc_type_list);

// ----- Singer doc type -----
// <https://input-output-hk.github.io/catalyst-libs/architecture/08_concepts/signed_doc/types/>
// 37(h'5e60e623ad024a1ba1ac406db978ee48')
let single_uuid = hex::decode("D825505E60E623AD024A1BA1AC406DB978EE48").unwrap();
let uuid = Uuid::parse_str("5e60e623-ad02-4a1b-a1ac-406db978ee48").unwrap();
let decoder = Decoder::new(&single_uuid);
// Failing Policy
let mut decoded_context = DecodeContext {
conversion_policy: ConversionPolicy::Fail,
report: &mut report.clone(),
};
assert!(DocType::decode(&mut decoder.clone(), &mut decoded_context).is_err());
// Warning Policy
let mut decoded_context = DecodeContext {
conversion_policy: ConversionPolicy::Warn,
report: &mut report.clone(),
};
let decoded_doc_type = DocType::decode(&mut decoder.clone(), &mut decoded_context).unwrap();
assert_eq!(decoded_doc_type, uuid.try_into().unwrap());
// Accept Policy
let mut decoded_context = DecodeContext {
conversion_policy: ConversionPolicy::Accept,
report: &mut report.clone(),
};
let decoded_doc_type = DocType::decode(&mut decoder.clone(), &mut decoded_context).unwrap();
assert_eq!(decoded_doc_type, uuid.try_into().unwrap());

// ----- Empty doc type -----
let mut decoder = Decoder::new(&[]);
assert!(DocType::decode(&mut decoder, &mut decoded_context).is_err());
}
}
1 change: 1 addition & 0 deletions rust/signed_doc/src/metadata/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ use std::fmt::{Display, Formatter};

mod content_encoding;
mod content_type;
mod doc_type;
mod document_ref;
mod extra_fields;
mod section;
Expand Down
Loading