ave-core 0.8.0

Averiun Ledger core runtime and node API
Documentation
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
//! # Event data model.
//!

use super::network::TimeOut;

use crate::{
    evaluation::response::{EvaluatorError, EvaluatorResponse},
    subject::Metadata,
    validation::request::ActualProtocols,
};

use ave_actors::ActorError;
use ave_common::{
    bridge::request::EventRequestType,
    identity::{DigestIdentifier, Signature, Signed, TimeStamp},
    request::EventRequest,
    response::{EvalResDB, LedgerDB, RequestEventDB},
};

use borsh::{BorshDeserialize, BorshSerialize};
use serde::{Deserialize, Serialize};
use thiserror::Error;

#[derive(Debug, Error, Clone)]
pub enum ProtocolsError {
    #[error(
        "invalid evaluation: evaluation result does not match expected state"
    )]
    InvalidEvaluation,

    #[error("invalid evaluation: approval required but not provided")]
    ApprovalRequired,

    #[error("invalid actual protocols: expected {expected}, got {got}")]
    InvalidActualProtocols {
        expected: &'static str,
        got: &'static str,
    },

    #[error(
        "invalid event request type: {request_type} is not supported for is_gov={is_gov}"
    )]
    InvalidEventRequestType {
        request_type: &'static str,
        is_gov: bool,
    },

    #[error(
        "expected create event with metadata, got different protocol or validation metadata"
    )]
    NotCreateWithMetadata,
}

impl From<ProtocolsError> for ActorError {
    fn from(error: ProtocolsError) -> Self {
        Self::Functional {
            description: error.to_string(),
        }
    }
}

#[derive(
    Clone, Debug, Serialize, Deserialize, BorshDeserialize, BorshSerialize,
)]
pub enum EvaluationResponse {
    Ok(EvaluatorResponse),
    Error(EvaluatorError),
}

#[derive(
    Clone, Debug, Serialize, Deserialize, BorshDeserialize, BorshSerialize,
)]
pub struct EvaluationData {
    pub eval_req_signature: Signature,
    pub eval_req_hash: DigestIdentifier,
    pub evaluators_signatures: Vec<Signature>,
    pub response: EvaluationResponse,
}

impl EvaluationData {
    pub fn evaluator_res(&self) -> Option<EvaluatorResponse> {
        match &self.response {
            EvaluationResponse::Ok(evaluator_response) => {
                Some(evaluator_response.clone())
            }
            _ => None,
        }
    }
}

#[derive(
    Clone, Debug, Serialize, Deserialize, BorshDeserialize, BorshSerialize,
)]
pub struct ApprovalData {
    pub approval_req_signature: Signature,
    pub approval_req_hash: DigestIdentifier,
    pub approvers_agrees_signatures: Vec<Signature>,
    pub approvers_disagrees_signatures: Vec<Signature>,
    pub approvers_timeout: Vec<TimeOut>,
    pub approved: bool,
}

#[derive(
    Debug, Clone, Serialize, Deserialize, BorshSerialize, BorshDeserialize,
)]
pub struct ValidationData {
    pub validation_req_signature: Signature,
    pub validation_req_hash: DigestIdentifier,
    pub validators_signatures: Vec<Signature>,
    pub validation_metadata: ValidationMetadata,
}

#[derive(
    Debug,
    Clone,
    Serialize,
    Deserialize,
    BorshSerialize,
    BorshDeserialize,
    Eq,
    PartialEq,
    Hash,
)]
pub enum ValidationMetadata {
    ModifiedHash(DigestIdentifier),
    Metadata(Box<Metadata>),
}

#[derive(
    Debug, Clone, Serialize, Deserialize, BorshSerialize, BorshDeserialize,
)]
pub enum Protocols {
    Create {
        validation: ValidationData,
    },
    TrackerFact {
        evaluation: EvaluationData,
        validation: ValidationData,
    },
    GovFact {
        evaluation: EvaluationData,
        approval: Option<ApprovalData>,
        validation: ValidationData,
    },
    Transfer {
        evaluation: EvaluationData,
        validation: ValidationData,
    },
    TrackerConfirm {
        validation: ValidationData,
    },
    GovConfirm {
        evaluation: EvaluationData,
        validation: ValidationData,
    },
    Reject {
        validation: ValidationData,
    },
    EOL {
        validation: ValidationData,
    },
}

