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
use super::*;

#[derive(Serialize, Deserialize)]
struct RawGroupings(Vec<RawGrouping>);
#[derive(Serialize, Deserialize)]
struct RawGrouping {
    name: String,
    validators: Vec<PublicKey>,
}
impl<'fbas> Groupings<'fbas> {
    pub fn organizations_from_json_str(orgs_json: &str, fbas: &'fbas Fbas) -> Self {
        Self::from_raw(
            serde_json::from_str(orgs_json).expect("Error parsing Organizations JSON"),
            fbas,
        )
    }
    pub fn isps_from_json_str(nodes_json: &str, fbas: &'fbas Fbas) -> Self {
        let raw_nodes: Vec<RawNode> =
            serde_json::from_str(&nodes_json).expect("Error parsing FBAS JSON");
        let raw_groupings = RawGroupings::isps_from_raw_nodes(raw_nodes);
        Groupings::from_raw(raw_groupings, &fbas)
    }
    pub fn countries_from_json_str(nodes_json: &str, fbas: &'fbas Fbas) -> Self {
        let raw_nodes: Vec<RawNode> =
            serde_json::from_str(&nodes_json).expect("Error parsing FBAS JSON");
        let raw_groupings = RawGroupings::countries_from_raw_nodes(raw_nodes);
        Groupings::from_raw(raw_groupings, &fbas)
    }
    pub fn organizations_from_json_file(path: &Path, fbas: &'fbas Fbas) -> Self {
        let json =
            fs::read_to_string(path).unwrap_or_else(|_| panic!("Error reading file {:?}", path));
        Self::organizations_from_json_str(&json, fbas)
    }
    pub fn isps_from_json_file(path: &Path, fbas: &'fbas Fbas) -> Self {
        let json =
            fs::read_to_string(path).unwrap_or_else(|_| panic!("Error reading file {:?}", path));
        Self::isps_from_json_str(&json, &fbas)
    }
    pub fn countries_from_json_file(path: &Path, fbas: &'fbas Fbas) -> Self {
        let json =
            fs::read_to_string(path).unwrap_or_else(|_| panic!("Error reading file {:?}", path));
        Self::countries_from_json_str(&json, &fbas)
    }
    fn from_raw(raw_groupings: RawGroupings, fbas: &'fbas Fbas) -> Self {
        let groupings: Vec<Grouping> = raw_groupings
            .0
            .into_iter()
            .map(|x| Grouping::from_raw(x, &fbas.pk_to_id))
            .collect();

        Groupings::new(groupings, fbas)
    }
    fn to_raw(&self) -> RawGroupings {
        RawGroupings(
            self.groupings
                .iter()
                .map(|org| org.to_raw(self.fbas))
                .collect(),
        )
    }
}
impl<'fbas> Serialize for Groupings<'fbas> {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        self.to_raw().serialize(serializer)
    }
}
impl Grouping {
    fn from_raw(raw_grouping: RawGrouping, pk_to_id: &HashMap<PublicKey, NodeId>) -> Self {
        Grouping {
            name: raw_grouping.name,
            validators: raw_grouping
                .validators
                .into_iter()
                .filter_map(|pk| pk_to_id.get(&pk))
                .cloned()
                .collect(),
        }
    }
    fn to_raw(&self, fbas: &Fbas) -> RawGrouping {
        RawGrouping {
            name: self.name.clone(),
            validators: self
                .validators
                .iter()
                .map(|&x| fbas.nodes[x].public_key.clone())
                .collect(),
        }
    }
}

impl RawGroupings {
    fn isps_from_raw_nodes(raw_nodes: Vec<RawNode>) -> Self {
        let mut isp_to_validators: HashMap<String, Vec<PublicKey>> =
            HashMap::with_capacity(raw_nodes.len());
        let mut raw_groupings: Vec<RawGrouping> = Vec::with_capacity(isp_to_validators.len());
        for raw_node in &raw_nodes {
            if let Some(name) = &raw_node.isp {
                let mut isp = name.clone();
                isp = remove_special_chars_from_grouping_name(isp);
                if isp_to_validators.get(&isp) == None {
                    isp_to_validators.insert(isp.clone(), Vec::new());
                }
                isp_to_validators
                    .get_mut(&isp)
                    .unwrap()
                    .push(raw_node.public_key.clone());
            };
        }
        let mut grouping_names = Vec::with_capacity(isp_to_validators.len());
        for key in isp_to_validators.keys() {
            grouping_names.push(key);
        }
        grouping_names.sort_unstable();
        for name in grouping_names {
            if let Some(validators) = isp_to_validators.get(name) {
                let raw_grouping = RawGrouping {
                    name: name.clone(),
                    validators: validators.clone(),
                };
                raw_groupings.push(raw_grouping);
            }
        }
        RawGroupings(raw_groupings)
    }
    fn countries_from_raw_nodes(raw_nodes: Vec<RawNode>) -> Self {
        let mut country_to_validators: HashMap<String, Vec<PublicKey>> =
            HashMap::with_capacity(raw_nodes.len());
        let mut raw_groupings: Vec<RawGrouping> = Vec::with_capacity(country_to_validators.len());
        for raw_node in &raw_nodes {
            if let Some(geodata) = &raw_node.geo_data {
                if let Some(name) = &geodata.country_name {
                    let mut country = name.clone();
                    country = remove_special_chars_from_grouping_name(country);
                    if country_to_validators.get(&country.clone()) == None {
                        country_to_validators.insert(country.clone(), Vec::new());
                    }
                    country_to_validators
                        .get_mut(&country.clone())
                        .unwrap()
                        .push(raw_node.public_key.clone());
                }
            };
        }
        let mut grouping_names = Vec::with_capacity(country_to_validators.len());
        for key in country_to_validators.keys() {
            grouping_names.push(key);
        }
        grouping_names.sort_unstable();
        for name in grouping_names {
            if let Some(validators) = country_to_validators.get(name) {
                let raw_grouping = RawGrouping {
                    name: name.clone(),
                    validators: validators.clone(),
                };
                raw_groupings.push(raw_grouping);
            }
        }
        RawGroupings(raw_groupings)
    }
}

