quantus-cli 2.1.1

Command line interface and library for interacting with the Quantus Network
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
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
//! Circuit binaries path resolution and lazy generation.
//!
//! The CLI needs access to ZK-circuit artifacts (`verifier.bin`, `common.bin`,
//! `private_batch_*.bin`, `public_batch_*.bin`, dummy proofs, etc.). The leaf
//! circuit no longer ships a `prover.bin` — `WormholeProver` builds fresh at
//! prove time. During `cargo build`/`cargo install` the remaining files are
//! produced by `build.rs` into `$OUT_DIR/generated-bins/`, but `cargo install`
//! does not copy build-script outputs alongside the installed executable. To
//! make installed binaries self-sufficient, this module resolves a persistent
//! storage location and regenerates the binaries there on demand.
//!
//! Resolution order:
//! 1. `QUANTUS_BINS_DIR` env var (optional override, including `./generated-bins`).
//! 2. `~/.quantus/generated-bins/` (default; generated on demand).
//!
//! `./generated-bins/` in the current working directory is never used unless
//! pointed at explicitly via `QUANTUS_BINS_DIR`. The manifest is unsigned and
//! lives in the directory it authenticates, so an attacker-prepared checkout
//! could ship a self-consistent artifact set that passes verification. When
//! CWD artifacts are present without an override they are ignored — resolution
//! falls through to the per-user store instead of requiring an env var.

use crate::{
	error::{QuantusError, Result},
	log_print, log_success,
};
use sha2::{Digest, Sha256};
use std::{
	fs,
	io::Write,
	path::{Path, PathBuf},
};

include!("bins_consts.rs");

mod fs_helpers {
	#![allow(dead_code)] // publish_dir_atomically is used by build.rs and tests
	include!("bins_fs.rs");
}
use fs_helpers::remove_path_nofollow;

/// Environment variable used to override the bins directory.
pub const BINS_DIR_ENV: &str = "QUANTUS_BINS_DIR";

/// Files that must be present for all wormhole operations to succeed.
///
/// No `*_prover.bin` artifacts: circuit-builder 4.2.0+ never emits them;
/// leaf / private-batch / public-batch provers rebuild from source.
const REQUIRED_FILES: &[&str] = &[
	"verifier.bin",
	"common.bin",
	"private_batch_verifier.bin",
	"private_batch_common.bin",
	"public_batch_verifier.bin",
	"public_batch_common.bin",
	"dummy_proof.bin",
	"dummy_private_batch_proof.bin",
	"config.json",
];

#[derive(serde::Deserialize, serde::Serialize)]
struct ArtifactManifest {
	manifest_version: u32,
	package_version: String,
	num_leaf_proofs: usize,
	num_private_batch_proofs: usize,
	files: std::collections::BTreeMap<String, String>,
}

/// Resolve the path where circuit binaries should live.
///
/// This never generates anything; see [`ensure_bins_dir`] for the full
/// resolve-and-generate flow.
///
/// `cwd_dir` is only used for tests; production ignores CWD artifacts unless
/// they are selected via [`BINS_DIR_ENV`].
pub fn resolve_bins_dir() -> Result<PathBuf> {
	resolve_bins_dir_from(std::env::var(BINS_DIR_ENV).ok(), Path::new("generated-bins"))
}

fn resolve_bins_dir_from(env_override: Option<String>, _cwd_dir: &Path) -> Result<PathBuf> {
	if let Some(dir) = env_override {
		return Ok(PathBuf::from(dir));
	}

	Ok(user_bins_dir())
}

/// Location used for auto-generated binaries on installed systems.
fn user_bins_dir() -> PathBuf {
	dirs::home_dir()
		.expect("Could not determine home directory for ~/.quantus/generated-bins")
		.join(".quantus")
		.join("generated-bins")
}

