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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
//! Output of an invocation, referenced by its invocation pointer.

use crate::{
    authority::{Issuer, UcanPrf},
    ipld::{DagCbor, DagCborRef, DagJson},
    task, Error, Pointer, Unit,
};
use libipld::{self, cbor::DagCborCodec, prelude::Codec, serde::from_ipld, Ipld};
use std::collections::BTreeMap;

pub mod metadata;

const RAN_KEY: &str = "ran";
const OUT_KEY: &str = "out";
const ISSUER_KEY: &str = "iss";
const METADATA_KEY: &str = "meta";
const PROOF_KEY: &str = "prf";

/// A Receipt is a cryptographically signed description of the [Invocation]
/// and its [resulting output] and requested effects.
///
/// TODO: Effects et al.
///
/// [resulting output]: Result
/// [Invocation]: super::Invocation
#[derive(Debug, Clone, PartialEq)]
pub struct Receipt<T> {
    ran: Pointer,
    out: task::Result<T>,
    meta: Ipld,
    issuer: Option<Issuer>,
    prf: UcanPrf,
}

impl<T> Receipt<T> {
    ///
    pub fn new(
        ran: Pointer,
        result: task::Result<T>,
        metadata: Ipld,
        issuer: Option<Issuer>,
        proof: UcanPrf,
    ) -> Self {
        Self {
            ran,
            out: result,
            meta: metadata,
            issuer,
            prf: proof,
        }
    }
}

impl<T> Receipt<T> {
    /// [Pointer] for [Invocation] ran.
    ///
    /// [Invocation]: super::Invocation
    pub fn ran(&self) -> &Pointer {
        &self.ran
    }

    /// [Result] output from invocation/execution.
    pub fn out(&self) -> &task::Result<T> {
        &self.out
    }

    /// [Ipld] metadata.
    pub fn meta(&self) -> &Ipld {
        &self.meta
    }

    /// Optional [Issuer] for [Receipt].
    pub fn issuer(&self) -> &Option<Issuer> {
        &self.issuer
    }

    /// [UcanPrf] delegation chain.
    pub fn prf(&self) -> &UcanPrf {
        &self.prf
    }
}

impl DagJson for Receipt<Ipld> {}

impl TryFrom<Receipt<Ipld>> for Vec<u8> {
    type Error = Error<Unit>;

    fn try_from(receipt: Receipt<Ipld>) -> Result<Self, Self::Error> {
        let receipt_ipld = Ipld::from(&receipt);
        let encoded = DagCborCodec.encode(&receipt_ipld)?;
        Ok(encoded)
    }
}

impl TryFrom<Vec<u8>> for Receipt<Ipld> {
    type Error = Error<Unit>;

    fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
        let ipld: Ipld = DagCborCodec.decode(&bytes)?;
        ipld.try_into()
    }
}

impl DagCbor for Receipt<Ipld> {}
impl DagCborRef for Receipt<Ipld> {}

impl From<&Receipt<Ipld>> for Ipld {
    fn from(receipt: &Receipt<Ipld>) -> Self {
        Ipld::Map(BTreeMap::from([
            (RAN_KEY.into(), receipt.ran.to_owned().into()),
            (OUT_KEY.into(), receipt.out.to_owned().into()),
            (METADATA_KEY.into(), receipt.meta.to_owned()),
            (
                ISSUER_KEY.into(),
                receipt
                    .issuer
                    .as_ref()
                    .map(|issuer| issuer.to_string().into())
                    .unwrap_or(Ipld::Null),
            ),
            (PROOF_KEY.into(), receipt.prf.to_owned().into()),
        ]))
    }
}

impl From<Receipt<Ipld>> for Ipld {
    fn from(receipt: Receipt<Ipld>) -> Self {
        From::from(&receipt)
    }
}

impl TryFrom<Ipld> for Receipt<Ipld> {
    type Error = Error<Unit>;

    fn try_from(ipld: Ipld) -> Result<Self, Self::Error> {
        let map = from_ipld::<BTreeMap<String, Ipld>>(ipld)?;

        let ran = map
            .get(RAN_KEY)
            .ok_or_else(|| Error::<Unit>::MissingField(RAN_KEY.to_string()))?
            .try_into()?;

        let out = map
            .get(OUT_KEY)
            .ok_or_else(|| Error::<Unit>::MissingField(OUT_KEY.to_string()))?;

        let meta = map
            .get(METADATA_KEY)
            .ok_or_else(|| Error::<Unit>::MissingField(METADATA_KEY.to_string()))?;

        let issuer = map
            .get(ISSUER_KEY)
            .and_then(|ipld| match ipld {
                Ipld::Null => None,
                ipld => Some(ipld),
            })
            .and_then(|ipld| from_ipld(ipld.to_owned()).ok())
            .map(Issuer::new);

        let prf = map
            .get(PROOF_KEY)
            .ok_or_else(|| Error::<Unit>::MissingField(PROOF_KEY.to_string()))?;

        Ok(Receipt {
            ran,
            out: task::Result::try_from(out)?,
            meta: meta.to_owned(),
            issuer,
            prf: UcanPrf::try_from(prf)?,
        })
    }
}

impl TryFrom<Receipt<Ipld>> for Pointer {
    type Error = Error<Unit>;

    fn try_from(receipt: Receipt<Ipld>) -> Result<Self, Self::Error> {
        Ok(Pointer::new(receipt.to_cid()?))
    }
}