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
use bc_components::{PublicKeyBase, ARID};
use bc_envelope::prelude::*;
use bytes::Bytes;
use anyhow::{Error, Result};

use crate::{STORE_SHARE_FUNCTION, DATA_PARAM, receipt::Receipt, util::{Abbrev, FlankedFunction}};

//
// Request
//

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct StoreShareRequest {
    id: ARID,
    key: PublicKeyBase,
    data: Bytes,
}

impl StoreShareRequest {
    pub fn from_fields(id: ARID, key: PublicKeyBase, data: Bytes) -> Self {
        Self {
            id,
            key,
            data,
        }
    }

    pub fn new(key: impl AsRef<PublicKeyBase>, data: impl AsRef<[u8]>) -> Self {
        Self::from_fields(ARID::new(), key.as_ref().clone(), Bytes::copy_from_slice(data.as_ref()))
    }

    pub fn from_body(id: ARID, key: PublicKeyBase, body: Envelope) -> Result<Self> {
        let data: Bytes = body.extract_object_for_parameter(DATA_PARAM)?;
        Ok(Self::from_fields(id, key, data))
    }

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

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

    pub fn data(&self) -> &Bytes {
        &self.data
    }
}

impl From<StoreShareRequest> for Envelope {
    fn from(value: StoreShareRequest) -> Self {
        let id = value.id().clone();
        Envelope::new_function(STORE_SHARE_FUNCTION)
            .add_parameter(DATA_PARAM, value.data)
            .into_transaction_request(id, &value.key)
    }
}

impl TryFrom<&Envelope> for StoreShareRequest {
    type Error = Error;

    fn try_from(envelope: &Envelope) -> Result<Self> {
        let (id, key, body, _) = envelope.parse_transaction_request(Some(&STORE_SHARE_FUNCTION))?;
        Self::from_body(id, key, body)
    }
}

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

//
// Response
//

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct StoreShareResponse {
    id: ARID,
    receipt: Receipt,
}

impl StoreShareResponse {
    pub fn new(id: ARID, receipt: Receipt) -> Self {
        Self {
            id,
            receipt,
        }
    }

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

    pub fn receipt(&self) -> Receipt {
        self.receipt.clone()
    }
}

impl From<StoreShareResponse> for Envelope {
    fn from(value: StoreShareResponse) -> Self {
        value.receipt.to_envelope().into_success_response(value.id)
    }
}

impl TryFrom<Envelope> for StoreShareResponse {
    type Error = Error;

    fn try_from(envelope: Envelope) -> Result<Self> {
        let (result, id) = envelope.parse_success_response(None)?;
        Ok(Self::new(id, result.try_into()?))
    }
}

impl std::fmt::Display for StoreShareResponse {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_fmt(format_args!("{}: {} OK receipt {}",
            self.id().abbrev(),
            "storeShare".flanked_function(),
            self.receipt().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())
    }

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

        let request = StoreShareRequest::from_fields(id(), key, Bytes::from_static(b"data"));
        let request_envelope = request.to_envelope();
        assert_eq!(request_envelope.format(),
        indoc! {r#"
        request(ARID(8712dfac)) [
            'body': «"storeShare"» [
                ❰"data"❱: Bytes(4)
            ]
            'senderPublicKey': PublicKeyBase
        ]
        "#}.trim()
        );
        let decoded = StoreShareRequest::try_from(&request_envelope).unwrap();
        assert_eq!(request, decoded);
    }

    #[test]
    fn test_response() {
        let response = StoreShareResponse::new(id(), receipt_1());
        let response_envelope = response.to_envelope();
        assert_eq!(response_envelope.format(),
        indoc! {r#"
        response(ARID(8712dfac)) [
            'result': Bytes(32) [
                'isA': "Receipt"
            ]
        ]
        "#}.trim()
        );
        let decoded = StoreShareResponse::try_from(response_envelope).unwrap();
        assert_eq!(response, decoded);
    }
}