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
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
use std::collections::HashSet;

use super::{
    error::{APIInternalError, ApiError},
    inner_api::InnerAPI,
    APICommands, ApiResponses, GetAllowedSubjects,
};
use super::{GetEvents, GetGovernanceSubjects};
#[cfg(feature = "aproval")]
use crate::approval::manager::ApprovalAPI;
use crate::commons::models::request::TapleRequest;
use crate::commons::models::state::SubjectData;
use crate::commons::{
    channel::{ChannelData, MpscChannel, SenderEnd},
    config::TapleSettings,
};
use crate::event::manager::EventAPI;
use crate::ledger::manager::EventManagerAPI;
use crate::signature::Signature;
#[cfg(feature = "aproval")]
use crate::ApprovalEntity;
use crate::ValidationProof;
use crate::{
    authorized_subjecs::manager::AuthorizedSubjectsAPI, signature::Signed, Event, EventRequest,
};
use crate::{identifier::DigestIdentifier, DatabaseCollection, DB};
use crate::{KeyDerivator, KeyIdentifier};
use async_trait::async_trait;
use tokio::sync::watch::Sender;

/// Trait that allows implementing the interface of a TAPLE node.
/// The only native implementation is [NodeAPI]. Users can use the trait
/// to add specific behaviors to an existing node interface. For example,
/// a [NodeAPI] wrapper could be created that again implements the trait
/// and perform certain intermediate operations, such as incrementing a counter
/// to find out how many API queries have been made.
#[async_trait]
pub trait ApiModuleInterface {
    /// Allows to make a request to the node from an external Invoker
    async fn external_request(
        &self,
        event_request: Signed<EventRequest>,
    ) -> Result<DigestIdentifier, ApiError>;
    /// Allows to get all subjects that are known to the current node, regardless of their governance.
    /// Paging can be performed using the optional arguments `from` and `quantity`.
    /// Regarding the first one, note that it admits negative values, in which case the paging is
    /// performed in the opposite direction starting from the end of the collection. Note that this method
    /// also returns the subjects that model governance.
    /// # Possible errors
    /// • [ApiError::InternalError] if an internal error occurred during the execution of the operation.
    async fn get_subjects(
        &self,
        namespace: String,
        from: Option<String>,
        quantity: Option<i64>,
    ) -> Result<Vec<SubjectData>, ApiError>;
    /// It allows to obtain all the subjects that model existing governance in the node.
    /// # Possible errors
    /// • [ApiError::InternalError] if an internal error occurred during the execution of the operation.
    async fn get_governances(
        &self,
        namespace: String,
        from: Option<String>,
        quantity: Option<i64>,
    ) -> Result<Vec<SubjectData>, ApiError>;
    async fn get_subjects_by_governance(
        &self,
        governance_id: DigestIdentifier,
        from: Option<String>,
        quantity: Option<i64>,
    ) -> Result<Vec<SubjectData>, ApiError>;
    /// Allows to obtain events from a specific subject previously existing in the node.
    /// Paging can be performed by means of the optional arguments `from` and `quantity`.
    /// Regarding the former, it should be noted that negative values are allowed, in which case
    /// the paging is performed in the opposite direction starting from the end of the string.
    /// # Possible errors
    /// • [ApiError::InvalidParameters] if the specified subject identifier does not match a valid [DigestIdentifier].
    async fn get_events(
        &self,
        subject_id: DigestIdentifier,
        from: Option<i64>,
        quantity: Option<i64>,
    ) -> Result<Vec<Signed<Event>>, ApiError>;

