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
use crate::{
    commons::{
        crypto::KeyPair,
        errors::SubjectError,
        identifier::{DigestIdentifier, KeyIdentifier},
    },
    signature::Signed,
    Derivable, Event,
};
use borsh::{BorshDeserialize, BorshSerialize};
use json_patch::{patch, Patch};
use serde::{Deserialize, Serialize};

use super::{evaluation::SubjectContext, request::EventRequest, value_wrapper::ValueWrapper};

/// A struct representing a TAPLE subject.
#[derive(Debug, Deserialize, Serialize, Clone, BorshSerialize, BorshDeserialize)]
pub struct Subject {
    /// The key pair associated with the subject, if any.
    pub keys: Option<KeyPair>,
    /// The identifier of the subject.
    pub subject_id: DigestIdentifier,
    /// The identifier of the governance contract associated with the subject.
    pub governance_id: DigestIdentifier,
    /// The current sequence number of the subject.
    pub sn: u64,
    /// The version of the governance contract that created the subject.
    pub genesis_gov_version: u64,
    /// The identifier of the public key of the subject owner.
    pub public_key: KeyIdentifier,
    /// The namespace of the subject.
    pub namespace: String,
    /// The name of the subject.
    pub name: String,
    /// The identifier of the schema used to validate the subject.
    pub schema_id: String,
    /// The identifier of the public key of the subject owner.
    pub owner: KeyIdentifier,
    /// The identifier of the public key of the subject creator.
    pub creator: KeyIdentifier,
    /// The current status of the subject.
    pub properties: ValueWrapper,
    /// Indicates whether the subject is active or not.
    pub active: bool,
}

/// A struct representing the data associated with a TAPLE subject.
#[derive(Debug, Deserialize, Serialize, Clone)]
pub struct SubjectData {
    /// The identifier of the subject.
    pub subject_id: DigestIdentifier,
    /// The identifier of the governance contract associated with the subject.
    pub governance_id: DigestIdentifier,
    /// The current sequence number of the subject.
    pub sn: u64,
    /// The identifier of the public key of the subject owner.
    pub public_key: KeyIdentifier,
    /// The namespace of the subject.
    pub namespace: String,
    /// The name of the subject.
    pub name: String,
    /// The identifier of the schema used to validate the subject.
    pub schema_id: String,
    /// The identifier of the public key of the subject owner.
    pub owner: KeyIdentifier,
    /// The identifier of the public key of the subject creator.
    pub creator: KeyIdentifier,
    /// The current status of the subject.
    pub properties: ValueWrapper,
    /// Indicates whether the subject is active or not.
    pub active: bool,
}

impl From<Subject> for SubjectData {
    fn from(subject: Subject) -> Self {
        Self {
            subject_id: subject.subject_id,
            governance_id: subject.governance_id,
            sn: subject.sn,
            public_key: subject.public_key,
            namespace: subject.namespace,
            schema_id: subject.schema_id,
            owner: subject.owner,
            creator: subject.creator,
            properties: subject.properties,
            active: subject.active,
            name: subject.name,
        }
    }
}

impl Subject {
    // // TODO: Probablemente borrar
    // pub fn from_genesis_request(
    //     event_request: EventRequest,
    //     init_state: String,
    // ) -> Result<Self, SubjectError> {
    //     let EventRequestType::Create(create_request) = event_request.request.clone() else {
    //         return Err(SubjectError::NotCreateEvent)
    //     };
    //     // TODO: Pasar que tipo de esquema criptográfico se quiere usar por parametros
    //     let keys = KeyPair::Ed25519(Ed25519KeyPair::new());
    //     let public_key = KeyIdentifier::new(keys.get_key_derivator(), &keys.public_key_bytes());
    //     let subject_id = generate_subject_id(
    //         &create_request.namespace,
    //         &create_request.schema_id,
    //         create_request.public_key.to_str(),
    //         create_request.governance_id.to_str(),
    //         0, // Ta mal
    //     )?;
    //     Ok(Subject {
    //         keys: Some(keys),
    //         subject_id,
    //         governance_id: create_request.governance_id.clone(),
    //         sn: 0,
    //         public_key,
    //         namespace: create_request.namespace.clone(),
    //         schema_id: create_request.schema_id.clone(),
    //         owner: event_request.signature.content.signer.clone(),
    //         creator: event_request.signature.content.signer.clone(),
    //         properties: init_state,
    //         active: true,
    //         name: create_request.name,
    //     })
    // }