fn remove_special_chars_from_grouping_name(mut name: String) -> String {
    name.retain(|c| c != ',');
    let mut maybe_fullstop = name.split_off(name.len() - 1);
    maybe_fullstop.retain(|c| c != '.');
    name.push_str(&maybe_fullstop);
    name
}

#[cfg(test)]
mod tests {
    use super::*;
    #[test]
    fn read_isps_from_nodes_json_str() {
        let json = r#"[
            {
                "publicKey": "GCGB2",
                "active": true,
                "isp": "Google.com"
            },
            {
                "publicKey": "GCM6Q",
                "active": true,
                "isp": "StackOverflow"
            },
            {
                "publicKey": "GCHAR",
                "active": true,
                "isp": "Hetzner"
            },
            {
                "publicKey": "GABMK",
                "active": true,
                "isp": "Google.com"
            }]"#;
        let fbas = Fbas::from_json_str(&json);
        let isps = Groupings::isps_from_json_str(&json, &fbas);
        let expected_names = vec!["Google.com", "Hetzner", "StackOverflow"];
        let actual_names: Vec<String> = isps.groupings.iter().map(|x| x.name.clone()).collect();
        let expected_validators: Vec<Vec<NodeId>> = vec![vec![0, 3], vec![2], vec![1]];
        let actual_validators: Vec<Vec<NodeId>> = isps
            .groupings
            .iter()
            .map(|x| x.validators.clone())
            .collect();
        assert_eq!(expected_names, actual_names);
        assert_eq!(expected_validators, actual_validators);
    }
    #[test]
    fn read_countries_from_nodes_json_str() {
        let json = r#"[
            {
                "publicKey": "GCGB2",
                "active": true,
                "geoData": {
                    "countryCode": "AA",
                    "countryName": "Absurdistan"
                }
            },
            {
                "publicKey": "GCM6Q",
                "active": true,
                "geoData": {
                    "countryCode": "WA",
                    "countryName": "Wakanda"
                }
            },
            {
                "publicKey": "GCHAR",
                "active": true,
                "geoData": {
                    "countryCode": "TI",
                    "countryName": "Timbuktu"
                }
            },
            {
                "publicKey": "GABMK",
                "active": true,
                "geoData": {
                    "countryCode": "TI",
                    "countryName": "Timbuktu"
                }
            }]"#;
        let fbas = Fbas::from_json_str(&json);
        let countries = Groupings::countries_from_json_str(&json, &fbas);
        let expected_names = vec!["Absurdistan", "Timbuktu", "Wakanda"];
        let actual_names: Vec<String> =
            countries.groupings.iter().map(|x| x.name.clone()).collect();
        let expected_validators: Vec<Vec<NodeId>> = vec![vec![0], vec![2, 3], vec![1]];
        let actual_validators: Vec<Vec<NodeId>> = countries
            .groupings
            .iter()
            .map(|x| x.validators.clone())
            .collect();
        assert_eq!(expected_names, actual_names);
        assert_eq!(expected_validators, actual_validators);
    }
    #[test]
    fn missing_ctry_key_in_json_doesnt_panic() {
        let json = r#"[
            {
                "publicKey": "GCGB2",
                "geoData": {
                    "countryName": "Wakanda"
                }
            },
            {
                "publicKey": "GCM6Q",
                "geoData": {
                    "countryName": "Absurdistan"
                }
            },
            {
                "publicKey": "GABMK"
            }]"#;
        let fbas = Fbas::from_json_str(&json);
        let countries = Groupings::countries_from_json_str(&json, &fbas);
        let expected_names = vec!["Absurdistan", "Wakanda"];
        let actual_names: Vec<String> =
            countries.groupings.iter().map(|x| x.name.clone()).collect();
        let expected_validators: Vec<Vec<NodeId>> = vec![vec![1], vec![0]];
        let actual_validators: Vec<Vec<NodeId>> = countries
            .groupings
            .iter()
            .map(|x| x.validators.clone())
            .collect();
        assert_eq!(expected_names, actual_names);
        assert_eq!(expected_validators, actual_validators);
    }
    #[test]
    fn special_chars_filtered_from_json_str() {
        let json = r#"[
            {
                "publicKey": "GCGB2",
                "isp": "Google.com"
            },
            {
                "publicKey": "GCM6Q",
                "isp": "Google.com."
            },
            {
                "publicKey": "GCHAR",
                "isp": "Amazon.com Inc,"
            },
            {
                "publicKey": "GCARK",
                "isp": "Google.com,"
            },
            {
                "publicKey": "GABMK",
                "isp": "Amazon.com, Inc."
            }]"#;
        let fbas = Fbas::from_json_str(&json);
        let isps = Groupings::isps_from_json_str(&json, &fbas);
        let expected_names = vec!["Amazon.com Inc", "Google.com"];
        let actual_names: Vec<String> = isps.groupings.iter().map(|x| x.name.clone()).collect();
        let expected_validators: Vec<Vec<NodeId>> = vec![vec![2, 4], vec![0, 1, 3]];
        let actual_validators: Vec<Vec<NodeId>> = isps
            .groupings
            .iter()
            .map(|x| x.validators.clone())
            .collect();
        assert_eq!(expected_names, actual_names);
        assert_eq!(expected_validators, actual_validators);
    }
}