/// Resolve the bins directory and generate any missing circuit binaries.
///
/// Safe to call multiple times. A directory attributable to a different CLI
/// version or sizing configuration (via its manifest or version marker) is
/// quarantined (its artifact files removed by exact filename, never the
/// directory itself) and regenerated, so upgrades recover automatically. A
/// same-version directory that fails authentication is rejected rather than
/// overwritten.
pub fn ensure_bins_dir() -> Result<PathBuf> {
	let dir = resolve_bins_dir()?;
	ensure_safe_bins_dir(&dir)?;

	if is_ready(&dir) {
		return Ok(dir);
	}

	if REQUIRED_FILES.iter().any(|f| dir.join(f).exists()) {
		match stale_artifact_provenance(&dir) {
			Some(provenance) => {
				log_print!(
					"♻️  Replacing circuit artifacts in {} ({}; current CLI is {})",
					dir.display(),
					provenance,
					env!("CARGO_PKG_VERSION")
				);
				remove_stale_artifact_files(&dir)?;
			},
			None => {
				return Err(QuantusError::Generic(format!(
					"Circuit artifact directory {} is incomplete or failed authentication; remove the directory and rerun this command to regenerate trusted artifacts",
					dir.display()
				)));
			},
		}
	}

	let num_leaf_proofs = env_num_leaf_proofs();
	let num_private_batch_proofs = env_num_private_batch_proofs();
	generate(&dir, num_leaf_proofs, num_private_batch_proofs)?;
	Ok(dir)
}

/// Best-effort attribution of an artifact directory to a different CLI version
/// or sizing configuration, so upgrades can quarantine-and-regenerate instead
/// of bricking wormhole commands.
///
/// Returns a description of the stale provenance, or `None` when the directory
/// claims to belong to the current version/sizing (in which case a failed
/// manifest check means tampering or corruption and must stay a hard error).
fn stale_artifact_provenance(dir: &Path) -> Option<String> {
	// Prefer the manifest: it records the producing package version and sizing.
	if let Ok(content) = fs::read_to_string(dir.join(MANIFEST_FILE)) {
		if let Ok(manifest) = serde_json::from_str::<ArtifactManifest>(&content) {
			if manifest.package_version != env!("CARGO_PKG_VERSION") {
				return Some(format!("built by quantus-cli {}", manifest.package_version));
			}
			if manifest.num_leaf_proofs != env_num_leaf_proofs() ||
				manifest.num_private_batch_proofs != env_num_private_batch_proofs()
			{
				return Some(format!(
					"sized for num_leaf_proofs={}, num_private_batch_proofs={}",
					manifest.num_leaf_proofs, manifest.num_private_batch_proofs
				));
			}
			return None;
		}
	}

	// Pre-manifest layouts from older releases only carry the version marker.
	if let Ok(marker) = fs::read_to_string(dir.join(VERSION_MARKER)) {
		let marker = marker.trim();
		if !marker.is_empty() && marker != env!("CARGO_PKG_VERSION") {
			return Some(format!("built by quantus-cli {marker}"));
		}
	}

	None
}

/// Remove stale circuit artifacts by exact filename, never recursively.
///
/// The bins directory can be user-pointed (`QUANTUS_BINS_DIR`) at a directory
/// that also holds unrelated data — e.g. `~/.quantus`, which contains wallets.
/// Quarantine therefore only ever deletes the bounded, explicit set of artifact
/// filenames this CLI (or an older release) produced, and refuses to touch
/// anything else. Stale files must still be removed (not just overwritten):
/// if a newer builder stops emitting a manifested file, a leftover stale copy
/// would otherwise be silently hashed into the new manifest as trusted.
fn remove_stale_artifact_files(dir: &Path) -> Result<()> {
	let mut names: std::collections::BTreeSet<&str> = REQUIRED_FILES.iter().copied().collect();
	names.extend(MANIFESTED_FILES.iter().copied());
	names.insert(MANIFEST_FILE);
	names.insert(VERSION_MARKER);
	// Legacy prover artifacts no longer emitted by circuit-builder 4.2.0+.
	names.insert("prover.bin");
	names.insert("private_batch_prover.bin");
	names.insert("public_batch_prover.bin");

	for name in names {
		let path = dir.join(name);
		match fs::symlink_metadata(&path) {
			Err(e) if e.kind() == std::io::ErrorKind::NotFound => continue,
			Err(e) => {
				return Err(QuantusError::Generic(format!(
					"Failed to inspect stale artifact {}: {}",
					path.display(),
					e
				)));
			},
			Ok(meta) if meta.is_dir() => {
				return Err(QuantusError::Generic(format!(
					"Refusing to remove directory {} while replacing stale circuit artifacts; remove it manually and rerun",
					path.display()
				)));
			},
			Ok(_) => {
				remove_path_nofollow(&path).map_err(QuantusError::Generic)?;
			},
		}
	}
	Ok(())
}

