1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
use bc_components::{ARID, Digest};
use bc_envelope::prelude::*;

#[derive(Clone, PartialEq, Eq, Hash)]
pub struct Receipt(Digest);

pub const RECEIPT_TYPE: &str = "Receipt";

impl Receipt {
    pub fn new(user_id: &ARID, data: impl AsRef<[u8]>) -> Self {
        Self(Digest::from_image_parts(&[user_id.data(), data.as_ref()]))
    }
}

impl std::ops::Deref for Receipt {
    type Target = Digest;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl std::fmt::Debug for Receipt {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "Receipt({})", hex::encode(&self.0))
    }
}

impl EnvelopeEncodable for Receipt {
    fn envelope(self) -> Envelope {
        Envelope::new(CBOR::byte_string(self.0))
            .add_type(RECEIPT_TYPE)
    }
}

impl From<Receipt> for Envelope {
    fn from(receipt: Receipt) -> Self {
        receipt.envelope()
    }
}

impl EnvelopeDecodable for Receipt {
    fn from_envelope(envelope: Envelope) -> anyhow::Result<Self> {
        envelope.clone().check_type_envelope(RECEIPT_TYPE)?;
        let cbor: CBOR = envelope.extract_subject()?;
        let bytes = cbor.expect_byte_string()?;
        let digest = Digest::from_data_ref(&bytes)?;
        Ok(Self(digest))
    }
}

impl TryFrom<Envelope> for Receipt {
    type Error = anyhow::Error;

    fn try_from(envelope: Envelope) -> Result<Self, Self::Error> {
        Self::from_envelope(envelope)
    }
}

impl EnvelopeCodable for Receipt { }

#[cfg(test)]
mod tests {
    use super::*;
    use hex_literal::hex;
    use indoc::indoc;

    #[test]
    fn test_receipt() {
        let user_id = ARID::from_data_ref(hex!("3eadf5bf7a4da69f824be029d2d0ece06fcb3aca7dd85d402b661f7b48f18294")).unwrap();
        let receipt = Receipt::new(&user_id, b"data");
        assert_eq!(format!("{:?}", receipt), "Receipt(12bd077763220d3223f6cd74f4d51103f29c7ba70b68765cd8ee13c84ee50152)");

        let envelope = receipt.clone().envelope();
        assert_eq!(format!("{}", envelope.ur_string()), "ur:envelope/lftpsohdcxbgryatktiacpbteycnynsnjywktlbyaxwznskgosbdiskohhtpwybwspglvwadgmoyadtpsoiogmihiaihinjojyamdwplrf");
        assert_eq!(envelope.format(),
        indoc!{r#"
        Bytes(32) [
            'isA': "Receipt"
        ]
        "#}.trim());

        let receipt_2 = Receipt::from_envelope(envelope.clone()).unwrap();
        assert_eq!(receipt, receipt_2);
    }
}