    async fn get_event(
        &self,
        subject_id: DigestIdentifier,
        sn: u64,
    ) -> Result<Signed<Event>, ApiError>;
    /// Allows to obtain a specified subject by specifying its identifier.
    /// # Possible errors
    /// • [ApiError::InvalidParameters] if the specified identifier does not match a valid [DigestIdentifier].<br />
    /// • [ApiError::NotFound] if the subject does not exist.
    async fn get_subject(&self, subject_id: DigestIdentifier) -> Result<SubjectData, ApiError>;
    /// Stops the node, consuming the instance on the fly. This implies that any previously created API
    /// or [NotificationHandler] instances will no longer be functional.
    async fn shutdown(self) -> Result<(), ApiError>;
    /// Allows to vote on a voting request that previously exists in the system.
    /// This vote will be sent to the corresponding node in charge of its collection.
    /// # Possible errors
    /// • [ApiError::InternalError] if an internal error occurs during operation execution.<br />
    /// • [ApiError::NotFound] if the request does not exist in the system.<br />
    /// • [ApiError::InvalidParameters] if the specified request identifier does not match a valid [DigestIdentifier].<br />
    /// • [ApiError::VoteNotNeeded] if the node's vote is no longer required. <br />
    /// This occurs when the acceptance of the changes proposed by the petition has already been resolved by the rest of the nodes in the network or when the node cannot participate in the voting process because it lacks the voting role.
    #[cfg(feature = "aproval")]
    async fn approval_request(
        &self,
        request_id: DigestIdentifier,
        acceptance: bool,
    ) -> Result<ApprovalEntity, ApiError>;
    /// It allows to obtain all the voting requests pending to be resolved in the node.
    /// These requests are received from other nodes in the network when they try to update
    /// a governance subject. It is necessary to vote their agreement or disagreement with
    /// the proposed changes in order for the events to be implemented.
    /// # Possible errors
    /// • [ApiError::InternalError] if an internal error occurs during operation execution.
    #[cfg(feature = "aproval")]
    async fn get_pending_requests(&self) -> Result<Vec<ApprovalEntity>, ApiError>;
    /// It allows to obtain a single voting request pending to be resolved in the node.
    /// This request is received from other nodes in the network when they try to update
    /// a governance subject. It is necessary to vote its agreement or disagreement with
    /// the proposed changes in order for the events to be implemented.
    /// # Possible errors
    /// • [ApiError::InternalError] if an internal error occurs during operation execution.
    /// • [ApiError::NotFound] if the requested request does not exist.
    #[cfg(feature = "aproval")]
    async fn get_single_request(&self, id: DigestIdentifier) -> Result<ApprovalEntity, ApiError>;
    async fn add_preauthorize_subject(
        &self,
        subject_id: &DigestIdentifier,
        providers: &HashSet<KeyIdentifier>,
    ) -> Result<(), ApiError>;
    async fn get_all_allowed_subjects_and_providers(
        &self,
        from: Option<String>,
        quantity: Option<i64>,
    ) -> Result<Vec<(DigestIdentifier, HashSet<KeyIdentifier>)>, ApiError>;
    async fn add_keys(&self, derivator: KeyDerivator) -> Result<KeyIdentifier, ApiError>;
    async fn get_validation_proof(
        &self,
        subject_id: DigestIdentifier,
    ) -> Result<(HashSet<Signature>, ValidationProof), ApiError>;
    async fn get_request(&self, request_id: DigestIdentifier) -> Result<TapleRequest, ApiError>;
    async fn get_governance_subjects(
        &self,
        governance_id: DigestIdentifier,
        from: Option<String>,
        quantity: Option<i64>,
    ) -> Result<Vec<SubjectData>, ApiError>;
    #[cfg(feature = "aproval")]
    async fn get_approval(&self, request_id: DigestIdentifier) -> Result<ApprovalEntity, ApiError>;
    #[cfg(feature = "aproval")]
    async fn get_approvals(
        &self,
        state: Option<crate::ApprovalState>,
        from: Option<String>,
        quantity: Option<i64>,
    ) -> Result<Vec<ApprovalEntity>, ApiError>;
}

/// Object that allows interaction with a TAPLE node.
///
/// It has methods to perform all available read and write operations,
/// as well as an additional action to stop a running node.
/// he interaction is performed thanks to the implementation of a trait
/// known as [ApiModuleInterface]. Consequently, it is necessary to import
/// the trait in order to properly use the object.
#[derive(Clone, Debug)]
pub struct NodeAPI {
    pub(crate) sender: SenderEnd<APICommands, ApiResponses>,
}

/// Feature that allows implementing the API Rest of an Taple node.
#[async_trait]
impl ApiModuleInterface for NodeAPI {
    async fn get_request(&self, request_id: DigestIdentifier) -> Result<TapleRequest, ApiError> {
        let response = self
            .sender
            .ask(APICommands::GetRequest(request_id))
            .await
            .unwrap();
        if let ApiResponses::GetRequest(data) = response {
            data
        } else {
            unreachable!()
        }
    }

    async fn external_request(
        &self,
        event_request: Signed<EventRequest>,
    ) -> Result<DigestIdentifier, ApiError> {
        let response = self
            .sender
            .ask(APICommands::ExternalRequest(event_request))
            .await
            .unwrap();
        if let ApiResponses::HandleExternalRequest(data) = response {
            data
        } else {
            unreachable!()
        }
    }