fn ensure_safe_bins_dir(dir: &Path) -> Result<()> {
	match fs::symlink_metadata(dir) {
		Ok(meta) => {
			if meta.file_type().is_symlink() {
				return Err(QuantusError::Generic(format!(
					"Refusing to use symlinked bins directory {}",
					dir.display()
				)));
			}
			if !meta.is_dir() {
				return Err(QuantusError::Generic(format!(
					"Bins path {} is not a directory",
					dir.display()
				)));
			}
		},
		Err(e) if e.kind() == std::io::ErrorKind::NotFound => {},
		Err(e) => {
			return Err(QuantusError::Generic(format!(
				"Failed to inspect bins directory {}: {}",
				dir.display(),
				e
			)));
		},
	}
	Ok(())
}

fn ensure_regular_file(path: &Path) -> Result<()> {
	let meta = fs::symlink_metadata(path).map_err(|e| {
		QuantusError::Generic(format!("Failed to inspect circuit artifact {}: {e}", path.display()))
	})?;
	if meta.file_type().is_symlink() {
		return Err(QuantusError::Generic(format!(
			"Refusing to use symlinked circuit artifact {}",
			path.display()
		)));
	}
	if !meta.is_file() {
		return Err(QuantusError::Generic(format!(
			"Circuit artifact {} is not a regular file",
			path.display()
		)));
	}
	Ok(())
}

fn is_ready(dir: &Path) -> bool {
	REQUIRED_FILES.iter().all(|f| dir.join(f).exists()) && verify_manifest(dir).is_ok()
}

/// Authenticate a circuit-artifact directory against its SHA-256 manifest.
pub(crate) fn verify_manifest(dir: &Path) -> Result<()> {
	ensure_safe_bins_dir(dir)?;
	ensure_regular_file(&dir.join(MANIFEST_FILE))?;
	let content = std::fs::read_to_string(dir.join(MANIFEST_FILE)).map_err(|e| {
		QuantusError::Generic(format!(
			"Failed to read circuit artifact manifest {}: {e}",
			dir.join(MANIFEST_FILE).display()
		))
	})?;
	let manifest: ArtifactManifest = serde_json::from_str(&content).map_err(|e| {
		QuantusError::Generic(format!(
			"Failed to parse circuit artifact manifest {}: {e}",
			dir.join(MANIFEST_FILE).display()
		))
	})?;
	validate_manifest(dir, &manifest)
}

fn validate_manifest(dir: &Path, manifest: &ArtifactManifest) -> Result<()> {
	if manifest.manifest_version != 1 {
		return Err(QuantusError::Generic(format!(
			"Unsupported circuit artifact manifest version {}",
			manifest.manifest_version
		)));
	}
	if manifest.package_version != env!("CARGO_PKG_VERSION") {
		return Err(QuantusError::Generic(
			"Circuit artifact manifest package version mismatch".to_string(),
		));
	}
	if manifest.num_leaf_proofs != env_num_leaf_proofs() ||
		manifest.num_private_batch_proofs != env_num_private_batch_proofs()
	{
		return Err(QuantusError::Generic(
			"Circuit artifact manifest sizing does not match current settings".to_string(),
		));
	}
	if manifest.files.len() != MANIFESTED_FILES.len() {
		return Err(QuantusError::Generic(
			"Circuit artifact manifest file set mismatch".to_string(),
		));
	}
	for filename in MANIFESTED_FILES {
		let expected = manifest.files.get(*filename).ok_or_else(|| {
			QuantusError::Generic(format!("Circuit artifact manifest lacks {filename}"))
		})?;
		let path = dir.join(filename);
		ensure_regular_file(&path)?;
		let actual = file_sha256_hex(&path)?;
		if &actual != expected {
			return Err(QuantusError::Generic(format!(
				"Circuit artifact hash mismatch for {filename}"
			)));
		}
	}
	Ok(())
}

fn write_manifest(
	dir: &Path,
	num_leaf_proofs: usize,
	num_private_batch_proofs: usize,
) -> Result<()> {
	let mut files = std::collections::BTreeMap::new();
	for filename in MANIFESTED_FILES {
		ensure_regular_file(&dir.join(filename))?;
		files.insert((*filename).to_string(), file_sha256_hex(&dir.join(filename))?);
	}
	let manifest = ArtifactManifest {
		manifest_version: 1,
		package_version: env!("CARGO_PKG_VERSION").to_string(),
		num_leaf_proofs,
		num_private_batch_proofs,
		files,
	};
	let content = serde_json::to_string_pretty(&manifest).map_err(|e| {
		QuantusError::Generic(format!("Failed to serialize circuit artifact manifest: {e}"))
	})?;
	atomic_write_new_file(&dir.join(MANIFEST_FILE), content.as_bytes())
}

