conformance/
conformance.rs1use std::fs;
24use std::io::Read;
25use std::path::{Path, PathBuf};
26use std::process::ExitCode;
27
28use libtracer::{decode, encode};
29
30fn from_hex(s: &str) -> Option<Vec<u8>> {
32 if s.len() % 2 != 0 {
33 return None;
34 }
35 let bytes = s.as_bytes();
36 let mut out = Vec::with_capacity(s.len() / 2);
37 let nibble = |c: u8| -> Option<u8> {
38 match c {
39 b'0'..=b'9' => Some(c - b'0'),
40 b'a'..=b'f' => Some(c - b'a' + 10),
41 b'A'..=b'F' => Some(c - b'A' + 10),
42 _ => None,
43 }
44 };
45 let mut i = 0;
46 while i < bytes.len() {
47 let hi = nibble(bytes[i])?;
48 let lo = nibble(bytes[i + 1])?;
49 out.push((hi << 4) | lo);
50 i += 2;
51 }
52 Some(out)
53}
54
55fn to_hex(bytes: &[u8]) -> String {
57 const HEX: &[u8; 16] = b"0123456789abcdef";
58 let mut s = String::with_capacity(bytes.len() * 2);
59 for &b in bytes {
60 s.push(HEX[(b >> 4) as usize] as char);
61 s.push(HEX[(b & 0x0f) as usize] as char);
62 }
63 s
64}
65
66fn run_roundtrip() -> ExitCode {
71 let mut text = String::new();
72 if std::io::stdin().read_to_string(&mut text).is_err() {
73 return ExitCode::SUCCESS;
75 }
76 let mut lines: Vec<&str> = text.split('\n').collect();
77 if lines.last() == Some(&"") {
79 lines.pop();
80 }
81 let mut out: Vec<String> = Vec::with_capacity(lines.len());
82 for raw in lines {
83 let line = raw.trim_end_matches(['\r', '\n']);
84 if line.is_empty() {
85 out.push("ERR:EMPTY_LINE".to_string());
86 continue;
87 }
88 match from_hex(line) {
89 None => out.push("ERR:BAD_HEX".to_string()),
90 Some(bytes) => match decode(&bytes) {
91 Ok(tlv) => out.push(to_hex(&encode(&tlv))),
92 Err(e) => out.push(format!("ERR:{}", e.name())),
93 },
94 }
95 }
96 print!("{}\n", out.join("\n"));
97 ExitCode::SUCCESS
98}
99
100fn reject_expectation(case_dir: &Path) -> Option<String> {
106 let text = fs::read_to_string(case_dir.join("expected.json")).ok()?;
107 let key = text.find("\"reject\"")?;
108 let colon = key + text[key..].find(':')?;
109 let q1 = colon + 1 + text[colon + 1..].find('"')?;
110 let q2 = q1 + 1 + text[q1 + 1..].find('"')?;
111 Some(text[q1 + 1..q2].to_string())
112}
113
114fn check_reject(reject_bin: &Path) -> (bool, String) {
119 let Some(want) = reject_bin.parent().and_then(reject_expectation) else {
120 return (
121 false,
122 "reject.bin without a \"reject\" expectation in expected.json".to_string(),
123 );
124 };
125 match fs::read(reject_bin) {
126 Err(e) => (false, e.to_string()),
127 Ok(bytes) => match decode(&bytes) {
128 Ok(_) => (false, format!("decode succeeded, expected {}", want)),
129 Err(e) if e.name() == want => (true, String::new()),
130 Err(e) => (
131 false,
132 format!("decode failed with {}, expected {}", e.name(), want),
133 ),
134 },
135 }
136}
137
138fn find_inputs(root: &Path, dir: &Path, out: &mut Vec<(String, PathBuf)>) {
143 let mut entries: Vec<PathBuf> = match fs::read_dir(dir) {
144 Ok(rd) => rd.filter_map(|e| e.ok().map(|e| e.path())).collect(),
145 Err(_) => return,
146 };
147 entries.sort();
148 for p in entries {
149 if p.is_dir() {
150 find_inputs(root, &p, out);
151 } else if p
152 .file_name()
153 .map(|n| n == "input.bin" || n == "reject.bin")
154 .unwrap_or(false)
155 {
156 let rel = p
157 .parent()
158 .unwrap()
159 .strip_prefix(root)
160 .unwrap()
161 .components()
162 .map(|c| c.as_os_str().to_string_lossy())
163 .collect::<Vec<_>>()
164 .join("/");
165 out.push((rel, p));
166 }
167 }
168}
169
170fn run_tap(vectors_dir: &Path) -> ExitCode {
172 let mut cases: Vec<(String, PathBuf)> = Vec::new();
173 find_inputs(vectors_dir, vectors_dir, &mut cases);
174 cases.sort_by(|a, b| a.0.cmp(&b.0));
176
177 let mut lines: Vec<String> = Vec::new();
178 lines.push("TAP version 13".to_string());
179 lines.push(format!("1..{}", cases.len()));
180 let mut n = 0;
181 let mut fails = 0;
182 for (rel, abs) in &cases {
183 n += 1;
184 let mut ok = false;
185 let mut diag = String::new();
186 if abs.file_name().map(|f| f == "reject.bin").unwrap_or(false) {
187 (ok, diag) = check_reject(abs);
188 } else {
189 match fs::read(abs) {
190 Ok(input) => match decode(&input) {
191 Ok(tlv) => {
192 ok = encode(&tlv) == input;
193 if !ok {
194 diag = "round-trip differs from input.bin".to_string();
195 }
196 }
197 Err(e) => diag = e.name().to_string(),
198 },
199 Err(e) => diag = e.to_string(),
200 }
201 }
202 lines.push(format!(
203 "{} {} - {}",
204 if ok { "ok" } else { "not ok" },
205 n,
206 rel
207 ));
208 if !ok {
209 lines.push(format!("# {}", diag));
210 fails += 1;
211 }
212 }
213
214 print!("{}\n", lines.join("\n"));
215 if fails == 0 {
216 ExitCode::SUCCESS
217 } else {
218 ExitCode::FAILURE
219 }
220}
221
222fn default_vectors_dir() -> PathBuf {
227 Path::new(env!("CARGO_MANIFEST_DIR")).join("../../tests/conformance/vectors/v1")
228}
229
230fn main() -> ExitCode {
231 let args: Vec<String> = std::env::args().skip(1).collect();
232 if args.iter().any(|a| a == "--roundtrip") {
233 return run_roundtrip();
234 }
235 let dir = args
238 .iter()
239 .find(|a| !a.starts_with("--"))
240 .map(PathBuf::from)
241 .unwrap_or_else(default_vectors_dir);
242 run_tap(&dir)
243}