1use std::collections::{BTreeSet, HashMap};
10use std::fs;
11use std::path::Path;
12
13use serde_json::Value;
14
15use crate::evidence::{current_lists, lists_from_response};
16use crate::manifest::Manifest;
17use crate::quorum::{Key, Policy, PublishedList, default_threshold};
18use crate::sha512_half;
19
20type Res<T> = Result<T, String>;
21
22#[derive(Debug, Clone)]
25pub struct Seen {
26 pub list: PublishedList,
27 pub site: String,
28 pub body: Vec<u8>,
29 pub first_seen_ms: u64,
30}
31
32pub fn load_lists(
34 unl_dir: &Path,
35 publishers: &[Key],
36 manifests: &mut Vec<Manifest>,
37 problems: &mut Vec<String>,
38) -> Res<Vec<Seen>> {
39 let mut first_seen: HashMap<String, u64> = HashMap::new();
41 if let Ok(log) = fs::read_to_string(unl_dir.join("observations.jsonl")) {
42 for line in log.lines() {
43 let Ok(v) = serde_json::from_str::<Value>(line) else {
44 continue;
45 };
46 if let (Some(h), Some(at)) = (
47 v.get("body_hash").and_then(Value::as_str),
48 v.get("at_ms").and_then(Value::as_u64),
49 ) {
50 let e = first_seen.entry(h.to_owned()).or_insert(at);
51 *e = (*e).min(at);
52 }
53 }
54 }
55 let mut out = Vec::new();
56 let mut publisher_manifests = Vec::new();
57 for site in fs::read_dir(unl_dir).map_err(|e| e.to_string())? {
58 let site = site.map_err(|e| e.to_string())?.path();
59 if !site.is_dir() {
60 continue;
61 }
62 let site_name = site
63 .file_name()
64 .map(|n| n.to_string_lossy().into_owned())
65 .unwrap_or_default();
66 for file in fs::read_dir(&site).map_err(|e| e.to_string())? {
67 let path = file.map_err(|e| e.to_string())?.path();
68 let body = fs::read(&path).map_err(|e| e.to_string())?;
69 let hash = hex::encode_upper(sha512_half(&body));
70 match lists_from_response(&body, publishers) {
71 Ok(got) => {
72 if got.untrusted > 0 {
73 problems.push(format!(
74 "{}: list is not from a trusted publisher, ignored",
75 path.display()
76 ));
77 }
78 manifests.extend(got.manifests);
79 publisher_manifests.extend(got.publisher_manifests);
80 for list in got.lists {
81 out.push(Seen {
82 list,
83 site: site_name.clone(),
84 body: body.clone(),
85 first_seen_ms: first_seen.get(&hash).copied().unwrap_or(u64::MAX),
86 });
87 }
88 }
89 Err(e) => problems.push(format!("{}: {e}", path.display())),
90 }
91 }
92 }
93 let mut current: Vec<PublishedList> = out.iter().map(|s| s.list.clone()).collect();
95 current_lists(&mut current, &publisher_manifests, problems);
96 out.retain(|s| current.contains(&s.list));
97 Ok(out)
98}
99
100pub fn policy_at(
104 lists: &[Seen],
105 publishers: &[Key],
106 at_ms: u64,
107 threshold: usize,
108 local: &BTreeSet<Key>,
109 nunl: &BTreeSet<Key>,
110) -> (Policy, bool) {
111 let mut chosen = Vec::new();
112 let mut observed_before = true;
113 for p in publishers {
114 let mine: Vec<&Seen> = lists.iter().filter(|s| &s.list.publisher == p).collect();
115 let pick = mine
116 .iter()
117 .filter(|s| s.first_seen_ms <= at_ms)
118 .max_by_key(|s| s.list.sequence)
119 .or_else(|| {
120 observed_before = false;
121 mine.iter().min_by_key(|s| s.first_seen_ms)
122 });
123 if let Some(s) = pick {
124 chosen.push(s.list.clone());
125 }
126 }
127 let threshold = if threshold == 0 {
128 default_threshold(publishers.len())
129 } else {
130 threshold
131 };
132 (
133 Policy {
134 lists: chosen,
135 threshold,
136 local: local.clone(),
137 negative_unl: nunl.clone(),
138 },
139 observed_before,
140 )
141}