fn file_sha256_hex(path: &Path) -> Result<String> {
	let data = std::fs::read(path).map_err(|e| {
		QuantusError::Generic(format!("Failed to read circuit artifact {}: {e}", path.display()))
	})?;
	let mut hasher = Sha256::new();
	hasher.update(&data);
	Ok(hex::encode(hasher.finalize()))
}

fn env_num_leaf_proofs() -> usize {
	std::env::var("QP_NUM_LEAF_PROOFS")
		.ok()
		.and_then(|v| v.parse().ok())
		.unwrap_or(DEFAULT_NUM_LEAF_PROOFS)
}

fn env_num_private_batch_proofs() -> usize {
	std::env::var("QP_NUM_PRIVATE_BATCH_PROOFS")
		.ok()
		.and_then(|v| v.parse().ok())
		.unwrap_or(DEFAULT_NUM_PRIVATE_BATCH_PROOFS)
}

fn atomic_write_new_file(path: &Path, contents: &[u8]) -> Result<()> {
	let parent = path.parent().unwrap_or_else(|| Path::new("."));
	let file_name = path
		.file_name()
		.and_then(|s| s.to_str())
		.ok_or_else(|| QuantusError::Generic("Invalid artifact filename".to_string()))?;
	let temp_path = parent.join(format!("{}.tmp-{}", file_name, std::process::id()));

	if let Ok(meta) = fs::symlink_metadata(path) {
		if meta.file_type().is_symlink() {
			return Err(QuantusError::Generic(format!(
				"Refusing to overwrite symlinked artifact {}",
				path.display()
			)));
		}
	}
	if let Ok(meta) = fs::symlink_metadata(&temp_path) {
		if meta.file_type().is_symlink() {
			return Err(QuantusError::Generic(format!(
				"Refusing to overwrite symlinked temporary artifact {}",
				temp_path.display()
			)));
		}
		if meta.is_file() {
			let _ = fs::remove_file(&temp_path);
		}
	}

	let mut file =
		fs::OpenOptions::new()
			.write(true)
			.create_new(true)
			.open(&temp_path)
			.map_err(|e| {
				QuantusError::Generic(format!("Failed to create {}: {}", path.display(), e))
			})?;
	file.write_all(contents)
		.and_then(|_| file.sync_all())
		.map_err(|e| QuantusError::Generic(format!("Failed to write {}: {}", path.display(), e)))?;
	drop(file);

	fs::rename(&temp_path, path).map_err(|e| {
		let _ = fs::remove_file(&temp_path);
		QuantusError::Generic(format!("Failed to publish {}: {}", path.display(), e))
	})?;
	Ok(())
}

fn write_version_marker_safely(dir: &Path) -> Result<()> {
	atomic_write_new_file(&dir.join(VERSION_MARKER), env!("CARGO_PKG_VERSION").as_bytes())
}

fn generate(dir: &Path, num_leaf_proofs: usize, num_private_batch_proofs: usize) -> Result<()> {
	std::fs::create_dir_all(dir).map_err(|e| {
		QuantusError::Generic(format!("Failed to create bins directory {}: {}", dir.display(), e))
	})?;
	ensure_safe_bins_dir(dir)?;

	log_print!("");
	log_print!("🛠️  Generating ZK circuit binaries (first-time setup, ~30s)...");
	log_print!("   Target: {}", dir.display());
	log_print!("   num_leaf_proofs: {}", num_leaf_proofs);
	log_print!("   num_private_batch_proofs: {}", num_private_batch_proofs);

	let start = std::time::Instant::now();
	qp_wormhole_circuit_builder::generate_all_circuit_binaries(
		dir,
		true,
		num_leaf_proofs,
		Some(num_private_batch_proofs),
	)
	.map_err(|e| QuantusError::Generic(format!("Failed to generate circuit binaries: {}", e)))?;
	ensure_safe_bins_dir(dir)?;

	write_version_marker_safely(dir)?;
	write_manifest(dir, num_leaf_proofs, num_private_batch_proofs)?;

	let elapsed = start.elapsed();
	log_success!("Circuit binaries ready in {:.1}s", elapsed.as_secs_f64());
	log_print!("");
	Ok(())
}