    pub fn get_subject_context(&self, invoker: KeyIdentifier) -> SubjectContext {
        SubjectContext {
            governance_id: self.governance_id.clone(),
            schema_id: self.schema_id.clone(),
            is_owner: invoker == self.owner,
            state: self.properties.clone(),
            namespace: self.namespace.clone(),
        }
    }

    pub fn from_genesis_event(
        event: Signed<Event>,
        init_state: ValueWrapper,
        keys: Option<KeyPair>,
    ) -> Result<Self, SubjectError> {
        let EventRequest::Create(create_request) = event.content.event_request.content.clone() else {
            return Err(SubjectError::NotCreateEvent)
        };
        let subject_id = generate_subject_id(
            &create_request.namespace,
            &create_request.schema_id,
            create_request.public_key.to_str(),
            create_request.governance_id.to_str(),
            event.content.gov_version,
        )?;
        Ok(Subject {
            keys,
            subject_id,
            governance_id: create_request.governance_id.clone(),
            sn: 0,
            public_key: create_request.public_key,
            namespace: create_request.namespace.clone(),
            schema_id: create_request.schema_id.clone(),
            owner: event.content.event_request.signature.signer.clone(),
            creator: event.content.event_request.signature.signer.clone(),
            properties: init_state,
            active: true,
            name: create_request.name,
            genesis_gov_version: event.content.gov_version,
        })
    }

    pub fn update_subject(
        &mut self,
        json_patch: ValueWrapper,
        new_sn: u64,
    ) -> Result<(), SubjectError> {
        let Ok(patch_json) = serde_json::from_value::<Patch>(json_patch.0) else {
                    return Err(SubjectError::ErrorParsingJsonString("Json Patch conversion fails".to_owned()));
                };
        let Ok(()) = patch(&mut self.properties.0, &patch_json) else {
                    return Err(SubjectError::ErrorApplyingPatch("Error Applying Patch".to_owned()));
                };
        self.sn = new_sn;
        Ok(())
    }

    pub fn transfer_subject(
        &mut self,
        owner: KeyIdentifier,
        public_key: KeyIdentifier,
        keys: Option<KeyPair>,
        sn: u64,
    ) {
        self.owner = owner;
        self.public_key = public_key;
        self.keys = keys;
        self.sn = sn;
    }

    pub fn get_state_hash(&self) -> Result<DigestIdentifier, SubjectError> {
        Ok(
            DigestIdentifier::from_serializable_borsh(&self.properties).map_err(|_| {
                SubjectError::CryptoError(String::from("Error calculating the hash of the state"))
            })?,
        )
    }

    pub fn eol_event(&mut self) {
        self.active = false;
    }

    pub fn state_hash_after_apply(
        &self,
        json_patch: ValueWrapper,
    ) -> Result<DigestIdentifier, SubjectError> {
        let mut subject_properties = self.properties.clone();
        let json_patch = serde_json::from_value::<Patch>(json_patch.0)
            .map_err(|_| SubjectError::CryptoError(String::from("Error parsing the json patch")))?;
        patch(&mut subject_properties.0, &json_patch).map_err(|_| {
            SubjectError::CryptoError(String::from("Error applying the json patch"))
        })?;
        Ok(
            DigestIdentifier::from_serializable_borsh(&subject_properties).map_err(|_| {
                SubjectError::CryptoError(String::from("Error calculating the hash of the state"))
            })?,
        )
    }
}

pub fn generate_subject_id(
    namespace: &str,
    schema_id: &str,
    public_key: String,
    governance_id: String,
    governance_version: u64,
) -> Result<DigestIdentifier, SubjectError> {
    let subject_id = DigestIdentifier::from_serializable_borsh((
        namespace,
        schema_id,
        public_key,
        governance_id,
        governance_version,
    ))
    .map_err(|_| SubjectError::ErrorCreatingSubjectId)?;
    Ok(subject_id)
}