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
use keri_core::actor::prelude::{HashFunctionCode, SelfAddressingIdentifier, SerializationFormats};
use keri_core::event::sections::seal::{EventSeal, Seal};
use keri_core::event_message::msg::KeriEvent;
use keri_core::event_message::timestamped::Timestamped;
use keri_core::prefix::IdentifierPrefix;
use teliox::event::verifiable_event::VerifiableEvent;
use teliox::query::{TelQueryArgs, TelQueryEvent, TelQueryRoute};
use teliox::seal::{AttachedSourceSeal, EventSourceSeal};

use crate::error::ControllerError;

use super::IdentifierController;

impl IdentifierController {
    /// Generate `vcp` event and `ixn` event with  seal to `vcp`. To finalize
    /// the process, `ixn` need to be signed confirmed with `finalize_event`
    /// function.
    pub fn incept_registry(&mut self) -> Result<(IdentifierPrefix, Vec<u8>), ControllerError> {
        // Create tel
        let tel = self.source.tel.clone();

        let vcp = tel.make_inception_event(
            self.id.clone(),
            vec![teliox::event::manager_event::Config::NoBackers],
            0,
            vec![],
        )?;
        let id = vcp.get_prefix();
        let seal = Seal::Event(EventSeal {
            prefix: vcp.get_prefix(),
            sn: vcp.get_sn(),
            event_digest: vcp.get_digest()?,
        });
        let ixn = self.anchor_with_seal(&[seal])?;
        let source_seal = EventSourceSeal {
            sn: ixn.data.sn,
            digest: ixn.digest()?,
        };
        let encoded = ixn.encode()?;

        let verifiable_event = VerifiableEvent {
            event: vcp,
            seal: AttachedSourceSeal { seal: source_seal },
        };

        tel.processor.process(verifiable_event)?;
        self.registry_id = Some(id.clone());

        Ok((id, encoded))
    }

    /// Generate `iss` event and `ixn` event with  seal to `iss`. To finalize
    /// the process, `ixn` need to be signed confirmed with `finalize_event`
    /// function.
    pub fn issue(
        &self,
        credential_digest: SelfAddressingIdentifier,
    ) -> Result<(IdentifierPrefix, Vec<u8>), ControllerError> {
        match self.registry_id.as_ref() {
            Some(registry_id) => {
                let tel = self.source.tel.clone();
                let iss = tel.make_issuance_event(registry_id, credential_digest)?;

                let vc_hash = iss.get_prefix();
                let seal = Seal::Event(EventSeal {
                    prefix: iss.get_prefix(),
                    sn: iss.get_sn(),
                    event_digest: iss.get_digest()?,
                });
                let ixn = self.anchor_with_seal(&[seal])?;

                let source_seal = EventSourceSeal {
                    sn: ixn.data.sn,
                    digest: ixn.digest()?,
                };
                let encoded_ixn = ixn.encode()?;

                let verifiable_event = VerifiableEvent {
                    event: iss,
                    seal: AttachedSourceSeal { seal: source_seal },
                };
                tel.processor.process(verifiable_event)?;

                Ok((vc_hash, encoded_ixn))
            }
            None => Err(ControllerError::OtherError("Tel not incepted".into())),
        }
    }

    /// Generate `rev` event and `ixn` event with  seal to `rev`. To finalize
    /// the process, `ixn` need to be signed confirmed with `finalize_event`
    /// function.
    pub fn revoke(
        &self,
        credential_sai: &SelfAddressingIdentifier,
    ) -> Result<Vec<u8>, ControllerError> {
        match &self.registry_id {
            Some(registry_id) => {
                let tel = self.source.tel.clone();
                let rev = tel.make_revoke_event(registry_id, credential_sai)?;

                let seal = Seal::Event(EventSeal {
                    prefix: rev.get_prefix(),
                    sn: rev.get_sn(),
                    event_digest: rev.get_digest()?,
                });
                let ixn = self.anchor_with_seal(&[seal])?;

                let source_seal = EventSourceSeal {
                    sn: ixn.data.sn,
                    digest: ixn.digest()?,
                };
                let encoded_ixn = ixn.encode()?;

                let verifiable_event = VerifiableEvent {
                    event: rev,
                    seal: AttachedSourceSeal { seal: source_seal },
                };
                tel.processor.process(verifiable_event)?;

                Ok(encoded_ixn)
            }
            None => Err(ControllerError::OtherError("Tel not incepted".into())),
        }
    }

    pub fn query_tel(
        &self,
        registry_id: IdentifierPrefix,
        vc_identifier: IdentifierPrefix,
    ) -> Result<TelQueryEvent, ControllerError> {
        let route = TelQueryRoute::Tels {
            reply_route: "".into(),
            args: TelQueryArgs {
                i: Some(vc_identifier),
                ri: Some(registry_id),
            },
        };
        let env = Timestamped::new(route);
        Ok(KeriEvent::new(
            SerializationFormats::JSON,
            HashFunctionCode::Blake3_256.into(),
            env,
        )?)
    }

    pub async fn notify_backers(&self) -> Result<(), ControllerError> {
        let to_notify = self.source.tel.recently_added_events.get();
        let backers = self.source.get_current_witness_list(&self.id)?;
        for backer in backers {
            let location = self
                .source
                .get_loc_schemas(&IdentifierPrefix::Basic(backer))?[0]
                .clone();
            for event in &to_notify {
                self.source
                    .tel_transport
                    .send_tel_event(event.clone(), location.clone())
                    .await
                    .map_err(|e| ControllerError::OtherError(e.to_string()))?;
            }
        }
        Ok(())
    }
}