#[cfg(test)]
mod tests {
	use super::*;
	use serial_test::serial;
	// Symlink-based tests are Unix-only; `cargo test` must still compile on
	// Windows, which the release pipeline ships for.
	#[cfg(unix)]
	use std::os::unix::fs::symlink;
	use tempfile::TempDir;

	fn seed_required_files(dir: &Path) {
		for name in REQUIRED_FILES {
			fs::write(dir.join(name), format!("contents-of-{name}")).unwrap();
		}
		fs::write(dir.join(VERSION_MARKER), env!("CARGO_PKG_VERSION")).unwrap();
	}

	fn write_valid_manifest_for_dir(dir: &Path) {
		write_manifest(dir, env_num_leaf_proofs(), env_num_private_batch_proofs()).unwrap();
	}

	#[test]
	fn verify_manifest_rejects_tampered_artifact() {
		// #160697: readiness/load must authenticate artifact bytes, not just names.
		let tmp = TempDir::new().unwrap();
		let dir = tmp.path();
		seed_required_files(dir);
		write_valid_manifest_for_dir(dir);
		assert!(verify_manifest(dir).is_ok());

		fs::write(dir.join("private_batch_verifier.bin"), b"attacker-substituted-circuit").unwrap();
		let err = verify_manifest(dir).expect_err("tampered verifier must fail authentication");
		assert!(err.to_string().contains("hash mismatch"), "unexpected error: {err}");
		assert!(!is_ready(dir));
	}

	#[test]
	fn cwd_artifacts_are_ignored_without_explicit_opt_in() {
		// #160697 follow-up: an attacker-prepared checkout can ship a
		// self-consistent ./generated-bins; it must never be trusted implicitly.
		// Prefer the per-user store over requiring QUANTUS_BINS_DIR.
		let tmp = TempDir::new().unwrap();
		let cwd_dir = tmp.path().join("generated-bins");
		fs::create_dir_all(&cwd_dir).unwrap();
		fs::write(cwd_dir.join("config.json"), b"{}").unwrap();

		let resolved = resolve_bins_dir_from(None, &cwd_dir)
			.expect("CWD artifacts must be ignored, not fatal");
		assert_eq!(resolved, user_bins_dir());
	}

	#[test]
	fn env_override_wins_over_cwd_artifacts() {
		let tmp = TempDir::new().unwrap();
		let cwd_dir = tmp.path().join("generated-bins");
		fs::create_dir_all(&cwd_dir).unwrap();
		fs::write(cwd_dir.join("config.json"), b"{}").unwrap();

		let resolved = resolve_bins_dir_from(Some("/tmp/explicit-bins".to_string()), &cwd_dir)
			.expect("explicit env override must resolve");
		assert_eq!(resolved, PathBuf::from("/tmp/explicit-bins"));
	}

	#[test]
	fn resolution_defaults_to_user_bins_dir_without_cwd_artifacts() {
		let tmp = TempDir::new().unwrap();
		let cwd_dir = tmp.path().join("generated-bins");

		let resolved = resolve_bins_dir_from(None, &cwd_dir).expect("default must resolve");
		assert_eq!(resolved, user_bins_dir());
	}

	#[test]
	#[serial]
	fn ensure_bins_dir_rejects_incomplete_unauthenticated_directory() {
		// #160697: do not regenerate over an existing unverified artifact set.
		let tmp = TempDir::new().unwrap();
		let dir = tmp.path().join("generated-bins");
		fs::create_dir_all(&dir).unwrap();
		seed_required_files(&dir);
		// No manifest.json

		std::env::set_var(BINS_DIR_ENV, &dir);
		let result = ensure_bins_dir();
		std::env::remove_var(BINS_DIR_ENV);

		let err = result.expect_err("incomplete/unauthenticated dir must be rejected");
		assert!(err.to_string().contains("failed authentication"), "unexpected error: {err}");
	}

