lib.rs 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643
  1. use http::status::StatusCode;
  2. use http_body_util::{BodyExt, Empty};
  3. use hyper::{body::Bytes, Body, Client, Method, Request};
  4. use hyper_util::rt::TokioExecutor;
  5. use lazy_static::lazy_static;
  6. //use select::{document::Document, predicate::Name};
  7. use serde::{Deserialize, Serialize};
  8. use sled::Db;
  9. use std::{
  10. collections::{BTreeMap, HashMap, HashSet},
  11. fmt,
  12. };
  13. pub mod analysis;
  14. pub mod bridge_verification_info;
  15. pub mod extra_info;
  16. pub mod negative_report;
  17. pub mod positive_report;
  18. pub mod request_handler;
  19. use analysis::Analyzer;
  20. use extra_info::*;
  21. use negative_report::*;
  22. use positive_report::*;
  23. lazy_static! {
  24. // known country codes based on Tor geoIP database
  25. // Produced with `cat /usr/share/tor/geoip{,6} | grep -v ^# | grep -o ..$ | sort | uniq | tr '[:upper:]' '[:lower:]' | tr '\n' ',' | sed 's/,/","/g'`
  26. pub static ref COUNTRY_CODES: HashSet<&'static str> = HashSet::from(["??","ad","ae","af","ag","ai","al","am","ao","ap","aq","ar","as","at","au","aw","ax","az","ba","bb","bd","be","bf","bg","bh","bi","bj","bl","bm","bn","bo","bq","br","bs","bt","bv","bw","by","bz","ca","cc","cd","cf","cg","ch","ci","ck","cl","cm","cn","co","cr","cs","cu","cv","cw","cx","cy","cz","de","dj","dk","dm","do","dz","ec","ee","eg","eh","er","es","et","eu","fi","fj","fk","fm","fo","fr","ga","gb","gd","ge","gf","gg","gh","gi","gl","gm","gn","gp","gq","gr","gs","gt","gu","gw","gy","hk","hm","hn","hr","ht","hu","id","ie","il","im","in","io","iq","ir","is","it","je","jm","jo","jp","ke","kg","kh","ki","km","kn","kp","kr","kw","ky","kz","la","lb","lc","li","lk","lr","ls","lt","lu","lv","ly","ma","mc","md","me","mf","mg","mh","mk","ml","mm","mn","mo","mp","mq","mr","ms","mt","mu","mv","mw","mx","my","mz","na","nc","ne","nf","ng","ni","nl","no","np","nr","nu","nz","om","pa","pe","pf","pg","ph","pk","pl","pm","pn","pr","ps","pt","pw","py","qa","re","ro","rs","ru","rw","sa","sb","sc","sd","se","sg","sh","si","sj","sk","sl","sm","sn","so","sr","ss","st","sv","sx","sy","sz","tc","td","tf","tg","th","tj","tk","tl","tm","tn","to","tr","tt","tv","tw","tz","ua","ug","um","us","uy","uz","va","vc","ve","vg","vi","vn","vu","wf","ws","ye","yt","za","zm","zw"]);
  27. }
  28. /// We will accept reports up to this many days old.
  29. pub const MAX_BACKDATE: u32 = 3;
  30. /// Get Julian date
  31. pub fn get_date() -> u32 {
  32. time::OffsetDateTime::now_utc()
  33. .date()
  34. .to_julian_day()
  35. .try_into()
  36. .unwrap()
  37. }
  38. #[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Serialize, Deserialize)]
  39. pub enum BridgeDistributor {
  40. Lox,
  41. }
  42. /// All the info for a bridge, to be stored in the database
  43. #[derive(Serialize, Deserialize)]
  44. pub struct BridgeInfo {
  45. /// hashed fingerprint (SHA-1 hash of 20-byte bridge ID)
  46. pub fingerprint: [u8; 20],
  47. /// nickname of bridge (probably not necessary)
  48. pub nickname: String,
  49. /// first Julian date we started collecting data on this bridge
  50. pub first_seen: u32,
  51. /// map of countries to data for this bridge in that country
  52. pub info_by_country: HashMap<String, BridgeCountryInfo>,
  53. }
  54. impl BridgeInfo {
  55. pub fn new(fingerprint: [u8; 20], nickname: &String) -> Self {
  56. Self {
  57. fingerprint: fingerprint,
  58. nickname: nickname.to_string(),
  59. first_seen: get_date(),
  60. info_by_country: HashMap::<String, BridgeCountryInfo>::new(),
  61. }
  62. }
  63. }
  64. impl fmt::Display for BridgeInfo {
  65. fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
  66. let mut str = format!(
  67. "fingerprint:{}\n",
  68. array_bytes::bytes2hex("", self.fingerprint).as_str()
  69. );
  70. str.push_str(format!("nickname: {}\n", self.nickname).as_str());
  71. str.push_str(format!("first_seen: {}\n", self.first_seen).as_str());
  72. str.push_str("info_by_country:");
  73. for country in self.info_by_country.keys() {
  74. str.push_str(format!("\n country: {}", country).as_str());
  75. let country_info = self.info_by_country.get(country).unwrap();
  76. for line in country_info.to_string().lines() {
  77. str.push_str(format!("\n {}", line).as_str());
  78. }
  79. }
  80. write!(f, "{}", str)
  81. }
  82. }
  83. #[derive(Clone, Copy, Eq, PartialEq, Ord, PartialOrd, Serialize, Deserialize)]
  84. pub enum BridgeInfoType {
  85. BridgeIps,
  86. NegativeReports,
  87. PositiveReports,
  88. }
  89. /// Information about bridge reachability from a given country
  90. #[derive(Serialize, Deserialize)]
  91. pub struct BridgeCountryInfo {
  92. pub info_by_day: BTreeMap<u32, BTreeMap<BridgeInfoType, u32>>,
  93. pub blocked: bool,
  94. }
  95. impl BridgeCountryInfo {
  96. pub fn new() -> Self {
  97. Self {
  98. info_by_day: BTreeMap::<u32, BTreeMap<BridgeInfoType, u32>>::new(),
  99. blocked: false,
  100. }
  101. }
  102. pub fn add_info(&mut self, info_type: BridgeInfoType, date: u32, count: u32) {
  103. if self.info_by_day.contains_key(&date) {
  104. let info = self.info_by_day.get_mut(&date).unwrap();
  105. if !info.contains_key(&info_type) {
  106. info.insert(info_type, count);
  107. } else if info_type == BridgeInfoType::BridgeIps {
  108. if *info.get(&info_type).unwrap() < count {
  109. // Use highest value we've seen today
  110. info.insert(info_type, count);
  111. }
  112. } else {
  113. // Add count to previous count for reports
  114. let new_count = info.get(&info_type).unwrap() + count;
  115. info.insert(info_type, new_count);
  116. }
  117. } else {
  118. let mut info = BTreeMap::<BridgeInfoType, u32>::new();
  119. info.insert(info_type, count);
  120. self.info_by_day.insert(date, info);
  121. }
  122. }
  123. }
  124. impl fmt::Display for BridgeCountryInfo {
  125. fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
  126. let mut str = String::from("info:");
  127. for date in self.info_by_day.keys() {
  128. let info = self.info_by_day.get(date).unwrap();
  129. let ip_count = match info.get(&BridgeInfoType::BridgeIps) {
  130. Some(v) => v,
  131. None => &0,
  132. };
  133. let nr_count = match info.get(&BridgeInfoType::NegativeReports) {
  134. Some(v) => v,
  135. None => &0,
  136. };
  137. let pr_count = match info.get(&BridgeInfoType::PositiveReports) {
  138. Some(v) => v,
  139. None => &0,
  140. };
  141. if ip_count > &0 || nr_count > &0 || pr_count > &0 {
  142. str.push_str(
  143. format!(
  144. "\n date: {}\n connections: {}\n negative reports: {}\n positive reports: {}",
  145. date,
  146. ip_count,
  147. nr_count,
  148. pr_count,
  149. )
  150. .as_str(),
  151. );
  152. }
  153. }
  154. write!(f, "{}", str)
  155. }
  156. }
  157. /// We store a set of all known bridges so that we can later iterate over them.
  158. /// This function just adds a bridge fingerprint to that set.
  159. pub fn add_bridge_to_db(db: &Db, fingerprint: [u8; 20]) {
  160. let mut bridges = match db.get("bridges").unwrap() {
  161. Some(v) => bincode::deserialize(&v).unwrap(),
  162. None => HashSet::<[u8; 20]>::new(),
  163. };
  164. bridges.insert(fingerprint);
  165. db.insert("bridges", bincode::serialize(&bridges).unwrap())
  166. .unwrap();
  167. }
  168. // Download a webpage and return it as a string
  169. pub async fn download(url: &str) -> Result<String, Box<dyn std::error::Error + Send + Sync>> {
  170. let https = hyper_rustls::HttpsConnectorBuilder::new()
  171. .with_native_roots()
  172. .expect("no native root CA certificates found")
  173. .https_only()
  174. .enable_http1()
  175. .build();
  176. let client: hyper_util::client::legacy::Client<_, Empty<Bytes>> =
  177. hyper_util::client::legacy::Client::builder(TokioExecutor::new()).build(https);
  178. println!("Downloading {}", url);
  179. let mut res = client.get(url.parse()?).await?;
  180. assert_eq!(res.status(), StatusCode::OK);
  181. let mut body_str = String::default();
  182. while let Some(next) = res.frame().await {
  183. let frame = next?;
  184. if let Some(chunk) = frame.data_ref() {
  185. body_str.push_str(&String::from_utf8(chunk.to_vec())?);
  186. }
  187. }
  188. Ok(body_str)
  189. }
  190. // Process extra-infos
  191. /// Adds the extra-info data for a single bridge to the database. If the
  192. /// database already contains an extra-info for this bridge for thid date,
  193. /// but this extra-info contains different data for some reason, use the
  194. /// greater count of connections from each country.
  195. pub fn add_extra_info_to_db(db: &Db, extra_info: ExtraInfo) {
  196. let fingerprint = extra_info.fingerprint;
  197. let mut bridge_info = match db.get(fingerprint).unwrap() {
  198. Some(v) => bincode::deserialize(&v).unwrap(),
  199. None => {
  200. add_bridge_to_db(&db, fingerprint);
  201. BridgeInfo::new(fingerprint, &extra_info.nickname)
  202. }
  203. };
  204. for country in extra_info.bridge_ips.keys() {
  205. if bridge_info.info_by_country.contains_key::<String>(country) {
  206. bridge_info
  207. .info_by_country
  208. .get_mut(country)
  209. .unwrap()
  210. .add_info(
  211. BridgeInfoType::BridgeIps,
  212. extra_info.date,
  213. *extra_info.bridge_ips.get(country).unwrap(),
  214. );
  215. } else {
  216. // No existing entry; make a new one.
  217. let mut bridge_country_info = BridgeCountryInfo::new();
  218. bridge_country_info.add_info(
  219. BridgeInfoType::BridgeIps,
  220. extra_info.date,
  221. *extra_info.bridge_ips.get(country).unwrap(),
  222. );
  223. bridge_info
  224. .info_by_country
  225. .insert(country.to_string(), bridge_country_info);
  226. }
  227. }
  228. // Commit changes to database
  229. db.insert(fingerprint, bincode::serialize(&bridge_info).unwrap())
  230. .unwrap();
  231. }
  232. /// Download new extra-infos files and add their data to the database
  233. pub async fn update_extra_infos(
  234. db: &Db,
  235. base_url: &str,
  236. ) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
  237. // Track which files have been processed. This is slightly redundant
  238. // because we're only downloading files we don't already have, but it
  239. // might be a good idea to check in case we downloaded a file but didn't
  240. // process it for some reason.
  241. let mut processed_extra_infos_files = match db.get(b"extra_infos_files").unwrap() {
  242. Some(v) => bincode::deserialize(&v).unwrap(),
  243. None => HashSet::<String>::new(),
  244. };
  245. let dir_page = download(base_url).await?;
  246. // Causes Send issues, so use solution below instead
  247. //let doc = Document::from(dir_page.as_str());
  248. //let links = doc.find(Name("a")).filter_map(|n| n.attr("href"));
  249. // Alternative, less robust solution
  250. let mut links = HashSet::<String>::new();
  251. for line in dir_page.lines() {
  252. let begin_match = "<a href=\"";
  253. let end_match = "\">";
  254. if line.contains(begin_match) {
  255. let link = &line[line.find(begin_match).unwrap() + begin_match.len()..];
  256. if link.contains(end_match) {
  257. let link = &link[0..link.find(end_match).unwrap()];
  258. links.insert(link.to_string());
  259. }
  260. }
  261. }
  262. let mut new_extra_infos = HashSet::<ExtraInfo>::new();
  263. // We should now have an iterable collection of links to consider downloading.
  264. for link in links {
  265. if link.ends_with("-extra-infos") && !processed_extra_infos_files.contains(&link) {
  266. let extra_infos_url = format!("{}{}", base_url, link);
  267. let extra_info_str = download(&extra_infos_url).await?;
  268. //ExtraInfo::parse_file(&extra_info_str, &mut new_extra_infos);
  269. let extra_infos = ExtraInfo::parse_file(&extra_info_str);
  270. new_extra_infos.extend(extra_infos);
  271. processed_extra_infos_files.insert(link);
  272. }
  273. }
  274. // Add new extra-infos data to database
  275. for extra_info in new_extra_infos {
  276. add_extra_info_to_db(&db, extra_info);
  277. }
  278. // Store which files we've already downloaded and processed
  279. db.insert(
  280. b"extra_infos_files",
  281. bincode::serialize(&processed_extra_infos_files).unwrap(),
  282. )
  283. .unwrap();
  284. Ok(())
  285. }
  286. // Process negative reports
  287. /// We store to-be-processed negative reports as a vector. Add this NR
  288. /// to that vector (or create a new vector if necessary)
  289. pub fn save_negative_report_to_process(db: &Db, nr: NegativeReport) {
  290. // TODO: Purge these database entries sometimes
  291. let mut nonces = match db.get(format!("nonces_{}", &nr.date)).unwrap() {
  292. Some(v) => bincode::deserialize(&v).unwrap(),
  293. None => HashSet::<[u8; 32]>::new(),
  294. };
  295. // Just ignore the report if we've seen the nonce before
  296. if nonces.insert(nr.nonce) {
  297. db.insert(
  298. format!("nonces_{}", &nr.date),
  299. bincode::serialize(&nonces).unwrap(),
  300. )
  301. .unwrap();
  302. let mut reports = match db.get("nrs-to-process").unwrap() {
  303. Some(v) => bincode::deserialize(&v).unwrap(),
  304. None => BTreeMap::<String, Vec<SerializableNegativeReport>>::new(),
  305. };
  306. // Store to-be-processed reports with key [fingerprint]_[country]_[date]
  307. let map_key = format!(
  308. "{}_{}_{}",
  309. array_bytes::bytes2hex("", &nr.fingerprint),
  310. &nr.country,
  311. &nr.date,
  312. );
  313. if reports.contains_key(&map_key) {
  314. reports
  315. .get_mut(&map_key)
  316. .unwrap()
  317. .push(nr.to_serializable_report());
  318. } else {
  319. let mut nrs = Vec::<SerializableNegativeReport>::new();
  320. nrs.push(nr.to_serializable_report());
  321. reports.insert(map_key, nrs);
  322. }
  323. // Commit changes to database
  324. db.insert("nrs-to-process", bincode::serialize(&reports).unwrap())
  325. .unwrap();
  326. }
  327. }
  328. /// Sends a collection of negative reports to the Lox Authority and returns the
  329. /// number of valid reports returned by the server. The negative reports in the
  330. /// collection should all have the same bridge fingerprint, date, country, and
  331. /// distributor.
  332. pub async fn verify_negative_reports(
  333. distributors: &BTreeMap<BridgeDistributor, String>,
  334. reports: &Vec<SerializableNegativeReport>,
  335. ) -> u32 {
  336. // Don't make a network call if we don't have any reports anyway
  337. if reports.is_empty() {
  338. return 0;
  339. }
  340. // Get one report, assume the rest have the same distributor
  341. let first_report = &reports[0];
  342. let distributor = first_report.distributor;
  343. let client = Client::new();
  344. let uri: String = (distributors.get(&distributor).unwrap().to_owned() + "/verifynegative")
  345. .parse()
  346. .unwrap();
  347. let req = Request::builder()
  348. .method(Method::POST)
  349. .uri(uri)
  350. .body(Body::from(serde_json::to_string(&reports).unwrap()))
  351. .unwrap();
  352. let resp = client.request(req).await.unwrap();
  353. let buf = hyper::body::to_bytes(resp).await.unwrap();
  354. serde_json::from_slice(&buf).unwrap()
  355. }
  356. /// Process today's negative reports and store the count of verified reports in
  357. /// the database.
  358. pub async fn update_negative_reports(db: &Db, distributors: &BTreeMap<BridgeDistributor, String>) {
  359. let mut all_negative_reports = match db.get("nrs-to-process").unwrap() {
  360. Some(v) => bincode::deserialize(&v).unwrap(),
  361. None => BTreeMap::<String, Vec<SerializableNegativeReport>>::new(),
  362. };
  363. // Key is [fingerprint]_[country]_[date]
  364. for bridge_country_date in all_negative_reports.keys() {
  365. let reports = all_negative_reports.get(bridge_country_date).unwrap();
  366. if !reports.is_empty() {
  367. let first_report = &reports[0];
  368. let fingerprint = first_report.fingerprint;
  369. let date = first_report.date;
  370. let country = first_report.country.clone();
  371. let count_valid = verify_negative_reports(&distributors, reports).await;
  372. // Get bridge info or make new one
  373. let mut bridge_info = match db.get(fingerprint).unwrap() {
  374. Some(v) => bincode::deserialize(&v).unwrap(),
  375. None => {
  376. // This case shouldn't happen unless the bridge hasn't
  377. // published any bridge stats.
  378. add_bridge_to_db(&db, fingerprint);
  379. BridgeInfo::new(fingerprint, &String::default())
  380. }
  381. };
  382. // Add the new report count to it
  383. if bridge_info.info_by_country.contains_key(&country) {
  384. let bridge_country_info = bridge_info.info_by_country.get_mut(&country).unwrap();
  385. bridge_country_info.add_info(BridgeInfoType::NegativeReports, date, count_valid);
  386. } else {
  387. // No existing entry; make a new one.
  388. let mut bridge_country_info = BridgeCountryInfo::new();
  389. bridge_country_info.add_info(BridgeInfoType::NegativeReports, date, count_valid);
  390. bridge_info
  391. .info_by_country
  392. .insert(country, bridge_country_info);
  393. }
  394. // Commit changes to database
  395. db.insert(fingerprint, bincode::serialize(&bridge_info).unwrap())
  396. .unwrap();
  397. }
  398. }
  399. // TODO: Would it be cheaper to just recreate it?
  400. all_negative_reports.clear();
  401. // Remove the now-processed reports from the database
  402. db.insert(
  403. "nrs-to-process",
  404. bincode::serialize(&all_negative_reports).unwrap(),
  405. )
  406. .unwrap();
  407. }
  408. // Process positive reports
  409. /// We store to-be-processed positive reports as a vector. Add this PR
  410. /// to that vector (or create a new vector if necessary).
  411. pub fn save_positive_report_to_process(db: &Db, pr: PositiveReport) {
  412. let mut reports = match db.get("prs-to-process").unwrap() {
  413. Some(v) => bincode::deserialize(&v).unwrap(),
  414. None => BTreeMap::<String, Vec<SerializablePositiveReport>>::new(),
  415. };
  416. // Store to-be-processed reports with key [fingerprint]_[country]_[date]
  417. let map_key = format!(
  418. "{}_{}_{}",
  419. array_bytes::bytes2hex("", &pr.fingerprint),
  420. &pr.country,
  421. &pr.date,
  422. );
  423. if reports.contains_key(&map_key) {
  424. reports
  425. .get_mut(&map_key)
  426. .unwrap()
  427. .push(pr.to_serializable_report());
  428. } else {
  429. let mut prs = Vec::<SerializablePositiveReport>::new();
  430. prs.push(pr.to_serializable_report());
  431. reports.insert(map_key, prs);
  432. }
  433. // Commit changes to database
  434. db.insert("prs-to-process", bincode::serialize(&reports).unwrap())
  435. .unwrap();
  436. }
  437. /// Sends a collection of positive reports to the Lox Authority and returns the
  438. /// number of valid reports returned by the server. The positive reports in the
  439. /// collection should all have the same bridge fingerprint, date, and country.
  440. pub async fn verify_positive_reports(
  441. distributors: &BTreeMap<BridgeDistributor, String>,
  442. reports: &Vec<SerializablePositiveReport>,
  443. ) -> u32 {
  444. // Don't make a network call if we don't have any reports anyway
  445. if reports.is_empty() {
  446. return 0;
  447. }
  448. let client = Client::new();
  449. let uri: String = (distributors
  450. .get(&BridgeDistributor::Lox)
  451. .unwrap()
  452. .to_owned()
  453. + "/verifypositive")
  454. .parse()
  455. .unwrap();
  456. let req = Request::builder()
  457. .method(Method::POST)
  458. .uri(uri)
  459. .body(Body::from(serde_json::to_string(&reports).unwrap()))
  460. .unwrap();
  461. let resp = client.request(req).await.unwrap();
  462. let buf = hyper::body::to_bytes(resp).await.unwrap();
  463. serde_json::from_slice(&buf).unwrap()
  464. }
  465. /// Process today's positive reports and store the count of verified reports in
  466. /// the database.
  467. pub async fn update_positive_reports(db: &Db, distributors: &BTreeMap<BridgeDistributor, String>) {
  468. let mut all_positive_reports = match db.get("prs-to-process").unwrap() {
  469. Some(v) => bincode::deserialize(&v).unwrap(),
  470. None => BTreeMap::<String, Vec<SerializablePositiveReport>>::new(),
  471. };
  472. // Key is [fingerprint]_[country]_[date]
  473. for bridge_country_date in all_positive_reports.keys() {
  474. let reports = all_positive_reports.get(bridge_country_date).unwrap();
  475. if !reports.is_empty() {
  476. let first_report = &reports[0];
  477. let fingerprint = first_report.fingerprint;
  478. let date = first_report.date;
  479. let country = first_report.country.clone();
  480. let count_valid = verify_positive_reports(&distributors, reports).await;
  481. // Get bridge info or make new one
  482. let mut bridge_info = match db.get(fingerprint).unwrap() {
  483. Some(v) => bincode::deserialize(&v).unwrap(),
  484. None => {
  485. // This case shouldn't happen unless the bridge hasn't
  486. // published any bridge stats.
  487. add_bridge_to_db(&db, fingerprint);
  488. BridgeInfo::new(fingerprint, &String::default())
  489. }
  490. };
  491. // Add the new report count to it
  492. if bridge_info.info_by_country.contains_key(&country) {
  493. let bridge_country_info = bridge_info.info_by_country.get_mut(&country).unwrap();
  494. bridge_country_info.add_info(BridgeInfoType::PositiveReports, date, count_valid);
  495. } else {
  496. // No existing entry; make a new one.
  497. let mut bridge_country_info = BridgeCountryInfo::new();
  498. bridge_country_info.add_info(BridgeInfoType::PositiveReports, date, count_valid);
  499. bridge_info
  500. .info_by_country
  501. .insert(country, bridge_country_info);
  502. }
  503. // Commit changes to database
  504. db.insert(fingerprint, bincode::serialize(&bridge_info).unwrap())
  505. .unwrap();
  506. }
  507. }
  508. // TODO: Would it be cheaper to just recreate it?
  509. all_positive_reports.clear();
  510. // Remove the now-processed reports from the database
  511. db.insert(
  512. "prs-to-process",
  513. bincode::serialize(&all_positive_reports).unwrap(),
  514. )
  515. .unwrap();
  516. }
  517. // Verdict on bridge reachability
  518. /// Guess which countries block a bridge. This function returns a map of new
  519. /// blockages (fingerprint : set of countries which block the bridge)
  520. pub fn guess_blockages(
  521. db: &Db,
  522. analyzer: &dyn Analyzer,
  523. confidence: f64,
  524. ) -> HashMap<[u8; 20], HashSet<String>> {
  525. // Map of bridge fingerprint to set of countries which newly block it
  526. let mut blockages = HashMap::<[u8; 20], HashSet<String>>::new();
  527. // Get list of bridges from database
  528. let bridges = match db.get("bridges").unwrap() {
  529. Some(v) => bincode::deserialize(&v).unwrap(),
  530. None => HashSet::<[u8; 20]>::new(),
  531. };
  532. // Guess for each bridge
  533. for fingerprint in bridges {
  534. let mut bridge_info: BridgeInfo =
  535. bincode::deserialize(&db.get(fingerprint).unwrap().unwrap()).unwrap();
  536. let mut new_blockages = HashSet::<String>::new();
  537. let blocked_in = analysis::blocked_in(analyzer, &bridge_info, confidence, get_date());
  538. for country in blocked_in {
  539. let bridge_country_info = bridge_info.info_by_country.get_mut(&country).unwrap();
  540. if !bridge_country_info.blocked {
  541. new_blockages.insert(country.to_string());
  542. // Mark bridge as blocked when db gets updated
  543. bridge_country_info.blocked = true;
  544. }
  545. }
  546. blockages.insert(fingerprint, new_blockages);
  547. // Commit changes to database
  548. db.insert(fingerprint, bincode::serialize(&bridge_info).unwrap())
  549. .unwrap();
  550. }
  551. // Return map of new blockages
  552. blockages
  553. }
  554. /// Report blocked bridges to bridge distributor
  555. pub async fn report_blockages(
  556. distributors: &BTreeMap<BridgeDistributor, String>,
  557. blockages: HashMap<[u8; 20], HashSet<String>>,
  558. ) {
  559. // For now, only report to Lox
  560. // TODO: Support more distributors
  561. let uri: String = (distributors
  562. .get(&BridgeDistributor::Lox)
  563. .unwrap()
  564. .to_owned()
  565. + "/reportblocked")
  566. .parse()
  567. .unwrap();
  568. // Convert map keys from [u8; 20] to 40-character hex strings
  569. let mut blockages_str = HashMap::<String, HashSet<String>>::new();
  570. for (fingerprint, countries) in blockages {
  571. let fpr_string = array_bytes::bytes2hex("", fingerprint);
  572. blockages_str.insert(fpr_string, countries);
  573. }
  574. // Report blocked bridges to bridge distributor
  575. let client = Client::new();
  576. let req = Request::builder()
  577. .method(Method::POST)
  578. .uri(uri)
  579. .body(Body::from(serde_json::to_string(&blockages_str).unwrap()))
  580. .unwrap();
  581. let resp = client.request(req).await.unwrap();
  582. let buf = hyper::body::to_bytes(resp).await.unwrap();
  583. let resp_str: String = serde_json::from_slice(&buf).unwrap();
  584. assert_eq!("OK", resp_str);
  585. }
  586. // Unit tests
  587. #[cfg(test)]
  588. mod tests;