radix_common/data/manifest/model/
manifest_proof.rs

1use crate::internal_prelude::*;
2
3use crate::data::manifest::*;
4use crate::*;
5
6#[cfg_attr(
7    feature = "fuzzing",
8    derive(::arbitrary::Arbitrary, ::serde::Serialize, ::serde::Deserialize)
9)]
10#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
11#[must_use]
12pub struct ManifestProof(pub u32);
13
14labelled_resolvable_with_identity_impl!(ManifestProof, resolver_output: Self);
15
16//========
17// error
18//========
19
20/// Represents an error when parsing ManifestProof.
21#[derive(Debug, Clone, PartialEq, Eq)]
22pub enum ParseManifestProofError {
23    InvalidLength,
24}
25
26#[cfg(not(feature = "alloc"))]
27impl std::error::Error for ParseManifestProofError {}
28
29#[cfg(not(feature = "alloc"))]
30impl fmt::Display for ParseManifestProofError {
31    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
32        write!(f, "{:?}", self)
33    }
34}
35
36//========
37// binary
38//========
39
40impl TryFrom<&[u8]> for ManifestProof {
41    type Error = ParseManifestProofError;
42
43    fn try_from(slice: &[u8]) -> Result<Self, Self::Error> {
44        if slice.len() != 4 {
45            return Err(Self::Error::InvalidLength);
46        }
47        Ok(Self(u32::from_le_bytes(slice.try_into().unwrap())))
48    }
49}
50
51impl ManifestProof {
52    pub fn to_vec(&self) -> Vec<u8> {
53        self.0.to_le_bytes().to_vec()
54    }
55}
56
57manifest_type!(ManifestProof, ManifestCustomValueKind::Proof, 4);
58scrypto_describe_for_manifest_type!(ManifestProof, OWN_PROOF_TYPE, own_proof_type_data);
59
60#[cfg(test)]
61mod tests {
62    use super::*;
63
64    #[test]
65    fn manifest_proof_fail() {
66        let proof = ManifestProof(37);
67        let mut proof_vec = proof.to_vec();
68
69        assert!(ManifestProof::try_from(proof_vec.as_slice()).is_ok());
70
71        // malform encoded vector
72        proof_vec.push(0);
73        let proof_out = ManifestProof::try_from(proof_vec.as_slice());
74        assert_matches!(proof_out, Err(ParseManifestProofError::InvalidLength));
75
76        #[cfg(not(feature = "alloc"))]
77        println!("Manifest Proof error: {}", proof_out.unwrap_err());
78    }
79
80    #[test]
81    fn manifest_proof_encode_decode_fail() {
82        let mut buf = Vec::new();
83        let mut encoder = VecEncoder::<ManifestCustomValueKind>::new(&mut buf, 1);
84        let malformed_value: u8 = 1; // use u8 instead of u32 should inovke an error
85        encoder.write_slice(&malformed_value.to_le_bytes()).unwrap();
86
87        let mut decoder = VecDecoder::<ManifestCustomValueKind>::new(&buf, 1);
88        let proof_output = decoder
89            .decode_deeper_body_with_value_kind::<ManifestProof>(ManifestProof::value_kind());
90
91        // expecting 4 bytes, found only 1, so Buffer Underflow error should occur
92        assert_matches!(proof_output, Err(DecodeError::BufferUnderflow { .. }));
93    }
94}