	#[cfg(unix)]
	#[test]
	#[serial]
	fn ensure_bins_dir_rejects_symlinked_directory() {
		// #160699: artifact directory must not be a symlink redirect.
		let tmp = TempDir::new().unwrap();
		let real = tmp.path().join("real-bins");
		let link = tmp.path().join("generated-bins");
		fs::create_dir_all(&real).unwrap();
		seed_required_files(&real);
		write_valid_manifest_for_dir(&real);
		symlink(&real, &link).unwrap();

		std::env::set_var(BINS_DIR_ENV, &link);
		let result = ensure_bins_dir();
		std::env::remove_var(BINS_DIR_ENV);

		let err = result.expect_err("symlinked bins dir must be rejected");
		assert!(err.to_string().contains("symlinked bins directory"), "unexpected error: {err}");
	}

	#[cfg(unix)]
	#[test]
	fn version_marker_write_refuses_existing_symlink() {
		// #160699: marker publication must not follow a pre-existing symlink.
		let tmp = TempDir::new().unwrap();
		let dir = tmp.path();
		fs::create_dir_all(dir).unwrap();
		let victim = tmp.path().join("victim.txt");
		fs::write(&victim, b"do-not-overwrite").unwrap();
		symlink(&victim, dir.join(VERSION_MARKER)).unwrap();

		let err = write_version_marker_safely(dir).expect_err("must refuse symlink marker");
		assert!(err.to_string().contains("symlinked"), "unexpected error: {err}");
		assert_eq!(fs::read_to_string(&victim).unwrap(), "do-not-overwrite");
	}

	#[cfg(unix)]
	#[test]
	fn verify_manifest_rejects_symlinked_artifact_file() {
		let tmp = TempDir::new().unwrap();
		let dir = tmp.path();
		seed_required_files(dir);
		write_valid_manifest_for_dir(dir);

		let evil = tmp.path().join("evil-verifier.bin");
		fs::write(&evil, b"redirected").unwrap();
		fs::remove_file(dir.join("verifier.bin")).unwrap();
		symlink(&evil, dir.join("verifier.bin")).unwrap();

		let err = verify_manifest(dir).expect_err("symlinked artifact must be rejected");
		assert!(err.to_string().contains("symlinked"), "unexpected error: {err}");
	}

	// Shared publish helpers from build.rs (#160700).
	use super::fs_helpers::publish_dir_atomically;

	#[cfg(unix)]
	#[test]
	fn publish_dir_atomically_replaces_destination_symlink_without_following() {
		// #160700: publishing must not write through a swapped destination symlink.
		let tmp = TempDir::new().unwrap();
		let src = tmp.path().join("src");
		let dest = tmp.path().join("generated-bins");
		let victim_dir = tmp.path().join("victim-dir");
		fs::create_dir_all(&src).unwrap();
		fs::create_dir_all(&victim_dir).unwrap();
		fs::write(src.join("config.json"), b"{\"ok\":true}").unwrap();
		fs::write(src.join("verifier.bin"), b"trusted").unwrap();
		fs::write(victim_dir.join("keep-me.txt"), b"safe").unwrap();
		symlink(&victim_dir, &dest).unwrap();

		publish_dir_atomically(&src, &dest).expect("publish must succeed");

		assert!(dest.is_dir());
		assert!(!fs::symlink_metadata(&dest).unwrap().file_type().is_symlink());
		assert_eq!(fs::read(dest.join("verifier.bin")).unwrap(), b"trusted");
		assert_eq!(fs::read(victim_dir.join("keep-me.txt")).unwrap(), b"safe");
		assert!(!victim_dir.join("config.json").exists());
	}

	#[cfg(unix)]
	#[test]
	fn remove_path_nofollow_removes_symlink_without_deleting_target() {
		let tmp = TempDir::new().unwrap();
		let target = tmp.path().join("target-dir");
		let link = tmp.path().join("link-dir");
		fs::create_dir_all(&target).unwrap();
		fs::write(target.join("keep.txt"), b"keep").unwrap();
		symlink(&target, &link).unwrap();

		remove_path_nofollow(&link).expect("remove symlink");
		assert!(!link.exists());
		assert!(target.join("keep.txt").exists());
	}