    #[cfg(feature = "aproval")]
    async fn get_pending_requests(&self) -> Result<Vec<ApprovalEntity>, ApiError> {
        let response = self
            .sender
            .ask(APICommands::GetPendingRequests)
            .await
            .unwrap();
        if let ApiResponses::GetPendingRequests(data) = response {
            data
        } else {
            unreachable!()
        }
    }

    #[cfg(feature = "aproval")]
    async fn get_single_request(&self, id: DigestIdentifier) -> Result<ApprovalEntity, ApiError> {
        let response = self
            .sender
            .ask(APICommands::GetSingleRequest(id))
            .await
            .unwrap();
        if let ApiResponses::GetSingleRequest(data) = response {
            data
        } else {
            unreachable!()
        }
    }

    async fn get_subjects(
        &self,
        namespace: String,
        from: Option<String>,
        quantity: Option<i64>,
    ) -> Result<Vec<SubjectData>, ApiError> {
        let response = self
            .sender
            .ask(APICommands::GetSubjects(super::GetSubjects {
                namespace,
                from,
                quantity,
            }))
            .await
            .unwrap();
        if let ApiResponses::GetSubjects(data) = response {
            data
        } else {
            unreachable!()
        }
    }

    async fn get_subjects_by_governance(
        &self,
        governance_id: DigestIdentifier,
        from: Option<String>,
        quantity: Option<i64>,
    ) -> Result<Vec<SubjectData>, ApiError> {
        let response = self
            .sender
            .ask(APICommands::GetSubjectByGovernance(
                super::GetSubjects {
                    namespace: "".into(),
                    from,
                    quantity,
                },
                governance_id,
            ))
            .await
            .unwrap();
        if let ApiResponses::GetSubjectByGovernance(data) = response {
            data
        } else {
            unreachable!()
        }
    }

    async fn get_governances(
        &self,
        namespace: String,
        from: Option<String>,
        quantity: Option<i64>,
    ) -> Result<Vec<SubjectData>, ApiError> {
        let response = self
            .sender
            .ask(APICommands::GetGovernances(super::GetSubjects {
                namespace,
                from,
                quantity,
            }))
            .await
            .unwrap();
        if let ApiResponses::GetGovernances(data) = response {
            data
        } else {
            unreachable!()
        }
    }

    async fn get_event(
        &self,
        subject_id: DigestIdentifier,
        sn: u64,
    ) -> Result<Signed<Event>, ApiError> {
        let response = self
            .sender
            .ask(APICommands::GetEvent(subject_id, sn))
            .await
            .unwrap();
        if let ApiResponses::GetEvent(data) = response {
            data
        } else {
            unreachable!()
        }
    }

    async fn get_events(
        &self,
        subject_id: DigestIdentifier,
        from: Option<i64>,
        quantity: Option<i64>,
    ) -> Result<Vec<Signed<Event>>, ApiError> {
        let response = self
            .sender
            .ask(APICommands::GetEvents(GetEvents {
                subject_id,
                from,
                quantity,
            }))
            .await
            .unwrap();
        if let ApiResponses::GetEvents(data) = response {
            data
        } else {
            unreachable!()
        }
    }

    async fn get_subject(&self, subject_id: DigestIdentifier) -> Result<SubjectData, ApiError> {
        let response = self
            .sender
            .ask(APICommands::GetSubject(super::GetSubject { subject_id }))
            .await
            .unwrap();
        if let ApiResponses::GetSubject(data) = response {
            data
        } else {
            unreachable!()
        }
    }

    #[cfg(feature = "aproval")]
    async fn approval_request(
        &self,
        request_id: DigestIdentifier,
        acceptance: bool,
    ) -> Result<ApprovalEntity, ApiError> {
        let response = self
            .sender
            .ask(APICommands::VoteResolve(acceptance, request_id))
            .await
            .unwrap();
        if let ApiResponses::VoteResolve(data) = response {
            data
        } else {
            unreachable!()
        }
    }

    async fn shutdown(self) -> Result<(), ApiError> {
        let response = self.sender.ask(APICommands::Shutdown).await.unwrap();
        if let ApiResponses::ShutdownCompleted = response {
            Ok(())
        } else {
            unreachable!()
        }
    }

