diff --git a/rust/catalyst-types/src/uuid/mod.rs b/rust/catalyst-types/src/uuid/mod.rs
index 3e25737e1d..c2df1c4795 100644
--- a/rust/catalyst-types/src/uuid/mod.rs
+++ b/rust/catalyst-types/src/uuid/mod.rs
@@ -15,8 +15,7 @@ use minicbor::data::Tag;
pub const INVALID_UUID: uuid::Uuid = uuid::Uuid::from_bytes([0x00; 16]);
/// UUID CBOR tag .
-#[allow(dead_code)]
-const UUID_CBOR_TAG: u64 = 37;
+pub const UUID_CBOR_TAG: u64 = 37;
/// Uuid validation errors, which could occur during decoding or converting to
/// `UuidV4` or `UuidV7` types.
@@ -29,6 +28,9 @@ pub enum UuidError {
/// `UUIDv7` invalid error
#[error("'{0}' is not a valid UUIDv7")]
InvalidUuidV7(uuid::Uuid),
+ /// Invalid string conversion
+ #[error("Invalid string conversion: {0}")]
+ StringConversion(String),
}
/// Context for `CBOR` encoding and decoding
diff --git a/rust/catalyst-types/src/uuid/uuid_v4.rs b/rust/catalyst-types/src/uuid/uuid_v4.rs
index c7e2dbb814..a7baf46248 100644
--- a/rust/catalyst-types/src/uuid/uuid_v4.rs
+++ b/rust/catalyst-types/src/uuid/uuid_v4.rs
@@ -1,5 +1,8 @@
//! `UUIDv4` Type.
-use std::fmt::{Display, Formatter};
+use std::{
+ fmt::{Display, Formatter},
+ str::FromStr,
+};
use minicbor::{Decode, Decoder, Encode};
use uuid::Uuid;
@@ -7,7 +10,7 @@ use uuid::Uuid;
use super::{decode_cbor_uuid, encode_cbor_uuid, CborContext, UuidError, INVALID_UUID};
/// Type representing a `UUIDv4`.
-#[derive(Copy, Clone, Debug, PartialEq, PartialOrd, serde::Serialize)]
+#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, PartialOrd, serde::Serialize)]
pub struct UuidV4(Uuid);
impl UuidV4 {
@@ -106,6 +109,15 @@ impl<'de> serde::Deserialize<'de> for UuidV4 {
}
}
+impl FromStr for UuidV4 {
+ type Err = UuidError;
+
+ fn from_str(s: &str) -> Result {
+ let uuid = Uuid::parse_str(s).map_err(|_| UuidError::StringConversion(s.to_string()))?;
+ UuidV4::try_from(uuid).map_err(|_| UuidError::InvalidUuidV4(uuid))
+ }
+}
+
#[cfg(test)]
mod tests {
use super::*;
diff --git a/rust/catalyst-types/src/uuid/uuid_v7.rs b/rust/catalyst-types/src/uuid/uuid_v7.rs
index 98fbd8cda6..1bb95e6ff9 100644
--- a/rust/catalyst-types/src/uuid/uuid_v7.rs
+++ b/rust/catalyst-types/src/uuid/uuid_v7.rs
@@ -1,5 +1,8 @@
//! `UUIDv7` Type.
-use std::fmt::{Display, Formatter};
+use std::{
+ fmt::{Display, Formatter},
+ str::FromStr,
+};
use minicbor::{Decode, Decoder, Encode};
use uuid::Uuid;
@@ -106,6 +109,15 @@ impl<'de> serde::Deserialize<'de> for UuidV7 {
}
}
+impl FromStr for UuidV7 {
+ type Err = UuidError;
+
+ fn from_str(s: &str) -> Result {
+ let uuid = Uuid::parse_str(s).map_err(|_| UuidError::StringConversion(s.to_string()))?;
+ UuidV7::try_from(uuid).map_err(|_| UuidError::InvalidUuidV7(uuid))
+ }
+}
+
#[cfg(test)]
mod tests {
use uuid::Uuid;
diff --git a/rust/signed_doc/src/doc_types/mod.rs b/rust/signed_doc/src/doc_types/mod.rs
index 15bcb5948f..2a2c22735e 100644
--- a/rust/signed_doc/src/doc_types/mod.rs
+++ b/rust/signed_doc/src/doc_types/mod.rs
@@ -1,55 +1,108 @@
//! An implementation of different defined document types
//!
+use std::sync::LazyLock;
+
use catalyst_types::uuid::Uuid;
+use deprecated::{
+ COMMENT_DOCUMENT_UUID_TYPE, PROPOSAL_ACTION_DOCUMENT_UUID_TYPE, PROPOSAL_DOCUMENT_UUID_TYPE,
+};
+
+use crate::DocType;
+
+/// Proposal document type.
+#[allow(clippy::expect_used)]
+pub static PROPOSAL_DOC_TYPE: LazyLock = LazyLock::new(|| {
+ let ids = &[PROPOSAL_UUID_TYPE];
+ ids.to_vec()
+ .try_into()
+ .expect("Failed to convert proposal document Uuid to DocType")
+});
+
+/// Proposal comment document type.
+#[allow(clippy::expect_used)]
+pub static PROPOSAL_COMMENT_DOC: LazyLock = LazyLock::new(|| {
+ let ids = &[COMMENT_UUID_TYPE, PROPOSAL_UUID_TYPE];
+ ids.to_vec()
+ .try_into()
+ .expect("Failed to convert proposal comment document Uuid to DocType")
+});
+
+/// Proposal action document type.
+#[allow(clippy::expect_used)]
+pub static PROPOSAL_ACTION_DOC: LazyLock = LazyLock::new(|| {
+ let ids = &[
+ ACTION_UUID_TYPE,
+ PROPOSAL_UUID_TYPE,
+ SUBMISSION_ACTION_UUID_TYPE,
+ ];
+ ids.to_vec()
+ .try_into()
+ .expect("Failed to convert proposal action document Uuid to DocType")
+});
+
+/// Submission Action UUID type.
+pub const SUBMISSION_ACTION_UUID_TYPE: Uuid =
+ Uuid::from_u128(0x7892_7329_CFD9_4EA1_9C71_0E01_9B12_6A65);
+/// Proposal UUID type.
+pub const PROPOSAL_UUID_TYPE: Uuid = PROPOSAL_DOCUMENT_UUID_TYPE;
+/// Comment UUID type.
+pub const COMMENT_UUID_TYPE: Uuid = COMMENT_DOCUMENT_UUID_TYPE;
+/// Action UUID type.
+pub const ACTION_UUID_TYPE: Uuid = PROPOSAL_ACTION_DOCUMENT_UUID_TYPE;
+
+/// Document type which will be deprecated.
+pub mod deprecated {
+ use catalyst_types::uuid::Uuid;
-/// Proposal document `UuidV4` type.
-pub const PROPOSAL_DOCUMENT_UUID_TYPE: Uuid =
- Uuid::from_u128(0x7808_D2BA_D511_40AF_84E8_C0D1_625F_DFDC);
-/// Proposal template `UuidV4` type.
-pub const PROPOSAL_TEMPLATE_UUID_TYPE: Uuid =
- Uuid::from_u128(0x0CE8_AB38_9258_4FBC_A62E_7FAA_6E58_318F);
-/// Comment document `UuidV4` type.
-pub const COMMENT_DOCUMENT_UUID_TYPE: Uuid =
- Uuid::from_u128(0xB679_DED3_0E7C_41BA_89F8_DA62_A178_98EA);
-/// Comment template `UuidV4` type.
-pub const COMMENT_TEMPLATE_UUID_TYPE: Uuid =
- Uuid::from_u128(0x0B84_24D4_EBFD_46E3_9577_1775_A69D_290C);
-/// Review document `UuidV4` type.
-pub const REVIEW_DOCUMENT_UUID_TYPE: Uuid =
- Uuid::from_u128(0xE4CA_F5F0_098B_45FD_94F3_0702_A457_3DB5);
-/// Review template `UuidV4` type.
-pub const REVIEW_TEMPLATE_UUID_TYPE: Uuid =
- Uuid::from_u128(0xEBE5_D0BF_5D86_4577_AF4D_008F_DDBE_2EDC);
-/// Category document `UuidV4` type.
-pub const CATEGORY_DOCUMENT_UUID_TYPE: Uuid =
- Uuid::from_u128(0x48C2_0109_362A_4D32_9BBA_E0A9_CF8B_45BE);
-/// Category template `UuidV4` type.
-pub const CATEGORY_TEMPLATE_UUID_TYPE: Uuid =
- Uuid::from_u128(0x65B1_E8B0_51F1_46A5_9970_72CD_F268_84BE);
-/// Campaign parameters document `UuidV4` type.
-pub const CAMPAIGN_DOCUMENT_UUID_TYPE: Uuid =
- Uuid::from_u128(0x0110_EA96_A555_47CE_8408_36EF_E6ED_6F7C);
-/// Campaign parameters template `UuidV4` type.
-pub const CAMPAIGN_TEMPLATE_UUID_TYPE: Uuid =
- Uuid::from_u128(0x7E8F_5FA2_44CE_49C8_BFD5_02AF_42C1_79A3);
-/// Brand parameters document `UuidV4` type.
-pub const BRAND_DOCUMENT_UUID_TYPE: Uuid =
- Uuid::from_u128(0x3E48_08CC_C86E_467B_9702_D60B_AA9D_1FCA);
-/// Brand parameters template `UuidV4` type.
-pub const BRAND_TEMPLATE_UUID_TYPE: Uuid =
- Uuid::from_u128(0xFD3C_1735_80B1_4EEA_8D63_5F43_6D97_EA31);
-/// Proposal action document `UuidV4` type.
-pub const PROPOSAL_ACTION_DOCUMENT_UUID_TYPE: Uuid =
- Uuid::from_u128(0x5E60_E623_AD02_4A1B_A1AC_406D_B978_EE48);
-/// Public vote transaction v2 `UuidV4` type.
-pub const PUBLIC_VOTE_TX_V2_UUID_TYPE: Uuid =
- Uuid::from_u128(0x8DE5_586C_E998_4B95_8742_7BE3_C859_2803);
-/// Private vote transaction v2 `UuidV4` type.
-pub const PRIVATE_VOTE_TX_V2_UUID_TYPE: Uuid =
- Uuid::from_u128(0xE78E_E18D_F380_44C1_A852_80AA_6ECB_07FE);
-/// Immutable ledger block `UuidV4` type.
-pub const IMMUTABLE_LEDGER_BLOCK_UUID_TYPE: Uuid =
- Uuid::from_u128(0xD9E7_E6CE_2401_4D7D_9492_F4F7_C642_41C3);
-/// Submission Action `UuidV4` type.
-pub const SUBMISSION_ACTION: Uuid = Uuid::from_u128(0x7892_7329_CFD9_4EA1_9C71_0E01_9B12_6A65);
+ /// Proposal document `UuidV4` type.
+ pub const PROPOSAL_DOCUMENT_UUID_TYPE: Uuid =
+ Uuid::from_u128(0x7808_D2BA_D511_40AF_84E8_C0D1_625F_DFDC);
+ /// Proposal template `UuidV4` type.
+ pub const PROPOSAL_TEMPLATE_UUID_TYPE: Uuid =
+ Uuid::from_u128(0x0CE8_AB38_9258_4FBC_A62E_7FAA_6E58_318F);
+ /// Comment document `UuidV4` type.
+ pub const COMMENT_DOCUMENT_UUID_TYPE: Uuid =
+ Uuid::from_u128(0xB679_DED3_0E7C_41BA_89F8_DA62_A178_98EA);
+ /// Comment template `UuidV4` type.
+ pub const COMMENT_TEMPLATE_UUID_TYPE: Uuid =
+ Uuid::from_u128(0x0B84_24D4_EBFD_46E3_9577_1775_A69D_290C);
+ /// Review document `UuidV4` type.
+ pub const REVIEW_DOCUMENT_UUID_TYPE: Uuid =
+ Uuid::from_u128(0xE4CA_F5F0_098B_45FD_94F3_0702_A457_3DB5);
+ /// Review template `UuidV4` type.
+ pub const REVIEW_TEMPLATE_UUID_TYPE: Uuid =
+ Uuid::from_u128(0xEBE5_D0BF_5D86_4577_AF4D_008F_DDBE_2EDC);
+ /// Category document `UuidV4` type.
+ pub const CATEGORY_DOCUMENT_UUID_TYPE: Uuid =
+ Uuid::from_u128(0x48C2_0109_362A_4D32_9BBA_E0A9_CF8B_45BE);
+ /// Category template `UuidV4` type.
+ pub const CATEGORY_TEMPLATE_UUID_TYPE: Uuid =
+ Uuid::from_u128(0x65B1_E8B0_51F1_46A5_9970_72CD_F268_84BE);
+ /// Campaign parameters document `UuidV4` type.
+ pub const CAMPAIGN_DOCUMENT_UUID_TYPE: Uuid =
+ Uuid::from_u128(0x0110_EA96_A555_47CE_8408_36EF_E6ED_6F7C);
+ /// Campaign parameters template `UuidV4` type.
+ pub const CAMPAIGN_TEMPLATE_UUID_TYPE: Uuid =
+ Uuid::from_u128(0x7E8F_5FA2_44CE_49C8_BFD5_02AF_42C1_79A3);
+ /// Brand parameters document `UuidV4` type.
+ pub const BRAND_DOCUMENT_UUID_TYPE: Uuid =
+ Uuid::from_u128(0x3E48_08CC_C86E_467B_9702_D60B_AA9D_1FCA);
+ /// Brand parameters template `UuidV4` type.
+ pub const BRAND_TEMPLATE_UUID_TYPE: Uuid =
+ Uuid::from_u128(0xFD3C_1735_80B1_4EEA_8D63_5F43_6D97_EA31);
+ /// Proposal action document `UuidV4` type.
+ pub const PROPOSAL_ACTION_DOCUMENT_UUID_TYPE: Uuid =
+ Uuid::from_u128(0x5E60_E623_AD02_4A1B_A1AC_406D_B978_EE48);
+ /// Public vote transaction v2 `UuidV4` type.
+ pub const PUBLIC_VOTE_TX_V2_UUID_TYPE: Uuid =
+ Uuid::from_u128(0x8DE5_586C_E998_4B95_8742_7BE3_C859_2803);
+ /// Private vote transaction v2 `UuidV4` type.
+ pub const PRIVATE_VOTE_TX_V2_UUID_TYPE: Uuid =
+ Uuid::from_u128(0xE78E_E18D_F380_44C1_A852_80AA_6ECB_07FE);
+ /// Immutable ledger block `UuidV4` type.
+ pub const IMMUTABLE_LEDGER_BLOCK_UUID_TYPE: Uuid =
+ Uuid::from_u128(0xD9E7_E6CE_2401_4D7D_9492_F4F7_C642_41C3);
+ /// Submission Action `UuidV4` type.
+ pub const SUBMISSION_ACTION: Uuid = Uuid::from_u128(0x7892_7329_CFD9_4EA1_9C71_0E01_9B12_6A65);
+}
diff --git a/rust/signed_doc/src/lib.rs b/rust/signed_doc/src/lib.rs
index 75e0681a48..b7e599ef04 100644
--- a/rust/signed_doc/src/lib.rs
+++ b/rust/signed_doc/src/lib.rs
@@ -23,6 +23,7 @@ pub use catalyst_types::{
};
pub use content::Content;
use coset::{CborSerializable, Header, TaggedCborSerializable};
+use decode_context::{CompatibilityPolicy, DecodeContext};
pub use metadata::{
ContentEncoding, ContentType, DocType, DocumentRef, ExtraFields, Metadata, Section,
};
@@ -88,11 +89,11 @@ impl From for CatalystSignedDocument {
impl CatalystSignedDocument {
// A bunch of getters to access the contents, or reason through the document, such as.
- /// Return Document Type `UUIDv4`.
+ /// Return Document Type `DocType` - List of `UUIDv4`.
///
/// # Errors
/// - Missing 'type' field.
- pub fn doc_type(&self) -> anyhow::Result {
+ pub fn doc_type(&self) -> anyhow::Result<&DocType> {
self.inner.metadata.doc_type()
}
@@ -238,8 +239,12 @@ impl Decode<'_, ()> for CatalystSignedDocument {
minicbor::decode::Error::message(format!("Invalid COSE Sign document: {e}"))
})?;
- let report = ProblemReport::new(PROBLEM_REPORT_CTX);
- let metadata = Metadata::from_protected_header(&cose_sign.protected, &report);
+ let mut report = ProblemReport::new(PROBLEM_REPORT_CTX);
+ let mut ctx = DecodeContext {
+ compatibility_policy: CompatibilityPolicy::Accept,
+ report: &mut report,
+ };
+ let metadata = Metadata::from_protected_header(&cose_sign.protected, &mut ctx);
let signatures = Signatures::from_cose_sig_list(&cose_sign.signatures, &report);
let content = if let Some(payload) = cose_sign.payload {
diff --git a/rust/signed_doc/src/metadata/doc_type.rs b/rust/signed_doc/src/metadata/doc_type.rs
index c26240df03..a7c2ca205b 100644
--- a/rust/signed_doc/src/metadata/doc_type.rs
+++ b/rust/signed_doc/src/metadata/doc_type.rs
@@ -1,24 +1,29 @@
//! Document Type.
-use std::fmt::{Display, Formatter};
+use std::{
+ fmt::{Display, Formatter},
+ hash::{Hash, Hasher},
+};
use catalyst_types::{
problem_report::ProblemReport,
- uuid::{CborContext, Uuid, UuidV4},
+ uuid::{CborContext, Uuid, UuidV4, UUID_CBOR_TAG},
};
+use coset::cbor::Value;
use minicbor::{Decode, Decoder, Encode};
+use serde::{Deserialize, Deserializer};
use tracing::warn;
use crate::{
decode_context::{CompatibilityPolicy, DecodeContext},
doc_types::{
- COMMENT_DOCUMENT_UUID_TYPE, PROPOSAL_ACTION_DOCUMENT_UUID_TYPE,
- PROPOSAL_DOCUMENT_UUID_TYPE, SUBMISSION_ACTION,
+ ACTION_UUID_TYPE, COMMENT_UUID_TYPE, PROPOSAL_ACTION_DOC, PROPOSAL_COMMENT_DOC,
+ PROPOSAL_DOC_TYPE, PROPOSAL_UUID_TYPE,
},
};
/// List of `UUIDv4` document type.
-#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
+#[derive(Clone, Debug, serde::Serialize, Eq)]
pub struct DocType(Vec);
/// `DocType` Errors.
@@ -30,6 +35,9 @@ pub enum DocTypeError {
/// `DocType` cannot be empty.
#[error("DocType cannot be empty")]
Empty,
+ /// Invalid string conversion
+ #[error("Invalid string conversion: {0}")]
+ StringConversion(String),
}
impl DocType {
@@ -38,6 +46,32 @@ impl DocType {
pub fn doc_types(&self) -> &Vec {
&self.0
}
+
+ /// Convert `DocType` to coset `Value`.
+ pub(crate) fn to_value(&self) -> Value {
+ Value::Array(
+ self.0
+ .iter()
+ .map(|uuidv4| {
+ Value::Tag(
+ UUID_CBOR_TAG,
+ Box::new(Value::Bytes(uuidv4.uuid().as_bytes().to_vec())),
+ )
+ })
+ .collect(),
+ )
+ }
+}
+
+impl Hash for DocType {
+ fn hash(&self, state: &mut H) {
+ let list = self
+ .0
+ .iter()
+ .map(std::string::ToString::to_string)
+ .collect::>();
+ list.hash(state);
+ }
}
impl From for DocType {
@@ -83,6 +117,25 @@ impl TryFrom> for DocType {
}
}
+impl TryFrom> for DocType {
+ type Error = DocTypeError;
+
+ fn try_from(value: Vec) -> Result {
+ if value.is_empty() {
+ return Err(DocTypeError::Empty);
+ }
+ let converted = value
+ .into_iter()
+ .map(|s| {
+ s.parse::()
+ .map_err(|_| DocTypeError::StringConversion(s))
+ })
+ .collect::, _>>()?;
+
+ Ok(DocType(converted))
+ }
+}
+
impl Display for DocType {
fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), std::fmt::Error> {
write!(
@@ -166,12 +219,7 @@ impl Decode<'_, DecodeContext<'_>> for DocType {
minicbor::decode::Error::message(format!("{CONTEXT}: {msg}"))
})?;
- let ids = map_doc_type(uuid.into()).map_err(|e| {
- decode_context.report.other(&e.to_string(), CONTEXT);
- minicbor::decode::Error::message(format!("{CONTEXT}: {e}"))
- })?;
-
- let doc_type = ids.to_vec().try_into().map_err(|e: DocTypeError| {
+ let doc_type = map_doc_type(uuid.into()).map_err(|e| {
decode_context.report.other(&e.to_string(), CONTEXT);
minicbor::decode::Error::message(format!("{CONTEXT}: {e}"))
})?;
@@ -205,20 +253,11 @@ impl Decode<'_, DecodeContext<'_>> for DocType {
/// Map single UUID doc type to new list of doc types
///
-fn map_doc_type(uuid: Uuid) -> anyhow::Result<&'static [Uuid]> {
- const PROPOSAL_DOC: &[Uuid] = &[PROPOSAL_DOCUMENT_UUID_TYPE];
- const PROPOSAL_COMMENT_DOC: &[Uuid] =
- &[COMMENT_DOCUMENT_UUID_TYPE, PROPOSAL_DOCUMENT_UUID_TYPE];
- const PROPOSAL_ACTION_DOC: &[Uuid] = &[
- PROPOSAL_ACTION_DOCUMENT_UUID_TYPE,
- PROPOSAL_DOCUMENT_UUID_TYPE,
- SUBMISSION_ACTION,
- ];
-
+fn map_doc_type(uuid: Uuid) -> anyhow::Result {
match uuid {
- id if id == PROPOSAL_DOCUMENT_UUID_TYPE => Ok(PROPOSAL_DOC),
- id if id == COMMENT_DOCUMENT_UUID_TYPE => Ok(PROPOSAL_COMMENT_DOC),
- id if id == PROPOSAL_ACTION_DOCUMENT_UUID_TYPE => Ok(PROPOSAL_ACTION_DOC),
+ id if id == PROPOSAL_UUID_TYPE => Ok(PROPOSAL_DOC_TYPE.clone()),
+ id if id == COMMENT_UUID_TYPE => Ok(PROPOSAL_COMMENT_DOC.clone()),
+ id if id == ACTION_UUID_TYPE => Ok(PROPOSAL_ACTION_DOC.clone()),
_ => anyhow::bail!("Unknown document type: {uuid}"),
}
}
@@ -250,10 +289,65 @@ impl Encode for DocType {
}
}
+impl<'de> Deserialize<'de> for DocType {
+ fn deserialize(deserializer: D) -> Result
+ where D: Deserializer<'de> {
+ #[derive(Deserialize)]
+ #[serde(untagged)]
+ enum DocTypeInput {
+ /// Single UUID string.
+ Single(String),
+ /// List of UUID string.
+ Multiple(Vec),
+ }
+
+ let input = DocTypeInput::deserialize(deserializer)?;
+ let dt = match input {
+ DocTypeInput::Single(s) => {
+ let uuid = Uuid::parse_str(&s).map_err(|_| {
+ serde::de::Error::custom(DocTypeError::StringConversion(s.clone()))
+ })?;
+ // If there is a map from old (single uuid) to new use that list, else convert that
+ // single uuid to [uuid] - of type DocType
+ map_doc_type(uuid).unwrap_or(uuid.try_into().map_err(serde::de::Error::custom)?)
+ },
+ DocTypeInput::Multiple(v) => v.try_into().map_err(serde::de::Error::custom)?,
+ };
+ Ok(dt)
+ }
+}
+
+// This is needed to preserve backward compatibility with the old solution.
+impl PartialEq for DocType {
+ fn eq(&self, other: &Self) -> bool {
+ // List of special-case (single UUID) -> new DocType
+ // The old one should equal to the new one
+ let special_cases = [
+ (PROPOSAL_UUID_TYPE, &*PROPOSAL_DOC_TYPE),
+ (COMMENT_UUID_TYPE, &*PROPOSAL_COMMENT_DOC),
+ (ACTION_UUID_TYPE, &*PROPOSAL_ACTION_DOC),
+ ];
+ for (uuid, expected) in special_cases {
+ match DocType::try_from(uuid) {
+ Ok(single) => {
+ if (self.0 == single.0 && other.0 == expected.0)
+ || (other.0 == single.0 && self.0 == expected.0)
+ {
+ return true;
+ }
+ },
+ Err(_) => return false,
+ }
+ }
+ self.0 == other.0
+ }
+}
+
#[cfg(test)]
mod tests {
use minicbor::Encoder;
+ use serde_json::json;
use super::*;
@@ -264,7 +358,7 @@ mod tests {
const PSA: &str = "D825505E60E623AD024A1BA1AC406DB978EE48";
#[test]
- fn test_empty_doc_type() {
+ fn test_empty_doc_type_cbor_decode() {
assert!(>>::try_from(vec![]).is_err());
let mut report = ProblemReport::new("Test empty doc type");
@@ -277,7 +371,7 @@ mod tests {
}
#[test]
- fn test_single_uuid_doc_type_fail_policy() {
+ fn test_single_uuid_doc_type_fail_policy_cbor_decode() {
let mut report = ProblemReport::new("Test single uuid doc type - fail");
let data = hex::decode(PSA).unwrap();
let decoder = Decoder::new(&data);
@@ -289,7 +383,7 @@ mod tests {
}
#[test]
- fn test_single_uuid_doc_type_warn_policy() {
+ fn test_single_uuid_doc_type_warn_policy_cbor_decode() {
let mut report = ProblemReport::new("Test single uuid doc type - warn");
let data = hex::decode(PSA).unwrap();
let decoder = Decoder::new(&data);
@@ -302,7 +396,7 @@ mod tests {
}
#[test]
- fn test_single_uuid_doc_type_accept_policy() {
+ fn test_single_uuid_doc_type_accept_policy_cbor_decode() {
let mut report = ProblemReport::new("Test single uuid doc type - accept");
let data = hex::decode(PSA).unwrap();
let decoder = Decoder::new(&data);
@@ -315,7 +409,7 @@ mod tests {
}
#[test]
- fn test_multi_uuid_doc_type() {
+ fn test_multi_uuid_doc_type_cbor_decode_encode() {
let uuidv4 = UuidV4::new();
let mut report = ProblemReport::new("Test multi uuid doc type");
let doc_type_list: DocType = vec![uuidv4, uuidv4].try_into().unwrap();
@@ -330,4 +424,90 @@ mod tests {
let decoded_doc_type = DocType::decode(&mut decoder, &mut decoded_context).unwrap();
assert_eq!(decoded_doc_type, doc_type_list);
}
+
+ #[test]
+ fn test_valid_vec_string() {
+ let uuid = Uuid::new_v4().to_string();
+ let input = vec![uuid.clone()];
+ let doc_type = DocType::try_from(input).expect("should succeed");
+
+ assert_eq!(doc_type.0.len(), 1);
+ assert_eq!(doc_type.0.first().unwrap().to_string(), uuid);
+ }
+
+ #[test]
+ fn test_empty_vec_string_fails() {
+ let input: Vec = vec![];
+ let result = DocType::try_from(input);
+ assert!(matches!(result, Err(DocTypeError::Empty)));
+ }
+
+ #[test]
+ fn test_invalid_uuid_vec_string() {
+ let input = vec!["not-a-uuid".to_string()];
+ let result = DocType::try_from(input);
+ assert!(matches!(result, Err(DocTypeError::StringConversion(s)) if s == "not-a-uuid"));
+ }
+
+ #[test]
+ fn test_doc_type_to_value() {
+ let uuid = uuid::Uuid::new_v4();
+ let doc_type = DocType(vec![UuidV4::try_from(uuid).unwrap()]);
+
+ for d in &doc_type.to_value().into_array().unwrap() {
+ let t = d.clone().into_tag().unwrap();
+ assert_eq!(t.0, UUID_CBOR_TAG);
+ assert_eq!(t.1.as_bytes().unwrap().len(), 16);
+ }
+ }
+
+ #[test]
+ fn test_doctype_equal_special_cases() {
+ // Direct equal
+ let uuid = PROPOSAL_UUID_TYPE;
+ let dt1 = DocType::try_from(vec![uuid]).unwrap();
+ let dt2 = DocType::try_from(vec![uuid]).unwrap();
+ assert_eq!(dt1, dt2);
+
+ // single -> special mapped type
+ let single = DocType::try_from(PROPOSAL_UUID_TYPE).unwrap();
+ assert_eq!(single, *PROPOSAL_DOC_TYPE);
+ let single = DocType::try_from(COMMENT_UUID_TYPE).unwrap();
+ assert_eq!(single, *PROPOSAL_COMMENT_DOC);
+ let single = DocType::try_from(ACTION_UUID_TYPE).unwrap();
+ assert_eq!(single, *PROPOSAL_ACTION_DOC);
+ }
+
+ #[test]
+ fn test_deserialize_single_uuid_normal() {
+ let uuid = uuid::Uuid::new_v4().to_string();
+ let json = json!(uuid);
+ let dt: DocType = serde_json::from_value(json).unwrap();
+
+ assert_eq!(dt.0.len(), 1);
+ assert_eq!(dt.0.first().unwrap().to_string(), uuid);
+ }
+
+ #[test]
+ fn test_deserialize_multiple_uuids() {
+ let uuid1 = uuid::Uuid::new_v4().to_string();
+ let uuid2 = uuid::Uuid::new_v4().to_string();
+ let json = json!([uuid1.clone(), uuid2.clone()]);
+
+ let dt: DocType = serde_json::from_value(json).unwrap();
+ let actual =
+ dt.0.iter()
+ .map(std::string::ToString::to_string)
+ .collect::>();
+ assert_eq!(actual, vec![uuid1, uuid2]);
+ }
+
+ #[test]
+ fn test_deserialize_special_case() {
+ let uuid = PROPOSAL_UUID_TYPE.to_string();
+ let json = json!(uuid);
+ let dt: DocType = serde_json::from_value(json).unwrap();
+
+ assert_eq!(dt, *PROPOSAL_DOC_TYPE);
+ }
}
diff --git a/rust/signed_doc/src/metadata/mod.rs b/rust/signed_doc/src/metadata/mod.rs
index 8597f8ba7f..703b71eacc 100644
--- a/rust/signed_doc/src/metadata/mod.rs
+++ b/rust/signed_doc/src/metadata/mod.rs
@@ -3,26 +3,24 @@ use std::fmt::{Display, Formatter};
mod content_encoding;
mod content_type;
-mod doc_type;
+pub(crate) mod doc_type;
mod document_ref;
mod extra_fields;
mod section;
pub(crate) mod utils;
-use catalyst_types::{
- problem_report::ProblemReport,
- uuid::{UuidV4, UuidV7},
-};
+use catalyst_types::{problem_report::ProblemReport, uuid::UuidV7};
pub use content_encoding::ContentEncoding;
pub use content_type::ContentType;
-use coset::{cbor::Value, iana::CoapContentFormat};
+use coset::{cbor::Value, iana::CoapContentFormat, CborSerializable};
pub use doc_type::DocType;
pub use document_ref::DocumentRef;
pub use extra_fields::ExtraFields;
+use minicbor::{Decode, Decoder};
pub use section::Section;
-use utils::{
- cose_protected_header_find, decode_document_field_from_protected_header, CborUuidV4, CborUuidV7,
-};
+use utils::{cose_protected_header_find, decode_document_field_from_protected_header, CborUuidV7};
+
+use crate::decode_context::DecodeContext;
/// `content_encoding` field COSE key value
const CONTENT_ENCODING_KEY: &str = "Content-Encoding";
@@ -42,9 +40,9 @@ pub struct Metadata(InnerMetadata);
/// An actual representation of all metadata fields.
#[derive(Clone, Debug, PartialEq, serde::Deserialize, Default)]
pub(crate) struct InnerMetadata {
- /// Document Type `UUIDv4`.
+ /// Document Type, list of `UUIDv4`.
#[serde(rename = "type")]
- doc_type: Option,
+ doc_type: Option,
/// Document ID `UUIDv7`.
id: Option,
/// Document Version `UUIDv7`.
@@ -61,13 +59,14 @@ pub(crate) struct InnerMetadata {
}
impl Metadata {
- /// Return Document Type `UUIDv4`.
+ /// Return Document Type `DocType` - a list of `UUIDv4`.
///
/// # Errors
/// - Missing 'type' field.
- pub fn doc_type(&self) -> anyhow::Result {
+ pub fn doc_type(&self) -> anyhow::Result<&DocType> {
self.0
.doc_type
+ .as_ref()
.ok_or(anyhow::anyhow!("Missing 'type' field"))
}
@@ -133,10 +132,10 @@ impl Metadata {
/// Converting COSE Protected Header to Metadata.
pub(crate) fn from_protected_header(
- protected: &coset::ProtectedHeader, report: &ProblemReport,
+ protected: &coset::ProtectedHeader, context: &mut DecodeContext,
) -> Self {
- let metadata = InnerMetadata::from_protected_header(protected, report);
- Self::from_metadata_fields(metadata, report)
+ let metadata = InnerMetadata::from_protected_header(protected, context);
+ Self::from_metadata_fields(metadata, context.report)
}
}
@@ -144,13 +143,13 @@ impl InnerMetadata {
/// Converting COSE Protected Header to Metadata fields, collecting decoding report
/// issues.
pub(crate) fn from_protected_header(
- protected: &coset::ProtectedHeader, report: &ProblemReport,
+ protected: &coset::ProtectedHeader, context: &mut DecodeContext,
) -> Self {
/// Context for problem report messages during decoding from COSE protected
/// header.
const COSE_DECODING_CONTEXT: &str = "COSE Protected Header to Metadata";
- let extra = ExtraFields::from_protected_header(protected, report);
+ let extra = ExtraFields::from_protected_header(protected, context.report);
let mut metadata = Self {
extra,
..Self::default()
@@ -160,7 +159,7 @@ impl InnerMetadata {
match ContentType::try_from(value) {
Ok(ct) => metadata.content_type = Some(ct),
Err(e) => {
- report.conversion_error(
+ context.report.conversion_error(
"COSE protected header content type",
&format!("{value:?}"),
&format!("Expected ContentType: {e}"),
@@ -177,7 +176,7 @@ impl InnerMetadata {
match ContentEncoding::try_from(value) {
Ok(ce) => metadata.content_encoding = Some(ce),
Err(e) => {
- report.conversion_error(
+ context.report.conversion_error(
"COSE protected header content encoding",
&format!("{value:?}"),
&format!("Expected ContentEncoding: {e}"),
@@ -187,19 +186,23 @@ impl InnerMetadata {
}
}
- metadata.doc_type = decode_document_field_from_protected_header::(
+ metadata.doc_type = cose_protected_header_find(
protected,
- TYPE_KEY,
- COSE_DECODING_CONTEXT,
- report,
+ |key| matches!(key, coset::Label::Text(label) if label.eq_ignore_ascii_case(TYPE_KEY)),
)
- .map(|v| v.0);
+ .and_then(|value| {
+ DocType::decode(
+ &mut Decoder::new(&value.clone().to_vec().unwrap_or_default()),
+ context,
+ )
+ .ok()
+ });
metadata.id = decode_document_field_from_protected_header::(
protected,
ID_KEY,
COSE_DECODING_CONTEXT,
- report,
+ context.report,
)
.map(|v| v.0);
@@ -207,7 +210,7 @@ impl InnerMetadata {
protected,
VER_KEY,
COSE_DECODING_CONTEXT,
- report,
+ context.report,
)
.map(|v| v.0);
@@ -243,10 +246,7 @@ impl TryFrom<&Metadata> for coset::Header {
}
builder = builder
- .text_value(
- TYPE_KEY.to_string(),
- Value::try_from(CborUuidV4(meta.doc_type()?))?,
- )
+ .text_value(TYPE_KEY.to_string(), meta.doc_type()?.to_value())
.text_value(
ID_KEY.to_string(),
Value::try_from(CborUuidV7(meta.doc_id()?))?,
diff --git a/rust/signed_doc/src/validator/mod.rs b/rust/signed_doc/src/validator/mod.rs
index 0c755bdcb5..da1b4604d2 100644
--- a/rust/signed_doc/src/validator/mod.rs
+++ b/rust/signed_doc/src/validator/mod.rs
@@ -5,7 +5,6 @@ pub(crate) mod utils;
use std::{
collections::HashMap,
- fmt,
sync::LazyLock,
time::{Duration, SystemTime},
};
@@ -14,7 +13,6 @@ use anyhow::Context;
use catalyst_types::{
catalyst_id::{role_index::RoleId, CatalystId},
problem_report::ProblemReport,
- uuid::{Uuid, UuidV4},
};
use coset::{CoseSign, CoseSignature};
use rules::{
@@ -24,28 +22,35 @@ use rules::{
use crate::{
doc_types::{
- CATEGORY_DOCUMENT_UUID_TYPE, COMMENT_DOCUMENT_UUID_TYPE, COMMENT_TEMPLATE_UUID_TYPE,
- PROPOSAL_ACTION_DOCUMENT_UUID_TYPE, PROPOSAL_DOCUMENT_UUID_TYPE,
- PROPOSAL_TEMPLATE_UUID_TYPE,
+ deprecated::{
+ CATEGORY_DOCUMENT_UUID_TYPE, COMMENT_TEMPLATE_UUID_TYPE, PROPOSAL_TEMPLATE_UUID_TYPE,
+ },
+ COMMENT_UUID_TYPE, PROPOSAL_ACTION_DOC, PROPOSAL_COMMENT_DOC, PROPOSAL_DOC_TYPE,
+ PROPOSAL_UUID_TYPE,
},
+ metadata::DocType,
providers::{CatalystSignedDocumentProvider, VerifyingKeyProvider},
CatalystSignedDocument, ContentEncoding, ContentType,
};
/// A table representing a full set or validation rules per document id.
-static DOCUMENT_RULES: LazyLock> = LazyLock::new(document_rules_init);
+static DOCUMENT_RULES: LazyLock> = LazyLock::new(document_rules_init);
-/// Returns an [`UuidV4`] from the provided argument, panicking if the argument is
-/// invalid.
+/// Returns an `DocType` from the provided argument.
+/// Reduce redundant conversion.
+/// This function should be used for hardcoded values, panic if conversion fail.
#[allow(clippy::expect_used)]
-fn expect_uuidv4(t: T) -> UuidV4
-where T: TryInto {
- t.try_into().expect("Must be a valid UUID V4")
+pub(crate) fn expect_doc_type(t: T) -> DocType
+where
+ T: TryInto,
+ T::Error: std::fmt::Debug,
+{
+ t.try_into().expect("Failed to convert to DocType")
}
/// `DOCUMENT_RULES` initialization function
#[allow(clippy::expect_used)]
-fn document_rules_init() -> HashMap {
+fn document_rules_init() -> HashMap {
let mut document_rules_map = HashMap::new();
let proposal_document_rules = Rules {
@@ -57,10 +62,10 @@ fn document_rules_init() -> HashMap {
optional: false,
},
content: ContentRule::Templated {
- exp_template_type: expect_uuidv4(PROPOSAL_TEMPLATE_UUID_TYPE),
+ exp_template_type: expect_doc_type(PROPOSAL_TEMPLATE_UUID_TYPE),
},
parameters: ParametersRule::Specified {
- exp_parameters_type: expect_uuidv4(CATEGORY_DOCUMENT_UUID_TYPE),
+ exp_parameters_type: expect_doc_type(CATEGORY_DOCUMENT_UUID_TYPE),
optional: true,
},
doc_ref: RefRule::NotSpecified,
@@ -71,7 +76,7 @@ fn document_rules_init() -> HashMap {
},
};
- document_rules_map.insert(PROPOSAL_DOCUMENT_UUID_TYPE, proposal_document_rules);
+ document_rules_map.insert(PROPOSAL_DOC_TYPE.clone(), proposal_document_rules);
let comment_document_rules = Rules {
content_type: ContentTypeRule {
@@ -82,14 +87,14 @@ fn document_rules_init() -> HashMap {
optional: false,
},
content: ContentRule::Templated {
- exp_template_type: expect_uuidv4(COMMENT_TEMPLATE_UUID_TYPE),
+ exp_template_type: expect_doc_type(COMMENT_TEMPLATE_UUID_TYPE),
},
doc_ref: RefRule::Specified {
- exp_ref_type: expect_uuidv4(PROPOSAL_DOCUMENT_UUID_TYPE),
+ exp_ref_type: expect_doc_type(PROPOSAL_UUID_TYPE),
optional: false,
},
reply: ReplyRule::Specified {
- exp_reply_type: expect_uuidv4(COMMENT_DOCUMENT_UUID_TYPE),
+ exp_reply_type: expect_doc_type(COMMENT_UUID_TYPE),
optional: true,
},
section: SectionRule::Specified { optional: true },
@@ -98,7 +103,7 @@ fn document_rules_init() -> HashMap {
exp: &[RoleId::Role0],
},
};
- document_rules_map.insert(COMMENT_DOCUMENT_UUID_TYPE, comment_document_rules);
+ document_rules_map.insert(PROPOSAL_COMMENT_DOC.clone(), comment_document_rules);
let proposal_action_json_schema = jsonschema::options()
.with_draft(jsonschema::Draft::Draft7)
@@ -119,11 +124,11 @@ fn document_rules_init() -> HashMap {
},
content: ContentRule::Static(ContentSchema::Json(proposal_action_json_schema)),
parameters: ParametersRule::Specified {
- exp_parameters_type: expect_uuidv4(CATEGORY_DOCUMENT_UUID_TYPE),
+ exp_parameters_type: expect_doc_type(CATEGORY_DOCUMENT_UUID_TYPE),
optional: true,
},
doc_ref: RefRule::Specified {
- exp_ref_type: expect_uuidv4(PROPOSAL_DOCUMENT_UUID_TYPE),
+ exp_ref_type: expect_doc_type(PROPOSAL_UUID_TYPE),
optional: false,
},
reply: ReplyRule::NotSpecified,
@@ -134,7 +139,7 @@ fn document_rules_init() -> HashMap {
};
document_rules_map.insert(
- PROPOSAL_ACTION_DOCUMENT_UUID_TYPE,
+ PROPOSAL_ACTION_DOC.clone(),
proposal_submission_action_rules,
);
@@ -164,7 +169,7 @@ where Provider: CatalystSignedDocumentProvider {
return Ok(false);
}
- let Some(rules) = DOCUMENT_RULES.get(&doc_type.uuid()) else {
+ let Some(rules) = DOCUMENT_RULES.get(doc_type) else {
doc.report().invalid_value(
"`type`",
&doc.doc_type()?.to_string(),
diff --git a/rust/signed_doc/src/validator/rules/doc_ref.rs b/rust/signed_doc/src/validator/rules/doc_ref.rs
index 53fec6825f..977893b061 100644
--- a/rust/signed_doc/src/validator/rules/doc_ref.rs
+++ b/rust/signed_doc/src/validator/rules/doc_ref.rs
@@ -1,13 +1,10 @@
//! `ref` rule type impl.
-use catalyst_types::{
- problem_report::ProblemReport,
- uuid::{Uuid, UuidV4},
-};
+use catalyst_types::problem_report::ProblemReport;
use crate::{
- providers::CatalystSignedDocumentProvider, validator::utils::validate_provided_doc,
- CatalystSignedDocument,
+ metadata::DocType, providers::CatalystSignedDocumentProvider,
+ validator::utils::validate_provided_doc, CatalystSignedDocument,
};
/// `ref` field validation rule
@@ -16,7 +13,7 @@ pub(crate) enum RefRule {
/// Is 'ref' specified
Specified {
/// expected `type` field of the referenced doc
- exp_ref_type: UuidV4,
+ exp_ref_type: DocType,
/// optional flag for the `ref` field
optional: bool,
},
@@ -36,7 +33,7 @@ impl RefRule {
{
if let Some(doc_ref) = doc.doc_meta().doc_ref() {
let ref_validator = |ref_doc: CatalystSignedDocument| {
- referenced_doc_check(&ref_doc, exp_ref_type.uuid(), "ref", doc.report())
+ referenced_doc_check(&ref_doc, exp_ref_type, "ref", doc.report())
};
return validate_provided_doc(&doc_ref, provider, doc.report(), ref_validator)
.await;
@@ -63,13 +60,14 @@ impl RefRule {
/// A generic implementation of the referenced document validation.
pub(crate) fn referenced_doc_check(
- ref_doc: &CatalystSignedDocument, exp_ref_type: Uuid, field_name: &str, report: &ProblemReport,
+ ref_doc: &CatalystSignedDocument, exp_ref_type: &DocType, field_name: &str,
+ report: &ProblemReport,
) -> bool {
let Ok(ref_doc_type) = ref_doc.doc_type() else {
report.missing_field("type", "Referenced document must have type field");
return false;
};
- if ref_doc_type.uuid() != exp_ref_type {
+ if ref_doc_type != exp_ref_type {
report.invalid_value(
field_name,
ref_doc_type.to_string().as_str(),
@@ -83,7 +81,7 @@ pub(crate) fn referenced_doc_check(
#[cfg(test)]
mod tests {
- use catalyst_types::uuid::UuidV7;
+ use catalyst_types::uuid::{UuidV4, UuidV7};
use super::*;
use crate::{providers::tests::TestCatalystSignedDocumentProvider, Builder};
@@ -137,7 +135,7 @@ mod tests {
// all correct
let rule = RefRule::Specified {
- exp_ref_type,
+ exp_ref_type: exp_ref_type.into(),
optional: false,
};
let doc = Builder::new()
@@ -150,7 +148,7 @@ mod tests {
// all correct, `ref` field is missing, but its optional
let rule = RefRule::Specified {
- exp_ref_type,
+ exp_ref_type: exp_ref_type.into(),
optional: true,
};
let doc = Builder::new().build();
@@ -158,7 +156,7 @@ mod tests {
// missing `ref` field, but its required
let rule = RefRule::Specified {
- exp_ref_type,
+ exp_ref_type: exp_ref_type.into(),
optional: false,
};
let doc = Builder::new().build();
diff --git a/rust/signed_doc/src/validator/rules/parameters.rs b/rust/signed_doc/src/validator/rules/parameters.rs
index 290d158439..41ad404df0 100644
--- a/rust/signed_doc/src/validator/rules/parameters.rs
+++ b/rust/signed_doc/src/validator/rules/parameters.rs
@@ -1,11 +1,9 @@
//! `parameters` rule type impl.
-use catalyst_types::uuid::UuidV4;
-
use super::doc_ref::referenced_doc_check;
use crate::{
- providers::CatalystSignedDocumentProvider, validator::utils::validate_provided_doc,
- CatalystSignedDocument,
+ metadata::DocType, providers::CatalystSignedDocumentProvider,
+ validator::utils::validate_provided_doc, CatalystSignedDocument,
};
/// `parameters` field validation rule
@@ -14,7 +12,7 @@ pub(crate) enum ParametersRule {
/// Is `parameters` specified
Specified {
/// expected `type` field of the parameter doc
- exp_parameters_type: UuidV4,
+ exp_parameters_type: DocType,
/// optional flag for the `parameters` field
optional: bool,
},
@@ -37,7 +35,7 @@ impl ParametersRule {
let parameters_validator = |replied_doc: CatalystSignedDocument| {
referenced_doc_check(
&replied_doc,
- exp_parameters_type.uuid(),
+ exp_parameters_type,
"parameters",
doc.report(),
)
@@ -126,7 +124,7 @@ mod tests {
// all correct
let rule = ParametersRule::Specified {
- exp_parameters_type,
+ exp_parameters_type: exp_parameters_type.into(),
optional: false,
};
let doc = Builder::new()
@@ -139,7 +137,7 @@ mod tests {
// all correct, `parameters` field is missing, but its optional
let rule = ParametersRule::Specified {
- exp_parameters_type,
+ exp_parameters_type: exp_parameters_type.into(),
optional: true,
};
let doc = Builder::new().build();
@@ -147,7 +145,7 @@ mod tests {
// missing `parameters` field, but its required
let rule = ParametersRule::Specified {
- exp_parameters_type,
+ exp_parameters_type: exp_parameters_type.into(),
optional: false,
};
let doc = Builder::new().build();
diff --git a/rust/signed_doc/src/validator/rules/reply.rs b/rust/signed_doc/src/validator/rules/reply.rs
index 5ac256667d..09b48ea28d 100644
--- a/rust/signed_doc/src/validator/rules/reply.rs
+++ b/rust/signed_doc/src/validator/rules/reply.rs
@@ -1,11 +1,9 @@
//! `reply` rule type impl.
-use catalyst_types::uuid::UuidV4;
-
use super::doc_ref::referenced_doc_check;
use crate::{
- providers::CatalystSignedDocumentProvider, validator::utils::validate_provided_doc,
- CatalystSignedDocument,
+ metadata::DocType, providers::CatalystSignedDocumentProvider,
+ validator::utils::validate_provided_doc, CatalystSignedDocument,
};
/// `reply` field validation rule
@@ -14,7 +12,7 @@ pub(crate) enum ReplyRule {
/// Is 'reply' specified
Specified {
/// expected `type` field of the replied doc
- exp_reply_type: UuidV4,
+ exp_reply_type: DocType,
/// optional flag for the `ref` field
optional: bool,
},
@@ -35,12 +33,7 @@ impl ReplyRule {
{
if let Some(reply) = doc.doc_meta().reply() {
let reply_validator = |replied_doc: CatalystSignedDocument| {
- if !referenced_doc_check(
- &replied_doc,
- exp_reply_type.uuid(),
- "reply",
- doc.report(),
- ) {
+ if !referenced_doc_check(&replied_doc, exp_reply_type, "reply", doc.report()) {
return false;
}
let Some(doc_ref) = doc.doc_meta().doc_ref() else {
@@ -165,7 +158,7 @@ mod tests {
// all correct
let rule = ReplyRule::Specified {
- exp_reply_type,
+ exp_reply_type: exp_reply_type.into(),
optional: false,
};
let doc = Builder::new()
@@ -179,7 +172,7 @@ mod tests {
// all correct, `reply` field is missing, but its optional
let rule = ReplyRule::Specified {
- exp_reply_type,
+ exp_reply_type: exp_reply_type.into(),
optional: true,
};
let doc = Builder::new().build();
@@ -187,7 +180,7 @@ mod tests {
// missing `reply` field, but its required
let rule = ReplyRule::Specified {
- exp_reply_type,
+ exp_reply_type: exp_reply_type.into(),
optional: false,
};
let doc = Builder::new()
diff --git a/rust/signed_doc/src/validator/rules/template.rs b/rust/signed_doc/src/validator/rules/template.rs
index 0d5b0c9aaa..13fea3b544 100644
--- a/rust/signed_doc/src/validator/rules/template.rs
+++ b/rust/signed_doc/src/validator/rules/template.rs
@@ -2,12 +2,12 @@
use std::fmt::Write;
-use catalyst_types::uuid::UuidV4;
-
use super::doc_ref::referenced_doc_check;
use crate::{
- metadata::ContentType, providers::CatalystSignedDocumentProvider,
- validator::utils::validate_provided_doc, CatalystSignedDocument,
+ metadata::{ContentType, DocType},
+ providers::CatalystSignedDocumentProvider,
+ validator::utils::validate_provided_doc,
+ CatalystSignedDocument,
};
/// Enum represents different content schemas, against which documents content would be
@@ -23,7 +23,7 @@ pub(crate) enum ContentRule {
/// Based on the 'template' field and loaded corresponding template document
Templated {
/// expected `type` field of the template
- exp_template_type: UuidV4,
+ exp_template_type: DocType,
},
/// Statically defined document's content schema.
/// `template` field should not been specified
@@ -48,12 +48,8 @@ impl ContentRule {
};
let template_validator = |template_doc: CatalystSignedDocument| {
- if !referenced_doc_check(
- &template_doc,
- exp_template_type.uuid(),
- "template",
- doc.report(),
- ) {
+ if !referenced_doc_check(&template_doc, exp_template_type, "template", doc.report())
+ {
return false;
}
@@ -181,7 +177,7 @@ fn content_schema_check(doc: &CatalystSignedDocument, schema: &ContentSchema) ->
#[cfg(test)]
mod tests {
- use catalyst_types::uuid::UuidV7;
+ use catalyst_types::uuid::{UuidV4, UuidV7};
use super::*;
use crate::{providers::tests::TestCatalystSignedDocumentProvider, Builder};
@@ -281,7 +277,9 @@ mod tests {
}
// all correct
- let rule = ContentRule::Templated { exp_template_type };
+ let rule = ContentRule::Templated {
+ exp_template_type: exp_template_type.into(),
+ };
let doc = Builder::new()
.with_json_metadata(serde_json::json!({
"template": {"id": valid_template_doc_id.to_string(), "ver": valid_template_doc_id.to_string() }
@@ -300,7 +298,9 @@ mod tests {
assert!(!rule.check(&doc, &provider).await.unwrap());
// missing content
- let rule = ContentRule::Templated { exp_template_type };
+ let rule = ContentRule::Templated {
+ exp_template_type: exp_template_type.into(),
+ };
let doc = Builder::new()
.with_json_metadata(serde_json::json!({
"template": {"id": valid_template_doc_id.to_string(), "ver": valid_template_doc_id.to_string() }
@@ -310,7 +310,9 @@ mod tests {
assert!(!rule.check(&doc, &provider).await.unwrap());
// content not a json encoded
- let rule = ContentRule::Templated { exp_template_type };
+ let rule = ContentRule::Templated {
+ exp_template_type: exp_template_type.into(),
+ };
let doc = Builder::new()
.with_json_metadata(serde_json::json!({
"template": {"id": valid_template_doc_id.to_string(), "ver": valid_template_doc_id.to_string() }
@@ -341,7 +343,9 @@ mod tests {
assert!(!rule.check(&doc, &provider).await.unwrap());
// missing `content-type` field in the referenced doc
- let rule = ContentRule::Templated { exp_template_type };
+ let rule = ContentRule::Templated {
+ exp_template_type: exp_template_type.into(),
+ };
let doc = Builder::new()
.with_json_metadata(serde_json::json!({
"template": {"id": missing_content_type_template_doc_id.to_string(), "ver": missing_content_type_template_doc_id.to_string() }
diff --git a/rust/signed_doc/tests/comment.rs b/rust/signed_doc/tests/comment.rs
index 1c746e589c..5725e3080c 100644
--- a/rust/signed_doc/tests/comment.rs
+++ b/rust/signed_doc/tests/comment.rs
@@ -8,16 +8,55 @@ mod common;
#[tokio::test]
async fn test_valid_comment_doc() {
let (proposal_doc, proposal_doc_id, proposal_doc_ver) =
- common::create_dummy_doc(doc_types::PROPOSAL_DOCUMENT_UUID_TYPE).unwrap();
+ common::create_dummy_doc(doc_types::PROPOSAL_UUID_TYPE).unwrap();
let (template_doc, template_doc_id, template_doc_ver) =
- common::create_dummy_doc(doc_types::COMMENT_TEMPLATE_UUID_TYPE).unwrap();
+ common::create_dummy_doc(doc_types::deprecated::COMMENT_TEMPLATE_UUID_TYPE).unwrap();
let uuid_v7 = UuidV7::new();
let (doc, ..) = common::create_dummy_signed_doc(
serde_json::json!({
"content-type": ContentType::Json.to_string(),
"content-encoding": ContentEncoding::Brotli.to_string(),
- "type": doc_types::COMMENT_DOCUMENT_UUID_TYPE,
+ "type": doc_types::PROPOSAL_COMMENT_DOC.clone(),
+ "id": uuid_v7.to_string(),
+ "ver": uuid_v7.to_string(),
+ "template": {
+ "id": template_doc_id,
+ "ver": template_doc_ver
+ },
+ "ref": {
+ "id": proposal_doc_id,
+ "ver": proposal_doc_ver
+ }
+ }),
+ serde_json::to_vec(&serde_json::Value::Null).unwrap(),
+ RoleId::Role0,
+ )
+ .unwrap();
+
+ let mut provider = TestCatalystSignedDocumentProvider::default();
+ provider.add_document(template_doc).unwrap();
+ provider.add_document(proposal_doc).unwrap();
+
+ let is_valid = validator::validate(&doc, &provider).await.unwrap();
+
+ assert!(is_valid);
+}
+
+#[tokio::test]
+async fn test_valid_comment_doc_old_type() {
+ let (proposal_doc, proposal_doc_id, proposal_doc_ver) =
+ common::create_dummy_doc(doc_types::PROPOSAL_UUID_TYPE).unwrap();
+ let (template_doc, template_doc_id, template_doc_ver) =
+ common::create_dummy_doc(doc_types::deprecated::COMMENT_TEMPLATE_UUID_TYPE).unwrap();
+
+ let uuid_v7 = UuidV7::new();
+ let (doc, ..) = common::create_dummy_signed_doc(
+ serde_json::json!({
+ "content-type": ContentType::Json.to_string(),
+ "content-encoding": ContentEncoding::Brotli.to_string(),
+ // Using old (single uuid)
+ "type": doc_types::deprecated::COMMENT_DOCUMENT_UUID_TYPE,
"id": uuid_v7.to_string(),
"ver": uuid_v7.to_string(),
"template": {
@@ -48,9 +87,9 @@ async fn test_valid_comment_doc_with_reply() {
let empty_json = serde_json::to_vec(&serde_json::json!({})).unwrap();
let (proposal_doc, proposal_doc_id, proposal_doc_ver) =
- common::create_dummy_doc(doc_types::PROPOSAL_DOCUMENT_UUID_TYPE).unwrap();
+ common::create_dummy_doc(doc_types::PROPOSAL_UUID_TYPE).unwrap();
let (template_doc, template_doc_id, template_doc_ver) =
- common::create_dummy_doc(doc_types::COMMENT_TEMPLATE_UUID_TYPE).unwrap();
+ common::create_dummy_doc(doc_types::deprecated::COMMENT_TEMPLATE_UUID_TYPE).unwrap();
let comment_doc_id = UuidV7::new();
let comment_doc_ver = UuidV7::new();
@@ -58,7 +97,7 @@ async fn test_valid_comment_doc_with_reply() {
.with_json_metadata(serde_json::json!({
"id": comment_doc_id,
"ver": comment_doc_ver,
- "type": doc_types::COMMENT_DOCUMENT_UUID_TYPE,
+ "type": doc_types::PROPOSAL_COMMENT_DOC.clone(),
"content-type": ContentType::Json.to_string(),
"template": { "id": template_doc_id.to_string(), "ver": template_doc_ver.to_string() },
"ref": {
@@ -75,7 +114,7 @@ async fn test_valid_comment_doc_with_reply() {
serde_json::json!({
"content-type": ContentType::Json.to_string(),
"content-encoding": ContentEncoding::Brotli.to_string(),
- "type": doc_types::COMMENT_DOCUMENT_UUID_TYPE,
+ "type": doc_types::PROPOSAL_COMMENT_DOC.clone(),
"id": uuid_v7.to_string(),
"ver": uuid_v7.to_string(),
"template": {
@@ -108,17 +147,16 @@ async fn test_valid_comment_doc_with_reply() {
#[tokio::test]
async fn test_invalid_comment_doc() {
- let (proposal_doc, ..) =
- common::create_dummy_doc(doc_types::PROPOSAL_DOCUMENT_UUID_TYPE).unwrap();
+ let (proposal_doc, ..) = common::create_dummy_doc(doc_types::PROPOSAL_UUID_TYPE).unwrap();
let (template_doc, template_doc_id, template_doc_ver) =
- common::create_dummy_doc(doc_types::COMMENT_TEMPLATE_UUID_TYPE).unwrap();
+ common::create_dummy_doc(doc_types::deprecated::COMMENT_TEMPLATE_UUID_TYPE).unwrap();
let uuid_v7 = UuidV7::new();
let (doc, ..) = common::create_dummy_signed_doc(
serde_json::json!({
"content-type": ContentType::Json.to_string(),
"content-encoding": ContentEncoding::Brotli.to_string(),
- "type": doc_types::COMMENT_DOCUMENT_UUID_TYPE,
+ "type": doc_types::PROPOSAL_COMMENT_DOC.clone(),
"id": uuid_v7.to_string(),
"ver": uuid_v7.to_string(),
"template": {
diff --git a/rust/signed_doc/tests/common/mod.rs b/rust/signed_doc/tests/common/mod.rs
index d7ea84150b..ae3d348f8a 100644
--- a/rust/signed_doc/tests/common/mod.rs
+++ b/rust/signed_doc/tests/common/mod.rs
@@ -27,6 +27,29 @@ pub fn test_metadata() -> (UuidV7, UuidV4, serde_json::Value) {
(uuid_v7, uuid_v4, metadata_fields)
}
+pub fn test_metadata_specific_type(
+ uuid_v4: Option, uuid_v7: Option,
+) -> (UuidV7, UuidV4, serde_json::Value) {
+ let uuid_v7 = uuid_v7.unwrap_or_else(UuidV7::new);
+ let uuid_v4 = uuid_v4.unwrap_or_else(UuidV4::new);
+
+ let metadata_fields = serde_json::json!({
+ "content-type": ContentType::Json.to_string(),
+ "content-encoding": ContentEncoding::Brotli.to_string(),
+ "type": uuid_v4.to_string(),
+ "id": uuid_v7.to_string(),
+ "ver": uuid_v7.to_string(),
+ "ref": {"id": uuid_v7.to_string(), "ver": uuid_v7.to_string()},
+ "reply": {"id": uuid_v7.to_string(), "ver": uuid_v7.to_string()},
+ "template": {"id": uuid_v7.to_string(), "ver": uuid_v7.to_string()},
+ "section": "$".to_string(),
+ "collabs": vec!["Alex1".to_string(), "Alex2".to_string()],
+ "parameters": {"id": uuid_v7.to_string(), "ver": uuid_v7.to_string()},
+ });
+
+ (uuid_v7, uuid_v4, metadata_fields)
+}
+
pub fn create_dummy_key_pair(
role_index: RoleId,
) -> anyhow::Result<(
diff --git a/rust/signed_doc/tests/decoding.rs b/rust/signed_doc/tests/decoding.rs
index 18697703c2..795183e699 100644
--- a/rust/signed_doc/tests/decoding.rs
+++ b/rust/signed_doc/tests/decoding.rs
@@ -10,7 +10,16 @@ mod common;
#[test]
fn catalyst_signed_doc_cbor_roundtrip_kid_as_id_test() {
- let (_, _, metadata_fields) = common::test_metadata();
+ catalyst_signed_doc_cbor_roundtrip_kid_as_id(common::test_metadata());
+ catalyst_signed_doc_cbor_roundtrip_kid_as_id(common::test_metadata_specific_type(
+ Some(doc_types::PROPOSAL_UUID_TYPE.try_into().unwrap()),
+ None,
+ ));
+}
+
+#[allow(clippy::unwrap_used)]
+fn catalyst_signed_doc_cbor_roundtrip_kid_as_id(data: (UuidV7, UuidV4, serde_json::Value)) {
+ let (_, _, metadata_fields) = data;
let (sk, _, kid) = create_dummy_key_pair(RoleId::Role0).unwrap();
// transform Catalyst ID URI form to the ID form
let kid = kid.as_id();
@@ -29,9 +38,19 @@ fn catalyst_signed_doc_cbor_roundtrip_kid_as_id_test() {
}
#[tokio::test]
-#[allow(clippy::too_many_lines)]
async fn catalyst_signed_doc_parameters_aliases_test() {
- let (_, _, metadata_fields) = common::test_metadata();
+ catalyst_signed_doc_parameters_aliases(common::test_metadata()).await;
+ catalyst_signed_doc_parameters_aliases(common::test_metadata_specific_type(
+ Some(doc_types::PROPOSAL_UUID_TYPE.try_into().unwrap()),
+ None,
+ ))
+ .await;
+}
+
+#[allow(clippy::unwrap_used)]
+#[allow(clippy::too_many_lines)]
+async fn catalyst_signed_doc_parameters_aliases(data: (UuidV7, UuidV4, serde_json::Value)) {
+ let (_, _, metadata_fields) = data;
let (sk, pk, kid) = common::create_dummy_key_pair(RoleId::Role0).unwrap();
let mut provider = TestVerifyingKeyProvider::default();
provider.add_pk(kid.clone(), pk);
@@ -215,7 +234,7 @@ fn signed_doc_with_all_fields_case() -> TestCase {
valid_doc: true,
post_checks: Some(Box::new({
move |doc| {
- (doc.doc_type().unwrap() == uuid_v4)
+ (doc.doc_type().unwrap() == &DocType::from(uuid_v4))
&& (doc.doc_id().unwrap() == uuid_v7)
&& (doc.doc_ver().unwrap() == uuid_v7)
&& (doc.doc_content_type().unwrap() == ContentType::Json)
diff --git a/rust/signed_doc/tests/proposal.rs b/rust/signed_doc/tests/proposal.rs
index 50ce1799e4..7e6f4f21d7 100644
--- a/rust/signed_doc/tests/proposal.rs
+++ b/rust/signed_doc/tests/proposal.rs
@@ -8,14 +8,46 @@ mod common;
#[tokio::test]
async fn test_valid_proposal_doc() {
let (template_doc, template_doc_id, template_doc_ver) =
- common::create_dummy_doc(doc_types::PROPOSAL_TEMPLATE_UUID_TYPE).unwrap();
+ common::create_dummy_doc(doc_types::deprecated::PROPOSAL_TEMPLATE_UUID_TYPE).unwrap();
let uuid_v7 = UuidV7::new();
let (doc, ..) = common::create_dummy_signed_doc(
serde_json::json!({
"content-type": ContentType::Json.to_string(),
"content-encoding": ContentEncoding::Brotli.to_string(),
- "type": doc_types::PROPOSAL_DOCUMENT_UUID_TYPE,
+ "type": doc_types::PROPOSAL_DOC_TYPE.clone(),
+ "id": uuid_v7.to_string(),
+ "ver": uuid_v7.to_string(),
+ "template": {
+ "id": template_doc_id,
+ "ver": template_doc_ver
+ },
+ }),
+ serde_json::to_vec(&serde_json::Value::Null).unwrap(),
+ RoleId::Proposer,
+ )
+ .unwrap();
+
+ let mut provider = TestCatalystSignedDocumentProvider::default();
+ provider.add_document(template_doc).unwrap();
+
+ let is_valid = validator::validate(&doc, &provider).await.unwrap();
+
+ assert!(is_valid);
+}
+
+#[tokio::test]
+async fn test_valid_proposal_doc_old_type() {
+ let (template_doc, template_doc_id, template_doc_ver) =
+ common::create_dummy_doc(doc_types::deprecated::PROPOSAL_TEMPLATE_UUID_TYPE).unwrap();
+
+ let uuid_v7 = UuidV7::new();
+ let (doc, ..) = common::create_dummy_signed_doc(
+ serde_json::json!({
+ "content-type": ContentType::Json.to_string(),
+ "content-encoding": ContentEncoding::Brotli.to_string(),
+ // Using old (single uuid)
+ "type": doc_types::deprecated::PROPOSAL_DOCUMENT_UUID_TYPE,
"id": uuid_v7.to_string(),
"ver": uuid_v7.to_string(),
"template": {
@@ -47,7 +79,7 @@ async fn test_valid_proposal_doc_with_empty_provider() {
serde_json::json!({
"content-type": ContentType::Json.to_string(),
"content-encoding": ContentEncoding::Brotli.to_string(),
- "type": doc_types::PROPOSAL_DOCUMENT_UUID_TYPE,
+ "type": doc_types::PROPOSAL_DOC_TYPE.clone(),
"id": uuid_v7.to_string(),
"ver": uuid_v7.to_string(),
"template": {
@@ -74,7 +106,7 @@ async fn test_invalid_proposal_doc() {
serde_json::json!({
"content-type": ContentType::Json.to_string(),
"content-encoding": ContentEncoding::Brotli.to_string(),
- "type": doc_types::PROPOSAL_DOCUMENT_UUID_TYPE,
+ "type": doc_types::PROPOSAL_DOC_TYPE.clone(),
"id": uuid_v7.to_string(),
"ver": uuid_v7.to_string(),
// without specifying template id
diff --git a/rust/signed_doc/tests/submission.rs b/rust/signed_doc/tests/submission.rs
index d10c6c3952..dc2ea5d56a 100644
--- a/rust/signed_doc/tests/submission.rs
+++ b/rust/signed_doc/tests/submission.rs
@@ -8,14 +8,47 @@ mod common;
#[tokio::test]
async fn test_valid_submission_action() {
let (proposal_doc, proposal_doc_id, proposal_doc_ver) =
- common::create_dummy_doc(doc_types::PROPOSAL_DOCUMENT_UUID_TYPE).unwrap();
+ common::create_dummy_doc(doc_types::PROPOSAL_UUID_TYPE).unwrap();
let uuid_v7 = UuidV7::new();
let (doc, ..) = common::create_dummy_signed_doc(
serde_json::json!({
"content-type": ContentType::Json.to_string(),
"content-encoding": ContentEncoding::Brotli.to_string(),
- "type": doc_types::PROPOSAL_ACTION_DOCUMENT_UUID_TYPE,
+ "type": doc_types::PROPOSAL_ACTION_DOC.clone(),
+ "id": uuid_v7.to_string(),
+ "ver": uuid_v7.to_string(),
+ "ref": {
+ "id": proposal_doc_id,
+ "ver": proposal_doc_ver
+ },
+ }),
+ serde_json::to_vec(&serde_json::json!({
+ "action": "final"
+ }))
+ .unwrap(),
+ RoleId::Proposer,
+ )
+ .unwrap();
+
+ let mut provider = TestCatalystSignedDocumentProvider::default();
+ provider.add_document(proposal_doc).unwrap();
+ let is_valid = validator::validate(&doc, &provider).await.unwrap();
+ assert!(is_valid, "{:?}", doc.problem_report());
+}
+
+#[tokio::test]
+async fn test_valid_submission_action_old_type() {
+ let (proposal_doc, proposal_doc_id, proposal_doc_ver) =
+ common::create_dummy_doc(doc_types::PROPOSAL_UUID_TYPE).unwrap();
+
+ let uuid_v7 = UuidV7::new();
+ let (doc, ..) = common::create_dummy_signed_doc(
+ serde_json::json!({
+ "content-type": ContentType::Json.to_string(),
+ "content-encoding": ContentEncoding::Brotli.to_string(),
+ // Using old (single uuid)
+ "type": doc_types::deprecated::PROPOSAL_ACTION_DOCUMENT_UUID_TYPE,
"id": uuid_v7.to_string(),
"ver": uuid_v7.to_string(),
"ref": {
@@ -47,7 +80,7 @@ async fn test_valid_submission_action_with_empty_provider() {
serde_json::json!({
"content-type": ContentType::Json.to_string(),
"content-encoding": ContentEncoding::Brotli.to_string(),
- "type": doc_types::PROPOSAL_ACTION_DOCUMENT_UUID_TYPE,
+ "type": doc_types::PROPOSAL_ACTION_DOC.clone(),
"id": uuid_v7.to_string(),
"ver": uuid_v7.to_string(),
"ref": {
@@ -78,7 +111,7 @@ async fn test_invalid_submission_action() {
serde_json::json!({
"content-type": ContentType::Json.to_string(),
"content-encoding": ContentEncoding::Brotli.to_string(),
- "type": doc_types::PROPOSAL_ACTION_DOCUMENT_UUID_TYPE,
+ "type": doc_types::PROPOSAL_ACTION_DOC.clone(),
"id": uuid_v7.to_string(),
"ver": uuid_v7.to_string(),
// without specifying ref
@@ -98,13 +131,13 @@ async fn test_invalid_submission_action() {
// corrupted JSON
let (proposal_doc, proposal_doc_id, proposal_doc_ver) =
- common::create_dummy_doc(doc_types::PROPOSAL_DOCUMENT_UUID_TYPE).unwrap();
+ common::create_dummy_doc(doc_types::PROPOSAL_UUID_TYPE).unwrap();
let uuid_v7 = UuidV7::new();
let (doc, ..) = common::create_dummy_signed_doc(
serde_json::json!({
"content-type": ContentType::Json.to_string(),
"content-encoding": ContentEncoding::Brotli.to_string(),
- "type": doc_types::PROPOSAL_ACTION_DOCUMENT_UUID_TYPE,
+ "type": doc_types::ACTION_UUID_TYPE,
"id": uuid_v7.to_string(),
"ver": uuid_v7.to_string(),
"ref": {
@@ -124,13 +157,13 @@ async fn test_invalid_submission_action() {
// empty content
let (proposal_doc, proposal_doc_id, proposal_doc_ver) =
- common::create_dummy_doc(doc_types::PROPOSAL_DOCUMENT_UUID_TYPE).unwrap();
+ common::create_dummy_doc(doc_types::PROPOSAL_UUID_TYPE).unwrap();
let uuid_v7 = UuidV7::new();
let (doc, ..) = common::create_dummy_signed_doc(
serde_json::json!({
"content-type": ContentType::Json.to_string(),
"content-encoding": ContentEncoding::Brotli.to_string(),
- "type": doc_types::PROPOSAL_ACTION_DOCUMENT_UUID_TYPE,
+ "type": doc_types::PROPOSAL_ACTION_DOC.clone(),
"id": uuid_v7.to_string(),
"ver": uuid_v7.to_string(),
"ref": {