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
use crate::prelude::*;
use arbitrary::{Arbitrary, Unstructured};
use contrafact::*;
use holo_hash::*;

/// A rough check that a sequence of Actions constitutes a valid source chain
/// - First action must be Dna
/// - Each subsequent action's prev_action hash must match the previous action
/// - The seq number must be increasing by 1, from 0
///
/// Notably, this does NOT check the following:
/// xxx Genesis actions in the proper place
/// xxx Genesis actions in the *wrong* place
///
/// TODO: It would be more readable/composable to break this into several parts:
/// - constrain action types based on position
/// - constrain seq num
/// - constrain prev_hashes
/// ...but, this does it all in one Fact
#[derive(Default)]
struct ValidChainFact {
    hash: Option<ActionHash>,
    seq: u32,
}

impl Fact<Action> for ValidChainFact {
    fn check(&self, action: &Action) -> Check {
        let action_hash = ActionHash::with_data_sync(action);
        let result = match (action.prev_action(), self.hash.as_ref()) {
            (Some(prev), Some(stored)) => {
                if prev == stored {
                    Check::pass()
                } else {
                    vec![format!("Hashes don't match: {} != {}", prev, stored)].into()
                }
            }
            (None, None) => Check::pass(),
            (None, Some(_)) => vec![format!(
                "Found Dna in position other than beginning of the chain. Hash: {}",
                action_hash
            )]
            .into(),
            (Some(_), None) => vec![format!(
                "First action must be of type Dna, but instead got type {:?}",
                action.action_type()
            )]
            .into(),
        };

        result
    }

    fn mutate(&self, action: &mut Action, u: &mut Unstructured<'static>) {
        if let Some(stored_hash) = self.hash.as_ref() {
            // This is not the first action we've seen
            while action.prev_action().is_none() {
                // Generate arbitrary actions until we get one with a prev action
                *action = Action::arbitrary(u).unwrap();
            }
            // Set the action's prev hash to the one we stored from our previous
            // visit
            *action.prev_action_mut().unwrap() = stored_hash.clone();
            // Also set the seq to the next value (this should only be None
            // iff prev_action is None)
            *action.action_seq_mut().unwrap() = self.seq;
        } else {
            // This is the first action we've seen, so it must be a Dna
            *action = Action::Dna(Dna::arbitrary(u).unwrap());
        }

        // println!(
        //     "{}  =>  {:?}\n",
        //     ActionHash::with_data_sync(action),
        //     action.prev_action()
        // );
    }

    fn advance(&mut self, action: &Action) {
        self.hash = Some(ActionHash::with_data_sync(action));
        self.seq += 1;
    }
}

pub fn is_of_type(action_type: ActionType) -> Facts<'static, Action> {
    facts![brute("action is of type", move |h: &Action| h
        .action_type()
        == action_type)]
}

pub fn is_new_entry_action() -> Facts<'static, Action> {
    facts![or(
        "is NewEntryAction",
        is_of_type(ActionType::Create),
        is_of_type(ActionType::Update)
    )]
}

/// WIP: Fact: The actions form a valid SourceChain
pub fn valid_chain() -> Facts<'static, Action> {
    facts![ValidChainFact::default(),]
}

/// Fact: The action must be a NewEntryAction
pub fn new_entry_action() -> Facts<'static, Action> {
    facts![brute("Is a NewEntryAction", |h: &Action| {
        matches!(h.action_type(), ActionType::Create | ActionType::Update)
    }),]
}

#[cfg(test)]
mod tests {

    use super::*;

    #[test]
    fn test_valid_chain_fact() {
        let mut u = Unstructured::new(&crate::NOISE);

        let chain = build_seq(&mut u, 5, valid_chain());
        check_seq(chain.as_slice(), valid_chain()).unwrap();

        let hashes: Vec<_> = chain
            .iter()
            .map(|h| ActionHash::with_data_sync(h))
            .collect();
        let backlinks: Vec<_> = chain
            .iter()
            .filter_map(|h| h.prev_action())
            .cloned()
            .collect();
        let action_seqs: Vec<_> = chain.iter().map(|h| h.action_seq()).collect();

        // Ensure that the backlinks line up with the actual hashes
        assert_eq!(hashes[0..chain.len() - 1], backlinks[..]);
        // Ensure that the action seqs form a sequence
        assert_eq!(action_seqs, vec![0, 1, 2, 3, 4]);
    }
}

pub trait ActionRefMut {
    fn author_mut(&mut self) -> &mut AgentPubKey;
    fn action_seq_mut(&mut self) -> Option<&mut u32>;
    fn prev_action_mut(&mut self) -> Option<&mut ActionHash>;
    fn entry_data_mut(&mut self) -> Option<(&mut EntryHash, &mut EntryType)>;
    fn timestamp_mut(&mut self) -> &mut Timestamp;
}

