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
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
use std::collections::{HashMap, HashSet};

use bc_components::{PublicKeyBase, ARID};
use bc_envelope::prelude::*;
use bytes::Bytes;

use crate::{receipt::Receipt, GET_SHARES_FUNCTION, RECEIPT_PARAM, util::{Abbrev, FlankedFunction}};

use super::{parse_request, parse_response, request_body, request_envelope, response_envelope};

//
// Request
//

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct GetSharesRequest {
    id: ARID,
    key: PublicKeyBase,
    receipts: HashSet<Receipt>,
}

impl GetSharesRequest {
    pub fn new<'a>(
        key: impl AsRef<PublicKeyBase>,
        receipts: impl IntoIterator<Item = &'a Receipt>,
    ) -> Self {
        Self::new_opt(
            ARID::new(),
            key.as_ref().clone(),
            receipts.into_iter().cloned().collect(),
        )
    }

    pub fn new_opt(id: ARID, key: PublicKeyBase, receipts: HashSet<Receipt>) -> Self {
        Self { id, key, receipts }
    }

    pub fn id(&self) -> &ARID {
        self.id.as_ref()
    }

    pub fn key(&self) -> &PublicKeyBase {
        &self.key
    }

    pub fn receipts(&self) -> &HashSet<Receipt> {
        &self.receipts
    }
}

impl EnvelopeEncodable for GetSharesRequest {
    fn envelope(self) -> Envelope {
        let mut body = request_body(GET_SHARES_FUNCTION, self.key);
        for receipt in self.receipts {
            body = body.add_parameter(RECEIPT_PARAM, receipt);
        }
        request_envelope(self.id, body)
    }
}

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

impl EnvelopeDecodable for GetSharesRequest {
    fn from_envelope(envelope: Envelope) -> anyhow::Result<Self> {
        let (id, key, body) = parse_request(GET_SHARES_FUNCTION, envelope)?;
        let receipts = body
            .objects_for_parameter(RECEIPT_PARAM)
            .into_iter()
            .map(|e| e.try_into())
            .collect::<anyhow::Result<HashSet<Receipt>>>()?;
        Ok(Self::new_opt(id, key, receipts))
    }
}

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

    fn try_from(value: Envelope) -> anyhow::Result<Self> {
        Self::from_envelope(value)
    }
}

impl EnvelopeCodable for GetSharesRequest {}

impl std::fmt::Display for GetSharesRequest {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_fmt(format_args!("{}: {} {} key {}",
            self.id().abbrev(),
            "getShares".flanked_function(),
            self.receipts().abbrev(),
            self.key().abbrev()
        ))
    }
}

//
// Response
//

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct GetSharesResponse {
    id: ARID,
    receipt_to_data: HashMap<Receipt, Bytes>,
}

impl GetSharesResponse {
    pub fn new(id: ARID, receipt_to_data: HashMap<Receipt, Bytes>) -> Self {
        Self {
            id,
            receipt_to_data,
        }
    }

    pub fn id(&self) -> &ARID {
        self.id.as_ref()
    }

    pub fn receipt_to_data(&self) -> &HashMap<Receipt, Bytes> {
        &self.receipt_to_data
    }

    pub fn data_for_receipt(&self, receipt: &Receipt) -> Option<Bytes> {
        self.receipt_to_data.get(receipt).cloned()
    }
}

impl EnvelopeEncodable for GetSharesResponse {
    fn envelope(self) -> Envelope {
        let mut result = known_values::OK_VALUE.envelope();
        for (receipt, data) in self.receipt_to_data {
            result = result.add_assertion(receipt, data);
        }
        response_envelope(self.id, Some(result))
    }
}

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

impl EnvelopeDecodable for GetSharesResponse {
    fn from_envelope(envelope: Envelope) -> anyhow::Result<Self> {
        let (id, result) = parse_response(envelope)?;
        let mut receipt_to_data = HashMap::new();
        for assertion in result.assertions() {
            let receipt: Receipt = assertion.expect_predicate()?.try_into()?;
            let data: Bytes = assertion.expect_object()?.try_into()?;
            receipt_to_data.insert(receipt, data);
        }
        Ok(Self::new(id, receipt_to_data))
    }
}

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

    fn try_from(value: Envelope) -> anyhow::Result<Self> {
        Self::from_envelope(value)
    }
}

impl EnvelopeCodable for GetSharesResponse {}

impl std::fmt::Display for GetSharesResponse {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_fmt(format_args!("{}: {} OK {}",
            self.id().abbrev(),
            "getShares".flanked_function(),
            self.receipt_to_data().abbrev()
        ))
    }
}

#[cfg(test)]
mod tests {
    use bc_components::PrivateKeyBase;
    use indoc::indoc;

    use super::*;

    fn id() -> ARID {
        ARID::from_data_ref(hex_literal::hex!(
            "8712dfac3d0ebfa910736b2a9ee39d4b68f64222a77bcc0074f3f5f1c9216d30"
        ))
        .unwrap()
    }

    fn user_id() -> ARID {
        ARID::from_data_ref(hex_literal::hex!(
            "8712dfac3d0ebfa910736b2a9ee39d4b68f64222a77bcc0074f3f5f1c9216d30"
        ))
        .unwrap()
    }

    fn data_1() -> Bytes {
        Bytes::from_static(b"data_1")
    }

    fn receipt_1() -> Receipt {
        Receipt::new(&user_id(), data_1())
    }

    fn data_2() -> Bytes {
        Bytes::from_static(b"data_2")
    }

    fn receipt_2() -> Receipt {
        Receipt::new(&user_id(), data_2())
    }

    #[test]
    fn test_request() {
        let private_key = PrivateKeyBase::new();
        let key = private_key.public_keys();

        let receipts = vec![receipt_1(), receipt_2()].into_iter().collect();

        let request = GetSharesRequest::new_opt(id(), key, receipts);
        let request_envelope = request.clone().envelope();
        assert_eq!(
            request_envelope.format(),
            indoc! {r#"
        request(ARID(8712dfac)) [
            'body': «"getShares"» [
                ❰"key"❱: PublicKeyBase
                ❰"receipt"❱: Bytes(32) [
                    'isA': "Receipt"
                ]
                ❰"receipt"❱: Bytes(32) [
                    'isA': "Receipt"
                ]
            ]
        ]
        "#}
            .trim()
        );
        let decoded = GetSharesRequest::try_from(request_envelope).unwrap();
        assert_eq!(request, decoded);
    }

    #[test]
    fn test_response() {
        let receipts_to_data = vec![(receipt_1(), data_1()), (receipt_2(), data_2())]
            .into_iter()
            .collect();
        let response = GetSharesResponse::new(id(), receipts_to_data);
        let response_envelope = response.clone().envelope();
        assert_eq!(
            response_envelope.format(),
            indoc! {r#"
        response(ARID(8712dfac)) [
            'result': 'OK' [
                Bytes(32) [
                    'isA': "Receipt"
                ]
                : Bytes(6)
                Bytes(32) [
                    'isA': "Receipt"
                ]
                : Bytes(6)
            ]
        ]
        "#}
            .trim()
        );
        let decoded = GetSharesResponse::try_from(response_envelope).unwrap();
        assert_eq!(response, decoded);
    }
}