impl Protocols {
    pub fn buidl_event_db(
        &self,
        event_request: &EventRequest,
    ) -> (RequestEventDB, DigestIdentifier) {
        match (self, event_request) {
            (Self::Create { validation }, EventRequest::Create(create)) => {
                let ValidationMetadata::Metadata(metadata) =
                    &validation.validation_metadata
                else {
                    unreachable!(
                        "Unreachable combination is a create event request"
                    )
                };

                (
                    RequestEventDB::Create {
                        name: create.name.clone(),
                        description: create.description.clone(),
                        schema_id: create.schema_id.to_string(),
                        namespace: create.namespace.to_string(),
                    },
                    metadata.subject_id.clone(),
                )
            }
            (
                Self::TrackerFact { evaluation, .. },
                EventRequest::Fact(fact_request),
            ) => {
                let evaluation_response = match evaluation.response.clone() {
                    EvaluationResponse::Ok(eval_res) => {
                        EvalResDB::Patch(eval_res.patch.0)
                    }
                    EvaluationResponse::Error(e) => {
                        EvalResDB::Error(e.to_string())
                    }
                };

                (
                    RequestEventDB::TrackerFact {
                        payload: fact_request.payload.0.clone(),
                        evaluation_response,
                    },
                    event_request.get_subject_id(),
                )
            }
            (
                Self::GovFact {
                    evaluation,
                    approval,
                    ..
                },
                EventRequest::Fact(fact_request),
            ) => {
                let (evaluation_response, approval_success) = match evaluation
                    .response
                    .clone()
                {
                    EvaluationResponse::Ok(eval_res) => {
                        if let Some(appr) = approval {
                            (
                                EvalResDB::Patch(eval_res.patch.0),
                                Some(appr.approved),
                            )
                        } else {
                            unreachable!(
                                "In a factual governance event, if the assessment is correct, there should be approval"
                            )
                        }
                    }
                    EvaluationResponse::Error(e) => {
                        (EvalResDB::Error(e.to_string()), None)
                    }
                };
                (
                    RequestEventDB::GovernanceFact {
                        payload: fact_request.payload.0.clone(),
                        evaluation_response,
                        approval_success,
                    },
                    event_request.get_subject_id(),
                )
            }
            (
                Self::Transfer { evaluation, .. },
                EventRequest::Transfer(transfer_request),
            ) => {
                let evaluation_error = match evaluation.response.clone() {
                    EvaluationResponse::Ok(_) => None,
                    EvaluationResponse::Error(e) => Some(e.to_string()),
                };
                (
                    RequestEventDB::Transfer {
                        new_owner: transfer_request.new_owner.to_string(),
                        evaluation_error,
                    },
                    event_request.get_subject_id(),
                )
            }
            (Self::TrackerConfirm { .. }, EventRequest::Confirm(..)) => (
                RequestEventDB::TrackerConfirm,
                event_request.get_subject_id(),
            ),
            (
                Self::GovConfirm { evaluation, .. },
                EventRequest::Confirm(confirm_request),
            ) => {
                let evaluation_response = match evaluation.response.clone() {
                    EvaluationResponse::Ok(eval_res) => {
                        EvalResDB::Patch(eval_res.patch.0)
                    }
                    EvaluationResponse::Error(e) => {
                        EvalResDB::Error(e.to_string())
                    }
                };
                (
                    RequestEventDB::GovernanceConfirm {
                        name_old_owner: confirm_request.name_old_owner.clone(),
                        evaluation_response,
                    },
                    event_request.get_subject_id(),
                )
            }
            (Self::Reject { .. }, EventRequest::Reject(..)) => {
                (RequestEventDB::Reject, event_request.get_subject_id())
            }
            (Self::EOL { .. }, EventRequest::EOL(..)) => {
                (RequestEventDB::EOL, event_request.get_subject_id())
            }
            _ => unreachable!(
                "Unreachable combination of protocol and event request"
            ),
        }
    }