    async fn add_preauthorize_subject(
        &self,
        subject_id: &DigestIdentifier,
        providers: &HashSet<KeyIdentifier>,
    ) -> Result<(), ApiError> {
        let response = self
            .sender
            .ask(APICommands::SetPreauthorizedSubject(
                subject_id.clone(),
                providers.clone(),
            ))
            .await
            .unwrap();
        if let ApiResponses::SetPreauthorizedSubjectCompleted = response {
            Ok(())
        } else {
            unreachable!()
        }
    }

    async fn get_all_allowed_subjects_and_providers(
        &self,
        from: Option<String>,
        quantity: Option<i64>,
    ) -> Result<Vec<(DigestIdentifier, HashSet<KeyIdentifier>)>, ApiError> {
        let response = self
            .sender
            .ask(APICommands::GetAllPreauthorizedSubjects(
                GetAllowedSubjects { from, quantity },
            ))
            .await
            .unwrap();
        if let ApiResponses::GetAllPreauthorizedSubjects(data) = response {
            data
        } else {
            unreachable!()
        }
    }

    async fn add_keys(&self, derivator: KeyDerivator) -> Result<KeyIdentifier, ApiError> {
        let response = self
            .sender
            .ask(APICommands::AddKeys(derivator))
            .await
            .unwrap();
        if let ApiResponses::AddKeys(data) = response {
            data
        } else {
            unreachable!()
        }
    }

    async fn get_validation_proof(
        &self,
        subject_id: DigestIdentifier,
    ) -> Result<(HashSet<Signature>, ValidationProof), ApiError> {
        let response = self
            .sender
            .ask(APICommands::GetValidationProof(subject_id))
            .await
            .unwrap();
        if let ApiResponses::GetValidationProof(data) = response {
            data
        } else {
            unreachable!()
        }
    }

    async fn get_governance_subjects(
        &self,
        governance_id: DigestIdentifier,
        from: Option<String>,
        quantity: Option<i64>,
    ) -> Result<Vec<SubjectData>, ApiError> {
        let response = self
            .sender
            .ask(APICommands::GetGovernanceSubjects(GetGovernanceSubjects {
                governance_id,
                from,
                quantity,
            }))
            .await
            .unwrap();
        if let ApiResponses::GetGovernanceSubjects(data) = response {
            data
        } else {
            unreachable!()
        }
    }

    #[cfg(feature = "aproval")]
    async fn get_approval(&self, request_id: DigestIdentifier) -> Result<ApprovalEntity, ApiError> {
        let response = self
            .sender
            .ask(APICommands::GetApproval(request_id))
            .await
            .unwrap();
        if let ApiResponses::GetApproval(data) = response {
            data
        } else {
            unreachable!()
        }
    }

    #[cfg(feature = "aproval")]
    async fn get_approvals(
        &self,
        state: Option<crate::ApprovalState>,
        from: Option<String>,
        quantity: Option<i64>,
    ) -> Result<Vec<ApprovalEntity>, ApiError> {
        let response = self
            .sender
            .ask(APICommands::GetApprovals(super::GetApprovals {
                state,
                from,
                quantity,
            }))
            .await
            .unwrap();
        if let ApiResponses::GetApprovals(data) = response {
            data
        } else {
            unreachable!()
        }
    }
}

pub struct API<C: DatabaseCollection> {
    input: MpscChannel<APICommands, ApiResponses>,
    _settings_sender: Sender<TapleSettings>,
    inner_api: InnerAPI<C>,
    shutdown_sender: Option<tokio::sync::broadcast::Sender<()>>,
    shutdown_receiver: tokio::sync::broadcast::Receiver<()>,
}

impl<C: DatabaseCollection> API<C> {
    pub fn new(
        input: MpscChannel<APICommands, ApiResponses>,
        event_api: EventAPI,
        #[cfg(feature = "aproval")] approval_api: ApprovalAPI,
        authorized_subjects_api: AuthorizedSubjectsAPI,
        ledger_api: EventManagerAPI,
        settings_sender: Sender<TapleSettings>,
        shutdown_sender: tokio::sync::broadcast::Sender<()>,
        shutdown_receiver: tokio::sync::broadcast::Receiver<()>,
        db: DB<C>,
    ) -> Self {
        Self {
            input,
            _settings_sender: settings_sender,
            inner_api: InnerAPI::new(
                event_api,
                authorized_subjects_api,
                db,
                #[cfg(feature = "aproval")]
                approval_api,
                ledger_api,
            ),
            shutdown_sender: Some(shutdown_sender),
            shutdown_receiver: shutdown_receiver,
        }
    }