	/// Upgrades must not brick wormhole: artifacts attributable to another CLI
	/// version are stale and eligible for quarantine-and-regenerate.
	#[test]
	fn artifacts_from_an_older_cli_version_are_stale() {
		let tmp = TempDir::new().unwrap();
		let dir = tmp.path();
		seed_required_files(dir);
		write_valid_manifest_for_dir(dir);

		// Same version and sizing: not stale (a failed check must stay a hard error).
		assert_eq!(stale_artifact_provenance(dir), None);

		// Rewrite the manifest as if produced by an older release.
		let content = fs::read_to_string(dir.join(MANIFEST_FILE)).unwrap();
		let mut manifest: ArtifactManifest = serde_json::from_str(&content).unwrap();
		manifest.package_version = "0.0.1-old".to_string();
		fs::write(dir.join(MANIFEST_FILE), serde_json::to_string(&manifest).unwrap()).unwrap();

		let provenance = stale_artifact_provenance(dir).expect("older version is stale");
		assert!(provenance.contains("0.0.1-old"), "unexpected provenance: {provenance}");
	}

	/// Pre-manifest layouts (older releases) are attributed via the version marker.
	#[test]
	fn pre_manifest_artifacts_with_old_version_marker_are_stale() {
		let tmp = TempDir::new().unwrap();
		let dir = tmp.path();
		seed_required_files(dir);
		// No manifest.json at all; marker from an older release.
		fs::write(dir.join(VERSION_MARKER), "0.0.1-old").unwrap();

		let provenance = stale_artifact_provenance(dir).expect("old marker is stale");
		assert!(provenance.contains("0.0.1-old"), "unexpected provenance: {provenance}");

		// Marker matching the current version without a manifest is NOT stale:
		// that directory claims to be ours but cannot be authenticated.
		fs::write(dir.join(VERSION_MARKER), env!("CARGO_PKG_VERSION")).unwrap();
		assert_eq!(stale_artifact_provenance(dir), None);
	}

	/// Quarantine must never delete anything beyond the exact artifact
	/// filenames — a user can point QUANTUS_BINS_DIR at a directory that also
	/// holds wallets or other data.
	#[test]
	fn stale_quarantine_preserves_unrelated_entries() {
		let tmp = TempDir::new().unwrap();
		let dir = tmp.path();
		seed_required_files(dir);
		fs::write(dir.join("prover.bin"), b"legacy leaf prover").unwrap();

		let wallets = dir.join("wallets");
		fs::create_dir_all(&wallets).unwrap();
		fs::write(wallets.join("alice.json"), b"precious wallet").unwrap();
		fs::write(dir.join("notes.txt"), b"user data").unwrap();

		remove_stale_artifact_files(dir).expect("quarantine succeeds");

		for name in REQUIRED_FILES {
			assert!(!dir.join(name).exists(), "stale artifact {name} must be removed");
		}
		assert!(!dir.join("prover.bin").exists(), "legacy prover must be removed");
		assert!(!dir.join(VERSION_MARKER).exists(), "version marker must be removed");
		assert!(
			wallets.join("alice.json").exists(),
			"unrelated wallet data must survive quarantine"
		);
		assert!(dir.join("notes.txt").exists(), "unrelated files must survive quarantine");
	}

	/// A directory occupying an artifact filename is never recursively deleted.
	#[test]
	fn stale_quarantine_refuses_directory_named_like_artifact() {
		let tmp = TempDir::new().unwrap();
		let dir = tmp.path();
		seed_required_files(dir);
		fs::remove_file(dir.join("verifier.bin")).unwrap();
		fs::create_dir_all(dir.join("verifier.bin")).unwrap();
		fs::write(dir.join("verifier.bin").join("keep.txt"), b"keep").unwrap();

		let err = remove_stale_artifact_files(dir)
			.expect_err("directory named like an artifact must abort quarantine");
		assert!(err.to_string().contains("Refusing to remove directory"), "got: {err}");
		assert!(
			dir.join("verifier.bin").join("keep.txt").exists(),
			"contents of the unexpected directory must be untouched"
		);
	}

	/// A same-version directory with mismatched sizing regenerates instead of erroring.
	#[test]
	fn artifacts_with_different_sizing_are_stale() {
		let tmp = TempDir::new().unwrap();
		let dir = tmp.path();
		seed_required_files(dir);
		write_valid_manifest_for_dir(dir);

		let content = fs::read_to_string(dir.join(MANIFEST_FILE)).unwrap();
		let mut manifest: ArtifactManifest = serde_json::from_str(&content).unwrap();
		manifest.num_leaf_proofs += 1;
		fs::write(dir.join(MANIFEST_FILE), serde_json::to_string(&manifest).unwrap()).unwrap();

		let provenance = stale_artifact_provenance(dir).expect("different sizing is stale");
		assert!(provenance.contains("num_leaf_proofs"), "unexpected provenance: {provenance}");
	}
}