    pub fn get_validation_data(&self) -> ValidationData {
        match self {
            Self::Create { validation }
            | Self::TrackerFact { validation, .. }
            | Self::GovFact { validation, .. }
            | Self::Transfer { validation, .. }
            | Self::TrackerConfirm { validation }
            | Self::GovConfirm { validation, .. }
            | Self::Reject { validation }
            | Self::EOL { validation } => validation.clone(),
        }
    }

    pub fn is_success(&self) -> bool {
        match self {
            Self::Create { .. } => true,
            Self::TrackerFact { evaluation, .. } => {
                evaluation.evaluator_res().is_some()
            }
            Self::GovFact { approval, .. } => {
                approval.as_ref().is_some_and(|approval| approval.approved)
            }
            Self::Transfer { evaluation, .. } => {
                evaluation.evaluator_res().is_some()
            }
            Self::TrackerConfirm { .. } => true,
            Self::GovConfirm { evaluation, .. } => {
                evaluation.evaluator_res().is_some()
            }
            Self::Reject { .. } => true,
            Self::EOL { .. } => true,
        }
    }

    pub fn build(
        is_gov: bool,
        event_request: EventRequestType,
        actual_protocols: ActualProtocols,
        validation: ValidationData,
    ) -> Result<Self, ProtocolsError> {
        match (event_request, is_gov) {
            (EventRequestType::Fact, true) => {
                let (evaluation, approval) = match actual_protocols {
                    ActualProtocols::Eval { eval_data } => {
                        if eval_data.evaluator_res().is_some() {
                            return Err(ProtocolsError::InvalidEvaluation);
                        } else {
                            (eval_data, None)
                        }
                    }
                    ActualProtocols::EvalApprove {
                        eval_data,
                        approval_data,
                    } => {
                        if let Some(eval_res) = eval_data.evaluator_res() {
                            if !eval_res.appr_required {
                                return Err(ProtocolsError::ApprovalRequired);
                            }
                        } else {
                            return Err(ProtocolsError::InvalidEvaluation);
                        };

                        (eval_data, Some(approval_data))
                    }
                    ActualProtocols::None => {
                        return Err(ProtocolsError::InvalidActualProtocols {
                            expected: "Eval or EvalApprove",
                            got: "None",
                        });
                    }
                };

                Ok(Self::GovFact {
                    evaluation,
                    approval,
                    validation,
                })
            }
            (EventRequestType::Fact, false) => {
                let evaluation = match actual_protocols {
                    ActualProtocols::Eval { eval_data } => eval_data,
                    ActualProtocols::None => {
                        return Err(ProtocolsError::InvalidActualProtocols {
                            expected: "Eval",
                            got: "None",
                        });
                    }
                    ActualProtocols::EvalApprove { .. } => {
                        return Err(ProtocolsError::InvalidActualProtocols {
                            expected: "Eval",
                            got: "EvalApprove",
                        });
                    }
                };

                Ok(Self::TrackerFact {
                    evaluation,
                    validation,
                })
            }
            (EventRequestType::Transfer, true)
            | (EventRequestType::Transfer, false) => {
                let evaluation = match actual_protocols {
                    ActualProtocols::Eval { eval_data } => eval_data,
                    ActualProtocols::None => {
                        return Err(ProtocolsError::InvalidActualProtocols {
                            expected: "Eval",
                            got: "None",
                        });
                    }
                    ActualProtocols::EvalApprove { .. } => {
                        return Err(ProtocolsError::InvalidActualProtocols {
                            expected: "Eval",
                            got: "EvalApprove",
                        });
                    }
                };

                Ok(Self::Transfer {
                    evaluation,
                    validation,
                })
            }
            (EventRequestType::Confirm, true) => {
                let evaluation = match actual_protocols {
                    ActualProtocols::Eval { eval_data } => eval_data,
                    ActualProtocols::None => {
                        return Err(ProtocolsError::InvalidActualProtocols {
                            expected: "Eval",
                            got: "None",
                        });
                    }
                    ActualProtocols::EvalApprove { .. } => {
                        return Err(ProtocolsError::InvalidActualProtocols {
                            expected: "Eval",
                            got: "EvalApprove",
                        });
                    }
                };
                Ok(Self::GovConfirm {
                    evaluation,
                    validation,
                })
            }
            (EventRequestType::Confirm, false) => {
                match actual_protocols {
                    ActualProtocols::Eval { .. } => {
                        return Err(ProtocolsError::InvalidActualProtocols {
                            expected: "None",
                            got: "Eval",
                        });
                    }
                    ActualProtocols::EvalApprove { .. } => {
                        return Err(ProtocolsError::InvalidActualProtocols {
                            expected: "None",
                            got: "EvalApprove",
                        });
                    }
                    ActualProtocols::None => {}
                }
                Ok(Self::TrackerConfirm { validation })
            }
            (EventRequestType::Reject, true)
            | (EventRequestType::Reject, false) => {
                match actual_protocols {
                    ActualProtocols::Eval { .. } => {
                        return Err(ProtocolsError::InvalidActualProtocols {
                            expected: "None",
                            got: "Eval",
                        });
                    }
                    ActualProtocols::EvalApprove { .. } => {
                        return Err(ProtocolsError::InvalidActualProtocols {
                            expected: "None",
                            got: "EvalApprove",
                        });
                    }
                    ActualProtocols::None => {}
                }
                Ok(Self::Reject { validation })
            }
            (EventRequestType::Eol, true) | (EventRequestType::Eol, false) => {
                match actual_protocols {
                    ActualProtocols::Eval { .. } => {
                        return Err(ProtocolsError::InvalidActualProtocols {
                            expected: "None",
                            got: "Eval",
                        });
                    }
                    ActualProtocols::EvalApprove { .. } => {
                        return Err(ProtocolsError::InvalidActualProtocols {
                            expected: "None",
                            got: "EvalApprove",
                        });
                    }
                    ActualProtocols::None => {}
                }
                Ok(Self::EOL { validation })
            }
            (EventRequestType::Create, _) => {
                Err(ProtocolsError::InvalidEventRequestType {
                    request_type: "Create",
                    is_gov,
                })
            }
        }
    }
}

