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
use super::super::sections::{seal::*, KeyConfig, RotationWitnessConfig};
use crate::{
    error::Error,
    prefix::BasicPrefix,
    state::{EventSemantics, IdentifierState, LastEstablishmentData, WitnessConfig},
};
use said::SelfAddressingIdentifier;
use serde::{Deserialize, Serialize};

/// Rotation Event
///
/// Describes the rotation (rot) event data
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
pub struct RotationEvent {
    #[serde(rename = "p")]
    pub previous_event_hash: SelfAddressingIdentifier,

    #[serde(flatten)]
    pub key_config: KeyConfig,

    #[serde(flatten)]
    pub witness_config: RotationWitnessConfig,

    #[serde(rename = "a")]
    pub data: Vec<Seal>,
}

impl EventSemantics for RotationEvent {
    fn apply_to(&self, state: IdentifierState) -> Result<IdentifierState, Error> {
        if state.current.verify_next(&self.key_config)? {
            // witness rotation processing
            let witnesses =
                if !self.witness_config.prune.is_empty() || !self.witness_config.graft.is_empty() {
                    let mut prunned = state
                        .witness_config
                        .witnesses
                        .into_iter()
                        .filter(|e| !self.witness_config.prune.contains(e))
                        .collect::<Vec<BasicPrefix>>();
                    prunned.append(&mut self.witness_config.graft.clone());
                    prunned
                } else {
                    state.witness_config.witnesses.clone()
                };
            let witness_config = WitnessConfig {
                tally: self.witness_config.tally.clone(),
                witnesses,
            };
            let last_est = LastEstablishmentData {
                sn: state.sn,
                digest: state.last_event_digest.clone(),
                br: self.witness_config.graft.clone(),
                ba: self.witness_config.prune.clone(),
            };

            Ok(IdentifierState {
                current: self.key_config.clone(),
                witness_config,
                last_est,
                ..state
            })
        } else {
            Err(Error::SemanticError("Incorrect Key Config binding".into()))
        }
    }
}