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
use super::*;
use crate::element::*;
use crate::error::{Error, Result};
use crate::Hash;
use serde::{Deserialize, Deserializer, Serialize};
use std::default::Default;
#[inline]
fn is_false(v: &bool) -> bool {
!v
}
fn get_validator<'de, D: Deserializer<'de>>(
deserializer: D,
) -> Result<Option<Box<Validator>>, D::Error> {
Ok(Some(Box::new(Validator::deserialize(deserializer)?)))
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields, default)]
pub struct HashValidator {
#[serde(skip_serializing_if = "String::is_empty")]
pub comment: String,
#[serde(
skip_serializing_if = "Option::is_none",
deserialize_with = "get_validator"
)]
pub link: Option<Box<Validator>>,
#[serde(skip_serializing_if = "Vec::is_empty")]
pub schema: Vec<Option<Hash>>,
#[serde(rename = "in", skip_serializing_if = "Vec::is_empty")]
pub in_list: Vec<Hash>,
#[serde(rename = "nin", skip_serializing_if = "Vec::is_empty")]
pub nin_list: Vec<Hash>,
#[serde(skip_serializing_if = "is_false")]
pub query: bool,
#[serde(skip_serializing_if = "is_false")]
pub link_ok: bool,
#[serde(skip_serializing_if = "is_false")]
pub schema_ok: bool,
}
impl Default for HashValidator {
fn default() -> Self {
Self {
comment: String::new(),
link: None,
schema: Vec::new(),
in_list: Vec::new(),
nin_list: Vec::new(),
query: false,
link_ok: false,
schema_ok: false,
}
}
}
impl HashValidator {
pub fn new() -> Self {
Self::default()
}
pub fn link(mut self, link: Validator) -> Self {
self.link = Some(Box::new(link));
self
}
pub fn schema_add(mut self, add: impl Into<Hash>) -> Self {
self.schema.push(Some(add.into()));
self
}
pub fn schema_self(mut self) -> Self {
self.schema.push(None);
self
}
pub fn in_add(mut self, add: impl Into<Hash>) -> Self {
self.in_list.push(add.into());
self
}
pub fn nin_add(mut self, add: impl Into<Hash>) -> Self {
self.nin_list.push(add.into());
self
}
pub fn query(mut self, query: bool) -> Self {
self.query = query;
self
}
pub fn link_ok(mut self, link_ok: bool) -> Self {
self.link_ok = link_ok;
self
}
pub fn schema_ok(mut self, schema_ok: bool) -> Self {
self.schema_ok = schema_ok;
self
}
pub fn build(self) -> Validator {
Validator::Hash(self)
}
pub(crate) fn validate<'c>(
&'c self,
parser: &mut Parser,
checklist: &mut Option<Checklist<'c>>,
) -> Result<()> {
let elem = parser
.next()
.ok_or_else(|| Error::FailValidate("Expected a hash".to_string()))??;
let val = if let Element::Hash(v) = elem {
v
} else {
return Err(Error::FailValidate(format!(
"Expected Hash, got {}",
elem.name()
)));
};
if !self.in_list.is_empty() && !self.in_list.iter().any(|v| *v == val) {
return Err(Error::FailValidate(
"Timestamp is not on `in` list".to_string(),
));
}
if self.nin_list.iter().any(|v| *v == val) {
return Err(Error::FailValidate(
"Timestamp is on `nin` list".to_string(),
));
}
if let Some(checklist) = checklist {
match (self.schema.is_empty(), self.link.as_ref()) {
(false, Some(link)) => checklist.insert(val, Some(&self.schema), Some(link)),
(false, None) => checklist.insert(val, Some(&self.schema), None),
(true, Some(link)) => checklist.insert(val, None, Some(link)),
_ => (),
}
}
Ok(())
}
fn query_check_self(&self, types: &BTreeMap<String, Validator>, other: &HashValidator) -> bool {
let initial_check = (self.query || (other.in_list.is_empty() && other.nin_list.is_empty()))
&& (self.link_ok || other.link.is_none())
&& (self.schema_ok || other.schema.is_empty());
if !initial_check {
return false;
}
if self.link_ok {
match (&self.link, &other.link) {
(None, None) => true,
(Some(_), None) => true,
(None, Some(_)) => false,
(Some(s), Some(o)) => s.query_check(types, o.as_ref()),
}
} else {
true
}
}
pub(crate) fn query_check(
&self,
types: &BTreeMap<String, Validator>,
other: &Validator,
) -> bool {
match other {
Validator::Hash(other) => self.query_check_self(types, other),
Validator::Multi(list) => list.iter().all(|other| match other {
Validator::Hash(other) => self.query_check_self(types, other),
_ => false,
}),
Validator::Any => true,
_ => false,
}
}
}
#[cfg(test)]
mod test {
use super::*;
use crate::{de::FogDeserializer, ser::FogSerializer};
#[test]
fn ser_default() {
let schema = HashValidator::default();
let mut ser = FogSerializer::default();
schema.serialize(&mut ser).unwrap();
let expected: Vec<u8> = vec![0x80];
let actual = ser.finish();
println!("expected: {:x?}", expected);
println!("actual: {:x?}", actual);
assert_eq!(expected, actual);
let mut de = FogDeserializer::with_debug(&actual, " ");
let decoded = HashValidator::deserialize(&mut de).unwrap();
println!("{}", de.get_debug().unwrap());
assert_eq!(schema, decoded);
}
#[test]
fn verify_simple() {
let mut schema = HashValidator {
link: Some(Box::new(Validator::Hash(HashValidator::default()))),
..HashValidator::default()
};
schema
.schema
.push(Some(Hash::new(b"Pretend I am a real schema")));
schema.schema.push(None);
let mut ser = FogSerializer::default();
Hash::new(b"Data to make a hash")
.serialize(&mut ser)
.unwrap();
let encoded = ser.finish();
let mut parser = Parser::new(&encoded);
let fake_schema = Hash::new(b"Pretend I, too, am a real schema");
let fake_types = BTreeMap::new();
let mut checklist = Some(Checklist::new(&fake_schema, &fake_types));
schema
.validate(&mut parser, &mut checklist)
.expect("should succeed as a validator");
}
}