-
Notifications
You must be signed in to change notification settings - Fork 0
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
Changes from 2 commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
6802e93
feat(signed-doc): add new type DocType
bkioshn 73bb037
fix(signed-doc): add conversion policy
bkioshn f255e95
fix(signed-doc): doc type
bkioshn 7e17446
fix(signed-doc): doc type error
bkioshn ed67e3e
fix(signed-doc): seperate test
bkioshn 0ee051d
fix(signed-doc): format
bkioshn File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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. | ||
bkioshn marked this conversation as resolved.
Show resolved
Hide resolved
|
||
Accept, | ||
/// Allow conversion but log warning. | ||
bkioshn marked this conversation as resolved.
Show resolved
Hide resolved
|
||
Warn, | ||
/// Fail when there is conversion. | ||
bkioshn marked this conversation as resolved.
Show resolved
Hide resolved
|
||
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, | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -2,6 +2,7 @@ | |
|
||
mod builder; | ||
mod content; | ||
mod decode_context; | ||
pub mod doc_types; | ||
mod metadata; | ||
pub mod providers; | ||
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)] | ||
bkioshn marked this conversation as resolved.
Show resolved
Hide resolved
|
||
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 { | ||
bkioshn marked this conversation as resolved.
Show resolved
Hide resolved
|
||
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| { | ||
bkioshn marked this conversation as resolved.
Show resolved
Hide resolved
|
||
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(|_| { | ||
bkioshn marked this conversation as resolved.
Show resolved
Hide resolved
|
||
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(|_| { | ||
bkioshn marked this conversation as resolved.
Show resolved
Hide resolved
|
||
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() { | ||
bkioshn marked this conversation as resolved.
Show resolved
Hide resolved
|
||
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()); | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.