/// Some necessary extra mutators for lenses/prisms over Actions
impl ActionRefMut for Action {
    /// returns a mutable reference to the author
    fn author_mut(&mut self) -> &mut AgentPubKey {
        match *self {
            Self::Dna(Dna { ref mut author, .. })
            | Self::AgentValidationPkg(AgentValidationPkg { ref mut author, .. })
            | Self::InitZomesComplete(InitZomesComplete { ref mut author, .. })
            | Self::CreateLink(CreateLink { ref mut author, .. })
            | Self::DeleteLink(DeleteLink { ref mut author, .. })
            | Self::Delete(Delete { ref mut author, .. })
            | Self::CloseChain(CloseChain { ref mut author, .. })
            | Self::OpenChain(OpenChain { ref mut author, .. })
            | Self::Create(Create { ref mut author, .. })
            | Self::Update(Update { ref mut author, .. }) => author,
        }
    }

    /// returns a mutable reference to the timestamp
    fn timestamp_mut(&mut self) -> &mut Timestamp {
        match *self {
            Self::Dna(Dna {
                ref mut timestamp, ..
            })
            | Self::AgentValidationPkg(AgentValidationPkg {
                ref mut timestamp, ..
            })
            | Self::InitZomesComplete(InitZomesComplete {
                ref mut timestamp, ..
            })
            | Self::CreateLink(CreateLink {
                ref mut timestamp, ..
            })
            | Self::DeleteLink(DeleteLink {
                ref mut timestamp, ..
            })
            | Self::Delete(Delete {
                ref mut timestamp, ..
            })
            | Self::CloseChain(CloseChain {
                ref mut timestamp, ..
            })
            | Self::OpenChain(OpenChain {
                ref mut timestamp, ..
            })
            | Self::Create(Create {
                ref mut timestamp, ..
            })
            | Self::Update(Update {
                ref mut timestamp, ..
            }) => timestamp,
        }
    }

    /// returns a mutable reference to the sequence ordinal of this action
    fn action_seq_mut(&mut self) -> Option<&mut u32> {
        match *self {
            // Dna is always 0
            Self::Dna(Dna { .. }) => None,
            Self::AgentValidationPkg(AgentValidationPkg {
                ref mut action_seq, ..
            })
            | Self::InitZomesComplete(InitZomesComplete {
                ref mut action_seq, ..
            })
            | Self::CreateLink(CreateLink {
                ref mut action_seq, ..
            })
            | Self::DeleteLink(DeleteLink {
                ref mut action_seq, ..
            })
            | Self::Delete(Delete {
                ref mut action_seq, ..
            })
            | Self::CloseChain(CloseChain {
                ref mut action_seq, ..
            })
            | Self::OpenChain(OpenChain {
                ref mut action_seq, ..
            })
            | Self::Create(Create {
                ref mut action_seq, ..
            })
            | Self::Update(Update {
                ref mut action_seq, ..
            }) => Some(action_seq),
        }
    }

    /// returns the previous action except for the DNA action which doesn't have a previous
    fn prev_action_mut(&mut self) -> Option<&mut ActionHash> {
        match self {
            Self::Dna(Dna { .. }) => None,
            Self::AgentValidationPkg(AgentValidationPkg {
                ref mut prev_action,
                ..
            }) => Some(prev_action),
            Self::InitZomesComplete(InitZomesComplete {
                ref mut prev_action,
                ..
            }) => Some(prev_action),
            Self::CreateLink(CreateLink {
                ref mut prev_action,
                ..
            }) => Some(prev_action),
            Self::DeleteLink(DeleteLink {
                ref mut prev_action,
                ..
            }) => Some(prev_action),
            Self::Delete(Delete {
                ref mut prev_action,
                ..
            }) => Some(prev_action),
            Self::CloseChain(CloseChain {
                ref mut prev_action,
                ..
            }) => Some(prev_action),
            Self::OpenChain(OpenChain {
                ref mut prev_action,
                ..
            }) => Some(prev_action),
            Self::Create(Create {
                ref mut prev_action,
                ..
            }) => Some(prev_action),
            Self::Update(Update {
                ref mut prev_action,
                ..
            }) => Some(prev_action),
        }
    }

    fn entry_data_mut(&mut self) -> Option<(&mut EntryHash, &mut EntryType)> {
        match self {
            Self::Create(Create {
                ref mut entry_hash,
                ref mut entry_type,
                ..
            }) => Some((entry_hash, entry_type)),
            Self::Update(Update {
                ref mut entry_hash,
                ref mut entry_type,
                ..
            }) => Some((entry_hash, entry_type)),
            _ => None,
        }
    }
}