    pub async fn start(mut self) {
        let mut response_channel = None;
        loop {
            tokio::select! {
                msg = self.input.receive() => {
                    let must_shutdown = if msg.is_none() {
                        // Channel closed
                        true
                    } else {
                        let result = self.process_input(msg.unwrap()).await;
                        if result.is_err() {
                            true
                        } else {
                            let response = result.unwrap();
                            if response.is_some() {
                                response_channel = response;
                                true
                            } else {
                                false
                            }
                        }
                    };
                    if must_shutdown {
                        log::error!("must shutdown before unwrap");
                        let sender = self.shutdown_sender.take().unwrap();
                        sender.send(()).expect("Shutdown Channel Closed");
                        drop(sender);
                        _ = self.shutdown_receiver.recv().await;
                        if response_channel.is_some() {
                            let response_channel = response_channel.unwrap();
                            let _ = response_channel.send(ApiResponses::ShutdownCompleted);
                        }
                        break;
                    }
                },
                _ = self.shutdown_receiver.recv() => {
                    break;
                }
            }
        }
    }

    async fn process_input(
        &mut self,
        input: ChannelData<APICommands, ApiResponses>,
    ) -> Result<Option<tokio::sync::oneshot::Sender<ApiResponses>>, APIInternalError> {
        // TODO: API commands to change the configuration are missing
        match input {
            ChannelData::AskData(data) => {
                let (sx, command) = data.get();
                let response = match command {
                    APICommands::Shutdown => {
                        return Ok(Some(sx));
                    }
                    APICommands::GetSubjects(data) => self.inner_api.get_all_subjects(data),
                    APICommands::GetGovernances(data) => {
                        self.inner_api.get_all_governances(data).await
                    }
                    APICommands::GetEvents(data) => {
                        self.inner_api.get_events_of_subject(data).await
                    }
                    APICommands::GetSubject(data) => self.inner_api.get_single_subject(data).await,
                    APICommands::GetRequest(request_id) => {
                        self.inner_api.get_request(request_id).await
                    }
                    APICommands::GetEvent(subject_id, sn) => {
                        self.inner_api.get_event(subject_id, sn)
                    }
                    #[cfg(feature = "aproval")]
                    APICommands::VoteResolve(acceptance, id) => {
                        self.inner_api.emit_vote(id, acceptance).await?
                    }
                    #[cfg(feature = "aproval")]
                    APICommands::GetPendingRequests => self.inner_api.get_pending_request().await,
                    #[cfg(feature = "aproval")]
                    APICommands::GetSingleRequest(data) => {
                        self.inner_api.get_single_request(data).await
                    }
                    APICommands::ExternalRequest(event_request) => {
                        let response = self.inner_api.handle_external_request(event_request).await;
                        response?
                    }
                    APICommands::SetPreauthorizedSubject(subject_id, providers) => {
                        self.inner_api
                            .set_preauthorized_subject(subject_id, providers)
                            .await?
                    }
                    APICommands::AddKeys(derivator) => {
                        self.inner_api.generate_keys(derivator).await?
                    }
                    APICommands::GetValidationProof(subject_id) => {
                        self.inner_api.get_validation_proof(subject_id).await
                    }
                    APICommands::GetGovernanceSubjects(data) => {
                        self.inner_api.get_governance_subjects(data).await
                    }
                    #[cfg(feature = "aproval")]
                    APICommands::GetApproval(request_id) => {
                        self.inner_api.get_approval(request_id).await
                    }
                    #[cfg(feature = "aproval")]
                    APICommands::GetApprovals(get_approvals) => {
                        self.inner_api
                            .get_approvals(
                                get_approvals.state,
                                get_approvals.from,
                                get_approvals.quantity,
                            )
                            .await
                    }
                    APICommands::GetAllPreauthorizedSubjects(data) => {
                        self.inner_api
                            .get_all_preauthorized_subjects_and_providers(data)
                            .await?
                    }
                    APICommands::GetSubjectByGovernance(params, gov_id) => {
                        self.inner_api.get_subjects_by_governance(params, gov_id)
                    }
                };
                sx.send(response)
                    .map_err(|_| APIInternalError::OneshotUnavailable)?;
            }
            ChannelData::TellData(_data) => {
                panic!("Tell in API")
            }
        }
        Ok(None)
    }
}