#[derive(
    Debug, Clone, Serialize, Deserialize, BorshSerialize, BorshDeserialize,
)]
pub struct Ledger {
    pub event_request: Signed<EventRequest>,
    pub gov_version: u64,
    pub sn: u64,
    pub prev_ledger_event_hash: DigestIdentifier,
    pub protocols: Protocols,
}

impl Ledger {
    pub fn get_subject_id(&self) -> DigestIdentifier {
        if let Protocols::Create { validation } = &self.protocols
            && let ValidationMetadata::Metadata(metadata) =
                &validation.validation_metadata
        {
            metadata.subject_id.clone()
        } else {
            self.event_request.content().get_subject_id()
        }
    }

    pub fn build_ledger_db(&self, signature_timestamp: u64) -> LedgerDB {
        let (event, subject_id) =
            self.protocols.buidl_event_db(self.event_request.content());

        LedgerDB {
            subject_id: subject_id.to_string(),
            sn: self.sn,
            event_request_timestamp: self
                .event_request
                .signature()
                .timestamp
                .as_nanos(),
            event_ledger_timestamp: signature_timestamp,
            sink_timestamp: TimeStamp::now().as_nanos(),
            event_type: event.get_event_type(),
            event,
        }
    }
    pub fn get_create_metadata(&self) -> Result<Metadata, ProtocolsError> {
        if let Protocols::Create { validation } = &self.protocols
            && let ValidationMetadata::Metadata(metadata) =
                &validation.validation_metadata
        {
            Ok(*metadata.clone())
        } else {
            Err(ProtocolsError::NotCreateWithMetadata)
        }
    }
}